@ambprotocol/ride-cli 1.4.0 → 1.6.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.
- package/amb +525 -151
- package/package.json +3 -3
package/amb
CHANGED
|
@@ -1,21 +1,35 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
2
|
+
import { createRequire as __ambCreateRequire } from 'node:module'; const require = __ambCreateRequire(import.meta.url);
|
|
3
|
+
var nS=Object.create;var ep=Object.defineProperty;var sS=Object.getOwnPropertyDescriptor;var iS=Object.getOwnPropertyNames;var aS=Object.getPrototypeOf,oS=Object.prototype.hasOwnProperty;var ae=(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 cS=(e,t)=>()=>(e&&(t=e(e=0)),t);var D=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var lS=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of iS(t))!oS.call(e,s)&&s!==r&&ep(e,s,{get:()=>t[s],enumerable:!(n=sS(t,s))||n.enumerable});return e};var uS=(e,t,r)=>(r=e!=null?nS(aS(e)):{},lS(t||!e||!e.__esModule?ep(r,"default",{value:e,enumerable:!0}):r,e));var _,p=cS(()=>{_={services:{authServerUrl:"https://backend.clutchwalletserver.xyz",ambTelemetryServiceUrl:"https://backend.clutchwalletserver.xyz/amb-telemetry",authWebappUrl:"https://agentconnect.ambprotocol.com",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.6.0",gitSha:"e0615801"},install:{mode:"npm",repoBranch:"main",expectedCliSha:"e0615801",minimumCliVersion:"1.3.0"},bridgePolicy:{minimumUsdc:"1",maxFeeBufferPct:20,burnGraceBlocks:30,mintMaxAttempts:5,leaseSeconds:120,logChunkBlocks:2e3}}});var gm=D((BV,fm)=>{"use strict";p();var mm=ae("stream").Stream,VI=ae("util");fm.exports=Ut;function Ut(){this.source=null,this.dataSize=0,this.maxDataSize=1024*1024,this.pauseStream=!0,this._maxDataSizeExceeded=!1,this._released=!1,this._bufferedEvents=[]}VI.inherits(Ut,mm);Ut.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(Ut.prototype,"readable",{configurable:!0,enumerable:!0,get:function(){return this.source.readable}});Ut.prototype.setEncoding=function(){return this.source.setEncoding.apply(this.source,arguments)};Ut.prototype.resume=function(){this._released||this.release(),this.source.resume()};Ut.prototype.pause=function(){this.source.pause()};Ut.prototype.release=function(){this._released=!0,this._bufferedEvents.forEach(function(e){this.emit.apply(this,e)}.bind(this)),this._bufferedEvents=[]};Ut.prototype.pipe=function(){var e=mm.prototype.pipe.apply(this,arguments);return this.resume(),e};Ut.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)};Ut.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 Em=D((HV,ym)=>{"use strict";p();var HI=ae("util"),_m=ae("stream").Stream,hm=gm();ym.exports=Se;function Se(){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}HI.inherits(Se,_m);Se.create=function(e){var t=new this;e=e||{};for(var r in e)t[r]=e[r];return t};Se.isStreamLike=function(e){return typeof e!="function"&&typeof e!="string"&&typeof e!="boolean"&&typeof e!="number"&&!Buffer.isBuffer(e)};Se.prototype.append=function(e){var t=Se.isStreamLike(e);if(t){if(!(e instanceof hm)){var r=hm.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};Se.prototype.pipe=function(e,t){return _m.prototype.pipe.call(this,e,t),this.resume(),e};Se.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}};Se.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=Se.isStreamLike(r);n&&(r.on("data",this._checkDataSize.bind(this)),this._handleErrors(r)),this._pipeNext(r)}.bind(this))};Se.prototype._pipeNext=function(e){this._currentStream=e;var t=Se.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()};Se.prototype._handleErrors=function(e){var t=this;e.on("error",function(r){t._emitError(r)})};Se.prototype.write=function(e){this.emit("data",e)};Se.prototype.pause=function(){this.pauseStreams&&(this.pauseStreams&&this._currentStream&&typeof this._currentStream.pause=="function"&&this._currentStream.pause(),this.emit("pause"))};Se.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")};Se.prototype.end=function(){this._reset(),this.emit("end")};Se.prototype.destroy=function(){this._reset(),this.emit("close")};Se.prototype._reset=function(){this.writable=!1,this._streams=[],this._currentStream=null};Se.prototype._checkDataSize=function(){if(this._updateDataSize(),!(this.dataSize<=this.maxDataSize)){var e="DelayedStream#maxDataSize of "+this.maxDataSize+" bytes exceeded.";this._emitError(new Error(e))}};Se.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)};Se.prototype._emitError=function(e){this._reset(),this.emit("error",e)}});var Tm=D(($V,GI)=>{GI.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 vm=D((WV,bm)=>{"use strict";p();bm.exports=Tm()});var Am=D(ot=>{"use strict";p();var zi=vm(),$I=ae("path").extname,Rm=/^\s*([^;\s]*)(?:;|\s|$)/,WI=/^text\//i;ot.charset=wm;ot.charsets={lookup:wm};ot.contentType=JI;ot.extension=KI;ot.extensions=Object.create(null);ot.lookup=YI;ot.types=Object.create(null);zI(ot.extensions,ot.types);function wm(e){if(!e||typeof e!="string")return!1;var t=Rm.exec(e),r=t&&zi[t[1].toLowerCase()];return r&&r.charset?r.charset:t&&WI.test(t[1])?"UTF-8":!1}function JI(e){if(!e||typeof e!="string")return!1;var t=e.indexOf("/")===-1?ot.lookup(e):e;if(!t)return!1;if(t.indexOf("charset")===-1){var r=ot.charset(t);r&&(t+="; charset="+r.toLowerCase())}return t}function KI(e){if(!e||typeof e!="string")return!1;var t=Rm.exec(e),r=t&&ot.extensions[t[1].toLowerCase()];return!r||!r.length?!1:r[0]}function YI(e){if(!e||typeof e!="string")return!1;var t=$I("x."+e).toLowerCase().substr(1);return t&&ot.types[t]||!1}function zI(e,t){var r=["nginx","apache",void 0,"iana"];Object.keys(zi).forEach(function(s){var i=zi[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 l=r.indexOf(zi[t[c]].source),u=r.indexOf(i.source);if(t[c]!=="application/octet-stream"&&(l>u||l===u&&t[c].substr(0,12)==="application/"))continue}t[c]=s}}})}});var Sm=D((zV,xm)=>{"use strict";p();xm.exports=XI;function XI(e){var t=typeof setImmediate=="function"?setImmediate:typeof process=="object"&&typeof process.nextTick=="function"?process.nextTick:null;t?t(e):setTimeout(e,0)}});var Ic=D((QV,Dm)=>{"use strict";p();var Im=Sm();Dm.exports=QI;function QI(e){var t=!1;return Im(function(){t=!0}),function(n,s){t?e(n,s):Im(function(){e(n,s)})}}});var Dc=D((eH,Om)=>{"use strict";p();Om.exports=ZI;function ZI(e){Object.keys(e.jobs).forEach(eD.bind(e)),e.jobs={}}function eD(e){typeof this.jobs[e]=="function"&&this.jobs[e]()}});var Oc=D((rH,Cm)=>{"use strict";p();var Nm=Ic(),tD=Dc();Cm.exports=rD;function rD(e,t,r,n){var s=r.keyedList?r.keyedList[r.index]:r.index;r.jobs[s]=nD(t,s,e[s],function(i,a){s in r.jobs&&(delete r.jobs[s],i?tD(r):r.results[s]=a,n(i,r.results))})}function nD(e,t,r,n){var s;return e.length==2?s=e(r,Nm(n)):s=e(r,t,Nm(n)),s}});var Nc=D((sH,Pm)=>{"use strict";p();Pm.exports=sD;function sD(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 Cc=D((aH,Lm)=>{"use strict";p();var iD=Dc(),aD=Ic();Lm.exports=oD;function oD(e){Object.keys(this.jobs).length&&(this.index=this.size,iD(this),aD(e)(null,this.results))}});var km=D((cH,Mm)=>{"use strict";p();var cD=Oc(),lD=Nc(),uD=Cc();Mm.exports=dD;function dD(e,t,r){for(var n=lD(e);n.index<(n.keyedList||e).length;)cD(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 uD.bind(n,r)}});var Pc=D((uH,Xi)=>{"use strict";p();var Um=Oc(),pD=Nc(),mD=Cc();Xi.exports=fD;Xi.exports.ascending=Fm;Xi.exports.descending=gD;function fD(e,t,r,n){var s=pD(e,r);return Um(e,t,s,function i(a,o){if(a){n(a,o);return}if(s.index++,s.index<(s.keyedList||e).length){Um(e,t,s,i);return}n(null,s.results)}),mD.bind(s,n)}function Fm(e,t){return e<t?-1:e>t?1:0}function gD(e,t){return-1*Fm(e,t)}});var jm=D((pH,qm)=>{"use strict";p();var hD=Pc();qm.exports=_D;function _D(e,t,r){return hD(e,t,null,r)}});var Vm=D((fH,Bm)=>{"use strict";p();Bm.exports={parallel:km(),serial:jm(),serialOrdered:Pc()}});var Lc=D((hH,Hm)=>{"use strict";p();Hm.exports=Object});var $m=D((yH,Gm)=>{"use strict";p();Gm.exports=Error});var Jm=D((TH,Wm)=>{"use strict";p();Wm.exports=EvalError});var Ym=D((vH,Km)=>{"use strict";p();Km.exports=RangeError});var Xm=D((wH,zm)=>{"use strict";p();zm.exports=ReferenceError});var Zm=D((xH,Qm)=>{"use strict";p();Qm.exports=SyntaxError});var Qi=D((IH,ef)=>{"use strict";p();ef.exports=TypeError});var rf=D((OH,tf)=>{"use strict";p();tf.exports=URIError});var sf=D((CH,nf)=>{"use strict";p();nf.exports=Math.abs});var of=D((LH,af)=>{"use strict";p();af.exports=Math.floor});var lf=D((kH,cf)=>{"use strict";p();cf.exports=Math.max});var df=D((FH,uf)=>{"use strict";p();uf.exports=Math.min});var mf=D((jH,pf)=>{"use strict";p();pf.exports=Math.pow});var gf=D((VH,ff)=>{"use strict";p();ff.exports=Math.round});var _f=D((GH,hf)=>{"use strict";p();hf.exports=Number.isNaN||function(t){return t!==t}});var Ef=D((WH,yf)=>{"use strict";p();var yD=_f();yf.exports=function(t){return yD(t)||t===0?t:t<0?-1:1}});var bf=D((KH,Tf)=>{"use strict";p();Tf.exports=Object.getOwnPropertyDescriptor});var Mc=D((zH,vf)=>{"use strict";p();var Zi=bf();if(Zi)try{Zi([],"length")}catch{Zi=null}vf.exports=Zi});var wf=D((QH,Rf)=>{"use strict";p();var ea=Object.defineProperty||!1;if(ea)try{ea({},"a",{value:1})}catch{ea=!1}Rf.exports=ea});var kc=D((eG,Af)=>{"use strict";p();Af.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 If=D((rG,Sf)=>{"use strict";p();var xf=typeof Symbol<"u"&&Symbol,ED=kc();Sf.exports=function(){return typeof xf!="function"||typeof Symbol!="function"||typeof xf("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:ED()}});var Uc=D((sG,Df)=>{"use strict";p();Df.exports=typeof Reflect<"u"&&Reflect.getPrototypeOf||null});var Fc=D((aG,Of)=>{"use strict";p();var TD=Lc();Of.exports=TD.getPrototypeOf||null});var Pf=D((cG,Cf)=>{"use strict";p();var bD="Function.prototype.bind called on incompatible ",vD=Object.prototype.toString,RD=Math.max,wD="[object Function]",Nf=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},AD=function(t,r){for(var n=[],s=r||0,i=0;s<t.length;s+=1,i+=1)n[i]=t[s];return n},xD=function(e,t){for(var r="",n=0;n<e.length;n+=1)r+=e[n],n+1<e.length&&(r+=t);return r};Cf.exports=function(t){var r=this;if(typeof r!="function"||vD.apply(r)!==wD)throw new TypeError(bD+r);for(var n=AD(arguments,1),s,i=function(){if(this instanceof s){var u=r.apply(this,Nf(n,arguments));return Object(u)===u?u:this}return r.apply(t,Nf(n,arguments))},a=RD(0,r.length-n.length),o=[],c=0;c<a;c++)o[c]="$"+c;if(s=Function("binder","return function ("+xD(o,",")+"){ return binder.apply(this,arguments); }")(i),r.prototype){var l=function(){};l.prototype=r.prototype,s.prototype=new l,l.prototype=null}return s}});var vs=D((uG,Lf)=>{"use strict";p();var SD=Pf();Lf.exports=Function.prototype.bind||SD});var ta=D((pG,Mf)=>{"use strict";p();Mf.exports=Function.prototype.call});var qc=D((fG,kf)=>{"use strict";p();kf.exports=Function.prototype.apply});var Ff=D((hG,Uf)=>{"use strict";p();Uf.exports=typeof Reflect<"u"&&Reflect&&Reflect.apply});var jf=D((yG,qf)=>{"use strict";p();var ID=vs(),DD=qc(),OD=ta(),ND=Ff();qf.exports=ND||ID.call(OD,DD)});var Vf=D((TG,Bf)=>{"use strict";p();var CD=vs(),PD=Qi(),LD=ta(),MD=jf();Bf.exports=function(t){if(t.length<1||typeof t[0]!="function")throw new PD("a function is required");return MD(CD,LD,t)}});var Kf=D((vG,Jf)=>{"use strict";p();var kD=Vf(),Hf=Mc(),$f;try{$f=[].__proto__===Array.prototype}catch(e){if(!e||typeof e!="object"||!("code"in e)||e.code!=="ERR_PROTO_ACCESS")throw e}var jc=!!$f&&Hf&&Hf(Object.prototype,"__proto__"),Wf=Object,Gf=Wf.getPrototypeOf;Jf.exports=jc&&typeof jc.get=="function"?kD([jc.get]):typeof Gf=="function"?function(t){return Gf(t==null?t:Wf(t))}:!1});var Zf=D((wG,Qf)=>{"use strict";p();var Yf=Uc(),zf=Fc(),Xf=Kf();Qf.exports=Yf?function(t){return Yf(t)}:zf?function(t){if(!t||typeof t!="object"&&typeof t!="function")throw new TypeError("getProto: not an object");return zf(t)}:Xf?function(t){return Xf(t)}:null});var ra=D((xG,eg)=>{"use strict";p();var UD=Function.prototype.call,FD=Object.prototype.hasOwnProperty,qD=vs();eg.exports=qD.call(UD,FD)});var og=D((IG,ag)=>{"use strict";p();var ie,jD=Lc(),BD=$m(),VD=Jm(),HD=Ym(),GD=Xm(),An=Zm(),wn=Qi(),$D=rf(),WD=sf(),JD=of(),KD=lf(),YD=df(),zD=mf(),XD=gf(),QD=Ef(),sg=Function,Bc=function(e){try{return sg('"use strict"; return ('+e+").constructor;")()}catch{}},Rs=Mc(),ZD=wf(),Vc=function(){throw new wn},eO=Rs?(function(){try{return arguments.callee,Vc}catch{try{return Rs(arguments,"callee").get}catch{return Vc}}})():Vc,vn=If()(),Ve=Zf(),tO=Fc(),rO=Uc(),ig=qc(),ws=ta(),Rn={},nO=typeof Uint8Array>"u"||!Ve?ie:Ve(Uint8Array),jr={__proto__:null,"%AggregateError%":typeof AggregateError>"u"?ie:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?ie:ArrayBuffer,"%ArrayIteratorPrototype%":vn&&Ve?Ve([][Symbol.iterator]()):ie,"%AsyncFromSyncIteratorPrototype%":ie,"%AsyncFunction%":Rn,"%AsyncGenerator%":Rn,"%AsyncGeneratorFunction%":Rn,"%AsyncIteratorPrototype%":Rn,"%Atomics%":typeof Atomics>"u"?ie:Atomics,"%BigInt%":typeof BigInt>"u"?ie:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?ie:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?ie:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?ie:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":BD,"%eval%":eval,"%EvalError%":VD,"%Float16Array%":typeof Float16Array>"u"?ie:Float16Array,"%Float32Array%":typeof Float32Array>"u"?ie:Float32Array,"%Float64Array%":typeof Float64Array>"u"?ie:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?ie:FinalizationRegistry,"%Function%":sg,"%GeneratorFunction%":Rn,"%Int8Array%":typeof Int8Array>"u"?ie:Int8Array,"%Int16Array%":typeof Int16Array>"u"?ie:Int16Array,"%Int32Array%":typeof Int32Array>"u"?ie:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":vn&&Ve?Ve(Ve([][Symbol.iterator]())):ie,"%JSON%":typeof JSON=="object"?JSON:ie,"%Map%":typeof Map>"u"?ie:Map,"%MapIteratorPrototype%":typeof Map>"u"||!vn||!Ve?ie:Ve(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":jD,"%Object.getOwnPropertyDescriptor%":Rs,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?ie:Promise,"%Proxy%":typeof Proxy>"u"?ie:Proxy,"%RangeError%":HD,"%ReferenceError%":GD,"%Reflect%":typeof Reflect>"u"?ie:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?ie:Set,"%SetIteratorPrototype%":typeof Set>"u"||!vn||!Ve?ie:Ve(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?ie:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":vn&&Ve?Ve(""[Symbol.iterator]()):ie,"%Symbol%":vn?Symbol:ie,"%SyntaxError%":An,"%ThrowTypeError%":eO,"%TypedArray%":nO,"%TypeError%":wn,"%Uint8Array%":typeof Uint8Array>"u"?ie:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?ie:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?ie:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?ie:Uint32Array,"%URIError%":$D,"%WeakMap%":typeof WeakMap>"u"?ie:WeakMap,"%WeakRef%":typeof WeakRef>"u"?ie:WeakRef,"%WeakSet%":typeof WeakSet>"u"?ie:WeakSet,"%Function.prototype.call%":ws,"%Function.prototype.apply%":ig,"%Object.defineProperty%":ZD,"%Object.getPrototypeOf%":tO,"%Math.abs%":WD,"%Math.floor%":JD,"%Math.max%":KD,"%Math.min%":YD,"%Math.pow%":zD,"%Math.round%":XD,"%Math.sign%":QD,"%Reflect.getPrototypeOf%":rO};if(Ve)try{null.error}catch(e){tg=Ve(Ve(e)),jr["%Error.prototype%"]=tg}var tg,sO=function e(t){var r;if(t==="%AsyncFunction%")r=Bc("async function () {}");else if(t==="%GeneratorFunction%")r=Bc("function* () {}");else if(t==="%AsyncGeneratorFunction%")r=Bc("async function* () {}");else if(t==="%AsyncGenerator%"){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(t==="%AsyncIteratorPrototype%"){var s=e("%AsyncGenerator%");s&&Ve&&(r=Ve(s.prototype))}return jr[t]=r,r},rg={__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"]},As=vs(),na=ra(),iO=As.call(ws,Array.prototype.concat),aO=As.call(ig,Array.prototype.splice),ng=As.call(ws,String.prototype.replace),sa=As.call(ws,String.prototype.slice),oO=As.call(ws,RegExp.prototype.exec),cO=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,lO=/\\(\\)?/g,uO=function(t){var r=sa(t,0,1),n=sa(t,-1);if(r==="%"&&n!=="%")throw new An("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new An("invalid intrinsic syntax, expected opening `%`");var s=[];return ng(t,cO,function(i,a,o,c){s[s.length]=o?ng(c,lO,"$1"):a||i}),s},dO=function(t,r){var n=t,s;if(na(rg,n)&&(s=rg[n],n="%"+s[0]+"%"),na(jr,n)){var i=jr[n];if(i===Rn&&(i=sO(n)),typeof i>"u"&&!r)throw new wn("intrinsic "+t+" exists, but is not available. Please file an issue!");return{alias:s,name:n,value:i}}throw new An("intrinsic "+t+" does not exist!")};ag.exports=function(t,r){if(typeof t!="string"||t.length===0)throw new wn("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new wn('"allowMissing" argument must be a boolean');if(oO(/^%?[^%]*%?$/,t)===null)throw new An("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=uO(t),s=n.length>0?n[0]:"",i=dO("%"+s+"%",r),a=i.name,o=i.value,c=!1,l=i.alias;l&&(s=l[0],aO(n,iO([0,1],l)));for(var u=1,d=!0;u<n.length;u+=1){var m=n[u],f=sa(m,0,1),g=sa(m,-1);if((f==='"'||f==="'"||f==="`"||g==='"'||g==="'"||g==="`")&&f!==g)throw new An("property names with quotes must have matching quotes");if((m==="constructor"||!d)&&(c=!0),s+="."+m,a="%"+s+"%",na(jr,a))o=jr[a];else if(o!=null){if(!(m in o)){if(!r)throw new wn("base intrinsic for "+t+" exists, but the property is not available.");return}if(Rs&&u+1>=n.length){var h=Rs(o,m);d=!!h,d&&"get"in h&&!("originalValue"in h.get)?o=h.get:o=o[m]}else d=na(o,m),o=o[m];d&&!c&&(jr[a]=o)}}return o}});var lg=D((OG,cg)=>{"use strict";p();var pO=kc();cg.exports=function(){return pO()&&!!Symbol.toStringTag}});var pg=D((CG,dg)=>{"use strict";p();var mO=og(),ug=mO("%Object.defineProperty%",!0),fO=lg()(),gO=ra(),hO=Qi(),ia=fO?Symbol.toStringTag:null;dg.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 hO("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans");ia&&(n||!gO(t,ia))&&(ug?ug(t,ia,{configurable:!s,enumerable:!1,value:r,writable:!1}):t[ia]=r)}});var fg=D((LG,mg)=>{"use strict";p();mg.exports=function(e,t){return Object.keys(t).forEach(function(r){e[r]=e[r]||t[r]}),e}});var _g=D((kG,hg)=>{"use strict";p();var Wc=Em(),_O=ae("util"),Hc=ae("path"),yO=ae("http"),EO=ae("https"),TO=ae("url").parse,bO=ae("fs"),vO=ae("stream").Stream,RO=ae("crypto"),Gc=Am(),wO=Vm(),AO=pg(),Rr=ra(),$c=fg();function gg(e){return String(e).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22")}function ue(e){if(!(this instanceof ue))return new ue(e);this._overheadLength=0,this._valueLength=0,this._valuesToMeasure=[],Wc.call(this),e=e||{};for(var t in e)this[t]=e[t]}_O.inherits(ue,Wc);ue.LINE_BREAK=`\r
|
|
4
|
+
`;ue.DEFAULT_CONTENT_TYPE="application/octet-stream";ue.prototype.append=function(e,t,r){r=r||{},typeof r=="string"&&(r={filename:r});var n=Wc.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)};ue.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)+ue.LINE_BREAK.length,!(!t||!t.path&&!(t.readable&&Rr(t,"httpVersion"))&&!(t instanceof vO))&&(r.knownLength||this._valuesToMeasure.push(t))};ue.prototype._lengthRetriever=function(e,t){Rr(e,"fd")?e.end!=null&&e.end!=1/0&&e.start!=null?t(null,e.end+1-(e.start?e.start:0)):bO.stat(e.path,function(r,n){if(r){t(r);return}var s=n.size-(e.start?e.start:0);t(null,s)}):Rr(e,"httpVersion")?t(null,Number(e.headers["content-length"])):Rr(e,"httpModule")?(e.on("response",function(r){e.pause(),t(null,Number(r.headers["content-length"]))}),e.resume()):t("Unknown stream")};ue.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="'+gg(e)+'"'].concat(n||[]),"Content-Type":[].concat(s||[])};typeof r.header=="object"&&$c(a,r.header);var o;for(var c in a)if(Rr(a,c)){if(o=a[c],o==null)continue;Array.isArray(o)||(o=[o]),o.length&&(i+=c+": "+o.join("; ")+ue.LINE_BREAK)}return"--"+this.getBoundary()+ue.LINE_BREAK+i+ue.LINE_BREAK};ue.prototype._getContentDisposition=function(e,t){var r;if(typeof t.filepath=="string"?r=Hc.normalize(t.filepath).replace(/\\/g,"/"):t.filename||e&&(e.name||e.path)?r=Hc.basename(t.filename||e&&(e.name||e.path)):e&&e.readable&&Rr(e,"httpVersion")&&(r=Hc.basename(e.client._httpMessage.path||"")),r)return'filename="'+gg(r)+'"'};ue.prototype._getContentType=function(e,t){var r=t.contentType;return!r&&e&&e.name&&(r=Gc.lookup(e.name)),!r&&e&&e.path&&(r=Gc.lookup(e.path)),!r&&e&&e.readable&&Rr(e,"httpVersion")&&(r=e.headers["content-type"]),!r&&(t.filepath||t.filename)&&(r=Gc.lookup(t.filepath||t.filename)),!r&&e&&typeof e=="object"&&(r=ue.DEFAULT_CONTENT_TYPE),r};ue.prototype._multiPartFooter=function(){return function(e){var t=ue.LINE_BREAK,r=this._streams.length===0;r&&(t+=this._lastBoundary()),e(t)}.bind(this)};ue.prototype._lastBoundary=function(){return"--"+this.getBoundary()+"--"+ue.LINE_BREAK};ue.prototype.getHeaders=function(e){var t,r={"content-type":"multipart/form-data; boundary="+this.getBoundary()};for(t in e)Rr(e,t)&&(r[t.toLowerCase()]=e[t]);return r};ue.prototype.setBoundary=function(e){if(typeof e!="string")throw new TypeError("FormData boundary must be a string");this._boundary=e};ue.prototype.getBoundary=function(){return this._boundary||this._generateBoundary(),this._boundary};ue.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(ue.LINE_BREAK)])));return Buffer.concat([e,Buffer.from(this._lastBoundary())])};ue.prototype._generateBoundary=function(){this._boundary="--------------------------"+RO.randomBytes(12).toString("hex")};ue.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};ue.prototype.hasKnownLength=function(){var e=!0;return this._valuesToMeasure.length&&(e=!1),e};ue.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}wO.parallel(this._valuesToMeasure,this._lengthRetriever,function(r,n){if(r){e(r);return}n.forEach(function(s){t+=s}),e(null,t)})};ue.prototype.submit=function(e,t){var r,n,s={method:"post"};return typeof e=="string"?(e=TO(e),n=$c({port:e.port,path:e.pathname,host:e.hostname,protocol:e.protocol},s)):(n=$c(e,s),n.port||(n.port=n.protocol==="https:"?443:80)),n.headers=this.getHeaders(e.headers),n.protocol==="https:"?r=EO.request(n):r=yO.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(l,u){return r.removeListener("error",c),r.removeListener("response",o),t.call(this,l,u)};o=c.bind(this,null),r.on("error",c),r.on("response",o)}}.bind(this)),r};ue.prototype._error=function(e){this.error||(this.error=e,this.pause(),this.emit("error",e))};ue.prototype.toString=function(){return"[object FormData]"};AO(ue.prototype,"FormData");hg.exports=ue});var Eg=D((FG,yg)=>{"use strict";p();var xn=1e3,Sn=xn*60,In=Sn*60,Br=In*24,xO=Br*7,SO=Br*365.25;yg.exports=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0)return IO(e);if(r==="number"&&isFinite(e))return t.long?OO(e):DO(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function IO(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*SO;case"weeks":case"week":case"w":return r*xO;case"days":case"day":case"d":return r*Br;case"hours":case"hour":case"hrs":case"hr":case"h":return r*In;case"minutes":case"minute":case"mins":case"min":case"m":return r*Sn;case"seconds":case"second":case"secs":case"sec":case"s":return r*xn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function DO(e){var t=Math.abs(e);return t>=Br?Math.round(e/Br)+"d":t>=In?Math.round(e/In)+"h":t>=Sn?Math.round(e/Sn)+"m":t>=xn?Math.round(e/xn)+"s":e+"ms"}function OO(e){var t=Math.abs(e);return t>=Br?aa(e,t,Br,"day"):t>=In?aa(e,t,In,"hour"):t>=Sn?aa(e,t,Sn,"minute"):t>=xn?aa(e,t,xn,"second"):e+" ms"}function aa(e,t,r,n){var s=t>=r*1.5;return Math.round(e/r)+" "+n+(s?"s":"")}});var Jc=D((jG,Tg)=>{"use strict";p();function NO(e){r.debug=r,r.default=r,r.coerce=c,r.disable=a,r.enable=s,r.enabled=o,r.humanize=Eg(),r.destroy=l,Object.keys(e).forEach(u=>{r[u]=e[u]}),r.names=[],r.skips=[],r.formatters={};function t(u){let d=0;for(let m=0;m<u.length;m++)d=(d<<5)-d+u.charCodeAt(m),d|=0;return r.colors[Math.abs(d)%r.colors.length]}r.selectColor=t;function r(u){let d,m=null,f,g;function h(...E){if(!h.enabled)return;let T=h,w=Number(new Date),v=w-(d||w);T.diff=v,T.prev=d,T.curr=w,d=w,E[0]=r.coerce(E[0]),typeof E[0]!="string"&&E.unshift("%O");let A=0;E[0]=E[0].replace(/%([a-zA-Z%])/g,(P,L)=>{if(P==="%%")return"%";A++;let W=r.formatters[L];if(typeof W=="function"){let Z=E[A];P=W.call(T,Z),E.splice(A,1),A--}return P}),r.formatArgs.call(T,E),(T.log||r.log).apply(T,E)}return h.namespace=u,h.useColors=r.useColors(),h.color=r.selectColor(u),h.extend=n,h.destroy=r.destroy,Object.defineProperty(h,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(f!==r.namespaces&&(f=r.namespaces,g=r.enabled(u)),g),set:E=>{m=E}}),typeof r.init=="function"&&r.init(h),h}function n(u,d){let m=r(this.namespace+(typeof d>"u"?":":d)+u);return m.log=this.log,m}function s(u){r.save(u),r.namespaces=u,r.names=[],r.skips=[];let d=(typeof u=="string"?u:"").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(u,d){let m=0,f=0,g=-1,h=0;for(;m<u.length;)if(f<d.length&&(d[f]===u[m]||d[f]==="*"))d[f]==="*"?(g=f,h=m,f++):(m++,f++);else if(g!==-1)f=g+1,h++,m=h;else return!1;for(;f<d.length&&d[f]==="*";)f++;return f===d.length}function a(){let u=[...r.names,...r.skips.map(d=>"-"+d)].join(",");return r.enable(""),u}function o(u){for(let d of r.skips)if(i(u,d))return!1;for(let d of r.names)if(i(u,d))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){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}Tg.exports=NO});var bg=D((ct,oa)=>{"use strict";p();ct.formatArgs=PO;ct.save=LO;ct.load=MO;ct.useColors=CO;ct.storage=kO();ct.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`."))}})();ct.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 CO(){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 PO(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+oa.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)}ct.log=console.debug||console.log||(()=>{});function LO(e){try{e?ct.storage.setItem("debug",e):ct.storage.removeItem("debug")}catch{}}function MO(){let e;try{e=ct.storage.getItem("debug")||ct.storage.getItem("DEBUG")}catch{}return!e&&typeof process<"u"&&"env"in process&&(e=process.env.DEBUG),e}function kO(){try{return localStorage}catch{}}oa.exports=Jc()(ct);var{formatters:UO}=oa.exports;UO.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var Rg=D((He,la)=>{"use strict";p();var FO=ae("tty"),ca=ae("util");He.init=$O;He.log=VO;He.formatArgs=jO;He.save=HO;He.load=GO;He.useColors=qO;He.destroy=ca.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");He.colors=[6,2,3,4,5,1];try{let e=ae("supports-color");e&&(e.stderr||e).level>=2&&(He.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{}He.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 qO(){return"colors"in He.inspectOpts?!!He.inspectOpts.colors:FO.isatty(process.stderr.fd)}function jO(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+"+la.exports.humanize(this.diff)+"\x1B[0m")}else e[0]=BO()+t+" "+e[0]}function BO(){return He.inspectOpts.hideDate?"":new Date().toISOString()+" "}function VO(...e){return process.stderr.write(ca.formatWithOptions(He.inspectOpts,...e)+`
|
|
7
|
+
`)}function HO(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function GO(){return process.env.DEBUG}function $O(e){e.inspectOpts={};let t=Object.keys(He.inspectOpts);for(let r=0;r<t.length;r++)e.inspectOpts[t[r]]=He.inspectOpts[t[r]]}la.exports=Jc()(He);var{formatters:vg}=la.exports;vg.o=function(e){return this.inspectOpts.colors=this.useColors,ca.inspect(e,this.inspectOpts).split(`
|
|
8
|
+
`).map(t=>t.trim()).join(" ")};vg.O=function(e){return this.inspectOpts.colors=this.useColors,ca.inspect(e,this.inspectOpts)}});var Dn=D((GG,Kc)=>{"use strict";p();typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Kc.exports=bg():Kc.exports=Rg()});var wg=D(Yc=>{"use strict";p();Object.defineProperty(Yc,"__esModule",{value:!0});function WO(e){return function(t,r){return new Promise((n,s)=>{e.call(this,t,r,(i,a)=>{i?s(i):n(a)})})}}Yc.default=WO});var Sg=D((Xc,xg)=>{"use strict";p();var Ag=Xc&&Xc.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},JO=ae("events"),KO=Ag(Dn()),YO=Ag(wg()),xs=KO.default("agent-base");function zO(e){return!!e&&typeof e.addRequest=="function"}function zc(){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 ua(e,t){return new ua.Agent(e,t)}(function(e){class t extends JO.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:zc()?443:80}set defaultPort(n){this.explicitDefaultPort=n}get protocol(){return typeof this.explicitProtocol=="string"?this.explicitProtocol:zc()?"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=zc()),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,l=f=>{n._hadError||(n.emit("error",f),n._hadError=!0)},u=()=>{o=null,a=!0;let f=new Error(`A "socket" was not created for HTTP request before ${c}ms`);f.code="ETIMEOUT",l(f)},d=f=>{a||(o!==null&&(clearTimeout(o),o=null),l(f))},m=f=>{if(a)return;if(o!=null&&(clearTimeout(o),o=null),zO(f)){xs("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}\``);l(g)};if(typeof this.callback!="function"){l(new Error("`callback` is not defined"));return}this.promisifiedCallback||(this.callback.length>=3?(xs("Converting legacy callback function to promise"),this.promisifiedCallback=YO.default(this.callback)):this.promisifiedCallback=this.callback),typeof c=="number"&&c>0&&(o=setTimeout(u,c)),"port"in i&&typeof i.port!="number"&&(i.port=Number(i.port));try{xs("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){xs("Freeing socket %o %o",n.constructor.name,s),n.destroy()}destroy(){xs("Destroying agent %o",this.constructor.name)}}e.Agent=t,e.prototype=e.Agent.prototype})(ua||(ua={}));xg.exports=ua});var Ig=D(Is=>{"use strict";p();var XO=Is&&Is.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Is,"__esModule",{value:!0});var QO=XO(Dn()),Ss=QO.default("https-proxy-agent:parse-proxy-response");function ZO(e){return new Promise((t,r)=>{let n=0,s=[];function i(){let d=e.read();d?u(d):e.once("readable",i)}function a(){e.removeListener("end",c),e.removeListener("error",l),e.removeListener("close",o),e.removeListener("readable",i)}function o(d){Ss("onclose had error %o",d)}function c(){Ss("onend")}function l(d){a(),Ss("onerror %o",d),r(d)}function u(d){s.push(d),n+=d.length;let m=Buffer.concat(s,n);if(m.indexOf(`\r
|
|
10
|
+
\r
|
|
11
|
+
`)===-1){Ss("have not received end of HTTP headers yet..."),i();return}let g=m.toString("ascii",0,m.indexOf(`\r
|
|
12
|
+
`)),h=+g.split(" ")[1];Ss("got proxy server response: %o",g),t({statusCode:h,buffered:m})}e.on("error",l),e.on("close",o),e.on("end",c),i()})}Is.default=ZO});var Ng=D(Vr=>{"use strict";p();var eN=Vr&&Vr.__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(u){try{l(n.next(u))}catch(d){a(d)}}function c(u){try{l(n.throw(u))}catch(d){a(d)}}function l(u){u.done?i(u.value):s(u.value).then(o,c)}l((n=n.apply(e,t||[])).next())})},On=Vr&&Vr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Vr,"__esModule",{value:!0});var Dg=On(ae("net")),Og=On(ae("tls")),tN=On(ae("url")),rN=On(ae("assert")),nN=On(Dn()),sN=Sg(),iN=On(Ig()),Ds=nN.default("https-proxy-agent:agent"),Qc=class extends sN.Agent{constructor(t){let r;if(typeof t=="string"?r=tN.default.parse(t):r=t,!r)throw new Error("an HTTP(S) proxy server `host` and `port` must be specified!");Ds("creating new HttpsProxyAgent instance: %o",r),super(r);let n=Object.assign({},r);this.secureProxy=r.secureProxy||cN(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 eN(this,void 0,void 0,function*(){let{proxy:n,secureProxy:s}=this,i;s?(Ds("Creating `tls.Socket`: %o",n),i=Og.default.connect(n)):(Ds("Creating `net.Socket`: %o",n),i=Dg.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:l,port:u,secureEndpoint:d}=r;oN(u,d)||(l+=`:${u}`),a.Host=l,a.Connection="close";for(let E of Object.keys(a))c+=`${E}: ${a[E]}\r
|
|
14
|
+
`;let m=iN.default(i);i.write(`${c}\r
|
|
15
|
+
`);let{statusCode:f,buffered:g}=yield m;if(f===200){if(t.once("socket",aN),r.secureEndpoint){Ds("Upgrading socket connection to TLS");let E=r.servername||r.host;return Og.default.connect(Object.assign(Object.assign({},lN(r,"host","hostname","path","port")),{socket:i,servername:E}))}return i}i.destroy();let h=new Dg.default.Socket({writable:!1});return h.readable=!0,t.once("socket",E=>{Ds("replaying proxy buffer for failed request"),rN.default(E.listenerCount("data")>0),E.push(g),E.push(null)}),h})}};Vr.default=Qc;function aN(e){e.resume()}function oN(e,t){return!!(!t&&e===80||t&&e===443)}function cN(e){return typeof e=="string"?/^https:?$/i.test(e):!1}function lN(e,...t){let r={},n;for(n in e)t.includes(n)||(r[n]=e[n]);return r}});var Pg=D((tl,Cg)=>{"use strict";p();var uN=tl&&tl.__importDefault||function(e){return e&&e.__esModule?e:{default:e}},Zc=uN(Ng());function el(e){return new Zc.default(e)}(function(e){e.HttpsProxyAgent=Zc.default,e.prototype=Zc.default.prototype})(el||(el={}));Cg.exports=el});var Mg=D((e$,Lg)=>{"use strict";p();var Os;Lg.exports=function(){if(!Os){try{Os=Dn()("follow-redirects")}catch{}typeof Os!="function"&&(Os=function(){})}Os.apply(null,arguments)}});var jg=D((r$,ml)=>{"use strict";p();var Cs=ae("url"),Ns=Cs.URL,dN=ae("http"),pN=ae("https"),al=ae("stream").Writable,ol=ae("assert"),kg=Mg();(function(){var t=typeof process<"u",r=typeof window<"u"&&typeof document<"u",n=Gr(Error.captureStackTrace);!t&&(r||!n)&&console.warn("The follow-redirects package should be excluded from browser builds.")})();var cl=!1;try{ol(new Ns(""))}catch(e){cl=e.code==="ERR_INVALID_URL"}var mN=["Authorization","Proxy-Authorization","Cookie"],fN=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],ll=["abort","aborted","connect","error","socket","timeout"],ul=Object.create(null);ll.forEach(function(e){ul[e]=function(t,r,n){this._redirectable.emit(e,t,r,n)}});var nl=Ps("ERR_INVALID_URL","Invalid URL",TypeError),sl=Ps("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),gN=Ps("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",sl),hN=Ps("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),_N=Ps("ERR_STREAM_WRITE_AFTER_END","write after end"),yN=al.prototype.destroy||Fg;function lt(e,t){al.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 sl?s:new sl({cause:s}))}},this._headerFilter=new RegExp("^(?:"+mN.concat(e.sensitiveHeaders).map(wN).join("|")+")$","i"),this._performRequest()}lt.prototype=Object.create(al.prototype);lt.prototype.abort=function(){pl(this._currentRequest),this._currentRequest.abort(),this.emit("abort")};lt.prototype.destroy=function(e){return pl(this._currentRequest,e),yN.call(this,e),this};lt.prototype.write=function(e,t,r){if(this._ending)throw new _N;if(!Hr(e)&&!vN(e))throw new TypeError("data should be a string, Buffer or Uint8Array");if(Gr(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 hN),this.abort())};lt.prototype.end=function(e,t,r){if(Gr(e)?(r=e,e=t=null):Gr(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}};lt.prototype.setHeader=function(e,t){this._options.headers[e]=t,this._currentRequest.setHeader(e,t)};lt.prototype.removeHeader=function(e){delete this._options.headers[e],this._currentRequest.removeHeader(e)};lt.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){lt.prototype[e]=function(t,r){return this._currentRequest[e](t,r)}});["aborted","connection","socket"].forEach(function(e){Object.defineProperty(lt.prototype,e,{get:function(){return this._currentRequest[e]}})});lt.prototype._sanitizeOptions=function(e){if(e.headers||(e.headers={}),bN(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))}};lt.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 ll)n.on(s,ul[s]);if(this._currentUrl=/^\//.test(this._options.path)?Cs.format(this._options):this._options.path,this._isRedirect){var i=0,a=this,o=this._requestBodyBuffers;(function c(l){if(n===a._currentRequest)if(l)a.emit("error",l);else if(i<o.length){var u=o[i++];n.finished||n.write(u.data,u.encoding,c)}else a._ended&&n.end()})()}};lt.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(pl(this._currentRequest),e.destroy(),++this._redirectCount>this._options.maxRedirects)throw new gN;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=[],rl(/^content-/i,this._options.headers));var a=rl(/^host$/i,this._options.headers),o=dl(this._currentUrl),c=a||o.host,l=/^\w+:/.test(r)?this._currentUrl:Cs.format(Object.assign(o,{host:c})),u=EN(r,l);if(kg("redirecting to",u.href),this._isRedirect=!0,il(u,this._options),(u.protocol!==o.protocol&&u.protocol!=="https:"||u.host!==c&&!TN(u.host,c))&&rl(this._headerFilter,this._options.headers),Gr(s)){var d={headers:e.headers,statusCode:t},m={url:l,method:i,headers:n};s(this._options,d,m),this._sanitizeOptions(this._options)}this._performRequest()};function Ug(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(l,u,d){return RN(l)?l=il(l):Hr(l)?l=il(dl(l)):(d=u,u=qg(l),l={protocol:s}),Gr(u)&&(d=u,u=null),u=Object.assign({maxRedirects:t.maxRedirects,maxBodyLength:t.maxBodyLength},l,u),u.nativeProtocols=r,!Hr(u.host)&&!Hr(u.hostname)&&(u.hostname="::1"),ol.equal(u.protocol,s,"protocol mismatch"),kg("options",u),new lt(u,d)}function c(l,u,d){var m=a.request(l,u,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 Fg(){}function dl(e){var t;if(cl)t=new Ns(e);else if(t=qg(Cs.parse(e)),!Hr(t.protocol))throw new nl({input:e});return t}function EN(e,t){return cl?new Ns(e,t):dl(Cs.resolve(t,e))}function qg(e){if(/^\[/.test(e.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(e.hostname))throw new nl({input:e.href||e});if(/^\[/.test(e.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(e.host))throw new nl({input:e.href||e});return e}function il(e,t){var r=t||{};for(var n of fN)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 rl(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){Gr(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 pl(e,t){for(var r of ll)e.removeListener(r,ul[r]);e.on("error",Fg),e.destroy(t)}function TN(e,t){ol(Hr(e)&&Hr(t));var r=e.length-t.length-1;return r>0&&e[r]==="."&&e.endsWith(t)}function bN(e){return e instanceof Array}function Hr(e){return typeof e=="string"||e instanceof String}function Gr(e){return typeof e=="function"}function vN(e){return typeof e=="object"&&"length"in e}function RN(e){return Ns&&e instanceof Ns}function wN(e){return e.replace(/[\]\\/()*+?.$]/g,"\\$&")}ml.exports=Ug({http:dN,https:pN});ml.exports.wrap=Ug});var tt=D((s$,t_)=>{"use strict";p();var _h=_g(),AN=ae("crypto"),xN=ae("url"),yh=Pg(),Eh=ae("http"),Th=ae("https"),bh=ae("http2"),Ll=ae("util"),Bg=ae("path"),SN=jg(),Dt=ae("zlib"),ut=ae("stream"),IN=ae("events");function vh(e,t){return function(){return e.apply(t,arguments)}}var{toString:DN}=Object.prototype,{getPrototypeOf:Pn}=Object,{iterator:Fs,toStringTag:Rh}=Symbol,ha=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),Ms=(e,t)=>{let r=e,n=[];for(;r!=null&&r!==Object.prototype;){if(n.indexOf(r)!==-1)return!1;if(n.push(r),ha(r,t))return!0;r=Pn(r)}return!1},ON=(e,t)=>e!=null&&Ms(e,t)?e[t]:void 0,Ml=(e=>t=>{let r=DN.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Ot=e=>(e=e.toLowerCase(),t=>Ml(t)===e),va=e=>t=>typeof t===e,{isArray:Jr}=Array,Kr=va("undefined");function Mn(e){return e!==null&&!Kr(e)&&e.constructor!==null&&!Kr(e.constructor)&&dt(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var wh=Ot("ArrayBuffer");function NN(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&wh(e.buffer),t}var CN=va("string"),dt=va("function"),Ah=va("number"),kn=e=>e!==null&&typeof e=="object",PN=e=>e===!0||e===!1,ma=e=>{if(!kn(e))return!1;let t=Pn(e);return(t===null||t===Object.prototype||Pn(t)===null)&&!Ms(e,Rh)&&!Ms(e,Fs)},LN=e=>{if(!kn(e)||Mn(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},MN=Ot("Date"),kN=Ot("File"),UN=e=>!!(e&&typeof e.uri<"u"),FN=e=>e&&typeof e.getParts<"u",qN=Ot("Blob"),jN=Ot("FileList"),BN=Ot("Set"),VN=e=>kn(e)&&dt(e.pipe);function HN(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}var Vg=HN(),Hg=typeof Vg.FormData<"u"?Vg.FormData:void 0,GN=e=>{if(!e)return!1;if(Hg&&e instanceof Hg)return!0;let t=Pn(e);if(!t||t===Object.prototype||!dt(e.append))return!1;let r=Ml(e);return r==="formdata"||r==="object"&&dt(e.toString)&&e.toString()==="[object FormData]"},$N=Ot("URLSearchParams"),[WN,JN,KN,YN]=["ReadableStream","Request","Response","Headers"].map(Ot),zN=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function qs(e,t,{allOwnKeys:r=!1}={}){if(e===null||typeof e>"u")return;let n,s;if(typeof e!="object"&&(e=[e]),Jr(e))for(n=0,s=e.length;n<s;n++)t.call(null,e[n],n,e);else{if(Mn(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 xh(e,t){if(Mn(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 $r=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Sh=e=>!Kr(e)&&e!==$r;function Al(...e){let{caseless:t,skipUndefined:r}=Sh(this)&&this||{},n={},s=(i,a)=>{if(a==="__proto__"||a==="constructor"||a==="prototype")return;let o=t&&typeof a=="string"&&xh(n,a)||a,c=ha(n,o)?n[o]:void 0;ma(c)&&ma(i)?n[o]=Al(c,i):ma(i)?n[o]=Al({},i):Jr(i)?n[o]=i.slice():(!r||!Kr(i))&&(n[o]=i)};for(let i=0,a=e.length;i<a;i++){let o=e[i];if(!o||Mn(o)||(qs(o,s),typeof o!="object"||Jr(o)))continue;let c=Object.getOwnPropertySymbols(o);for(let l=0;l<c.length;l++){let u=c[l];cC.call(o,u)&&s(o[u],u)}}return n}var XN=(e,t,r,{allOwnKeys:n}={})=>(qs(t,(s,i)=>{r&&dt(s)?Object.defineProperty(e,i,{__proto__:null,value:vh(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),QN=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),ZN=(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)},eC=(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&&Pn(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},tC=(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},rC=e=>{if(!e)return null;if(Jr(e))return e;let t=e.length;if(!Ah(t))return null;let r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},nC=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Pn(Uint8Array)),sC=(e,t)=>{let n=(e&&e[Fs]).call(e),s;for(;(s=n.next())&&!s.done;){let i=s.value;t.call(e,i[0],i[1])}},iC=(e,t)=>{let r,n=[];for(;(r=e.exec(t))!==null;)n.push(r);return n},aC=Ot("HTMLFormElement"),oC=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,s){return n.toUpperCase()+s}),{propertyIsEnumerable:cC}=Object.prototype,lC=Ot("RegExp"),Ih=(e,t)=>{let r=Object.getOwnPropertyDescriptors(e),n={};qs(r,(s,i)=>{let a;(a=t(s,i,e))!==!1&&(n[i]=a||s)}),Object.defineProperties(e,n)},uC=e=>{Ih(e,(t,r)=>{if(dt(e)&&["arguments","caller","callee"].includes(r))return!1;let n=e[r];if(dt(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+"'")})}})},dC=(e,t)=>{let r={},n=s=>{s.forEach(i=>{r[i]=!0})};return Jr(e)?n(e):n(String(e).split(t)),r},pC=()=>{},mC=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function fC(e){return!!(e&&dt(e.append)&&e[Rh]==="FormData"&&e[Fs])}var gC=e=>{let t=new WeakSet,r=n=>{if(kn(n)){if(t.has(n))return;if(Mn(n))return n;if(!("toJSON"in n)){t.add(n);let s;if(BN(n)){s=[];for(let i of n){let a=r(i);!Kr(a)&&s.push(a)}}else s=Jr(n)?[]:{},qs(n,(i,a)=>{let o=r(i);!Kr(o)&&(s[a]=o)});return t.delete(n),s}}return n};return r(e)},hC=Ot("AsyncFunction"),_C=e=>e&&(kn(e)||dt(e))&&dt(e.then)&&dt(e.catch),Dh=((e,t)=>e?setImmediate:t?((r,n)=>($r.addEventListener("message",({source:s,data:i})=>{s===$r&&i===r&&n.length&&n.shift()()},!1),s=>{n.push(s),$r.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",dt($r.postMessage)),yC=typeof queueMicrotask<"u"?queueMicrotask.bind($r):typeof process<"u"&&process.nextTick||Dh,Oh=e=>e!=null&&dt(e[Fs]),EC=e=>e!=null&&Ms(e,Fs)&&Oh(e),y={isArray:Jr,isArrayBuffer:wh,isBuffer:Mn,isFormData:GN,isArrayBufferView:NN,isString:CN,isNumber:Ah,isBoolean:PN,isObject:kn,isPlainObject:ma,isEmptyObject:LN,isReadableStream:WN,isRequest:JN,isResponse:KN,isHeaders:YN,isUndefined:Kr,isDate:MN,isFile:kN,isReactNativeBlob:UN,isReactNative:FN,isBlob:qN,isRegExp:lC,isFunction:dt,isStream:VN,isURLSearchParams:$N,isTypedArray:nC,isFileList:jN,forEach:qs,merge:Al,extend:XN,trim:zN,stripBOM:QN,inherits:ZN,toFlatObject:eC,kindOf:Ml,kindOfTest:Ot,endsWith:tC,toArray:rC,forEachEntry:sC,matchAll:iC,isHTMLForm:aC,hasOwnProperty:ha,hasOwnProp:ha,hasOwnInPrototypeChain:Ms,getSafeProp:ON,reduceDescriptors:Ih,freezeMethods:uC,toObjectSet:dC,toCamelCase:oC,noop:pC,toFiniteNumber:mC,findKey:xh,global:$r,isContextDefined:Sh,isSpecCompliantForm:fC,toJSONObject:gC,isAsyncFn:hC,isThenable:_C,setImmediate:Dh,asap:yC,isIterable:Oh,isSafeIterable:EC},TC=y.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"]),bC=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=y.hasOwnProp(t,r);!r||o&&y.hasOwnProp(TC,r)||(r==="set-cookie"?o?t[r].push(n):t[r]=[n]:t[r]=o?t[r]+", "+n:n)}),t};function vC(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 RC=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),wC=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function kl(e,t){return y.isArray(e)?e.map(r=>kl(r,t)):vC(String(e).replace(t,""))}var AC=e=>kl(e,RC),xC=e=>kl(e,wC);function Ul(e){let t=Object.create(null);return y.forEach(e.toJSON(),(r,n)=>{t[n]=xC(r)}),t}var Gg=Symbol("internals");function Ls(e){return e&&String(e).trim().toLowerCase()}function fa(e){return e===!1||e==null?e:y.isArray(e)?e.map(fa):AC(String(e))}function SC(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 IC=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function fl(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 DC(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 OC(e){let t=Object.create(null),r=String(e),n=0,s=!1,i=!1;function a(o){let c=fl(r.slice(n,o)),l=c.indexOf("=");if(l<1)return;let u=fl(c.slice(0,l));if(!IC.test(u))return;let d=u.toLowerCase();if(d==="__proto__"||d==="constructor"||d==="prototype")return;let m=fl(c.slice(l+1));t[d]=DC(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 NC=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function gl(e,t,r,n,s){if(y.isFunction(n))return n.call(this,t,r);if(s&&(t=r),!!y.isString(t)){if(y.isString(n))return t.indexOf(n)!==-1;if(y.isRegExp(n))return n.test(t)}}function CC(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,r,n)=>r.toUpperCase()+n)}function PC(e,t){let r=y.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 Pe=class{constructor(t){t&&this.set(t)}set(t,r,n){let s=this;function i(o,c,l){let u=Ls(c);if(!u)return;let d=y.findKey(s,u);(!d||s[d]===void 0||l===!0||l===void 0&&s[d]!==!1)&&(s[d||c]=fa(o))}let a=(o,c)=>y.forEach(o,(l,u)=>i(l,u,c));if(y.isPlainObject(t)||t instanceof this.constructor)a(t,r);else if(y.isString(t)&&(t=t.trim())&&!NC(t))a(bC(t),r);else if(y.isObject(t)&&y.isSafeIterable(t)){let o=Object.create(null),c,l;for(let u of t){if(!y.isArray(u))throw new TypeError("Object iterator must return a key-value pair");l=u[0],y.hasOwnProp(o,l)?(c=o[l],o[l]=y.isArray(c)?[...c,u[1]]:[c,u[1]]):o[l]=u[1]}a(o,r)}else t!=null&&i(r,t,n);return this}get(t,r){if(t=Ls(t),t){let n=y.findKey(this,t);if(n){let s=this[n];if(!r)return s;if(r===!0)return SC(s);if(y.isFunction(r))return r.call(this,s,n);if(y.isRegExp(r))return r.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,r){if(t=Ls(t),t){let n=y.findKey(this,t);return!!(n&&this[n]!==void 0&&(!r||gl(this,this[n],n,r)))}return!1}delete(t,r){let n=this,s=!1;function i(a){if(a=Ls(a),a){let o=y.findKey(n,a);o&&(!r||gl(n,n[o],o,r))&&(delete n[o],s=!0)}}return y.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||gl(this,this[i],i,t,!0))&&(delete this[i],s=!0)}return s}normalize(t){let r=this,n={};return y.forEach(this,(s,i)=>{let a=y.findKey(n,i);if(a){r[a]=fa(s),delete r[i];return}let o=t?CC(i):String(i).trim();o!==i&&delete r[i],r[o]=fa(s),n[o]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let r=Object.create(null);return y.forEach(this,(n,s)=>{n!=null&&n!==!1&&(r[s]=t&&y.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 y.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 OC(t)}static concat(t,...r){let n=new this(t);return r.forEach(s=>n.set(s)),n}static accessor(t){let n=(this[Gg]=this[Gg]={accessors:{}}).accessors,s=this.prototype;function i(a){let o=Ls(a);n[o]||(PC(s,a),n[o]=!0)}return y.isArray(t)?t.forEach(i):i(t),this}};Pe.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);y.reduceDescriptors(Pe.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}});y.freezeMethods(Pe);var _a="[REDACTED ****]";function LC(e){if(y.hasOwnProp(e,"toJSON"))return!0;let t=Object.getPrototypeOf(e);for(;t&&t!==Object.prototype;){if(y.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}function MC(e,t){let r=new Set(t.map(i=>String(i).toLowerCase())),n=[],s=i=>{if(i===null||typeof i!="object"||y.isBuffer(i))return i;if(n.indexOf(i)!==-1)return;i instanceof Pe&&(i=i.toJSON()),n.push(i);let a;if(y.isArray(i))a=[],i.forEach((o,c)=>{let l=s(o);y.isUndefined(l)||(a[c]=l)});else{if(!y.isPlainObject(i)&&LC(i))return n.pop(),i;a=Object.create(null);for(let[o,c]of Object.entries(i)){let l=r.has(o.toLowerCase())?_a:s(c);y.isUndefined(l)||(a[o]=l)}}return n.pop(),a};return s(e)}function $g(e){try{return String(e)}catch{return""}}function kC(e){return e.errors.map(r=>{try{return r&&r.message?$g(r.message):$g(r)}catch{return""}}).filter(Boolean).join("; ")||e.name||"AggregateError"}var I=class e extends Error{static from(t,r,n,s,i,a){let o=t.message;!o&&y.isArray(t.errors)&&t.errors.length&&(o=kC(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&&y.hasOwnProp(t,"redact")?t.redact:void 0,n=y.isArray(r)&&r.length>0?MC(t,r):y.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}}};I.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";I.ERR_BAD_OPTION="ERR_BAD_OPTION";I.ECONNABORTED="ECONNABORTED";I.ETIMEDOUT="ETIMEDOUT";I.ECONNREFUSED="ECONNREFUSED";I.ERR_NETWORK="ERR_NETWORK";I.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";I.ERR_DEPRECATED="ERR_DEPRECATED";I.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";I.ERR_BAD_REQUEST="ERR_BAD_REQUEST";I.ERR_CANCELED="ERR_CANCELED";I.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";I.ERR_INVALID_URL="ERR_INVALID_URL";I.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";var hl={isBufferAvailable(){return typeof Buffer<"u"},from(e){return Buffer.from(e)}},Nh=100;function xl(e){return y.isPlainObject(e)||y.isArray(e)}function Ch(e){return y.endsWith(e,"[]")?e.slice(0,-2):e}function _l(e,t,r){return e?e.concat(t).map(function(s,i){return s=Ch(s),!r&&i?"["+s+"]":s}).join(r?".":""):t}function UC(e){return y.isArray(e)&&!e.some(xl)}var FC=y.toFlatObject(y,{},null,function(t){return/^is[A-Z]/.test(t)});function Ra(e,t,r){if(!y.isObject(e))throw new TypeError("target must be an object");t=t||new(_h||FormData),r=y.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(w,v){return!y.isUndefined(v[w])});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?Nh:r.maxDepth,l=o&&y.isSpecCompliantForm(t),u=[];if(!y.isFunction(s))throw new TypeError("visitor must be a function");function d(T){if(T===null)return"";if(y.isDate(T))return T.toISOString();if(y.isBoolean(T))return T.toString();if(!l&&y.isBlob(T))throw new I("Blob is not supported. Use a Buffer instead.");if(y.isArrayBuffer(T)||y.isTypedArray(T)){if(l&&typeof o=="function")return new o([T]);if(hl&&hl.isBufferAvailable())return hl.from(T);throw new I("Blob is not supported. Use a Buffer instead.",I.ERR_NOT_SUPPORT)}return T}function m(T){if(T>c)throw new I("Object is too deeply nested ("+T+" levels). Max depth: "+c,I.ERR_FORM_DATA_DEPTH_EXCEEDED)}function f(T,w){if(c===1/0)return JSON.stringify(T);let v=[];return JSON.stringify(T,function(C,P){if(!y.isObject(P))return P;for(;v.length&&v[v.length-1]!==this;)v.pop();return v.push(P),m(w+v.length-1),P})}function g(T,w,v){let A=T;if(y.isReactNative(t)&&y.isReactNativeBlob(T))return t.append(_l(v,w,i),d(T)),!1;if(T&&!v&&typeof T=="object"){if(y.endsWith(w,"{}"))w=n?w:w.slice(0,-2),T=f(T,1);else if(y.isArray(T)&&UC(T)||(y.isFileList(T)||y.endsWith(w,"[]"))&&(A=y.toArray(T)))return w=Ch(w),A.forEach(function(P,L){!(y.isUndefined(P)||P===null)&&t.append(a===!0?_l([w],L,i):a===null?w:w+"[]",d(P))}),!1}return xl(T)?!0:(t.append(_l(v,w,i),d(T)),!1)}let h=Object.assign(FC,{defaultVisitor:g,convertValue:d,isVisitable:xl});function E(T,w,v=0){if(!y.isUndefined(T)){if(m(v),u.indexOf(T)!==-1)throw new Error("Circular reference detected in "+w.join("."));u.push(T),y.forEach(T,function(C,P){(!(y.isUndefined(C)||C===null)&&s.call(t,C,y.isString(P)?P.trim():P,w,h))===!0&&E(C,w?w.concat(P):[P],v+1)}),u.pop()}}if(!y.isObject(e))throw new TypeError("data must be an object");return E(e),t}function Wg(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,function(n){return t[n]})}function Ph(e,t){this._pairs=[],e&&Ra(e,this,t)}var Lh=Ph.prototype;Lh.append=function(t,r){this._pairs.push([t,r])};Lh.toString=function(t){let r=t?n=>t.call(this,n,Wg):Wg;return this._pairs.map(function(s){return r(s[0])+"="+r(s[1])},"").join("&")};function qC(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Fl(e,t,r){if(!t)return e;e=e||"";let n=y.isFunction(r)?{serialize:r}:r,s=y.getSafeProp(n,"encode")||qC,i=y.getSafeProp(n,"serialize"),a;if(i?a=i(t,n):a=y.isURLSearchParams(t)?t.toString():new Ph(t,n).toString(s),a){let o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var ya=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){y.forEach(this.handlers,function(n){n!==null&&t(n)})}},wa={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},jC=xN.URLSearchParams,yl="abcdefghijklmnopqrstuvwxyz",Jg="0123456789",Mh={DIGIT:Jg,ALPHA:yl,ALPHA_DIGIT:yl+yl.toUpperCase()+Jg},BC=(e=16,t=Mh.ALPHA_DIGIT)=>{let r="",{length:n}=t,s=new Uint32Array(e);AN.randomFillSync(s);for(let i=0;i<e;i++)r+=t[s[i]%n];return r},VC={isNode:!0,classes:{URLSearchParams:jC,FormData:_h,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Mh,generateString:BC,protocols:["http","https","file","data"]},ql=typeof window<"u"&&typeof document<"u",Sl=typeof navigator=="object"&&navigator||void 0,HC=ql&&(!Sl||["ReactNative","NativeScript","NS"].indexOf(Sl.product)<0),GC=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",$C=ql&&window.location.href||"http://localhost",WC=Object.freeze({__proto__:null,hasBrowserEnv:ql,hasStandardBrowserEnv:HC,hasStandardBrowserWebWorkerEnv:GC,navigator:Sl,origin:$C}),Ae={...WC,...VC};function JC(e,t){return Ra(e,new Ae.classes.URLSearchParams,{visitor:function(r,n,s,i){return Ae.isNode&&y.isBuffer(r)?(this.append(n,r.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}var Kg=Nh;function kh(e){if(e>Kg)throw new I("FormData field is too deeply nested ("+e+" levels). Max depth: "+Kg,I.ERR_FORM_DATA_DEPTH_EXCEEDED)}function KC(e){let t=[],r=/[^.[\]]+|\[([^.[\]]*)]/g,n;for(;(n=r.exec(e))!==null;)kh(t.length),t.push(n[0]==="[]"?"":n[1]||n[0]);return t}function YC(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 Uh(e){function t(r,n,s,i){kh(i);let a=r[i++];if(a==="__proto__")return!0;let o=Number.isFinite(+a),c=i>=r.length;return a=!a&&y.isArray(s)?s.length:a,c?(y.hasOwnProp(s,a)?s[a]=y.isArray(s[a])?s[a].concat(n):[s[a],n]:s[a]=n,!o):((!y.hasOwnProp(s,a)||!y.isObject(s[a]))&&(s[a]=[]),t(r,n,s[a],i)&&y.isArray(s[a])&&(s[a]=YC(s[a])),!o)}if(y.isFormData(e)&&y.isFunction(e.entries)){let r={};return y.forEachEntry(e,(n,s)=>{t(KC(n),s,r,0)}),r}return null}var Nn=(e,t)=>e!=null&&y.hasOwnProp(e,t)?e[t]:void 0;function zC(e,t,r){if(y.isString(e))try{return(t||JSON.parse)(e),y.trim(e)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(e)}var js={transitional:wa,adapter:["xhr","http","fetch"],transformRequest:[function(t,r){let n=r.getContentType()||"",s=n.indexOf("application/json")>-1,i=y.isObject(t);if(i&&y.isHTMLForm(t)&&(t=new FormData(t)),y.isFormData(t))return s?JSON.stringify(Uh(t)):t;if(y.isArrayBuffer(t)||y.isBuffer(t)||y.isStream(t)||y.isFile(t)||y.isBlob(t)||y.isReadableStream(t))return t;if(y.isArrayBufferView(t))return t.buffer;if(y.isURLSearchParams(t))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let o;if(i){let c=Nn(this,"formSerializer");if(n.indexOf("application/x-www-form-urlencoded")>-1)return JC(t,c).toString();if((o=y.isFileList(t))||n.indexOf("multipart/form-data")>-1){let l=Nn(this,"env"),u=l&&l.FormData;return Ra(o?{"files[]":t}:t,u&&new u,c)}}return i||s?(r.setContentType("application/json",!1),zC(t)):t}],transformResponse:[function(t){let r=Nn(this,"transitional")||js.transitional,n=r&&r.forcedJSONParsing,s=Nn(this,"responseType"),i=s==="json";if(y.isResponse(t)||y.isReadableStream(t))return t;if(t&&y.isString(t)&&(n&&!s||i)){let o=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(t,Nn(this,"parseReviver"))}catch(c){if(o)throw c.name==="SyntaxError"?I.from(c,I.ERR_BAD_RESPONSE,this,null,Nn(this,"response")):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ae.classes.FormData,Blob:Ae.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};y.forEach(["delete","get","head","post","put","patch","query"],e=>{js.headers[e]={}});function El(e,t){let r=this||js,n=t||r,s=Pe.from(n.headers),i=n.data;return y.forEach(e,function(o){i=o.call(r,i,s.normalize(),t?t.status:void 0)}),s.normalize(),i}function Fh(e){return!!(e&&e.__CANCEL__)}var dr=class extends I{constructor(t,r,n){super(t??"canceled",I.ERR_CANCELED,r,n),this.name="CanceledError",this.__CANCEL__=!0}};function Cn(e,t,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new I("Request failed with status code "+r.status,r.status>=400&&r.status<500?I.ERR_BAD_REQUEST:I.ERR_BAD_RESPONSE,r.config,r.request,r))}function XC(e){return typeof e!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function QC(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 ZC=/^https?:(?!\/\/)/i,eP=/[\t\n\r]/g;function tP(e){let t=0;for(;t<e.length&&e.charCodeAt(t)<=32;)t++;return e.slice(t)}function rP(e){return tP(e).replace(eP,"")}function nP(e){return e&&e.replace(/(^|&)([^=&]*=)?[^&]+/g,(t,r,n="")=>`${r}${n}${_a}`)}function sP(e){let t=e.replace(/^(https?:\/{0,2})[^/?#]*@/i,`$1${_a}@`),r=t.indexOf("#"),s=(r===-1?t:t.slice(0,r)).replace(/([?&][^=&#]*=)[^&#]*/g,`$1${_a}`);return r===-1?s:`${s}#${nP(t.slice(r+1))}`}function Yg(e,t){if(typeof e=="string"){let r=rP(e);if(ZC.test(r))throw new I(`Invalid URL ${JSON.stringify(sP(r))}: missing "//" after protocol`,I.ERR_INVALID_URL,t)}}function jl(e,t,r,n){Yg(t,n);let s=!XC(t);return e&&(s||r===!1)?(Yg(e,n),QC(e,t)):t}var iP={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function aP(e){try{return new URL(e)}catch{return null}}function oP(e){var t=(typeof e=="string"?aP(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)||iP[r]||0,!cP(n,s)))return"";var i=Il(r+"_proxy")||Il("all_proxy");return i&&i.indexOf("://")===-1&&(i=r+"://"+i),i}function cP(e,t){var r=Il("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 Il(e){return process.env[e.toLowerCase()]||process.env[e.toUpperCase()]||""}var ks="1.19.0";function qh(e){let t=/^([-+\w]{1,25}):(?:\/\/)?/.exec(e);return t&&t[1]||""}var lP=/^([^,;]+\/[^,;]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/;function uP(e,t,r){let n=r&&r.Blob||Ae.classes.Blob,s=qh(e);if(t===void 0&&n&&(t=!0),s==="data"){e=s.length?e.slice(s.length+1):e;let i=lP.exec(e);if(!i)throw new I("Invalid URL",I.ERR_INVALID_URL);let a=i[1],o=i[2],c=i[3]?"base64":"utf8",l=i[4],u="";a?u=o?a+o:a:o&&(u="text/plain"+o);let d=c==="base64"?Buffer.from(l,"base64"):Buffer.from(decodeURIComponent(l),c);if(t){if(!n)throw new I("Blob is not supported",I.ERR_NOT_SUPPORT);return new n([d],{type:u})}return d}throw new I("Unsupported protocol "+s,I.ERR_NOT_SUPPORT)}var dP=["content-type","content-length"];function jh(e,t,r){if(r!=="content-only"){e.set(t);return}Object.entries(t||{}).forEach(([n,s])=>{dP.includes(n.toLowerCase())&&e.set(n,s)})}var Tl=Symbol("internals"),Ea=class extends ut.Transform{constructor(t){t=y.toFlatObject(t,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(n,s)=>!y.isUndefined(s[n])),super({readableHighWaterMark:t.chunkSize});let r=this[Tl]={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[Tl];return r.onReadCallback&&r.onReadCallback(),super._read(t)}_transform(t,r,n){let s=this[Tl],i=s.maxRate,a=this.readableHighWaterMark,o=s.timeWindow,c=1e3/o,l=i/c,u=s.minChunkSize!==!1?Math.max(s.minChunkSize,l*.01):0,d=(f,g)=>{let h=Buffer.byteLength(f);s.bytesSeen+=h,s.bytes+=h,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 h=Buffer.byteLength(f),E=null,T=a,w,v=0;if(i){let A=Date.now();(!s.ts||(v=A-s.ts)>=o)&&(s.ts=A,w=l-s.bytes,s.bytes=w<0?-w:0,v=0),w=l-s.bytes}if(i){if(w<=0)return setTimeout(()=>{g(null,f)},o-v);w<T&&(T=w)}T&&h>T&&h-T>u&&(E=f.subarray(T),f=f.subarray(0,T)),d(f,E?()=>{process.nextTick(g,null,E)}:g)};m(t,function f(g,h){if(g)return n(g);h?m(h,f):n(null)})}},{asyncIterator:zg}=Symbol,Bh=async function*(e){e.stream?yield*e.stream():e.arrayBuffer?yield await e.arrayBuffer():e[zg]?yield*e[zg]():yield e},pP=Ae.ALPHABET.ALPHA_DIGIT+"-_",Us=typeof TextEncoder=="function"?new TextEncoder:new Ll.TextEncoder,Wr=`\r
|
|
18
|
+
`,mP=Us.encode(Wr),fP=2,Dl=class{constructor(t,r){let{escapeName:n}=this.constructor,s=y.isString(r),i=`Content-Disposition: form-data; name="${n(t)}"${!s&&r.name?`; filename="${n(r.name)}"`:""}${Wr}`;if(s)r=Us.encode(String(r).replace(/\r?\n|\r\n?/g,Wr));else{let a=String(r.type||"application/octet-stream").replace(/[\r\n]/g,"");i+=`Content-Type: ${a}${Wr}`}this.headers=Us.encode(i+Wr),this.contentLength=s?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+fP,this.name=t,this.value=r}async*encode(){yield this.headers;let{value:t}=this;y.isTypedArray(t)?yield t:yield*Bh(t),yield mP}static escapeName(t){return String(t).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},gP=(e,t,r)=>{let{tag:n="form-data-boundary",size:s=25,boundary:i=n+"-"+Ae.generateString(s,pP)}=r||{};if(!y.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=Us.encode("--"+i+Wr),o=Us.encode("--"+i+"--"+Wr),c=o.byteLength,l=Array.from(e.entries()).map(([d,m])=>{let f=new Dl(d,m);return c+=f.size,f});c+=a.byteLength*l.length,c=y.toFiniteNumber(c);let u={"Content-Type":`multipart/form-data; boundary=${i}`};return Number.isFinite(c)&&(u["Content-Length"]=c),t&&t(u),ut.Readable.from((async function*(){for(let d of l)yield a,yield*d.encode();yield o})())},Ol=class extends ut.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)}},Nl=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&&Ll.isDeepStrictEqual(g,r))return f}}let s=bh.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:l}=r;if(l!=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()},l))}),m}}s.once("close",o);let u=[s,r];return n?n.push(u):n=this.sessions[t]=[u],s}},hP=(e,t)=>y.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,_P=new Set(["localhost","0.0.0.0"]),Vh=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)},bl=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},yP=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(u=>u===""))return e;if(r.length===4){let u=r.map(bl);return u.some(d=>d===null||d<0||d>255)?e:u.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=bl(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 u=i-1,d=a;u>=0;u--,d>>=8)c[u]=d&255;let l=n.map(bl);return l.some(u=>u===null||u<0||u>255)?e:[...l,...c].join(".")},vl=e=>/^0{1,4}$/.test(e),EP=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(vl)&&a.every(vl)}let r=e.split(":");return r.length===8&&r.every(vl)},TP=e=>{if(e==="::1")return!0;let t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(t)return Vh(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},Xg=e=>e?_P.has(e)||Vh(e)||EP(e)?!0:TP(e):!1,bP={http:80,https:443,ws:80,wss:443,ftp:21},vP=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]},RP=/^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i,wP=/^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i,AP=e=>{if(typeof e!="string"||e.indexOf(":")===-1)return e;let t=e.match(RP);if(t)return t[1];let r=e.match(wP);if(r){let n=parseInt(r[1],16),s=parseInt(r[2],16);return`${n>>8}.${n&255}.${s>>8}.${s&255}`}return e},Qg=e=>{if(!e)return e;e.charAt(0)==="["&&e.charAt(e.length-1)==="]"&&(e=e.slice(1,-1));let t=e.replace(/\.+$/,""),r=yP(t);return r!==t?r:AP(t)};function xP(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)||bP[t.protocol.split(":",1)[0]]||0,s=Qg(t.hostname.toLowerCase());return r.split(/[\s,]+/).some(i=>{if(!i)return!1;if(i==="*")return!0;let[a,o]=vP(i);return a=Qg(a),!a||o&&o!==n?!1:(a.charAt(0)==="*"&&(a=a.slice(1)),a.charAt(0)==="."?s.endsWith(a):s===a||Xg(s)&&Xg(a))})}function SP(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 l=Date.now(),u=n[i];a||(a=l),r[s]=c,n[s]=l;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),l-a<t)return;let f=u&&l-u;return f?Math.round(m*1e3/f):void 0}}function IP(e,t){let r=0,n=1e3/t,s,i,a=(l,u=Date.now())=>{r=u,s=null,i&&(clearTimeout(i),i=null),e(...l)};return[(...l)=>{let u=Date.now(),d=u-r;d>=n?a(l,u):(s=l,i||(i=setTimeout(()=>{i=null,a(s)},n-d)))},()=>s&&a(s)]}var Ln=(e,t,r=3)=>{let n=0,s=SP(50,250);return IP(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),l=Math.max(0,c-n),u=s(l);n=Math.max(n,c);let d={loaded:c,total:o,progress:o?c/o:void 0,bytes:l,rate:u||void 0,estimated:u&&o?(o-c)/u:void 0,event:i,lengthComputable:o!=null,[t?"download":"upload"]:!0};e(d)},r)},Ta=(e,t)=>{let r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},ba=(e,t=y.asap)=>(...r)=>t(()=>e(...r)),Zg=e=>e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102,Hh=(e,t,r)=>t+2<r&&Zg(e.charCodeAt(t+1))&&Zg(e.charCodeAt(t+2)),eh=e=>e<=57?e-48:(e&223)-55,DP=e=>e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===43||e===47||e===45||e===95,OP=e=>e===9||e===10||e===12||e===13||e===32,NP=e=>{let t=Math.floor(e/4),r=e%4;return t*3+(r===2?1:r===3?2:0)},Gh=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)},CP=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&&Hh(e,i,t)&&(a=eh(e.charCodeAt(i+1))*16+eh(e.charCodeAt(i+2)),i+=2),!OP(a)){if(a===61){n++;continue}if(!DP(a)||n>0){s=!0;continue}r++}}return s||n>2||n>0&&(r+n)%4!==0||r%4===1?Gh(e):NP(r)},$h=(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 l=s.charCodeAt(o);if(l===37&&Hh(s,o,c))a+=1,o+=2;else if(l<128)a+=1;else if(l<2048)a+=2;else if(l>=55296&&l<=56319&&o+1<c){let u=s.charCodeAt(o+1);u>=56320&&u<=57343?(a+=4,o++):a+=3}else a+=3}return a};function PP(e){let t=typeof e=="string"?e.indexOf("#"):-1;return $h(t===-1?e:e.slice(0,t),CP)}function LP(e){return $h(e,Gh)}var th={flush:Dt.constants.Z_SYNC_FLUSH,finishFlush:Dt.constants.Z_SYNC_FLUSH},MP={flush:Dt.constants.BROTLI_OPERATION_FLUSH,finishFlush:Dt.constants.BROTLI_OPERATION_FLUSH},kP={flush:Dt.constants.ZSTD_e_flush,finishFlush:Dt.constants.ZSTD_e_flush},Wh=y.isFunction(Dt.createBrotliDecompress),Jh=y.isFunction(Dt.createZstdDecompress),Kh="gzip, compress, deflate"+(Wh?", br":""),UP=Kh+(Jh?", zstd":""),rh=typeof process<"u"&&process.nextTick?process.nextTick.bind(process):y.asap,{http:FP,https:qP}=SN,Bl=/https:?/,nh=Symbol("axios.http.socketListener"),da=Symbol("axios.http.currentReq"),Yh=Symbol("axios.http.installedTunnel"),jP=new Map,sh=new WeakMap,ih={22:21,24:5};function BP(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:ih[t]!=null&&r>=ih[t]}function VP(e,t=process.versions&&process.versions.node){if(!BP(t))return!1;let r=e&&e.options;return!!(r&&y.hasOwnProp(r,"proxyEnv")&&r.proxyEnv!=null)}function HP(e,t,r){return Bl.test(e.protocol)?r||Th.globalAgent:t||Eh.globalAgent}function GP(e,t){let r=e.protocol+"//"+e.hostname+":"+(e.port||"")+"#"+(e.auth||""),n=t?sh.get(t)||sh.set(t,new Map).get(t):jP,s=n.get(r);if(s)return s;let i=t&&t.options?{...t.options,...e}:e;if(s=new yh(i),t&&t.options){let a={...t.options},o=s.callback;s.callback=function(l,u){return o.call(this,l,{...a,...u})}}return s[Yh]=!0,n.set(r,s),s}var ah=Ae.protocols.map(e=>e+":"),oh=e=>{if(!y.isString(e))return e;try{return decodeURIComponent(e)}catch{return e}},ch=(e,[t,r])=>(e.on("end",r).on("error",r),t),$P=new Nl;function WP(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 JP(e,t){e&&Object.keys(e).forEach(r=>{t.has(r.toLowerCase())&&delete e[r]})}function KP(e,t){if(!t)return!1;try{return new URL(t.url).origin===new URL(e.href).origin}catch{return!1}}function zh(e,t,r,n,s,i){let a=t,o=HP(e,i,s);if(!a&&a!==!1&&!VP(o)){let c=oP(r);c&&(xP(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[Yh]&&(e.agent=void 0),a){let c=a instanceof URL,l=g=>c||y.hasOwnProp(a,g)?a[g]:void 0,u=l("username"),d=l("password"),m=y.hasOwnProp(a,"auth")?a.auth:void 0;if(u&&(m=(u||"")+":"+(d||"")),m){let g=typeof m=="object",h=g&&y.hasOwnProp(m,"username")?m.username:void 0,E=g&&y.hasOwnProp(m,"password")?m.password:void 0;if(!!(h||E))m=(h||"")+":"+(E||"");else if(g)throw new I("Invalid proxy authorization",I.ERR_BAD_OPTION,{proxy:a})}if(Bl.test(e.protocol)){if(!(s instanceof yh)){let g=l("hostname")||l("host"),h=l("port"),E=l("protocol"),T=E?E.includes(":")?E:`${E}:`:"http:",w=g&&g.includes(":")&&!g.startsWith("[")?`[${g}]`:g,v=new URL(`${T}//${w}${h?":"+h:""}`),A={protocol:v.protocol,hostname:v.hostname.replace(/^\[|\]$/g,""),port:v.port,auth:m&&typeof m=="string"?m:void 0};v.protocol==="https:"&&(A.ALPNProtocols=["http/1.1"]);let C=GP(A,s);e.agent=C,e.agents&&(e.agents.https=C)}}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 h=l("hostname")||l("host");e.hostname=h,e.host=h,e.port=l("port"),e.path=r;let E=l("protocol");E&&(e.protocol=E.includes(":")?E:`${E}:`)}}e.beforeRedirects.proxy=function(l){zh(l,t,l.href,!0,s,i)}}var YP=typeof process<"u"&&y.kindOf(process)==="process",zP=e=>new Promise((t,r)=>{let n,s,i=(c,l)=>{s||(s=!0,n&&n(c,l))},a=c=>{i(c),t(c)},o=c=>{i(c,!0),r(c)};e(a,o,c=>n=c).catch(o)}),XP=({address:e,family:t})=>{if(!y.isString(e))throw TypeError("address must be a string");return{address:e,family:t||(e.indexOf(".")<0?6:4)}},lh=(e,t)=>XP(y.isObject(e)?e:{address:e,family:t}),QP={request(e,t){let r=e.protocol+"//"+e.hostname+":"+(e.port||(e.protocol==="https:"?443:80)),{http2Options:n,headers:s}=e,i=$P.getSession(r,n),{HTTP2_HEADER_SCHEME:a,HTTP2_HEADER_METHOD:o,HTTP2_HEADER_PATH:c,HTTP2_HEADER_STATUS:l}=bh.constants,u={[a]:e.protocol.replace(":",""),[o]:e.method,[c]:e.path};y.forEach(s,(m,f)=>{f.charAt(0)!==":"&&(u[f]=m)});let d=i.request(u);return d.once("response",m=>{let f=d;m=Object.assign({},m);let g=m[l];delete m[l],f.headers=m,f.statusCode=+g,t(f)}),d}},ZP=YP&&function(t){return zP(async function(n,s,i){let a=U=>y.getSafeProp(t,U),o=a("transitional")||wa,c=a("data"),l=a("lookup"),u=a("family"),d=a("httpVersion");d===void 0&&(d=1);let m=a("http2Options"),f=a("httpAgent"),g=a("httpsAgent"),h=a("proxy"),E=a("responseType"),T=a("responseEncoding"),w=a("socketPath"),v=a("method").toUpperCase(),A=a("maxRedirects"),C=a("maxBodyLength"),P=a("maxContentLength"),L=a("decompress"),W,Z=!1,V,Y;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 ge=d===2;if(l){let U=hP(l,k=>y.isArray(k)?k:[k]);l=(k,oe,Re)=>{U(k,oe,(re,je,Ke)=>{if(re)return Re(re);let Ce=y.isArray(je)?je.map(dn=>lh(dn)):[lh(je,Ke)];oe.all?Re(re,Ce):Re(re,Ce[0].address,Ce[0].family)})}}let ee=new IN.EventEmitter;function te(U){try{ee.emit("abort",!U||U.type?new dr(null,t,V):U)}catch{}}function pe(){Y&&(clearTimeout(Y),Y=null)}function St(){let U=a("timeout"),k=U?"timeout of "+U+"ms exceeded":"timeout exceeded",oe=a("timeoutErrorMessage");return oe&&(k=oe),new I(k,o.clarifyTimeoutError?I.ETIMEDOUT:I.ECONNABORTED,t,V)}ee.once("abort",s);let rr=()=>{pe(),t.cancelToken&&t.cancelToken.unsubscribe(te),t.signal&&t.signal.removeEventListener("abort",te),ee.removeAllListeners()};(t.cancelToken||t.signal)&&(t.cancelToken&&t.cancelToken.subscribe(te),t.signal&&(t.signal.aborted?te():t.signal.addEventListener("abort",te))),i((U,k)=>{if(W=!0,pe(),k){Z=!0,rr();return}let{data:oe}=U;if(oe instanceof ut.Readable||oe instanceof ut.Duplex){let Re=ut.finished(oe,()=>{Re(),rr()})}else rr()});let nr=jl(a("baseURL"),a("url"),a("allowAbsoluteUrls"),t),ls=w?"http://localhost":Ae.hasBrowserEnv?Ae.origin:void 0,Te=new URL(nr,ls),ve=Te.protocol||ah[0];if(ve==="data:"){if(P>-1){let k=String(a("url")||nr||"");if(LP(k)>P)return s(new I("maxContentLength size of "+P+" exceeded",I.ERR_BAD_RESPONSE,t))}let U;if(v!=="GET")return Cn(n,s,{status:405,statusText:"method not allowed",headers:{},config:t});try{U=uP(a("url"),E==="blob",{Blob:t.env&&t.env.Blob})}catch(k){throw I.from(k,I.ERR_BAD_REQUEST,t)}return E==="text"?(U=U.toString(T),(!T||T==="utf8")&&(U=y.stripBOM(U))):E==="stream"&&(U=ut.Readable.from(U)),Cn(n,s,{data:U,status:200,statusText:"OK",headers:new Pe,config:t})}if(ah.indexOf(ve)===-1)return s(new I("Unsupported protocol "+ve,I.ERR_BAD_REQUEST,t));let Ne=Pe.from(t.headers).normalize();Ne.set("User-Agent","axios/"+ks,!1);let{onUploadProgress:Gt,onDownloadProgress:sr}=t,Lr=t.maxRate,de,$e;if(y.isSpecCompliantForm(c)){let U=Ne.getContentType(/boundary=([-_\w\d]{10,70})/i);c=gP(c,k=>{Ne.set(k)},{tag:`axios-${ks}-boundary`,boundary:U&&U[1]||void 0})}else if(y.isFormData(c)&&y.isFunction(c.getHeaders)&&c.getHeaders!==Object.prototype.getHeaders){if(jh(Ne,c.getHeaders(),a("formDataHeaderPolicy")),!Ne.hasContentLength())try{let U=await Ll.promisify(c.getLength).call(c);Number.isFinite(U)&&U>=0&&Ne.setContentLength(U)}catch{}}else if(y.isBlob(c)||y.isFile(c))c.size&&Ne.setContentType(c.type||"application/octet-stream"),Ne.setContentLength(c.size||0),c=ut.Readable.from(Bh(c));else if(c&&!y.isStream(c)){if(!Buffer.isBuffer(c))if(y.isArrayBuffer(c))c=Buffer.from(new Uint8Array(c));else if(y.isString(c))c=Buffer.from(c,"utf-8");else return s(new I("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",I.ERR_BAD_REQUEST,t));if(Ne.setContentLength(c.length,!1),C>-1&&c.length>C)return s(new I("Request body larger than maxBodyLength limit",I.ERR_BAD_REQUEST,t))}let ln=y.toFiniteNumber(Ne.getContentLength());y.isArray(Lr)?(de=Lr[0],$e=Lr[1]):de=$e=Lr,c&&(Gt||de)&&(y.isStream(c)||(c=ut.Readable.from(c,{objectMode:!1})),c=ut.pipeline([c,new Ea({maxRate:y.toFiniteNumber(de)})],y.noop),Gt&&c.on("progress",ch(c,Ta(ln,Ln(ba(Gt,rh),!1,3)))));let $t,us=a("auth");if(us){let U=y.getSafeProp(us,"username")||"",k=y.getSafeProp(us,"password")||"";$t=U+":"+k}if(!$t&&(Te.username||Te.password)){let U=oh(Te.username),k=oh(Te.password);$t=U+":"+k}$t&&Ne.delete("authorization");let ds;try{ds=Fl(Te.pathname+Te.search,a("params"),a("paramsSerializer")).replace(/^\?/,"")}catch(U){return s(I.from(U,I.ERR_BAD_REQUEST,t,null,null,{url:a("url"),exists:!0}))}Ne.set("Accept-Encoding",y.hasOwnProp(o,"advertiseZstdAcceptEncoding")&&o.advertiseZstdAcceptEncoding===!0?UP:Kh,!1);let me=Object.assign(Object.create(null),{path:ds,method:v,headers:Ul(Ne),agents:{http:f,https:g},auth:$t,protocol:ve,family:u,beforeRedirect:WP,beforeRedirects:Object.create(null),http2Options:m});if(!y.isUndefined(l)&&(me.lookup=l),w){if(typeof w!="string")return s(new I("socketPath must be a string",I.ERR_BAD_OPTION_VALUE,t));let U=a("allowedSocketPaths");if(U!=null){let k=Array.isArray(U)?U:[U],oe=Bg.resolve(w);if(!k.some(re=>typeof re=="string"&&Bg.resolve(re)===oe))return s(new I(`socketPath "${w}" is not permitted by allowedSocketPaths`,I.ERR_BAD_OPTION_VALUE,t))}me.socketPath=w}else me.hostname=Te.hostname.startsWith("[")?Te.hostname.slice(1,-1):Te.hostname,me.port=Te.port,zh(me,h,ve+"//"+Te.hostname+(Te.port?":"+Te.port:"")+me.path,!1,g,f);let yr,un=!1,It=!1,z=Bl.test(me.protocol);if(me.agent==null&&(me.agent=z?g:f),ge)yr=QP;else{let U=a("transport");if(U)yr=U;else if(A===0)yr=z?Th:Eh,un=!0;else{It=!0,me.sensitiveHeaders=[],A&&(me.maxRedirects=A);let k=a("beforeRedirect");if(k&&(me.beforeRedirects.config=k),$t){let Re=Te.origin,re=$t;me.beforeRedirects.auth=function(Ke){try{new URL(Ke.href).origin===Re&&(Ke.auth=re)}catch{}}}let oe=a("sensitiveHeaders");if(oe!=null){if(!y.isArray(oe))return s(new I("sensitiveHeaders must be an array of strings",I.ERR_BAD_OPTION_VALUE,t));let Re=new Set;for(let re of oe){if(!y.isString(re))return s(new I("sensitiveHeaders must be an array of strings",I.ERR_BAD_OPTION_VALUE,t));Re.add(re.toLowerCase())}Re.size&&(me.sensitiveHeaders=Array.from(Re),me.beforeRedirects.sensitiveHeaders=function(je,Ke){KP(je,Ke)||JP(je.headers,Re)})}yr=z?qP:FP}}C>-1?me.maxBodyLength=C:me.maxBodyLength=1/0,me.insecureHTTPParser=!!a("insecureHTTPParser"),V=yr.request(me,function(k){if(pe(),V.destroyed)return;let oe=[k],Re=y.toFiniteNumber(k.headers["content-length"]);if(sr||$e){let Ce=new Ea({maxRate:y.toFiniteNumber($e)});sr&&Ce.on("progress",ch(Ce,Ta(Re,Ln(ba(sr,rh),!0,3)))),oe.push(Ce)}let re=k,je=k.req||V;if(L!==!1&&k.headers["content-encoding"])switch((v==="HEAD"||k.statusCode===204)&&delete k.headers["content-encoding"],(k.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":oe.push(Dt.createUnzip(th)),delete k.headers["content-encoding"];break;case"deflate":oe.push(new Ol),oe.push(Dt.createUnzip(th)),delete k.headers["content-encoding"];break;case"br":Wh&&(oe.push(Dt.createBrotliDecompress(MP)),delete k.headers["content-encoding"]);break;case"zstd":Jh&&(oe.push(Dt.createZstdDecompress(kP)),delete k.headers["content-encoding"]);break}re=oe.length>1?ut.pipeline(oe,y.noop):oe[0];let Ke={status:k.statusCode,statusText:k.statusMessage,headers:new Pe(k.headers),config:t,request:je};if(E==="stream"){if(P>-1){let Ce=P,dn=re;async function*ps(){let Be=0;for await(let Zd of dn){if(Be+=Zd.length,Be>Ce)throw new I("maxContentLength size of "+Ce+" exceeded",I.ERR_BAD_RESPONSE,t,je);yield Zd}}re=ut.Readable.from(ps(),{objectMode:!1})}Ke.data=re,Cn(n,s,Ke)}else{let Ce=[],dn=0;re.on("data",function(Be){Ce.push(Be),dn+=Be.length,P>-1&&dn>P&&(Z=!0,re.destroy(),te(new I("maxContentLength size of "+P+" exceeded",I.ERR_BAD_RESPONSE,t,je)))}),re.on("aborted",function(){if(Z)return;let Be=new I("stream has been aborted",I.ERR_BAD_RESPONSE,t,je,Ke);re.destroy(Be),s(Be)}),re.on("error",function(Be){Z||s(I.from(Be,null,t,je,Ke))}),re.on("end",function(){try{let Be=Ce.length===1?Ce[0]:Buffer.concat(Ce);E!=="arraybuffer"&&(Be=Be.toString(T),(!T||T==="utf8")&&(Be=y.stripBOM(Be))),Ke.data=Be}catch(Be){return s(I.from(Be,null,t,Ke.request,Ke))}Cn(n,s,Ke)})}ee.once("abort",Ce=>{re.destroyed||(re.emit("error",Ce),re.destroy())})}),ee.once("abort",U=>{V.close?V.close():V.destroy(U)}),V.on("error",function(k){s(I.from(k,null,t,V))});let We=new Set;if(V.on("socket",function(k){typeof k.setKeepAlive=="function"&&k.setKeepAlive(!0,1e3*60),k[nh]||(k.on("error",function(Re){let re=k[da];re&&!re.destroyed&&re.destroy(Re)}),k[nh]=!0),k[da]=V,We.add(k)}),V.once("close",function(){pe();for(let k of We)k[da]===V&&(k[da]=null);We.clear()}),a("timeout")){let U=parseInt(a("timeout"),10);if(Number.isNaN(U)){te(new I("error trying to parse `config.timeout` to int",I.ERR_BAD_OPTION_VALUE,t,V));return}let k=function(){W||te(St())};un&&U>0&&(Y=setTimeout(k,U)),V.setTimeout(U,k)}else V.setTimeout(0);if(y.isStream(c)){let U=!1,k=!1;c.on("end",()=>{U=!0}),c.once("error",Re=>{k=!0,V.destroy(Re)}),c.on("close",()=>{!U&&!k&&te(new dr("Request stream has been aborted",t,V))});let oe=c;if(C>-1&&!It){let Re=C,re=0;oe=ut.pipeline([c,new ut.Transform({transform(je,Ke,Ce){if(re+=je.length,re>Re)return Ce(new I("Request body larger than maxBodyLength limit",I.ERR_BAD_REQUEST,t,V));Ce(null,je)}})],y.noop),oe.on("error",je=>{V.destroyed||V.destroy(je)})}oe.pipe(V)}else c&&V.write(c),V.end()})},eL=Ae.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Ae.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Ae.origin),Ae.navigator&&/(msie|trident)/i.test(Ae.navigator.userAgent)):()=>!0,tL=Ae.hasStandardBrowserEnv?{write(e,t,r,n,s,i,a){if(typeof document>"u")return;let o=[`${e}=${encodeURIComponent(t)}`];y.isNumber(r)&&o.push(`expires=${new Date(r).toUTCString()}`),y.isString(n)&&o.push(`path=${n}`),y.isString(s)&&o.push(`domain=${s}`),i===!0&&o.push("secure"),y.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(){}},uh=e=>e instanceof Pe?{...e}:e,rL=e=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(e).concat(Object.getOwnPropertySymbols(e).filter(t=>Object.getOwnPropertyDescriptor(e,t).enumerable)):Object.keys(e);function Yr(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(u,d,m,f){return y.isPlainObject(u)&&y.isPlainObject(d)?y.merge.call({caseless:f},u,d):y.isPlainObject(d)?y.merge({},d):y.isArray(d)?d.slice():d}function s(u,d,m,f){if(y.isUndefined(d)){if(!y.isUndefined(u))return n(void 0,u,m,f)}else return n(u,d,m,f)}function i(u,d){if(!y.isUndefined(d))return n(void 0,d)}function a(u,d){if(y.isUndefined(d)){if(!y.isUndefined(u))return n(void 0,u)}else return n(void 0,d)}function o(u){let d=y.hasOwnProp(t,"transitional")?t.transitional:void 0;if(!y.isUndefined(d))if(y.isPlainObject(d)){if(y.hasOwnProp(d,u))return d[u]}else return;let m=y.hasOwnProp(e,"transitional")?e.transitional:void 0;if(y.isPlainObject(m)&&y.hasOwnProp(m,u))return m[u]}function c(u,d,m){if(y.hasOwnProp(t,m))return n(u,d);if(y.hasOwnProp(e,m))return n(void 0,u)}let l={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:(u,d,m)=>s(uh(u),uh(d),m,!0)};return y.forEach(rL({...e,...t}),function(d){if(d==="__proto__"||d==="constructor"||d==="prototype")return;let m=y.hasOwnProp(l,d)?l[d]:s,f=y.hasOwnProp(e,d)?e[d]:void 0,g=y.hasOwnProp(t,d)?t[d]:void 0,h=m(f,g,d);y.isUndefined(h)&&m!==c||(r[d]=h)}),y.hasOwnProp(t,"validateStatus")&&y.isUndefined(t.validateStatus)&&o("validateStatusUndefinedResolves")===!1&&(y.hasOwnProp(e,"validateStatus")?r.validateStatus=n(void 0,e.validateStatus):delete r.validateStatus),r}var nL=e=>encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,(t,r)=>String.fromCharCode(parseInt(r,16)));function Xh(e){let t=Yr({},e),r=m=>y.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"),l=r("baseURL"),u=r("allowAbsoluteUrls"),d=r("url");if(t.headers=o=Pe.from(o),t.url=Fl(jl(l,d,u,t),r("params"),r("paramsSerializer")),c){let m=y.getSafeProp(c,"username")||"",f=y.getSafeProp(c,"password")||"";try{o.set("Authorization","Basic "+btoa(m+":"+(f?nL(f):"")))}catch(g){throw I.from(g,I.ERR_BAD_OPTION_VALUE,e)}}if(y.isFormData(n)&&(Ae.hasStandardBrowserEnv||Ae.hasStandardBrowserWebWorkerEnv||y.isReactNative(n)?o.setContentType(void 0):y.isFunction(n.getHeaders)&&jh(o,n.getHeaders(),r("formDataHeaderPolicy"))),Ae.hasStandardBrowserEnv&&(y.isFunction(s)&&(s=s(t)),s===!0||s==null&&eL(t.url))){let f=i&&a&&tL.read(a);f&&o.set(i,f)}return t}var sL=typeof XMLHttpRequest<"u",iL=sL&&function(e){return new Promise(function(r,n){let s=Xh(e),i=s.data,a=Pe.from(s.headers).normalize(),{responseType:o,onUploadProgress:c,onDownloadProgress:l}=s,u,d,m,f,g;function h(){f&&f(),g&&g(),s.cancelToken&&s.cancelToken.unsubscribe(u),s.signal&&s.signal.removeEventListener("abort",u)}let E=new XMLHttpRequest;E.open(s.method.toUpperCase(),s.url,!0),E.timeout=s.timeout;function T(){if(!E)return;let v=Pe.from("getAllResponseHeaders"in E&&E.getAllResponseHeaders()),C={data:!o||o==="text"||o==="json"?E.responseText:E.response,status:E.status,statusText:E.statusText,headers:v,config:e,request:E};Cn(function(L){r(L),h()},function(L){n(L),h()},C),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 I("Request aborted",I.ECONNABORTED,e,E)),h(),E=null)},E.onerror=function(A){let C=A&&A.message?A.message:"Network Error",P=new I(C,I.ERR_NETWORK,e,E);P.event=A||null,n(P),h(),E=null},E.ontimeout=function(){let A=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded",C=s.transitional||wa;s.timeoutErrorMessage&&(A=s.timeoutErrorMessage),n(new I(A,C.clarifyTimeoutError?I.ETIMEDOUT:I.ECONNABORTED,e,E)),h(),E=null},i===void 0&&a.setContentType(null),"setRequestHeader"in E&&y.forEach(Ul(a),function(A,C){E.setRequestHeader(C,A)}),y.isUndefined(s.withCredentials)||(E.withCredentials=!!s.withCredentials),o&&o!=="json"&&(E.responseType=s.responseType),l&&([m,g]=Ln(l,!0),E.addEventListener("progress",m)),c&&E.upload&&([d,f]=Ln(c),E.upload.addEventListener("progress",d),E.upload.addEventListener("loadend",f)),(s.cancelToken||s.signal)&&(u=v=>{E&&(n(!v||v.type?new dr(null,e,E):v),E.abort(),h(),E=null)},s.cancelToken&&s.cancelToken.subscribe(u),s.signal&&(s.signal.aborted?u():s.signal.addEventListener("abort",u)));let w=qh(s.url);if(w&&!Ae.protocols.includes(w)){n(new I("Unsupported protocol "+w+":",I.ERR_BAD_REQUEST,e)),h();return}E.send(i||null)})},aL=(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 l=c instanceof Error?c:this.reason;r.abort(l instanceof I?l:new dr(l instanceof Error?l.message:l))}},i=t&&setTimeout(()=>{i=null,s(new I(`timeout of ${t}ms exceeded`,I.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=()=>y.asap(a),o},oL=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},cL=async function*(e,t){for await(let r of lL(e))yield*oL(r,t)},lL=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()}},dh=(e,t,r,n)=>{let s=cL(e,t),i=0,a,o=c=>{a||(a=!0,n&&n(c))};return new ReadableStream({async pull(c){try{let{done:l,value:u}=await s.next();if(l){o(),c.close();return}let d=u.byteLength;if(r){let m=i+=d;r(m)}c.enqueue(new Uint8Array(u))}catch(l){throw o(l),l}},cancel(c){return o(c),s.return()}},{highWaterMark:2})},ph=64*1024,{isFunction:pa}=y,uL=e=>encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,(t,r)=>String.fromCharCode(parseInt(r,16))),mh=e=>{if(!y.isString(e))return e;try{return decodeURIComponent(e)}catch{return e}},fh=(e,...t)=>{try{return!!e(...t)}catch{return!1}},dL=e=>{let t=e.indexOf("://"),r=e;return t!==-1&&(r=r.slice(t+3)),r.includes("@")||r.includes(":")},pL=e=>{let t=y.global!==void 0&&y.global!==null?y.global:globalThis,{ReadableStream:r,TextEncoder:n}=t;e=y.merge.call({skipUndefined:!0},{Request:t.Request,Response:t.Response},e);let{fetch:s,Request:i,Response:a}=e,o=s?pa(s):typeof fetch=="function",c=pa(i),l=pa(a);if(!o)return!1;let u=o&&pa(r),d=o&&(typeof n=="function"?(T=>w=>T.encode(w))(new n):async T=>new Uint8Array(await new i(T).arrayBuffer())),m=c&&u&&fh(()=>{let T=!1,w=new i(Ae.origin,{body:new r,method:"POST",get duplex(){return T=!0,"half"}}),v=w.headers.has("Content-Type");return w.body!=null&&w.body.cancel(),T&&!v}),f=l&&u&&fh(()=>y.isReadableStream(new a("").body)),g={stream:f&&(T=>T.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(T=>{!g[T]&&(g[T]=(w,v)=>{let A=w&&w[T];if(A)return A.call(w);throw new I(`Response type '${T}' is not supported`,I.ERR_NOT_SUPPORT,v)})});let h=async T=>{if(T==null)return 0;if(y.isBlob(T))return T.size;if(y.isSpecCompliantForm(T))return(await new i(Ae.origin,{method:"POST",body:T}).arrayBuffer()).byteLength;if(y.isArrayBufferView(T)||y.isArrayBuffer(T))return T.byteLength;if(y.isURLSearchParams(T)&&(T=T+""),y.isString(T))return(await d(T)).byteLength},E=async(T,w)=>{let v=y.toFiniteNumber(T.getContentLength());return v??h(w)};return async T=>{let{url:w,method:v,data:A,signal:C,cancelToken:P,timeout:L,onDownloadProgress:W,onUploadProgress:Z,responseType:V,headers:Y,withCredentials:ge="same-origin",fetchOptions:ee,maxContentLength:te,maxBodyLength:pe}=Xh(T),St=y.isNumber(te)&&te>-1,rr=y.isNumber(pe)&&pe>-1,nr=de=>y.hasOwnProp(T,de)?T[de]:void 0,ls=s||fetch;V=V?(V+"").toLowerCase():"text";let Te=aL([C,P&&P.toAbortSignal()],L),ve=null,Ne=Te&&Te.unsubscribe&&(()=>{Te.unsubscribe()}),Gt,sr=null,Lr=()=>new I("Request body larger than maxBodyLength limit",I.ERR_BAD_REQUEST,T,ve);try{let de,$e=nr("auth");if($e){let z=y.getSafeProp($e,"username")||"",We=y.getSafeProp($e,"password")||"";de={username:z,password:We}}if(dL(w)){let z=new URL(w,Ae.origin);if(!de&&(z.username||z.password)){let We=mh(z.username),U=mh(z.password);de={username:We,password:U}}(z.username||z.password)&&(z.username="",z.password="",w=z.href)}if(de&&(Y.delete("authorization"),Y.set("Authorization","Basic "+btoa(uL((de.username||"")+":"+(de.password||""))))),St&&typeof w=="string"&&w.startsWith("data:")&&PP(w)>te)throw new I("maxContentLength size of "+te+" exceeded",I.ERR_BAD_RESPONSE,T,ve);if(rr&&v!=="get"&&v!=="head"){let z=await h(A);if(typeof z=="number"&&isFinite(z)&&(Gt=z,z>pe))throw Lr()}let ln=rr&&(y.isReadableStream(A)||y.isStream(A)),$t=(z,We,U)=>dh(z,ph,k=>{if(rr&&k>pe)throw sr=Lr();We&&We(k)},U);if(m&&v!=="get"&&v!=="head"&&(Z||ln)){if(Gt=Gt??await E(Y,A),Gt!==0||ln){let z=new i(w,{method:"POST",body:A,duplex:"half"}),We;if(y.isFormData(A)&&(We=z.headers.get("content-type"))&&Y.setContentType(We),z.body){let[U,k]=Z&&Ta(Gt,Ln(ba(Z)))||[];A=$t(z.body,U,k)}}}else if(ln&&!c&&u&&v!=="get"&&v!=="head")A=$t(A);else if(ln&&c&&!m&&v!=="get"&&v!=="head")throw new I("Stream request bodies are not supported by the current fetch implementation",I.ERR_NOT_SUPPORT,T,ve);y.isString(ge)||(ge=ge?"include":"omit");let us=c&&"credentials"in i.prototype;if(y.isFormData(A)){let z=Y.getContentType();z&&/^multipart\/form-data/i.test(z)&&!/boundary=/i.test(z)&&Y.delete("content-type")}Y.set("User-Agent","axios/"+ks,!1);let ds={...ee,signal:Te,method:v.toUpperCase(),headers:Ul(Y.normalize()),body:A,duplex:"half",credentials:us?ge:void 0};ve=c&&new i(w,ds);let me=await(c?ls(ve,ee):ls(w,ds)),yr=Pe.from(me.headers);if(St){let z=y.toFiniteNumber(yr.getContentLength());if(z!=null&&z>te)throw new I("maxContentLength size of "+te+" exceeded",I.ERR_BAD_RESPONSE,T,ve)}let un=f&&(V==="stream"||V==="response");if(f&&me.body&&(W||St||un&&Ne)){let z={};["status","statusText","headers"].forEach(re=>{z[re]=me[re]});let We=y.toFiniteNumber(yr.getContentLength()),[U,k]=W&&Ta(We,Ln(ba(W),!0))||[],oe=0,Re=re=>{if(St&&(oe=re,oe>te))throw new I("maxContentLength size of "+te+" exceeded",I.ERR_BAD_RESPONSE,T,ve);U&&U(re)};me=new a(dh(me.body,ph,Re,()=>{k&&k(),Ne&&Ne()}),z)}V=V||"text";let It=await g[y.findKey(g,V)||"text"](me,T);if(St&&!f&&!un){let z;if(It!=null&&(typeof It.byteLength=="number"?z=It.byteLength:typeof It.size=="number"?z=It.size:typeof It=="string"&&(z=typeof n=="function"?new n().encode(It).byteLength:It.length)),typeof z=="number"&&z>te)throw new I("maxContentLength size of "+te+" exceeded",I.ERR_BAD_RESPONSE,T,ve)}return!un&&Ne&&Ne(),await new Promise((z,We)=>{Cn(z,We,{data:It,headers:Pe.from(me.headers),status:me.status,statusText:me.statusText,config:T,request:ve})})}catch(de){if(Ne&&Ne(),Te&&Te.aborted&&Te.reason instanceof I){let $e=Te.reason;throw $e.config=T,ve&&($e.request=ve),de!==$e&&Object.defineProperty($e,"cause",{__proto__:null,value:de,writable:!0,enumerable:!1,configurable:!0}),$e}if(sr)throw ve&&!sr.request&&(sr.request=ve),sr;if(de instanceof I)throw ve&&!de.request&&(de.request=ve),de;if(de&&de.name==="TypeError"&&/Load failed|fetch/i.test(de.message)){let $e=new I("Network Error",I.ERR_NETWORK,T,ve,de&&de.response);throw Object.defineProperty($e,"cause",{__proto__:null,value:de.cause||de,writable:!0,enumerable:!1,configurable:!0}),$e}throw I.from(de,de&&de.code,T,ve,de&&de.response)}}},mL=new Map,Qh=e=>{let t=e&&e.env||{},{fetch:r,Request:n,Response:s}=t,i=[n,s,r],a=i.length,o=a,c,l,u=mL;for(;o--;)c=i[o],l=u.get(c),l===void 0&&u.set(c,l=o?new Map:pL(t)),u=l;return l};Qh();var Vl={http:ZP,xhr:iL,fetch:{get:Qh}};y.forEach(Vl,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{__proto__:null,value:t})}catch{}Object.defineProperty(e,"adapterName",{__proto__:null,value:t})}});var gh=e=>`- ${e}`,fL=e=>y.isFunction(e)||e===null||e===!1;function gL(e,t){e=y.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,!fL(n)&&(s=Vl[(o=String(n)).toLowerCase()],s===void 0))throw new I(`Unknown adapter '${o}'`);if(s&&(y.isFunction(s)||(s=s.get(t))))break;i[o||"#"+a]=s}if(!s){let a=Object.entries(i).map(([c,l])=>`adapter ${c} `+(l===!1?"is not supported by the environment":"is not available in the build")),o=r?a.length>1?`since :
|
|
19
|
+
`+a.map(gh).join(`
|
|
20
|
+
`):" "+gh(a[0]):"as no adapter specified";throw new I("There is no suitable adapter to dispatch the request "+o,I.ERR_NOT_SUPPORT)}return s}var Zh={getAdapter:gL,adapters:Vl};function Rl(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new dr(null,e)}function wl(e){return Rl(e),e.headers=Pe.from(e.headers),e.data=El.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Zh.getAdapter(e.adapter||js.adapter,e)(e).then(function(n){Rl(e),e.response=n;try{n.data=El.call(e,e.transformResponse,n)}finally{delete e.response}return n.headers=Pe.from(n.headers),n},function(n){if(!Fh(n)&&(Rl(e),n&&n.response)){e.response=n.response;try{n.response.data=El.call(e,e.transformResponse,n.response)}finally{delete e.response}n.response.headers=Pe.from(n.response.headers)}return Promise.reject(n)})}var Aa={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Aa[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});var hh={};Aa.transitional=function(t,r,n){function s(i,a){return"[Axios v"+ks+"] Transitional option '"+i+"'"+a+(n?". "+n:"")}return(i,a,o)=>{if(t===!1)throw new I(s(a," has been removed"+(r?" in "+r:"")),I.ERR_DEPRECATED);return r&&!hh[a]&&(hh[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}};Aa.spelling=function(t){return(r,n)=>(console.warn(`${n} is likely a misspelling of ${t}`),!0)};function hL(e,t,r){if(typeof e!="object"||e===null)throw new I("options must be an object",I.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 I("option "+i+" must be "+c,I.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new I("Unknown option "+i,I.ERR_BAD_OPTION)}}var ga={assertOptions:hL,validators:Aa},ze=ga.validators,ur=class{constructor(t){this.defaults=t||{},this.interceptors={request:new ya,response:new ya}}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=Yr(this.defaults,r);let{transitional:n,paramsSerializer:s,headers:i}=r;n!==void 0&&ga.assertOptions(n,{silentJSONParsing:ze.transitional(ze.boolean),forcedJSONParsing:ze.transitional(ze.boolean),clarifyTimeoutError:ze.transitional(ze.boolean),legacyInterceptorReqResOrdering:ze.transitional(ze.boolean),advertiseZstdAcceptEncoding:ze.transitional(ze.boolean),validateStatusUndefinedResolves:ze.transitional(ze.boolean)},!1),s!=null&&(y.isFunction(s)?r.paramsSerializer={serialize:s}:ga.assertOptions(s,{encode:ze.function,serialize:ze.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),ga.assertOptions(r,{baseUrl:ze.spelling("baseURL"),withXsrfToken:ze.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let a=i&&y.merge(i.common,i[r.method]);i&&y.forEach(["delete","get","head","post","put","patch","query","common"],g=>{delete i[g]}),r.headers=Pe.concat(a,i);let o=[],c=!0;this.interceptors.request.forEach(function(h){if(typeof h.runWhen=="function"&&h.runWhen(r)===!1)return;c=c&&h.synchronous;let E=r.transitional||wa;E&&E.legacyInterceptorReqResOrdering?o.unshift(h.fulfilled,h.rejected):o.push(h.fulfilled,h.rejected)});let l=[];this.interceptors.response.forEach(function(h){l.push(h.fulfilled,h.rejected)});let u,d=0,m;if(!c){let g=[wl.bind(this),void 0];for(g.unshift(...o),g.push(...l),m=g.length,u=Promise.resolve(r);d<m;)u=u.then(g[d++],g[d++]);return u}m=o.length;let f=r;for(;d<m;){let g=o[d++],h=o[d++];try{f=g?g(f):f}catch(E){if(!h){u=Promise.reject(E);break}try{let T=h.call(this,E);y.isThenable(T)&&(u=Promise.resolve(T).then(()=>wl.call(this,f)))}catch(T){u=Promise.reject(T)}break}}if(!u)try{u=wl.call(this,f)}catch(g){u=Promise.reject(g)}for(d=0,m=l.length;d<m;)u=u.then(l[d++],l[d++]);return u}getUri(t){t=Yr(this.defaults,t);let r=jl(t.baseURL,t.url,t.allowAbsoluteUrls,t);return Fl(r,t.params,t.paramsSerializer)}};y.forEach(["delete","get","head","options"],function(t){ur.prototype[t]=function(r,n){return this.request(Yr(n||{},{method:t,url:r,data:n&&y.hasOwnProp(n,"data")?n.data:void 0}))}});y.forEach(["post","put","patch","query"],function(t){function r(n){return function(i,a,o){return this.request(Yr(o||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:i,data:a}))}}ur.prototype[t]=r(),t!=="query"&&(ur.prototype[t+"Form"]=r(!0))});var Cl=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 dr(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 _L(e){return function(r){return e.apply(null,r)}}function yL(e){return y.isObject(e)&&e.isAxiosError===!0}var Pl={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(Pl).forEach(([e,t])=>{Pl[t]=e});function e_(e){let t=new ur(e),r=vh(ur.prototype.request,t);return y.extend(r,ur.prototype,t,{allOwnKeys:!0}),y.extend(r,t,null,{allOwnKeys:!0}),r.create=function(s){return e_(Yr(e,s))},r}var ke=e_(js);ke.Axios=ur;ke.CanceledError=dr;ke.CancelToken=Cl;ke.isCancel=Fh;ke.VERSION=ks;ke.toFormData=Ra;ke.AxiosError=I;ke.Cancel=ke.CanceledError;ke.all=function(t){return Promise.all(t)};ke.spread=_L;ke.isAxiosError=yL;ke.mergeConfig=Yr;ke.AxiosHeaders=Pe;ke.formToJSON=e=>Uh(y.isHTMLForm(e)?new FormData(e):e);ke.getAdapter=Zh.getAdapter;ke.HttpStatusCode=Pl;ke.default=ke;t_.exports=ke});var Gl=D(Ie=>{"use strict";p();var EL=Ie&&Ie.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ie,"__esModule",{value:!0});Ie.Api=Ie.HttpClient=Ie.ContentType=Ie.MissionV1Type=Ie.MissionType=Ie.MissionRewardType=Ie.MissionFrequency=Ie.LinkActionType=Ie.BannerType=void 0;var r_;(function(e){e.Clutch="Clutch",e.TelegramMiniApp="TelegramMiniApp",e.TelegramMiniAppBookLocation="TelegramMiniApp-book-location",e.TelegramMiniAppBookInfo="TelegramMiniApp-book-info",e.TelegramMiniAppMVLDescription="TelegramMiniApp-MVL-description"})(r_||(Ie.BannerType=r_={}));var n_;(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"})(n_||(Ie.LinkActionType=n_={}));var s_;(function(e){e.PERMANANT="PERMANANT",e.DAILY="DAILY"})(s_||(Ie.MissionFrequency=s_={}));var i_;(function(e){e.BALANCE="BALANCE",e.MISSION_POINT="MISSION_POINT"})(i_||(Ie.MissionRewardType=i_={}));var a_;(function(e){e.USER_ACTIVITY="USER_ACTIVITY",e.THIRDPARTY_ACTIVITY="THIRDPARTY_ACTIVITY",e.REFEREE_ACTIVITY="REFEREE_ACTIVITY"})(a_||(Ie.MissionType=a_={}));var o_;(function(e){e.MY_ACTIVITIES_COUNT="MY_ACTIVITIES_COUNT",e.REFEREE_ACTIVITIES_COUNT="REFEREE_ACTIVITIES_COUNT"})(o_||(Ie.MissionV1Type=o_={}));var TL=EL(tt()),Un;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(Un||(Ie.ContentType=Un={}));var xa=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=TL.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)||{},l=this.mergeRequestParams(o,c),u=i||this.format||void 0;return n===Un.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===Un.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...l,headers:{...l.headers||{},...n&&n!==Un.FormData?{"Content-Type":n}:{}},params:s,responseType:u,data:a,url:r}).then(d=>d.data)}};Ie.HttpClient=xa;var Hl=class extends xa{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:Un.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})};Ie.Api=Hl});var Wl=D(H=>{"use strict";p();var bL=H&&H.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(H,"__esModule",{value:!0});H.Api=H.HttpClient=H.ContentType=H.AmbientHailingTelemetryEventDtoSubMarketEnum=H.AmbientHailingTelemetryEventDtoStageEnum=H.AmbientHailingTelemetryEventDtoRegionEnum=H.AmbientHailingTelemetryEventDtoPaymentModeEnum=H.AmbientHailingTelemetryEventDtoOutcomeEnum=H.AmbientHailingTelemetryEventDtoJourneyOutcomeEnum=H.AmbientHailingTelemetryEventDtoFailureReasonEnum=H.AmbientHailingTelemetryEventDtoEventNameEnum=H.AmbientHailingTelemetryEventDtoErrorCodeEnum=H.AmbientHailingTelemetryEventDtoDispatchOutcomeEnum=H.AmbientHailingTelemetryEventDtoDepositTokenEnum=H.AmbientHailingTelemetryEventDtoDepositPathEnum=H.AmbientHailingTelemetryEventDtoDepositNetworkEnum=H.AmbientHailingTelemetryEventDtoCommandEnum=H.AmbientHailingTelemetryEventDtoCancellationStageEnum=H.AmbientHailingTelemetryEventDtoCancellationActorEnum=H.AmbientHailingTelemetryEventDtoBuildEnvEnum=H.AmbientHailingTelemetryEventDtoAhUserTypeEnum=H.AmbientHailingTelemetryBatchDtoSourceEnum=H.AmbientHailingTelemetryBatchDtoSchemaVersionEnum=H.AmbientHailingAgentRuntime=H.AmbientHailingAgentModelSource=void 0;var c_;(function(e){e.ClaudeSessionStart="claude_session_start",e.OpenclawSession="openclaw_session"})(c_||(H.AmbientHailingAgentModelSource=c_={}));var l_;(function(e){e.ClaudeCode="claude_code",e.Openclaw="openclaw"})(l_||(H.AmbientHailingAgentRuntime=l_={}));var u_;(function(e){e[e.Value1=1]="Value1"})(u_||(H.AmbientHailingTelemetryBatchDtoSchemaVersionEnum=u_={}));var d_;(function(e){e.AmbientHailing="ambient_hailing"})(d_||(H.AmbientHailingTelemetryBatchDtoSourceEnum=d_={}));var p_;(function(e){e.New="new",e.Existing="existing"})(p_||(H.AmbientHailingTelemetryEventDtoAhUserTypeEnum=p_={}));var m_;(function(e){e.Dev="dev",e.Staging="staging",e.Production="production"})(m_||(H.AmbientHailingTelemetryEventDtoBuildEnvEnum=m_={}));var f_;(function(e){e.Rider="rider",e.Driver="driver",e.Company="company",e.System="system"})(f_||(H.AmbientHailingTelemetryEventDtoCancellationActorEnum=f_={}));var g_;(function(e){e.PreMatch="pre_match",e.PostMatch="post_match",e.InRide="in_ride"})(g_||(H.AmbientHailingTelemetryEventDtoCancellationStageEnum=g_={}));var h_;(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",e.DepositAdd="deposit-add",e.DepositRelayStatus="deposit-relay-status",e.DepositStatus="deposit-status"})(h_||(H.AmbientHailingTelemetryEventDtoCommandEnum=h_={}));var __;(function(e){e.BASE="BASE",e.BASE_SEPOLIA="BASE_SEPOLIA",e.ETHEREUM="ETHEREUM",e.ETHEREUM_SEPOLIA="ETHEREUM_SEPOLIA"})(__||(H.AmbientHailingTelemetryEventDtoDepositNetworkEnum=__={}));var y_;(function(e){e.MvlDirect="mvl-direct",e.Relay="relay"})(y_||(H.AmbientHailingTelemetryEventDtoDepositPathEnum=y_={}));var E_;(function(e){e.MVL="MVL",e.USDC="USDC"})(E_||(H.AmbientHailingTelemetryEventDtoDepositTokenEnum=E_={}));var T_;(function(e){e.SearchNotStarted="search_not_started",e.SearchStarted="search_started",e.NoDriver="no_driver",e.Matched="matched"})(T_||(H.AmbientHailingTelemetryEventDtoDispatchOutcomeEnum=T_={}));var b_;(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",e.INSUFFICIENT_DEPOSIT="INSUFFICIENT_DEPOSIT",e.DEPOSIT_FAILED="DEPOSIT_FAILED"})(b_||(H.AmbientHailingTelemetryEventDtoErrorCodeEnum=b_={}));var v_;(function(e){e.AmbientCliCommandStarted="ambient_cli_command_started",e.AmbientCliCommandCompleted="ambient_cli_command_completed",e.AmbientCliCommandFailed="ambient_cli_command_failed"})(v_||(H.AmbientHailingTelemetryEventDtoEventNameEnum=v_={}));var R_;(function(e){e.WalletNoBalance="wallet_no_balance",e.WalletInsufficientBalance="wallet_insufficient_balance",e.CardError="card_error",e.InsufficientDeposit="insufficient_deposit",e.RelayUnavailable="relay_unavailable",e.TokenNotDepositable="token_not_depositable",e.JwtNotFound="jwt_not_found",e.WalletSubmissionFailed="wallet_submission_failed",e.WalletTransactionFailed="wallet_transaction_failed",e.RelayFailed="relay_failed",e.Other="other"})(R_||(H.AmbientHailingTelemetryEventDtoFailureReasonEnum=R_={}));var w_;(function(e){e.Completed="completed",e.Cancelled="cancelled",e.Abandoned="abandoned"})(w_||(H.AmbientHailingTelemetryEventDtoJourneyOutcomeEnum=w_={}));var A_;(function(e){e.Started="started",e.Completed="completed",e.Failed="failed"})(A_||(H.AmbientHailingTelemetryEventDtoOutcomeEnum=A_={}));var x_;(function(e){e.Card="card",e.WalletUsdc="wallet_usdc"})(x_||(H.AmbientHailingTelemetryEventDtoPaymentModeEnum=x_={}));var S_;(function(e){e.SG="SG",e.US="US"})(S_||(H.AmbientHailingTelemetryEventDtoRegionEnum=S_={}));var I_;(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",e.DepositRequired="deposit_required",e.DepositStarted="deposit_started",e.DepositSubmitted="deposit_submitted",e.DepositConfirmed="deposit_confirmed",e.DepositActivated="deposit_activated",e.DepositFailed="deposit_failed"})(I_||(H.AmbientHailingTelemetryEventDtoStageEnum=I_={}));var D_;(function(e){e.SG="SG",e.NYC="NYC",e.DENVER="DENVER",e.OTHER="OTHER"})(D_||(H.AmbientHailingTelemetryEventDtoSubMarketEnum=D_={}));var vL=bL(tt()),Fn;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(Fn||(H.ContentType=Fn={}));var Sa=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=vL.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)||{},l=this.mergeRequestParams(o,c),u=i||this.format||void 0;return n===Fn.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===Fn.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...l,headers:{...l.headers||{},...n&&n!==Fn.FormData?{"Content-Type":n}:{}},params:s,responseType:u,data:a,url:r}).then(d=>d.data)}};H.HttpClient=Sa;var $l=class extends Sa{getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t});postV1Events=(t,r={})=>this.request({path:"/v1/events",method:"POST",body:t,type:Fn.Json,format:"json",...r})};H.Api=$l});var Kl=D(Nt=>{"use strict";p();var RL=Nt&&Nt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.Api=Nt.HttpClient=Nt.ContentType=Nt.SwapType=void 0;var O_;(function(e){e.TOBEP20="TO_BEP20",e.TOERC20="TO_ERC20"})(O_||(Nt.SwapType=O_={}));var wL=RL(tt()),wr;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(wr||(Nt.ContentType=wr={}));var Ia=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=wL.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)||{},l=this.mergeRequestParams(o,c),u=i||this.format||void 0;return n===wr.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===wr.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...l,headers:{...l.headers||{},...n&&n!==wr.FormData?{"Content-Type":n}:{}},params:s,responseType:u,data:a,url:r}).then(d=>d.data)}};Nt.HttpClient=Ia;var Jl=class extends Ia{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:wr.Json,format:"json",...r});postV1Swap=(t,r={})=>this.request({path:"/v1/swap",method:"POST",body:t,type:wr.Json,...r});postV2Swap=(t,r={})=>this.request({path:"/v2/swap",method:"POST",body:t,type:wr.Json,format:"json",...r})};Nt.Api=Jl});var zl=D(J=>{"use strict";p();var AL=J&&J.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(J,"__esModule",{value:!0});J.Api=J.HttpClient=J.ContentType=J.UpbitPriceInfoResponseDtoCurrencyCodeEnum=J.TransactionType=J.TransactionStatus=J.TokenType=J.StakingType=J.StakingStatus=J.SortOrder=J.GetV3BlockchainNetworksParamsRegionEnum=J.GetV3BlockchainNetworksParamsEnvironmentEnum=J.GetV3BlockchainContractsParamsRegionEnum=J.GetV3BlockchainContractsParamsEnvironmentEnum=J.GetV2WalletsSimplePricePublicParamsIdsEnum=J.GetV1PriceHistoryMvlParamsCurrencyEnum=J.GetTokenPriceByDateDtoPriceTypeEnum=J.FilterType=J.CryptoCurrency=J.ContractName=J.BlockchainNetwork=J.AssetMigrationStatus=void 0;var N_;(function(e){e.PENDING="PENDING",e.COMPLETED="COMPLETED",e.FAILED="FAILED"})(N_||(J.AssetMigrationStatus=N_={}));var C_;(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"})(C_||(J.BlockchainNetwork=C_={}));var P_;(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"})(P_||(J.ContractName=P_={}));var L_;(function(e){e.JPY="JPY",e.USDC="USDC"})(L_||(J.CryptoCurrency=L_={}));var M_;(function(e){e.ALL="ALL",e.SEND="SEND",e.RECEIVE="RECEIVE"})(M_||(J.FilterType=M_={}));var k_;(function(e){e.HIGH="HIGH",e.LOW="LOW"})(k_||(J.GetTokenPriceByDateDtoPriceTypeEnum=k_={}));var U_;(function(e){e.USD="USD",e.SGD="SGD",e.KRW="KRW",e.IDR="IDR",e.THB="THB",e.KHR="KHR",e.JPY="JPY"})(U_||(J.GetV1PriceHistoryMvlParamsCurrencyEnum=U_={}));var F_;(function(e){e.MassVehicleLedger="mass-vehicle-ledger"})(F_||(J.GetV2WalletsSimplePricePublicParamsIdsEnum=F_={}));var q_;(function(e){e.Production="production",e.Stage="stage",e.Dev="dev"})(q_||(J.GetV3BlockchainContractsParamsEnvironmentEnum=q_={}));var j_;(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"})(j_||(J.GetV3BlockchainContractsParamsRegionEnum=j_={}));var B_;(function(e){e.Production="production",e.Stage="stage",e.Dev="dev"})(B_||(J.GetV3BlockchainNetworksParamsEnvironmentEnum=B_={}));var V_;(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"})(V_||(J.GetV3BlockchainNetworksParamsRegionEnum=V_={}));var H_;(function(e){e.Asc="asc",e.Desc="desc"})(H_||(J.SortOrder=H_={}));var G_;(function(e){e.ACTIVE="ACTIVE",e.FINISHED="FINISHED"})(G_||(J.StakingStatus=G_={}));var $_;(function(e){e.LP="LP",e.SINGLE="SINGLE",e.SINGLE_LOCKUP="SINGLE_LOCKUP"})($_||(J.StakingType=$_={}));var W_;(function(e){e.COIN="COIN",e.ERC20="ERC20",e.BEP20="BEP20",e.FA2="FA2",e.FA12="FA1.2",e.SERVERED="SERVERED",e.JETTON="JETTON"})(W_||(J.TokenType=W_={}));var J_;(function(e){e.PENDING="PENDING",e.SUCCESS="SUCCESS",e.FAIL="FAIL"})(J_||(J.TransactionStatus=J_={}));var K_;(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"})(K_||(J.TransactionType=K_={}));var Y_;(function(e){e.USD="USD",e.SGD="SGD",e.KRW="KRW",e.IDR="IDR",e.THB="THB",e.KHR="KHR",e.JPY="JPY"})(Y_||(J.UpbitPriceInfoResponseDtoCurrencyCodeEnum=Y_={}));var xL=AL(tt()),Kt;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(Kt||(J.ContentType=Kt={}));var Da=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=xL.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)||{},l=this.mergeRequestParams(o,c),u=i||this.format||void 0;return n===Kt.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===Kt.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...l,headers:{...l.headers||{},...n&&n!==Kt.FormData?{"Content-Type":n}:{}},params:s,responseType:u,data:a,url:r}).then(d=>d.data)}};J.HttpClient=Da;var Yl=class extends Da{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:Kt.Json,format:"json",...r});postV11WalletsTransactions=(t,r={})=>this.request({path:"/v1.1/wallets/transactions",method:"POST",body:t,type:Kt.Json,format:"json",...r});postV1WalletsTransactions=(t,r={})=>this.request({path:"/v1/wallets/transactions",method:"POST",body:t,type:Kt.Json,format:"json",...r});postV2LinkTransferLog=(t,r={})=>this.request({path:"/v2/link-transfer/log",method:"POST",body:t,secure:!0,type:Kt.Json,format:"json",...r});postV2WalletsTransaction=(t,r={})=>this.request({path:"/v2/wallets/transaction",method:"POST",body:t,secure:!0,type:Kt.Json,format:"json",...r})};J.Api=Yl});var Ql=D(G=>{"use strict";p();var SL=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.UserIdentifierType=G.TriggerSnapshotDtoRegionsEnum=G.TriggerSnapshotDtoIdentifierTypesEnum=G.TransferingToDataAttestationWalletRequestDtoToCurrencyEnum=G.TransferingToDataAttestationWalletRequestDtoFromCurrencyEnum=G.TransferInputDtoUserModelEnum=G.TransferInputDtoTransferTypeEnum=G.TransactionStatusEnum=G.TadaPointRuleType=G.S2SGetWalletBalanceResponseDtoCurrencyEnum=G.S2SGetWalletBalanceRequestDtoCurrencyEnum=G.Region=G.PointRequestType=G.GetWalletTokenHistoryResponseDtoCurrencyEnum=G.GetWalletTokenHistoryRequestDtoCurrencyEnum=G.GetWalletBalanceUcResponseCurrencyEnum=G.DataGeneratedNotificationV1DtoStatusEnum=G.DataAttestationTxType=G.DATA_PROVIDER=G.BulkRegisterWalletResultStatus=G.BlockchainNetwork=G.AttestationRequestStatus=void 0;var z_;(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"})(z_||(G.AttestationRequestStatus=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.Reused="reused",e.Created="created",e.Skipped="skipped",e.PrivyMissing="privy_missing",e.Error="error"})(Q_||(G.BulkRegisterWalletResultStatus=Q_={}));var Z_;(function(e){e.TADA="TADA"})(Z_||(G.DATA_PROVIDER=Z_={}));var ey;(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"})(ey||(G.DataAttestationTxType=ey={}));var ty;(function(e){e.SUCCESS="SUCCESS",e.FAIL="FAIL"})(ty||(G.DataGeneratedNotificationV1DtoStatusEnum=ty={}));var ry;(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"})(ry||(G.GetWalletBalanceUcResponseCurrencyEnum=ry={}));var ny;(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"})(ny||(G.GetWalletTokenHistoryRequestDtoCurrencyEnum=ny={}));var sy;(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"})(sy||(G.GetWalletTokenHistoryResponseDtoCurrencyEnum=sy={}));var iy;(function(e){e.LOCK="LOCK",e.UNLOCK="UNLOCK"})(iy||(G.PointRequestType=iy={}));var ay;(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"})(ay||(G.Region=ay={}));var oy;(function(e){e.TADA_TOKEN="TADA_TOKEN",e.LOCKED_TADA_POINT_US="LOCKED_TADA_POINT_US",e.TADA_POINT_US="TADA_POINT_US"})(oy||(G.S2SGetWalletBalanceRequestDtoCurrencyEnum=oy={}));var cy;(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"})(cy||(G.S2SGetWalletBalanceResponseDtoCurrencyEnum=cy={}));var ly;(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"})(ly||(G.TadaPointRuleType=ly={}));var uy;(function(e){e.PENDING="PENDING",e.SUCCESS="SUCCESS",e.FAIL="FAIL"})(uy||(G.TransactionStatusEnum=uy={}));var dy;(function(e){e.COIN_TRANSFER="COIN_TRANSFER",e.INCENTIVE_TRANSFER="INCENTIVE_TRANSFER",e.SUBSIDY_TRANSFER="SUBSIDY_TRANSFER"})(dy||(G.TransferInputDtoTransferTypeEnum=dy={}));var py;(function(e){e.DRIVER="DRIVER",e.RIDER="RIDER"})(py||(G.TransferInputDtoUserModelEnum=py={}));var my;(function(e){e.FIAT_SGD="FIAT_SGD",e.FIAT_USD="FIAT_USD",e.MVL="MVL",e.TADA_TOKEN="TADA_TOKEN"})(my||(G.TransferingToDataAttestationWalletRequestDtoFromCurrencyEnum=my={}));var fy;(function(e){e.MVL="MVL",e.TADA_TOKEN="TADA_TOKEN"})(fy||(G.TransferingToDataAttestationWalletRequestDtoToCurrencyEnum=fy={}));var gy;(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"})(gy||(G.TriggerSnapshotDtoIdentifierTypesEnum=gy={}));var hy;(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"})(hy||(G.TriggerSnapshotDtoRegionsEnum=hy={}));var _y;(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"})(_y||(G.UserIdentifierType=_y={}));var IL=SL(tt()),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 Oa=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=IL.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)||{},l=this.mergeRequestParams(o,c),u=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({...l,headers:{...l.headers||{},...n&&n!==Le.FormData?{"Content-Type":n}:{}},params:s,responseType:u,data:a,url:r}).then(d=>d.data)}};G.HttpClient=Oa;var Xl=class extends Oa{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:Le.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:Le.Json,format:"json",...r});postV1IncentiveAggregateSummary=(t,r={})=>this.request({path:"/v1/incentive-aggregate/summary",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1InternalSubsidy=(t,r={})=>this.request({path:"/v1/internal/subsidy",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1InternalTransactionHistory=(t,r={})=>this.request({path:"/v1/internal/transaction/history",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1InternalTransactionRideHistory=(t,r={})=>this.request({path:"/v1/internal/transaction/ride-history",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1InternalWallet=(t,r={})=>this.request({path:"/v1/internal/wallet",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1InternalWalletBalanceSnapshot=(t,r={})=>this.request({path:"/v1/internal/wallet-balance/snapshot",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1InternalWalletBulk=(t,r={})=>this.request({path:"/v1/internal/wallet/bulk",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1InternalWebhookNotificationDataGenerated=(t,r={})=>this.request({path:"/v1/internal/webhook/notification/data-generated",method:"POST",body:t,secure:!0,type:Le.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:Le.Json,format:"json",...r});postV1S2SPointUnlock=(t,r={})=>this.request({path:"/v1/s2s/point/unlock",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1TadaReferrals=(t,r={})=>this.request({path:"/v1/tada/referrals",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1TransferingToDataAttestationWallet=(t,r={})=>this.request({path:"/v1/transfering-to-data-attestation-wallet",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1WalletBalance=(t,r={})=>this.request({path:"/v1/wallet/balance",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postV1WalletHistory=(t,r={})=>this.request({path:"/v1/wallet/history",method:"POST",body:t,secure:!0,type:Le.Json,format:"json",...r});postWebhookDummy=(t={})=>this.request({path:"/webhook-dummy",method:"POST",...t})};G.Api=Xl});var eu=D(pt=>{"use strict";p();var DL=pt&&pt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(pt,"__esModule",{value:!0});pt.Api=pt.HttpClient=pt.ContentType=pt.TextAlignEnum=pt.FontEnum=void 0;var yy;(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"})(yy||(pt.FontEnum=yy={}));var Ey;(function(e){e.Left="left",e.Center="center",e.Right="right"})(Ey||(pt.TextAlignEnum=Ey={}));var OL=DL(tt()),qn;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(qn||(pt.ContentType=qn={}));var Na=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=OL.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)||{},l=this.mergeRequestParams(o,c),u=i||this.format||void 0;return n===qn.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===qn.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...l,headers:{...l.headers||{},...n&&n!==qn.FormData?{"Content-Type":n}:{}},params:s,responseType:u,data:a,url:r}).then(d=>d.data)}};pt.HttpClient=Na;var Zl=class extends Na{getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t});postImageFactoryCreate=(t,r={})=>this.request({path:"/image-factory/create",method:"POST",body:t,type:qn.Json,format:"json",...r})};pt.Api=Zl});var tu=D(Yt=>{"use strict";p();var NL=Yt&&Yt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Yt,"__esModule",{value:!0});Yt.error=Yt.warn=Yt.log=void 0;var CL=NL(Dn()),Ca=(0,CL.default)("api-client");Ca.log=console.log.bind(console);var PL=Ca.extend("log");Yt.log=PL;var Ty=Ca.extend("warn");Yt.warn=Ty;Ty.log=console.warn.bind(console);var by=Ca.extend("error");Yt.error=by;by.log=console.error.bind(console)});var nu=D(Ct=>{"use strict";p();var LL=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.EntityType=void 0;var vy;(function(e){e.MISSION_GROUP="MISSION_GROUP",e.INVENTORY_ITEM="INVENTORY_ITEM"})(vy||(Ct.EntityType=vy={}));var ML=LL(tt()),Bs;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(Bs||(Ct.ContentType=Bs={}));var Pa=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=ML.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)||{},l=this.mergeRequestParams(o,c),u=i||this.format||void 0;return n===Bs.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===Bs.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...l,headers:{...l.headers||{},...n&&n!==Bs.FormData?{"Content-Type":n}:{}},params:s,responseType:u,data:a,url:r}).then(d=>d.data)}};Ct.HttpClient=Pa;var ru=class extends Pa{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})};Ct.Api=ru});var iu=D(R=>{"use strict";p();var kL=R&&R.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(R,"__esModule",{value:!0});R.PreparedLeaseTokenPrototypeDtoStatusEnum=R.PaymentInfoStatus=R.PaymentEventType=R.PaymentEventCurrency=R.PaymentEventChannel=R.PayerStatus=R.OrderStatus=R.OperatorActionType=R.OperatorActionStatus=R.OperatorActionBlockedReason=R.OnchainTransactionType=R.OnchainTransactionStatus=R.OnchainStatus=R.OnchainEntityType=R.NftType=R.NftLeaseStatus=R.MusubiTransactionTypeFilter=R.MusubiIncomesCurrency=R.ListingSortBy=R.LeaseIssueStrategy=R.LeaseDetailByMaturityDateDtoCurrencyEnum=R.LeaseCompanyPeriods=R.KycStatus=R.InvoiceSavedStatus=R.InvoicePaymentStatus=R.InvestorStatus=R.InitiateRedeemResultStatus=R.GuarantorVaultTransactionType=R.GuarantorVaultTransactionStatus=R.GuarantorVaultToken=R.GuarantorStatus=R.GuaranteePositionStatus=R.GetV2JpRwaVehicleNftsParamsTypeEnum=R.GetV1GarageExportCsvParamsLangEnum=R.GetNftsSortBy=R.GetMarketListingParamsSortOrderEnum=R.DepreciationMethod=R.DataProvisionConsent=R.Currency=R.ContractStatus=R.ContractPaymentScheduleType=R.ContractPaymentFrequency=R.ContractPayerConfirmation=R.ContractCurrency=R.ClassifiedTransactionType=R.BuildVaultWithdrawalDtoTokenEnum=R.BlockchainNetwork=R.ArPaymentMethod=R.ArB2BTokenStatus=R.AmlStatus=void 0;R.Api=R.HttpClient=R.ContentType=R.XAxisInterval=R.VehicleTokenType=R.VehicleStatus=R.VehicleProductCategory=R.VehicleOdometerHistoryDtoTypeEnum=R.VehicleOdometerHistoryDtoPeriodEnum=R.VehicleAssetStockStatus=R.TransferTokenResponseDtoTokenTypeEnum=R.TransferTokenResponseDtoTokenStandardEnum=R.TransferTokenRequestDtoVersionEnum=R.TokenType=R.TokenStatus=R.TokenPrototypeDtoTokenTypeEnum=R.TokenPrototypeDtoTokenStandardEnum=R.TokenPrototypeDtoStatusEnum=R.TermsConsent=R.SupportedLanguage=R.Strategy=R.StatisticsPeriod=R.SortOrder=R.SettlementPeriodType=R.SellerStatus=R.RwaNoticeTag=R.RwaNoticeStatus=R.RwaNoticeCategory=R.ReverifyPurchaseOutcome=R.RegisteredBy=R.RedeemStatus=R.RedeemMode=R.PurchaseType=R.PurchaseTransactionStatus=R.PreparedOwnershipTokenPrototypeDtoTokenTypeEnum=R.PreparedOwnershipTokenPrototypeDtoTokenStandardEnum=R.PreparedOwnershipTokenPrototypeDtoStatusEnum=R.PreparedLeaseTokenPrototypeDtoTokenTypeEnum=R.PreparedLeaseTokenPrototypeDtoTokenStandardEnum=void 0;var Ry;(function(e){e.APPROVED="APPROVED",e.IN_PROGRESS="IN_PROGRESS",e.REJECTED="REJECTED",e.SKIPPED="SKIPPED"})(Ry||(R.AmlStatus=Ry={}));var wy;(function(e){e.HELD="HELD",e.MATURED="MATURED",e.REDEEMED="REDEEMED"})(wy||(R.ArB2BTokenStatus=wy={}));var Ay;(function(e){e.FIAT_SELLER="FIAT_SELLER",e.TADA="TADA",e.WALLET="WALLET",e.GUARANTOR="GUARANTOR"})(Ay||(R.ArPaymentMethod=Ay={}));var xy;(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"})(xy||(R.BlockchainNetwork=xy={}));var Sy;(function(e){e.USDC="USDC"})(Sy||(R.BuildVaultWithdrawalDtoTokenEnum=Sy={}));var Iy;(function(e){e.PURCHASE="PURCHASE",e.RETURN="RETURN",e.RECEIVED="RECEIVED",e.SENT="SENT",e.APPROVE="APPROVE",e.MINT="MINT",e.UNKNOWN="UNKNOWN"})(Iy||(R.ClassifiedTransactionType=Iy={}));var Dy;(function(e){e.USD="USD",e.USDC="USDC",e.JPYC="JPYC"})(Dy||(R.ContractCurrency=Dy={}));var Oy;(function(e){e.RECEIVED="RECEIVED",e.PENDING="PENDING",e.REJECTED="REJECTED"})(Oy||(R.ContractPayerConfirmation=Oy={}));var Ny;(function(e){e.WEEKLY="WEEKLY",e.MONTHLY="MONTHLY",e.QUARTERLY="QUARTERLY",e.YEARLY="YEARLY",e.DAILY="DAILY"})(Ny||(R.ContractPaymentFrequency=Ny={}));var Cy;(function(e){e.FIXED_DATE="FIXED_DATE",e.CUSTOM_DATE="CUSTOM_DATE"})(Cy||(R.ContractPaymentScheduleType=Cy={}));var Py;(function(e){e.DRAFT="DRAFT",e.DELETED="DELETED",e.INVOICE_GENERATED="INVOICE_GENERATED",e.GUARANTEE_REGISTERED="GUARANTEE_REGISTERED",e.CLOSED="CLOSED"})(Py||(R.ContractStatus=Py={}));var Ly;(function(e){e.USD="USD",e.USDC="USDC",e.MVL="MVL",e.JPY="JPY",e.BTC="BTC"})(Ly||(R.Currency=Ly={}));var My;(function(e){e.RECEIVED="RECEIVED",e.WAITING="WAITING",e.REJECTED="REJECTED"})(My||(R.DataProvisionConsent=My={}));var ky;(function(e){e.FLAT_RATE="FLAT_RATE"})(ky||(R.DepreciationMethod=ky={}));var Uy;(function(e){e.Asc="asc",e.Desc="desc"})(Uy||(R.GetMarketListingParamsSortOrderEnum=Uy={}));var Fy;(function(e){e.MATURITY="MATURITY",e.VEHICLE_STATUS="VEHICLE_STATUS"})(Fy||(R.GetNftsSortBy=Fy={}));var qy;(function(e){e.En="en",e.Jp="jp"})(qy||(R.GetV1GarageExportCsvParamsLangEnum=qy={}));var jy;(function(e){e.OWNERSHIP="OWNERSHIP",e.LEASE="LEASE"})(jy||(R.GetV2JpRwaVehicleNftsParamsTypeEnum=jy={}));var By;(function(e){e.DRAFT="DRAFT",e.CONFIRMED="CONFIRMED",e.ONCHAIN_SUCCESS="ONCHAIN_SUCCESS"})(By||(R.GuaranteePositionStatus=By={}));var Vy;(function(e){e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE",e.PENDING="PENDING",e.REJECTED="REJECTED",e.DELETED="DELETED"})(Vy||(R.GuarantorStatus=Vy={}));var Hy;(function(e){e.USDC="USDC",e.MVL="MVL"})(Hy||(R.GuarantorVaultToken=Hy={}));var Gy;(function(e){e.PENDING="PENDING",e.CONFIRMED="CONFIRMED",e.FAILED="FAILED"})(Gy||(R.GuarantorVaultTransactionStatus=Gy={}));var $y;(function(e){e.DEPOSIT="DEPOSIT",e.WITHDRAWAL="WITHDRAWAL"})($y||(R.GuarantorVaultTransactionType=$y={}));var Wy;(function(e){e.QUEUED="QUEUED"})(Wy||(R.InitiateRedeemResultStatus=Wy={}));var Jy;(function(e){e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE",e.REJECTED="REJECTED"})(Jy||(R.InvestorStatus=Jy={}));var Ky;(function(e){e.UNPAID="UNPAID",e.PARTIALLY_PAID="PARTIALLY_PAID",e.OVERDUE="OVERDUE",e.MISSED="MISSED",e.PAID="PAID",e.DEFAULTED="DEFAULTED"})(Ky||(R.InvoicePaymentStatus=Ky={}));var Yy;(function(e){e.DRAFT="DRAFT",e.CONFIRMED="CONFIRMED",e.LISTED="LISTED",e.PARTIALLY_FUNDED="PARTIALLY_FUNDED",e.SOLD_OUT="SOLD_OUT"})(Yy||(R.InvoiceSavedStatus=Yy={}));var zy;(function(e){e.APPROVED="APPROVED",e.IN_PROGRESS="IN_PROGRESS",e.REJECTED="REJECTED",e.SKIPPED="SKIPPED"})(zy||(R.KycStatus=zy={}));var Xy;(function(e){e.DAY="DAY",e.WEEK="WEEK",e.MONTH="MONTH"})(Xy||(R.LeaseCompanyPeriods=Xy={}));var Qy;(function(e){e.USD="USD",e.BTC="BTC"})(Qy||(R.LeaseDetailByMaturityDateDtoCurrencyEnum=Qy={}));var Zy;(function(e){e.SINGLE="SINGLE",e.FRACTIONAL="FRACTIONAL"})(Zy||(R.LeaseIssueStrategy=Zy={}));var eE;(function(e){e.CreatedAt="createdAt",e.FaceValue="faceValue",e.DueDate="dueDate"})(eE||(R.ListingSortBy=eE={}));var tE;(function(e){e.USD="USD",e.MVL="MVL",e.BTC="BTC"})(tE||(R.MusubiIncomesCurrency=tE={}));var rE;(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"})(rE||(R.MusubiTransactionTypeFilter=rE={}));var nE;(function(e){e.NOT_STARTED="NOT_STARTED",e.ACTIVE="ACTIVE",e.EXPIRED="EXPIRED",e.CLAIMED="CLAIMED"})(nE||(R.NftLeaseStatus=nE={}));var sE;(function(e){e.OWNERSHIP="OWNERSHIP",e.LEASE="LEASE"})(sE||(R.NftType=sE={}));var iE;(function(e){e.SELLER="SELLER",e.PAYER="PAYER",e.GUARANTOR="GUARANTOR",e.GUARANTEE_POSITION="GUARANTEE_POSITION",e.INVOICE="INVOICE",e.SELLER_SETTLEMENT="SELLER_SETTLEMENT"})(iE||(R.OnchainEntityType=iE={}));var aE;(function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.CONFIRMED="CONFIRMED",e.FAILED="FAILED"})(aE||(R.OnchainStatus=aE={}));var oE;(function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.COMPLETED="COMPLETED",e.FAILED="FAILED",e.PERMANENTLY_FAILED="PERMANENTLY_FAILED"})(oE||(R.OnchainTransactionStatus=oE={}));var cE;(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",e.SELF_REDEEM="SELF_REDEEM"})(cE||(R.OnchainTransactionType=cE={}));var lE;(function(e){e.EXECUTOR_NOT_SAFE_OWNER="EXECUTOR_NOT_SAFE_OWNER",e.SIGNATURES_SHORT_OF_THRESHOLD="SIGNATURES_SHORT_OF_THRESHOLD",e.SIMULATION_FAILED="SIMULATION_FAILED",e.ORACLE_PRICE_ABOVE_CAP="ORACLE_PRICE_ABOVE_CAP"})(lE||(R.OperatorActionBlockedReason=lE={}));var uE;(function(e){e.IDLE="IDLE",e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.COMPLETED="COMPLETED",e.FAILED="FAILED"})(uE||(R.OperatorActionStatus=uE={}));var dE;(function(e){e.GUARANTOR_DEPOSIT="GUARANTOR_DEPOSIT",e.PURCHASE="PURCHASE",e.REDEEM="REDEEM",e.PAYMENT="PAYMENT"})(dE||(R.OperatorActionType=dE={}));var pE;(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"})(pE||(R.OrderStatus=pE={}));var mE;(function(e){e.ACTIVE="ACTIVE",e.PENDING="PENDING",e.REJECTED="REJECTED"})(mE||(R.PayerStatus=mE={}));var fE;(function(e){e.ADMIN_CSV="ADMIN_CSV",e.ADMIN_MANUAL="ADMIN_MANUAL",e.AUTO_GENERATED="AUTO_GENERATED"})(fE||(R.PaymentEventChannel=fE={}));var gE;(function(e){e.USD="USD",e.USDC="USDC"})(gE||(R.PaymentEventCurrency=gE={}));var hE;(function(e){e.PAID="PAID",e.OVERDUE="OVERDUE",e.MISSED="MISSED",e.DEFAULTED="DEFAULTED"})(hE||(R.PaymentEventType=hE={}));var _E;(function(e){e.VERIFICATION_REQUIRED="VERIFICATION_REQUIRED",e.COMFIRMED="COMFIRMED",e.FAILED="FAILED"})(_E||(R.PaymentInfoStatus=_E={}));var yE;(function(e){e.DRAFT="DRAFT",e.IMAGE_GENERATING="IMAGE_GENERATING",e.METADATA_UPLOADING="METADATA_UPLOADING",e.MINTING="MINTING",e.MINTED="MINTED",e.COMPLETED="COMPLETED"})(yE||(R.PreparedLeaseTokenPrototypeDtoStatusEnum=yE={}));var EE;(function(e){e.ERC721="ERC_721",e.ERC3525="ERC_3525"})(EE||(R.PreparedLeaseTokenPrototypeDtoTokenStandardEnum=EE={}));var TE;(function(e){e.OWNERSHIP="OWNERSHIP",e.LEASE="LEASE"})(TE||(R.PreparedLeaseTokenPrototypeDtoTokenTypeEnum=TE={}));var bE;(function(e){e.DRAFT="DRAFT",e.IMAGE_GENERATING="IMAGE_GENERATING",e.METADATA_UPLOADING="METADATA_UPLOADING",e.MINTING="MINTING",e.MINTED="MINTED",e.COMPLETED="COMPLETED"})(bE||(R.PreparedOwnershipTokenPrototypeDtoStatusEnum=bE={}));var vE;(function(e){e.ERC721="ERC_721",e.ERC3525="ERC_3525"})(vE||(R.PreparedOwnershipTokenPrototypeDtoTokenStandardEnum=vE={}));var RE;(function(e){e.OWNERSHIP="OWNERSHIP",e.LEASE="LEASE"})(RE||(R.PreparedOwnershipTokenPrototypeDtoTokenTypeEnum=RE={}));var wE;(function(e){e.PENDING="PENDING",e.CONFIRMED="CONFIRMED",e.FAILED="FAILED",e.VERIFICATION_FAILED="VERIFICATION_FAILED"})(wE||(R.PurchaseTransactionStatus=wE={}));var AE;(function(e){e.OWNERSHIP="OWNERSHIP",e.FRACTIONAL="FRACTIONAL"})(AE||(R.PurchaseType=AE={}));var xE;(function(e){e.MANUAL="MANUAL",e.AUTO="AUTO"})(xE||(R.RedeemMode=xE={}));var SE;(function(e){e.REDEEMED="REDEEMED",e.PARTIAL_REDEEM="PARTIAL_REDEEM",e.FAILED="FAILED",e.VERIFICATION_FAILED="VERIFICATION_FAILED"})(SE||(R.RedeemStatus=SE={}));var IE;(function(e){e.SELLER="SELLER",e.OPERATOR="OPERATOR"})(IE||(R.RegisteredBy=IE={}));var DE;(function(e){e.CONFIRMED="CONFIRMED",e.ALREADY_CONFIRMED="ALREADY_CONFIRMED",e.REJECTED="REJECTED"})(DE||(R.ReverifyPurchaseOutcome=DE={}));var OE;(function(e){e.NEW_RELEASE="NEW_RELEASE",e.MEDIA_COVERAGE="MEDIA_COVERAGE",e.ETC="ETC"})(OE||(R.RwaNoticeCategory=OE={}));var NE;(function(e){e.VALID="VALID",e.ABOLISHED="ABOLISHED",e.CLOSED="CLOSED",e.IN_PREPARATION="IN_PREPARATION"})(NE||(R.RwaNoticeStatus=NE={}));var CE;(function(e){e.DOCUMENT="DOCUMENT",e.NOTICE="NOTICE",e.REPORT="REPORT",e.PROMOTION="PROMOTION",e.OTHERS="OTHERS"})(CE||(R.RwaNoticeTag=CE={}));var PE;(function(e){e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE",e.REJECTED="REJECTED"})(PE||(R.SellerStatus=PE={}));var LE;(function(e){e.Year="year",e.Month="month",e.Week="week"})(LE||(R.SettlementPeriodType=LE={}));var ME;(function(e){e.ASC="ASC",e.DESC="DESC"})(ME||(R.SortOrder=ME={}));var kE;(function(e){e.WEEK="WEEK",e.MONTH="MONTH",e.THREE_MONTHS="THREE_MONTHS",e.YEAR="YEAR",e.ALL="ALL"})(kE||(R.StatisticsPeriod=kE={}));var UE;(function(e){e.LINEAR_DECAY="LINEAR_DECAY",e.FIXED_APR="FIXED_APR",e.STEP_DECAY="STEP_DECAY",e.FLAT_DISCOUNT="FLAT_DISCOUNT"})(UE||(R.Strategy=UE={}));var FE;(function(e){e.En="en",e.Jp="jp"})(FE||(R.SupportedLanguage=FE={}));var qE;(function(e){e.APPROVED="APPROVED",e.IN_PROGRESS="IN_PROGRESS",e.REJECTED="REJECTED",e.SKIPPED="SKIPPED"})(qE||(R.TermsConsent=qE={}));var jE;(function(e){e.DRAFT="DRAFT",e.IMAGE_GENERATING="IMAGE_GENERATING",e.METADATA_UPLOADING="METADATA_UPLOADING",e.MINTING="MINTING",e.MINTED="MINTED",e.COMPLETED="COMPLETED"})(jE||(R.TokenPrototypeDtoStatusEnum=jE={}));var BE;(function(e){e.ERC721="ERC_721",e.ERC3525="ERC_3525"})(BE||(R.TokenPrototypeDtoTokenStandardEnum=BE={}));var VE;(function(e){e.OWNERSHIP="OWNERSHIP",e.LEASE="LEASE"})(VE||(R.TokenPrototypeDtoTokenTypeEnum=VE={}));var HE;(function(e){e.DRAFT="DRAFT",e.IMAGE_GENERATING="IMAGE_GENERATING",e.METADATA_UPLOADING="METADATA_UPLOADING",e.MINTING="MINTING",e.MINTED="MINTED",e.COMPLETED="COMPLETED"})(HE||(R.TokenStatus=HE={}));var GE;(function(e){e.ERC721="ERC_721",e.ERC3525="ERC_3525"})(GE||(R.TokenType=GE={}));var $E;(function(e){e.V1="v1",e.V2="v2"})($E||(R.TransferTokenRequestDtoVersionEnum=$E={}));var WE;(function(e){e.ERC721="ERC_721",e.ERC3525="ERC_3525"})(WE||(R.TransferTokenResponseDtoTokenStandardEnum=WE={}));var JE;(function(e){e.OWNERSHIP="OWNERSHIP",e.LEASE="LEASE"})(JE||(R.TransferTokenResponseDtoTokenTypeEnum=JE={}));var KE;(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"})(KE||(R.VehicleAssetStockStatus=KE={}));var YE;(function(e){e.DAY="DAY",e.WEEK="WEEK",e.MONTH="MONTH"})(YE||(R.VehicleOdometerHistoryDtoPeriodEnum=YE={}));var zE;(function(e){e.ODOMETER="ODOMETER",e.BATTERY="BATTERY"})(zE||(R.VehicleOdometerHistoryDtoTypeEnum=zE={}));var XE;(function(e){e.TUKTUK="TUKTUK",e.BIKE="BIKE",e.CAR="CAR",e.TRUCK="TRUCK",e.UNKNOWN="UNKNOWN"})(XE||(R.VehicleProductCategory=XE={}));var QE;(function(e){e[e.Value20=20]="Value20",e[e.Value40=40]="Value40",e[e.Value50=50]="Value50",e[e.Value70=70]="Value70"})(QE||(R.VehicleStatus=QE={}));var ZE;(function(e){e.OWNERSHIP="OWNERSHIP",e.LEASE="LEASE"})(ZE||(R.VehicleTokenType=ZE={}));var eT;(function(e){e.MONTHLY="MONTHLY",e.QUARTERLY="QUARTERLY",e.BI_ANNUAL="BI_ANNUAL"})(eT||(R.XAxisInterval=eT={}));var UL=kL(tt()),Rt;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(Rt||(R.ContentType=Rt={}));var La=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=UL.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)||{},l=this.mergeRequestParams(o,c),u=i||this.format||void 0;return n===Rt.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===Rt.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...l,headers:{...l.headers||{},...n&&n!==Rt.FormData?{"Content-Type":n}:{}},params:s,responseType:u,data:a,url:r}).then(d=>d.data)}};R.HttpClient=La;var su=class extends La{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:Rt.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:Rt.Json,format:"json",...r});postPurchase=(t,r={})=>this.request({path:"/purchase",method:"POST",body:t,secure:!0,type:Rt.Json,format:"json",...r});postPurchaseRedeem=(t,r={})=>this.request({path:"/purchase/redeem",method:"POST",body:t,secure:!0,type:Rt.Json,format:"json",...r});postV1Order=(t,r={})=>this.request({path:"/v1/order",method:"POST",body:t,secure:!0,type:Rt.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:Rt.Json,format:"json",...r});postV2JpRwaVehicleInvestorMessage=(t,r={})=>this.request({path:"/v2/jp/rwa-vehicle/investor-message",method:"POST",body:t,secure:!0,type:Rt.Json,format:"json",...r});putInvestor=(t,r={})=>this.request({path:"/investor",method:"PUT",body:t,secure:!0,type:Rt.Json,format:"json",...r})};R.Api=su});var ou=D(_e=>{"use strict";p();var FL=_e&&_e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_e,"__esModule",{value:!0});_e.Api=_e.HttpClient=_e.ContentType=_e.StockStatus=_e.ProductType=_e.PaymentMethod=_e.OrderStatus=_e.ItemActionType=_e.CouponItemDataTypeEnum=_e.CommonItemDataTypeEnum=_e.CollectionItemDataTypeEnum=void 0;var tT;(function(e){e.COLLECTION="COLLECTION"})(tT||(_e.CollectionItemDataTypeEnum=tT={}));var rT;(function(e){e.COLLECTION="COLLECTION",e.COUPON_CODE="COUPON_CODE"})(rT||(_e.CommonItemDataTypeEnum=rT={}));var nT;(function(e){e.COUPON_CODE="COUPON_CODE"})(nT||(_e.CouponItemDataTypeEnum=nT={}));var sT;(function(e){e.NONE="NONE",e.WEBVIEW="WEBVIEW",e.DAPPVIEW="DAPPVIEW",e.DEEPLINK="DEEPLINK",e.DEEPLINK_WITH_DEFERRED_AUTH="DEEPLINK_WITH_DEFERRED_AUTH"})(sT||(_e.ItemActionType=sT={}));var iT;(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"})(iT||(_e.OrderStatus=iT={}));var aT;(function(e){e.BALANCE_TRANSACTION="BALANCE_TRANSACTION"})(aT||(_e.PaymentMethod=aT={}));var oT;(function(e){e.ITEM="ITEM",e.REDEEMABLE_ITEM="REDEEMABLE_ITEM"})(oT||(_e.ProductType=oT={}));var cT;(function(e){e.PENDING="PENDING",e.READY="READY",e.USED="USED",e.CANCELED="CANCELED",e.EXPIRED="EXPIRED"})(cT||(_e.StockStatus=cT={}));var qL=FL(tt()),zr;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(zr||(_e.ContentType=zr={}));var Ma=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=qL.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)||{},l=this.mergeRequestParams(o,c),u=i||this.format||void 0;return n===zr.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===zr.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...l,headers:{...l.headers||{},...n&&n!==zr.FormData?{"Content-Type":n}:{}},params:s,responseType:u,data:a,url:r}).then(d=>d.data)}};_e.HttpClient=Ma;var au=class extends Ma{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:zr.Json,format:"json",...r});postV1OrdersByIdPayments=(t,r,n={})=>this.request({path:`/v1/orders/${t}/payments`,method:"POST",body:r,secure:!0,type:zr.Json,format:"json",...n})};_e.Api=au});var lu=D(ka=>{"use strict";p();Object.defineProperty(ka,"__esModule",{value:!0});ka.BasicSecurityPolicy=void 0;var jL=jn(),cu=class{securityType=jL.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")}`}};ka.BasicSecurityPolicy=cu});var du=D(Ua=>{"use strict";p();Object.defineProperty(Ua,"__esModule",{value:!0});Ua.JwtSecurityPolicy=void 0;var BL=jn(),Xr=tu(),uu=class{securityType=BL.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,Xr.error)("missing userService baseUrl"),new Error("[JwtSecurityPolicy] missing userService baseUrl");let{refreshToken:r}=t;if(!r)throw(0,Xr.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,Xr.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,Xr.warn)("Wait for refreshing token has been processed. url=%s",i),await this.promiseRefresh?(s.headers.Authorization=`Bearer ${this.accessToken}`,t(s)):((0,Xr.error)("Failed to get refreshed token promised. url=%s",i),Promise.reject(n));let c=()=>{};this.promiseRefresh=new Promise(l=>{c=l});try{let l=await this.requestRefreshToken(this.getSecurityInfo()),u={accessToken:l.accessToken,refreshToken:l.refreshToken},d={accessToken:this.accessToken,refreshToken:this.refreshToken};if(this.setSecurityInfo(u),!r)try{await this.requestConfirmRefreshToken()}catch(m){throw this.setSecurityInfo(d),m}return(0,Xr.warn)("Token refreshed. retry request url=%s",i),this.promiseRefresh=null,this.onChangeSecurityData?.(u),s.headers.Authorization=`Bearer ${u.accessToken}`,c(!0),t(s)}catch(l){l.response.status===401&&((0,Xr.error)("Refresh token is expired"),this.clearSecurityInfo(),this.onRefreshTokenExpired?.()),c(!1)}}return Promise.reject(n)}};Ua.JwtSecurityPolicy=uu});var mu=D(Fa=>{"use strict";p();Object.defineProperty(Fa,"__esModule",{value:!0});Fa.PublicSecurityPolicy=void 0;var VL=jn(),pu=class{securityType=VL.SecurityType.PUBLIC;securityWorker=void 0;setSecurityInfo(t){}getSecurityInfo(){return{}}clearSecurityInfo(){}onApiRejectedInterceptor=void 0};Fa.PublicSecurityPolicy=pu});var jn=D(wt=>{"use strict";p();var HL=wt&&wt.__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]})),gu=wt&&wt.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&HL(t,e,r)};Object.defineProperty(wt,"__esModule",{value:!0});wt.SecurityPolicyFactory=wt.SecurityType=void 0;var GL=lu(),$L=du(),WL=mu();gu(lu(),wt);gu(du(),wt);gu(mu(),wt);var Vs;(function(e){e.JWT="jwt-auth",e.BASIC="basic",e.PUBLIC="public"})(Vs||(wt.SecurityType=Vs={}));var fu=class{static create(t){switch(t.type){case Vs.JWT:return new $L.JwtSecurityPolicy(t);case Vs.BASIC:return new GL.BasicSecurityPolicy;case Vs.PUBLIC:return new WL.PublicSecurityPolicy;default:throw new Error("Invalid Security Type")}}};wt.SecurityPolicyFactory=fu});var _u=D(mt=>{"use strict";p();var JL=mt&&mt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(mt,"__esModule",{value:!0});mt.Api=mt.HttpClient=mt.ContentType=mt.StatisticsTokenType=mt.BlockchainNetwork=void 0;var lT;(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"})(lT||(mt.BlockchainNetwork=lT={}));var uT;(function(e){e.LP="LP"})(uT||(mt.StatisticsTokenType=uT={}));var KL=JL(tt()),Hs;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(Hs||(mt.ContentType=Hs={}));var qa=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=KL.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)||{},l=this.mergeRequestParams(o,c),u=i||this.format||void 0;return n===Hs.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===Hs.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...l,headers:{...l.headers||{},...n&&n!==Hs.FormData?{"Content-Type":n}:{}},params:s,responseType:u,data:a,url:r}).then(d=>d.data)}};mt.HttpClient=qa;var hu=class extends qa{getHealth=(t={})=>this.request({path:"/health",method:"GET",format:"json",...t});getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t})};mt.Api=hu});var Eu=D(j=>{"use strict";p();var YL=j&&j.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(j,"__esModule",{value:!0});j.Api=j.HttpClient=j.ContentType=j.WalletProviderId=j.TadaTonTipRequestStatus=j.TadaRegion=j.TadaCity=j.SubmitRatingDtoTagsEnum=j.SendVerificationCodeStatus=j.RideRequestReceiptStatus=j.RideRequestDetailResponseDtoStatusEnum=j.RideHistoryStatus=j.RecommendPlaceType=j.PutMapSessionResultDtoStatusEnum=j.PlaceMatchType=j.PaymentMethod=j.PartnerRestrictType=j.PartnerDisclaimerType=j.DiscountType=j.DepositRelayRequestStatus=j.CouponDiscountType=j.ChatSenderType=j.ChatMessageType=j.CctpMintRelayStatus=j.CarType=j.BlockchainNetwork=j.AllowanceType=void 0;var dT;(function(e){e.BOTH="BOTH",e.ONLY_PICKUP="ONLY_PICKUP",e.ONLY_DROPOFF="ONLY_DROPOFF"})(dT||(j.AllowanceType=dT={}));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||(j.BlockchainNetwork=pT={}));var mT;(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"})(mT||(j.CarType=mT={}));var fT;(function(e){e.PENDING="PENDING",e.ATTESTED="ATTESTED",e.SUBMITTED="SUBMITTED",e.CONFIRMED="CONFIRMED",e.ALREADY_MINTED="ALREADY_MINTED",e.FAILED="FAILED"})(fT||(j.CctpMintRelayStatus=fT={}));var gT;(function(e){e.TEXT="TEXT",e.IMAGE="IMAGE",e.SYSTEM="SYSTEM"})(gT||(j.ChatMessageType=gT={}));var hT;(function(e){e.RIDER="RIDER",e.DRIVER="DRIVER",e.ADMIN="ADMIN",e.SYSTEM="SYSTEM"})(hT||(j.ChatSenderType=hT={}));var _T;(function(e){e.RATE="RATE",e.AMOUNT="AMOUNT",e.TARGET="TARGET"})(_T||(j.CouponDiscountType=_T={}));var yT;(function(e){e.PENDING="PENDING",e.SUBMITTED="SUBMITTED",e.CONFIRMED="CONFIRMED",e.FAILED="FAILED"})(yT||(j.DepositRelayRequestStatus=yT={}));var ET;(function(e){e.FIXED="FIXED",e.PERCENTAGE="PERCENTAGE"})(ET||(j.DiscountType=ET={}));var TT;(function(e){e.NO_WAITING="NO_WAITING"})(TT||(j.PartnerDisclaimerType=TT={}));var bT;(function(e){e.BOTH="BOTH",e.ONLY_PICKUP="ONLY_PICKUP",e.ONLY_DROPOFF="ONLY_DROPOFF"})(bT||(j.PartnerRestrictType=bT={}));var vT;(function(e){e.BASE_PAY="BASE_PAY",e.X402="X402"})(vT||(j.PaymentMethod=vT={}));var RT;(function(e){e.Exact="exact",e.Approximate="approximate"})(RT||(j.PlaceMatchType=RT={}));var wT;(function(e){e.JwtExpired="jwt_expired",e.Cancelled="cancelled"})(wT||(j.PutMapSessionResultDtoStatusEnum=wT={}));var AT;(function(e){e.DEPARTURE="DEPARTURE",e.DESTINATION="DESTINATION",e.ALL="ALL"})(AT||(j.RecommendPlaceType=AT={}));var xT;(function(e){e.Pending="pending",e.InProgress="in_progress",e.Completed="completed",e.RiderCancelled="rider_cancelled",e.DriverCancelled="driver_cancelled",e.Error="error"})(xT||(j.RideHistoryStatus=xT={}));var ST;(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"})(ST||(j.RideRequestDetailResponseDtoStatusEnum=ST={}));var IT;(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"})(IT||(j.RideRequestReceiptStatus=IT={}));var DT;(function(e){e.SUCCESS="SUCCESS",e.ALREADY_VERIFIED="ALREADY_VERIFIED"})(DT||(j.SendVerificationCodeStatus=DT={}));var OT;(function(e){e.Value401="401",e.Value402="402",e.Value403="403",e.Value404="404",e.Value405="405",e.Value451="451",e.Value452="452",e.Value453="453",e.Value454="454",e.Value455="455",e.Value456="456",e.Value457="457",e.Value458="458",e.Value459="459"})(OT||(j.SubmitRatingDtoTagsEnum=OT={}));var NT;(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"})(NT||(j.TadaCity=NT={}));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.JP="JP",e.GLOBAL="GLOBAL",e.CO="CO",e.NY="NY"})(CT||(j.TadaRegion=CT={}));var PT;(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"})(PT||(j.TadaTonTipRequestStatus=PT={}));var LT;(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"})(LT||(j.WalletProviderId=LT={}));var zL=YL(tt()),Me;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(Me||(j.ContentType=Me={}));var ja=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=zL.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)||{},l=this.mergeRequestParams(o,c),u=i||this.format||void 0;return n===Me.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===Me.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...l,headers:{...l.headers||{},...n&&n!==Me.FormData?{"Content-Type":n}:{}},params:s,responseType:u,data:a,url:r}).then(d=>d.data)}};j.HttpClient=ja;var yu=class extends ja{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});getV1AgentCctpRelayRelayMintById=(t,r={})=>this.request({path:`/v1/agent-cctp-relay/relay-mint/${t}`,method:"GET",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});getV2RidesRequestByIdRating=(t,r={})=>this.request({path:`/v2/rides/request/${t}/rating`,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});postV1AgentCctpRelayRelayMint=(t,r={})=>this.request({path:"/v1/agent-cctp-relay/relay-mint",method:"POST",body:t,secure:!0,type:Me.Json,format:"json",...r});postV1AgentDepositPriceQuote=(t,r={})=>this.request({path:"/v1/agent-deposit/price-quote",method:"POST",body:t,secure:!0,type:Me.Json,format:"json",...r});postV1AgentDepositRelay=(t,r={})=>this.request({path:"/v1/agent-deposit/relay",method:"POST",body:t,secure:!0,type:Me.Json,format:"json",...r});postV1AuthLogin=(t,r={})=>this.request({path:"/v1/auth/login",method:"POST",body:t,type:Me.Json,format:"json",...r});postV1ChatByRideRequestIdImage=(t,r,n={})=>this.request({path:`/v1/chat/${t}/image`,method:"POST",body:r,secure:!0,type:Me.FormData,format:"json",...n});postV1MapSession=(t,r={})=>this.request({path:"/v1/map-session",method:"POST",body:t,secure:!0,type:Me.Json,...r});postV1PhoneVerificationConfirm=(t,r={})=>this.request({path:"/v1/phone-verification/confirm",method:"POST",body:t,secure:!0,type:Me.Json,format:"json",...r});postV1PhoneVerificationSendCode=(t,r={})=>this.request({path:"/v1/phone-verification/send-code",method:"POST",body:t,secure:!0,type:Me.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:Me.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:Me.Json,format:"json",...r});postV2RidesPreRequest=(t,r={})=>this.request({path:"/v2/rides/pre-request",method:"POST",body:t,secure:!0,type:Me.Json,format:"json",...r});postV2RidesRequestByIdCancel=(t,r,n={})=>this.request({path:`/v2/rides/request/${t}/cancel`,method:"POST",body:r,secure:!0,type:Me.Json,format:"json",...n});postV2RidesRequestByIdRating=(t,r,n={})=>this.request({path:`/v2/rides/request/${t}/rating`,method:"POST",body:r,secure:!0,type:Me.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:Me.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:Me.Json,format:"json",...n});putV1MapSessionBySessionIdResult=(t,r,n={})=>this.request({path:`/v1/map-session/${t}/result`,method:"PUT",body:r,type:Me.Json,...n})};j.Api=yu});var bu=D(M=>{"use strict";p();var XL=M&&M.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(M,"__esModule",{value:!0});M.Api=M.HttpClient=M.ContentType=M.WalletStatus=M.VerifiedWalletType=M.UserIdentifierType=M.TokenType=M.ThirdPartySupportedCurrency=M.ThirdPartyIntegrationStatus=M.TadaRegion=M.TadaPointRequestType=M.TadaPointRequestStatus=M.TadaPointActionType=M.TadaPointActionStatus=M.SendTxWalletResultKind=M.SendCallsWalletResultKind=M.QuoteDtoTypeEnum=M.QuorumWalletSessionStatus=M.PurchasableType=M.PurchasablePayMethod=M.PrivyTransactionStatus=M.PartnerType=M.Oauth2TokenType=M.MobileOs=M.KnownAuthClients=M.ForClutchUserIdentifierType=M.EarnEventClaimType=M.EarnEventClaimStatus=M.DepositTrustedDtoTypeEnum=M.CosignSignMethod=M.BlockchainNetwork=M.BalanceSwapType=M.BalanceRequestStatus=M.AppStateEnum=M.AppEventStateResponseDtoStateEnum=void 0;var MT;(function(e){e.REQUIRED="REQUIRED",e.OPTIONAL="OPTIONAL",e.LATEST="LATEST"})(MT||(M.AppEventStateResponseDtoStateEnum=MT={}));var kT;(function(e){e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE"})(kT||(M.AppStateEnum=kT={}));var UT;(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"})(UT||(M.BalanceRequestStatus=UT={}));var FT;(function(e){e.WITHDRAWAL="WITHDRAWAL",e.DEPOSIT="DEPOSIT"})(FT||(M.BalanceSwapType=FT={}));var qT;(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"})(qT||(M.BlockchainNetwork=qT={}));var jT;(function(e){e.PersonalSign="personal_sign",e.EthSignTypedDataV4="eth_signTypedData_v4"})(jT||(M.CosignSignMethod=jT={}));var BT;(function(e){e.TADA_POINT_TELEGRAM="TADA_POINT_TELEGRAM"})(BT||(M.DepositTrustedDtoTypeEnum=BT={}));var VT;(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"})(VT||(M.EarnEventClaimStatus=VT={}));var HT;(function(e){e.CONSTANT="CONSTANT",e.RATIO_DIVISION="RATIO_DIVISION"})(HT||(M.EarnEventClaimType=HT={}));var GT;(function(e){e.GOOGLE="GOOGLE",e.APPLE="APPLE"})(GT||(M.ForClutchUserIdentifierType=GT={}));var $T;(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"})($T||(M.KnownAuthClients=$T={}));var WT;(function(e){e.IOS="IOS",e.ANDROID="ANDROID",e.UNKNOWN="UNKNOWN"})(WT||(M.MobileOs=WT={}));var JT;(function(e){e.Bearer="Bearer"})(JT||(M.Oauth2TokenType=JT={}));var KT;(function(e){e.PARTNER="PARTNER",e.OPERATOR="OPERATOR"})(KT||(M.PartnerType=KT={}));var YT;(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"})(YT||(M.PrivyTransactionStatus=YT={}));var zT;(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"})(zT||(M.PurchasablePayMethod=zT={}));var XT;(function(e){e.MINT_ITEM="MINT_ITEM",e.MINT_BALANCE="MINT_BALANCE",e.NFT_UPGRADE="NFT_UPGRADE"})(XT||(M.PurchasableType=XT={}));var QT;(function(e){e.Pending="pending",e.Done="done",e.Failed="failed"})(QT||(M.QuorumWalletSessionStatus=QT={}));var ZT;(function(e){e.TADA_POINT_TELEGRAM="TADA_POINT_TELEGRAM"})(ZT||(M.QuoteDtoTypeEnum=ZT={}));var eb;(function(e){e.TransactionId="transaction_id"})(eb||(M.SendCallsWalletResultKind=eb={}));var tb;(function(e){e.TxHash="tx_hash",e.UserOperationHash="user_operation_hash"})(tb||(M.SendTxWalletResultKind=tb={}));var rb;(function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.SENT="SENT",e.FINISHED="FINISHED",e.FAILED="FAILED",e.FAILED_PARTIAL="FAILED_PARTIAL"})(rb||(M.TadaPointActionStatus=rb={}));var nb;(function(e){e.LOCK="LOCK",e.UNLOCK="UNLOCK"})(nb||(M.TadaPointActionType=nb={}));var sb;(function(e){e.PENDING="PENDING",e.PROCESSING="PROCESSING",e.SENT="SENT",e.FINISHED="FINISHED",e.FAILED="FAILED",e.FAILED_PARTIAL="FAILED_PARTIAL"})(sb||(M.TadaPointRequestStatus=sb={}));var ib;(function(e){e.LOCK="LOCK",e.UNLOCK="UNLOCK"})(ib||(M.TadaPointRequestType=ib={}));var ab;(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"})(ab||(M.TadaRegion=ab={}));var ob;(function(e){e.CONNECTED="CONNECTED",e.DISCONNECTED="DISCONNECTED"})(ob||(M.ThirdPartyIntegrationStatus=ob={}));var cb;(function(e){e.MVP="MVP",e.TADAP="TADAP",e.ONIONP="ONIONP"})(cb||(M.ThirdPartySupportedCurrency=cb={}));var lb;(function(e){e.COIN="COIN",e.ERC20="ERC20",e.BEP20="BEP20",e.FA2="FA2",e.FA12="FA1.2",e.SERVERED="SERVERED",e.JETTON="JETTON"})(lb||(M.TokenType=lb={}));var ub;(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"})(ub||(M.UserIdentifierType=ub={}));var db;(function(e){e.PRIVY_EXTERNAL="PRIVY_EXTERNAL",e.PRIVY_EMBEDDED="PRIVY_EMBEDDED",e.PRIVY_QUORUM="PRIVY_QUORUM",e.CLUTCH="CLUTCH"})(db||(M.VerifiedWalletType=db={}));var pb;(function(e){e.ACTIVE="ACTIVE",e.INACTIVE="INACTIVE"})(pb||(M.WalletStatus=pb={}));var QL=XL(tt()),F;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(F||(M.ContentType=F={}));var Ba=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=QL.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)||{},l=this.mergeRequestParams(o,c),u=i||this.format||void 0;return n===F.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===F.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...l,headers:{...l.headers||{},...n&&n!==F.FormData?{"Content-Type":n}:{}},params:s,responseType:u,data:a,url:r}).then(d=>d.data)}};M.HttpClient=Ba;var Tu=class extends Ba{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:F.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:F.Json,format:"json",...r});postAuthPartnerChangePassword=(t,r={})=>this.request({path:"/auth/partner/change-password",method:"POST",body:t,type:F.Json,format:"json",...r});postAuthPartnerSignin=(t,r={})=>this.request({path:"/auth/partner/signin",method:"POST",body:t,type:F.Json,format:"json",...r});postAuthPrivyArSignin=(t,r={})=>this.request({path:"/auth/privy/ar/signin",method:"POST",body:t,secure:!0,type:F.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:F.Json,format:"json",...r});postAuthSiweToken=(t,r={})=>this.request({path:"/auth/siwe/token",method:"POST",body:t,type:F.Json,format:"json",...r});postAuthSiweUsers=(t,r={})=>this.request({path:"/auth/siwe/users",method:"POST",body:t,type:F.Json,format:"json",...r});postAuthWeb3Request=(t,r={})=>this.request({path:"/auth/web3/request",method:"POST",body:t,type:F.Json,format:"json",...r});postAuthWeb3Validate=(t,r={})=>this.request({path:"/auth/web3/validate",method:"POST",body:t,type:F.Json,format:"json",...r});postBalanceWithdrawals=(t,r={})=>this.request({path:"/balance/withdrawals",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postFormsById=(t,r,n={})=>this.request({path:`/forms/${t}`,method:"POST",body:r,type:F.Json,format:"json",...n});postFormsByIdInventory=(t,r,n={})=>this.request({path:`/forms/${t}/inventory`,method:"POST",body:r,type:F.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:F.Json,...n});postGamesDemocopterResultsByGameResultIdTwitterShareValidate=(t,r,n={})=>this.request({path:`/games/democopter/results/${t}/twitter/share/validate`,method:"POST",body:r,secure:!0,type:F.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:F.Json,format:"json",...r});postGamesUserResult=(t,r={})=>this.request({path:"/games/user/result",method:"POST",body:t,secure:!0,type:F.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:F.Json,format:"json",...r});postQuorumWalletQuorum=(t,r={})=>this.request({path:"/quorum-wallet/quorum",method:"POST",body:t,type:F.Json,format:"json",...r});postQuorumWalletRegister=(t,r={})=>this.request({path:"/quorum-wallet/register",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postQuorumWalletSendcalls=(t,r={})=>this.request({path:"/quorum-wallet/sendcalls",method:"POST",body:t,type:F.Json,format:"json",...r});postQuorumWalletSendtx=(t,r={})=>this.request({path:"/quorum-wallet/sendtx",method:"POST",body:t,type:F.Json,format:"json",...r});postQuorumWalletSession=(t,r={})=>this.request({path:"/quorum-wallet/session",method:"POST",body:t,type:F.Json,format:"json",...r});postQuorumWalletValidate=(t,r={})=>this.request({path:"/quorum-wallet/validate",method:"POST",body:t,type:F.Json,format:"json",...r});postUsersCurrentWallet=(t,r={})=>this.request({path:"/users/current/wallet",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postUsersCurrentWalletBidSignature=(t,r={})=>this.request({path:"/users/current/wallet/bidSignature",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postUsersCurrentWalletSign=(t,r={})=>this.request({path:"/users/current/wallet/sign",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postUsersEmailMe=(t,r={})=>this.request({path:"/users/email/me",method:"POST",body:t,secure:!0,type:F.Json,...r});postUsersReferrer=(t,r={})=>this.request({path:"/users/referrer",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV1Accounts=(t,r={})=>this.request({path:"/v1/accounts",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV1AccountsCheck=(t,r={})=>this.request({path:"/v1/accounts/check",method:"POST",body:t,secure:!0,type:F.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:F.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:F.Json,format:"json",...r});postV1MobilesCurrent=(t,r={})=>this.request({path:"/v1/mobiles/current",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV1ThirdPartyByAppIdConnect=(t,r,n={})=>this.request({path:`/v1/third-party/${t}/connect`,method:"POST",body:r,secure:!0,type:F.Json,format:"json",...n});postV1ThirdPartyByAppIdConnectCheck=(t,r,n={})=>this.request({path:`/v1/third-party/${t}/connect/check`,method:"POST",body:r,secure:!0,type:F.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:F.Json,format:"json",...r});postV21Accounts=(t,r={})=>this.request({path:"/v2.1/accounts",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV21AccountsRestore=(t,r={})=>this.request({path:"/v2.1/accounts/restore",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV2Accounts=(t,r={})=>this.request({path:"/v2/accounts",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV2AccountsCheck=(t,r={})=>this.request({path:"/v2/accounts/check",method:"POST",body:t,secure:!0,type:F.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:F.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:F.Json,format:"json",...r});postV2AuthAllowedJwt=(t,r={})=>this.request({path:"/v2/auth/allowed-jwt",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV2BalanceMvpSwapWithdrawalRequests=(t,r={})=>this.request({path:"/v2/balance/mvp/swap/withdrawal-requests",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV2BalanceMvpTransfer=(t,r={})=>this.request({path:"/v2/balance/mvp/transfer",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV2Mobiles=(t,r={})=>this.request({path:"/v2/mobiles",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV2ThirdPartyByAppIdConnect=(t,r,n={})=>this.request({path:`/v2/third-party/${t}/connect`,method:"POST",body:r,secure:!0,type:F.Json,format:"json",...n});postV2ThirdPartyByAppIdConnectCheck=(t,r,n={})=>this.request({path:`/v2/third-party/${t}/connect/check`,method:"POST",body:r,secure:!0,type:F.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:F.Json,format:"json",...r});postV3BalanceMvpSwapDepositRequests=(t,r={})=>this.request({path:"/v3/balance/mvp/swap/deposit-requests",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV3BalanceMvpSwapDepositRequestsPrecheck=(t,r={})=>this.request({path:"/v3/balance/mvp/swap/deposit-requests/precheck",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV3ThirdPartyBalanceCurrent=(t,r={})=>this.request({path:"/v3/third-party/balance/current",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV3ThirdPartyUsersBalanceCurrent=(t,r={})=>this.request({path:"/v3/third-party/users/balance/current",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV3ThirdPartyUsersBalanceTransfer=(t,r={})=>this.request({path:"/v3/third-party/users/balance/transfer",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postV3Wallets=(t,r={})=>this.request({path:"/v3/wallets",method:"POST",body:t,secure:!0,type:F.Json,format:"json",...r});postWaitinglistSignature=(t,r={})=>this.request({path:"/waitinglist/signature",method:"POST",body:t,type:F.Json,format:"json",...r});putV1AccountsSs=(t,r={})=>this.request({path:"/v1/accounts/ss",method:"PUT",body:t,secure:!0,type:F.Json,...r});putV2AccountsSs=(t,r={})=>this.request({path:"/v2/accounts/ss",method:"PUT",body:t,secure:!0,type:F.Json,...r})};M.Api=Tu});var Ru=D(Q=>{"use strict";p();var ZL=Q&&Q.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Q,"__esModule",{value:!0});Q.Api=Q.HttpClient=Q.ContentType=Q.VehicleSubscriptionStatus=Q.VehicleStatisticsType=Q.TadaRideAbstractV2DtoRegionEnum=Q.TadaRideAbstractDtoRegionEnum=Q.TadaRegion=Q.RwaNoticeCategory=Q.RideStatusAbstract=Q.RidePointTypeEnum=Q.Period=Q.OnionStationType=Q.OnionStationStatus=Q.GetV1DepinVehiclesDashParamsVehicleSeriesEnum=Q.DepinVehiclesFilterEnum=Q.DepinVehicleType=Q.ChargerStatus=Q.BlockchainNetwork=void 0;var mb;(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"})(mb||(Q.BlockchainNetwork=mb={}));var fb;(function(e){e.FULLY_CHARGED="FULLY_CHARGED",e.CHARGING="CHARGING",e.PROBLEM="PROBLEM",e.NO_BATTERY="NO_BATTERY",e.OFF="OFF"})(fb||(Q.ChargerStatus=fb={}));var gb;(function(e){e.X1="X1",e.T1="T1",e.X2="X2"})(gb||(Q.DepinVehicleType=gb={}));var hb;(function(e){e.ALL="ALL",e.VEHICLE_ON="VEHICLE_ON",e.VEHICLE_OFF="VEHICLE_OFF"})(hb||(Q.DepinVehiclesFilterEnum=hb={}));var _b;(function(e){e.ALL="ALL",e.T1="T1",e.X="X"})(_b||(Q.GetV1DepinVehiclesDashParamsVehicleSeriesEnum=_b={}));var yb;(function(e){e.ON="ON",e.OFF="OFF"})(yb||(Q.OnionStationStatus=yb={}));var Eb;(function(e){e.HUB="HUB",e.PARTNER="PARTNER",e.FACTORY="FACTORY",e.SERVICE_CENTER="SERVICE_CENTER",e.MEGA="MEGA",e.MINI="MINI"})(Eb||(Q.OnionStationType=Eb={}));var Tb;(function(e){e.DAY="DAY",e.WEEK="WEEK",e.MONTH="MONTH"})(Tb||(Q.Period=Tb={}));var bb;(function(e){e.PICKUP="PICKUP",e.DROPOFF="DROPOFF"})(bb||(Q.RidePointTypeEnum=bb={}));var vb;(function(e){e.PENDING="PENDING",e.MATCHED="MATCHED"})(vb||(Q.RideStatusAbstract=vb={}));var Rb;(function(e){e.NEW_RELEASE="NEW_RELEASE",e.MEDIA_COVERAGE="MEDIA_COVERAGE",e.ETC="ETC"})(Rb||(Q.RwaNoticeCategory=Rb={}));var wb;(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"})(wb||(Q.TadaRegion=wb={}));var Ab;(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"})(Ab||(Q.TadaRideAbstractDtoRegionEnum=Ab={}));var xb;(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"})(xb||(Q.TadaRideAbstractV2DtoRegionEnum=xb={}));var Sb;(function(e){e.ODOMETER="ODOMETER",e.BATTERY="BATTERY"})(Sb||(Q.VehicleStatisticsType=Sb={}));var Ib;(function(e){e.ON_TIME="ON_TIME",e.OVERDUE="OVERDUE",e.FINISHED="FINISHED",e.CANCELLED="CANCELLED"})(Ib||(Q.VehicleSubscriptionStatus=Ib={}));var eM=ZL(tt()),pr;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(pr||(Q.ContentType=pr={}));var Va=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=eM.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)||{},l=this.mergeRequestParams(o,c),u=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({...l,headers:{...l.headers||{},...n&&n!==pr.FormData?{"Content-Type":n}:{}},params:s,responseType:u,data:a,url:r}).then(d=>d.data)}};Q.HttpClient=Va;var vu=class extends Va{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:pr.Json,format:"json",...r});postVehicleBatterySwap=(t,r={})=>this.request({path:"/vehicle/battery/swap",method:"POST",body:t,secure:!0,type:pr.Json,format:"json",...r});postVehicleSubscription=(t,r={})=>this.request({path:"/vehicle/subscription",method:"POST",body:t,secure:!0,type:pr.Json,format:"json",...r});postVehicleSubscriptionUpdate=(t,r={})=>this.request({path:"/vehicle/subscription/update",method:"POST",body:t,secure:!0,type:pr.Json,format:"json",...r});postVehicleTestS2SHmac=(t={})=>this.request({path:"/vehicle-test/s2s-hmac",method:"POST",secure:!0,format:"json",...t})};Q.Api=vu});var Au=D(ft=>{"use strict";p();var tM=ft&&ft.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ft,"__esModule",{value:!0});ft.Api=ft.HttpClient=ft.ContentType=ft.CheckPointId=ft.BlockchainNetwork=void 0;var Db;(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"})(Db||(ft.BlockchainNetwork=Db={}));var Ob;(function(e){e.CONFIRMED="CONFIRMED",e.LATEST="LATEST",e.PARSED_LATEST="PARSED_LATEST"})(Ob||(ft.CheckPointId=Ob={}));var rM=tM(tt()),Gs;(function(e){e.Json="application/json",e.FormData="multipart/form-data",e.UrlEncoded="application/x-www-form-urlencoded",e.Text="text/plain"})(Gs||(ft.ContentType=Gs={}));var Ha=class{instance;securityData=null;securityWorker;secure;format;constructor({securityWorker:t,secure:r,format:n,...s}={}){this.instance=rM.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)||{},l=this.mergeRequestParams(o,c),u=i||this.format||void 0;return n===Gs.FormData&&a&&a!==null&&typeof a=="object"&&(a=this.createFormData(a)),n===Gs.Text&&a&&a!==null&&typeof a!="string"&&(a=JSON.stringify(a)),this.instance.request({...l,headers:{...l.headers||{},...n&&n!==Gs.FormData?{"Content-Type":n}:{}},params:s,responseType:u,data:a,url:r}).then(d=>d.data)}};ft.HttpClient=Ha;var wu=class extends Ha{getMetrics=(t={})=>this.request({path:"/metrics",method:"GET",...t})};ft.Api=wu});var Cb=D(ne=>{"use strict";p();var Nb=ne&&ne.__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]})),nM=ne&&ne.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),gt=ne&&ne.__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"&&Nb(r,t,n[s]);return nM(r,t),r}})(),sM=ne&&ne.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Nb(t,e,r)};Object.defineProperty(ne,"__esModule",{value:!0});ne.DataAttestationService=ne.StatisticsService=ne.MusubiService=ne.TadaTonService=ne.WatcherWorker=ne.VehicleOracleService=ne.UserService=ne.SaleService=ne.PushService=ne.ImageFactoryService=ne.ClutchService=ne.AmbTelemetryService=ne.ActivityService=ne.Bep20SwapService=void 0;var iM=Gl(),aM=Wl(),oM=Kl(),cM=zl(),lM=Ql(),uM=eu(),dM=tu(),pM=nu(),mM=iu(),fM=ou(),gM=jn(),hM=_u(),_M=Eu(),yM=bu(),EM=Ru(),TM=Au();ne.Bep20SwapService=gt(Kl());ne.ActivityService=gt(Gl());ne.AmbTelemetryService=gt(Wl());ne.ClutchService=gt(zl());ne.ImageFactoryService=gt(eu());ne.PushService=gt(nu());ne.SaleService=gt(ou());ne.UserService=gt(bu());ne.VehicleOracleService=gt(Ru());ne.WatcherWorker=gt(Au());ne.TadaTonService=gt(Eu());ne.MusubiService=gt(iu());ne.StatisticsService=gt(_u());ne.DataAttestationService=gt(Ql());sM(jn(),ne);var bM="en",xu=class e{securityPolicy;clientId;clientVersion;interceptors;services;static getServiceApiConstructor(t){switch(t){case"userService":return yM.Api;case"activityService":return iM.Api;case"ambTelemetryService":return aM.Api;case"saleService":return fM.Api;case"clutchService":return cM.Api;case"pushService":return pM.Api;case"imageFactoryService":return uM.Api;case"vehicleOracleService":return EM.Api;case"watcherWorker":return TM.Api;case"bep20SwapService":return oM.Api;case"tadaTonService":return _M.Api;case"musubiService":return mM.Api;case"statisticsService":return hM.Api;case"dataAttestationService":return lM.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,dM.log)("init, securityType=%s, clientId=%s, clientVersion=%s, baseUrls=%j",t.securityType,t.clientId,t.clientVersion,t.baseUrls),this.interceptors=t.interceptors,this.securityPolicy=gM.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??bM}};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:l,options:u}=o;i.interceptors.request.use(c,l,u)}),this.interceptors?.response&&this.interceptors.response.forEach(o=>{let{onFulfilled:c=d=>d,onRejected:l,options:u}=o;i.interceptors.response.use(c,l,u)});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}};ne.default=xu});p();p();p();import At from"fs";import Vn from"path";import Qb from"crypto";import{spawn as KM}from"child_process";import{recoverMessageAddress as YM,getAddress as zM}from"viem";p();function uc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dc(e){return e==null?"null":String(e)}function tp(e,t){let r=" ".repeat(t),n=[];for(let s of e)if(uc(s)||Array.isArray(s)){let i=pc(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}- ${
|
|
5
|
-
`)?s.push(`${r}${i}: |`,...
|
|
6
|
-
`).map(
|
|
26
|
+
`).map(i=>`${r} ${i}`)):s===""?n.push(`${r}- (none)`):n.push(`${r}- ${dc(s)}`);return n}function pc(e,t){let r=" ".repeat(t);if(uc(e)){let n=Object.keys(e);if(n.length===0)return[`${r}(none)`];let s=[];for(let i of n){let a=e[i];uc(a)?Object.keys(a).length===0?s.push(`${r}${i}: (none)`):(s.push(`${r}${i}:`),s.push(...pc(a,t+1))):Array.isArray(a)?a.length===0?s.push(`${r}${i}: (none)`):(s.push(`${r}${i}:`),s.push(...tp(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}: ${dc(a)}`)}return s}return Array.isArray(e)?e.length===0?[`${r}(none)`]:tp(e,t):typeof e=="string"&&e.includes(`
|
|
7
29
|
`)?[`${r}|`,...e.split(`
|
|
8
|
-
`).map(n=>`${r} ${n}`)]:[`${r}${
|
|
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
|
-
`
|
|
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}${dc(e)}`]}function rp(e){return pc(e,0).join(`
|
|
31
|
+
`)}var Ei="json";function np(e){Ei=e}function ms(){return Ei}function sp(e){return{json:e.includes("--json"),argv:e.filter(t=>t!=="--json")}}function S(e){console.log(Ei==="json"?JSON.stringify(e,null,2):rp(e))}function b(e){console.error(Ei==="json"?JSON.stringify(e):rp(e))}p();import gc from"fs";import kr from"path";import{fileURLToPath as vS}from"url";p();import ip from"os";import pn from"path";function pS(e){return e.startsWith("~/")?pn.join(ip.homedir(),e.slice(2)):pn.resolve(e)}function ye(){return pS(process.env.AMB_RIDE_STATE_DIR??pn.join(ip.homedir(),".amb"))}function mn(){return pn.join(ye(),"state","data")}function ap(){return pn.join(ye(),"state","keys")}function Ti(e){return pn.join(e,".tada-state")}p();import se from"fs";import Lt from"path";import mS from"crypto";function op(e){return mS.createHash("sha256").update(se.readFileSync(e)).digest("hex")}function lp(e,t){let r=se.readdirSync(e).sort(),n=se.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=Lt.join(e,s),a=Lt.join(t,s),o=se.lstatSync(i),c=se.lstatSync(a);if(o.isSymbolicLink()||c.isSymbolicLink())throw new Error("UNSAFE_STATE_ENTRY: skill-local symlink");if(o.isDirectory()&&c.isDirectory()){lp(i,a);continue}if(!o.isFile()||!c.isFile()||op(i)!==op(a))throw new Error("MIGRATION_VALIDATION_FAILED: skill-local content mismatch")}}function up(e){for(let r of se.readdirSync(e)){let n=Lt.join(e,r);if(se.lstatSync(n).isDirectory())up(n);else{let i=se.openSync(n,"r");try{se.fsyncSync(i)}finally{se.closeSync(i)}}}let t=se.openSync(e,"r");try{se.fsyncSync(t)}finally{se.closeSync(t)}}function cp(e){let t=`${e}.${process.pid}.tmp`;se.writeFileSync(t,new Date().toISOString(),{flag:"wx",mode:384});let r=se.openSync(t,"r");try{se.fsyncSync(r)}finally{se.closeSync(r)}se.renameSync(t,e);let n=se.openSync(Lt.dirname(e),"r");try{se.fsyncSync(n)}finally{se.closeSync(n)}}function bi(e,t){let r=Lt.join(t,".migrated-from-legacy");if(se.existsSync(r))return{migrated:!1,reason:"already-migrated"};if(!se.existsSync(e))return{migrated:!1,reason:"no-legacy"};let n=Lt.join(t,"data");if(se.existsSync(Lt.join(n,"tada-ride-agent.db")))return se.mkdirSync(t,{recursive:!0}),cp(r),{migrated:!1,reason:"target-already-populated"};if(se.existsSync(t))throw new Error("MIGRATION_CONFLICT: partial intermediate legacy state");let s=`${t}.skill-migrating`;se.mkdirSync(Lt.dirname(t),{recursive:!0,mode:448}),se.existsSync(s)&&se.rmSync(s,{recursive:!0}),se.mkdirSync(s,{recursive:!1,mode:448});try{for(let a of["data","keys"]){let o=Lt.join(e,a);if(!se.existsSync(o))continue;let c=Lt.join(s,a);se.cpSync(o,c,{recursive:!0,errorOnExist:!0,force:!1}),lp(o,c)}up(s),se.renameSync(s,t);let i=se.openSync(Lt.dirname(t),"r");try{se.fsyncSync(i)}finally{se.closeSync(i)}}catch(i){throw se.existsSync(s)&&se.rmSync(s,{recursive:!0}),i}return cp(r),{migrated:!0,reason:"copied"}}p();var fS=/^\d+\.\d+\.\d+$/,dp=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function st(e,t){return new Error(`Invalid AmbBuildConfig at ${e}: ${t}`)}function ir(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw st(t,"expected an object");return e}function Er(e,t,r){let n=new Set(t),s=Object.keys(e).filter(a=>!n.has(a)),i=t.filter(a=>!dp(e,a));if(s.length>0)throw st(r,`unknown field ${s[0]}`);if(i.length>0)throw st(`${r}.${i[0]}`,"is required")}function we(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw st(t,r?"expected a string":"expected a non-empty string");return e}function mc(e,t){let r=we(e,t);if(!fS.test(r))throw st(t,"expected stable three-part SemVer");return r}function fs(e,t,r={}){if(typeof e!="number"||!Number.isFinite(e))throw st(t,"expected a finite number");if(r.integer&&!Number.isInteger(e))throw st(t,"expected an integer");if(r.min!==void 0&&e<r.min)throw st(t,`must be >= ${r.min}`);if(r.max!==void 0&&e>r.max)throw st(t,`must be <= ${r.max}`);return e}function gS(e,t){if(!Array.isArray(e)||e.length===0)throw st(t,"expected a non-empty string array");return e.map((r,n)=>we(r,`${t}[${n}]`))}function hS(e,t){let r=ir(e,t),n={};for(let[s,i]of Object.entries(r)){if(s.length===0)throw st(t,"contains an empty key");n[s]=we(i,`${t}.${s}`)}return n}function _S(e){let t=ir(e,"bridgePolicy");Er(t,["minimumUsdc","maxFeeBufferPct","burnGraceBlocks","mintMaxAttempts","leaseSeconds","logChunkBlocks"],"bridgePolicy");let r=we(t.minimumUsdc,"bridgePolicy.minimumUsdc"),n=Number(r);if(!Number.isFinite(n)||n<0)throw st("bridgePolicy.minimumUsdc","expected a non-negative decimal number");return{minimumUsdc:r,maxFeeBufferPct:fs(t.maxFeeBufferPct,"bridgePolicy.maxFeeBufferPct",{min:0,max:100}),burnGraceBlocks:fs(t.burnGraceBlocks,"bridgePolicy.burnGraceBlocks",{integer:!0,min:1}),mintMaxAttempts:fs(t.mintMaxAttempts,"bridgePolicy.mintMaxAttempts",{integer:!0,min:1}),leaseSeconds:fs(t.leaseSeconds,"bridgePolicy.leaseSeconds",{integer:!0,min:1}),logChunkBlocks:fs(t.logChunkBlocks,"bridgePolicy.logChunkBlocks",{integer:!0,min:1})}}function pp(e){if(typeof e!="object"||e===null||Object.isFrozen(e))return e;for(let t of Object.values(e))pp(t);return Object.freeze(e)}function yS(e){let t=ir(e,"buildConfig");Er(t,["services","networks","providers","artifact","install","bridgePolicy"],"buildConfig");let r=ir(t.services,"services");Er(r,["authServerUrl","ambTelemetryServiceUrl","authWebappUrl","privyAppId","cryptoGatewayUrl","memberGatewayUrls","defaultRegion"],"services");let n=ir(t.networks,"networks");Er(n,["depositNetworks","paymentNetwork","paymentCurrency","paymentUsdcAddress","bridgeSource","bridgeDestination"],"networks");let s=ir(t.providers,"providers");Er(s,["tada"],"providers");let i=ir(s.tada,"providers.tada");Er(i,["memberClientId","memberClientSecret"],"providers.tada");let a=ir(t.artifact,"artifact");Er(a,["cliVersion","gitSha"],"artifact");let o=ir(t.install,"install"),c=we(o.mode,"install.mode");if(c!=="git"&&c!=="npm")throw st("install.mode","expected git or npm");Er(o,c==="git"?["mode","repoBranch","repoUrl","expectedCliSha","minimumCliVersion"]:["mode","repoBranch","expectedCliSha","minimumCliVersion"],"install");let l=we(o.expectedCliSha,"install.expectedCliSha",c==="npm"),u=hS(r.memberGatewayUrls,"services.memberGatewayUrls"),d=we(r.defaultRegion,"services.defaultRegion");if(!dp(u,d))throw st("services.defaultRegion","must name a memberGatewayUrls entry");return pp({services:{authServerUrl:we(r.authServerUrl,"services.authServerUrl"),ambTelemetryServiceUrl:we(r.ambTelemetryServiceUrl,"services.ambTelemetryServiceUrl"),authWebappUrl:we(r.authWebappUrl,"services.authWebappUrl"),privyAppId:we(r.privyAppId,"services.privyAppId"),cryptoGatewayUrl:we(r.cryptoGatewayUrl,"services.cryptoGatewayUrl"),memberGatewayUrls:u,defaultRegion:d},networks:{depositNetworks:gS(n.depositNetworks,"networks.depositNetworks"),paymentNetwork:we(n.paymentNetwork,"networks.paymentNetwork"),paymentCurrency:we(n.paymentCurrency,"networks.paymentCurrency"),paymentUsdcAddress:we(n.paymentUsdcAddress,"networks.paymentUsdcAddress"),bridgeSource:we(n.bridgeSource,"networks.bridgeSource",!0),bridgeDestination:we(n.bridgeDestination,"networks.bridgeDestination",!0)},providers:{tada:{memberClientId:we(i.memberClientId,"providers.tada.memberClientId",!0),memberClientSecret:we(i.memberClientSecret,"providers.tada.memberClientSecret",!0)}},artifact:{cliVersion:mc(a.cliVersion,"artifact.cliVersion"),gitSha:we(a.gitSha,"artifact.gitSha")},install:c==="git"?{mode:"git",repoBranch:we(o.repoBranch,"install.repoBranch"),repoUrl:we(o.repoUrl,"install.repoUrl"),expectedCliSha:l,minimumCliVersion:mc(o.minimumCliVersion,"install.minimumCliVersion")}:{mode:"npm",repoBranch:we(o.repoBranch,"install.repoBranch"),expectedCliSha:l,minimumCliVersion:mc(o.minimumCliVersion,"install.minimumCliVersion")},bridgePolicy:_S(t.bridgePolicy)})}var ES,vi;function xe(){return vi||(vi=yS(ES??_),vi)}p();var TS={AMB_RIDE_STATE_DIR:"stateDir",AMB_RIDE_PASSPHRASE:"passphrase",AMB_RIDE_LOG_LEVEL:"logLevel",AMB_RIDE_OPENCLAW_CLI:"openclawCli"},bS=/^AMB_RIDE_RPC_URL_([A-Z0-9_]+)$/,mp=/^[A-Z0-9]+(?:_[A-Z0-9]+)*$/;function Ri(e){let t=e.toUpperCase();if(!mp.test(t))throw new Error(`Invalid Ambient Ride RPC network: ${e}`);return`AMB_RIDE_RPC_URL_${t}`}function Mr(e=process.env){let t={rpcUrls:{}};for(let[r,n]of Object.entries(e)){if(!r.startsWith("AMB_RIDE_"))continue;let s=TS[r];if(s!==void 0){n!==void 0&&(t[s]=n);continue}let i=bS.exec(r);if(i&&mp.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 fc(e,t,r){return t.rpcUrls[e]??r[e]}function RS(e){let t=e;for(;;){if(gc.existsSync(kr.join(t,"SKILL.md")))return t;let r=kr.dirname(t);if(r===t)break;t=r}return kr.dirname(kr.dirname(e))}function wS(){let e=kr.dirname(vS(import.meta.url));return RS(e)}function AS(e){if(!gc.existsSync(e))return{};let t={};for(let r of gc.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 fn={BASE_SEPOLIA:84532,BASE:8453,ETHEREUM:1,ETHEREUM_SEPOLIA:11155111},wi={BASE_SEPOLIA:"https://sepolia.base.org",BASE:"https://mainnet.base.org",ETHEREUM:"https://eth.drpc.org",ETHEREUM_SEPOLIA:"https://sepolia.drpc.org"},gp={BASE_SEPOLIA:"0xcC1F1b0C7b505D94ee04E028eA19f81464AdefA9",ETHEREUM:"0xA4bAE3CeFA30F6A263402D388261c611663b2683"},xS={BASE_SEPOLIA:"0x3B7E10b1AEA923E13e2716b538789b6EC9F0A4c1",ETHEREUM:"0x5c23a543963A181267d5790d61eBa55b66246f0a"},Ai={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}},SS=Object.freeze({chainId:84532,rpcUrl:wi.BASE_SEPOLIA,router:gp.BASE_SEPOLIA,mvlToken:"0x0283F3bDE2566C41F88C10E269cE9a59e3C97700",usdcToken:Ai.BASE_SEPOLIA.usdc}),gj=Object.freeze({chainId:11155111,rpcUrl:"https://ethereum-sepolia-rpc.publicnode.com",mvlToken:"0x3cf4ccf7Ec4Bb094d1504D1315057A46005d5065",l1StandardBridge:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",baseMvlToken:SS.mvlToken});function IS(e){return Ai[e]}var DS=Object.entries(Ai).filter(([,e])=>e.irisBaseUrl).map(([e])=>e);function OS(e,t=Mr()){return fc(e,t,wi)}function fp(e,t,r,n=Mr()){if(!t)return{error:`${e} is not set \u2014 this build has no USDC bridge configured.`};let s=IS(t);if(!s)return{error:`${e}=${t} is not a CCTP network. Known networks: ${Object.keys(Ai).join(", ")}.`};let i=fn[t];if(i===void 0)return{error:`${e}=${t} has no chain id configured. Known networks: ${Object.keys(fn).join(", ")}.`};if(r==="source"&&!s.irisBaseUrl)return{error:`${e}=${t} is not supported as a bridge source (no Circle attestation host). Supported sources: ${DS.join(", ")}.`};let a=OS(t,n);if(!a)return{error:`No RPC URL for ${t}. Set ${Ri(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 NS(e=xe().networks.bridgeSource,t=xe().networks.bridgeDestination,r=Mr()){let n=fp("bridge source",e,"source",r);if(!n.endpoint||!n.net)return{error:n.error??"Bridge source could not be resolved."};let s=fp("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 CS(e,t,r){if(r===void 0)return{...e};if(t!=="dev")throw new Error("AMB_DEV_SERVICES_ORIGIN is accepted only by development builds");if(r.length===0||r.trim()!==r)throw new Error("AMB_DEV_SERVICES_ORIGIN must be an exact loopback HTTP origin");let n;try{n=new URL(r)}catch{throw new Error("AMB_DEV_SERVICES_ORIGIN must be a valid loopback HTTP origin")}let s=n.hostname==="127.0.0.1"||n.hostname==="[::1]",i=Number(n.port),a=n.pathname==="/"&&n.search===""&&n.hash==="";if(n.protocol!=="http:"||!s||!n.port||!Number.isInteger(i)||i<=0||i>65535||n.username!==""||n.password!==""||!a||n.href!==`${n.origin}/`)throw new Error("AMB_DEV_SERVICES_ORIGIN must be origin-only http on numeric loopback with an explicit nonzero port");return{appServerUrl:n.origin,gatewayServerUrl:n.origin}}function O(){let e=xe(),t=wS();bi(Ti(t),kr.join(ye(),"state"));let r=mn(),n=ap(),s=AS(kr.join(r,".env"));for(let[h,E]of Object.entries(s))process.env[h]===void 0&&(process.env[h]=E);let i=Mr();function a(h,E){if(h)return h;b({error:`Missing required environment variable: ${E} \u2014 local state is not initialised. Run \`amb install\`.`}),process.exit(1)}let c=e.networks.depositNetworks.map(h=>{let E=i.rpcUrls[h]??wi[h];E||(b({error:`Missing ${Ri(h)} and no default RPC URL for network ${h}`}),process.exit(1));let T=gp[h];T||(b({error:`No v2 DepositRouter address configured for network ${h}. Mainnet \uC8FC\uC18C\uB294 Kaelie \uCE21 v2 \uBC30\uD3EC \uD6C4 \uCD94\uAC00.`}),process.exit(1));let w=xS[h];w||(b({error:`No v2 AgentDepositV2 ledger address for network ${h}.`}),process.exit(1));let v=fn[h];return v===void 0&&(b({error:`Unknown network name: ${h}. Known networks: ${Object.keys(fn).join(", ")}`}),process.exit(1)),{name:h,rpcUrl:E,chainId:v,depositContract:T,agentDepositLedger:w}}),l=e.networks.paymentNetwork,u=fn[l];u===void 0&&(b({error:`Unknown payment network name: ${l}. Known networks: ${Object.keys(fn).join(", ")}`}),process.exit(1));let d=fc(l,i,wi);d||(b({error:`Missing ${Ri(l)} and no default RPC URL for payment network ${l}`}),process.exit(1));let m=NS(e.networks.bridgeSource,e.networks.bridgeDestination,i),f=e.bridgePolicy,g=CS({appServerUrl:e.services.authServerUrl,gatewayServerUrl:e.services.cryptoGatewayUrl},e.install.repoBranch,process.env.AMB_DEV_SERVICES_ORIGIN);return{appServerUrl:g.appServerUrl,webappUrl:e.services.authWebappUrl,privyAppId:e.services.privyAppId,dataDir:r,keysDir:n,depositNetworks:c,gatewayServerUrl:g.gatewayServerUrl,passphrase:a(i.passphrase,"AMB_RIDE_PASSPHRASE"),payCurrency:e.networks.paymentCurrency,paymentNetwork:l,paymentRpcUrl:d,paymentChainId:u,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 hp(e){return e.riderCliApp.clientId!==""&&e.riderCliApp.clientSecret!==""}function gs(){let e=xe(),t=e.providers.tada.memberClientId,r=e.providers.tada.memberClientSecret,n=e.services.memberGatewayUrls[e.services.defaultRegion]??"";return t!==""&&r!==""&&n!==""}p();import MS from"better-sqlite3";import Si from"fs";import Ii from"path";p();import ar from"fs";import xi from"path";import PS from"better-sqlite3";var yp="tada-ride-agent.db",_p="ambient-ride.db",Ep=["","-wal","-shm","-journal"];function LS(e){let t=ar.openSync(e,"r");try{ar.fsyncSync(t)}finally{ar.closeSync(t)}}function hs(e){return Ep.some(t=>ar.existsSync(xi.join(e,`${yp}${t}`)))}function Tp(e){if(!hs(e))return!1;ar.mkdirSync(e,{recursive:!0,mode:448});for(let n of Ep){let s=xi.join(e,`${yp}${n}`),i=xi.join(e,`${_p}${n}`);if(ar.existsSync(s)){if(ar.existsSync(i))throw new Error(`MIGRATION_CONFLICT: both database names exist (${n||"main"})`);ar.renameSync(s,i),LS(e)}}let t=xi.join(e,_p);if(!ar.existsSync(t))throw new Error("MIGRATION_INTERRUPTED: database sidecar exists without main database");let r=new PS(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 bp=Mr().logLevel==="debug";function vp(){return bp}function Et(e){bp&&process.stderr.write(e)}var K;function N(e){let t=Ii.dirname(e),r=Ii.basename(t)==="state"?Ii.dirname(t):t;if(Si.existsSync(`${r}.amb-migration-quiesced`))throw new Error("MIGRATION_CONFLICT: runtime state is being migrated");Si.existsSync(e)||Si.mkdirSync(e,{recursive:!0});let n=Ii.join(e,"ambient-ride.db");if(!Si.existsSync(n)&&hs(e))throw new Error("LEGACY_AMBIENT_DATABASE: run `amb install` before using the CLI");K=new MS(n),K.pragma("journal_mode = WAL"),K.pragma("foreign_keys = ON"),K.exec(`
|
|
19
33
|
CREATE TABLE IF NOT EXISTS identity (
|
|
20
34
|
id INTEGER PRIMARY KEY,
|
|
21
35
|
privy_user_id TEXT NOT NULL UNIQUE,
|
|
@@ -25,7 +39,7 @@ ${Ln.randomUUID()}
|
|
|
25
39
|
|
|
26
40
|
CREATE TABLE IF NOT EXISTS wallets (
|
|
27
41
|
wallet_address TEXT PRIMARY KEY,
|
|
28
|
-
wallet_type TEXT NOT NULL CHECK(wallet_type IN ('privy', 'external')),
|
|
42
|
+
wallet_type TEXT NOT NULL CHECK(wallet_type IN ('privy', 'external', 'metamask')),
|
|
29
43
|
label TEXT,
|
|
30
44
|
last_valid INTEGER DEFAULT 0,
|
|
31
45
|
invalid_reason TEXT,
|
|
@@ -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,67 @@ ${Ln.randomUUID()}
|
|
|
193
239
|
expires_at INTEGER NOT NULL,
|
|
194
240
|
created_at INTEGER NOT NULL
|
|
195
241
|
);
|
|
196
|
-
|
|
242
|
+
|
|
243
|
+
-- Exact, signed ROUTER_SIG requests waiting for an authoritative terminal
|
|
244
|
+
-- relay result. The composite primary key is intentionally wider than an
|
|
245
|
+
-- amount-specific intent: while one MVL deposit is unresolved, a second
|
|
246
|
+
-- amount for the same wallet/network/token must not be allowed to race it.
|
|
247
|
+
-- There is no wallets FK for the same reason bridge_jobs has none: removing
|
|
248
|
+
-- local wallet metadata must not erase the only recovery handle for an
|
|
249
|
+
-- already-authorized value transfer.
|
|
250
|
+
CREATE TABLE IF NOT EXISTS mvl_relay_submissions (
|
|
251
|
+
wallet_address TEXT NOT NULL,
|
|
252
|
+
network TEXT NOT NULL,
|
|
253
|
+
token_address TEXT NOT NULL,
|
|
254
|
+
amount_raw TEXT NOT NULL,
|
|
255
|
+
body_json TEXT,
|
|
256
|
+
approve_tx TEXT,
|
|
257
|
+
request_id TEXT,
|
|
258
|
+
status TEXT NOT NULL DEFAULT 'PREPARING'
|
|
259
|
+
CHECK(status IN ('PREPARING', 'PREPARED', 'PENDING', 'SUBMITTED')),
|
|
260
|
+
owner_id TEXT,
|
|
261
|
+
lease_expires_at INTEGER,
|
|
262
|
+
wallet_request_kind TEXT CHECK(wallet_request_kind IN ('APPROVE', 'TYPED_DATA')),
|
|
263
|
+
wallet_polling_id TEXT,
|
|
264
|
+
wallet_request_json TEXT,
|
|
265
|
+
client_attempt_id TEXT,
|
|
266
|
+
created_at INTEGER NOT NULL DEFAULT (strftime('%s','now')),
|
|
267
|
+
updated_at INTEGER NOT NULL DEFAULT (strftime('%s','now')),
|
|
268
|
+
PRIMARY KEY (wallet_address, network, token_address),
|
|
269
|
+
CHECK(
|
|
270
|
+
(status = 'PREPARING' AND body_json IS NULL AND owner_id IS NOT NULL AND lease_expires_at IS NOT NULL)
|
|
271
|
+
OR
|
|
272
|
+
(status != 'PREPARING' AND body_json IS NOT NULL AND owner_id IS NULL AND lease_expires_at IS NULL)
|
|
273
|
+
)
|
|
274
|
+
);
|
|
275
|
+
`);try{K.exec(`
|
|
276
|
+
CREATE TABLE IF NOT EXISTS telemetry_deposit_attempts (
|
|
277
|
+
attempt_id TEXT PRIMARY KEY,
|
|
278
|
+
account_id TEXT NOT NULL,
|
|
279
|
+
journey_id TEXT,
|
|
280
|
+
created_at INTEGER NOT NULL,
|
|
281
|
+
started_at INTEGER,
|
|
282
|
+
deposit_network TEXT,
|
|
283
|
+
deposit_token TEXT CHECK(deposit_token IN ('MVL', 'USDC')),
|
|
284
|
+
deposit_path TEXT CHECK(deposit_path IN ('mvl-direct', 'relay')),
|
|
285
|
+
relay_request_id TEXT UNIQUE,
|
|
286
|
+
direct_transaction_id TEXT,
|
|
287
|
+
baseline_active INTEGER CHECK(baseline_active IN (0, 1)),
|
|
288
|
+
terminal_state TEXT CHECK(terminal_state IN ('confirmed', 'failed')),
|
|
289
|
+
updated_at INTEGER NOT NULL
|
|
290
|
+
);
|
|
291
|
+
CREATE TABLE IF NOT EXISTS telemetry_deposit_stages (
|
|
292
|
+
attempt_id TEXT NOT NULL,
|
|
293
|
+
stage TEXT NOT NULL,
|
|
294
|
+
observed_at INTEGER NOT NULL,
|
|
295
|
+
PRIMARY KEY (attempt_id, stage),
|
|
296
|
+
FOREIGN KEY (attempt_id) REFERENCES telemetry_deposit_attempts(attempt_id) ON DELETE CASCADE
|
|
297
|
+
);
|
|
298
|
+
CREATE INDEX IF NOT EXISTS idx_telemetry_deposit_claim
|
|
299
|
+
ON telemetry_deposit_attempts(account_id, journey_id, started_at);
|
|
300
|
+
CREATE INDEX IF NOT EXISTS idx_telemetry_deposit_status
|
|
301
|
+
ON telemetry_deposit_attempts(account_id, deposit_network, terminal_state);
|
|
302
|
+
`)}catch{}K.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='saved_places'").get()&&K.transaction(()=>{K.exec(`
|
|
197
303
|
INSERT INTO places (
|
|
198
304
|
id, wallet_address, label, name, formatted_address,
|
|
199
305
|
latitude, longitude, google_place_id, city, region,
|
|
@@ -214,14 +320,31 @@ ${Ln.randomUUID()}
|
|
|
214
320
|
END AS dedup_key
|
|
215
321
|
FROM saved_places;
|
|
216
322
|
DROP TABLE saved_places;
|
|
217
|
-
`)})(),
|
|
323
|
+
`)})(),K.prepare("PRAGMA table_info(ride_events)").all().some(A=>A.name==="read")||K.exec("ALTER TABLE ride_events ADD COLUMN read INTEGER DEFAULT 0");let a=K.prepare("PRAGMA table_info(jwt_cache)").all();a.some(A=>A.name==="kind")||K.exec("ALTER TABLE jwt_cache ADD COLUMN kind TEXT NOT NULL DEFAULT 'siwe'"),a.some(A=>A.name==="refresh_token")||K.exec("ALTER TABLE jwt_cache ADD COLUMN refresh_token TEXT"),a.some(A=>A.name==="refresh_expires_at")||K.exec("ALTER TABLE jwt_cache ADD COLUMN refresh_expires_at INTEGER"),K.prepare("PRAGMA table_info(bridge_jobs)").all().some(A=>A.name==="relay_request_id")||K.exec("ALTER TABLE bridge_jobs ADD COLUMN relay_request_id TEXT");let c=K.prepare("PRAGMA table_info(mvl_relay_submissions)").all();c.some(A=>A.name==="wallet_request_kind")||K.exec(`ALTER TABLE mvl_relay_submissions ADD COLUMN wallet_request_kind TEXT
|
|
324
|
+
CHECK(wallet_request_kind IN ('APPROVE', 'TYPED_DATA'))`),c.some(A=>A.name==="wallet_polling_id")||K.exec("ALTER TABLE mvl_relay_submissions ADD COLUMN wallet_polling_id TEXT"),c.some(A=>A.name==="wallet_request_json")||K.exec("ALTER TABLE mvl_relay_submissions ADD COLUMN wallet_request_json TEXT"),c.some(A=>A.name==="client_attempt_id")||K.exec("ALTER TABLE mvl_relay_submissions ADD COLUMN client_attempt_id TEXT"),K.prepare("PRAGMA table_info(wallets)").all().some(A=>A.name==="is_active")&&K.exec("ALTER TABLE wallets DROP COLUMN is_active"),K.prepare("PRAGMA table_info(phone_verifications)").all().some(A=>A.name==="wallet_address")||K.exec(`DROP TABLE phone_verifications;
|
|
218
325
|
CREATE TABLE phone_verifications (
|
|
219
326
|
wallet_address TEXT NOT NULL,
|
|
220
327
|
phone TEXT NOT NULL,
|
|
221
328
|
verified_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
222
329
|
PRIMARY KEY (wallet_address, phone),
|
|
223
330
|
FOREIGN KEY (wallet_address) REFERENCES wallets(wallet_address) ON DELETE CASCADE
|
|
224
|
-
);`),
|
|
331
|
+
);`),K.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='active_listeners'").get()&&K.exec("DROP TABLE active_listeners");let m=K.prepare("SELECT sql FROM sqlite_master WHERE type='table' AND name='wallets'").get();if(!!m&&/CHECK\s*\(\s*wallet_type\s+IN/i.test(m.sql)&&!m.sql.includes("'metamask'")){K.pragma("foreign_keys = OFF");try{K.transaction(()=>{K.exec(`
|
|
332
|
+
CREATE TABLE wallets__new (
|
|
333
|
+
wallet_address TEXT PRIMARY KEY,
|
|
334
|
+
wallet_type TEXT NOT NULL CHECK(wallet_type IN ('privy', 'external', 'metamask')),
|
|
335
|
+
label TEXT,
|
|
336
|
+
last_valid INTEGER DEFAULT 0,
|
|
337
|
+
invalid_reason TEXT,
|
|
338
|
+
last_validity_check_at TEXT,
|
|
339
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
340
|
+
);
|
|
341
|
+
INSERT INTO wallets__new
|
|
342
|
+
SELECT wallet_address, wallet_type, label, last_valid, invalid_reason,
|
|
343
|
+
last_validity_check_at, created_at
|
|
344
|
+
FROM wallets;
|
|
345
|
+
DROP TABLE wallets;
|
|
346
|
+
ALTER TABLE wallets__new RENAME TO wallets;
|
|
347
|
+
`);let A=K.pragma("foreign_key_check");if(A.length>0)throw new Error(`WALLETS_MIGRATION_FAILED: rebuilding wallets left ${A.length} dangling foreign-key reference(s); the database is unchanged.`)})()}finally{K.pragma("foreign_keys = ON")}}let h=K.prepare("PRAGMA table_info(tada_members)").all().find(A=>A.name==="phone");h&&h.notnull===1&&K.exec(`
|
|
225
348
|
CREATE TABLE tada_members__new (
|
|
226
349
|
id TEXT PRIMARY KEY,
|
|
227
350
|
phone TEXT,
|
|
@@ -233,9 +356,11 @@ ${Ln.randomUUID()}
|
|
|
233
356
|
INSERT INTO tada_members__new SELECT id, phone, display_name, region, created_at, last_active_at FROM tada_members;
|
|
234
357
|
DROP TABLE tada_members;
|
|
235
358
|
ALTER TABLE tada_members__new RENAME TO tada_members;
|
|
236
|
-
`);let
|
|
359
|
+
`);let E=K.prepare("PRAGMA table_info(ride_requests)").all();E.length>0&&!E.some(A=>A.name==="member_id")&&K.exec(`
|
|
237
360
|
CREATE TABLE ride_requests__new (
|
|
238
361
|
request_id TEXT PRIMARY KEY,
|
|
362
|
+
journey_id TEXT,
|
|
363
|
+
ride_id TEXT,
|
|
239
364
|
wallet_address TEXT,
|
|
240
365
|
member_id TEXT,
|
|
241
366
|
region TEXT NOT NULL,
|
|
@@ -263,87 +388,335 @@ ${Ln.randomUUID()}
|
|
|
263
388
|
FROM ride_requests;
|
|
264
389
|
DROP TABLE ride_requests;
|
|
265
390
|
ALTER TABLE ride_requests__new RENAME TO ride_requests;
|
|
266
|
-
`),
|
|
391
|
+
`);let T=K.prepare("PRAGMA table_info(ride_requests)").all();T.some(A=>A.name==="journey_id")||K.exec("ALTER TABLE ride_requests ADD COLUMN journey_id TEXT"),T.some(A=>A.name==="ride_id")||K.exec("ALTER TABLE ride_requests ADD COLUMN ride_id TEXT"),K.exec(`
|
|
267
392
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_places_dedup ON places(wallet_address, dedup_key);
|
|
268
393
|
CREATE INDEX IF NOT EXISTS idx_places_wallet ON places(wallet_address);
|
|
269
394
|
CREATE INDEX IF NOT EXISTS idx_places_label ON places(wallet_address, label);
|
|
270
395
|
CREATE INDEX IF NOT EXISTS idx_places_hit ON places(wallet_address, hit_count DESC, last_used_at DESC);
|
|
271
396
|
CREATE INDEX IF NOT EXISTS idx_bridge_jobs_wallet_status ON bridge_jobs (wallet_address, status);
|
|
272
|
-
|
|
397
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_mvl_relay_submissions_request
|
|
398
|
+
ON mvl_relay_submissions(request_id) WHERE request_id IS NOT NULL;
|
|
399
|
+
CREATE INDEX IF NOT EXISTS idx_telemetry_links_journey ON telemetry_journey_links(journey_id);
|
|
400
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_telemetry_journey_singletons
|
|
401
|
+
ON telemetry_journey_links(journey_id, link_type)
|
|
402
|
+
WHERE link_type IN ('request', 'ride');
|
|
403
|
+
`);let w=Math.floor(Date.now()/1e3),v=K.prepare(`
|
|
273
404
|
DELETE FROM jwt_cache
|
|
274
405
|
WHERE (kind != 'member' AND expires_at <= ?)
|
|
275
406
|
OR (kind = 'member' AND refresh_expires_at IS NOT NULL AND refresh_expires_at <= ?)
|
|
276
|
-
`).run(
|
|
277
|
-
|
|
407
|
+
`).run(w,w);K.prepare("DELETE FROM search_cache WHERE expires_at <= ?").run(Date.now()),K.prepare("DELETE FROM payment_cache WHERE expires_at <= ?").run(Date.now());try{K.prepare(`
|
|
408
|
+
DELETE FROM telemetry_deposit_attempts
|
|
409
|
+
WHERE COALESCE(started_at, created_at) < ?
|
|
410
|
+
`).run(Date.now()-10080*6e4)}catch{}Et(`[jwt-debug] INIT db=${n} now=${w} cleanup_removed_jwt=${v.changes} pid=${process.pid}
|
|
411
|
+
`)}function x(){if(!K)throw new Error("DB not initialized. Call initDb() first.");return K}p();function Di(e){x().prepare(`
|
|
278
412
|
INSERT OR REPLACE INTO wallets (wallet_address, wallet_type, label)
|
|
279
413
|
VALUES (?, 'privy', ?)
|
|
280
|
-
`).run(e.wallet_address,e.label??null),
|
|
414
|
+
`).run(e.wallet_address,e.label??null),x().prepare(`
|
|
281
415
|
INSERT OR REPLACE INTO privy_wallet_meta (wallet_address, wallet_id, quorum_id, k_i_pub, k_i_key_path)
|
|
282
416
|
VALUES (?, ?, ?, ?, ?)
|
|
283
|
-
`).run(e.wallet_address,e.wallet_id,e.quorum_id,e.k_i_pub,e.k_i_key_path)}function
|
|
284
|
-
INSERT
|
|
285
|
-
VALUES (?, '
|
|
286
|
-
|
|
417
|
+
`).run(e.wallet_address,e.wallet_id,e.quorum_id,e.k_i_pub,e.k_i_key_path)}function Rp(e){x().prepare(`
|
|
418
|
+
INSERT INTO wallets (wallet_address, wallet_type, label)
|
|
419
|
+
VALUES (?, 'metamask', ?)
|
|
420
|
+
ON CONFLICT(wallet_address) DO UPDATE SET
|
|
421
|
+
wallet_type = excluded.wallet_type,
|
|
422
|
+
label = COALESCE(excluded.label, wallets.label)
|
|
423
|
+
`).run(e.wallet_address,e.label??null)}function Oi(){return x().prepare("SELECT * FROM wallets ORDER BY created_at ASC").all()}function Ni(){return x().prepare("SELECT * FROM wallets WHERE last_valid = 1").all()}function Ye(e){return x().prepare("SELECT * FROM wallets WHERE wallet_address = ? COLLATE NOCASE").get(e)}function Tt(e){return x().prepare("SELECT * FROM privy_wallet_meta WHERE wallet_address = ?").get(e)}function or(e,t){x().prepare(`
|
|
287
424
|
UPDATE wallets SET last_valid = 0, invalid_reason = ?, last_validity_check_at = CURRENT_TIMESTAMP
|
|
288
425
|
WHERE wallet_address = ?
|
|
289
|
-
`).run(t,e)}function
|
|
426
|
+
`).run(t,e)}function gn(e){x().prepare(`
|
|
290
427
|
UPDATE wallets SET last_valid = 1, invalid_reason = NULL, last_validity_check_at = CURRENT_TIMESTAMP
|
|
291
428
|
WHERE wallet_address = ?
|
|
292
|
-
`).run(e)}
|
|
429
|
+
`).run(e)}p();p();import{spawnSync as kS}from"child_process";var US=e=>{let t=kS("mm",e,{encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(t.error)throw t.error;return{status:t.status,stdout:t.stdout??"",stderr:t.stderr??""}};function FS(e){if(/Not authenticated/i.test(e))return{code:"MM_NOT_AUTHENTICATED",hint:"run `mm login`, or export MM_CLI_TOKEN for a headless session"};if(/MNEMONIC_LOCKED|password-protected/i.test(e))return{code:"MM_LOCKED",hint:"export MM_PASSWORD to unlock the BYOK mnemonic"};if(/unsupported chain|chain .* not supported/i.test(e))return{code:"MM_CHAIN_UNSUPPORTED",hint:"run `mm chains list` for the supported set"}}function qS(e){let t=[];for(let r of e.split(`
|
|
430
|
+
`)){let n=r.trim();if(n)try{let s=JSON.parse(n);s&&typeof s=="object"&&t.push(s)}catch{}}if(t.length===0)try{let r=JSON.parse(e);r&&typeof r=="object"&&t.push(r)}catch{}return t}function jS(e){let t=e.find(n=>n._summary)?._summary;if(t&&typeof t=="object")return t;let r=e.find(n=>n._notice)?._notice;if(r&&typeof r=="object"){let n=r;return{status:n.kind,pollingId:n.pollingId}}}function wp(e,t=US){let r;try{r=t([...e,"--json"])}catch(a){let o=a;throw o.code==="ENOENT"?new Error("MM_NOT_INSTALLED: the MetaMask Agent Wallet CLI (`mm`) is not on PATH. Install it with `npm i -g @metamask/agentic-cli` (needs Node >= 22.18)."):new Error(`MM_CALL_FAILED: could not run \`mm ${e.join(" ")}\` \u2014 ${o.message}`)}let n=qS(r.stdout),s=n.find(a=>a.ok===!0);if(s)return s.data;let i=jS(n);if(i)return i;if(r.status!==0){let a=FS(r.stderr);throw a?new Error(`${a.code}: ${a.hint}. mm said: ${r.stderr.trim()}`):new Error(`MM_CALL_FAILED: \`mm ${e.join(" ")}\` exited ${r.status}. mm said: ${r.stderr.trim()}`)}throw n.length===0?new Error(`MM_CALL_FAILED: \`mm ${e.join(" ")}\` returned unparseable stdout. stdout: ${r.stdout.slice(0,200)} stderr: ${r.stderr.trim()}`):new Error(`MM_CALL_FAILED: \`mm ${e.join(" ")}\` reported failure. stderr: ${r.stderr.trim()}`)}function Ci(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{130}$/.test(e))throw new Error(`MM_CALL_FAILED: mm returned a signature that is not 65 bytes: ${String(e).slice(0,80)}`);return e.toLowerCase()}var Mt=class extends Error{constructor(r,n,s){super(`MM_REQUEST_${s}: MetaMask request ended with ${s}.`);this.kind=r;this.pollingId=n;this.status=s;this.name="MmRequestTerminalError"}kind;pollingId;status},it=class extends Error{constructor(r,n,s){super(`MM_REQUEST_INDETERMINATE: MetaMask request reported unknown status ${s}; do not submit another request until this exact request is reconciled.`);this.kind=r;this.pollingId=n;this.status=s;this.name="MmRequestIndeterminateError"}kind;pollingId;status},et=class extends Error{constructor(r,n,s){super(`MM_APPROVAL_PENDING: MetaMask is holding this ${s} for approval. Approve it where MetaMask asked, then resume through the owning amb command.`);this.kind=r;this.pollingId=n;this.name="MmApprovalPendingError"}kind;pollingId},Ap=30;function hn(e,t,r,n){let s=e.pollingId??n??e.requestId,i=new Set(["PENDING","AWAITING_MFA","SIGNING","BROADCASTING"]),a=new Set(["REJECTED","DENIED","FAILED","EXPIRED","BROADCAST_FAILED"]);if(e.status&&a.has(e.status))throw s?new Mt(t,s,e.status):new Error(`MM_CALL_FAILED: mm returned ${e.status} without a polling id`);if(e.status&&i.has(e.status))throw s?new et(t,s,r):new Error("MM_CALL_FAILED: mm returned a pending job without a polling id");if(s&&!e.signature&&!e.hash)throw new it(t,s,e.status??"MISSING");return e}function Pi(e){let t=s=>wp(s,e),r=["--wait","--wallet-timeout",String(Ap)],n=["--wallet-timeout",String(Ap)];return{kind:"metamask",getAddress(){let s=t(["wallet","address"]);if(typeof s.address!="string")throw new Error("MM_CALL_FAILED: `mm wallet address` returned no address");return s.address},async signMessage(s,i){let a=hn(t(["wallet","sign-message","--message",s,"--chain-id",String(i),...r]),"message","message signature");return Ci(a.signature)},async resumeMessage(s){let i=hn(t(["wallet","requests","watch","--polling-id",s,...n]),"message","message signature",s);return Ci(i.signature)},async signTypedData(s,i){let a=hn(t(["wallet","sign-typed-data","--chain-id",String(i),"--payload",JSON.stringify(s),...r]),"typed-data","typed-data signature");return Ci(a.signature)},async resumeTypedData(s){let i=hn(t(["wallet","requests","watch","--polling-id",s,...n]),"typed-data","typed-data signature",s);return Ci(i.signature)},sendTransaction(s,i){let a={to:s.to,value:s.value,...s.data?{data:s.data}:{}},o=hn(t(["wallet","send-transaction","--chain-id",String(i),"--payload",JSON.stringify(a),...r]),"transaction","transaction");if(typeof o.hash!="string")throw new Error("MM_CALL_FAILED: mm accepted the transaction but returned no hash");return{tx_hash:o.hash}},resumeTransaction(s){let i=hn(t(["wallet","requests","watch","--polling-id",s,...n]),"transaction","transaction",s);if(typeof i.hash!="string")throw new Error("MM_CALL_FAILED: mm completed the transaction request but returned no hash");return{tx_hash:i.hash}}}}p();import{createPublicClient as BS,http as VS,parseAbi as HS,BaseError as GS,ContractFunctionZeroDataError as $S,ContractFunctionRevertedError as WS}from"viem";var JS=HS(["function eip712Domain() view returns (bytes1 fields, string name, string version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] extensions)"]);function hc(e){return BS({transport:VS(e.rpcUrl)})}async function xp(e){return hc(e).getChainId()}async function _n(e,t){let r=await hc(e).getCode({address:t});return!!r&&r!=="0x"}async function Li(e,t){let r=t;try{let n=await hc(e).readContract({address:r,abi:JS,functionName:"eip712Domain"});return{name:n[1],version:n[2],chainId:Number(n[3]),verifyingContract:r}}catch(n){if(!(n instanceof GS&&!!n.walk(i=>i instanceof $S||i instanceof WS)))throw n;return{name:"Kernel",version:"0.3.3",chainId:e.chainId,verifyingContract:r}}}p();var Sp,_c="TadaRideAiAgent";function le(e){Sp=e.replace(/\/$/,"")}async function bt(e,t,r,n,s){let i={"Content-Type":"application/json","x-auth-client-id":_c};n&&(i.Authorization=`Bearer ${n}`);let a=await fetch(`${Sp}${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 Ip(e){return bt("POST","/quorum-wallet/session",{kIPub:e})}async function Mi(e){let t=await bt("GET",`/quorum-wallet/session/${e}`);return{...t,status:String(t.status).toUpperCase()}}function ki(e){return bt("POST","/quorum-wallet/validate",e)}function Dp(e,t){return bt("POST","/quorum-wallet/cosign",e,void 0,t)}function Op(e){return bt("POST","/quorum-wallet/sendtx",e)}function Np(e){return bt("POST","/quorum-wallet/sendcalls",e)}function Cp(e,t){return bt("POST","/auth/siwe/nonce",e,void 0,t)}function Pp(e,t){return bt("POST","/auth/siwe/token",e,void 0,t)}function Lp(e,t){return bt("POST","/auth/siwe/users",e,void 0,t)}function Mp(e,t){return bt("POST","/auth/typed-data/signin",e,void 0,t)}function kp(e,t){return bt("POST","/auth/typed-data/signup",e,void 0,t)}function Ui(e,t){return bt("GET",`/quorum-wallet/transaction/${e}`,void 0,void 0,t)}function yc(e,t){return bt("GET",`/auth/siwe/users/${e}`,void 0,void 0,t)}p();import kt from"fs";import ys from"path";p();import Fi from"path";import KS from"fs";import YS from"better-sqlite3";function at(e,t){return Fi.join(e,Fi.basename(t))}function qi(e){return Fi.basename(e)}var zS=[{table:"privy_wallet_meta",id:"wallet_address"},{table:"pending_sessions",id:"session_token"}];function Up(e){if(!KS.existsSync(e))return{normalized:0};let t=null;try{return t=new YS(e),t.transaction(()=>{let n=new Map,s=0;for(let i of zS){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 l of o){let u=l.k_i_key_path.replace(/\\/g,"/"),d=Fi.posix.basename(u);if(!d||d==="."||d==="..")throw new Error(`INVALID_KEY_PATH: ${i.table}.${i.id}=${l.id}`);let m=n.get(d);if(m!==void 0&&m!==u)throw new Error(`KEY_PATH_COLLISION: ${d}`);n.set(d,u),l.k_i_key_path!==d&&(c.run(d,l.id),s++)}}return{normalized:s}})()}finally{t?.close()}}p();function _s(e,t,r){return`${e}?handle=${t}&pub=${encodeURIComponent(r)}`}p();import cr from"crypto";var Fp=Buffer.from("RAGK"),qp=1,ji=4,jp=1,Bi=32,Vi=12,Ec=16,XS=ji+jp+Bi+Vi+Ec,QS=16384,ZS=8,eI=1,tI=32;function Bp(){let{publicKey:e,privateKey:t}=cr.generateKeyPairSync("ec",{namedCurve:"prime256v1",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKeyPem:e,privateKeyPem:t}}function Vp(e){return cr.createPublicKey(e).export({type:"spki",format:"der"}).toString("base64")}function Hi(e){let t=cr.createPrivateKey(e);return cr.createPublicKey(t).export({type:"spki",format:"der"}).toString("base64")}function Hp(e,t){return cr.scryptSync(e,t,tI,{N:QS,r:ZS,p:eI})}function Gp(e,t){let r=cr.randomBytes(Bi),n=cr.randomBytes(Vi),s=Hp(t,r),i=cr.createCipheriv("aes-256-gcm",s,n),a=Buffer.concat([i.update(e),i.final()]),o=i.getAuthTag();return Buffer.concat([Fp,Buffer.from([qp]),r,n,o,a])}function Wt(e,t){if(e.length<XS)throw new Error("Invalid encrypted data: too short");if(!e.subarray(0,ji).equals(Fp))throw new Error("Invalid encrypted data: bad magic");let n=e[ji];if(n!==qp)throw new Error(`Unsupported encrypted data version: ${n}`);let s=ji+jp,i=e.subarray(s,s+Bi);s+=Bi;let a=e.subarray(s,s+Vi);s+=Vi;let o=e.subarray(s,s+Ec);s+=Ec;let c=e.subarray(s),l=Hp(t,i),u=cr.createDecipheriv("aes-256-gcm",l,a);return u.setAuthTag(o),Buffer.concat([u.update(c),u.final()])}function vt(e){e.fill(0)}p();function Gi(){return x().prepare("SELECT * FROM pending_sessions ORDER BY created_at DESC, rowid DESC LIMIT 1").get()}function $p(e){x().prepare(`
|
|
293
431
|
INSERT INTO pending_sessions (session_token, k_i_pub, k_i_key_path)
|
|
294
432
|
VALUES (@session_token, @k_i_pub, @k_i_key_path)
|
|
295
|
-
`).run(e)}function
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
433
|
+
`).run(e)}function Ur(e){x().prepare("DELETE FROM pending_sessions WHERE session_token = ?").run(e)}async function Wp(e,t,r=!1){let n=r?[]:Ni();if(n.length>0){let m=[],f=[];for(let g of n){let h=Tt(g.wallet_address);if(!h){f.push(g.wallet_address);continue}try{let E=at(e.keysDir,h.k_i_key_path);if(!kt.existsSync(E)){f.push(g.wallet_address);continue}let T=kt.readFileSync(E),w=Wt(T,t),v=w.toString("utf8"),A=Hi(v);if(vt(w),A!==h.k_i_pub){f.push(g.wallet_address);continue}m.push({wallet_address:g.wallet_address,wallet_id:h.wallet_id})}catch{f.push(g.wallet_address)}}if(m.length>0){if(f.length>0)for(let g of f)or(g,"Local validation failed");return{status:"ready",wallets:m}}for(let g of f)or(g,"Local validation failed")}let s=Gi();if(s){try{let m=await Mi(s.session_token);if(m.status==="PENDING")return{status:"auth_pending",auth_url:_s(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:h}=m,E=e.keysDir,T=at(E,s.k_i_key_path),w=ys.join(E,`${h}_private.enc`);return kt.renameSync(T,w),kt.rmSync(ys.join(E,`${s.session_token}_public.pem`),{force:!0}),Di({wallet_address:h,wallet_id:g,quorum_id:f,k_i_pub:s.k_i_pub,k_i_key_path:qi(w)}),gn(h),Ur(s.session_token),{status:"ready",wallets:[{wallet_address:h,wallet_id:g}]}}}catch{}kt.rmSync(at(e.keysDir,s.k_i_key_path),{force:!0}),kt.rmSync(ys.join(e.keysDir,`${s.session_token}_public.pem`),{force:!0}),Ur(s.session_token)}let{publicKeyPem:i,privateKeyPem:a}=Bp(),o=Vp(i),{sessionToken:c}=await Ip(o),l=_s(e.webappUrl,c,o),u=ys.join(e.keysDir,`${c}_private.enc`),d=ys.join(e.keysDir,`${c}_public.pem`);try{kt.mkdirSync(e.keysDir,{recursive:!0,mode:448});let m=Buffer.from(a,"utf8"),f=Gp(m,t);vt(m),kt.writeFileSync(u,f,{mode:384}),kt.writeFileSync(d,i,{mode:420}),$p({session_token:c,k_i_pub:o,k_i_key_path:u})}catch(m){throw kt.rmSync(u,{force:!0}),kt.rmSync(d,{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"}}p();import Jp from"fs";import Kp from"path";var rI=1e3;async function Tc(e,t={}){let r=Gi();if(!r)return{status:"no_pending"};let{session_token:n,k_i_pub:s,k_i_key_path:i}=r,a=_s(e.webappUrl,n,s),o=Date.now()+(t.waitMs??0),c;for(;c=await Mi(n),c.status==="PENDING";){if(Date.now()>=o)return{status:"pending",auth_url:a};await new Promise(E=>setTimeout(E,rI))}if(c.status!=="DONE")return Ur(n),{status:"failed",reason:c.status==="FAILED"?c.reason:`Unexpected session status: ${c.status}`};let{quorumId:l,walletId:u,walletAddress:d}=c,m=e.keysDir,f=at(m,i),g=Kp.join(m,`${d}_private.enc`),h=Kp.join(m,`${n}_public.pem`);try{Jp.renameSync(f,g)}catch(E){throw Ur(n),new Error(`Failed to rename key file: ${E}`)}return Jp.rmSync(h,{force:!0}),Di({wallet_address:d,wallet_id:u,quorum_id:l,k_i_pub:s,k_i_key_path:qi(g)}),gn(d),Ur(n),{status:"ready",wallet_address:d}}p();p();function bc(e,t){return t==="siwe"?e.toLowerCase():e}function vc(e,t,r,n="siwe"){let s=x(),i=bc(e,n);s.transaction(()=>{n==="siwe"&&s.prepare("DELETE FROM jwt_cache WHERE kind = 'siwe' AND cache_key = ? COLLATE NOCASE").run(i),s.prepare(`
|
|
434
|
+
INSERT OR REPLACE INTO jwt_cache (cache_key, token, expires_at, kind, refresh_token, refresh_expires_at)
|
|
435
|
+
VALUES (?, ?, ?, ?, NULL, NULL)
|
|
436
|
+
`).run(i,t,r,n)})()}function Yp(e,t,r,n,s){x().prepare(`
|
|
299
437
|
INSERT OR REPLACE INTO jwt_cache (cache_key, token, expires_at, kind, refresh_token, refresh_expires_at)
|
|
300
438
|
VALUES (?, ?, ?, 'member', ?, ?)
|
|
301
|
-
`).run(e,t,r,n,s)}function
|
|
302
|
-
SELECT token FROM jwt_cache
|
|
303
|
-
|
|
439
|
+
`).run(e,t,r,n,s)}function ce(e,t="siwe"){let r=Math.floor(Date.now()/1e3);return x().prepare(`
|
|
440
|
+
SELECT token FROM jwt_cache
|
|
441
|
+
WHERE cache_key = ? ${t==="siwe"?"COLLATE NOCASE":""}
|
|
442
|
+
AND kind = ? AND expires_at > ?
|
|
443
|
+
ORDER BY expires_at DESC LIMIT 1
|
|
444
|
+
`).get(bc(e,t),t,r)?.token??null}function $i(e){let t=Math.floor(Date.now()/1e3);return x().prepare(`
|
|
304
445
|
SELECT refresh_token, refresh_expires_at
|
|
305
446
|
FROM jwt_cache
|
|
306
447
|
WHERE cache_key = ? AND kind = 'member'
|
|
307
448
|
AND refresh_token IS NOT NULL
|
|
308
449
|
AND (refresh_expires_at IS NULL OR refresh_expires_at > ?)
|
|
309
|
-
`).get(e,t)??null}function
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
`).get(e,t)
|
|
315
|
-
INSERT OR REPLACE INTO payment_cache (request_id, data, expires_at)
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
450
|
+
`).get(e,t)??null}function zp(e,t="siwe"){let r=Math.floor(Date.now()/1e3);return x().prepare(`
|
|
451
|
+
SELECT token, expires_at FROM jwt_cache
|
|
452
|
+
WHERE cache_key = ? ${t==="siwe"?"COLLATE NOCASE":""}
|
|
453
|
+
AND kind = ? AND expires_at > ?
|
|
454
|
+
ORDER BY expires_at DESC LIMIT 1
|
|
455
|
+
`).get(bc(e,t),t,r)??null}function X(e){Ye(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 Ee(e){let t=ce(e),r=Math.floor(Date.now()/1e3);Et(`[jwt-debug] GET cache_key=${e} now=${r} found=${!!t} pid=${process.pid}
|
|
456
|
+
`),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 wI,http as AI,formatUnits as xc,parseAbi as xI}from"viem";import{baseSepolia as rm,base as SI,mainnet as II,sepolia as DI}from"viem/chains";p();function Xp(e){let t=new Map,r=(i,a,o)=>{let c=t.get(i);if(c)return c;let l={network:i,chainId:a,rpcUrl:o,tokens:[{kind:"native"}]};return t.set(i,l),l},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 iI,http as aI,parseAbi as oI}from"viem";import{baseSepolia as cI,base as lI,mainnet as uI,sepolia as dI}from"viem/chains";p();import{parseAbi as nI}from"viem";var yn=nI(["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 sI}from"viem";var En=sI(["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 pI={84532:cI,8453:lI,1:uI,11155111:dI},Qp=oI(["function allowance(address owner, address spender) view returns (uint256)","function balanceOf(address account) view returns (uint256)"]);function mI(e){let t=pI[e];if(!t)throw new Error(`Unsupported chainId: ${e}`);return t}function Jt(e){return iI({chain:mI(e.chainId),transport:aI(e.rpcUrl)})}async function Wi(e,t){return await Jt(e).readContract({address:e.agentDepositLedger,abi:En,functionName:"deposits",args:[t]})}async function Es(e,t){return await Jt(e).readContract({address:e.agentDepositLedger,abi:En,functionName:"isAgentActive",args:[t]})}async function Rc(e){return(await Jt(e).readContract({address:e.depositContract,abi:yn,functionName:"supportedTokens"})).filter(r=>!/^0x0{40}$/i.test(r))}async function Ji(e,t){return await Jt(e).readContract({address:e.agentDepositLedger,abi:En,functionName:"nextWithdrawAt",args:[t]})}async function Ts(e){return await Jt(e).readContract({address:e.agentDepositLedger,abi:En,functionName:"minRequiredBalance"})}async function Fr(e){return await Jt(e).readContract({address:e.agentDepositLedger,abi:En,functionName:"mvlToken"})}async function Zp(e){return await Jt(e).readContract({address:e.depositContract,abi:yn,functionName:"mvlReserve"})}async function Ki(e,t){return Jt(e).getBalance({address:t})}async function bs(e,t,r,n){return await Jt(e).readContract({address:t,abi:Qp,functionName:"allowance",args:[r,n]})}async function em(e,t,r){return await Jt(e).readContract({address:t,abi:Qp,functionName:"balanceOf",args:[r]})}p();import{createPublicClient as fI,http as gI,parseAbi as hI}from"viem";import{baseSepolia as _I,base as yI,mainnet as EI,sepolia as TI}from"viem/chains";var bI={84532:_I,8453:yI,1:EI,11155111:TI},wc=hI(["function symbol() view returns (string)","function name() view returns (string)","function decimals() view returns (uint8)"]),vI={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}}},Ac=new Map;function RI(e,t){return`${e}:${t.toLowerCase()}`}async function qr(e,t){let r=RI(e.name,t),n=Ac.get(r);if(n)return n;let s=vI[e.name]?.[t.toLowerCase()];if(s)return Ac.set(r,s),s;let i=bI[e.chainId],a=fI({chain:i,transport:gI(e.rpcUrl)}),o=t,[c,l,u]=await Promise.all([a.readContract({address:o,abi:wc,functionName:"symbol"}),a.readContract({address:o,abi:wc,functionName:"name"}),a.readContract({address:o,abi:wc,functionName:"decimals"})]),d={symbol:c,name:l,decimals:u};return Ac.set(r,d),d}var nm={84532:rm,8453:SI,1:II,11155111:DI},OI=xI(["function balanceOf(address account) view returns (uint256)"]),NI=(e,t)=>wI({chain:nm[e]??rm,transport:AI(t)});function tm(e,t,r){return e.readContract({address:t,abi:OI,functionName:"balanceOf",args:[r]})}async function sm(e,t,r={}){let n=r.makeClient??NI,s=r.mvlTokenReader??Fr,i=r.tokenMetadata??qr,a=Xp(t),o=await Promise.all(a.map(async m=>{let f;try{f=n(m.chainId,m.rpcUrl)}catch(g){return m.tokens.map(h=>({status:"rejected",network:m.network,symbol:u(h),error:g.message}))}return await Promise.all(m.tokens.map(async g=>{try{return{status:"fulfilled",row:await d(g,m,f)}}catch(h){return{status:"rejected",network:m.network,symbol:u(g),error:h.message}}}))})),c=[],l=[];for(let m of o.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 u(m){return m.kind==="erc20"?m.symbol:m.kind==="mvl"?"MVL":"native"}async function d(m,f,g){let h=f.network;if(m.kind==="native"){let v=await g.getBalance({address:e}),A=nm[f.chainId]?.nativeCurrency.symbol??"ETH";return{network:h,symbol:A,amount:xc(v,18)}}if(m.kind==="erc20"){let v=await tm(g,m.address,e);return{network:h,symbol:m.symbol,amount:xc(v,m.decimals),address:m.address}}let E=await s(m.deposit),T=await i(m.deposit,E),w=await tm(g,E,e);return{network:h,symbol:T.symbol,amount:xc(w,T.decimals),address:E}}}p();import cm from"fs";p();import{p256 as CI}from"@noble/curves/p256";import{sha256 as PI}from"@noble/hashes/sha2";import{formatRequestForAuthorizationSignature as LI}from"@privy-io/node";import MI from"crypto";function im(e,t){let n=MI.createPrivateKey(t).export({format:"jwk"}),s=Buffer.from(n.d,"base64url"),i=CI.sign(PI(typeof e=="string"?Buffer.from(e):e),s);return Buffer.from(i.toDERRawBytes()).toString("base64")}function Tn(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=LI(i);return im(a,r)}function Yi(e,t){return im(`${e}`,t)}p();import{getAddress as am,recoverMessageAddress as kI,recoverTypedDataAddress as om}from"viem";function UI(e,t){let r=(n,s)=>{if(am(n)!==am(t))throw new Error(`MM_ADDRESS_MISMATCH: this ${s} came back signed by ${n}, not the registered ${t}. The active wallet moved while \`mm\` was signing \u2014 switch back with \`mm wallet select\` before retrying. The signature was discarded.`)};return{...e,async signMessage(n,s){let i=await e.signMessage(n,s);return r(await kI({message:n,signature:i}),"message signature"),i},async signTypedData(n,s){let i=await e.signTypedData(n,s);return r(await om({...n,signature:i}),"typed-data signature"),i},...e.resumeTypedData?{async resumeTypedData(n,s){let i=await e.resumeTypedData(n,s);return r(await om({...s,signature:i}),"typed-data signature"),i}}:{}}}function Tr(e,t=()=>Pi()){if(Ye(e)?.wallet_type!=="metamask")return;let n=t(),s=n.getAddress();if(s.toLowerCase()!==e.toLowerCase())throw new Error(`MM_ADDRESS_MISMATCH: this skill is registered to ${e} but \`mm\` is currently active on ${s}. Switch back with \`mm wallet select\` before retrying.`);return UI(n,e)}async function br(e,t,r,n){let{wallet_address:s,sign_method:i,message:a}=e;if(!Ye(s))throw new Error(`Wallet not found: ${s}`);let c=Tt(s);if(!c){let E=Tr(s);if(E){if(i==="personal_sign"){if(typeof a!="string")throw new Error("personal_sign requires a string message");return{wallet_signature:await E.signMessage(a,1)}}if(typeof a=="string")throw new Error("eth_signTypedData_v4 requires a typed data object");let T=Number(a.domain.chainId??1);return{wallet_signature:await E.signTypedData(a,T)}}throw new Error("External wallet: signing must be done externally. This address was registered with the retired `wallet-add-external` command, which the skill cannot sign for. Re-register it with `amb wallet-connect-metamask` to drive it through the MetaMask Agent Wallet CLI.")}let l=at(t.keysDir,c.k_i_key_path);if(!cm.existsSync(l))throw new Error(`Key file not found: ${l}`);let u=cm.readFileSync(l),d=Wt(u,r),m=d.toString("utf8");if(i==="personal_sign"&&typeof a!="string")throw vt(d),new Error("personal_sign requires a string message");if(i==="eth_signTypedData_v4"&&typeof a=="string")throw vt(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=Tn(c.wallet_id,f,m,t.privyAppId),{walletSignature:h}=await Dp({signMethod:i,message:a,walletId:c.wallet_id,kISig:g},n);return vt(d),{wallet_signature:h}}p();import lm from"fs";var um={1:"https://etherscan.io/tx",11155111:"https://sepolia.etherscan.io/tx",8453:"https://basescan.org/tx",84532:"https://sepolia.basescan.org/tx"};function FI(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,resume_polling_id:l}=e,u=FI(i),d=Ye(n);if(!d)throw new Error(`Wallet not found: ${n}`);let m=Tt(n);if(!m){let T=Tr(n);if(T){if(l&&!T.resumeTransaction)throw new Error("MM_CALL_FAILED: the active MetaMask signer cannot resume transaction requests");let{tx_hash:w}=l?T.resumeTransaction(l):T.sendTransaction({to:s,value:u,...o?{data:o}:{}},a),v=um[a];return{kind:"tx_hash",tx_hash:w,...v?{explorer_url:`${v}/${w}`}:{}}}throw new Error("External wallet: signing must be done externally. This address was registered with the retired `wallet-add-external` command, which the skill cannot sign for. Re-register it with `amb wallet-connect-metamask` to drive it through the MetaMask Agent Wallet CLI.")}let f=at(t.keysDir,m.k_i_key_path);if(!lm.existsSync(f))throw new Error(`Key file not found: ${f}`);let g=lm.readFileSync(f),h=Wt(g,r),E=h.toString("utf8");try{let T=Date.now(),w=Yi(T,E),v;try{v=await ki({walletId:m.wallet_id,quorumId:m.quorum_id,kIPub:m.k_i_pub,timestamp:T,kISig:w})}catch(Y){throw(Y instanceof Error?Y.message:String(Y)).includes("HTTP 401")&&or(d.wallet_address,"Unauthorized (401)"),Y}if(!v.valid)throw or(d.wallet_address,v.reason??"Server returned valid:false"),new Error(`Wallet validation failed: ${v.reason??"unknown reason"}`);let A={method:"eth_sendTransaction",caip2:`eip155:${a}`,params:{transaction:{to:s,value:u,...o?{data:o}:{}}},...c?{sponsor:!0}:{}},C=`${Date.now()}:${crypto.randomUUID()}`,P=Tn(m.wallet_id,A,E,t.privyAppId,{"privy-idempotency-key":C}),L=await Op({walletId:m.wallet_id,caip2:`eip155:${a}`,transaction:{to:s,value:u,...o?{data:o}:{}},idempotencyKey:C,kISig:P,...c?{sponsor:!0}:{}}),W=L.transactionId?{transactionId:L.transactionId}:{};if(L.kind==="user_operation_hash")return{kind:"user_operation_hash",user_operation_hash:L.userOperationHash,...W};let Z=L.txHash,V=um[a];return{kind:"tx_hash",tx_hash:Z,...V?{explorer_url:`${V}/${Z}`}:{},...W}}finally{vt(h)}}p();import{createHash as qI}from"crypto";var jI=/^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,BI=/^wallet:[0-9a-f]{24}$/;function vr(e){return`member:${e}`}function Je(e){return`wallet:${qI("sha256").update(e.toLowerCase()).digest("hex").slice(0,24)}`}function dm(e){return typeof e=="string"&&(jI.test(e)||BI.test(e))}function pm(e,t,r){try{let n=x(),s=e.startsWith("member:")?"member":"wallet";n.prepare(`
|
|
457
|
+
INSERT OR IGNORE INTO telemetry_accounts (account_id, installation_id, auth_type)
|
|
458
|
+
VALUES (?, ?, ?)
|
|
459
|
+
`).run(e,t,s);let i=n.prepare(`
|
|
460
|
+
SELECT a.first_ride_created_at, j.started_at AS journey_started_at
|
|
461
|
+
FROM telemetry_accounts a
|
|
462
|
+
LEFT JOIN telemetry_journeys j ON j.journey_id = ?
|
|
463
|
+
WHERE a.account_id = ?
|
|
464
|
+
`).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 Sc(e,t=Date.now()){try{x().prepare(`
|
|
465
|
+
UPDATE telemetry_accounts
|
|
466
|
+
SET first_ride_created_at = COALESCE(first_ride_created_at, ?)
|
|
467
|
+
WHERE account_id = ?
|
|
468
|
+
`).run(t,e)}catch{}}p();import{createHash as FM,randomUUID as qM}from"crypto";p();var bn=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},i=s.command==="deposit-add"||s.command==="deposit-relay-status"||s.command==="deposit-status";if(!i&&s.command!=="activation"&&(!s.region||!s.payment_mode)||i&&(s.region||s.payment_mode)||s.account_id!==void 0&&!dm(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 mr=uS(Cb(),1);var vM=2e3,RM=typeof mr.default=="function"?mr.default:mr.default.default;function wM(){let e=xe(),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 AM(){let t={ambTelemetryService:wM()};return new RM({securityType:mr.SecurityType.PUBLIC,baseUrls:t,clientId:"RideAgentSkill",clientVersion:xe().artifact.cliVersion}).ambTelemetry}function xM(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.deposit_attempt_id&&(n.depositAttemptId=r.deposit_attempt_id),r.deposit_network&&(n.depositNetwork=r.deposit_network),r.deposit_token&&(n.depositToken=r.deposit_token),r.deposit_path&&(n.depositPath=r.deposit_path),r.relay_request_id&&(n.relayRequestId=r.relay_request_id),r.error_code&&(n.errorCode=r.error_code),r.failure_reason&&(n.failureReason=r.failure_reason),n}var Bn=class{constructor(t=AM()){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:mr.AmbTelemetryService.AmbientHailingTelemetryBatchDtoSchemaVersionEnum.Value1,source:mr.AmbTelemetryService.AmbientHailingTelemetryBatchDtoSourceEnum.AmbientHailing,events:t.map(({event:n,occurredAt:s})=>xM(n,s))},{timeout:vM});if(r.accepted!==t.length)throw new Error(`Ambient Hailing telemetry accepted ${r.accepted} of ${t.length} events`);return r.accepted}};p();var SM={401:"unauthorized",404:"agent_session_not_found",409:"agent_session_already_decided",410:"agent_session_expired"},Ge=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},Ar=class extends Error{code="coupon_not_applicable";constructor(){super("The coupon is not applicable to the latest quote."),this.name="CouponQuoteError"}},Ga=class extends Error{code="coupon_price_changed";constructor(){super("The coupon total changed after confirmation. Re-quote before booking."),this.name="CouponPriceChangedError"}},Pb={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 $a(e){if(!(typeof e!="string"||!Object.hasOwn(Pb,e)))return Pb[e]}function ht(e,t){let r=SM[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 Ge(e,r,n)}p();import{randomUUID as IM}from"crypto";import $s from"fs";import DM from"path";var OM=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Wa=new Map;function Lb(e){try{let t=$s.readFileSync(e,"utf8").trim();return OM.test(t)?t:void 0}catch{return}}function Ja(e){let t=DM.join(e,"telemetry-installation-id"),r=Lb(t);if(r)return r;let n=Wa.get(t)??IM();Wa.set(t,n);let s=`${t}.${n}.tmp`;try{return $s.mkdirSync(e,{recursive:!0,mode:448}),$s.writeFileSync(s,`${n}
|
|
469
|
+
`,{mode:384,flag:"wx"}),$s.linkSync(s,t),Wa.delete(t),n}catch(i){if(i.code==="EEXIST"){let a=Lb(t);if(a)return Wa.delete(t),a}return n}finally{try{$s.unlinkSync(s)}catch{}}}p();import{randomBytes as NM}from"crypto";var rt=class{constructor(t=Date.now){this.now=t}now;create(t){let r=this.now(),n={journey_id:CM(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 x().prepare(`
|
|
470
|
+
INSERT INTO telemetry_journeys (
|
|
471
|
+
journey_id, account_id, payment_mode, region, market_code,
|
|
472
|
+
status, started_at, expires_at, closed_at
|
|
473
|
+
) VALUES (
|
|
474
|
+
@journey_id, @account_id, @payment_mode, @region, @market_code,
|
|
475
|
+
@status, @started_at, @expires_at, @closed_at
|
|
476
|
+
)
|
|
477
|
+
`).run(n),n}findOrCreate(t){let r=x();return r.transaction(()=>r.prepare(`
|
|
478
|
+
SELECT j.* FROM telemetry_journeys j
|
|
479
|
+
WHERE j.account_id = ? AND j.payment_mode = ? AND j.region = ?
|
|
480
|
+
AND (j.market_code = ? OR (j.market_code IS NULL AND ? IS NULL))
|
|
481
|
+
AND j.status = 'open' AND j.expires_at > ?
|
|
482
|
+
AND NOT EXISTS (
|
|
483
|
+
SELECT 1 FROM telemetry_journey_links l
|
|
484
|
+
WHERE l.journey_id = j.journey_id AND l.link_type = 'request'
|
|
485
|
+
)
|
|
486
|
+
ORDER BY j.started_at DESC LIMIT 1
|
|
487
|
+
`).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=x();try{s.transaction(()=>{this.requireOpen({journey_id:t},r);let i=s.prepare(`
|
|
488
|
+
SELECT journey_id, backend_id FROM telemetry_journey_links
|
|
489
|
+
WHERE link_type = ? AND link_id = ?
|
|
490
|
+
`).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(`
|
|
491
|
+
INSERT INTO telemetry_journey_links (link_type, link_id, journey_id, backend_id)
|
|
492
|
+
VALUES (?, ?, ?, ?)
|
|
493
|
+
`).run(n.link_type,n.link_id,t,n.backend_id??null),n.link_type==="request"){s.prepare(`
|
|
494
|
+
UPDATE telemetry_journeys SET expires_at = MAX(expires_at, ?) WHERE journey_id = ?
|
|
495
|
+
`).run(this.now()+1440*6e4,t);let a=s.prepare(`
|
|
496
|
+
SELECT link_id FROM telemetry_journey_links
|
|
497
|
+
WHERE journey_id = ? AND link_type = 'ride'
|
|
498
|
+
`).get(t);s.prepare(`
|
|
499
|
+
UPDATE ride_requests SET journey_id = ?, ride_id = COALESCE(?, ride_id)
|
|
500
|
+
WHERE request_id = ?
|
|
501
|
+
`).run(t,a?.link_id??null,n.link_id)}else if(n.link_type==="ride"){let a=s.prepare(`
|
|
502
|
+
SELECT link_id FROM telemetry_journey_links
|
|
503
|
+
WHERE journey_id = ? AND link_type = 'request'
|
|
504
|
+
`).get(t);a&&s.prepare(`
|
|
505
|
+
UPDATE ride_requests SET journey_id = ?, ride_id = ? WHERE request_id = ?
|
|
506
|
+
`).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){x().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=x().prepare("SELECT * FROM telemetry_journeys WHERE journey_id = ?").get(t);return n?.account_id===r?n:void 0}resolveSearchForBooking(t,r,n){let s=x(),i=s.prepare(`
|
|
507
|
+
SELECT j.*, l.backend_id
|
|
508
|
+
FROM telemetry_journeys j
|
|
509
|
+
JOIN telemetry_journey_links l ON l.journey_id = j.journey_id
|
|
510
|
+
WHERE l.link_type = 'search' AND l.link_id = ?
|
|
511
|
+
`).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(`
|
|
512
|
+
UPDATE telemetry_journeys SET status = 'closed', closed_at = ? WHERE journey_id = ?
|
|
513
|
+
`).run(this.now(),o.journey_id);let l=o.payment_mode===n.payment_mode&&o.region===n.region&&o.market_code===n.market_code;return{journey:c&&l?o:void 0,backend_id:a}}close(t,r){let n=this.requireOpen({journey_id:t},r),s=this.now();return x().prepare(`
|
|
514
|
+
UPDATE telemetry_journeys SET status = 'closed', closed_at = ? WHERE journey_id = ?
|
|
515
|
+
`).run(s,t),{...n,status:"closed",closed_at:s}}requireOpen(t,r){let n=x(),s="journey_id"in t?n.prepare("SELECT * FROM telemetry_journeys WHERE journey_id = ?").get(t.journey_id):n.prepare(`
|
|
516
|
+
SELECT j.* FROM telemetry_journeys j
|
|
517
|
+
JOIN telemetry_journey_links l ON l.journey_id = j.journey_id
|
|
518
|
+
WHERE l.link_type = ? AND l.link_id = ?
|
|
519
|
+
`).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(`
|
|
520
|
+
UPDATE telemetry_journeys SET status = 'closed', closed_at = ? WHERE journey_id = ?
|
|
521
|
+
`).run(this.now(),s.journey_id),new Error("JOURNEY_EXPIRED");return s}};function CM(e){let t=NM(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 Mb=new Set(["MATCHED","CONFIRMED","ASSIGNED","PICKUP"]),kb=new Set([...Mb,"PICKUP_ARRIVED"]),PM=new Set([...kb,"FINISHED","COMPLETED"]);function Ka(e){return e.toUpperCase().startsWith("INUSE")}function Ub(e){return Mb.has(e.toUpperCase())}function Fb(e){return kb.has(e.toUpperCase())}function LM(e){return Ka(e)||PM.has(e.toUpperCase())}function qb(e){let t=e.toUpperCase();return Ya(t)?!1:LM(t)||t==="NOT_MATCHED"||t.startsWith("EXPIRED")||t.startsWith("ERROR")}function Ya(e){let t=e.toUpperCase();return t==="ERROR_PAYMENT"||t==="EXPIRED_BEFORE_PAY"}var Qr=["driver_search_started","driver_matched","pickup_arrived","ride_started","ride_arrived"];function Su(e,t){let r=e.toUpperCase(),n=t?.toUpperCase(),s=new Set(jb(n)),i=jb(r).filter(a=>!s.has(a)).map(a=>MM(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:kM(r),cancellationStage:UM(r,t)}}),(r.startsWith("EXPIRED")||r.startsWith("ERROR"))&&i.push({stage:"ride_abandoned",properties:{lifecycleStatus:r,journeyOutcome:"abandoned",...Ya(r)?{dispatchOutcome:"search_not_started"}:{}}}),i}function jb(e){return e?Ya(e)?[]:e==="PENDING"?Qr.slice(0,1):e.startsWith("DRIVER_CANCELED")||Ub(e)?Qr.slice(0,2):e==="PICKUP_ARRIVED"?Qr.slice(0,3):Ka(e)?Qr.slice(0,4):e==="FINISHED"||e==="COMPLETED"?Qr:e==="NOT_MATCHED"||e.startsWith("EXPIRED")||e.startsWith("ERROR")?Qr.slice(0,1):[]:[]}function MM(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 kM(e){return e.startsWith("USER_")?"rider":e.startsWith("DRIVER_")?"driver":e.startsWith("COMPANY_")?"company":"system"}function UM(e,t){let r=t?.toUpperCase();return r&&Ka(r)?"in_ride":e.startsWith("DRIVER_CANCELED")||r&&Fb(r)?"post_match":"pre_match"}async function za(e,t,r,n,s=!1){let i=Nu(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 Du(e,t,r,n){return za(e,{...t,command:"ride-search",startedStage:"vehicle_search_started",completedStage:s=>jM(s)?"options_presented":"zero_results",completedContext:Wb,failedStage:"vehicle_search_failed",errorCode:"RIDE_SEARCH_FAILED"},r,n,n!==void 0)}async function Ft(e,t,r){let n=Nu(e,{command:"activation",completedStage:()=>t,accountId:r?.id});n?.completed(void 0),await n?.shutdown()}function jM(e){if(!e||typeof e!="object")return!1;let t=e.options;return Array.isArray(t)&&t.length>0}function Ou(e,t,r,n){return za(e,{...t,command:"ride-request",startedStage:"call_confirmed",completedStage:()=>"booking_requested",additionalCompletedEvents:s=>t.paymentMode==="card"?[{stage:"payment_step_completed"},{stage:"ride_created"},...BM(s)]:[],completedContext:s=>Wb(s,t.paymentMode==="card"),failedStage:"booking_failed",errorCode:"RIDE_REQUEST_FAILED",failureReason:s=>t.paymentMode==="card"?WM(s):"other",suppressFailure:s=>t.paymentMode==="wallet_usdc"&&Cu(s)},r,n)}async function Bb(e,t){let r=Nu(e,{...t,command:"tip",completedStage:()=>"tip_completed"});r?.completed(void 0),await r?.shutdown()}function Vb(e,t,r){return za(e,{...t,command:"ride-pay-prepare",startedStage:"payment_started",completedStage:()=>"payment_authorization_prepared",failedStage:"payment_failed",errorCode:"RIDE_PAY_PREPARE_FAILED"},r)}function Hb(e,t,r){return za(e,{...t,command:"ride-pay-confirm",startedStage:"payment_confirmation_started",completedStage:()=>"payment_completed",failedStage:"payment_failed",errorCode:"RIDE_PAY_CONFIRM_FAILED",failureReason:$M,resultFailureReason:n=>VM(n)?"other":void 0},r)}function Nu(e,t){try{let r=Gb(e);if(!r)return;let n=t.journeyId,s=performance.now(),i=Ws(r,t),a,o=(c,l)=>({event_id:t.command==="ride-request"&&c==="call_confirmed"&&n?Iu(`${n}:call_confirmed`):qM(),stage:c,duration_ms:l??Math.max(0,Math.round(performance.now()-s))});return{started:(c,l,u)=>{let d=c?Ws(r,{...t,...c}):i;t.startedStage&&d.capture({event:"ambient_cli_command_started",...o(t.startedStage,l),occurredAt:u,outcome:"started"})},completed:(c,l)=>{let u=l?{...t,...l}:t,d=l?Ws(r,u):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 h=t.completedContext?.(c)??{};for(let E of f)(E.properties?Ws(r,{...u,...E.properties}):d).capture({event:"ambient_cli_command_completed",...o(E.stage),...h,outcome:"completed"})&&u.accountId&&E.stage==="ride_created"&&(a=u.accountId);if(u.accountId&&u.journeyId&&f.some(E=>HM(E.stage)))try{new rt().close(u.journeyId,u.accountId)}catch{}},failed:c=>{t.suppressFailure?.(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&&Sc(a)}}}catch{return}}function Cu(e){let r=(e instanceof Error?e.message:String(e??"")).toLowerCase();return r.includes("deposit")||r.includes("collateral")}function Gb(e){let t=xe(),r=JM(t.install.repoBranch);return{transport:new Bn,installationId:Ja(e),cliVersion:t.artifact.cliVersion,environment:r}}function Ws(e,t,r){let n=$b(e,t,r);return new bn(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 $b(e,t,r){if(r)return r.ahUserType;if(t.ahUserType)return t.ahUserType;if(t.accountId)return pm(t.accountId,e.installationId,t.journeyId)}function Wb(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 BM(e){if(!e||typeof e!="object")return[];let t=e.rideStatus;return typeof t!="string"?[]:Su(t,"WAITPAY")}function VM(e){return!!e&&typeof e=="object"&&e.success===!1}function HM(e){return e==="ride_arrived"||e==="ride_cancelled"||e==="ride_abandoned"}async function Jb(e,t){let r=Su(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=Gb(e);if(!a)return;let o=$b(a,{...t,command:"ride-monitor"}),c=!1;for(let[l,u]of n.entries())Ws(a,{...t,command:"ride-monitor",...u.properties,lifecycleStatus:t.status},{ahUserType:o}).capture({event:"ambient_cli_command_completed",event_id:GM(t,u.stage,l),stage:u.stage,outcome:"completed",duration_ms:t.durationMs})&&t.accountId&&u.stage==="ride_created"&&(c=!0);await a.transport.shutdown(),c&&t.accountId&&Sc(t.accountId)}catch{}}function GM(e,t,r){let n=e.requestId??e.rideId;return n?Iu(`${n}:${t}`):r===0?e.eventId:Iu(`${e.eventId}:${t}`)}function Iu(e){return`evt_${FM("sha256").update(e).digest("hex").slice(0,24)}`}function $M(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 WM(e){return e instanceof Ge&&(e.status===402||e.code==="card_api_error")?"card_error":"other"}function JM(e){if(e==="main")return"production";if(e==="dev"||e==="staging")return e;throw new Error(`Unsupported telemetry build environment: ${e}`)}var Zb=300*1e3,XM=async e=>{let t=O();N(t.dataDir);let r=Oi();S({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:Tt(n.wallet_address)?.wallet_id}:{}}))})};function QM(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=KM(t,r,{stdio:"ignore",detached:!0});n.on("error",()=>{}),n.unref()}catch{}}var ZM=async e=>{let t=O();N(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 Wp(t,s,r)}catch(c){b({error:c.message}),process.exit(1)}if(n){S(i);return}if(i.status==="ready"){S(i);return}let a=i.auth_url;process.stderr.write(`Open this URL to authenticate:
|
|
522
|
+
${a}
|
|
523
|
+
|
|
524
|
+
`),QM(a),process.stderr.write(`Waiting for authentication to complete (up to 5 minutes)\u2026
|
|
525
|
+
`);let o;try{o=await Tc(t,{waitMs:Zb})}catch(c){b({error:c.message}),process.exit(1)}if(S(o),o.status==="ready"){await Ft(t.dataDir,"activation_authenticated",{id:Je(o.wallet_address)}),process.stderr.write(`Wallet registered: ${o.wallet_address}
|
|
526
|
+
`);return}o.status==="failed"&&(process.stderr.write(`Authentication failed: ${o.reason}
|
|
527
|
+
`),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)},ek=async e=>{let t=O();N(t.dataDir),le(t.appServerUrl);let r=e.includes("--wait")?Zb:0;try{let n=await Tc(t,{waitMs:r});n.status==="ready"&&await Ft(t.dataDir,"activation_authenticated",{id:Je(n.wallet_address)}),S(n)}catch(n){b({error:n.message}),process.exit(1)}};function tk(e,t){return["ambient-ride wallet registration",`address: ${e}`,`nonce: ${t}`,"purpose: prove control of this address (no transaction, no value transfer)"].join(`
|
|
528
|
+
`)}async function rk(e,t,r){let n=await YM({message:t,signature:r});if(n.toLowerCase()!==e.toLowerCase())throw new Error(`MM_ADDRESS_MISMATCH: the challenge signature recovers to ${n}, not ${e}. The wallet did not prove control of the address it reported.`);return!0}var Lu="wallet-connect-metamask.resume.json";function nk(e){return Vn.join(e,Lu)}function ev(e,t,r){At.mkdirSync(e,{recursive:!0});let n=Vn.join(e,t),s=`${n}.${process.pid}.tmp`;At.writeFileSync(s,JSON.stringify(r),{encoding:"utf8",mode:384}),At.renameSync(s,n),At.chmodSync(n,384)}function tv(e,t){At.rmSync(Vn.join(e,t),{force:!0})}function sk(e){let t=nk(e);if(!At.existsSync(t))return;let r;try{r=JSON.parse(At.readFileSync(t,"utf8"))}catch{throw new Error(`MM_CONNECT_RESUME_INVALID: ${Vn.basename(t)} contains malformed JSON.`)}if(typeof r.address!="string"||typeof r.challenge!="string"||typeof r.pollingId!="string"||typeof r.network!="string"||r.label!==null&&typeof r.label!="string")throw new Error("MM_CONNECT_RESUME_INVALID: stored MetaMask approval state is malformed.");return r}function ik(e,t){ev(e,Lu,t)}function Kb(e){tv(e,Lu)}function Yb(e){S({status:"approval_pending",wallet_address:e.address,wallet_type:"metamask",network:e.network,label:e.label,next_step:"Complete the external MetaMask approval, then have the Agent run the same amb wallet-connect-metamask command again."})}function Xa(e,t){let r=e instanceof Error?e.message:String(e),n=r.match(/^(MM_(?:CALL_FAILED|NOT_AUTHENTICATED|LOCKED|CHAIN_UNSUPPORTED|NOT_INSTALLED)):/)?.[1];return n==="MM_NOT_INSTALLED"?r:n?`${n}: MetaMask CLI could not complete ${t}.`:r}function Mu(e){return`wallet-sign-typed-${Qa(e.toLowerCase())}.resume.json`}function ak(e,t){let r=Vn.join(e,Mu(t));if(!At.existsSync(r))return;let n;try{n=JSON.parse(At.readFileSync(r,"utf8"))}catch{throw new Error(`MM_TYPED_SIGN_RESUME_INVALID: ${Vn.basename(r)} contains malformed JSON.`)}if(typeof n.address!="string"||n.method!=="eth_signTypedData_v4"||typeof n.pollingId!="string"||typeof n.typedDataDigest!="string"||typeof n.inputIdentity!="string")throw new Error("MM_TYPED_SIGN_RESUME_INVALID: stored MetaMask typed-sign state is malformed.");return n}function ok(e,t){ev(e,Mu(t.address),t)}function Pu(e,t){tv(e,Mu(t))}function Qa(e){return Qb.createHash("sha256").update(e).digest("hex")}function zb(e){return Qa(JSON.stringify(e))}function Xb(e){S({status:"approval_pending",wallet_address:e.address,sign_method:e.method,next_step:"Complete the external MetaMask approval, then have the Agent run the same amb wallet-sign command again."})}var ck=async e=>{let[t,r]=e,n=O();N(n.dataDir);let s;try{s=sk(n.dataDir)}catch(o){b({error:o.message}),process.exit(1);return}if(s&&(t!==void 0&&t!==s.network||r!==void 0&&r!==s.label)){b({error:"MM_CONNECT_RESUME_MISMATCH: re-run the same wallet-connect-metamask command that created the pending approval."}),process.exit(1);return}let i=s?.network??t,a=i?n.depositNetworks.find(o=>o.name===i):n.depositNetworks[0];if(!a){b({error:"UNKNOWN_NETWORK",message:i?`Network "${i}" not configured. Available: ${n.depositNetworks.map(o=>o.name).join(", ")}`:"No deposit networks are configured for this build."}),process.exit(1);return}try{let o=Pi(),c=zM(o.getAddress());if(Tt(c))throw new Error(`MM_PRIVY_WALLET_CONFLICT: ${c} is already registered as a Privy wallet. Converting it would leave the signing backend ambiguous. Use a different MetaMask account, or remove the Privy registration first.`);let l,u;if(s){if(s.address.toLowerCase()!==c.toLowerCase())throw new Error("MM_ADDRESS_MISMATCH: the active MetaMask wallet changed while approval was pending.");l=s.challenge,u=await o.resumeMessage(s.pollingId)}else{let f=Qb.randomBytes(16).toString("hex");l=tk(c,f);let g=()=>({address:c,challenge:l,pollingId:"",network:a.name,label:r??null});try{u=await o.signMessage(l,1)}catch(h){if(h instanceof et||h instanceof it){s={...g(),pollingId:h.pollingId},ik(n.dataDir,s),Yb(s);return}throw h}}await rk(c,l,u),await _n({rpcUrl:a.rpcUrl,chainId:a.chainId},c)&&process.stderr.write(`warning: ${c} carries EIP-7702 delegate code on ${a.name}. Only plain EOAs are verified so far; deposits and payments from this wallet may revert on chain.
|
|
529
|
+
`);let m=s?.label??r;Rp({wallet_address:c,label:m??void 0}),gn(c),s&&Kb(n.dataDir),S({status:"registered",wallet_address:c,wallet_type:"metamask",network:a.name,label:m??null})}catch(o){if(s&&(o instanceof et||o instanceof it)){Yb(s);return}if(s&&o instanceof Mt){Kb(n.dataDir),b({error:`MM_REQUEST_${o.status}: the pending MetaMask approval ended without a signature.`}),process.exit(1);return}b({error:Xa(o,"wallet registration")}),process.exit(1)}},lk=async e=>{let[t]=e;t||(console.error("error: Usage: amb wallet-balance <wallet_address>"),process.exit(1));let r=O();N(r.dataDir),X(t);try{let n=await sm(t,r);S({wallet_address:t,...n})}catch(n){b({error:"RPC_ERROR",message:`Failed to fetch balance: ${n.message}`}),process.exit(1)}},uk=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=O();N(s.dataDir),X(t),le(s.appServerUrl);let i;try{i=ak(s.dataDir,t)}catch(l){b({error:Xa(l,"typed signature")}),process.exit(1);return}let a=Buffer.from(s.passphrase,"utf8"),o;if(r==="personal_sign")if(At.existsSync(n)){let{message:l,expiresAt:u}=JSON.parse(At.readFileSync(n,"utf8"));Date.now()/1e3>u&&(b({error:"SIWE message expired. Run `amb siwe-request-message` again."}),process.exit(1)),o=l}else o=n.replace(/\\n/g,`
|
|
530
|
+
`);else if(At.existsSync(n)){let l=JSON.parse(At.readFileSync(n,"utf8")),u=l.typedData??l;if(typeof l.expiresAt=="number"&&Date.now()/1e3>l.expiresAt){if(i&&(i.inputIdentity!==Qa(n)||i.typedDataDigest!==zb(u))){b({error:"MM_TYPED_SIGN_RESUME_MISMATCH: the expired typed file is not the pending approval input."}),process.exit(1);return}i&&Pu(s.dataDir,t),b({error:"Typed-data challenge expired. Run `amb siwe-request-typed` again."}),process.exit(1);return}o=u}else try{o=JSON.parse(n)}catch{b({error:"eth_signTypedData_v4 requires valid JSON typed data or a typed file path"}),process.exit(1)}let c=r==="eth_signTypedData_v4"&&typeof o!="string"?{digest:zb(o),inputIdentity:Qa(n)}:void 0;if(i){if(r!==i.method||t.toLowerCase()!==i.address.toLowerCase()||!c||c.digest!==i.typedDataDigest||c.inputIdentity!==i.inputIdentity){b({error:"MM_TYPED_SIGN_RESUME_MISMATCH: re-run the exact wallet-sign command that created the pending approval."}),process.exit(1);return}try{let l=Tr(t);if(!l?.resumeTypedData)throw new Error("MM_TYPED_SIGN_RESUME_UNAVAILABLE: registered wallet cannot resume typed-data approval.");let u=await l.resumeTypedData(i.pollingId,o);Pu(s.dataDir,t),S({wallet_signature:u});return}catch(l){if(l instanceof et||l instanceof it){Xb(i);return}if(l instanceof Mt){Pu(s.dataDir,t),b({error:`MM_REQUEST_${l.status}: the pending MetaMask typed signature ended without a signature.`}),process.exit(1);return}b({error:Xa(l,"typed signature")}),process.exit(1);return}}try{let l=await br({wallet_address:t,sign_method:r,message:o},s,a);S(l)}catch(l){if(c&&(l instanceof et||l instanceof it)){i={address:t,method:"eth_signTypedData_v4",pollingId:l.pollingId,typedDataDigest:c.digest,inputIdentity:c.inputIdentity},ok(s.dataDir,i),Xb(i);return}b({error:Xa(l,"typed signature")}),process.exit(1)}},dk=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=O();N(a.dataDir),X(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);S(c)}catch(c){b({error:c.message}),process.exit(1)}},rv={"wallet-status":XM,"wallet-setup":ZM,"wallet-setup-verify":ek,"wallet-connect-metamask":ck,"wallet-balance":lk,"wallet-sign":uk,"wallet-send-tx":dk};p();import{randomUUID as Kk}from"crypto";import{encodeFunctionData as Yk,formatUnits as zk}from"viem";p();import{maxUint256 as wv}from"viem";p();import{encodeFunctionData as ku,parseAbi as pk}from"viem";var mk=pk(["function approve(address spender, uint256 amount) returns (bool)"]);function Uu(e,t){return ku({abi:mk,functionName:"approve",args:[e,t]})}function nv(e,t){return ku({abi:yn,functionName:"depositMVL",args:[e,t]})}function sv(){return ku({abi:yn,functionName:"withdraw",args:[]})}p();import iv from"fs";import fk from"crypto";function gk(e){let[t,r=""]=e.split("."),n=r.padEnd(18,"0").slice(0,18);return"0x"+(BigInt(t)*BigInt("1000000000000000000")+BigInt(n)).toString(16)}function hk(e){let t=e?.status;if(typeof t=="number")return t;let r=e instanceof Error?e.message:String(e??""),n=/^HTTP (\d{3})\b/.exec(r);return n?Number(n[1]):void 0}var Za=class extends Error{status;constructor(t){super(t instanceof Error?t.message:String(t??"")),this.name="WalletSendCallsSubmissionError",this.status=hk(t)}};function av(e){if(!(e instanceof Za))return!1;let{status:t}=e;return t===void 0||t>=500||[408,409,425,429].includes(t)}async function eo(e,t,r){let{wallet_address:n,chain_id:s,calls:i,sponsor:a}=e,o=Ye(n);if(!o)throw new Error(`Wallet not found: ${n}`);let c=Tt(n);if(!c)throw new Error("BATCH_NOT_SUPPORTED: atomic batches need Privy's EIP-5792 wallet_sendCalls, which does not exist for external wallets \u2014 the mm CLI exposes no batch command. Deposit USDC instead (fully gas-free for external wallets), or use the MVL signature path.");let l=at(t.keysDir,c.k_i_key_path);if(!iv.existsSync(l))throw new Error(`Key file not found: ${l}`);let u=iv.readFileSync(l),d=Wt(u,r),m=d.toString("utf8");try{let f=Date.now(),g=Yi(f,m),h;try{h=await ki({walletId:c.wallet_id,quorumId:c.quorum_id,kIPub:c.k_i_pub,timestamp:f,kISig:g})}catch(C){throw(C instanceof Error?C.message:String(C)).includes("HTTP 401")&&or(o.wallet_address,"Unauthorized (401)"),C}if(!h.valid)throw or(o.wallet_address,h.reason??"Server returned valid:false"),new Error(`Wallet validation failed: ${h.reason??"unknown reason"}`);let E=i.map(C=>({to:C.to,value:gk(C.value_eth),...C.data?{data:C.data}:{}})),T={method:"wallet_sendCalls",caip2:`eip155:${s}`,chain_type:"ethereum",...a?{sponsor:!0}:{},params:{calls:E}},w=`${Date.now()}:${fk.randomUUID()}`,v=Tn(c.wallet_id,T,m,t.privyAppId,{"privy-idempotency-key":w}),A;try{if(A=await Np({walletId:c.wallet_id,caip2:`eip155:${s}`,calls:E,idempotencyKey:w,kISig:v,...a?{sponsor:!0}:{}}),typeof A.transactionId!="string"||A.transactionId.trim()==="")throw new Error("wallet_sendCalls response did not contain a transaction ID")}catch(C){throw new Za(C)}return{kind:"transaction_id",transaction_id:A.transactionId,caip2:A.caip2}}finally{vt(d)}}p();import Sk from"crypto";p();import{getAddress as ov}from"viem";import{createSiweMessage as _k,parseSiweMessage as yk}from"viem/siwe";var cv=60;function Ek(e){try{let t=e.split(".")[1];if(!t)return null;let r=JSON.parse(Buffer.from(t,"base64url").toString("utf8")),n=r.addr??r.customPayload?.addr;return typeof n=="string"?n:null}catch{return null}}function Tk(e,t){try{return ov(e)===ov(t)}catch{return!1}}async function Js(e,t,r){let n=await Cp({walletAddress:e,chainId:t},r),s=_k({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,nonce:n.nonce}}async function to(e,t,r){let n=yk(e),s=Math.floor(Date.now()/1e3),i=n.address,{flag:a}=await yc(i,r),o=a?await Pp({message:e,signature:t},r):await Lp({message:e,signature:t},r),{accessToken:c,expiresIn:l}=o,u=s+l-cv;return vc(n.address,c,u),Et(`[jwt-debug] SET cache_key=${n.address} expires_at=${u} now=${s} expiresIn=${l} pid=${process.pid}
|
|
531
|
+
`),{accessToken:c,expiresIn:l}}async function lv(e,t,r,n,s){let i=Math.floor(Date.now()/1e3),{flag:a}=await yc(e,s),o=a?await Mp({nonce:r,signature:n},s):await kp({nonce:r,signature:n},s),{accessToken:c,expiresIn:l}=o,u=Ek(c);if(!u||!Tk(u,e))throw new Error("typed-data login identity mismatch: token wallet does not match the requested wallet");let d=i+l-cv;return vc(e,c,d),Et(`[jwt-debug] SET (typed) cache_key=${e} expires_at=${d} now=${i} expiresIn=${l} pid=${process.pid}
|
|
532
|
+
`),{accessToken:c,expiresIn:l}}function De(e){return ce(e)}p();import{hashTypedData as bk,parseSignature as vk,concat as Rk,toHex as wk,keccak256 as Ak,toBytes as xk}from"viem";var pW=Ak(xk("Kernel(bytes32 hash)"));function ro(e){return bk(e)}function no(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 so(e){let{r:t,s:r,yParity:n}=vk(e),s=BigInt(r)|BigInt(n)<<255n;return Rk(["0x00",t,wk(s,{size:32})])}p();async function uv(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}`)}var Fu="ROUTER_SIG";function Ik(e){let{capability:t,params:r}=e;return{domain:{name:t.domainName,version:t.domainVersion,chainId:t.chainId,verifyingContract:t.signingContractAddress},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 qu(e,t,r){let n=r.toLowerCase();return e.find(s=>s.network===t&&s.tokenAddress.toLowerCase()===n)}function ju(e){return Math.floor(Date.now()/1e3)+e+60}function Bu(){return"0x"+Sk.randomBytes(32).toString("hex")}async function Vu(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 Dk(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 l=ro(t),u=no({kernelDomain:n,innerDigest:l}),{wallet_signature:d}=await s({wallet_address:o,sign_method:"eth_signTypedData_v4",message:u},i,a);return so(d)}let{wallet_signature:c}=await s({wallet_address:o,sign_method:"eth_signTypedData_v4",message:t},i,a);return c}var fr=class extends Error{constructor(r,n,s){super(r===void 0?`POST /relay outcome unknown: ${n}`:`POST /relay failed (${r}): ${n}`);this.status=r;this.detail=n;this.code=s;this.name="RelaySubmitHttpError"}status;detail;code};function Ok(e){return e instanceof fr?typeof e.status=="number"&&e.status>=400&&e.status<500&&![408,409,425,429].includes(e.status):!1}function dv(e){return e instanceof fr&&!Ok(e)}var Nk=/^[A-Za-z0-9_-]{1,128}$/;function pv(e){if(!e||typeof e!="object")return;let t=e;if(!(typeof t.requestId!="string"||!Nk.test(t.requestId)||!["PENDING","SUBMITTED","CONFIRMED","FAILED"].includes(String(t.status))||!["txHash","errorCode","errorMessage"].every(r=>t[r]==null||typeof t[r]=="string")))return{requestId:t.requestId,status:t.status,...typeof t.txHash=="string"?{txHash:t.txHash}:{},...typeof t.errorCode=="string"?{errorCode:t.errorCode}:{},...typeof t.errorMessage=="string"?{errorMessage:t.errorMessage}:{}}}var Ck=new Set(["SIGNATURE_EXPIRED"]);function mv(e){return e instanceof fr&&typeof e.status=="number"&&e.status>=400&&e.status<500&&e.code!==void 0&&Ck.has(e.code)}async function Hu(e,t,r){let n;try{n=await fetch(`${r.gatewayServerUrl.replace(/\/$/,"")}/v1/agent-deposit/relay`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)})}catch{throw new fr(void 0,"transport failed after request began")}if(n.ok){let o;try{o=await n.json()}catch{throw new fr(void 0,"response body was unavailable")}let c=pv(o);if(!c)throw new fr(void 0,"response body did not match the relay contract");return c}let s=await n.text().catch(()=>""),i,a=s;try{let o=JSON.parse(s);i=typeof o.code=="string"?o.code:void 0,(o.code||o.message)&&(a=`${o.code??""} ${o.message??""}`.trim())}catch{}throw a||(a=`HTTP ${n.status}`),new fr(n.status,a,i)}function Gu(e){return{request_id:e.requestId,status:e.status,tx_hash:e.txHash,error_code:e.errorCode,error_message:e.errorMessage}}async function io(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),1e4);s.unref();try{let i=await fetch(`${r.gatewayServerUrl.replace(/\/$/,"")}/v1/agent-deposit/relay/${encodeURIComponent(t)}`,{method:"GET",headers:{Authorization:`Bearer ${e}`},signal:n.signal});if(i.ok){let o;try{o=await i.json()}catch{throw new Error("GET relay status contract response was invalid")}let c=pv(o);if(!c||c.requestId!==t)throw new Error("GET relay status contract response was invalid");return c}let a=await i.text().catch(()=>"");throw new Error(`GET /relay/${t} failed (${i.status}): ${a||"no body"}`)}finally{clearTimeout(s)}}function fv(e){return e!=null&&"unavailable"in e}async function Pk(e){let{params:t,network:r,config:n,passphrase:s,jwtProvider:i,capabilitiesFetcher:a,priceQuoteFetcher:o,smartAccountProbe:c,walletSigner:l,relaySubmitter:u}=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=qu(m.capabilities,r.name,t.token);if(!f)return{unavailable:"NO_CAPABILITY"};if(f.method!=="AUTHORIZATION")throw new Error(`UNSUPPORTED_RELAY_METHOD: convertible-token relay expected AUTHORIZATION, got ${f.method}`);let g=await o(d,{network:r.name,tokenAddress:t.token,tokenAmount:t.amount},n),h={from:t.wallet_address,to:f.depositContractAddress,value:t.amount,validAfter:"0",validBefore:ju(m.deadlineMinBufferSec).toString(),nonce:Bu()},E=Ik({capability:f,params:h}),{isSmartAccount:T,kernelDomain:w}=await c(r,t.wallet_address),v=await Dk({typedData:E,agent:t.wallet_address,isSmartAccount:T,kernelDomain:w,walletSigner:l,config:n,passphrase:s}),A=await u(d,{network:r.name,tokenAddress:t.token,params:{...h,quote:{mvlAmount:g.quote.mvlAmount,nonce:g.quote.nonce,timestamp:g.quote.timestamp,deadline:g.quote.deadline},quoteSignature:g.signature},signature:v},n);return{path:"relay",request_id:A.requestId,status:A.status,mvl_amount:g.quote.mvlAmount,tx_hash:A.txHash,error_code:A.errorCode,error_message:A.errorMessage,next_step:`Run \`amb deposit-relay-status ${t.wallet_address} ${A.requestId}\` until status is CONFIRMED or FAILED`}}var Lk=new Set(["CONFIRMED","FAILED"]);async function gv(e,t,r,n={}){let s=n.intervalMs??3e3,i=n.timeoutMs??12e4,a=Date.now()+i,o=await io(e,t,r);for(;!Lk.has(o.status)&&Date.now()<a;)await new Promise(c=>setTimeout(c,s)),o=await io(e,t,r);return o}function hv(e){return Pk({...e,jwtProvider:De,capabilitiesFetcher:Vu,priceQuoteFetcher:uv,smartAccountProbe:async(t,r)=>{let n=await _n(t,r);return{isSmartAccount:n,kernelDomain:n?await Li(t,r):void 0}},walletSigner:br,relaySubmitter:Hu})}p();async function ao(e,t,r,n,s,i,a={}){let o=a.intervalMs??3e3,c=a.timeoutMs??12e4,l=Date.now()+c,u=await bs(e,t,r,n);for(;!s(u)&&Date.now()<l;)await new Promise(d=>setTimeout(d,o)),u=await bs(e,t,r,n);if(!s(u))throw new Error(`ALLOWANCE_NOT_CONFIRMED: approve (approval reference ${i??"unknown"}) did not reflect on-chain within ${c}ms (current allowance ${u.toString()}). Re-run deposit-add; the on-chain allowance will be reused and any already-mined approve skipped.`)}p();function $u(e){return{domain:{name:e.domainName,version:e.domainVersion,chainId:e.chainId,verifyingContract:e.signingContractAddress},types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}],DepositMVL:[{name:"agent",type:"address"},{name:"amount",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},primaryType:"DepositMVL",message:{agent:e.agent,amount:e.amount.toString(),nonce:e.nonce.toString(),deadline:e.deadline.toString()}}}p();import{randomUUID as Mk}from"crypto";var kk=600;function Uk(){return Math.floor(Date.now()/1e3)}function zt(e){return{walletAddress:e.walletAddress.toLowerCase(),network:e.network,tokenAddress:e.tokenAddress.toLowerCase()}}function Ks(e){let t=zt(e);return x().prepare(`
|
|
533
|
+
SELECT * FROM mvl_relay_submissions
|
|
534
|
+
WHERE wallet_address = ? AND network = ? AND token_address = ?
|
|
535
|
+
`).get(t.walletAddress,t.network,t.tokenAddress)}function co(e){if(e.status==="PREPARING"||!e.body_json)throw new Error("MVL_DEPOSIT_STATE_CORRUPT: pending relay row has no signed body");let t;try{t=JSON.parse(e.body_json)}catch{throw new Error("MVL_DEPOSIT_STATE_CORRUPT: pending relay body is not valid JSON")}if(t.method!=="ROUTER_SIG"||t.network!==e.network||t.tokenAddress.toLowerCase()!==e.token_address||t.params.agent.toLowerCase()!==e.wallet_address||t.params.amount!==e.amount_raw)throw new Error("MVL_DEPOSIT_STATE_CORRUPT: pending relay body does not match its intent key");return{walletAddress:e.wallet_address,network:e.network,tokenAddress:e.token_address,amount:e.amount_raw,body:t,...e.approve_tx?{approveTx:e.approve_tx}:{},...e.request_id?{requestId:e.request_id}:{},status:e.status}}function Fk(e){if(!e.wallet_request_kind&&!e.wallet_polling_id&&!e.wallet_request_json)return;if(!e.wallet_request_kind||!e.wallet_polling_id)throw new Error("MVL_DEPOSIT_STATE_CORRUPT: pending wallet request coordinates are incomplete");if(e.wallet_request_kind==="APPROVE"){if(e.wallet_request_json)throw new Error("MVL_DEPOSIT_STATE_CORRUPT: approval request unexpectedly has a typed draft");return{kind:"APPROVE",pollingId:e.wallet_polling_id}}if(!e.wallet_request_json)throw new Error("MVL_DEPOSIT_STATE_CORRUPT: typed-data request has no draft");let t;try{t=JSON.parse(e.wallet_request_json)}catch{throw new Error("MVL_DEPOSIT_STATE_CORRUPT: typed-data draft is not valid JSON")}if(!t||typeof t!="object")throw new Error("MVL_DEPOSIT_STATE_CORRUPT: typed-data draft is not an object");let{draft:r,typedData:n}=t;if(!r||!n||typeof n!="object"||r.method!=="ROUTER_SIG"||r.network!==e.network||typeof r.tokenAddress!="string"||r.tokenAddress.toLowerCase()!==e.token_address||!r.params||typeof r.params.agent!="string"||r.params.agent.toLowerCase()!==e.wallet_address||typeof r.params.amount!="string"||r.params.amount!==e.amount_raw||typeof r.params.nonce!="string"||!/^[0-9]+$/.test(r.params.nonce)||typeof r.params.deadline!="string"||!/^[0-9]+$/.test(r.params.deadline))throw new Error("MVL_DEPOSIT_STATE_CORRUPT: typed-data draft does not match its intent key");return{kind:"TYPED_DATA",pollingId:e.wallet_polling_id,draft:r,typedData:n}}function oo(e){let t=e.request_id?` (request ${e.request_id}, ${e.status})`:"";return new Error(`MVL_DEPOSIT_IN_FLIGHT: an unresolved MVL deposit of ${e.amount_raw} already exists${t}; wait for it to reach CONFIRMED or FAILED before starting another amount.`)}function Wu(e){return new Error(`MVL_DEPOSIT_PREPARING: another process is preparing an MVL deposit of ${e.amount_raw}; the safety lease is held through unix ${e.lease_expires_at}. Do not retry while MetaMask approval is pending.`)}function _v(e,t={}){let r=x(),n=zt(e),s=t.nowSec??Uk(),i=t.leaseSec??kk,a=Mk(),o=s+i;return r.transaction(()=>{if(r.prepare(`
|
|
536
|
+
INSERT INTO mvl_relay_submissions (
|
|
537
|
+
wallet_address, network, token_address, amount_raw, status, owner_id, lease_expires_at,
|
|
538
|
+
client_attempt_id
|
|
539
|
+
) VALUES (?, ?, ?, ?, 'PREPARING', ?, ?, ?)
|
|
540
|
+
ON CONFLICT(wallet_address, network, token_address) DO NOTHING
|
|
541
|
+
`).run(n.walletAddress,n.network,n.tokenAddress,e.amount,a,o,e.clientAttemptId??null).changes===1)return{kind:"owner",ownerId:a};let l=Ks(n);if(!l)throw new Error("MVL_DEPOSIT_STATE_LOST: active relay claim disappeared");if(l.status!=="PREPARING"){if(l.amount_raw!==e.amount)throw oo(l);return{kind:"resume",submission:co(l)}}let u=Fk(l);if(u){if(l.amount_raw!==e.amount)throw oo(l);if(!l.owner_id)throw new Error("MVL_DEPOSIT_STATE_CORRUPT: pending wallet request has no owner");return{kind:"owner",ownerId:l.owner_id,...l.approve_tx?{approveTx:l.approve_tx}:{},pendingRequest:u}}if(l.lease_expires_at==null||l.lease_expires_at>=s)throw Wu(l);if(r.prepare(`
|
|
542
|
+
UPDATE mvl_relay_submissions
|
|
543
|
+
SET amount_raw = ?, owner_id = ?, lease_expires_at = ?, updated_at = ?
|
|
544
|
+
WHERE wallet_address = ? AND network = ? AND token_address = ?
|
|
545
|
+
AND status = 'PREPARING' AND lease_expires_at < ?
|
|
546
|
+
`).run(e.amount,a,o,s,n.walletAddress,n.network,n.tokenAddress,s).changes===1)return{kind:"owner",ownerId:a,...l.approve_tx?{approveTx:l.approve_tx}:{}};if(l=Ks(n),!l)throw new Error("MVL_DEPOSIT_STATE_LOST: active relay claim disappeared");if(l.status==="PREPARING")throw Wu(l);if(l.amount_raw!==e.amount)throw oo(l);return{kind:"resume",submission:co(l)}})()}function yv(e){let t=Ks(e);if(!(!t||t.amount_raw!==e.amount))return t.client_attempt_id??void 0}function Ju(e,t,r,n,s){let i=zt(e),a=JSON.stringify(r);if(x().prepare(`
|
|
547
|
+
UPDATE mvl_relay_submissions
|
|
548
|
+
SET body_json = ?, approve_tx = COALESCE(?, approve_tx), status = 'PREPARED',
|
|
549
|
+
owner_id = NULL, lease_expires_at = NULL,
|
|
550
|
+
wallet_request_kind = NULL, wallet_polling_id = NULL, wallet_request_json = NULL,
|
|
551
|
+
updated_at = strftime('%s','now')
|
|
552
|
+
WHERE wallet_address = ? AND network = ? AND token_address = ?
|
|
553
|
+
AND status = 'PREPARING' AND owner_id = ? AND amount_raw = ?
|
|
554
|
+
AND ${s?"wallet_polling_id = ?":"wallet_polling_id IS NULL"}
|
|
555
|
+
`).run(a,n??null,i.walletAddress,i.network,i.tokenAddress,t,e.amount,...s?[s]:[]).changes===1)return co(Ks(i));let c=Ks(i);if(!c)throw new Error("MVL_DEPOSIT_STATE_LOST: relay claim disappeared before signing completed");if(c.status==="PREPARING")throw Wu(c);if(c.amount_raw!==e.amount)throw oo(c);return co(c)}function Ku(e,t,r){let n=zt(e);if(x().prepare(`
|
|
556
|
+
UPDATE mvl_relay_submissions
|
|
557
|
+
SET wallet_request_kind = ?, wallet_polling_id = ?, wallet_request_json = ?,
|
|
558
|
+
updated_at = strftime('%s','now')
|
|
559
|
+
WHERE wallet_address = ? AND network = ? AND token_address = ?
|
|
560
|
+
AND status = 'PREPARING' AND owner_id = ? AND wallet_polling_id IS NULL
|
|
561
|
+
`).run(r.kind,r.pollingId,r.kind==="TYPED_DATA"?JSON.stringify({draft:r.draft,typedData:r.typedData}):null,n.walletAddress,n.network,n.tokenAddress,t).changes!==1)throw new Error("MVL_DEPOSIT_STATE_LOST: could not persist the pending wallet request")}function Ev(e,t,r){let n=zt(e);if(x().prepare(`
|
|
562
|
+
UPDATE mvl_relay_submissions
|
|
563
|
+
SET approve_tx = ?, updated_at = strftime('%s','now')
|
|
564
|
+
WHERE wallet_address = ? AND network = ? AND token_address = ?
|
|
565
|
+
AND status = 'PREPARING' AND owner_id = ?
|
|
566
|
+
`).run(r,n.walletAddress,n.network,n.tokenAddress,t).changes!==1)throw new Error("MVL_DEPOSIT_STATE_LOST: could not persist the approval transaction")}function Tv(e,t,r,n){let s=zt(e);return x().prepare(`
|
|
567
|
+
UPDATE mvl_relay_submissions
|
|
568
|
+
SET approve_tx = ?, wallet_request_kind = NULL, wallet_polling_id = NULL,
|
|
569
|
+
wallet_request_json = NULL, updated_at = strftime('%s','now')
|
|
570
|
+
WHERE wallet_address = ? AND network = ? AND token_address = ?
|
|
571
|
+
AND status = 'PREPARING' AND owner_id = ?
|
|
572
|
+
AND wallet_request_kind = 'APPROVE' AND wallet_polling_id = ?
|
|
573
|
+
`).run(n,s.walletAddress,s.network,s.tokenAddress,t,r).changes===1}function Yu(e,t,r){let n=zt(e);return x().prepare(`
|
|
574
|
+
DELETE FROM mvl_relay_submissions
|
|
575
|
+
WHERE wallet_address = ? AND network = ? AND token_address = ?
|
|
576
|
+
AND status = 'PREPARING' AND owner_id = ? AND wallet_polling_id = ?
|
|
577
|
+
`).run(n.walletAddress,n.network,n.tokenAddress,t,r).changes===1}function bv(e,t){let r=zt(e);x().prepare(`
|
|
578
|
+
DELETE FROM mvl_relay_submissions
|
|
579
|
+
WHERE wallet_address = ? AND network = ? AND token_address = ?
|
|
580
|
+
AND status = 'PREPARING' AND owner_id = ?
|
|
581
|
+
`).run(r.walletAddress,r.network,r.tokenAddress,t)}function vv(e,t,r){let n=zt(e),s=JSON.stringify(t),i=r.status==="PENDING"||r.status==="SUBMITTED"?r.status:null;x().prepare(`
|
|
582
|
+
UPDATE mvl_relay_submissions
|
|
583
|
+
SET request_id = ?, status = COALESCE(?, status), updated_at = strftime('%s','now')
|
|
584
|
+
WHERE wallet_address = ? AND network = ? AND token_address = ? AND body_json = ?
|
|
585
|
+
`).run(r.requestId,i,n.walletAddress,n.network,n.tokenAddress,s)}function Rv(e,t){let r=zt(e);x().prepare(`
|
|
586
|
+
DELETE FROM mvl_relay_submissions
|
|
587
|
+
WHERE wallet_address = ? AND network = ? AND token_address = ? AND body_json = ?
|
|
588
|
+
`).run(r.walletAddress,r.network,r.tokenAddress,JSON.stringify(t))}function Ys(e){x().prepare("DELETE FROM mvl_relay_submissions WHERE request_id = ?").run(e)}async function Av(e,t,r,n,s){if(!/^[1-9][0-9]*$/.test(e.amount))throw new Error("INVALID_AMOUNT: amount must be a canonical positive decimal integer");let i=BigInt(e.amount);if(i===0n||i>wv)throw new Error("INVALID_AMOUNT: amount must be greater than 0 and no greater than uint256.max");let a=await Fr(t);if(e.token.toLowerCase()!==a.toLowerCase()){try{await s?.onPathResolved?.("relay")}catch{}let l=await hv({params:e,network:t,config:r,passphrase:n});if(fv(l))throw new Error(l.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 (${a}) is always accepted through the wallet's MVL path. 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. MVL (${a}) remains available through the wallet's MVL path.`);return l}let o=Tr(e.wallet_address);if(o){try{await s?.onPathResolved?.("relay")}catch{}let l=De(e.wallet_address);if(!l)throw new Error("JWT_NOT_FOUND: No cached JWT for this MetaMask wallet. Run siwe-request-typed, wallet-sign with eth_signTypedData_v4, then typed-submit.");let u=await Vu(l,r);if(!u)throw new Error(`RELAY_UNAVAILABLE: the agent-deposit relay could not be reached for ${t.name}.`);let d=qu(u.capabilities,t.name,e.token);if(!d||d.method!==Fu)throw new Error(`TOKEN_NOT_DEPOSITABLE: the deposit relay has no ROUTER_SIG capability for MVL ${e.token} on ${t.name}.`);let m=t.depositContract.toLowerCase(),f=[...d.chainId===t.chainId?[]:[`chainId ${d.chainId} != ${t.chainId}`],...d.depositContractAddress.toLowerCase()===m?[]:[`depositContractAddress ${d.depositContractAddress} != ${t.depositContract}`],...d.signingContractAddress.toLowerCase()===m?[]:[`signingContractAddress ${d.signingContractAddress} != ${t.depositContract}`]];if(f.length>0)throw new Error(`CAPABILITY_MISMATCH: relay capability does not match local ${t.name} config: ${f.join("; ")}`);let g={walletAddress:e.wallet_address,network:t.name,tokenAddress:e.token},h=_v({...g,amount:e.amount,clientAttemptId:s?.attemptId});if(h.kind==="resume"){let A=await zu(l,g,h.submission,r);return Xu(e,h.submission.approveTx,A)}let E,T=h.pendingRequest!==void 0,w=h.approveTx!==void 0;try{let A=h.approveTx;if(h.pendingRequest?.kind==="TYPED_DATA"){if(!o.resumeTypedData)throw new Error("MM_CALL_FAILED: the active MetaMask signer cannot resume typed-data requests");let ee=h.pendingRequest.draft,te=$u({domainName:d.domainName,domainVersion:d.domainVersion,signingContractAddress:d.signingContractAddress,chainId:d.chainId,agent:ee.params.agent,amount:BigInt(ee.params.amount),nonce:BigInt(ee.params.nonce),deadline:BigInt(ee.params.deadline)});if(JSON.stringify(te)!==JSON.stringify(h.pendingRequest.typedData))throw new Error("CAPABILITY_MISMATCH: persisted MetaMask typed data no longer matches relay capability");let pe;try{pe=await o.resumeTypedData(h.pendingRequest.pollingId,h.pendingRequest.typedData)}catch(nr){throw(nr instanceof Mt||nr instanceof Error&&nr.message.startsWith("MM_ADDRESS_MISMATCH:"))&&Yu(g,h.ownerId,h.pendingRequest.pollingId)&&(T=!1),nr}let St={...ee,signature:pe};E=Ju({...g,amount:e.amount},h.ownerId,St,void 0,h.pendingRequest.pollingId);let rr=await zu(l,g,E,r);return Xu(e,E.approveTx,rr)}if(h.pendingRequest?.kind==="APPROVE"){if(!o.resumeTransaction)throw new Error("MM_CALL_FAILED: the active MetaMask signer cannot resume transaction requests");try{A=o.resumeTransaction(h.pendingRequest.pollingId).tx_hash}catch(ee){throw ee instanceof Mt&&Yu(g,h.ownerId,h.pendingRequest.pollingId)&&(T=!1),ee}if(!Tv(g,h.ownerId,h.pendingRequest.pollingId,A))throw new Error("MVL_DEPOSIT_RESUME_RACE: another process already continued this wallet request");T=!1,w=!0,await ao(t,e.token,e.wallet_address,d.depositContractAddress,ee=>ee>=i,A),w=!1}else A&&h.pendingRequest===void 0&&(await ao(t,e.token,e.wallet_address,d.depositContractAddress,ee=>ee>=i,A),w=!1);let C=await em(t,e.token,e.wallet_address);if(C<i)throw new Error(`INSUFFICIENT_MVL_BALANCE: depositing ${e.amount} needs at least that much MVL, but ${e.wallet_address} holds ${C.toString()} on ${t.name}.`);if(await bs(t,e.token,e.wallet_address,d.depositContractAddress)<i&&!A){if(await Ki(t,e.wallet_address)===0n)throw new Error(`INSUFFICIENT_GAS: approving MVL needs native gas on ${t.name}, and ${e.wallet_address} holds none. Fund the address, then retry.`);let te;try{te=o.sendTransaction({to:e.token,value:"0x0",data:Uu(d.depositContractAddress,wv)},d.chainId)}catch(pe){throw(pe instanceof et||pe instanceof it)&&pe.kind==="transaction"&&(T=!0,Ku(g,h.ownerId,{kind:"APPROVE",pollingId:pe.pollingId})),pe}A=te.tx_hash,w=!0,Ev(g,h.ownerId,A),await ao(t,e.token,e.wallet_address,d.depositContractAddress,pe=>pe>=i,A),w=!1}let L=BigInt(Bu()),W=BigInt(ju(u.deadlineMinBufferSec)),Z=$u({domainName:d.domainName,domainVersion:d.domainVersion,signingContractAddress:d.signingContractAddress,chainId:d.chainId,agent:e.wallet_address,amount:i,nonce:L,deadline:W}),V={network:t.name,method:Fu,tokenAddress:e.token,params:{agent:e.wallet_address,amount:e.amount,nonce:L.toString(),deadline:W.toString()}},Y;try{Y=await o.signTypedData(Z,d.chainId)}catch(ee){throw(ee instanceof et||ee instanceof it)&&ee.kind==="typed-data"&&(T=!0,Ku(g,h.ownerId,{kind:"TYPED_DATA",pollingId:ee.pollingId,draft:V,typedData:Z})),ee}let ge={...V,signature:Y};E=Ju({...g,amount:e.amount},h.ownerId,ge,A)}catch(A){throw A instanceof Error&&A.message.startsWith("ALLOWANCE_NOT_CONFIRMED:")&&(w=!1),!T&&!w&&bv(g,h.ownerId),A}let v=await zu(l,g,E,r);return Xu(e,E.approveTx,v)}try{await s?.onPathResolved?.("mvl-direct")}catch{}let c=await eo({wallet_address:e.wallet_address,chain_id:t.chainId,sponsor:!0,calls:[{to:e.token,value_eth:"0",data:Uu(t.depositContract,i)},{to:t.depositContract,value_eth:"0",data:nv(e.wallet_address,i)}]},r,n);return{path:"mvl-direct",token:e.token,agent:e.wallet_address,amount:e.amount,batch_tx:c}}async function zu(e,t,r,n){let s;try{s=await Hu(e,r.body,n)}catch(i){throw mv(i)&&Rv(t,r.body),i}return vv(t,r.body,s),s}function Xu(e,t,r){return{path:"mvl-sig-relay",token:e.token,agent:e.wallet_address,amount:e.amount,...t?{approve_tx:t}:{},request_id:r.requestId,status:r.status,mvl_amount:e.amount,tx_hash:r.txHash,error_code:r.errorCode,error_message:r.errorMessage,next_step:`Run \`amb deposit-relay-status ${e.wallet_address} ${r.requestId}\` until status is CONFIRMED or FAILED`}}p();import Zr from"fs";import lo from"path";import{createHash as qk}from"crypto";function Qu(e){return`deposit-withdraw-${qk("sha256").update(e.toLowerCase()).digest("hex")}.resume.json`}function jk(e,t){let r=lo.join(e,Qu(t));if(!Zr.existsSync(r))return;let n;try{n=JSON.parse(Zr.readFileSync(r,"utf8"))}catch{throw new Error(`MM_WITHDRAW_RESUME_INVALID: ${lo.basename(r)} contains malformed JSON.`)}if(typeof n.walletAddress!="string"||typeof n.network!="string"||typeof n.pollingId!="string")throw new Error("MM_WITHDRAW_RESUME_INVALID: stored MetaMask withdrawal state is malformed.");return n}function Bk(e,t){Zr.mkdirSync(e,{recursive:!0});let r=lo.join(e,Qu(t.walletAddress)),n=`${r}.${process.pid}.tmp`;Zr.writeFileSync(n,JSON.stringify(t),{encoding:"utf8",mode:384}),Zr.renameSync(n,r),Zr.chmodSync(r,384)}function xv(e,t){Zr.rmSync(lo.join(e,Qu(t)),{force:!0})}function Sv(e){let t=e instanceof et?"MM_APPROVAL_PENDING":"MM_REQUEST_INDETERMINATE";return new Error(`${t}: MetaMask has not completed this withdrawal. Complete any external approval, then have the Agent run the same \`amb deposit-withdraw\` command again; no new transaction will be submitted.`)}async function Iv(e,t,r,n){let s=Ye(e.wallet_address)?.wallet_type==="metamask",i=sv(),a=s?jk(r.dataDir,e.wallet_address):void 0;if(a){if(a.walletAddress.toLowerCase()!==e.wallet_address.toLowerCase()||a.network!==t.name)throw new Error("MM_WITHDRAW_RESUME_MISMATCH: re-run the same deposit-withdraw command that created the pending approval.");try{let u=await lr({wallet_address:e.wallet_address,to:t.depositContract,value_eth:"0",chain_id:t.chainId,data:i,sponsor:!1,resume_polling_id:a.pollingId},r,n);return xv(r.dataDir,e.wallet_address),{path:"mvl-withdraw",agent:e.wallet_address,withdraw_tx:u}}catch(u){throw u instanceof Mt&&xv(r.dataDir,e.wallet_address),u instanceof et||u instanceof it?Sv(u):u}}let o=await Ji(t,e.wallet_address),c=BigInt(Math.floor(Date.now()/1e3));if(o>c){let u=Number(o-c),d=Math.ceil(u/60);throw new Error(`WITHDRAW_COOLDOWN: next withdraw allowed at unix ${o.toString()} (~${d} min from now). v2 enforces a per-agent withdraw cooldown.`)}if(s&&await Ki(t,e.wallet_address)===0n)throw new Error(`INSUFFICIENT_GAS: MetaMask withdrawal needs native gas on ${t.name}, and ${e.wallet_address} holds none. Fund the address, then retry the same command.`);let l;try{l=await lr({wallet_address:e.wallet_address,to:t.depositContract,value_eth:"0",chain_id:t.chainId,data:i,sponsor:!s},r,n)}catch(u){throw s&&(u instanceof et||u instanceof it)&&u.kind==="transaction"?(Bk(r.dataDir,{walletAddress:e.wallet_address,network:t.name,pollingId:u.pollingId}),Sv(u)):u}return{path:"mvl-withdraw",agent:e.wallet_address,withdraw_tx:l}}p();function Dv(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 Ov(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 Nv(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}`)}p();var Vk=["confirmed","finalized"],Hk=["execution_reverted","failed","provider_error"],Gk=["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 uo(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 Vk.includes(r.status)?{kind:"SUCCESS",...s}:Hk.includes(r.status)?{kind:"FAILED",...s}:Gk.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();import{createHash as Wk,randomUUID as Jk}from"crypto";var Xt=10080*6e4,Cv=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Zu(e,t){return`evt_${Wk("sha256").update(`deposit:${e}:${t}`).digest("hex").slice(0,24)}`}var ed=class{constructor(t){this.options=t;this.now=t.now??Date.now,this.createAttemptId=t.createAttemptId??Jk}options;now;createAttemptId;inMemoryStages=new Set;async recordRequired(t){let r=this.now(),n,s=!0;try{let i=x();({row:n,firstObservation:s}=i.transaction(()=>{this.prune(r);let o=i.prepare(`
|
|
589
|
+
SELECT * FROM telemetry_deposit_attempts
|
|
590
|
+
WHERE account_id = ? AND journey_id = ? AND started_at IS NULL
|
|
591
|
+
AND created_at >= ?
|
|
592
|
+
ORDER BY created_at LIMIT 1
|
|
593
|
+
`).get(t.accountId,t.journeyId,r-Xt)??this.insertAttempt({attemptId:this.createAttemptId(),accountId:t.accountId,journeyId:t.journeyId,createdAt:r,startedAt:null}),c=i.prepare(`
|
|
594
|
+
INSERT OR IGNORE INTO telemetry_deposit_stages(attempt_id, stage, observed_at)
|
|
595
|
+
VALUES (?, 'deposit_required', ?)
|
|
596
|
+
`).run(o.attempt_id,r).changes===1;return{row:o,firstObservation:c}}).immediate())}catch{let i=this.createAttemptId();n=this.memoryRow(i,t.accountId,t.journeyId,r),s=this.claimMemoryStage(i,"deposit_required")}return s&&await this.capture(n,"deposit_required",{command:"ride-request",region:t.region,paymentMode:t.paymentMode,marketCode:t.marketCode,errorCode:"INSUFFICIENT_DEPOSIT",failureReason:"insufficient_deposit"}),await this.flush(),this.handle(n)}async claimForDeposit(t){let r=this.now();try{return x().transaction(()=>{this.prune(r);let n;if(t.explicitAttemptId&&Cv.test(t.explicitAttemptId))n=x().prepare(`
|
|
597
|
+
SELECT * FROM telemetry_deposit_attempts
|
|
598
|
+
WHERE attempt_id = ? AND account_id = ? AND started_at IS NULL AND created_at >= ?
|
|
599
|
+
`).get(t.explicitAttemptId,t.accountId,r-Xt);else if(!t.explicitAttemptId){let i=x().prepare(`
|
|
600
|
+
SELECT a.* FROM telemetry_deposit_attempts a
|
|
601
|
+
LEFT JOIN telemetry_journeys j ON j.journey_id = a.journey_id
|
|
602
|
+
WHERE a.account_id = ? AND a.started_at IS NULL AND a.created_at >= ?
|
|
603
|
+
AND (? IS NULL OR a.journey_id = ?)
|
|
604
|
+
AND (a.journey_id IS NULL OR (j.status = 'open' AND j.expires_at > ?))
|
|
605
|
+
ORDER BY a.created_at
|
|
606
|
+
`).all(t.accountId,r-Xt,t.journeyId??null,t.journeyId??null,r);i.length===1&&(n=i[0])}if(n&&x().prepare(`
|
|
607
|
+
UPDATE telemetry_deposit_attempts
|
|
608
|
+
SET started_at = ?, deposit_network = ?, baseline_active = ?, updated_at = ?
|
|
609
|
+
WHERE attempt_id = ? AND account_id = ? AND started_at IS NULL
|
|
610
|
+
`).run(r,t.network,this.bool(t.baselineActive),r,n.attempt_id,t.accountId).changes===1)return this.handle({...n,started_at:r,deposit_network:t.network,baseline_active:this.bool(t.baselineActive),updated_at:r});let s=!t.explicitAttemptId||t.explicitAttemptId===t.resumeAttemptId;if(t.resumeAttemptId&&s&&Cv.test(t.resumeAttemptId)){let i=x().prepare(`
|
|
611
|
+
SELECT a.* FROM telemetry_deposit_attempts a
|
|
612
|
+
WHERE a.attempt_id = ? AND a.account_id = ? AND a.deposit_network = ?
|
|
613
|
+
AND a.started_at IS NOT NULL
|
|
614
|
+
AND a.started_at >= ?
|
|
615
|
+
`).get(t.resumeAttemptId,t.accountId,t.network,r-Xt);if(i)return this.handle(i)}return this.handle(this.insertAttempt({attemptId:this.createAttemptId(),accountId:t.accountId,createdAt:r,startedAt:r,network:t.network,baselineActive:this.bool(t.baselineActive)}))}).immediate()}catch{return this.handle(this.memoryRow(this.createAttemptId(),t.accountId,void 0,r,t.network))}}async observe(t,r){if(r.stage==="relay-status")try{let i=this.resolve(t);return r.flush!==!1&&await this.flush(),i?this.handle(i):void 0}catch{r.flush!==!1&&await this.flush();return}if(r.stage==="status")return this.reconcileDirect(t,r);let n,s=!1;try{let i=this.resolve(t);if(!i)return;({row:n,firstObservation:s}=x().transaction(()=>this.persistObservation(i,r,this.now())).immediate())}catch{r.flush!==!1&&await this.flush();return}return n&&s&&await this.captureObservation(n,r),r.flush!==!1&&await this.flush(),n?this.handle(n):void 0}async reconcileDirect(t,r){if(!t.network)return;let n;try{n=x().prepare(`
|
|
616
|
+
SELECT * FROM telemetry_deposit_attempts
|
|
617
|
+
WHERE account_id = ? AND deposit_network = ? AND deposit_path = 'mvl-direct'
|
|
618
|
+
AND direct_transaction_id IS NOT NULL AND terminal_state IS NULL
|
|
619
|
+
AND started_at >= ?
|
|
620
|
+
ORDER BY started_at
|
|
621
|
+
`).all(t.accountId,t.network,this.now()-Xt)}catch{return}let s=await Promise.all(n.map(async a=>{try{return{row:a,status:await r.resolveDirectTransaction(a.direct_transaction_id)}}catch{return{row:a,status:void 0}}})),i;for(let{row:a,status:o}of s)o?.kind==="SUCCESS"?i=await this.observe(this.handle(a),{stage:"confirmed",command:"deposit-status",token:"MVL",path:"mvl-direct",flush:!1}):o?.kind==="FAILED"&&(i=await this.observe(this.handle(a),{stage:"failed",command:"deposit-status",token:"MVL",path:"mvl-direct",failureReason:"wallet_transaction_failed",flush:!1}));if(r.isActive)try{let a=x().prepare(`
|
|
622
|
+
SELECT a.* FROM telemetry_deposit_attempts a
|
|
623
|
+
WHERE a.account_id = ? AND a.deposit_network = ?
|
|
624
|
+
AND a.terminal_state = 'confirmed' AND a.baseline_active = 0
|
|
625
|
+
AND a.started_at >= ?
|
|
626
|
+
AND NOT EXISTS (
|
|
627
|
+
SELECT 1 FROM telemetry_deposit_stages s
|
|
628
|
+
WHERE s.attempt_id = a.attempt_id AND s.stage = 'deposit_activated'
|
|
629
|
+
)
|
|
630
|
+
`).all(t.accountId,t.network,this.now()-Xt);if(a.length===1){let o=a[0],c=this.persistActivation(o,this.now());c.firstObservation&&await this.capture(c.row,"deposit_activated",{command:"deposit-status",token:c.row.deposit_token,path:c.row.deposit_path,relayRequestId:c.row.relay_request_id??void 0}),i=this.handle(c.row)}}catch{}return r.flush!==!1&&await this.flush(),i}persistActivation(t,r){return x().transaction(()=>{let n=this.resolve(this.handle(t));if(!n||n.terminal_state!=="confirmed"||n.baseline_active!==0)return{row:t,firstObservation:!1};let s=x().prepare(`
|
|
631
|
+
SELECT attempt_id FROM telemetry_deposit_attempts a
|
|
632
|
+
WHERE a.account_id = ? AND a.deposit_network = ?
|
|
633
|
+
AND a.terminal_state = 'confirmed' AND a.baseline_active = 0
|
|
634
|
+
AND a.started_at >= ?
|
|
635
|
+
AND NOT EXISTS (
|
|
636
|
+
SELECT 1 FROM telemetry_deposit_stages s
|
|
637
|
+
WHERE s.attempt_id = a.attempt_id AND s.stage = 'deposit_activated'
|
|
638
|
+
)
|
|
639
|
+
`).all(n.account_id,n.deposit_network,r-Xt);if(s.length!==1||s[0].attempt_id!==n.attempt_id)return{row:n,firstObservation:!1};let i=x().prepare(`
|
|
640
|
+
INSERT OR IGNORE INTO telemetry_deposit_stages(attempt_id, stage, observed_at)
|
|
641
|
+
VALUES (?, 'deposit_activated', ?)
|
|
642
|
+
`).run(n.attempt_id,r).changes===1;return{row:n,firstObservation:i}}).immediate()}persistObservation(t,r,n){let s=`deposit_${r.stage}`;if(t.started_at==null||n-t.started_at>Xt)return{row:t,firstObservation:!1};let i=this.hasStage(t.attempt_id,"deposit_started"),a=this.hasStage(t.attempt_id,"deposit_submitted");if(!this.validObservation(r,i,a))return{row:t,firstObservation:!1};if(!this.bind(t.attempt_id,"deposit_token",r.token)||!this.bind(t.attempt_id,"deposit_path",r.path)||!this.bind(t.attempt_id,"relay_request_id",r.relayRequestId)||r.stage==="submitted"&&!this.bind(t.attempt_id,"direct_transaction_id",r.directTransactionId))return{row:this.resolve(this.handle(t))??t,firstObservation:!1};if(r.stage==="confirmed"||r.stage==="failed"){let c=r.stage;if(!(x().prepare(`
|
|
643
|
+
UPDATE telemetry_deposit_attempts SET terminal_state = ?, updated_at = ?
|
|
644
|
+
WHERE attempt_id = ? AND terminal_state IS NULL
|
|
645
|
+
`).run(c,n,t.attempt_id).changes===1))return{row:this.resolve(this.handle(t))??t,firstObservation:!1}}else if(t.terminal_state)return{row:t,firstObservation:!1};x().prepare("UPDATE telemetry_deposit_attempts SET updated_at = ? WHERE attempt_id = ?").run(n,t.attempt_id);let o=x().prepare(`
|
|
646
|
+
INSERT OR IGNORE INTO telemetry_deposit_stages(attempt_id, stage, observed_at)
|
|
647
|
+
VALUES (?, ?, ?)
|
|
648
|
+
`).run(t.attempt_id,s,n).changes===1;return{row:this.resolve(this.handle(t))??t,firstObservation:o}}validObservation(t,r,n){let s=t.token==="MVL"&&t.path==="mvl-direct"&&t.relayRequestId===void 0,i=(t.token==="USDC"||t.token==="MVL")&&t.path==="relay",a=i&&t.relayRequestId!==void 0,o=t.token===void 0&&t.path===void 0;if(t.stage==="started")return t.command==="deposit-add"&&t.relayRequestId===void 0&&(o||s||i);if(t.stage==="submitted")return r&&t.command==="deposit-add"&&(s||a);if(t.stage==="confirmed")return n&&(s&&t.command==="deposit-status"||a&&(t.command==="deposit-add"||t.command==="deposit-relay-status"));if(n)return s&&t.command==="deposit-status"&&t.failureReason==="wallet_transaction_failed"||a&&(t.command==="deposit-add"||t.command==="deposit-relay-status")&&t.failureReason==="relay_failed";let c=new Set(["relay_unavailable","token_not_depositable","jwt_not_found","wallet_submission_failed","other"]);return r&&t.command==="deposit-add"&&t.relayRequestId===void 0&&c.has(t.failureReason)&&(o||s||i)}bind(t,r,n){if(n===void 0)return!0;if(!new Set(["deposit_token","deposit_path","relay_request_id","direct_transaction_id"]).has(r))return!1;let i=x().prepare(`SELECT ${r} value FROM telemetry_deposit_attempts WHERE attempt_id = ?`).get(t);if(i.value!==null)return i.value===n;try{return x().prepare(`
|
|
649
|
+
UPDATE telemetry_deposit_attempts SET ${r} = ?
|
|
650
|
+
WHERE attempt_id = ? AND ${r} IS NULL
|
|
651
|
+
`).run(n,t).changes===1}catch{return!1}}resolve(t){if("attemptId"in t)return x().prepare(`
|
|
652
|
+
SELECT * FROM telemetry_deposit_attempts WHERE attempt_id = ? AND account_id = ?
|
|
653
|
+
`).get(t.attemptId,t.accountId);if(t.relayRequestId)return x().prepare(`
|
|
654
|
+
SELECT * FROM telemetry_deposit_attempts WHERE relay_request_id = ? AND account_id = ?
|
|
655
|
+
`).get(t.relayRequestId,t.accountId)}async captureObservation(t,r){await this.capture(t,`deposit_${r.stage}`,{command:r.command,token:r.token,path:r.path,relayRequestId:r.relayRequestId,...r.stage==="failed"?{errorCode:"DEPOSIT_FAILED",failureReason:r.failureReason}:{}})}async capture(t,r,n){try{let s=new bn(this.options.transport,{installation_id:this.options.installationId,journey_id:t.journey_id??void 0,account_id:t.account_id,market_code:n.marketCode,command:n.command,region:n.region,payment_mode:n.paymentMode,deposit_attempt_id:t.attempt_id,deposit_network:r==="deposit_required"?void 0:t.deposit_network??void 0,deposit_token:n.token,deposit_path:n.path,relay_request_id:n.relayRequestId,cli_version:this.options.cliVersion,build_env:this.options.buildEnv});r==="deposit_required"||r==="deposit_failed"?s.capture({event:"ambient_cli_command_failed",event_id:Zu(t.attempt_id,r),stage:r,outcome:"failed",duration_ms:this.duration(t),error_code:n.errorCode,failure_reason:n.failureReason}):r==="deposit_started"?s.capture({event:"ambient_cli_command_started",event_id:Zu(t.attempt_id,r),stage:r,outcome:"started",duration_ms:this.duration(t)}):s.capture({event:"ambient_cli_command_completed",event_id:Zu(t.attempt_id,r),stage:r,outcome:"completed",duration_ms:this.duration(t)})}catch{}}async flush(){try{await this.options.transport.shutdown()}catch{}}insertAttempt(t){return x().prepare(`
|
|
656
|
+
INSERT INTO telemetry_deposit_attempts(
|
|
657
|
+
attempt_id, account_id, journey_id, created_at, started_at,
|
|
658
|
+
deposit_network, baseline_active, updated_at
|
|
659
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
660
|
+
`).run(t.attemptId,t.accountId,t.journeyId??null,t.createdAt,t.startedAt,t.network??null,t.baselineActive??null,t.createdAt),x().prepare("SELECT * FROM telemetry_deposit_attempts WHERE attempt_id = ?").get(t.attemptId)}memoryRow(t,r,n,s,i){return{attempt_id:t,account_id:r,journey_id:n??null,created_at:s,started_at:s,deposit_network:i??null,deposit_token:null,deposit_path:null,relay_request_id:null,direct_transaction_id:null,baseline_active:null,terminal_state:null,updated_at:s}}handle(t){return{attemptId:t.attempt_id,accountId:t.account_id,...t.journey_id?{journeyId:t.journey_id}:{},...t.deposit_network?{network:t.deposit_network}:{},...t.deposit_token?{token:t.deposit_token}:{},...t.deposit_path?{path:t.deposit_path}:{}}}duration(t){return Math.min(Xt,Math.max(0,this.now()-(t.started_at??t.created_at)))}bool(t){return t===void 0?null:t?1:0}hasStage(t,r){return!!x().prepare(`
|
|
661
|
+
SELECT 1 FROM telemetry_deposit_stages WHERE attempt_id = ? AND stage = ?
|
|
662
|
+
`).get(t,r)}claimMemoryStage(t,r){let n=`${t}:${r}`;return this.inMemoryStages.has(n)?!1:(this.inMemoryStages.add(n),!0)}prune(t){x().prepare(`
|
|
663
|
+
DELETE FROM telemetry_deposit_attempts WHERE COALESCE(started_at, created_at) < ?
|
|
664
|
+
`).run(t-Xt)}};function Hn(e){try{let t=xe(),r=t.install.repoBranch,n=r==="main"?"production":r;return n!=="dev"&&n!=="staging"&&n!=="production"?void 0:new ed({transport:new Bn,installationId:Ja(e),cliVersion:t.artifact.cliVersion,buildEnv:n})}catch{return}}var Pv="note: collateral is credited in MVL (not the deposited token); withdrawals return MVL.",Xk="note: withdrawals return MVL regardless of the token originally deposited.",Qk=2e3,Zk=new Set(["BASE","BASE_SEPOLIA","ETHEREUM","ETHEREUM_SEPOLIA"]);function Mv(e){return Zk.has(e)?e:void 0}function eU(e){let t=[],r,n=!1;for(let s=0;s<e.length;s++){let i=e[s];if(i==="--no-wait")n=!0;else if(i==="--deposit-attempt-id"){let a=e[s+1];a&&!a.startsWith("--")&&(r=a,s++)}else i.startsWith("--deposit-attempt-id=")?r=i.slice(21)||void 0:t.push(i)}return{argv:t,noWait:n,explicitAttemptId:r}}async function tU(e,t){let r;try{return await Promise.race([Es(e,t),new Promise(n=>{r=setTimeout(()=>n(void 0),2e3),r.unref?.()})])}catch{return}finally{r&&clearTimeout(r)}}function rU(e){let t=e instanceof Error?e.message:String(e??"");return t.startsWith("JWT_NOT_FOUND:")?"jwt_not_found":t.startsWith("TOKEN_NOT_DEPOSITABLE:")?"token_not_depositable":t.startsWith("RELAY_UNAVAILABLE:")?"relay_unavailable":"wallet_submission_failed"}function kv(e,t){let r=e instanceof Error?e.message:String(e??""),n=r.match(/^([A-Z][A-Z0-9_]+):\s*(.+)$/s),s=t?{deposit_attempt_id:t}:{};n?b({error:n[1],message:n[2],...s}):b({error:r,...s})}var nU="run SIWE login (siwe-request-message then siwe-submit) to compute the token amount needed to activate",sU="run typed login (siwe-request-typed, wallet-sign with eth_signTypedData_v4, then typed-submit) to compute the token amount needed to activate";async function iU(e,t,r,n){if(r===0n)return{entries:null,reason:null};let s=De(t);if(!s)return{entries:null,reason:"NO_JWT",hint:Ye(t)?.wallet_type==="metamask"?sU:nU};try{let i=await Rc(e);if(i.length===0)return{entries:null,reason:"RATE_UNAVAILABLE"};let o=(await Promise.allSettled(i.map(async c=>{let l=await qr(e,c),u=await Nv(s,{network:e.name,tokenAddress:c},n),d=Dv(r,BigInt(u.tokenAmount),BigInt(u.mvlAmount));return{tokenAddress:c,symbol:l.symbol,tokenWei:d.toString(),display:`~${Ov(d,l.decimals)} ${l.symbol} to activate`,ratePreview:u.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 aU=async e=>{let[t]=e;t||(console.error("error: Usage: amb deposit-status <wallet_address>"),process.exit(1));let r=O();N(r.dataDir),X(t);try{le(r.appServerUrl)}catch{}let n=Hn(r.dataDir),s=Je(t);try{let i=await Promise.allSettled(r.depositNetworks.map(async l=>{let[u,d,m,f,g]=await Promise.all([Es(l,t),Wi(l,t),Ji(l,t),Ts(l),Zp(l)]),h=f>d?f-d:0n,E=Mv(l.name);if(n&&E)try{await n.observe({accountId:s,network:E},{stage:"status",command:"deposit-status",isActive:u,resolveDirectTransaction:async P=>{let L=new AbortController,W=setTimeout(()=>L.abort(),Qk);W.unref();try{return await uo(Z=>Ui(Z,L.signal),P)}finally{clearTimeout(W)}}})}catch{}let T=null,w=null;if(h>0n)try{let P=await Fr(l),L=await qr(l,P);T={tokenAddress:P,symbol:L.symbol,tokenWei:h.toString(),display:`${zk(h,L.decimals)} ${L.symbol} to activate`}}catch(P){w=`MVL activation guidance unavailable: ${P.message}`}let v=await iU(l,t,h,r),A=[...T?[T]:[],...v.entries??[]],C=A.length>0?A:null;return{mvlError:w,network:l.name,isActive:u,deposited:d.toString(),minRequired:f.toString(),nextWithdrawAt:Number(m),mvlReserve:g.toString(),mvlGap:h.toString(),requiredToActivate:C,requiredToActivateReason:v.reason,...v.hint?{requiredToActivateHint:v.hint}:{}}})),a=[],o=[];i.forEach((l,u)=>{if(l.status==="fulfilled"){let{mvlError:d,...m}=l.value;a.push(m),d&&o.push({network:m.network,error:d})}else o.push({network:r.depositNetworks[u].name,error:l.reason?.message})});let c=a.some(l=>l.isActive);S({anyActive:c,networks:a,errors:o})}catch(i){b({error:i.message}),process.exit(1)}},oU=async e=>{let{noWait:t,argv:r,explicitAttemptId:n}=eU(e),[s,i,a,o]=r;if(!s||!i||!a||!o){console.error("error: Usage: amb deposit-add <wallet_address> <network> <token_address> <amount> [--no-wait] [--deposit-attempt-id <uuid>]"),console.error('hint: amount is raw units (e.g. 1000 MVL = "1000000000000000000000")');let v=xe().networks.depositNetworks;console.error(v.length?` network: ${v.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 c=O();N(c.dataDir),X(s),le(c.appServerUrl);let l=c.depositNetworks.find(v=>v.name===i);l||(b({error:"UNKNOWN_NETWORK",message:`Network "${i}" not configured. Available: ${c.depositNetworks.map(v=>v.name).join(", ")}`}),process.exit(1));let u=Buffer.from(c.passphrase,"utf8"),d=Je(s),m=Mv(l.name),f=Hn(c.dataDir),g={attemptId:Kk(),accountId:d,...m?{network:m}:{}};if(f&&m)try{let v=yv({walletAddress:s,network:l.name,tokenAddress:a,amount:o});g=await f.claimForDeposit({accountId:d,explicitAttemptId:n,network:m,baselineActive:await tU(l,s),resumeAttemptId:v}),await f.observe(g,{stage:"started",command:"deposit-add",flush:!1})}catch{}let h,E,T=!1,w;try{let v=await Av({wallet_address:s,token:a,amount:o},l,c,u,{attemptId:g.attemptId,onPathResolved:te=>{E=te,te==="mvl-direct"&&(h="MVL")}});if(E=v.path==="mvl-direct"?"mvl-direct":"relay",h=v.path==="relay"?"USDC":"MVL",v.path==="mvl-direct"){T=!0,await f?.observe(g,{stage:"submitted",command:"deposit-add",token:"MVL",path:"mvl-direct",directTransactionId:v.batch_tx.transaction_id}),S({...v,deposit_attempt_id:g.attemptId});return}await f?.observe(g,{stage:"submitted",command:"deposit-add",token:h,path:"relay",relayRequestId:v.request_id,flush:!1}),T=!0,w=v.request_id,v.status==="CONFIRMED"?await f?.observe(g,{stage:"confirmed",command:"deposit-add",token:h,path:"relay",relayRequestId:v.request_id}):v.status==="FAILED"&&await f?.observe(g,{stage:"failed",command:"deposit-add",token:h,path:"relay",relayRequestId:v.request_id,failureReason:"relay_failed"});let A={...v,deposit_attempt_id:g.attemptId,next_step:`${v.next_step} (deposit attempt ID: ${g.attemptId})`};if(t){let{next_step:te,...pe}=A;if(v.status!=="CONFIRMED"&&v.status!=="FAILED"&&await f?.observe(g,{stage:"relay-status",command:"deposit-relay-status",relayRequestId:v.request_id}),v.status==="FAILED"){S(pe),v.path==="mvl-sig-relay"&&Ys(v.request_id),process.exit(2);return}S(v.status==="CONFIRMED"?pe:A),v.path==="mvl-sig-relay"&&v.status==="CONFIRMED"&&Ys(v.request_id),v.path==="relay"&&console.error(Pv);return}let C=De(s);if(!C){await f?.observe(g,{stage:"relay-status",command:"deposit-relay-status",relayRequestId:v.request_id});let te=v.path==="mvl-sig-relay"?"No cached JWT for this MetaMask relay. Run siwe-request-typed, wallet-sign with eth_signTypedData_v4, then typed-submit.":"No cached JWT for this wallet. Call siwe-request-message + siwe-submit first.";b({error:"JWT_NOT_FOUND",request_id:v.request_id,deposit_attempt_id:g.attemptId,message:te}),process.exit(1);return}let P=await gv(C,v.request_id,c);P.status==="CONFIRMED"?await f?.observe(g,{stage:"confirmed",command:"deposit-add",token:h,path:"relay",relayRequestId:v.request_id}):P.status==="FAILED"?await f?.observe(g,{stage:"failed",command:"deposit-add",token:h,path:"relay",relayRequestId:v.request_id,failureReason:"relay_failed"}):await f?.observe(g,{stage:"relay-status",command:"deposit-relay-status",relayRequestId:v.request_id});let L=P.status==="CONFIRMED"||P.status==="FAILED",{next_step:W,status:Z,tx_hash:V,error_code:Y,error_message:ge,...ee}=v;S({...ee,...Gu(P),deposit_attempt_id:g.attemptId,...L?{}:{next_step:v.next_step}}),v.path==="mvl-sig-relay"&&L&&Ys(v.request_id),P.status==="FAILED"&&process.exit(2),v.path==="relay"&&console.error(Pv)}catch(v){try{let A=h&&E?{token:h,path:E}:{},C=E==="relay"&&dv(v),P=E==="mvl-direct"&&av(v);!T&&!C&&!P?await f?.observe(g,{stage:"failed",command:"deposit-add",failureReason:rU(v),...A}):w?await f?.observe(g,{stage:"relay-status",command:"deposit-relay-status",relayRequestId:w}):await f?.observe(g,{stage:"started",command:"deposit-add",...A})}catch{}kv(v,g.attemptId),process.exit(1)}},cU=async e=>{let t=e[0],r=O(),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=[],l=await Fr(o),u=null;try{u=await qr(o,l)}catch(h){c.push(`MVL metadata unavailable: ${h.message}`)}let[d,m]=await Promise.allSettled([Rc(o),Ts(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 h=>{let E=await qr(o,h);return{token:h,symbol:E.symbol,name:E.name,decimals:E.decimals}})),g=[];return f.forEach((h,E)=>{if(h.status==="fulfilled")g.push(h.value);else{let T=d.status==="fulfilled"?d.value[E]:"(unknown)";c.push(`token ${T} metadata unavailable: ${h.reason?.message}`)}}),{scopedErrors:c,network:o.name,tokens:[{token:l,symbol:u?.symbol??null,name:u?.name??null,decimals:u?.decimals??null},...g],minRequiredMvl:m.status==="fulfilled"?m.value.toString():null}})),i=[],a=[];s.forEach((o,c)=>{if(o.status==="fulfilled"){let{scopedErrors:l,...u}=o.value;i.push(u);for(let d of l)a.push({network:u.network,error:d})}else a.push({network:n[c].name,error:o.reason?.message})}),S({networks:i,errors:a})}catch(s){b({error:s.message}),process.exit(1)}},lU=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=O();N(s.dataDir),X(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 Iv({wallet_address:t},i,s,a);S(o),console.error(Xk)}catch(o){kv(o),process.exit(1)}},uU="0xfd0Bf71F60660E2f608ed56e1659C450eB113120",dU=11155111,Lv=2e5,pU=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=Yk({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,Lv,"0x"]}),a=O();N(a.dataDir),X(t),le(a.appServerUrl);let o=Buffer.from(a.passphrase,"utf8");try{let c=await lr({wallet_address:t,to:uU,value_eth:r,chain_id:dU,data:i},a,o);S({...c,l2_recipient:s,min_gas_limit:Lv})}catch(c){b({error:c.message}),process.exit(1)}},mU=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" or path="mvl-sig-relay"'),process.exit(1));let n=O();N(n.dataDir);let s=Hn(n.dataDir),i=Je(t),a=De(t);a||(b({error:"JWT_NOT_FOUND",message:"No cached JWT for this wallet. Call siwe-request-message + siwe-submit first."}),process.exit(1));try{let o=await io(a,r,n);if(o.requestId!==r)throw new Error("Relay status response did not match the requested relay ID");let c=await s?.observe({accountId:i,relayRequestId:r},{stage:"relay-status",command:"deposit-relay-status",relayRequestId:r,flush:!1});c&&o.status==="CONFIRMED"?await s?.observe(c,{stage:"confirmed",command:"deposit-relay-status",token:c.token??"USDC",path:"relay",relayRequestId:r}):c&&o.status==="FAILED"&&await s?.observe(c,{stage:"failed",command:"deposit-relay-status",token:c.token??"USDC",path:"relay",relayRequestId:r,failureReason:"relay_failed"});let l=Gu(o);S(c?{...l,deposit_attempt_id:c.attemptId}:l),(o.status==="CONFIRMED"||o.status==="FAILED")&&Ys(r),o.status==="FAILED"&&process.exit(2)}catch(o){b({error:o.message}),process.exit(1)}},Uv={"deposit-status":aU,"deposit-add":oU,"deposit-tokens":cU,"deposit-withdraw":lU,"deposit-relay-status":mU,"bridge-deposit-eth":pU};p();import{createPublicClient as qU,http as jU,formatUnits as BU}from"viem";import{base as VU,baseSepolia as HU,mainnet as GU,sepolia as $U}from"viem/chains";p();import{randomUUID as fU}from"crypto";var gU=["INITIATED","BURN_SUBMITTED","ATTESTED","MINT_SUBMITTED","COMPLETED","FAILED"],xr=["COMPLETED","FAILED"],BJ=gU.filter(e=>!xr.includes(e)),Fv=xr.map(()=>"?").join(","),hU={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 td(){return Math.floor(Date.now()/1e3)}function qv(e){let t=x();return t.transaction(()=>{if(t.prepare(`
|
|
665
|
+
SELECT id FROM bridge_jobs
|
|
666
|
+
WHERE wallet_address = ? AND status NOT IN (${Fv})
|
|
667
|
+
LIMIT 1
|
|
668
|
+
`).get(e.walletAddress,...xr))throw new Error("BRIDGE_JOB_IN_FLIGHT");let n=fU();return t.prepare(`
|
|
669
|
+
INSERT INTO bridge_jobs (
|
|
670
|
+
id, wallet_address, status, source_chain_id, dest_chain_id,
|
|
671
|
+
amount_raw, is_fast, max_fee_raw, from_block, mint_from_block
|
|
672
|
+
) VALUES (@id, @walletAddress, 'INITIATED', @sourceChainId, @destChainId,
|
|
673
|
+
@amountRaw, @isFast, @maxFeeRaw, @fromBlock, @mintFromBlock)
|
|
674
|
+
`).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}),Sr(n)})()}function Sr(e){return x().prepare("SELECT * FROM bridge_jobs WHERE id = ?").get(e)}function jv(e){return x().prepare(`
|
|
675
|
+
SELECT * FROM bridge_jobs
|
|
676
|
+
WHERE wallet_address = ? AND status NOT IN (${Fv})
|
|
677
|
+
ORDER BY created_at DESC, rowid DESC LIMIT 1
|
|
678
|
+
`).get(e,...xr)}function Bv(e,t=20){return x().prepare(`
|
|
679
|
+
SELECT * FROM bridge_jobs WHERE wallet_address = ?
|
|
680
|
+
ORDER BY created_at DESC, rowid DESC LIMIT ?
|
|
681
|
+
`).all(e,t)}function rd(e,t){let r=Object.entries(t),n=[],s=[];for(let[i,a]of r){let o=hU[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(td()),x().prepare(`UPDATE bridge_jobs SET ${n.join(", ")} WHERE id = ?`).run(...s,e))}function po(e,t,r=td()){return x().prepare(`
|
|
682
|
+
UPDATE bridge_jobs SET lease_expires_at = ?, updated_at = ?
|
|
683
|
+
WHERE id = ? AND (lease_expires_at IS NULL OR lease_expires_at < ?)
|
|
684
|
+
`).run(r+t,r,e,r).changes===1}function Vv(e){x().prepare("UPDATE bridge_jobs SET lease_expires_at = NULL, updated_at = ? WHERE id = ?").run(td(),e)}p();function Gn(e){return x().prepare("SELECT * FROM bridge_fast_grants WHERE wallet_address = ?").get(e)}function Hv(e,t){return x().prepare(`
|
|
685
|
+
INSERT INTO bridge_fast_grants (wallet_address, max_fee_raw)
|
|
686
|
+
VALUES (?, ?)
|
|
687
|
+
ON CONFLICT(wallet_address) DO UPDATE SET
|
|
688
|
+
max_fee_raw = excluded.max_fee_raw,
|
|
689
|
+
granted_at = CURRENT_TIMESTAMP
|
|
690
|
+
`).run(e,t),Gn(e)}function Gv(e){return x().prepare("DELETE FROM bridge_fast_grants WHERE wallet_address = ?").run(e).changes>0}function nd(e,t){if(t===0n)return!0;let r=Gn(e);return r?t<=BigInt(r.max_fee_raw):!1}p();p();import{encodeFunctionData as id,decodeEventLog as yU,pad as Yv}from"viem";p();import{parseAbi as sd,parseAbiItem as _U}from"viem";var $v=sd(["function depositForBurn(uint256 amount, uint32 destinationDomain, bytes32 mintRecipient, address burnToken, bytes32 destinationCaller, uint256 maxFee, uint32 minFinalityThreshold)"]),Wv=sd(["function receiveMessage(bytes message, bytes attestation) returns (bool)"]),Jv=sd(["function approve(address spender, uint256 amount) returns (bool)"]),Kv=_U("event MintAndWithdraw(address indexed mintRecipient, uint256 amount, address indexed mintToken, uint256 feeCollected)");function zv(e){return id({abi:$v,functionName:"depositForBurn",args:[e.amount,e.destinationDomain,Yv(e.mintRecipient,{size:32}),e.burnToken,Yv("0x",{size:32}),e.maxFee,e.minFinalityThreshold]})}function Xv(e,t){return id({abi:Wv,functionName:"receiveMessage",args:[e,t]})}function Qv(e,t){return id({abi:Jv,functionName:"approve",args:[e,t]})}function mo(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=yU({abi:[Kv],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 eR="Run `amb bridge-usdc <wallet>` to resume",EU={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 xt(e,t){rd(e.id,t);let r={...e};for(let[n,s]of Object.entries(t)){let i=EU[n];i&&(r[i]=s)}return r}function fo(e,t,r=!1){return xt(e,{status:"FAILED",failureReason:t}),{status:"FAILED",...r?{fundsMidFlight:!0}:{}}}function qt(e,t,r={}){return{status:e,nextStep:eR,...t?.note?{note:t.note}:{},...t?.privyStatus?{privyStatus:t.privyStatus}:{},...r}}function tR(e,t){let r=BigInt(e.amount_raw);return t>=r&&t<=r+BigInt(e.max_fee_raw)}function en(e,t,r){return xt(e,{status:"COMPLETED",mintedAmountRaw:t}),{status:"COMPLETED",mintedAmountRaw:t,...r?{note:r}:{}}}function ad(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 zs(e,t){let r=BigInt(e.mint_from_block??e.from_block??"0"),n=await t.scanMintLogs(r,e.wallet_address);return n&&tR(e,BigInt(n.amountRaw))?n.amountRaw:null}async function rR(e,t){if(!e.cctp_nonce)return!1;try{return await t.isNonceUsed(e.cctp_nonce)}catch{return!1}}async function nR(e,t){if(BigInt(e.max_fee_raw)===0n)return{amountRaw:e.amount_raw};let r=await zs(e,t);return r?{amountRaw:r}:{amountRaw:null,note:ad(e.wallet_address)}}function sR(e){let t=e instanceof Error?e.message:String(e);return/already used|nonce already/i.test(t)}async function TU(e,t,r){let n=await zs(e,t);if(n)return en(e,n);let s=Sr(e.id)??e,i=s.last_revert_sig===r?s.mint_attempts+1:1,a=xt(e,{mintAttempts:i,lastRevertSig:r});if(i>=t.mintMaxAttempts)return fo(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=xt(a,{status:"MINT_SUBMITTED",mintPrivyTxId:o.transactionId,mintTxHash:null}),qt("MINT_SUBMITTED")}catch(o){if(sR(o)){let c=await zs(a,t);if(c)return en(a,c)}throw o}}var Zv=new Set;function bU(e){return xr.includes(e)}async function iR(e,t){let r=`${e.id}:${e.burn_tx_hash??""}`;if(Zv.has(r))return e;Zv.add(r);try{let n=await t.registerRelay(e);if(n&&!e.relay_request_id)return rd(e.id,{relayRequestId:n}),Sr(e.id)??e}catch{}return e}var Fe=e=>({advanced:!1,result:e}),go=e=>({advanced:!0,job:e});async function vU(e,t){if(e.burn_privy_tx_id){let a=await t.resolveTxStatus(e.burn_privy_tx_id);return a.kind==="FAILED"?Fe(fo(e,`burn transaction failed (${a.privyStatus??"reverted"}); no USDC was burned`)):a.kind==="REPLACED"?(a.hash&&xt(e,{burnTxHash:a.hash}),Fe(qt("INITIATED",a,{note:`burn transaction was replaced (nonce replacement); now tracking ${a.hash}`}))):a.kind==="SUCCESS"&&a.hash?go(xt(e,{status:"BURN_SUBMITTED",burnTxHash:a.hash})):Fe(qt("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 go(xt(e,{status:"BURN_SUBMITTED",burnTxHash:s.hash}));let i=n-r;return i<BigInt(t.graceBlocks)?Fe({status:"INITIATED",verdictWithheld:!0,nextStep:eR,note:`no DepositForBurn found yet, but only ${i} of ${t.graceBlocks} grace blocks have passed; withholding judgement`}):Fe(fo(e,`no DepositForBurn from ${e.wallet_address} in ${i} blocks since block ${r}; the burn never went out`))}async function RU(e,t){let r=e.burn_tx_hash;if(!r)return Fe(qt("BURN_SUBMITTED"));let n=await t.irisAttestation(e.source_chain_id,r);if(n&&n.attestation)return go(xt(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?Fe(fo(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`)):Fe(qt("BURN_SUBMITTED",void 0,s?{note:`Circle has not attested the burn yet; Iris reports: ${s}`}:{}))}async function wU(e,t){if(await rR(e,t)){let{amountRaw:n,note:s}=await nR(e,t);return Fe(en(e,n,s))}let r=e.mint_from_block?e:xt(e,{mintFromBlock:(await t.destBlock()).toString()});try{let n=await t.sendMint(r);return go(xt(r,{status:"MINT_SUBMITTED",mintPrivyTxId:n.transactionId,mintTxHash:null}))}catch(n){if(sR(n)){let s=await zs(r,t);if(s)return Fe(en(r,s))}throw n}}async function AU(e,t){if(!e.mint_privy_tx_id)return Fe(qt("MINT_SUBMITTED"));let r=await t.resolveTxStatus(e.mint_privy_tx_id);if(r.kind==="FAILED")return Fe(await TU(e,t,r.privyStatus??"unknown_revert"));if(r.kind==="REPLACED")return r.hash&&xt(e,{mintTxHash:r.hash}),Fe(qt("MINT_SUBMITTED",r,{note:`mint transaction was replaced (nonce replacement); now tracking ${r.hash}`}));if(r.kind!=="SUCCESS"||!r.hash)return Fe(qt("MINT_SUBMITTED",r));let n=xt(e,{mintTxHash:r.hash}),s=await t.getReceipt(r.hash),i=s?mo(s,t.destTokenMessenger,n.wallet_address):null;if(i)return tR(n,i.amountRaw)?Fe(en(n,i.amountRaw.toString())):Fe(qt("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 rR(n,t)){let{amountRaw:o,note:c}=await nR(n,t);return Fe(en(n,o,c))}let a=await zs(n,t);return Fe(a?en(n,a):qt("MINT_SUBMITTED",void 0,{note:`mint transaction ${r.hash} succeeded but no MintAndWithdraw for ${n.wallet_address} was found yet`}))}async function aR(e,t){let r=await t.sendBurn(e),n=xt(e,{burnPrivyTxId:r.transactionId});return n=await iR(n,t),ho(n,t)}async function ho(e,t){let r=e;for(let n=0;n<xU;n++){r.burn_tx_hash&&!bU(r.status)&&(r=await iR(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 vU(r,t);break;case"BURN_SUBMITTED":s=await RU(r,t);break;case"ATTESTED":s=await wU(r,t);break;case"MINT_SUBMITTED":s=await AU(r,t);break}if(!s.advanced)return s.result;r=s.job}return qt(r.status)}var xU=8;p();var SU=10000n;function oR(e,t){return(e+t-1n)/t}function cR(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=oR(t*BigInt(i.minimumFee),SU);return oR(a*BigInt(100+n),100n)}async function od(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 IU(e){return typeof e=="string"&&e.startsWith("0x")}function DU(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 lR(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"&&DU(o,t)&&typeof o.message=="string"&&IU(o.attestation));return a?{message:a.message,attestation:a.attestation,nonce:a.eventNonce??null}:null}p();import{decodeEventLog as OU,parseAbiItem as NU,pad as CU}from"viem";var PU=NU("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)"),uR=128,dR=8,LU=[/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 MU(e){let t=e instanceof Error?e.message:String(e);return LU.some(r=>r.test(t))}async function pR(e,t,r){let n=t.chunk??O().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(l){if(!MU(l))throw l;if(++i>dR)throw new Error(`eth_getLogs range rejections are not converging after ${dR} halvings (blocks ${s}-${a})`);let u=Number(a-s+1n),d=Math.floor(u/2);if(d<uR)throw new Error(`eth_getLogs still rejects the block range at the ${uR}-block floor (blocks ${s}-${a}): ${l instanceof Error?l.message:String(l)}`);n=d;continue}i=0;let c=r(o);if(c!==null)return c;s=a+1n}return null}async function mR(e,t,r,n){let s=t.tokenMessenger.toLowerCase(),i=r.toLowerCase(),a=CU(n.mintRecipient,{size:32}).toLowerCase();return pR(e,t,o=>{for(let c of o){if(c.address?.toLowerCase()!==s)continue;let l;try{l=OU({abi:[PU],data:c.data,topics:c.topics})}catch{continue}let u=l.args;if(u.depositor?.toLowerCase()===i&&u.amount===n.amountRaw&&u.destinationDomain===n.destinationDomain&&u.mintRecipient?.toLowerCase()===a)return{transactionHash:c.transactionHash,blockNumber:BigInt(c.blockNumber),amountRaw:u.amount,mintRecipient:u.mintRecipient,destinationDomain:u.destinationDomain}}return null})}async function fR(e,t,r){return pR(e,t,n=>{for(let s of n){let i=mo({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 gR=[{type:"function",name:"usedNonces",stateMutability:"view",inputs:[{name:"nonce",type:"bytes32"}],outputs:[{name:"",type:"uint256"}]}];async function hR(e,t,r){return await e(t,r)!==0n}p();function kU(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 _R(e,t,r,n,s,i=1e4){let a=AbortSignal.timeout(i);async function o(){let u=await t(a);if(!u)return null;let d=await e(`${s.gatewayServerUrl.replace(/\/$/,"")}/v1/agent-cctp-relay/relay-mint`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`},body:JSON.stringify(kU(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,l=new Promise(u=>{c=setTimeout(()=>u(null),i),c.unref?.()});try{return await Promise.race([o(),l])}catch{return null}finally{clearTimeout(c)}}var TR=6,WU=5e3,JU=3*6e4,KU=25*6e4,ld=e=>`Run \`amb bridge-usdc ${e}\` to resume`,ud=e=>`note: this bridge is NOT finished (status ${e}). Your USDC has not arrived yet \u2014 do not report it as complete.`,_o=e=>`This bridge could not complete on its own and your USDC is mid-flight.
|
|
691
|
+
Nothing is lost \u2014 it can be finished manually.
|
|
692
|
+
Send the full output of \`amb bridge-usdc-status ${e}\` to support.`,YU=/^\d+(\.\d{1,6})?$/;function Xs(e){if(!YU.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(TR,"0"))}function Ue(e){return BU(e,TR)}var zU={1:GU,11155111:$U,8453:VU,84532:HU},XU=[{name:"balanceOf",type:"function",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{name:"",type:"uint256"}]}],QU=(e,t)=>{let r=qU({chain:zU[e],transport:jU(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:gR,functionName:"usedNonces",args:[s]}),erc20Balance:(n,s)=>r.readContract({address:n,abi:XU,functionName:"balanceOf",args:[s]})}},Qs=QU;var $n={now:()=>Date.now(),sleep:e=>new Promise(t=>setTimeout(t,e))};function tn(e){return e instanceof Error?e.message:String(e)}function bR(e){let t=/^HTTP (\d{3})\b/.exec(tn(e));return t?Number(t[1]):void 0}var ZU=1e3,e0=8e3,t0=5;async function yR(e){let t=ZU;for(let r=1;;r++)try{return await e()}catch(n){if(bR(n)!==429||r>=t0)throw n;await $n.sleep(t),t=Math.min(t*2,e0)}}function r0(e){let t=tn(e);return bR(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 n0(e,t,r){return async n=>{let s=De(e);if(s)return s;let{message:i}=await Js(e,t.paymentChainId,n),{wallet_signature:a}=await br({wallet_address:e,sign_method:"personal_sign",message:i},t,r,n),{accessToken:o}=await to(i,a,n);return o}}function cd(e,t,r,n){let{source:s,dest:i}=t,a=Qs(s.chainId,s.rpcUrl),o=Qs(i.chainId,i.rpcUrl),c=BigInt(r.amount_raw)+BigInt(r.max_fee_raw);return{irisFees:(l,u)=>od(fetch,{irisBaseUrl:t.irisBaseUrl,srcDomain:l,dstDomain:u}),irisAttestation:(l,u)=>lR(fetch,{irisBaseUrl:t.irisBaseUrl,srcDomain:s.cctpDomain,transactionHash:u,destinationDomain:i.cctpDomain,amountRaw:c}),resolveTxStatus:l=>uo(Ui,l),sendBurn:async l=>{let u=BigInt(l.amount_raw)+BigInt(l.max_fee_raw);return{transactionId:(await yR(()=>eo({wallet_address:l.wallet_address,chain_id:s.chainId,sponsor:!0,calls:[{to:s.usdcAddress,value_eth:"0",data:Qv(s.tokenMessengerV2,u)},{to:s.tokenMessengerV2,value_eth:"0",data:zv({amount:u,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:u,attestation:d}=l;if(!u||!d)throw new Error("BRIDGE_NOT_ATTESTED: the job has no message/attestation to submit yet");let m=await yR(()=>lr({wallet_address:l.wallet_address,to:i.messageTransmitterV2,value_eth:"0",chain_id:i.chainId,sponsor:!0,data:Xv(u,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:l=>o.getReceipt(l),currentBlock:()=>a.getBlockNumber(),destBlock:()=>o.getBlockNumber(),scanBurnLogs:async(l,u,d)=>{let m=await mR(f=>a.getLogs(f),{fromBlock:l,toBlock:u,tokenMessenger:s.tokenMessengerV2},d,{amountRaw:c,mintRecipient:r.wallet_address,destinationDomain:i.cctpDomain});return m?{hash:m.transactionHash}:null},scanMintLogs:async(l,u)=>{let d=await fR(m=>o.getLogs(m),{fromBlock:l,toBlock:await o.getBlockNumber(),tokenMessenger:i.tokenMessengerV2},u);return d?{amountRaw:d.amountRaw.toString()}:null},getTransactionByHash:l=>a.getTransaction(l),isNonceUsed:l=>hR((u,d)=>o.usedNonces(u,d),i.messageTransmitterV2,l),registerRelay:l=>_R(fetch,n0(l.wallet_address,e,n),l,t,e),now:()=>Math.floor($n.now()/1e3),destTokenMessenger:i.tokenMessengerV2,graceBlocks:e.bridgeBurnGraceBlocks,mintMaxAttempts:e.bridgeMintMaxAttempts}}function dd(e){return xr.includes(e)}function yo(e){return e.status==="FAILED"&&!!e.burn_tx_hash&&!e.minted_amount_raw}function s0(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 Eo(e){let t=s0(e);return{job_id:e.id,status:e.status,wallet_address:e.wallet_address,amount_usdc:Ue(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:Ue(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:ad(e.wallet_address)}:{},...yo(e)?{funds_mid_flight:!0,recovery:_o(e.wallet_address)}:{},...t?{agent_guidance:t}:{}}}function i0(e,t,r){let n=Sr(e.id)??e,s=Eo(n),i=dd(n.status);if(S({...s,...t.verdictWithheld?{verdict_withheld:!0}:{},...t.note?{note:t.note}:{},...t.privyStatus?{privy_status:t.privyStatus}:{},...i?{}:{next_step:ld(r)}}),!i){console.error(ud(n.status));return}n.status==="FAILED"&&((yo(n)||t.fundsMidFlight)&&console.error(_o(r)),process.exit(2))}async function vR(e,t,r,n,s){let i=await od(fetch,{irisBaseUrl:s.irisBaseUrl,srcDomain:s.source.cctpDomain,dstDomain:s.dest.cctpDomain}),a=cR(i,t,r,n.bridgeMaxFeeBufferPct),o=t+a,l=await Qs(s.source.chainId,s.source.rpcUrl).erc20Balance(s.source.usdcAddress,e);return{amountRaw:t,maxFeeRaw:a,requiredRaw:o,sourceBalanceRaw:l,sufficient:l>=o}}var a0=async e=>{let t=e.includes("--fast"),r=e.includes("--wait"),n=e.filter(u=>u!=="--fast"&&u!=="--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=O();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;N(a.dataDir),X(s),le(a.appServerUrl);let c=Buffer.from(a.passphrase,"utf8"),l;try{let u,d;if(i===void 0){let f=jv(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(!po(f.id,a.bridgeLeaseSec)){S({...Eo(f),lease_held:!0,next_step:ld(s)}),console.error(ud(f.status)),console.error("note: another process is already advancing this bridge; nothing was submitted.");return}l=f.id,u=f,d=await ho(u,cd(a,o,u,c))}else{let f=Xs(i),g=Xs(a.bridgeMinUsdc);if(f<g){b({error:"BRIDGE_AMOUNT_BELOW_MIN",message:`${Ue(f)} USDC is below the fixed ${a.bridgeMinUsdc} USDC bridge minimum. Nothing was submitted.`,amount_usdc:Ue(f),min_usdc:a.bridgeMinUsdc}),process.exit(1);return}let h=await vR(s,f,t,a,o),E=h.maxFeeRaw;if(!h.sufficient){b({error:"BRIDGE_INSUFFICIENT_USDC",message:`${Ue(h.sourceBalanceRaw)} USDC on ${o.source.name} is short of the ${Ue(h.requiredRaw)} USDC this transfer needs`+(E>0n?` (${Ue(f)} to receive + ${Ue(E)} max fee)`:"")+". Nothing was submitted.",source:o.source.name,balance_usdc:Ue(h.sourceBalanceRaw),required_usdc:Ue(h.requiredRaw),required_raw:h.requiredRaw.toString()}),process.exit(1);return}if(!nd(s,E)){let C=Gn(s);b({error:"BRIDGE_FEE_NOT_AUTHORIZED",message:`This transfer's fee is ${Ue(E)} USDC`+(C?`, above the ${Ue(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:Ue(E),max_fee_raw:E.toString(),grant_max_fee_usdc:C?Ue(BigInt(C.max_fee_raw)):null}),process.exit(1);return}let w=await Qs(o.source.chainId,o.source.rpcUrl).getBlockNumber(),A=await Qs(o.dest.chainId,o.dest.rpcUrl).getBlockNumber();u=qv({walletAddress:s,sourceChainId:o.source.chainId,destChainId:o.dest.chainId,amountRaw:f.toString(),isFast:t,maxFeeRaw:E.toString(),fromBlock:w.toString(),mintFromBlock:A.toString()}),po(u.id,a.bridgeLeaseSec),l=u.id,d=await aR(u,cd(a,o,u,c))}if(t||r){let f=t?JU:KU,g=$n.now()+f;for(;!dd(d.status)&&$n.now()<g;){await $n.sleep(Math.min(WU,g-$n.now()));let h=Sr(u.id);if(!h)break;po(h.id,a.bridgeLeaseSec),d=await ho(h,cd(a,o,h,c))}}i0(u,d,s)}catch(u){let d=r0(u);if(d)b(d);else if(tn(u)==="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=tn(u),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{l&&Vv(l)}},o0=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=O();N(n.dataDir);try{if(r){let a=Sr(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}S(Eo(a)),yo(a)&&console.error(_o(t));return}let s=Bv(t),i=s.find(a=>!dd(a.status));S({wallet_address:t,active_job_id:i?.id??null,jobs:s.map(Eo),...i?{next_step:ld(t)}:{}}),i&&console.error(ud(i.status));for(let a of s)if(yo(a)){console.error(_o(t));break}}catch(s){b({error:tn(s)}),process.exit(1)}};function ER(e){let t=Gn(e);return{wallet_address:e,granted:!!t,max_fee_usdc:t?Ue(BigInt(t.max_fee_raw)):null,max_fee_raw:t?t.max_fee_raw:null,granted_at:t?t.granted_at:null}}var c0=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=O();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;N(i.dataDir),X(n);let o;try{o=Xs(s)}catch(c){b({error:"BRIDGE_AMOUNT_INVALID",message:tn(c).replace(/^BRIDGE_AMOUNT_INVALID:\s*/,"")}),process.exit(1);return}try{let c=await vR(n,o,t,i,a),l=Gn(n);S({wallet_address:n,amount_usdc:Ue(c.amountRaw),amount_raw:c.amountRaw.toString(),mode:t?"fast":"standard",max_fee_usdc:Ue(c.maxFeeRaw),max_fee_raw:c.maxFeeRaw.toString(),required_usdc:Ue(c.requiredRaw),source:a.source.name,source_balance_usdc:Ue(c.sourceBalanceRaw),sufficient:c.sufficient,below_min:o<Xs(i.bridgeMinUsdc),min_usdc:i.bridgeMinUsdc,preauthorized:nd(n,c.maxFeeRaw),grant_max_fee_usdc:l?Ue(BigInt(l.max_fee_raw)):null})}catch(c){b({error:tn(c)}),process.exit(1)}},l0=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=O();if(N(i.dataDir),X(n),t){Gv(n),S(ER(n));return}if(s!==void 0){let a;try{a=Xs(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}Hv(n,a.toString())}S(ER(n))},RR={"bridge-usdc":a0,"bridge-usdc-status":o0,"bridge-usdc-quote":c0,"bridge-fast-grant":l0};p();import{randomUUID as Sd}from"crypto";p();var u0={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 Wn(e,t){if(!e||!t)return null;let r=u0[e];return r?`${r}/tx/${t}`:null}p();function To(e,t){x().prepare(`
|
|
693
|
+
INSERT OR REPLACE INTO phone_verifications (wallet_address, phone, verified_at)
|
|
694
|
+
VALUES (?, ?, CURRENT_TIMESTAMP)
|
|
695
|
+
`).run(e,t)}function wR(e){return x().prepare("SELECT phone FROM phone_verifications WHERE wallet_address = ? ORDER BY verified_at ASC").all(e).map(r=>r.phone)}function AR(e,t){return x().prepare("SELECT 1 FROM phone_verifications WHERE wallet_address = ? AND phone = ?").get(e,t)!==void 0}p();function bo(e){x().prepare(`
|
|
320
696
|
INSERT OR REPLACE INTO ride_requests (
|
|
321
|
-
request_id, wallet_address, member_id, region, product_code, status, price, pay_currency,
|
|
697
|
+
request_id, journey_id, ride_id, wallet_address, member_id, region, product_code, status, price, pay_currency,
|
|
322
698
|
origin_name, origin_addr, origin_lat, origin_lng,
|
|
323
699
|
dest_name, dest_addr, dest_lat, dest_lng,
|
|
324
700
|
rider_name, rider_phone
|
|
325
701
|
) VALUES (
|
|
326
|
-
@request_id, @wallet_address, @member_id, @region, @product_code, @status, @price, @pay_currency,
|
|
702
|
+
@request_id, @journey_id, @ride_id, @wallet_address, @member_id, @region, @product_code, @status, @price, @pay_currency,
|
|
327
703
|
@origin_name, @origin_addr, @origin_lat, @origin_lng,
|
|
328
704
|
@dest_name, @dest_addr, @dest_lat, @dest_lng,
|
|
329
705
|
@rider_name, @rider_phone
|
|
330
706
|
)
|
|
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
|
|
707
|
+
`).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 Oe(e){return x().prepare("SELECT * FROM ride_requests WHERE request_id = ?").get(e)}function Jn(e,t){x().prepare(`
|
|
332
708
|
UPDATE ride_requests SET status = ?, status_updated_at = strftime('%s', 'now') WHERE request_id = ?
|
|
333
|
-
`).run(t,e)}function
|
|
334
|
-
INSERT OR REPLACE INTO
|
|
335
|
-
VALUES (?, ?,
|
|
336
|
-
`).run(e,t
|
|
337
|
-
SELECT
|
|
338
|
-
`).get(e,t
|
|
339
|
-
INSERT INTO
|
|
340
|
-
VALUES (?, ?,
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
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(`
|
|
709
|
+
`).run(t,e)}function xR(e,t){x().prepare("UPDATE ride_requests SET ride_id = COALESCE(ride_id, ?) WHERE request_id = ?").run(t,e)}p();var Zs;function be(e){Zs=e.replace(/\/$/,"")}async function Qt(e,t,r,n,s,i){let a={"Content-Type":"application/json",Authorization:`Bearer ${r}`,...i},o=s?`${Zs}${t}?${new URLSearchParams(s).toString()}`:`${Zs}${t}`,c=await fetch(o,{method:e,headers:a,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 SR(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(`${Zs}/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 IR(e,t){return Qt("GET","/v1/phone-verification/check",e,void 0,{phone:t})}function DR(e,t){return Qt("POST","/v1/phone-verification/send-code",e,{phone:t})}function OR(e,t,r){return Qt("POST","/v1/phone-verification/confirm",e,{phone:t,code:r})}function NR(e,t,r){return Qt("POST","/v2/rides/base-search",e,{region:t,locations:r})}function CR(e,t){return Qt("POST","/v2/rides/pre-request",e,t)}function PR(e,t){return SR(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 LR(e,t,r){return SR(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 ei={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"},d0={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 ti(e){let t=e.toUpperCase();return ei[t]?t:d0[e.toLowerCase()]}var p0={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 MR(e,t,r,n,s){let i=ei[r];if(!i)throw new Error(`Unsupported city code: ${r}. Use codes like SIN, BKK, DEN.`);let a=p0[r],o=n??a.lat,c=s??a.lng;return Qt("GET","/v2/places/autocomplete",e,void 0,{input:t,latitude:String(o),longitude:String(c)},{region:i})}function kR(e,t,r){let n=ei[r];if(!n)throw new Error(`Unsupported city code: ${r}. Use codes like SIN, BKK, DEN.`);return Qt("GET",`/v1/places/${encodeURIComponent(t)}`,e,void 0,{region:n,city:r},{region:n})}function ri(e,t){return Qt("GET",`/v1/rides/request/${t}`,e)}function vo(e,t,r,n){let s={};return r&&(s.reason=r),n!=null&&(s.cancelReasonType=n),Qt("POST",`/v2/rides/request/${t}/cancel`,e,s)}async function Ro(e,t,r,n=20){let s={limit:String(n)};r&&(s.messageTs=r);let a=(await Qt("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 wo(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(`${Zs}/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 UR(e,t,r=18e4){let n=Date.now()+r;x().prepare(`
|
|
710
|
+
INSERT OR REPLACE INTO search_cache (check_sum, raw, expires_at)
|
|
711
|
+
VALUES (?, ?, ?)
|
|
712
|
+
`).run(e,t,n)}function FR(e){let t=Date.now();return x().prepare(`
|
|
713
|
+
SELECT raw FROM search_cache WHERE check_sum = ? AND expires_at > ?
|
|
714
|
+
`).get(e,t)?.raw??null}function qR(e,t,r=6e5){let n=Date.now()+r;x().prepare(`
|
|
715
|
+
INSERT OR REPLACE INTO payment_cache (request_id, data, expires_at)
|
|
716
|
+
VALUES (?, ?, ?)
|
|
717
|
+
`).run(e,JSON.stringify(t),n)}function jR(e){let t=Date.now(),r=x().prepare(`
|
|
718
|
+
SELECT data FROM payment_cache WHERE request_id = ? AND expires_at > ?
|
|
719
|
+
`).get(e,t);return r?JSON.parse(r.data):null}function Ao(e,t){UR(e,t,18e4)}function xo(e){return FR(e)}function So(e,t){let r=t.expiresAt-Date.now();qR(e,t,r>0?r:6e5)}function Kn(e){let t=jR(e);return t||null}p();var BR={12:"Ride Throo",14:"EV Throo"},VR={0:"Save Throo",1:"XL Throo",31:"EV Throo",13:"Premium Throo",4:"Premium XL Throo",4e4:"WAV Throo"};function Io(e,t,r,n){return(e??"").toUpperCase()!=="NY"?n:t!==void 0&&t in BR?BR[t]:r!==void 0&&r in VR?VR[r]:n}p();function m0(e,t){return`${(t==="mi"?e/1609.344:e/1e3).toFixed(1)} ${t}`}function f0(e){return`${Math.round(e/60)} min`}var g0=e=>typeof e=="number"&&Number.isFinite(e),HR=(e,...t)=>{for(let r of t)if(g0(e[r]))return e[r]};function GR(e,t){if(e==null||typeof e!="object")return e;let r=e,n={...r},s=HR(r,"distance","distance_meter"),i=HR(r,"duration","duration_seconds");return s!==void 0&&(n.distance_display=m0(s,t)),i!==void 0&&(n.duration_display=f0(i)),n}function Do(e,t){if(Array.isArray(e))return e.map(n=>GR(n,t));if(e==null||typeof e!="object")return e;let r={};for(let[n,s]of Object.entries(e))r[n]=GR(s,t);return r}p();var h0={minLat:15,maxLat:72,minLng:-168,maxLng:-52};function _t(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Invalid coordinate for region routing: lat=${e}, lng=${t}`);let r=h0;return e>=r.minLat&&e<=r.maxLat&&t>=r.minLng&&t<=r.maxLng?"US":"SG"}var _0=new Set(["NY"]);function Pt(e){return e&&_0.has(e.toUpperCase())?"US":"SG"}function Oo(e){return e==="US"?"mi":"km"}function nt(e,t,r){return(t??{})[e]??r}function Xe(e,t){return nt("US",e,t)}function y0(e){let t=De(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 No(e){let t=y0(e.wallet_address),r=await NR(t,e.region,e.locations),n=JSON.stringify(r),s=r.checkSum;if(!s)throw new Error("product-search response missing checkSum field");Ao(s,n);let i=r.products??[],a=[];for(let o of i){let l=(o.priceInfos??[]).find(u=>u.currencyId===e.payCurrency);if(l){let u=l.supportedCurrencyPriceInfo;a.push({product_id:o.id,product_code:o.code,product_name:Io(e.region,o.productType,o.carType,o.title),pay_currency:e.payCurrency,price:u?.priceAfterDiscount??u?.price,price_currency:u?.currency})}}return{search_id:s,options:a,routes:Do(r.routes,Oo(Pt(e.region)))}}p();p();p();p();function Yn(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 zn(e){if(e==null)return null;let t=e.trim();return t.length===0?null:t.toLowerCase()}function pd(e){let t=zn(e.label),r=Yn({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=x().prepare(`
|
|
347
720
|
INSERT INTO places (
|
|
348
721
|
wallet_address, label, name, formatted_address, latitude, longitude,
|
|
349
722
|
google_place_id, city, region, ftid, kg_id, source_url,
|
|
@@ -354,16 +727,16 @@ ${Ln.randomUUID()}
|
|
|
354
727
|
1, 0, NULL, @dedup_key,
|
|
355
728
|
strftime('%s', 'now')
|
|
356
729
|
)
|
|
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
|
|
358
|
-
ORDER BY ${
|
|
359
|
-
WHERE wallet_address = ? AND label IN (${l})${
|
|
360
|
-
ORDER BY ${
|
|
361
|
-
WHERE wallet_address = ? AND (${
|
|
362
|
-
ORDER BY ${
|
|
363
|
-
WHERE wallet_address = ? AND (${
|
|
364
|
-
ORDER BY ${
|
|
730
|
+
`).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 x().prepare("SELECT * FROM places WHERE id = ?").get(n.lastInsertRowid)}var Co="is_favorite DESC, hit_count DESC, last_used_at DESC NULLS LAST, created_at DESC";function md(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 ")}
|
|
731
|
+
ORDER BY ${Co}`;return t.limit&&t.limit>0&&(s+=" LIMIT ?",n.push(t.limit)),x().prepare(s).all(...n)}function $R(e,t,r={}){let n=Array.from(new Set(t.map(v=>v.trim().toLowerCase()).filter(v=>v.length>0)));if(n.length===0)return{matches:md(e,r),matched_tier:null,normalized_queries:[]};let s=x(),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 ?":"",l=n.map(()=>"?").join(","),u=[e,...n];o&&u.push(r.limit);let d=s.prepare(`SELECT * FROM places
|
|
732
|
+
WHERE wallet_address = ? AND label IN (${l})${a}
|
|
733
|
+
ORDER BY ${Co}${c}`).all(...u);if(d.length>0)return{matches:d,matched_tier:"label",normalized_queries:n};let m=n.map(v=>`%${v}%`),f=n.map(()=>"name LIKE ? COLLATE NOCASE").join(" OR "),g=[e,...m];o&&g.push(r.limit);let h=s.prepare(`SELECT * FROM places
|
|
734
|
+
WHERE wallet_address = ? AND (${f})${a}
|
|
735
|
+
ORDER BY ${Co}${c}`).all(...g);if(h.length>0)return{matches:h,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 w=s.prepare(`SELECT * FROM places
|
|
736
|
+
WHERE wallet_address = ? AND (${E})${a}
|
|
737
|
+
ORDER BY ${Co}${c}`).all(...T);return w.length>0?{matches:w,matched_tier:"address",normalized_queries:n}:{matches:[],matched_tier:null,normalized_queries:n}}function WR(e,t){let r=x().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,t);return r?(x().prepare("DELETE FROM places WHERE wallet_address = ? AND id = ?").run(e,t),r):null}function JR(e,t){let r=zn(t);if(!r)return null;let n=x().prepare("SELECT * FROM places WHERE wallet_address = ? AND label = ?").get(e,r);return n?(x().prepare("DELETE FROM places WHERE wallet_address = ? AND id = ?").run(e,n.id),n):null}function KR(e){let t=x(),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
738
|
google_place_id = COALESCE(google_place_id, ?)
|
|
366
|
-
WHERE wallet_address = ? AND id = ?`).run(e.dedup_key,e.google_place_id,e.wallet_address,
|
|
739
|
+
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
740
|
`),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
741
|
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
742
|
INSERT INTO places (
|
|
@@ -375,7 +748,7 @@ ${Ln.randomUUID()}
|
|
|
375
748
|
@google_place_id, NULL, @region, NULL, NULL, NULL,
|
|
376
749
|
0, 1, @ts, @dedup_key, strftime('%s', 'now')
|
|
377
750
|
)
|
|
378
|
-
`).run(e);return t.prepare("SELECT * FROM places WHERE id = ?").get(s.lastInsertRowid)}function
|
|
751
|
+
`).run(e);return t.prepare("SELECT * FROM places WHERE id = ?").get(s.lastInsertRowid)}function fd(e,t){return x().prepare("SELECT * FROM places WHERE wallet_address = ? AND dedup_key = ?").get(e,t)}function gd(e,t,r){let n=x();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?zn(r.label):null;return n.prepare(`
|
|
379
752
|
UPDATE places SET
|
|
380
753
|
is_favorite = 1,
|
|
381
754
|
label = CASE WHEN @label_provided THEN @label ELSE label END,
|
|
@@ -389,91 +762,92 @@ ${Ln.randomUUID()}
|
|
|
389
762
|
region = COALESCE(@region, region),
|
|
390
763
|
updated_at = strftime('%s', 'now')
|
|
391
764
|
WHERE wallet_address = @wallet_address AND dedup_key = @dedup_key
|
|
392
|
-
`).run({wallet_address:e,dedup_key:t,label:
|
|
765
|
+
`).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 ni(e,t){return x().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,t)}function YR(e,t,r){if(!ni(e,t))return null;let s=r!==void 0?zn(r):void 0;return x().prepare(`
|
|
393
766
|
UPDATE places SET
|
|
394
767
|
is_favorite = 1,
|
|
395
768
|
label = CASE WHEN ? THEN ? ELSE label END,
|
|
396
769
|
updated_at = strftime('%s','now')
|
|
397
770
|
WHERE wallet_address = ? AND id = ?
|
|
398
|
-
`).run(s!==void 0?1:0,s??null,e,t),
|
|
399
|
-
WHERE wallet_address = ? AND id = ?`).run(e,t),
|
|
400
|
-
WHERE wallet_address = ? AND id = ?`).run(e,n.id),
|
|
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
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
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
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
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(`
|
|
771
|
+
`).run(s!==void 0?1:0,s??null,e,t),x().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,t)}function zR(e,t){let r=zn(t);if(r)return x().prepare("SELECT * FROM places WHERE wallet_address = ? AND label = ?").get(e,r)}function XR(e,t){let r=ni(e,t);return r?r.is_favorite===0?r:(x().prepare(`UPDATE places SET is_favorite = 0, label = NULL, updated_at = strftime('%s','now')
|
|
772
|
+
WHERE wallet_address = ? AND id = ?`).run(e,t),x().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,t)):null}function QR(e,t){let r=zn(t);if(!r)return null;let n=x().prepare("SELECT * FROM places WHERE wallet_address = ? AND label = ?").get(e,r);return n?n.is_favorite===0?n:(x().prepare(`UPDATE places SET is_favorite = 0, label = NULL, updated_at = strftime('%s','now')
|
|
773
|
+
WHERE wallet_address = ? AND id = ?`).run(e,n.id),x().prepare("SELECT * FROM places WHERE wallet_address = ? AND id = ?").get(e,n.id)):null}function ZR(e){for(let t of e.locations){let r=t.googlePlaceId??t.placeId,n=Yn({placeId:r,latitude:t.latitude,longitude:t.longitude});if(!n){process.stderr.write(`[place-history] skip location (no placeId + invalid coords): name=${t.name}
|
|
774
|
+
`);continue}KR({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 E0(e){let t=De(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 Po(e,t){let r=E0(e.wallet_address),n=xo(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 l=c.walletProviderId,u=await CR(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}}),d=e.locations[0],m=e.locations[e.locations.length-1];bo({request_id:u.requestId,wallet_address:e.wallet_address,region:e.region,product_code:e.product_code,price:u.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{ZR({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}
|
|
775
|
+
`)}return{request_id:u.requestId,price:u.price,currency:u.currency}}p();var Lo;function Ir(e){Lo=e.replace(/\/$/,"")}async function Mo(e,t,r,n,s){let i={"Content-Type":"application/json",Authorization:`Bearer ${r}`},a=s?`${Lo}${t}?${new URLSearchParams(s).toString()}`:`${Lo}${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 ew(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(`${Lo}/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 tw(e,t){return Mo("GET","/tip/config",e,void 0,{region:t})}function rw(e,t,r){return Mo("POST",`/v2/rides/request/${t}/tip/pre-request`,e,{price:r})}function nw(e,t){return ew(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 sw(e,t,r){return ew(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 iw(e,t=20){let r=await Mo("GET","/v2/rides/request/history",e,void 0,{status:"completed",limit:String(t)});return{items:r.items??[],nextCursor:r.nextCursor??null}}function ko(e,t){return Mo("GET",`/v2/ride-histories/detail/${t}`,e)}p();import yd from"fs";import{spawn as b0}from"child_process";import Ed from"path";p();import jt from"fs";import aw from"path";function Uo(e,t){return aw.join(e,"run",`${t}.pid`)}function hd(e){try{let t=parseInt(jt.readFileSync(e,"utf8").trim(),10);return Number.isNaN(t)?null:t}catch{return null}}function ow(e){try{return process.kill(e,0),!0}catch{return!1}}function Xn(e,t){let r=hd(Uo(e,t));return r!==null&&ow(r)}function _d(e,t){if(jt.existsSync(`${e}.amb-migration-quiesced`))return!1;let r=Uo(e,t);jt.mkdirSync(aw.dirname(r),{recursive:!0});try{let n=jt.openSync(r,"wx");return jt.writeSync(n,String(process.pid)),jt.closeSync(n),!0}catch{let n=hd(r);if(n===process.pid||n!==null&&ow(n))return!1;try{jt.unlinkSync(r)}catch{}try{let s=jt.openSync(r,"wx");return jt.writeSync(s,String(process.pid)),jt.closeSync(s),!0}catch{return!1}}}function Fo(e,t){try{hd(Uo(e,t))===process.pid&&jt.unlinkSync(Uo(e,t))}catch{}}p();import{createHash as cw}from"crypto";var lw=1,T0=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 Bt(e){return T0.has(e.toUpperCase())}function rn(e){let t=e.kind==="ride_status"?`${e.rideId}|ride_status|${e.status??""}`:`${e.rideId}|${e.kind}|${cw("sha256").update(e.content??"").digest("hex")}`;return"evt_"+cw("sha256").update(t).digest("hex").slice(0,24)}function v0(){let e=process.argv[1]??"",t=e?Ed.resolve(e):"";if(!t||!yd.existsSync(t))throw new Error(`amb entry not found (argv[1]=${process.argv[1]}, resolved=${t})`);return t}async function gr(e,t={}){try{let r=Oe(e);if(!r||Bt(r.status)||Xn(ye(),`sup-${e}`))return!1;let n=t.spawn??b0,s=v0();return n(process.execPath,[s,"monitor-supervisor",e],{detached:!0,stdio:"ignore"}).unref?.(),!0}catch(r){try{let n=Ed.join(ye(),"run",`monitor-trace-${e}.log`);yd.mkdirSync(Ed.dirname(n),{recursive:!0}),yd.appendFileSync(n,JSON.stringify({ts:new Date().toISOString(),pid:process.pid,event:"ensure_monitor_failed",rideId:e,error:String(r)})+`
|
|
776
|
+
`)}catch{}return!1}}p();import R0 from"fs";import w0 from"path";p();function uw(e){let t=Math.floor(Date.now()/1e3),r=x();r.prepare("DELETE FROM tada_members WHERE id <> ?").run(e.id),r.prepare(`
|
|
777
|
+
INSERT INTO tada_members (id, phone, display_name, region, created_at, last_active_at)
|
|
778
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
779
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
780
|
+
phone = excluded.phone,
|
|
781
|
+
display_name = excluded.display_name,
|
|
782
|
+
region = excluded.region,
|
|
783
|
+
last_active_at = excluded.last_active_at
|
|
784
|
+
`).run(e.id,e.phone??null,e.display_name??null,e.region??null,t,t)}function si(){return x().prepare("SELECT * FROM tada_members ORDER BY last_active_at DESC LIMIT 1").get()}function dw(e){let t=x();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 Td;function mw(e){Td=e}function fw(){return Td}function gw(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 pw(){return{hasMember:!1,hasWallet:!1,member:void 0,walletAddress:void 0}}function A0(){let e=mn(),t=w0.join(e,"ambient-ride.db");if(!R0.existsSync(t))return pw();try{N(e);let r=si(),n=Ni(),s=n.length>0?n:Oi();return{hasMember:!!r,hasWallet:s.length>0,member:r,walletAddress:s.length===1?s[0].wallet_address:void 0}}catch{return pw()}}function Qe(e={}){let t=e.flag??Td,r=A0();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 x0=["wallet-","deposit-","siwe-","ride-pay-","bridge-"],S0=new Set(["wallet-setup","wallet-setup-verify","wallet-status","wallet-balance","wallet-connect-metamask"]),I0=["coupon-"];function hw(e){if(!S0.has(e)){if(x0.some(t=>e.startsWith(t)))return"wallet";if(I0.some(t=>e.startsWith(t)))return"tada"}}function _w(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 yw="";function Qn(e){yw=e.replace(/\/$/,"")}async function Dr(e,t,r={}){let n=(r.host??yw).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 ht(a.status,o)}return a.json()}function Ew(e,t){return Dr("/v1/cards",t,{host:e})}function Tw(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 nn(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=Tw(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"?(S({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 ii="";function Or(e){ii=e.replace(/\/$/,"")}function D0(e){return`Basic ${Buffer.from(`${e.clientId}:${e.clientSecret}`).toString("base64")}`}async function bd(e,t,r,n){if(!ii)throw new Error("tada gateway api not initialized");let s=await fetch(`${ii}${r}`,{method:t,headers:{"Content-Type":"application/json",Authorization:D0(e)},body:n!==void 0?JSON.stringify(n):void 0});if(!s.ok){let i=await s.text().catch(()=>"");throw ht(s.status,i)}return s.json()}function bw(e){return bd(e,"POST","/v1/agent-session")}function vw(e,t,r){return bd(e,"POST","/v1/oauth/token",{grant_type:"agent_session",session_token:t,user_code:r})}function Rw(e,t){return bd(e,"POST","/v1/oauth/token",{grant_type:"refresh_token",refresh_token:t})}async function ww(e){if(!ii)throw new Error("tada gateway api not initialized");let t=await fetch(`${ii}/v1/me`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!t.ok){let r=await t.text().catch(()=>"");throw ht(t.status,r)}return t.json()}p();function Aw(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 xw(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 N0(){return Math.floor(Date.now()/1e3)}async function vd(e){let t=await bw(e);return{sessionToken:t.session_token,approvalUrl:t.approval_url,expiresAt:t.expires_at,pollIntervalSec:t.polling_interval_seconds}}async function Rd(e,t,r){let n=await vw(e,t,r),s=Aw(n.access_token);if(!s)throw new Error("access token missing sub claim");let i=await C0(n.access_token);return uw({id:s,display_name:i?.name??void 0,phone:i?.phone??void 0}),Sw(s,n.access_token,n.expires_in,n.refresh_token),{memberId:s}}async function C0(e){try{let t=await ww(e);return{name:t.name,phone:t.phone}}catch(t){return Et(`[tada-auth] /v1/me profile fetch failed; persisting member id only: ${String(t)}
|
|
785
|
+
`),null}}function Sw(e,t,r,n){Yp(e,t,N0()+r,n,xw(n))}async function qo(e){let t=si();if(!t)return null;let r=ce(t.id,"member");if(r)return r;let n=$i(t.id);if(!n)return Et(`[tada-auth] no usable member refresh token (expired or pruned); re-login required
|
|
786
|
+
`),null;try{let s=await Rw(e,n.refresh_token);return Sw(t.id,s.access_token,s.expires_in,s.refresh_token),s.access_token}catch(s){return Et(`[tada-auth] member token refresh failed; re-login required: ${String(s)}
|
|
787
|
+
`),null}}function Iw(){let e=si();return e?(dw(e.id),!0):!1}p();p();import{EventEmitter as M0}from"events";import{io as k0}from"socket.io-client";p();import L0 from"path";var jo=1e4;function Bo(e,t){return L0.join(e,"run",`chat-${t}.sock`)}function wd(e,t){if(!vp())return;let r={ts:new Date().toISOString(),msg:e,...t??{}};Et("[chat-debug] "+JSON.stringify(r)+`
|
|
788
|
+
`)}var Vo=class extends M0{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=ce(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=k0(`${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"})},jo);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",()=>{wd("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=>{wd("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=ce(this.walletAddress),s=!!n;n&&t.auth&&(t.auth.token=n),wd("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 Nr=class extends Error{code="NOT_SUPPORTED";constructor(t){super(t),this.name="NotSupportedError"}},Zn=class extends Error{code="SHARE_NOT_AVAILABLE";constructor(t){super(t),this.name="ShareNotAvailableError"}};p();p();async function Ho(e){let{rawTypedData:t,walletAddress:r,target:n}=e;if(Tt(r)==null)return{typed_data:t,isSmartAccount:!1};let s=await xp(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 _n(n,r))return{typed_data:t,isSmartAccount:!1};let i=await Li(n,r),a=ro(t);return{typed_data:no({kernelDomain:i,innerDigest:a}),isSmartAccount:!0}}function Go(e,t){return t?so(e):e}function U0(e){let t=De(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 $o(e){let{request_id:t,price:r,wallet_address:n,config:s}=e,i=U0(n);await rw(i,t,r);let{accepts:a,nonce:o}=await nw(i,t);if(!a.length)throw new Error("TIP_PAY_PROBE_FAILED: Server returned no payment accepts.");let c=a[0],l=String(Math.floor(Date.now()/1e3)+c.maxTimeoutSeconds),u=c.network.split(":")[1],d=u?parseInt(u,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:l,nonce:o}},{typed_data:f,isSmartAccount:g}=await Ho({rawTypedData:m,walletAddress:n,target:{rpcUrl:s.paymentRpcUrl,chainId:d}});return So(t,{accepts:a,nonce:o,walletAddress:n,validBefore:l,expiresAt:Date.now()+c.maxTimeoutSeconds*1e3,isSmartAccount:g}),{typed_data:f}}p();function F0(e){let t=De(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 Wo(e){let{request_id:t,signature:r}=e,n=Kn(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,l=F0(a),u=s[0],d={x402Version:2,accepted:u,payload:{authorization:{from:a,to:u.payTo,value:u.amount,validAfter:"0",validBefore:o,nonce:i},signature:Go(r,c===!0)}},m=Buffer.from(JSON.stringify(d)).toString("base64"),f=await sw(l,t,m);return{success:f.success,tx_hash:f.transaction}}p();function Jo(e,t){if(e?.length)return e.find(r=>!t(r)?.toLowerCase().includes("driver"))??e[0]}function Ze(e){return e.replace(/([\\`*_{}\[\]()<>#+!|])/g,"\\$1")}function Ad(e){return`${Ze(e.amount)} ${e.currency?Ze(e.currency):"currency unavailable"}`}function Ow(e,t){return[`${" ".repeat(t)}- ${Ze(e.label)}: ${Ad(e.amount)}`,...(e.children??[]).flatMap(r=>Ow(r,t+1))]}function Dw(e){let t=e.name.trim(),r=e.address.replace(/^[\s,;:–—-]+/u,"").trim();return Ze(t&&r&&t!==r?`${t} \u2014 ${r}`:t||r)}function q0(e){return e.replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\s/g,"%20")}function Nw(e){return new Set(e.flatMap(t=>[t.amount.currency,...Nw(t.children??[])]).filter(t=>!!t))}function Cw(e){let t=["# Ride receipt"];if(e.total&&t.push("","## Total fee charged",`**${Ad(e.total)}**`),e.fareItems.length){t.push("","## Fare breakdown");for(let n of e.fareItems)t.push(...Ow(n,0))}let r=Nw(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 ${Ze(n)} and the charge in ${Ze(e.total.currency)}${e.exchangeRate?`; exchange rate ${Ze(e.exchangeRate)}`:""}.`)}if(e.transactions?.length){t.push("","## Transactions");for(let n of e.transactions){let s=n.explorerUrl?`[${Ze(n.hash)}](${q0(n.explorerUrl)})`:Ze(n.hash),i=n.network?` (${Ze(n.network)})`:"",a=n.amount?` \u2014 ${Ad(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: ${Ze(n)}`)}return e.rideType&&t.push(`- Ride type: ${Ze(e.rideType)}`),e.driverName&&t.push(`- Driver: ${Ze(e.driverName)}`),e.passengerName&&t.push(`- Passenger: ${Ze(e.passengerName)}`),t.push(`- Ride ID: ${Ze(e.rideId)}`),e.pickup&&t.push(`- Pickup: ${Dw(e.pickup)}`),e.dropoff&&t.push(`- Destination: ${Dw(e.dropoff)}`),e.paymentMethod&&t.push(`- Payment method: ${Ze(e.paymentMethod)}`),`${t.join(`
|
|
445
789
|
`)}
|
|
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()>=
|
|
790
|
+
`}function Pw(e,t){return{label:e.displayName,amount:{amount:String(e.fare),currency:t},...e.children?.length?{children:e.children.map(r=>Pw(r,t))}:{}}}function j0(e){let t=Jo(e.receiptBreakdown,u=>u.subtotalName),r=e.locations[0],n=e.locations.at(-1),s=e.receiptInfo?.paidNetwork??void 0,i=[],a=(u,d,m,f)=>{if(!m)return;let g=Wn(d??null,m);i.push({kind:u,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()??""),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:o&&c,...l?{total:l}:{},fareItems:t?.fareItems.map(u=>Pw(u,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 ai=class{constructor(t,r,n,s=br){this.config=t;this.jwt=r;this.walletAddress=n;this.walletSigner=s;be(t.gatewayServerUrl),Ir(t.gatewayServerUrl),t.appServerUrl&&le(t.appServerUrl)}config;jwt;walletAddress;walletSigner;async searchRides(t){return No(t)}getCancelPenalty(t){throw new Nr("getCancelPenalty: not supported in crypto mode (cancellation fee is reported on cancel via isFreeCancel)")}getCancelReasons(t){throw new Nr("getCancelReasons: not supported in crypto mode")}getCards(t){throw new Nr("Card list is only available for TADA/Throo members.")}async getTipConfig(t){let r=await tw(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 $o({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 Wo({request_id:t,signature:i});return{tipStatus:a.success?"PAID":"FAILED",...a.tx_hash?{txHash:a.tx_hash}:{}}}async bookRide(t){let n=await Po(t,this.config);return{rideId:n.request_id,price:n.price,currency:n.currency}}getRideStatus(t){return ri(this.jwt,t)}async getReceipt(t){return j0(await ko(this.jwt,t))}async getShareLink(t){let r=await ri(this.jwt,t);if(!r.rideShareUrl)throw new Zn("Share link is available after a driver is assigned.");return{url:r.rideShareUrl}}cancelRide(t,r,n){return vo(this.jwt,t,r,n)}async sendChat(t,r){if(r.image)return wo(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 Vo(this.config,t,this.walletAddress)}getMessages(t,r){return Ro(t,this.jwt,r!=null?String(r):void 0)}};p();p();async function sn(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 ht(o.status,c)}return o.json()}function B0(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 Lw(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:B0(e.driver),locations:t,region:e.region,netPrice:e.net_price,payStatus:e.pay_status,tipAmount:e.tip_amount,riderName:e.rider_name}}function oi(e,t,r){return sn(e,"GET",`/v1/rides/${encodeURIComponent(r)}`,t)}function ci(e,t,r){return sn(e,"POST","/v1/products/search",t,r)}function Mw(e,t,r){return sn(e,"POST","/v1/rides",t,r)}function kw(e,t,r,n){return sn(e,"POST",`/v1/rides/${encodeURIComponent(r)}/cancel`,t,n)}function Uw(e,t,r,n){let s=n!=null?`?cancelReasonType=${n}`:"";return sn(e,"GET",`/v1/rides/${encodeURIComponent(r)}/cancel-penalty${s}`,t)}function Fw(e,t,r,n="en"){return sn(e,"GET",`/v1/rides/${encodeURIComponent(r)}/cancel-reasons`,t,void 0,{"Accept-Language":n})}function qw(e){return{url:e.url,urlId:e.url_id,...e.message!=null?{message:e.message}:{},...e.chat_url!=null?{chatUrl:e.chat_url}:{}}}function jw(e,t,r,n="en"){return sn(e,"POST",`/v1/rides/${encodeURIComponent(r)}/share`,t,void 0,{"Accept-Language":n})}p();var V0={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},H0={PH:10,TAXI:11,ANYTADA:12,STUDENT:13,EV:14,TADAFAST:15,TADASAVER:16};function Bw(e){if(e!=null)return V0[e]}function Vw(e){if(e!=null)return H0[e]}function Hw(e){return e?e.split("_").map(t=>t&&t[0].toUpperCase()+t.slice(1).toLowerCase()).join(" "):""}p();async function Gw(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 ht(a.status,o)}return a.json()}function $w(e,t,r){return Gw(e,"GET",`/v1/rides/tip-config?region=${encodeURIComponent(r)}`,t)}function Ww(e,t,r,n){return Gw(e,"POST",`/v1/rides/${encodeURIComponent(r)}/tip`,t,n)}function Jw(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 Kw(e){return{tipStatus:e.tip_status}}p();import{EventEmitter as G0}from"events";async function Yw(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 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"),a=l}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 ht(o.status,await o.text().catch(()=>""));return o.json()}var zw=10;async function xd(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)+zw)*1e3),o=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${t}`},signal:a});if(!o.ok)throw ht(o.status,await o.text().catch(()=>""));return o.json()}var $0=25,W0=2e3;function J0(e){return new Promise(t=>setTimeout(t,e))}var Ko=class extends G0{constructor(r,n,s,i={}){super();this.host=r;this.jwt=n;this.rideId=s;this.wait=i.wait??$0,this.backoffMs=i.backoffMs??W0,this.since=i.startSince??i.nowMs??Date.now(),this.sleepFn=i.sleepFn??J0}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+zw)*1e3);try{let s=await xd(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 eA(e,t){return{label:e.display_name,amount:{amount:String(e.fare),currency:t},...e.children?.length?{children:e.children.map(r=>eA(r,t))}:{}}}function Xw(e){return e==null||typeof e=="string"&&["RATE","AMOUNT","TARGET"].includes(e)}function li(e){let[t,r]=String(e).toLowerCase().split("e"),n=t.split(".")[1]?.length??0;return Math.max(0,n-Number(r??0))}var K0=6;function Y0(e,t){let n=10**Math.max(li(e),li(t));return(Math.round(e*n)+Math.round(t*n))/n}function Qw(e){let t=e.discount;if(![e.net_price,t.original_price,t.discounted_price].every(Number.isFinite))throw new Ar;let n=Math.max(li(e.net_price),li(t.original_price),li(t.discounted_price));if(n>K0)throw new Ar;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 Zw(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 z0(e){let t=Jo(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,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?Y0(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(l=>eA(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 ui=class{constructor(t,r,n,s){this.config=t;this.jwt=r;this.memberId=n;this.rideHost=s}config;jwt;memberId;rideHost;sgHost(){return nt("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 nt(_t(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 Ar;let n=this.hostForPickup(r.locations),i=(await ci(n,this.jwt,{locations:r.locations,payment_item_uuid:r.paymentItemUuid,...r.couponCode?{coupon_code:r.couponCode}:{}})).products.filter(l=>!l.na&&l.price_entry&&Number.isFinite(l.price_entry.net_price)),a=r.productId!=null?i.find(l=>l.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||!Xw(o.discount.discount_type)))throw new Ar;if(r.couponCode){let l=Zw(Qw(o)),u=Zw(r.confirmedPrice);if(!l||!u||l!==u)throw new Ga}let c=await Mw(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 bo({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 Lw(await oi(this.followupHost(),this.jwt,t))}async getReceipt(t){let r=await oi(this.followupHost(),this.jwt,t);return z0(r)}async searchRides(t){let r=t,n=this.hostForPickup(r.locations),s=await ci(n,this.jwt,{locations:r.locations,payment_item_uuid:r.paymentItemUuid,...r.couponCode?{coupon_code:r.couponCode}:{}}),i=r.locations[0],a=Oo(_t(i.latitude,i.longitude));return{options:s.products.map(c=>{let l=c.na===!0||!c.price_entry||!Number.isFinite(c.price_entry.net_price),u=c.price_entry?.discount,d=!l&&u?.applicable===!0&&Xw(u.discount_type),m;if(d)try{m=Qw(c.price_entry)}catch(f){if(!(f instanceof Ar))throw f;d=!1}return{product_id:c.id,product_name:Io(c.region,Vw(c.product_type),Bw(c.car_type),c.description_local??Hw(c.car_type)),price:l?null:d?m:String(c.price_entry.net_price),price_currency:l?null:c.price_entry.currency,na:l,...u?{discount:{applicable:d,...Number.isFinite(u.original_price)?{original_price:String(u.original_price)}:{},...Number.isFinite(u.discounted_price)?{discounted_price:String(u.discounted_price)}:{},...Number.isFinite(u.discount_amount)?{discount_amount:String(u.discount_amount)}:{},...Number.isFinite(u.available_coupon_count)?{available_coupon_count:u.available_coupon_count}:{},...u.discount_type!=null?{discount_type:u.discount_type}:{},...u.title!=null?{title:u.title}:{},...u.code!=null?{coupon_code:u.code}:{},...u.promotion_code!=null?{campaign_promotion_code:u.promotion_code}:{}}}:{}}}),routes:Do(s.routes,a)}}async cancelRide(t,r,n){return kw(this.followupHost(),this.jwt,t,{cancel_reason_type:n??null,cancel_reason:r??null})}getCancelPenalty(t,r){return Uw(this.followupHost(),this.jwt,t,r)}async getCancelReasons(t){return((await Fw(this.followupHost(),this.jwt,t)).reasons??[]).map(n=>({id:n.reason_id,title:n.title}))}async getShareLink(t,r="en"){return qw(await jw(this.followupHost(),this.jwt,t,r))}getCards(t){return Ew(t,this.jwt)}hostForRegion(t){return nt(Pt(t),this.config.cliGatewayHosts,this.config.cliGatewayHost)}async getTipConfig(t){return Jw(await $w(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 Kw(await Ww(this.followupHost(),this.jwt,t,n))}sendChat(t,r){return Yw(this.followupHost(),this.jwt,t,r)}subscribeChat(t){return new Ko(this.followupHost(),this.jwt,t)}getMessages(t,r){return xd(this.followupHost(),this.jwt,t,{since:r})}};async function yt(e,t){if(t.wallet_address){let a=ce(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 ai(e,a,t.wallet_address),jwt:a,identity:t.wallet_address,mode:"wallet"}}Or(Xe(e.cliGatewayHosts,e.cliGatewayHost));let r={clientId:e.riderCliApp.clientId,clientSecret:e.riderCliApp.clientSecret},n=await qo(r);if(!n)throw new Error("Your TADA/Throo session expired. Run `amb login` again.");let s=t.member_id??"",i=nt(Pt(t.region),e.cliGatewayHosts,e.cliGatewayHost);return{backend:new ui(e,n,s,i),jwt:n,identity:s,mode:"tada"}}async function an(e){let t=Qe();if(t.mode==="wallet"){let r=t.walletAddress;if(!r)throw new Error("No registered wallet. Run wallet setup first.");let n=ce(r);if(!n)throw new Error("JWT_NOT_FOUND: no valid wallet JWT. Run siwe-request-message + siwe-submit first.");return{backend:new ai(e,n,r),jwt:n,identity:r,mode:"wallet"}}if(t.mode==="tada"){Or(Xe(e.cliGatewayHosts,e.cliGatewayHost));let r={clientId:e.riderCliApp.clientId,clientSecret:e.riderCliApp.clientSecret},n=await qo(r);if(!n)throw new Error("Your TADA/Throo session expired. Run `amb login` again.");let s=t.member?.id??"";return{backend:new ui(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 Zt(e){Or(Xe(e.cliGatewayHosts,e.cliGatewayHost));let t={clientId:e.riderCliApp.clientId,clientSecret:e.riderCliApp.clientSecret},r=await qo(t);if(!r)throw new Error("Your TADA/Throo session expired. Run `amb login` again.");return r}p();var X0=new Set(["NY","NYC","US","CO","DEN","DENVER"]),Q0={minLat:40.3,maxLat:41.1,minLng:-74.5,maxLng:-73.3},Z0={minLat:39.4,maxLat:40.1,minLng:-105.5,maxLng:-104.4};function es(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 ts(e){let t=e?.trim().toUpperCase();return t&&X0.has(t)?"US":Pt(e)}function di(e,t){return _t(e,t)==="SG"?{marketCode:"SG",subMarket:"SG"}:tA(Q0,e,t)?{marketCode:"NYC",subMarket:"NYC"}:tA(Z0,e,t)?{marketCode:"DEN",subMarket:"DENVER"}:{marketCode:"US",subMarket:"OTHER"}}function tA(e,t,r){return t>=e.minLat&&t<=e.maxLat&&r>=e.minLng&&r<=e.maxLng}p();function Vt(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 rA=["lat_lng","locationPoint"];function e1(e){if(e==null||typeof e!="object")return null;let t=rA.map(i=>e[i]).find(i=>i!=null&&typeof i=="object"),r=Vt(e.latitude)??Vt(e.lat)??Vt(t?.latitude),n=Vt(e.longitude)??Vt(e.lng)??Vt(t?.longitude);if(r==null||n==null)return null;let s={...e};for(let i of["latitude","longitude","lat","lng",...rA])delete s[i];return{...s,latitude:r,longitude:n}}function Yo(e){if(!Array.isArray(e)||e.length===0)return null;let t=[];for(let r of e){let n=e1(r);if(n==null)return null;t.push(n)}return t}p();var t1=new Set(["ASSIGNED","PICKUP","PICKUP_ARRIVED"]),r1=new Set(["INUSE","INUSE_WITH_CANCEL_PENDING"]),n1=new Set(["PAYCONFIRMED","PENDING","ASSIGNED","PICKUP","PICKUP_ARRIVED"]);function zo(e){let{status:t,mode:r,supportsReasons:n,hasReasonType:s}=e;return Bt(t)?{kind:"not_cancelable",why:`ride already ended (${t})`}:r1.has(t)?{kind:"not_cancelable",why:`ride is in progress (${t}) \u2014 it cannot be cancelled`}:r==="crypto"&&!n1.has(t)?{kind:"not_cancelable",why:`ride cannot be cancelled in status ${t}`}:t1.has(t)&&n&&!s?{kind:"needs_reason"}:{kind:"immediate"}}p();p();function s1(e){if(e.member_id&&!e.wallet_address)return vr(e.member_id);if(e.wallet_address&&!e.member_id)return Je(e.wallet_address)}function rs(e){let t=s1(e);if(!t)return;let r=e.region.trim(),n=r?ts(r):void 0,s=es(r);if(!r&&e.journey_id)try{let i=new rt().find(e.journey_id,t);i&&(n=i.region,s=es(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=_t(e.origin_lat,e.origin_lng),s=di(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:i1(e)}}function i1(e){if(e.ride_id)return e.ride_id;if(e.member_id)return e.request_id}async function Xo(e,t,r){try{let n=rs(t),s=n?.accountId;if(n&&await Jb(e,{...n,...r,rideId:r.rideId??n.rideId}),r.rideId&&(xR(t.request_id,r.rideId),t.ride_id??=r.rideId),r.rideId&&t.journey_id&&s)try{new rt().link(t.journey_id,s,{link_type:"ride",link_id:r.rideId})}catch{}if(Bt(r.status)&&t.journey_id&&s)try{new rt().close(t.journey_id,s)}catch{}}catch{}}function a1(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 sA(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=$a(t);return t&&n?{error:t.toUpperCase(),message:n}:void 0}var o1=async e=>{let t=O();if(N(t.dataDir),Qe().mode==="tada"){let u;try{u=a1(e)}catch(Y){b({error:"INVALID_ARGUMENT",message:Y.message}),process.exit(1)}let{positional:d,couponCode:m}=u,[f,g,h,E,T]=d;(!f||!g||!h||!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 w=Vt(f),v=Vt(g),A=Vt(h),C=Vt(E);if(w==null||v==null||A==null||C==null){b({error:"INVALID_COORDINATES",message:"origin/destination lat and lng must all be numbers."}),process.exit(1);return}let P;try{P=await an(t)}catch(Y){b({error:Y.message}),process.exit(1);return}let L=nt(_t(w,v),t.cliGatewayHosts,t.cliGatewayHost),W=await nn(P.backend,T,L);if(W==null)return;let Z=_t(w,v),V=di(w,v);try{let Y=P.identity?vr(P.identity):void 0,ge,ee,te;if(Y)try{ge=new rt,ee=ge.findOrCreate({account_id:Y,payment_mode:"card",region:Z,market_code:V.marketCode}),te=Sd(),ge.link(ee.journey_id,Y,{link_type:"search",link_id:te})}catch{ge=void 0,ee=void 0,te=void 0}let pe=await Du(t.dataDir,{region:Z,...V,paymentMode:"card",accountId:Y,journeyId:ee?.journey_id,searchId:te},()=>P.backend.searchRides({locations:[{latitude:w,longitude:v},{latitude:A,longitude:C}],paymentItemUuid:W,...m?{couponCode:m}:{}}));ee&&te&&pe&&typeof pe=="object"?S({...pe,journey_id:ee.journey_id,search_id:te}):S(pe)}catch(Y){b(sA(Y)??{error:Y.message}),process.exit(1)}return}let[s,i,a,o,c,l]=e;(!s||!i||!a||!o||!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] [--coupon-code CODE]"),console.error("hint: region: SG (Singapore), NY (New York)"),process.exit(1)),X(s),Ee(s),le(t.appServerUrl),be(t.gatewayServerUrl);try{let u=Je(s),d=es(i),m,f;try{m=new rt,f=m.findOrCreate({account_id:u,payment_mode:"wallet_usdc",region:ts(i),market_code:d.marketCode})}catch{}let g=Sd(),h,E,T,w=await Du(t.dataDir,{region:ts(i),...d,paymentMode:"wallet_usdc",accountId:u,journeyId:f?.journey_id,searchId:g},async()=>{T=await No({wallet_address:s,region:i,locations:[{latitude:parseFloat(a),longitude:parseFloat(o)},{latitude:parseFloat(c),longitude:parseFloat(l)}],payCurrency:t.payCurrency}),E=T.search_id;let v=xo(E);if(v)try{return Ao(g,v),h=g,{...T,search_id:h}}catch{}return T},()=>{let v=T?{...T,search_id:""}:void 0;if(!f||!m||!h)return{context:{journeyId:void 0,searchId:void 0},result:v};try{m.link(f.journey_id,u,{link_type:"search",link_id:h,backend_id:E});return}catch{return f=void 0,{context:{journeyId:void 0,searchId:void 0},result:v}}});f&&h?S({...w,search_id:h,journey_id:f.journey_id}):h?S({...w,search_id:h}):E?S({...w,search_id:E}):S(w)}catch(u){b({error:u.message}),process.exit(1)}},c1=async e=>{let t=O();if(N(t.dataDir),Qe().mode==="tada"){let l=e[0];l||(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(l)}catch{b({error:"INVALID_JSON",message:"Failed to parse json_params argument."}),process.exit(1);return}let d=u.locations,m=u.payment_item_uuid,f=u.product_id,g=u.search_id,h=u.coupon_code,E=u.confirmed_price;if(!d||d.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(h!==void 0&&(typeof h!="string"||h.length===0)){b({error:"INVALID_ARGUMENT",message:"coupon_code must be a non-empty case-sensitive string."}),process.exit(1);return}if(h!==void 0&&f==null){b({error:"INVALID_ARGUMENT",message:"product_id is required with coupon_code."}),process.exit(1);return}let T=typeof E=="string"?E.trim():void 0;if(h!==void 0&&(!T||!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(T))){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(h===void 0&&E!==void 0){b({error:"INVALID_ARGUMENT",message:"confirmed_price may be used only with coupon_code."}),process.exit(1);return}let w;try{w=await an(t)}catch(ge){b({error:"RIDE_REQUEST_FAILED",message:ge.message}),process.exit(1);return}let v=Yo(d);if(v==null){b({error:"INVALID_COORDINATES",message:"Every entry in locations needs numeric coordinates (latitude/longitude, or lat/lng)."}),process.exit(1);return}let A=v[0],C=nt(_t(A.latitude,A.longitude),t.cliGatewayHosts,t.cliGatewayHost),P=await nn(w.backend,m,C);if(P==null)return;let L=w.identity?vr(w.identity):void 0,W=_t(A.latitude,A.longitude),Z=di(A.latitude,A.longitude),V=L?new rt:void 0,Y;if(V&&g)try{Y=V.resolveSearchForBooking(g,L,{payment_mode:"card",region:W,market_code:Z.marketCode}).journey}catch{}try{let ge=Y,ee=await Ou(t.dataDir,{region:W,...Z,paymentMode:"card",accountId:L,journeyId:Y?.journey_id,searchId:Y?g:void 0},()=>w.backend.bookRide({locations:v,paymentItemUuid:P,...f!=null?{productId:f}:{},...typeof h=="string"?{couponCode:h}:{},...T?{confirmedPrice:T}:{}}),St=>{if(!(!Y||!V))try{V.linkRequestAndRide(Y.journey_id,L,St.rideId,St.rideId);return}catch{return ge=void 0,{context:{journeyId:void 0,searchId:void 0}}}});await gr(ee.rideId);let{rideStatus:te,...pe}=ee;ge?S({...pe,journey_id:ge.journey_id}):S(pe)}catch(ge){b(sA(ge)??{error:"RIDE_REQUEST_FAILED",message:ge.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(X(a),Ee(a),o&&!AR(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),be(t.gatewayServerUrl);let c;try{let l=Je(a),u=new rt,d,m,f=i.search_id,g=es(i.region),h=ts(i.region);try{let w=u.resolveSearchForBooking(f,l,{payment_mode:"wallet_usdc",region:h,market_code:g.marketCode});d=w.journey,m=w.backend_id??void 0}catch{}c={accountId:l,journey:d,region:h,marketCode:g.marketCode};let E=d,T=await Ou(t.dataDir,{region:h,...g,paymentMode:"wallet_usdc",accountId:l,journeyId:d?.journey_id,searchId:d?f:void 0},()=>Po({...i,search_id:m??f},t),w=>{if(d)try{u.link(d.journey_id,l,{link_type:"request",link_id:w.request_id});return}catch{return E=void 0,{context:{journeyId:void 0,searchId:void 0}}}});await gr(T.request_id),E?S({...T,journey_id:E.journey_id}):S(T)}catch(l){let u=l.message??"";if(Cu(l)){let d=Sd();if(c)try{let m=c.journey??new rt().findOrCreate({account_id:c.accountId,payment_mode:"wallet_usdc",region:c.region,market_code:c.marketCode}),g=await Hn(t.dataDir)?.recordRequired({accountId:c.accountId,journeyId:m.journey_id,region:c.region,paymentMode:"wallet_usdc",marketCode:c.marketCode});g&&(d=g.attemptId)}catch{}b({error:"INSUFFICIENT_DEPOSIT",message:u,deposit_attempt_id:d,action:`Run \`amb deposit-status\` to identify the network, then \`amb deposit-add <wallet> <network> <token> <amount> --deposit-attempt-id ${d}\`.`})}else b({error:"RIDE_REQUEST_FAILED",message:u,action:"Run `amb deposit-status` + `amb wallet-balance` to diagnose."});process.exit(1)}};function iA(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 aA(e,t,r,n){let s=await e.getCancelReasons(t),i;if(n==="member")try{i=await e.getCancelPenalty(t)}catch{}S({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 nA(e,t,r,n){return await aA(e,t,r,n),{kind:"done"}}async function l1(e,t,r,n,s,i,a){let o;try{o=await e.cancelRide(t,r,n)}catch(u){if(!(u instanceof Ge))throw u;if(u.status===409&&u.code==="ride_cancel_not_allowed"){let d=await e.getRideStatus(t),m=zo({status:d.status,mode:s,supportsReasons:i,hasReasonType:n!=null});return m.kind==="needs_reason"?nA(e,t,d.status,s):m.kind==="not_cancelable"?{kind:"not_cancelable",why:m.why,status:d.status}:{kind:"hold",status:d.status}}if(u.status===400&&u.code==="invalid_parameter"&&n!=null&&i){let d=await e.getRideStatus(t),m=zo({status:d.status,mode:s,supportsReasons:i,hasReasonType:!1});return m.kind==="not_cancelable"?{kind:"not_cancelable",why:m.why,status:d.status}:nA(e,t,d.status,s)}return{kind:"failed",message:u.message}}let c=o,l=s==="member"?c?.ride_status??"USER_CANCELED":c?.isFreeCancel===!1?"USER_CANCELED_NO_FREE":"USER_CANCELED";return S(o),{kind:"done",status:l,previousStatus:a}}async function oA(e,t,r){let{status:n,rideId:s}=r,i=r.previousStatus??t.status,a=!!s&&s!==t.ride_id,o=rn({rideId:t.request_id,kind:"ride_status",status:n});await Xo(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)}),Jn(t.request_id,n)}var u1=async e=>{let{positional:t,reasonType:r}=iA(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=O();N(s.dataDir),await gr(n);let i=Oe(n);if(i?.status?.startsWith("EXPIRED")&&(S({already_expired:!0,status:i.status,message:"Ride has already expired. No active ride to cancel."}),process.exit(0)),i){let u=i.wallet_address?"crypto":"member",d=u==="crypto"?t[2]:t[1],m=u==="member",f;try{let{backend:g}=await yt(s,i),h=await g.getRideStatus(n),E=zo({status:h.status,mode:u,supportsReasons:m,hasReasonType:r!=null});E.kind==="not_cancelable"?f={kind:"not_cancelable",why:E.why,status:h.status}:E.kind==="needs_reason"?(await aA(g,n,h.status,u),f={kind:"done"}):f=await l1(g,n,d,r,u,m,h.status)}catch(g){f={kind:"failed",message:g.message}}if(f.kind==="done"){f.status&&await oA(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}X(c),Ee(c),le(s.appServerUrl),be(s.gatewayServerUrl);let l=ce(c);if(!l){b({error:"JWT_NOT_FOUND",message:"No valid JWT. Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1);return}try{let u=await vo(l,n,o,r);Jn(n,u.isFreeCancel===!1?"USER_CANCELED_NO_FREE":"USER_CANCELED"),S(u)}catch(u){b({error:"RIDE_CANCEL_FAILED",message:u.message}),process.exit(1)}},d1=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=O();N(n.dataDir),await gr(t);let s=Oe(t);if(s){try{let{backend:o}=await yt(n,s),c=await o.getRideStatus(t);S(c),await oA(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}X(i),Ee(i),le(n.appServerUrl),be(n.gatewayServerUrl);let a=ce(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 ri(a,t);Jn(t,o.status),S(o)}catch(o){b({error:"RIDE_STATUS_FAILED",message:o.message}),process.exit(1)}},p1=async e=>{let{positional:t,reasonType:r}=iA(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=O();N(s.dataDir);let i=Oe(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 yt(s,i),o=await a.getCancelPenalty(n,r);S(o)}catch(a){a instanceof Nr?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)}},m1=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=O();N(s.dataDir);let i=Oe(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 yt(s,i),o=await a.getShareLink(n,t);S(o)}catch(a){if(a instanceof Zn){b({error:a.code,message:a.message}),process.exit(1);return}b({error:"SHARE_LINK_FAILED",message:a.message}),process.exit(1)}},f1=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=O();N(s.dataDir),X(t),Ee(t),Ir(s.gatewayServerUrl);let i=ce(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 iw(i,n);S(a)}catch(a){b({error:"RIDE_HISTORY_FAILED",message:a.message}),process.exit(1)}};function g1(e,t){let r=Oe(t);return r?.region?nt(Pt(r.region),e.cliGatewayHosts,e.cliGatewayHost):e.cliGatewayHost}function h1(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(Cw(e))}var _1=async e=>{let t=e.filter(c=>c.startsWith("--format"));if(t.length>1||t[0]&&t[0]!=="--format=markdown"||ms()==="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=O();N(s.dataDir);let i=Oe(n);if(!i){b({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${n}.`}),process.exit(1);return}let a=fw(),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 yt(s,i);h1(await c.getReceipt(n))}catch(c){b({error:"RIDE_RECEIPT_FAILED",message:c.message}),process.exit(1)}},y1=async e=>{if(Qe().mode==="tada"){let[a]=e;if(!a){console.error("error: Usage: amb ride-history-detail <request_id>"),process.exit(1);return}let o=O();N(o.dataDir);let c;try{c=await Zt(o)}catch(l){b({error:"MEMBER_SESSION_EXPIRED",message:l.message}),process.exit(1);return}try{let l=await oi(g1(o,a),c,a);S(l)}catch(l){b({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=O();N(s.dataDir),X(r),Ee(r),Ir(s.gatewayServerUrl);let i=ce(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 ko(i,n);if(ms()==="plain"){let o=a.receiptInfo?.paidNetwork??null,c={...a},l=Wn(o,a.receiptInfo?.paidTxHash??null);if(l&&(c.receiptInfo={...a.receiptInfo,explorerUrl:l}),a.refundReceiptInfo){let d=Wn(a.refundReceiptInfo.refundNetwork??o,a.refundReceiptInfo.refundTxHash);c.refundReceiptInfo=d?{...a.refundReceiptInfo,explorerUrl:d}:a.refundReceiptInfo}let u=a.tipInfo?.tipRequest?.txHash??null;if(u){let d=Wn(a.tipInfo?.tipRequest?.network??null,u);d&&a.tipInfo&&(c.tipInfo={...a.tipInfo,tipRequest:{...a.tipInfo.tipRequest,explorerUrl:d}})}S(c)}else S(a)}catch(a){b({error:"RIDE_HISTORY_DETAIL_FAILED",message:a.message}),process.exit(1)}},cA={"ride-search":o1,"ride-request":c1,"ride-cancel":u1,"ride-status":d1,"ride-cancel-penalty":p1,"ride-share":m1,"ride-history":f1,"ride-history-detail":y1,"ride-receipt":_1};p();p();function E1(e){let t=De(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 lA(e){let{request_id:t,wallet_address:r,config:n}=e,s=E1(r),{accepts:i,nonce:a}=await PR(s,t),o=i[0],c=String(Math.floor(Date.now()/1e3)+o.maxTimeoutSeconds),l=parseInt(o.network.split(":")[1],10),u={domain:{name:o.extra.name,version:o.extra.version,chainId:l,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 Ho({rawTypedData:u,walletAddress:r,target:{rpcUrl:n.paymentRpcUrl,chainId:l}});return So(t,{accepts:i,nonce:a,walletAddress:r,validBefore:c,expiresAt:Date.now()+o.maxTimeoutSeconds*1e3,isSmartAccount:m}),{typed_data:d}}p();function T1(e){let t=De(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 uA(e){let{request_id:t,signature:r}=e,n=Kn(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,l=T1(a),u=s[0],d={x402Version:2,accepted:u,payload:{authorization:{from:a,to:u.payTo,value:u.amount,validAfter:"0",validBefore:o,nonce:i},signature:Go(r,c===!0)}},m=Buffer.from(JSON.stringify(d)).toString("base64"),f=await LR(l,t,m);return{success:f.success,tx_hash:f.transaction}}function dA(e,t){let r={},n;try{let a=Oe(e);if(n=a?.wallet_address??void 0,a?.wallet_address){let o=rs(a);o&&(r=o)}}catch{}let s=n??t,i=s?Je(s):void 0;return{...r,accountId:i,paymentMode:"wallet_usdc",requestId:e}}var b1=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=O();N(n.dataDir),X(r),Ee(r),le(n.appServerUrl),be(n.gatewayServerUrl);try{let s=await Vb(n.dataDir,dA(t,r),()=>lA({request_id:t,wallet_address:r,config:n}));S(s)}catch(s){b({error:s.message}),process.exit(1)}},v1=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=O();N(s.dataDir),le(s.appServerUrl),be(s.gatewayServerUrl);try{let i=Kn(t)?.walletAddress,a=await Hb(s.dataDir,dA(t,i),()=>uA({request_id:t,signature:r}));S(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)}},pA={"ride-pay-prepare":b1,"ride-pay-confirm":v1};p();async function mA(e,t){try{let r=Oe(t),n=r?rs(r):void 0;n&&await Bb(e,n)}catch{}}function R1(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 w1=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=O();N(r.dataDir);let n;try{n=await an(r)}catch(s){b({error:"TIP_CONFIG_FAILED",message:s.message}),process.exit(1);return}try{S(await n.backend.getTipConfig(t))}catch(s){b({error:"TIP_CONFIG_FAILED",message:s.message}),process.exit(1)}},A1=async e=>{let{positionals:t,currency:r,card:n}=R1(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=O();N(o.dataDir);let c=Oe(s);if(!c){b({error:"RIDE_NOT_FOUND",message:`No local record for ride_id: ${s}.`}),process.exit(1);return}let l;try{l=await yt(o,c)}catch(g){b({error:"TIP_FAILED",message:g.message}),process.exit(1);return}let{backend:u,mode:d}=l,m=r,f;if(d==="tada"){let g;try{g=await u.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 h=nt(Pt(c.region),o.cliGatewayHosts,o.cliGatewayHost),E=await nn(u,n,h);if(E==null)return;f=E}try{let g=await u.payTip(s,{amount:a,currency:m,paymentItemUuid:f});g.tipStatus?.toUpperCase()==="PAID"&&await mA(o.dataDir,s),S(g)}catch(g){if(g instanceof Ge)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 h=g.message??"";h.toLowerCase().includes("insufficient")||h.toLowerCase().includes("balance")?b({error:"INSUFFICIENT_BALANCE",message:h,action:"Run `amb wallet-balance` and top up your wallet."}):b({error:"TIP_FAILED",message:h})}process.exit(1)}},x1=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=O();N(i.dataDir),X(n),Ee(n),be(i.gatewayServerUrl),Ir(i.gatewayServerUrl);try{let a=await $o({request_id:t,price:s,wallet_address:n,config:i});S(a)}catch(a){b({error:"TIP_PREPARE_FAILED",message:a.message}),process.exit(1)}},S1=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=O();N(n.dataDir),Ir(n.gatewayServerUrl);try{let s=await Wo({request_id:t,signature:r});s.success&&await mA(n.dataDir,t),S(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)}},fA={"tip-config":w1,tip:A1,"tip-prepare":x1,"tip-confirm":S1};p();p();var hA=new Set(["maps.app.goo.gl","goo.gl"]),I1=new Set(["www.google.com","google.com","maps.google.com"]),gA=5;function Cr(e,t){let r=new Error(t?`${e}: ${t}`:e);throw r.code=e,r}async function D1(e){let t=e;for(let r=0;r<gA;r++){let n=new URL(t);if(!hA.has(n.host))return t;let s;try{s=await fetch(t,{redirect:"manual",method:"HEAD"})}catch(i){Cr("URL_RESOLVE_FAILED",i.message)}if(s.status>=300&&s.status<400){let i=s.headers.get("location");i||Cr("URL_RESOLVE_FAILED","redirect status without Location header"),t=new URL(i,t).toString();continue}Cr("URL_RESOLVE_FAILED",`unexpected status ${s.status} on short link`)}Cr("URL_RESOLVE_FAILED",`redirect chain exceeded ${gA}`)}function O1(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 N1(e){let t=e.match(/!3d(-?\d+(?:\.\d+)?)!4d(-?\d+(?:\.\d+)?)/);if(t)return{lat:parseFloat(t[1]),lng:parseFloat(t[2])}}function C1(e){let t=e.match(/\/@(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),/);if(t)return{lat:parseFloat(t[1]),lng:parseFloat(t[2])}}function P1(e){let t=e.match(/!1s(0x[0-9a-fA-F]+:0x[0-9a-fA-F]+)/);return t?t[1]:void 0}async function Id(e){let t;try{t=new URL(e)}catch{Cr("INVALID_URL","not a parseable URL")}if(hA.has(t.host)){let a=await D1(e);return Id(a)}I1.has(t.host)||Cr("INVALID_URL",`host ${t.host} not in allowlist`);let r=t.pathname,n=N1(r)??C1(r);n||Cr("COORDS_NOT_FOUND_IN_URL");let s=O1(r)??Cr("INVALID_URL","no /place/<name>/ segment"),i=P1(r);return{name:s,latitude:n.lat,longitude:n.lng,...i&&{ftid:i}}}p();var Dd="";function _A(e){Dd=e.replace(/\/$/,"")}function ns(e,t){let r=new Error(t?`${e}: ${t}`:e);throw r.code=e,r}async function yA(e,t){Dd||ns("RESOLVE_FAILED","initSavedPlacesApi not called");let r=await fetch(`${Dd}/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){ns("RESOLVE_FAILED",`malformed JSON response: ${n.message}`)}r.status===404&&ns("PLACE_NOT_FOUND"),r.status===422&&ns("REGION_UNSUPPORTED"),r.status===401&&ns("JWT_EXPIRED"),ns("RESOLVE_FAILED",`status ${r.status}`)}p();function L1(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 M1(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 EA(e){let t=L1(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(M1(c)===t)return c}catch{}return null}catch{return null}}p();function TA(e,t,r){return Dr("/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 bA(e,t,r,n){return Dr(`/v1/places/${encodeURIComponent(t)}`,e,{query:{region:r.region,city:r.city},lang:n})}function vA(e,t,r){return Dr("/v1/places/nearby",e,{query:{latitude:t.latitude,longitude:t.longitude,limit:t.limit},lang:r})}function RA(e,t,r){return Dr("/v1/places/airports",e,{query:{city:t.city},lang:r})}function wA(e,t,r){return Dr("/v1/places/reverse-geocode",e,{query:{latitude:t.latitude,longitude:t.longitude,region:t.region},lang:r})}function pi(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 mi(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 Od(e){b({error:"NOT_SUPPORTED",message:`tada ${e} is only available for TADA/Throo members. Run 'amb login' first.`}),process.exit(1)}var k1=async e=>{if(Qe().mode==="tada"){let{positional:d,city:m,sessionToken:f,lang:g}=pi(e),[h,E,T,w]=d;(!h||!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!=(w!==void 0)&&(b({error:"INVALID_COORDINATES",message:"originLat and originLng must be provided together."}),process.exit(1));let v=T!==void 0?parseFloat(T):void 0,A=w!==void 0?parseFloat(w):void 0;(v!==void 0&&isNaN(v)||A!==void 0&&isNaN(A))&&(b({error:"INVALID_COORDINATES",message:"originLat and originLng must be valid numbers."}),process.exit(1));let C=O();N(C.dataDir),Qn(Xe(C.cliGatewayHosts,C.cliGatewayHost));let P;try{P=await Zt(C)}catch(L){b({error:"MEMBER_AUTH_FAILED",message:L.message}),process.exit(1);return}try{let L=await TA(P,{query:h,region:E,city:m,originLat:v,originLng:A,sessionToken:f},g);S({...L,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(L){b({error:"PLACE_SEARCH_FAILED",message:mi(L)}),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=ti(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 l=O();N(l.dataDir),X(t),Ee(t),le(l.appServerUrl),be(l.gatewayServerUrl);let u=ce(t);u||(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 MR(u,n,a,o,c);d.length===0?S({results:[],next_action:"REPORT_NO_MATCHES_TO_USER"}):S({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)}},U1=async e=>{if(Qe().mode==="tada"){let{positional:o,city:c,lang:l}=pi(e),[u,d,m]=o,f=c??m;(!u||!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=O();N(g.dataDir),Qn(Xe(g.cliGatewayHosts,g.cliGatewayHost));let h;try{h=await Zt(g)}catch(E){b({error:"MEMBER_AUTH_FAILED",message:E.message}),process.exit(1);return}try{let E=await bA(h,u,{region:d,city:f},l);S(E)}catch(E){b({error:"PLACE_DETAIL_FAILED",message:mi(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=ti(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=O();N(i.dataDir),X(t),Ee(t),le(i.appServerUrl),be(i.gatewayServerUrl);let a=ce(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 kR(a,n,s);S(o)}catch(o){b({error:"PLACE_DETAIL_FAILED",message:o.message}),process.exit(1)}},F1=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=O();N(i.dataDir),X(t),Ee(t),_A(i.gatewayServerUrl);let a=ce(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 Id(r)}catch(g){let h=g.code??"INVALID_URL";console.error(JSON.stringify({error:h,message:g.message})),process.exit(1)}let c=await EA(o.ftid),l;try{l=await yA(a,{name:o.name,latitude:o.latitude,longitude:o.longitude,...o.ftid&&{ftid:o.ftid},...c&&{resolvedPlaceId:c}})}catch(g){let h=g.code??"RESOLVE_FAILED";console.error(JSON.stringify({error:h,message:g.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 u=Yn({placeId:l.googlePlaceId,latitude:l.location.latitude,longitude:l.location.longitude}),d,m=!1,f={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:o.ftid??null,kg_id:null,source_url:r};u?fd(t,u)?(d=gd(t,u,{...n!==void 0&&{label:n},source_url:r,google_place_id:l.googlePlaceId,ftid:o.ftid??null,kg_id:null,formatted_address:l.formattedAddress,name:l.name,city:l.city,region:l.region}),m=!0):d=pd(f):d=pd(f),console.log(JSON.stringify({...d,was_promoted:m},null,2))},q1=async e=>{let t=e[0],r=[],n=!1,s=!1,i;for(let u=1;u<e.length;u++){let d=e[u];if(d==="--match"&&e[u+1]!=null)r.push(e[u+1]),u++;else if(d==="--favorites-only")n=!0;else if(d==="--history-only")s=!0;else if(d==="--limit"&&e[u+1]!=null){let m=e[u+1],f=parseInt(m,10);(!/^\d+$/.test(m)||f<=0)&&(console.log(JSON.stringify({error:"INVALID_LIMIT",value:m})),process.exit(1)),i=f,u++}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=O();N(o.dataDir),X(t);let c={favoritesOnly:n,historyOnly:s,limit:a},l;r.length===0?l={matches:md(t,c),matched_tier:null,normalized_queries:[]}:l=$R(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))},j1=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=O();N(n.dataDir),X(t);let s=/^\d+$/.test(r)?parseInt(r,10):null,i=s!=null?WR(t,s):JR(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}))},B1=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=O();N(s.dataDir),X(t);let i=/^\d+$/.test(r)?parseInt(r,10):null,a;i!=null?a=ni(t,i):a=fd(t,r),a||(console.log(JSON.stringify({error:"NOT_FOUND"})),process.exit(1));let o=a.is_favorite===1,c=i!=null?YR(t,i,n):gd(t,r,{...n!==void 0&&{label:n}});console.log(JSON.stringify({...c,was_favorite_before:o},null,2))},V1=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=O();N(n.dataDir),X(t);let s=/^\d+$/.test(r)?parseInt(r,10):null,i;if(s!=null?i=ni(t,s):i=zR(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?XR(t,s):QR(t,r);console.log(JSON.stringify({...a,was_favorite_before:!0},null,2))},H1=async e=>{Qe().mode!=="tada"&&Od("place-nearby");let{positional:t,lang:r}=pi(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 l=O();N(l.dataDir),Qn(Xe(l.cliGatewayHosts,l.cliGatewayHost));let u;try{u=await Zt(l)}catch(d){b({error:"MEMBER_AUTH_FAILED",message:d.message}),process.exit(1);return}try{S(await vA(u,{latitude:a,longitude:o,limit:c},r))}catch(d){b({error:"PLACE_NEARBY_FAILED",message:mi(d)}),process.exit(1)}},G1=async e=>{Qe().mode!=="tada"&&Od("place-airports");let{positional:t,lang:r}=pi(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=O();N(s.dataDir),Qn(Xe(s.cliGatewayHosts,s.cliGatewayHost));let i;try{i=await Zt(s)}catch(a){b({error:"MEMBER_AUTH_FAILED",message:a.message}),process.exit(1);return}try{S(await RA(i,{city:n},r))}catch(a){b({error:"PLACE_AIRPORTS_FAILED",message:mi(a)}),process.exit(1)}},$1=async e=>{Qe().mode!=="tada"&&Od("place-reverse-geocode");let{positional:t,lang:r}=pi(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=O();N(c.dataDir),Qn(Xe(c.cliGatewayHosts,c.cliGatewayHost));let l;try{l=await Zt(c)}catch(u){b({error:"MEMBER_AUTH_FAILED",message:u.message}),process.exit(1);return}try{S(await wA(l,{latitude:a,longitude:o,region:i},r))}catch(u){b({error:"PLACE_REVERSE_GEOCODE_FAILED",message:mi(u)}),process.exit(1)}},AA={"place-search":k1,"place-detail":U1,"place-save":F1,"place-list":q1,"place-remove":j1,"place-favorite":B1,"place-unfavorite":V1,"place-nearby":H1,"place-airports":G1,"place-reverse-geocode":$1};p();import{readFileSync as W1}from"fs";p();async function Nd(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(u){process.stderr.write(`map-session-check poll_error: ${u.message}
|
|
791
|
+
`)}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()>=a)return{status:"pending",auth_url:i};await new Promise(u=>setTimeout(u,n))}}function SA(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 Cd(e){try{let t=JSON.parse(e);if(Array.isArray(t))return t;if(Array.isArray(t.subPlaces))return t.subPlaces}catch{}}function IA(e,t={}){let r=t.purpose?{...e,purpose:t.purpose}:e;if(ms()==="json"){S(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
792
|
`);return}if(e.status==="pending"){process.stderr.write(`\u23F3 Still waiting. Resume with: amb map-session-verify <session_id>
|
|
449
793
|
auth_url: ${e.auth_url}
|
|
450
794
|
`);return}process.stderr.write(`\u2717 Map session failed: ${e.reason}
|
|
451
|
-
`),process.exit(1)}var
|
|
795
|
+
`),process.exit(1)}var xA=async e=>{let{positional:t,subplacesJson:r,subplacesFile:n,purpose:s,noWait:i}=SA(e),a=t[0],o=t[1],c=t[2],l=t[3],u=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=ti(o);d||(b({error:"UNKNOWN_CITY",message:`Cannot resolve city: "${o}"`}),process.exit(1));let m=ei[d],f=c?parseFloat(c):void 0,g=l?parseFloat(l):void 0,h=O();N(h.dataDir),X(a),Ee(a);let E=ce(a);E||(b({error:"JWT_NOT_FOUND"}),process.exit(1)),be(h.gatewayServerUrl);let T;if(r)T=Cd(r);else if(n)try{let w=W1(n,"utf-8");T=Cd(w)}catch{}else if(!process.stdin.isTTY){let w=[];for await(let A of process.stdin)w.push(Buffer.from(A));let v=Buffer.concat(w).toString("utf-8").trim();v&&(T=Cd(v))}try{let w=await fetch(`${h.gatewayServerUrl}/v1/map-session`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E}`},body:JSON.stringify({initialLat:f,initialLng:g,initialName:u,city:d,region:m,subPlaces:T})});if(!w.ok){let L=await w.text();b({error:"MAP_SESSION_CREATE_FAILED",status:w.status,message:L}),process.exit(1)}let v=await w.json();if(v.mapUrl&&!v.mapUrl.startsWith("http")&&(v.mapUrl=`${h.webappUrl}${v.mapUrl}`),s&&(v.purpose=s),i){S(v);return}let{sessionId:A,mapUrl:C=""}=v;A||(b({error:"MAP_SESSION_INVALID_RESPONSE",message:"response missing sessionId"}),process.exit(1)),process.stderr.write(`Open this URL to pick a location:
|
|
452
796
|
${C}
|
|
453
797
|
|
|
454
798
|
Waiting (up to 5 minutes)\u2026
|
|
455
|
-
`);let
|
|
456
|
-
`)}catch(m){
|
|
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
|
-
`)
|
|
459
|
-
`)
|
|
460
|
-
`,
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
`),
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
`))
|
|
467
|
-
`);if(
|
|
468
|
-
`)
|
|
469
|
-
|
|
470
|
-
`),
|
|
471
|
-
`),
|
|
472
|
-
`),
|
|
473
|
-
${
|
|
474
|
-
`)
|
|
475
|
-
|
|
476
|
-
|
|
799
|
+
`);let P=await Nd(h,A,{authUrl:C});IA(P,{purpose:s})}catch(w){b({error:"MAP_SESSION_CREATE_FAILED",message:w.message}),process.exit(1)}},J1=async e=>{let{positional:t,purpose:r}=SA(e),n=t[0];n||(console.error("error: Usage: map-session-verify <session_id> [--purpose origin|destination]"),process.exit(1));let s=O(),i=await Nd(s,n,{});IA(i,{purpose:r})},DA={"map-session-create":e=>xA(e.includes("--no-wait")?e:[...e,"--no-wait"]),"map-session":xA,"map-session-verify":J1};p();var K1=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=O();N(n.dataDir),X(t),Ee(t);let s=ce(t);le(n.appServerUrl),be(n.gatewayServerUrl);try{let i=await DR(s,r);i.status==="ALREADY_VERIFIED"&&To(t,r),S(i)}catch(i){b({error:i.message}),process.exit(1)}},Y1=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=O();N(s.dataDir),X(t),Ee(t);let i=ce(t);le(s.appServerUrl),be(s.gatewayServerUrl);try{let a=await OR(i,r,n);a.status==="ok"&&To(t,r),S({status:a.status})}catch(a){b({error:a.message}),process.exit(1)}},z1=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=O();N(n.dataDir),X(t),Ee(t);let s=ce(t);le(n.appServerUrl),be(n.gatewayServerUrl);try{let i=await IR(s,r);i.verified&&To(t,r),S(i)}catch(i){b({error:i.message}),process.exit(1)}},OA={"phone-verify-start":K1,"phone-verify-confirm":Y1,"phone-verify-check":z1};p();import ss from"fs";import CA from"path";p();var X1="Ambient Ride";function NA(e,t,r,n){return{domain:{name:X1,version:"1",chainId:t},types:{Login:[{name:"address",type:"address"},{name:"chainId",type:"uint256"},{name:"nonce",type:"string"},{name:"clientId",type:"string"}]},primaryType:"Login",message:{address:e,chainId:t,nonce:r,clientId:n}}}var Q1=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=O();N(n.dataDir),X(t),le(n.appServerUrl);try{let{message:s,expiresAt:i}=await Js(t,parseInt(r,10));ss.mkdirSync(n.dataDir,{recursive:!0});let a=`siwe-${t}-exp${i}.json`,o=CA.join(n.dataDir,a);ss.writeFileSync(o,JSON.stringify({message:s,walletAddress:t,expiresAt:i},null,2),{mode:384}),S({message:s,siwe_file:o,expires_at:new Date(i*1e3).toISOString()})}catch(s){b({error:s.message}),process.exit(1)}},Z1=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=O();N(n.dataDir),le(n.appServerUrl);try{let{message:s,expiresAt:i,walletAddress:a}=JSON.parse(ss.readFileSync(t,"utf8"));Date.now()/1e3>i&&(b({error:"SIWE message expired. Run `amb siwe-request-message` again."}),process.exit(1));let o=await to(s,r);a&&await Ft(n.dataDir,"activation_authenticated",{id:Je(a)}),S({access_token:o.accessToken,expires_in:o.expiresIn})}catch(s){b({error:s.message}),process.exit(1)}},eF=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb siwe-request-typed <wallet_address> <chain_id>"),console.error("hint: chain_id: 84532 (BASE_SEPOLIA), 11155111 (ETH_SEPOLIA)"),process.exit(1));let n=O();N(n.dataDir),X(t),le(n.appServerUrl);try{let s=parseInt(r,10),{expiresAt:i,nonce:a}=await Js(t,s),o=NA(t,s,a,_c);ss.mkdirSync(n.dataDir,{recursive:!0});let c=`typed-${t}-exp${i}.json`,l=CA.join(n.dataDir,c);ss.writeFileSync(l,JSON.stringify({typedData:o,nonce:a,walletAddress:t,chainId:s,expiresAt:i},null,2),{mode:384}),S({typed_file:l,nonce:a,expires_at:new Date(i*1e3).toISOString()})}catch(s){b({error:s.message}),process.exit(1)}},tF=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb typed-submit <typed_file> <signature>"),console.error("hint: typed_file is from `amb siwe-request-typed`; signature from `amb wallet-sign ... eth_signTypedData_v4`"),process.exit(1));let n=O();N(n.dataDir),le(n.appServerUrl);try{let{nonce:s,walletAddress:i,chainId:a,expiresAt:o}=JSON.parse(ss.readFileSync(t,"utf8"));Date.now()/1e3>o&&(b({error:"Typed-data nonce expired. Run `amb siwe-request-typed` again."}),process.exit(1));let c=await lv(i,a,s,r);await Ft(n.dataDir,"activation_authenticated",{id:Je(i)}),S({access_token:c.accessToken,expires_in:c.expiresIn})}catch(s){b({error:s.message}),process.exit(1)}},PA={"siwe-request-message":Q1,"siwe-submit":Z1,"siwe-request-typed":eF,"typed-submit":tF};p();import*as Pd from"fs";import*as MA from"path";import{io as nF}from"socket.io-client";p();import rF from"net";function LA(e,t,r={}){let n=r.connectTimeoutMs??1e3,s=r.responseTimeoutMs??jo;return new Promise(i=>{let a=!1,o=m=>{if(!a){a=!0;try{c.destroy()}catch{}clearTimeout(l),clearTimeout(u),i(m)}},c=rF.connect(e),l=setTimeout(()=>o({ok:!1,reason:"monitor_unreachable"}),n),u=setTimeout(()=>{},0);clearTimeout(u);let d="";c.on("connect",()=>{clearTimeout(l),u=setTimeout(()=>o({ok:!1,reason:"response_timeout"}),s);try{c.write(JSON.stringify({content:t})+`
|
|
800
|
+
`)}catch(m){o({ok:!1,reason:`write_failed: ${m.message}`})}}),c.on("data",m=>{d+=m.toString();let f=d.indexOf(`
|
|
801
|
+
`);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 sF={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp"};function iF(e,t,r,n){let i=new URL(e.gatewayServerUrl).origin,a=nF(`${i}/chat`,{path:"/tada-ton/chat-socket",transports:["websocket"],auth:{token:r}});return new Promise(o=>{let c=!1,l,u;function d(f){c||(c=!0,clearTimeout(l),clearTimeout(u),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)=>{l=setTimeout(()=>g(new Error("join room timeout")),1e4),a.emit("JOIN_ROOM",{rideRequestId:t}),a.once("MESSAGE_SENT",h=>{if(clearTimeout(l),h.event!=="joined"){g(new Error(`unexpected join event: ${h.event}`));return}let E=h.roomId;u=setTimeout(()=>g(new Error("send message timeout")),1e4),a.emit("SEND_MESSAGE",{roomId:E,content:n,type:"TEXT"}),a.once("MESSAGE_SENT",()=>{clearTimeout(u),f()})})}).then(()=>{d({ok:!0})},f=>{m(f.message)})})}var aF=async e=>{let[t,r]=e;(!t||!r)&&(console.error("error: Usage: amb chat-send-message <request_id> <content>"),process.exit(1));let n=O();N(n.dataDir);let s=Oe(t);if(s||(b({error:"ride request not found",request_id:t}),process.exit(1)),!s.wallet_address){let l;try{({backend:l}=await yt(n,s))}catch(u){b({error:"AUTH_FAILED",message:u.message,request_id:t}),process.exit(1)}try{let u=await l.sendChat(t,{message:r});S(u)}catch(u){let d=u instanceof Ge?u.code:"CHAT_SEND_FAILED";b({error:d,message:u.message,request_id:t}),process.exit(1)}return}let i=s.wallet_address;X(i),Ee(i);let a=ce(i);a||(b({error:"JWT_NOT_FOUND",message:"Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1)),gr(t);let o=await LA(Bo(ye(),t),r);if(o.ok){S({success:!0,via:"monitor"});return}let c=await iF(n,t,a,r);if(c.ok){S({success:!0,via:"fallback"});return}b({error:"CHAT_SEND_FAILED",primary:o.reason,fallback:c.reason}),process.exit(1)},oF=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=MA.extname(r).toLowerCase(),s=sF[n];s||(b({error:"UNSUPPORTED_FORMAT",message:`Unsupported image format: "${n}". Supported: jpeg, jpg, png, gif, webp`}),process.exit(1));let i=O();N(i.dataDir);let a=Oe(t);if(a||(b({error:"RIDE_NOT_FOUND",message:`No local record for request_id: ${t}`}),process.exit(1)),!a.wallet_address){let u;try{u=Pd.readFileSync(r)}catch(m){b({error:"FILE_READ_FAILED",message:m.message}),process.exit(1)}let d;try{({backend:d}=await yt(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:u,mimetype:s}});S(m)}catch(m){let f=m instanceof Ge?m.code:"CHAT_SEND_FAILED";b({error:f,message:m.message,request_id:t}),process.exit(1)}return}let o=a.wallet_address;X(o),Ee(o),be(i.gatewayServerUrl);let c=ce(o),l;try{l=Pd.readFileSync(r)}catch(u){b({error:"FILE_READ_FAILED",message:u.message}),process.exit(1)}try{let u=await wo(c,t,l,s);S(u)}catch(u){b({error:"CHAT_SEND_IMAGE_FAILED",message:u.message}),process.exit(1)}},cF=async e=>{let[t,r]=e;t||(console.error("error: Usage: amb chat-get-messages <request_id> [cursor]"),process.exit(1));let n=O();N(n.dataDir);let s=Oe(t);if(s||(b({error:"ride request not found",request_id:t}),process.exit(1)),!s.wallet_address){let o;try{({backend:o}=await yt(n,s))}catch(c){b({error:"AUTH_FAILED",message:c.message,request_id:t}),process.exit(1)}try{S(await o.getMessages(t,r?Number(r):void 0))}catch(c){let l=c instanceof Ge?c.code:"CHAT_GET_FAILED";b({error:l,message:c.message,request_id:t}),process.exit(1)}return}let i=s.wallet_address;X(i),Ee(i),be(n.gatewayServerUrl);let a=ce(i);a||(b({error:"JWT_NOT_FOUND",message:"Run `amb siwe-request-message` + `amb siwe-submit` first."}),process.exit(1));try{let o=await Ro(t,a,r);S(o)}catch(o){b({error:"CHAT_GET_FAILED",message:o.message}),process.exit(1)}},kA={"chat-send-message":aF,"chat-send-image":oF,"chat-get-messages":cF};p();import*as $ from"fs";import*as fe from"path";import*as nc from"os";import*as ux from"crypto";import{spawnSync as PF}from"child_process";import LF from"better-sqlite3";p();import Bd from"crypto";import q from"fs";import B from"path";p();function UA(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 lF={fresh:["initialize_ambient"],legacy_candidate:["migrate_legacy"],ambient_fresh:["use_ambient"],already_migrated:["validate_migrated"],resume_before_backup:["resume_backup"]};function FA(e,t){if(t==="conflict")throw new Error("MIGRATION_CONFLICT: filesystem state is not safe to migrate");return{state:t,paths:{...e},actions:[...lF[t]]}}p();var jA={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"},qA=new Set(Object.values(jA)),uF=/^(?:TADA_AGENT_|TADA_OPENCLAW_)/,dF=/^TADA_AGENT_DEPOSIT_RPC_URL_([A-Z0-9]+(?:_[A-Z0-9]+)*)$/,pF=/^TADA_AGENT_BRIDGE_RPC_URL_([A-Z0-9]+(?:_[A-Z0-9]+)*)$/,mF=/^[A-Z0-9]+(?:_[A-Z0-9]+)*$/;function Pr(e,t){throw new Error(`${e}: ${t}`)}function fi(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&&Pr("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)||Pr("INVALID_ENV_KEY",`source=${e.name} line=${r+1}`),Object.hasOwn(t,a)&&Pr("DUPLICATE_ENV_KEY",`source=${e.name} key=${a}`),t[a]=o}return t}function fF(e){let t=Array.isArray(e)?e:[{name:"input",env:e}],r=[],n=new Map;for(let s of t){let i=fi(s);for(let[a,o]of Object.entries(i)){if(o===void 0)continue;let c=n.get(a);if(c&&c.value!==o&&Pr("ENV_SOURCE_CONFLICT",`key=${a} sources=${c.source},${s.name}`),!c){let l={key:a,value:o,source:s.name};n.set(a,l),r.push(l)}}}return r}function gF(e,t){let r=dF.exec(e);if(r)return r[1];let n=pF.exec(e);if(n)return n[1];if(e==="TADA_AGENT_PAYMENT_RPC_URL")return t}function on(e,t){if(!mF.test(t))throw new Error(`INVALID_PAYMENT_NETWORK: network=${t}`);let r=fF(e),n={},s=new Map,i=new Map,a=[],o=[],c=(l,u)=>{let d=s.get(u);d&&d.value!==l.value&&Pr("ENV_TARGET_CONFLICT",`target=${u} keys=${d.key},${l.key} sources=${d.source},${l.source}`),d||(s.set(u,l),n[u]=l.value),o.push({from:l.key,to:u})};for(let l of r){let u=jA[l.key];if(u){c(l,u);continue}let d=gF(l.key,t);if(d){let m=i.get(d)??[];m.push(l),i.set(d,m);continue}if(qA.has(l.key)||/^AMB_RIDE_RPC_URL_/.test(l.key)){!qA.has(l.key)&&!/^AMB_RIDE_RPC_URL_[A-Z0-9]+(?:_[A-Z0-9]+)*$/.test(l.key)&&Pr("UNKNOWN_AMBIENT_ENV_KEY",`key=${l.key} source=${l.source}`),c(l,l.key);continue}l.key.startsWith("AMB_RIDE_")&&Pr("UNKNOWN_AMBIENT_ENV_KEY",`key=${l.key} source=${l.source}`),uF.test(l.key)&&a.push(l.key)}for(let[l,u]of i){new Set(u.map(f=>f.value)).size>1&&Pr("RPC_CONFIG_CONFLICT",`network=${l} keys=${u.map(f=>f.key).join(",")} sources=${u.map(f=>f.source).join(",")}`);let m=`AMB_RIDE_RPC_URL_${l}`;for(let f of u)c(f,m)}return{env:n,droppedLegacyConfig:[...new Set(a)].sort(),mappedLegacyConfig:o}}p();import cn from"fs";import hr from"path";import hF from"better-sqlite3";var GA=["identity","wallets","privy_wallet_meta","pending_sessions","jwt_cache","ride_requests","tada_members","places","bridge_jobs","mvl_relay_submissions","member_login_sessions"];function qe(e,t){throw new Error(t?`${e}: ${t}`:e)}function BA(e){try{return new hF(e,{readonly:!0,fileMustExist:!0})}catch(t){return qe("SQLITE_OPEN_FAILED",String(t))}}function Ld(e,t){return!!e.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(t)}function VA(e){return Object.fromEntries(GA.map(t=>{if(!Ld(e,t))return[t,"absent"];let r=e.prepare(`SELECT COUNT(*) AS count FROM ${t}`).get();return[t,r.count]}))}function _F(e){let t=[];if(Ld(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(Ld(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 HA(e){let t;try{t=e.pragma("integrity_check")}catch(r){qe("SQLITE_INTEGRITY_FAILED",String(r))}(t.length!==1||t[0]?.integrity_check!=="ok")&&qe("SQLITE_INTEGRITY_FAILED",t.map(r=>r.integrity_check).join("; "))}function yF(e,t){for(let r of GA)e[r]!==t[r]&&qe("ROW_COUNT_MISMATCH",`${r}: source=${e[r]} staged=${t[r]}`)}function Md(e){let t=hr.resolve(e.dataDir),r=hr.resolve(e.keysDir),n=hr.resolve(e.dbPath);for(let[o,c]of[["DATA_DIR",t],["KEYS_DIR",r]]){let l;try{l=cn.lstatSync(c)}catch{qe(`MISSING_${o}`)}(!l.isDirectory()||l.isSymbolicLink())&&qe(`INVALID_${o}`)}hr.dirname(n)!==t&&qe("DB_OUTSIDE_DATA_DIR"),cn.existsSync(n)||qe("MISSING_DATABASE");let s=cn.lstatSync(n);(!s.isFile()||s.isSymbolicLink())&&qe("INVALID_DATABASE_FILE");let i;if(e.sourceDbPath){let o=hr.resolve(e.sourceDbPath);o===n&&qe("SOURCE_EQUALS_STAGED");let c=BA(o);try{HA(c),i=VA(c)}finally{c.close()}}try{Up(n)}catch(o){let c=String(o);c.includes("KEY_PATH_COLLISION")&&qe("KEY_PATH_COLLISION",c),/malformed|not a database|database disk image/i.test(c)&&qe("SQLITE_INTEGRITY_FAILED",c),qe("KEY_PATH_NORMALIZATION_FAILED",c)}let a=BA(n);try{HA(a);let o=VA(a);i&&yF(i,o);let c=_F(a),l=0;for(let u of c){let d=at(r,u.storedPath),m=hr.relative(r,d);(m.startsWith("..")||hr.isAbsolute(m))&&qe("KEY_OUTSIDE_KEYS_DIR",`${u.table}:${u.id}`);let f;try{f=cn.lstatSync(d)}catch{qe("MISSING_KEY_FILE",`${u.table}:${u.id}`)}(!f.isFile()||f.isSymbolicLink())&&qe("INVALID_KEY_FILE",`${u.table}:${u.id}`);let g=cn.realpathSync(d),h=cn.realpathSync(r),E=hr.relative(h,g);(E.startsWith("..")||hr.isAbsolute(E))&&qe("KEY_OUTSIDE_KEYS_DIR",`${u.table}:${u.id}`);let T;try{T=Wt(cn.readFileSync(d),Buffer.from(e.passphrase,"utf8")),Hi(T.toString("utf8"))!==u.publicKey&&qe("KEY_PUBLIC_MISMATCH",`${u.table}:${u.id}`)}catch(w){if(String(w).includes("KEY_PUBLIC_MISMATCH"))throw w;qe("KEY_DECRYPT_FAILED",`${u.table}:${u.id}`)}finally{T&&vt(T)}l++}return{sqliteIntegrity:"ok",criticalRowCounts:o,referencedKeys:c.length,openedKeys:l}}finally{a.close()}}var ec=".amb-migration-provenance.json",Fd=".amb-migration-attempt",WA=".amb-migration-report.json",kd=".env.legacy",is=384;function Zo(e){return`${e.stagingRoot}.owner`}function he(e,t){return new Error(t?`${e}: ${t}`:e)}function EF(e){let t=Object.fromEntries(Object.entries(e).map(([r,n])=>[r,B.resolve(n)]));if(new Set(Object.values(t)).size!==Object.keys(t).length)throw he("MIGRATION_CONFLICT","migration paths must be distinct");if(B.dirname(t.stagingRoot)!==B.dirname(t.ambientRoot))throw he("MIGRATION_CONFLICT","staging must be an Ambient sibling");if(B.dirname(t.backupRoot)!==B.dirname(t.legacyRoot))throw he("MIGRATION_CONFLICT","backup must be a legacy sibling");for(let r of[t.legacyRoot,t.ambientRoot,t.stagingRoot,t.backupRoot]){let n=B.relative(r,t.lockPath);if(n===""||!n.startsWith("..")&&!B.isAbsolute(n))throw he("MIGRATION_CONFLICT","lock must be outside state trees")}}function Ud(e,t,r){let n=e.lstat(t);if(!n.isDirectory()||n.isSymbolicLink())throw he(r)}function TF(e,t,r){let n=e.lstat(t);if(!n.isFile()||n.isSymbolicLink())throw he(r)}function JA(e){return`${JSON.stringify(e,null,2)}
|
|
802
|
+
`}function KA(e,t){let r=Bd.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(B.basename(s)),r.update(i),n+=i.length}return{size:n,sha256:r.digest("hex")}}function rc(e){return B.join(e.oldDataDir,"tada-ride-agent.db")}function er(e){return B.join(e.stagingRoot,"state","data")}function Qo(e){return B.join(e.stagingRoot,"state","keys")}function qd(e){return B.join(e.ambientRoot,"state","data")}function bF(e){return B.join(e.ambientRoot,"state","keys")}function Vd(e,t,r){try{return JSON.parse(e.readFile(t).toString("utf8"))}catch{throw he(r)}}function as(e,t,r){e.fsyncDirectory(B.dirname(t)),e.rename(t,r),e.fsyncDirectory(B.dirname(r))}function YA(e,t,r,n){if(e.exists(t))return;let s=`${t}.${n}.tmp`;e.writeFileExclusive(s,JA(r),is),e.fsyncFile(s),as(e,s,t),e.fsyncFile(t)}function vF(e,t){let r=B.join(er(e.paths),".env"),n=e.transformEnv??on,s=t.exists(r)?fi({name:"legacy-state",env:t.readFile(r).toString("utf8")}):{},i=n(s,e.paymentNetwork);if(t.exists(r)){let o=B.join(er(e.paths),kd);if(t.exists(o))throw he("MIGRATION_COLLISION");as(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(`
|
|
803
|
+
`)}${a.length?`
|
|
804
|
+
`:""}`,is),t.fsyncFile(r),t.exists(B.join(er(e.paths),kd))&&t.unlink(B.join(er(e.paths),kd)),t.fsyncDirectory(B.dirname(r)),i}function RF(e,t,r,n,s){let i=KA(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 zA(e,t,r){let n=B.join(t.ambientRoot,ec);if(!e.exists(n))throw he("MIGRATION_INTERRUPTED","missing provenance");let s=Vd(e,n,"MIGRATION_INTERRUPTED"),i=KA(e,r);if(s.schemaVersion!==1||s.sourcePath!==e.realpath(r)||s.sourceDbSize!==i.size||s.sourceDbSha256!==i.sha256)throw he("MIGRATION_INTERRUPTED","source provenance mismatch");return s}function XA(e,t,r){let n=B.join(t.ambientRoot,Fd);if(e.exists(n)){if(e.readFile(n).toString("utf8").trim()!==r)throw he("MIGRATION_INTERRUPTED","attempt provenance mismatch");e.unlink(n),e.fsyncDirectory(t.ambientRoot)}}function wF(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(B.dirname(e.managedLegacyLink)))}function tc(e,t){let r=B.join(t,"state","data"),n=B.join(r,"ambient-ride.db"),s=B.join(r,".env");for(let i of[n,`${n}-wal`,`${n}-shm`,s])e.exists(i)&&e.fsyncFile(i);for(let i of[r,B.join(t,"state","keys"),B.join(t,"state"),t])e.fsyncDirectory(i)}function jd(e,t){let r=e.validate??Md;try{return r({dataDir:B.join(t,"state","data"),keysDir:B.join(t,"state","keys"),dbPath:B.join(t,"state","data","ambient-ride.db"),sourceDbPath:rc(e),passphrase:QA(e,t)})}catch{throw he("MIGRATION_VALIDATION_FAILED")}}function QA(e,t){let r=B.join(t,"state","data",".env"),s=fi({name:"ambient-state",env:e.fs?.readFile(r).toString("utf8")??q.readFileSync(r,"utf8")}).AMB_RIDE_PASSPHRASE;if(!s)throw he("MIGRATION_VALIDATION_FAILED","missing passphrase");return s}function ZA(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 AF(e,t){let r=fi({name:"ambient-state",env:e.readFile(B.join(qd(t),".env")).toString("utf8")});return{env:Object.fromEntries(Object.entries(r).filter(n=>n[1]!==void 0)),droppedLegacyConfig:[],mappedLegacyConfig:[]}}function ex(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 tx(e,t){let r=Vd(e,B.join(t.ambientRoot,ec),"MIGRATION_INTERRUPTED");if(!Array.isArray(r.mappedLegacyConfig)||!Array.isArray(r.droppedLegacyConfig)||!ex(r.mappedLegacyConfig,r.droppedLegacyConfig))throw he("MIGRATION_INTERRUPTED","invalid provenance");return{...AF(e,t),mappedLegacyConfig:r.mappedLegacyConfig,droppedLegacyConfig:r.droppedLegacyConfig}}function rx(e,t,r,n,s,i){if(e.installManagedCli(),e.smoke(e.paths.ambientRoot),zA(t,e.paths,rc(e)),t.exists(e.paths.backupRoot))throw he("MIGRATION_BACKUP_EXISTS");wF(e,t),as(t,e.paths.legacyRoot,e.paths.backupRoot);let a=ZA(r,e,s,i);return YA(t,B.join(e.paths.ambientRoot,WA),a,n),a}function xF(e,t,r){Ud(t,e.paths.legacyRoot,"INVALID_LEGACY_ROOT"),Ud(t,e.oldDataDir,"INVALID_LEGACY_DATA_DIR"),Ud(t,e.oldKeysDir,"INVALID_LEGACY_KEYS_DIR");let n=rc(e);TF(t,n,"INVALID_LEGACY_DATABASE");let s=e.quiesceLegacy(),i=!1;try{t.writeFileExclusive(Zo(e.paths),`${r}
|
|
805
|
+
`,is),t.fsyncFile(Zo(e.paths)),t.fsyncDirectory(B.dirname(e.paths.stagingRoot)),i=!0,t.copyTreeExclusive(e.paths.legacyRoot,e.paths.stagingRoot,["cli"]),t.writeFileExclusive(B.join(e.paths.stagingRoot,Fd),`${r}
|
|
806
|
+
`,is),t.fsyncFile(B.join(e.paths.stagingRoot,Fd));let a=B.join(e.paths.stagingRoot,B.relative(e.paths.legacyRoot,e.oldDataDir)),o=B.join(e.paths.stagingRoot,B.relative(e.paths.legacyRoot,e.oldKeysDir));if(B.resolve(a)!==B.resolve(er(e.paths))){let g=B.join(e.paths.stagingRoot,"state");t.exists(g)||t.mkdirExclusive(g,448),t.exists(er(e.paths))&&t.removeOwnedPath(er(e.paths)),t.copyTreeExclusive(e.oldDataDir,er(e.paths))}if(B.resolve(o)!==B.resolve(Qo(e.paths))){let g=B.join(e.paths.stagingRoot,"state");t.exists(g)||t.mkdirExclusive(g,448),t.exists(Qo(e.paths))&&t.removeOwnedPath(Qo(e.paths)),t.copyTreeExclusive(e.oldKeysDir,Qo(e.paths))}let c=vF(e,t),l=B.join(er(e.paths),"tada-ride-agent.db"),u=B.join(er(e.paths),"ambient-ride.db");if(t.exists(u))throw he("MIGRATION_COLLISION");as(t,l,u);for(let g of["-wal","-shm","-journal"]){let h=`${l}${g}`,E=`${u}${g}`;if(t.exists(h)){if(t.exists(E))throw he("MIGRATION_COLLISION");as(t,h,E)}}let d=jd(e,e.paths.stagingRoot);tc(t,e.paths.stagingRoot);let m=RF(t,n,d,c,r);t.writeFileExclusive(B.join(e.paths.stagingRoot,ec),JA(m),is),t.fsyncFile(B.join(e.paths.stagingRoot,ec)),t.fsyncDirectory(e.paths.stagingRoot),as(t,e.paths.stagingRoot,e.paths.ambientRoot),i=!1,t.unlink(Zo(e.paths)),t.fsyncDirectory(B.dirname(e.paths.stagingRoot)),XA(t,e.paths,r);let f=jd(e,e.paths.ambientRoot);return tc(t,e.paths.ambientRoot),rx(e,t,"migrated",r,c,f)}catch(a){if(i)try{t.removeOwnedStaging(e.paths.stagingRoot,r)}catch{throw he("MIGRATION_INTERRUPTED","staging cleanup failed")}throw a}finally{s.release()}}function SF(e,t,r){let n=e.quiesceLegacy();try{let s=rc(e),i=zA(t,e.paths,s);XA(t,e.paths,i.attemptId);let a=jd(e,e.paths.ambientRoot);return tc(t,e.paths.ambientRoot),rx(e,t,"resumed",r,tx(t,e.paths),a)}finally{n.release()}}function IF(e,t){let r=Zo(t);if(!e.exists(r))return;let n=e.readFile(r).toString("utf8").trim();if(!n||n.includes(`
|
|
807
|
+
`))throw he("MIGRATION_CONFLICT","invalid staging owner");e.removeOwnedStaging(t.stagingRoot,n)}function DF(e,t,r){let n=B.join(e.paths.ambientRoot,WA),s;try{s=(e.validate??Md)({dataDir:qd(e.paths),keysDir:bF(e.paths),dbPath:B.join(qd(e.paths),"ambient-ride.db"),passphrase:QA(e,e.paths.ambientRoot)})}catch{throw he("MIGRATION_VALIDATION_FAILED")}tc(t,e.paths.ambientRoot);let i=tx(t,e.paths);if(t.exists(n)){let o=Vd(t,n,"MIGRATION_INTERRUPTED");if(o.schemaVersion!==1||!["migrated","resumed","already_migrated"].includes(o.status)||!Array.isArray(o.mappedLegacyConfig)||!Array.isArray(o.droppedLegacyConfig)||!ex(o.mappedLegacyConfig,o.droppedLegacyConfig))throw he("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=ZA("already_migrated",e,i,s);return YA(t,n,a,r),a}function nx(e){let t=e.fs??NF,r=e.attemptId??Bd.randomUUID();EF(e.paths);let n;try{n=t.acquireLock(e.paths.lockPath)}catch{throw he("MIGRATION_CONFLICT","migration lock is held")}try{try{IF(t,e.paths);let s=UA(e.paths,a=>t.exists(a));switch(FA(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 xF(e,t,r);case"resume_before_backup":return SF(e,t,r);case"already_migrated":return DF(e,t,r)}}catch(s){throw/\b(?:MIGRATION_|INVALID_|UNSAFE_|STAGING_)[A-Z_]+/.test(String(s))?s:he("MIGRATION_INTERRUPTED")}}finally{n.release()}}function sx(e,t,r=[]){let n=q.lstatSync(e);if(!n.isDirectory()||n.isSymbolicLink())throw he("UNSAFE_STATE_ENTRY");q.mkdirSync(t,{mode:n.mode&511,recursive:!1});try{for(let i of q.readdirSync(e)){if(r.includes(i))continue;let a=B.join(e,i),o=B.join(t,i),c=q.lstatSync(a);if(c.isSymbolicLink()||!c.isDirectory()&&!c.isFile())throw he("UNSAFE_STATE_ENTRY");if(c.isDirectory())sx(a,o);else{q.copyFileSync(a,o,q.constants.COPYFILE_EXCL),q.chmodSync(o,c.mode&511),q.chownSync(o,c.uid,c.gid);let l=q.openSync(o,"r");try{q.fsyncSync(l)}finally{q.closeSync(l)}}}q.chmodSync(t,n.mode&511),q.chownSync(t,n.uid,n.gid);let s=q.openSync(t,"r");try{q.fsyncSync(s)}finally{q.closeSync(s)}}catch(s){throw q.rmSync(t,{recursive:!0}),s}}function OF(e,t){let r=`${e}.owner`;if(!q.existsSync(r)||q.readFileSync(r,"utf8").trim()!==t)throw he("STAGING_NOT_OWNED");q.existsSync(e)&&q.rmSync(e,{recursive:!0}),q.unlinkSync(r);let n=q.openSync(B.dirname(e),"r");try{q.fsyncSync(n)}finally{q.closeSync(n)}}function $A(e){let t=q.openSync(e,"r");try{q.fsyncSync(t)}finally{q.closeSync(t)}}var NF={exists:q.existsSync,lstat:q.lstatSync,mkdirExclusive(e,t){q.mkdirSync(e,{mode:t,recursive:!1})},copyTreeExclusive:sx,removeOwnedPath(e){q.rmSync(e,{recursive:!0})},rename(e,t){if(q.existsSync(t))throw he("MIGRATION_COLLISION");q.renameSync(e,t)},removeOwnedStaging:OF,writeFileExclusive(e,t,r){q.writeFileSync(e,t,{flag:"wx",mode:r})},readFile:q.readFileSync,readlink:q.readlinkSync,realpath:q.realpathSync,unlink:q.unlinkSync,fsyncFile:$A,fsyncDirectory:$A,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&&q.existsSync(t))throw n();let c;try{return c=q.openSync(e,"wx",is),q.writeFileSync(c,`${process.pid}
|
|
808
|
+
${Bd.randomUUID()}
|
|
809
|
+
`,"utf8"),q.fsyncSync(c),{descriptor:c,identity:q.fstatSync(c)}}catch(l){if(c!==void 0){try{let u=q.lstatSync(e),d=q.fstatSync(c);r(u,d)&&q.unlinkSync(e)}catch{}q.closeSync(c)}throw l}},i;try{i=s()}catch(o){if(o.code!=="EEXIST"||q.existsSync(t))throw o;let c,l;try{c=q.openSync(e,"r"),l=q.fstatSync(c);let d=Number(q.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&&q.closeSync(c)}try{q.linkSync(e,t)}catch{throw o}let u=q.lstatSync(t);try{let d=q.lstatSync(e);if(l===void 0||!r(l,u)||!r(d,u))throw o;q.unlinkSync(e),i=s(!0)}finally{try{let d=q.lstatSync(t);r(d,u)&&q.unlinkSync(t)}catch{}}}let a=!1;return{release(){if(!a){a=!0,q.closeSync(i.descriptor);try{let o=q.lstatSync(e);r(o,i.identity)&&q.unlinkSync(e)}catch(o){if(o.code!=="ENOENT")throw o}}}}}};p();function ix(e,t){let r=t.replace(/\s*[\r\n]+\s*/g," ");process.stderr.write(JSON.stringify({error:e,message:r})+`
|
|
810
|
+
`)}p();var CF="22.22.0";function ax(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 ox(e){return`Node.js ${CF} or newer is required; found ${e}. Upgrade Node.js and run the installer again.`}function MF(e){if(!$.existsSync(e))return{};let t={};for(let r of $.readFileSync(e,"utf8").split(`
|
|
811
|
+
`)){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 cx;function lx(e){try{return process.kill(e,0),!0}catch{return!1}}function Hd(e){let t=fe.join(e,"run"),r=`${e}.amb-migration-quiesced`;if($.existsSync(r)){let i=Number.parseInt($.readFileSync(r,"utf8").trim(),10);if(Number.isSafeInteger(i)&&i>1&&lx(i))throw new Error("MIGRATION_CONFLICT: legacy quiescence is held");$.unlinkSync(r)}let n=$.openSync(r,"wx",384);$.writeFileSync(n,`${process.pid}
|
|
812
|
+
`),$.closeSync(n);let s;try{if($.existsSync(t))for(let o of $.readdirSync(t)){if(!/^(?:mon|sup|relay)-.+\.pid$/.test(o))continue;let c=Number.parseInt($.readFileSync(fe.join(t,o),"utf8").trim(),10);if(Number.isSafeInteger(c)&&c>1&&c!==process.pid&&lx(c))throw new Error(`MIGRATION_CONFLICT: legacy writer pid ${c} is still active`)}let a=[fe.join(e,"state","data","tada-ride-agent.db"),fe.join(e,"state","data","ambient-ride.db"),fe.join(e,"data","tada-ride-agent.db"),fe.join(e,"data","ambient-ride.db")].find(o=>$.existsSync(o));a&&(s=new LF(a,{fileMustExist:!0,timeout:0}),s.pragma("wal_checkpoint(TRUNCATE)"),s.exec("BEGIN EXCLUSIVE"))}catch(i){try{s?.close()}catch{}try{$.unlinkSync(r)}catch{}throw i}return{release(){try{s?.inTransaction&&s.exec("ROLLBACK"),s?.close()}catch{}finally{s=void 0}try{$.unlinkSync(r)}catch{}}}}function kF(e,t){return{legacyRoot:t,ambientRoot:e,stagingRoot:`${e}.migrating`,backupRoot:`${t}.bak`,lockPath:`${e}-migration.lock`}}function UF(e){let t={},r=[];for(let n of e){if(!$.existsSync(n))continue;let s=JSON.parse($.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 FF(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 u of[o,c]){if(!u||typeof u!="object"||Array.isArray(u))continue;let d=u,m=Object.fromEntries(Object.entries(d).filter(([g,h])=>typeof h=="string"&&/^(?:TADA_AGENT_|TADA_OPENCLAW_)/.test(g))),f=on(m,t);for(let g of Object.keys(m))delete d[g];Object.assign(d,f.env)}let l=$.statSync(a.path);n.push({path:a.path,content:`${JSON.stringify(a.json,null,2)}
|
|
813
|
+
`,original:$.readFileSync(a.path),mode:l.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 qF(e,t,r){let n=`${e}.amb-migration-${process.pid}.tmp`,s;try{s=$.openSync(n,"wx",r),$.writeFileSync(s,t),$.fsyncSync(s),$.closeSync(s),s=void 0,$.renameSync(n,e);let i=$.openSync(fe.dirname(e),"r");try{$.fsyncSync(i)}finally{$.closeSync(i)}}catch(i){s!==void 0&&$.closeSync(s);try{$.unlinkSync(n)}catch{}throw i}}function jF(e={}){let t=e.ambientRoot??ye(),r=e.legacyRoot??fe.join(fe.dirname(t),".tada"),n=e.skillDir??fe.resolve(fe.dirname(new URL(import.meta.url).pathname),".."),s=Ti(n),i=$.existsSync(s)?(e.quiesceLegacy??Hd)(s):void 0,a=fe.join(t,"state","data");if(hs(a)){let C=(e.quiesceLegacy??Hd)(t);try{Tp(a)}finally{C.release()}}let o=kF(t,r),c=xe().networks.paymentNetwork,l=e.managedSettingsPaths??[fe.join(nc.homedir(),".claude","settings.json"),fe.join(nc.homedir(),".openclaw","openclaw.json")],u=UF(l),d=e.environmentSnapshot??{...process.env},m;try{bi(s,fe.join(r,"state")),m=(e.migrate??nx)({paths:o,oldDataDir:fe.join(r,"state","data"),oldKeysDir:fe.join(r,"state","keys"),paymentNetwork:c,installManagedCli:e.installManagedCli??(()=>{}),smoke:e.smoke??(()=>{}),quiesceLegacy:()=>(e.quiesceLegacy??Hd)(r),managedLegacyLink:e.managedLegacyLink??fe.join(nc.homedir(),".local","bin","tada"),expectedLegacyLinkTarget:e.expectedLegacyLinkTarget??fe.join(r,"cli","tada"),transformEnv:(C,P)=>on([{name:"legacy-state",env:C},{name:"managed-settings",env:u.legacy},{name:"process-env",env:d}],P)})}finally{i?.release()}FF(u,c,e.replaceManagedFile??qF);let f=fe.join(t,"state","data"),g=fe.join(t,"state","keys"),h=fe.join(f,".installed"),E=fe.join(f,".env");if($.existsSync(h)){let C=JSON.parse($.readFileSync(h,"utf8"));return{status:"already_installed",migration:m,output:{status:"already_installed",installed_at:C.installed_at,skill_dir:n,state_dir:t,data_dir:f,keys_dir:g,migration:m}}}$.mkdirSync(f,{recursive:!0,mode:448}),$.mkdirSync(g,{recursive:!0,mode:448});let T={...on(d,c).env,...on(u.legacy,c).env,...MF(E)},w=T.AMB_RIDE_PASSPHRASE??ux.randomBytes(32).toString("hex"),v=T.AMB_RIDE_PASSPHRASE?"preserved from existing .env":"newly generated",A={...T,AMB_RIDE_PASSPHRASE:w};return $.writeFileSync(E,["# Ambient Ride - auto-generated by amb install",`# Generated at: ${new Date().toISOString()}`,`# Source: ${v}`,...Object.entries(A).sort(([C],[P])=>C.localeCompare(P)).map(([C,P])=>`${C}=${P}`),""].join(`
|
|
814
|
+
`),{mode:384}),$.writeFileSync(h,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:v,migration:m,next_steps:["No platform config edits needed \u2014 the skill is self-contained.","Run `amb whoami` to see onboarding state."]}}}var BF=async e=>{let t=cx?.nodeVersion??process.versions.node;ax(t)||(ix("AMB_INSTALL_FAILED",ox(t)),process.exit(1)),process.env.SUDO_UID&&(S({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=jF(cx??{installManagedCli(){let s=process.argv[1];if(!s||fe.basename(s)!=="amb")throw new Error("MIGRATION_INTERRUPTED: Ambient CLI entrypoint is not verified");$.accessSync(s,$.constants.R_OK)},smoke(s){let i=PF(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 Ft(n.output.data_dir,"activation_installed"),S(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})}
|
|
815
|
+
`),process.exit(1)}},VF=async e=>{let[t]=e;t||(console.error("error: Usage: amb setup-check <wallet_address>"),process.exit(1));let r=O();try{N(r.dataDir)}catch{S({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||(S({wallet:s,jwt:null,phone:null,deposit:null,ready_for_ride:!1}),process.exit(0));let i=zp(n.wallet_address),a=i?{valid:!0,expires_at:i.expires_at}:{valid:!1,expires_at:null};i||(S({wallet:s,jwt:a,phone:null,deposit:null,ready_for_ride:!1}),process.exit(0));let o=wR(n.wallet_address),c={verified:o.length>0,numbers:o};o.length===0&&(S({wallet:s,jwt:a,phone:c,deposit:null,ready_for_ride:!1}),process.exit(0));let l=null,u=!1;try{l=(await Promise.allSettled(r.depositNetworks.map(async f=>{let[g,h,E]=await Promise.all([Es(f,n.wallet_address),Wi(f,n.wallet_address),Ts(f)]);return{network:f.name,isActive:g,deposited:h.toString(),minRequired:E.toString()}}))).filter(f=>f.status==="fulfilled").map(f=>f.value),u=l.some(f=>f.isActive)}catch{l=null,u=!1}S({wallet:s,jwt:a,phone:c,deposit:l,ready_for_ride:u})},dx={install:BF,"setup-check":VF};p();import YF from"fs";p();import sc from"fs";import GF from"path";p();function px(e,t){return!!x().prepare("SELECT 1 FROM processed_events WHERE ride_id=? AND event_id=?").get(e,t)}function mx(e,t,r){x().prepare("INSERT OR IGNORE INTO processed_events(ride_id,event_id,seq) VALUES(?,?,?)").run(e,t,r)}function fx(e){return x().prepare("SELECT MAX(seq) AS m FROM processed_events WHERE ride_id=?").get(e).m??0}p();import HF from"path";function Gd(e,t){return HF.join(e,"events",`${t}.jsonl`)}function $d(e,t){let r=rn({rideId:t.rideId,kind:t.kind,status:t.status,content:t.content});if(px(t.rideId,r))return null;let n=fx(t.rideId)+1,s={v:lw,seq:n,eventId:r,rideId:t.rideId,kind:t.kind,terminal:t.terminal,ts:t.ts,payload:t.payload},i=Gd(e,t.rideId);return sc.mkdirSync(GF.dirname(i),{recursive:!0}),sc.appendFileSync(i,JSON.stringify(s)+`
|
|
816
|
+
`),mx(t.rideId,r,n),s}function gx(e,t,r){let n=Gd(e,t);if(!sc.existsSync(n))return[];let s=[];for(let i of sc.readFileSync(n,"utf8").split(`
|
|
817
|
+
`))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
|
|
818
|
+
`)}return s}p();p();var $F={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 hx(e,t){let r=t?.trim();return r&&r.length>0?r:$F[e]??e}var WF={KRW:"\u20A9",USD:"$",SGD:"S$",VND:"\u20AB"};function ic(e,t){let r=e.toLocaleString("en-US"),n=WF[t];return n?`${n}${r}`:`${r} ${t}`}function JF(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 KF(e){let t=typeof e=="string"?e.toUpperCase():"";return t==="NY"?"Throo":t===""?"TADA/Throo":"TADA"}function _x(e){let t=KF(e.payload.region);if(e.kind==="driver_chat"){let l=e.payload.content??"";return`${t} ride: driver sent "${l}". 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=hx(n,r);if(e.terminal){let l=e.payload.tip,u=`${t} ride ${e.rideId} ${s}. Tell the user the final outcome briefly.`;if(n==="FINISHED"&&(u+=" Ask whether they would like to see their receipt. Fetch it only if they explicitly ask."),l){let d=l.maxAmount?`from ${ic(l.minAmount,l.currency)} up to ${ic(l.maxAmount,l.currency)}`:`from ${ic(l.minAmount,l.currency)}`;u+=` Tips ${d} are welcome. You may offer the tip together with that receipt question.`}return u}let i=e.payload.etaMin,a=JF(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 zF(e){try{return parseInt(YF.readFileSync(e,"utf8").trim(),10)||0}catch{return 0}}var XF=e=>new Promise(t=>setTimeout(t,e));async function QF(e){let t=e.write??(n=>process.stdout.write(n+`
|
|
819
|
+
`)),r=e.pollMs??2e3;for(;;){let n=zF(e.cursorFile),s=gx(e.root,e.rideId,n);for(let i of s){let a=e.prompt?{...i,prompt:_x(i)}:i;if(t(JSON.stringify(a)),i.terminal)return 0}if(!e.follow)return 0;await XF(r)}}var ZF=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=O();N(s.dataDir),await gr(r);let i=await QF({root:ye(),rideId:r,cursorFile:n,follow:e.includes("--follow"),prompt:e.includes("--prompt")});process.exit(i)},yx={events:ZF};p();import Kd from"fs";import Yd from"path";import{spawn as sq}from"child_process";p();var Ex=[2e3,5e3,15e3,3e4];function Tx(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,Ex.length-1);return{action:"restart",delayMs:Ex[t]}}p();import eq from"net";import Wd from"fs";import tq from"path";function bx(e){let t=e.trace??(()=>{});try{Wd.mkdirSync(tq.dirname(e.sockPath),{recursive:!0})}catch{}try{Wd.unlinkSync(e.sockPath)}catch{}let r=eq.createServer(n=>{let s="";n.on("data",i=>{s+=i.toString();let a=s.indexOf(`
|
|
820
|
+
`);if(a<0)return;let o=s.slice(0,a);s="",(async()=>{let c;try{let l=JSON.parse(o);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)+`
|
|
821
|
+
`)}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{Wd.unlinkSync(e.sockPath)}catch{}}}}p();var rq=5e3,vx=3e4,Rx=3,wx=Symbol("timed_out");function nq(e){let t,r=new Promise(n=>{t=setTimeout(()=>n(wx),rq)});return Promise.race([e,r]).finally(()=>clearTimeout(t))}function Ax(e){let t=e.trace??(()=>{}),r=e.now??Date.now,n=null,s=null,i=null,a=0,o=null,c=(l,u)=>{l!==null&&l!==s||(a+=1,o=r(),s=null,i=null,t("share_fetch_failed",{attempt:a,reason:u}),a>=Rx&&t("share_fetch_gave_up"))};return async l=>{if(e.mode!=="tada"||l.rideShareUrl||!l.driverInfo)return l;if(Bt(l.status))return n?{...l,rideShareUrl:n}:l;if(n)return{...l,rideShareUrl:n};if(s&&i!==null&&r()-i>=vx)return c(s,"abandoned"),t("share_fetch_abandoned",{status:l.status}),l;if(!s){if(a>=Rx||o!==null&&r()-o<vx)return l;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 u=s,d;try{d=await nq(u)}catch(m){return c(u,String(m.message??m)),l}return d===wx?(t("share_fetch_slow",{status:l.status}),l):(n=d,s=null,i=null,{...l,rideShareUrl:n})}}async function iq(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:rn({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=Bt(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=$d(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??rn({rideId:e.rideId,kind:"ride_status",status:r.status}),status:r.status,previousStatus:s,rideId:r.rideId,rideCreatedObserved:n})}catch{}return Jn(e.rideId,r.status),e.lastStatusRef.status=r.status,t("event_appended",{status:r.status,terminal:i}),{terminal:i}}function aq(e,t,r,n){let s;return e.on("ready",()=>{if(!s)try{s=bx({sockPath:Bo(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 oq(e){return Yd.join(ye(),"run",`monitor-trace-${e}.log`)}function Sx(e){let t=oq(e);return(r,n)=>{try{Kd.mkdirSync(Yd.dirname(t),{recursive:!0}),Kd.appendFileSync(t,JSON.stringify({ts:new Date().toISOString(),pid:process.pid,event:r,rideId:e,...n??{}})+`
|
|
822
|
+
`)}catch{}}}var Jd=5e3,cq=250,xx=e=>new Promise(t=>setTimeout(t,e));function lq(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 uq=async e=>{let t=e[0];t||(console.error(JSON.stringify({error:"USAGE",message:"amb monitor <request_id>"})),process.exit(1));let r=Sx(t),n=O();N(n.dataDir);let s=Oe(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 yt(n,s)}catch(L){r("backend_resolve_failed",{msg:L.message}),console.error(JSON.stringify({error:"BACKEND_UNAVAILABLE",message:L.message})),process.exit(1);return}let{backend:a,mode:o}=i;r("startup",{rideId:t,mode:o,gatewayServerUrl:n.gatewayServerUrl,dataDir:n.dataDir,pollIntervalMs:Jd});let c=lq(a,s.region),l=Ax({backend:a,mode:o,rideId:t,trace:r}),u="mon-"+t;if(!_d(ye(),u)){r("already_running",{lockName:u}),process.exit(0);return}r("lock_acquired",{lockName:u});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},h={rideId:s.ride_id??void 0},E=new Set,T=0,w=!1,v=L=>{if(!w){w=!0;try{d?.dispose()}catch{}m?.close(),Fo(ye(),u),r("lock_released",{reason:L})}},A=(L,W)=>{throw v(W),r("exit",{code:L,reason:W}),process.exit(L),new Error("unreachable")},C=!1,P=async L=>{C&&A(2,`${L}_repeat`),C=!0,r("signal",{signal:L});let W;try{await Promise.race([Promise.allSettled([...E]),new Promise(Z=>{W=setTimeout(Z,cq)})])}finally{W&&clearTimeout(W)}A(2,L)};process.on("SIGTERM",()=>{P("SIGTERM")}),process.on("SIGINT",()=>{P("SIGINT")}),process.on("uncaughtException",L=>{r("crash",{source:"uncaughtException",error:String(L),stack:L?.stack}),v("uncaughtException"),r("exit",{code:1,reason:"uncaughtException"}),process.exit(1)}),process.on("unhandledRejection",L=>{let W=L instanceof Error?L:new Error(String(L));r("crash",{source:"unhandledRejection",error:String(W),stack:W.stack}),v("unhandledRejection"),r("exit",{code:1,reason:"unhandledRejection"}),process.exit(1)});try{for(;;){T+=1,r("poll_begin",{iteration:T,lastStatus:f.status}),o==="wallet"&&(ce(s.wallet_address)||(process.stderr.write(JSON.stringify({error:"JWT_EXPIRED"})+`
|
|
823
|
+
`),r("jwt_missing",{iteration:T}),A(1,"jwt_missing")));let L;try{L=await dq({backend:a,rideId:t,lastStatusRef:f,lastRideIdRef:h,trace:r,tipLookup:c,region:s.region,shareEnricher:l,onStatusChange:async W=>{let Z=Date.now();W.status.toUpperCase()==="PENDING"&&g.at==null&&(g.at=Z),g.at==null&&qb(W.status)&&(g.at=s.created_at*1e3);let V=Xo(n.dataDir,s,{...W,durationMs:Math.max(0,Z-(g.at??s.created_at*1e3))});E.add(V);try{await V}finally{E.delete(V)}}})}catch(W){let Z=W.message;Z.includes("401")&&(process.stderr.write(JSON.stringify({error:"JWT_EXPIRED",message:Z})+`
|
|
824
|
+
`),r("jwt_expired",{iteration:T,message:Z}),A(1,"jwt_expired")),process.stderr.write(`poll_error: ${Z}
|
|
825
|
+
`),r("poll_error",{iteration:T,message:Z}),await xx(Jd);continue}L.driverInfo&&!d&&(r("chat_client_start",{rideId:t}),d=a.subscribeChat(t),d.on("message",W=>{let Z=W.data,V=Z?.content??"",Y=Z?.senderType,ge=Y==="DRIVER"?"driver":Y==="SYSTEM"?"system":"unknown";r("chat_msg_raw",{raw:Z,senderType:Y,sender:ge}),$d(ye(),{rideId:t,kind:"driver_chat",terminal:!1,ts:new Date().toISOString(),content:V,payload:{content:V,sender:ge,region:s.region}})}),d.on("error",W=>{r("chat_error",{message:W.message})}),d.connect(),m=aq(d,t,ye(),r)),Bt(L.status)&&(r("terminal",{status:L.status}),A(0,"terminal")),await xx(Jd)}}catch(L){if(w)throw L;let W=L;r("crash",{source:"poll_loop",error:String(W),stack:W?.stack}),v("crash"),r("exit",{code:1,reason:"crash"}),process.exit(1)}};async function dq(e){let t;if(await iq({root:ye(),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 pq(){let e=process.argv[1]??"",t=e?Yd.resolve(e):"";if(!t||!Kd.existsSync(t))throw new Error(`amb entry not found (argv[1]=${process.argv[1]}, resolved=${t})`);return t}function mq(e){let t=Sx(e);return(r,n)=>t(r,{role:"supervisor",...n??{}})}var fq=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=mq(t);r("sup_start",{rideId:t,pid:process.pid});let n="sup-"+t;if(!_d(ye(),n)){r("sup_already_running",{lockName:n}),process.exit(0);return}r("sup_lock_acquired",{lockName:n});let s;try{s=pq(),r("sup_entry_resolved",{ambEntry:s})}catch(f){r("sup_entry_unresolved",{error:String(f)}),Fo(ye(),n),r("sup_stop",{code:2,reason:"entry_unresolved"}),process.exit(2);return}let i,a=!1,o=!1,c=f=>{o||(o=!0,Fo(ye(),n),r("sup_lock_released",{reason:f}))},l=()=>{if(i&&i.exitCode===null&&i.signalCode===null)try{i.kill("SIGTERM")}catch{}},u=async f=>{if(a)return;a=!0,r("sup_signal",{signal:f});let g=!!(i&&i.exitCode===null&&i.signalCode===null);l(),g&&await new Promise(h=>{let E=!1,T=()=>{E||(E=!0,h())};i.once("exit",T),setTimeout(T,25e3).unref()}),c(f),r("sup_stop",{code:2,reason:f}),process.exit(2)};process.on("SIGTERM",()=>{u("SIGTERM")}),process.on("SIGINT",()=>{u("SIGINT")});let d=(f,g)=>{if(a)return;a=!0;let h=g instanceof Error?g:new Error(String(g));r("sup_crash",{source:f,error:String(h),stack:h.stack}),l(),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=sq(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,h)=>{if(a)return;r("sup_child_exit",{exitCode:g,signal:h,restartCount:m});let E=Tx({exitCode:g,signal:h,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()})},Ix={monitor:uq,"monitor-supervisor":fq};p();function gq(e){let t=ce(e,"member")!==null,r=$i(e)!==null;return t||r?"active":"needs_login"}var hq="Your TADA/Throo session isn't active \u2014 run 'amb login' to sign in again.",_q=async e=>{let t=Qe(),r=gs();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 ask the user to choose Built-in Privy (default) or MetaMask and have the Agent complete that wallet setup; add a TADA/Throo membership with 'amb login' if they want card payment."};S(i);return}if(t.mode==="tada"&&t.member){let i=gq(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:hq}};S(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};S(i);return}if(t.mode==="wallet"&&t.hasWallet){let i={mode:"wallet",reason:t.reason,identity:null,member_available:r,has_wallet:!0,hint:"Multiple wallets are registered. Run 'amb wallet-status', ask the user which wallet to use, and pass that address to subsequent wallet commands."};S(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}`};S(s)},Dx={whoami:_q};p();p();function Ox(e,t){x().prepare("INSERT OR REPLACE INTO member_login_sessions (session_token, expires_at, created_at) VALUES (?, ?, ?)").run(e,t,Math.floor(Date.now()/1e3))}function Nx(){return x().prepare("SELECT * FROM member_login_sessions ORDER BY created_at DESC, rowid DESC LIMIT 1").get()}function ac(e){x().prepare("DELETE FROM member_login_sessions WHERE session_token = ?").run(e)}function Cx(){x().prepare("DELETE FROM member_login_sessions").run()}p();import yq from"os";import Px from"path";import Eq from"fs";import Lx from"qrcode";async function zd(e){return Lx.toString(e,{type:"terminal",small:!0,errorCorrectionLevel:"L"})}async function Mx(e){let t=Eq.mkdtempSync(Px.join(yq.tmpdir(),"tada-login-")),r=Px.join(t,"qr.png");return await Lx.toFile(r,e,{type:"png",margin:4,width:320}),r}import bq from"readline/promises";async function vq(){let e=bq.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 Rq(){if(!gs()){S({status:"unavailable",message:"Member login is not available in this build (missing RIDER_CLI_APP credentials or gateway host)."});return}let e=O();N(e.dataDir);let t={clientId:e.riderCliApp.clientId,clientSecret:e.riderCliApp.clientSecret};Or(Xe(e.cliGatewayHosts,e.cliGatewayHost));try{let r=await vd(t),n=Date.parse(r.expiresAt),s=Number.isFinite(n)?Math.floor(n/1e3):Math.floor(Date.now()/1e3)+600;Cx(),Ox(r.sessionToken,s);let i={status:"auth_required",approval_url:r.approvalUrl,expires_at:r.expiresAt};try{let a=await zd(r.approvalUrl);process.stderr.write(`Scan this QR to approve the login in the TADA/Throo app:
|
|
826
|
+
${a}
|
|
827
|
+
`),i.qr_image_path=await Mx(r.approvalUrl)}catch{}S(i)}catch{S({status:"error",message:"Failed to start login session."})}}var wq=async e=>{if(e.includes("--no-wait"))return Rq();let r=O();if(!hp(r)){console.log("Member login is not available in this build (missing RIDER_CLI_APP credentials).");return}N(r.dataDir);let n={clientId:r.riderCliApp.clientId,clientSecret:r.riderCliApp.clientSecret};Or(Xe(r.cliGatewayHosts,r.cliGatewayHost));let s=await vd(n),i="";try{i=`
|
|
828
|
+
${await zd(s.approvalUrl)}`}catch{}console.log(`Approve this login in the TADA/Throo app:${i} ${s.approvalUrl}
|
|
829
|
+
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 l=1;l<=5;l++){let u=o??await vq();try{let d=await Rd(n,s.sessionToken,u);await Ft(r.dataDir,"activation_authenticated",{id:vr(d.memberId)}),console.log(`Logged in as TADA/Throo member ${d.memberId}.`);return}catch(d){if(d instanceof Ge&&d.code==="invalid_user_code"){if(c=!0,console.log(`Code did not match (${l}/5)${l===4?" \u2014 last attempt!":""}.`),o!==void 0)return;continue}if(d instanceof Ge&&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.")},Aq=async()=>{let e=O();N(e.dataDir),console.log(Iw()?"Logged out of TADA/Throo member account.":"No active TADA/Throo member session.")},xq=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)),!gs()){S({status:"unavailable",message:"Member login is not available in this build (missing RIDER_CLI_APP credentials or gateway host)."});return}let n=O();N(n.dataDir);let s={clientId:n.riderCliApp.clientId,clientSecret:n.riderCliApp.clientSecret};Or(Xe(n.cliGatewayHosts,n.cliGatewayHost));let i=Nx(),a=Math.floor(Date.now()/1e3);if(!i||i.expires_at<=a){i&&ac(i.session_token),S({status:"session_expired",message:"No active login session. Run `amb login --no-wait` to start over."});return}try{let o=await Rd(s,i.session_token,r);ac(i.session_token),await Ft(n.dataDir,"activation_authenticated",{id:vr(o.memberId)}),S({status:"logged_in",member_id:o.memberId})}catch(o){if(o instanceof Ge&&o.code==="invalid_user_code"){S({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 Ge&&(o.code==="invalid_grant"||o.code==="agent_session_not_found"||o.code==="agent_session_already_decided"||o.code==="agent_session_expired")){ac(i.session_token),S({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}S({status:"error",message:"Login failed. Run `amb login --no-wait` to start over."})}},kx={login:wq,logout:Aq,"login-verify":xq};p();import os from"fs";import cs from"path";p();var Sq="proprietary (see LICENSE)";function oc(){let{cliVersion:e,gitSha:t}=xe().artifact;return{version:e,git_sha:t,license:Sq}}function Ux(e){return`version: ${e.version}
|
|
477
830
|
git_sha: ${e.git_sha}
|
|
478
|
-
license: ${e.license}`}import
|
|
479
|
-
`),manifest:n}}import{spawn as
|
|
831
|
+
license: ${e.license}`}p();import Iq from"fs";import tr from"path";function Fx(e,t){return[{arcname:`events-${e}.jsonl`,rel:tr.join("events",`${e}.jsonl`)},{arcname:`monitor-trace-${e}.log`,rel:tr.join("run",`monitor-trace-${e}.log`)},{arcname:`relay-error-${e}.log`,rel:tr.join("run",`relay-error-${e}.log`)},{arcname:`relay-trace-${e}.jsonl`,rel:tr.join("run",`relay-trace-${e}.jsonl`)},{arcname:`mon-${e}.pid`,rel:tr.join("run",`mon-${e}.pid`)},{arcname:`sup-${e}.pid`,rel:tr.join("run",`sup-${e}.pid`)},{arcname:`relay-${e}.pid`,rel:tr.join("run",`relay-${e}.pid`)},{arcname:`cursor-openclaw-${e}`,rel:tr.join("cursors",`openclaw-${e}`)},{arcname:`cursor-stdout-${e}`,rel:tr.join("cursors",`stdout-${e}`)}].map(({arcname:n,rel:s})=>{let i=tr.join(t,s);return{arcname:n,absPath:i,present:Iq.existsSync(i)}})}p();function qx(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(`
|
|
832
|
+
`),manifest:n}}p();import{spawn as Dq}from"child_process";import Oq from"path";var gi=class extends Error{constructor(){super("zip binary not found on PATH"),this.name="ZipUnavailableError"}},hi=class extends Error{constructor(t){super(`zip exited ${t}`),this.name="ZipFailedError"}},Nq=(e,t,r)=>new Promise((n,s)=>{let i=Dq(e,t,{cwd:r,stdio:"ignore"});i.on("error",s),i.on("exit",a=>n(a??1))});async function jx(e){if(!Oq.isAbsolute(e.outZipPath))throw new Error("outZipPath must be absolute");let t=e.run??Nq,r;try{r=await t("zip",["-r","-q",e.outZipPath,"."],e.stagingDir)}catch(n){throw n.code==="ENOENT"?new gi:n}if(r!==0)throw new hi(r)}function Bx(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 Cq=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}N(mn());let r=ye(),n=new Date,s=cs.join(r,"debug"),i=cs.join(s,`.staging-${Bx(n)}-${process.pid}`);os.mkdirSync(i,{recursive:!0});let a=cs.join(s,`tada-debug-${t.slice(0,8)}-${Bx(n)}.zip`);try{let o=Fx(t,r);for(let d of o)if(d.present)try{os.copyFileSync(d.absPath,cs.join(i,d.arcname))}catch{d.present=!1}let c=oc(),l=xe(),u=qx({rideId:t,createdAt:n.toISOString(),version:{version:c.version,git_sha:c.git_sha,branch:l.install.repoBranch,install_mode:l.install.mode},rideRow:Oe(t)??null,liveness:{monitor:Xn(r,`mon-${t}`),supervisor:Xn(r,`sup-${t}`),relay:Xn(r,`relay-${t}`)},artifacts:o.map(d=>({arcname:d.arcname,present:d.present}))});os.writeFileSync(cs.join(i,"summary.md"),u.markdown),os.writeFileSync(cs.join(i,"manifest.json"),JSON.stringify(u.manifest,null,2)),await jx({stagingDir:i,outZipPath:a}),os.rmSync(i,{recursive:!0,force:!0}),S({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(os.rmSync(i,{recursive:!0,force:!0}),o instanceof gi){b({error:"ZIP_UNAVAILABLE",message:"zip binary not found on PATH"}),process.exit(1);return}if(o instanceof hi){b({error:"ZIP_FAILED",message:o.message}),process.exit(1);return}b({error:"DEBUG_FAILED",message:o.message}),process.exit(1);return}},Vx={debug:Cq};p();p();async function _i(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 ht(a.status,await a.text().catch(()=>""));return a.json()}function Hx(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 Gx(e,t,r={}){return _i(e,"GET",`/v1/coupons/current${Hx(r)}`,t)}function $x(e,t,r={}){return _i(e,"GET",`/v1/coupons/past${Hx(r)}`,t)}function Wx(e,t,r){return _i(e,"GET",`/v1/coupons/${encodeURIComponent(r)}`,t)}function Jx(e,t,r){return _i(e,"POST","/v1/coupons/register",t,{code:r})}function Pq(e,t,r,n){return _i(e,"POST","/v1/coupons/available",t,r,n)}async function Kx(e,t,r,n){let i=(await ci(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 Pq(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 Ht(e){b({error:"INVALID_ARGUMENT",message:e}),process.exit(1)}function Yx(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 yi(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 zx(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)??$a(t)??s[t??""]??e.message}),process.exit(1)}async function cc(e){let t=O();N(t.dataDir);let r;try{r=await Zt(t)}catch(n){b({error:"MEMBER_AUTH_FAILED",message:n.message}),process.exit(1)}try{S(await e(Xe(t.cliGatewayHosts,t.cliGatewayHost),r))}catch(n){zx(n)}}var Lq=async e=>{let t;try{t=Yx(e)}catch(r){Ht(r.message)}await cc(async(r,n)=>{let s=await Gx(r,n,t);return{coupons:s.coupons.map(yi),page:s.page,has_next:s.has_next}})},Mq=async e=>{let t;try{t=Yx(e,!0)}catch(r){Ht(r.message)}await cc(async(r,n)=>{let s=await $x(r,n,t);return{coupons:s.coupons.map(yi),page:s.page,has_next:s.has_next}})},kq=async e=>{let t=e[0];(!t||e.length!==1)&&Ht("Usage: amb coupon-detail <code>"),await cc(async(r,n)=>yi(await Wx(r,n,t)))},Uq=async e=>{let t=e[0];(!t||e.length!==1)&&Ht("Usage: amb coupon-register <code>"),await cc(async(r,n)=>yi(await Jx(r,n,t)))},Fq=async e=>{let t,r=[];for(let m=0;m<e.length;m++)e[m]==="--lang"?t=e[++m]??Ht("--lang requires a value."):r.push(e[m]);r[0]||Ht("Usage: amb coupon-available '<json_params>' [--lang TAG]"),r.length!==1&&Ht("coupon-available accepts exactly one json_params argument.");let n;try{n=JSON.parse(r[0])}catch{Ht("Failed to parse json_params argument.")}let s=Yo(n.locations),i=n.product_id,a=n.payment_item_uuid;(!s||s.length<2)&&Ht("locations must contain valid origin and destination coordinates."),(!Number.isSafeInteger(i)||i<=0)&&Ht("product_id must be a positive integer."),a!==void 0&&(typeof a!="string"||!a)&&Ht("payment_item_uuid must be a non-empty string.");let o=O();N(o.dataDir);let c;try{c=await an(o)}catch(m){b({error:"MEMBER_AUTH_FAILED",message:m.message}),process.exit(1)}let l=s[0],u=nt(_t(l.latitude,l.longitude),o.cliGatewayHosts,o.cliGatewayHost),d=await nn(c.backend,a,u);if(d!=null)try{let m=await Kx(u,c.jwt,{locations:s,payment_item_uuid:d,product_id:i},t);S(m.map(yi))}catch(m){zx(m)}},Xx={"coupon-current":Lq,"coupon-past":Mq,"coupon-detail":kq,"coupon-register":Uq,"coupon-available":Fq};p();function Qx(){let e=xe().install.repoBranch;return e==="dev"||e==="staging"}var Zx={...rv,...Uv,...RR,...cA,...pA,...fA,...AA,...DA,...OA,...PA,...kA,...dx,...yx,...Ix,...Dx,...kx,...Xx,...Qx()?Vx:{}};function eS(e){return Zx[e]}function Xd(){return Object.keys(Zx).sort()}var{json:tS,argv:qq}=sp(process.argv.slice(2));np(tS?"json":"plain");var Qd;try{let e=gw(qq);mw(e.account),Qd=e.argv}catch(e){b({error:"USAGE",message:e.message}),process.exit(1)}var _r=Qd[0];if(_r==="--version"||_r==="-v"){let e=oc();console.log(tS?JSON.stringify(e):Ux(e)),process.exit(0)}(!_r||_r==="--help"||_r==="-h")&&(b({error:"USAGE",message:"amb <command> [args]",commands:Xd()}),process.exit(_r?0:1));var rS=eS(_r);rS||(b({error:"UNKNOWN_COMMAND",message:`Unknown command: ${_r}`,commands:Xd()}),process.exit(1));var lc=hw(_r);if(lc){let e=Qe();e.mode&&e.mode!==lc&&(b({error:"MODE_MISMATCH",message:_w(lc,e.mode),required_mode:lc,active_mode:e.mode,active_reason:e.reason}),process.exit(1))}try{await rS(Qd.slice(1))}catch(e){b({error:"CLI_ERROR",message:e.message??String(e)}),process.exit(1)}
|
|
833
|
+
/*! Bundled license information:
|
|
834
|
+
|
|
835
|
+
mime-db/index.js:
|
|
836
|
+
(*!
|
|
837
|
+
* mime-db
|
|
838
|
+
* Copyright(c) 2014 Jonathan Ong
|
|
839
|
+
* Copyright(c) 2015-2022 Douglas Christopher Wilson
|
|
840
|
+
* MIT Licensed
|
|
841
|
+
*)
|
|
842
|
+
|
|
843
|
+
mime-types/index.js:
|
|
844
|
+
(*!
|
|
845
|
+
* mime-types
|
|
846
|
+
* Copyright(c) 2014 Jonathan Ong
|
|
847
|
+
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
848
|
+
* MIT Licensed
|
|
849
|
+
*)
|
|
850
|
+
|
|
851
|
+
axios/dist/node/axios.cjs:
|
|
852
|
+
(*! Axios v1.19.0 Copyright (c) 2026 Matt Zabriskie and contributors *)
|
|
853
|
+
*/
|