@mearl/native-host 2.13.0 → 2.14.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/dist/index.js +13 -13
- package/package.json +6 -6
package/dist/index.js
CHANGED
|
@@ -19,7 +19,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
19
19
|
\r
|
|
20
20
|
`)+4,req.output[0]=req._header+first.substring(endOfHeaders),debug("Output buffer: %o",req.output)):req.outputData&&req.outputData.length>0&&(debug("Patching connection write() output buffer with updated header"),first=req.outputData[0].data,endOfHeaders=first.indexOf(`\r
|
|
21
21
|
\r
|
|
22
|
-
`)+4,req.outputData[0].data=req._header+first.substring(endOfHeaders),debug("Output buffer: %o",req.outputData[0].data))}return yield(0,once_1.default)(socket,"connect"),socket})}};exports.default=HttpProxyAgent}});var require_dist3=__commonJS({"../../node_modules/.pnpm/http-proxy-agent@5.0.0/node_modules/http-proxy-agent/dist/index.js"(exports,module){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}},agent_1=__importDefault(require_agent2());function createHttpProxyAgent(opts){return new agent_1.default(opts)}(function(createHttpProxyAgent2){createHttpProxyAgent2.HttpProxyAgent=agent_1.default,createHttpProxyAgent2.prototype=agent_1.default.prototype})(createHttpProxyAgent||(createHttpProxyAgent={}));module.exports=createHttpProxyAgent}});var require_utils=__commonJS({"../../node_modules/.pnpm/smart-buffer@4.2.0/node_modules/smart-buffer/build/utils.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var buffer_1=__require("buffer"),ERRORS={INVALID_ENCODING:"Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",INVALID_SMARTBUFFER_SIZE:"Invalid size provided. Size must be a valid integer greater than zero.",INVALID_SMARTBUFFER_BUFFER:"Invalid Buffer provided in SmartBufferOptions.",INVALID_SMARTBUFFER_OBJECT:"Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",INVALID_OFFSET:"An invalid offset value was provided.",INVALID_OFFSET_NON_NUMBER:"An invalid offset value was provided. A numeric value is required.",INVALID_LENGTH:"An invalid length value was provided.",INVALID_LENGTH_NON_NUMBER:"An invalid length value was provived. A numeric value is required.",INVALID_TARGET_OFFSET:"Target offset is beyond the bounds of the internal SmartBuffer data.",INVALID_TARGET_LENGTH:"Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",INVALID_READ_BEYOND_BOUNDS:"Attempted to read beyond the bounds of the managed data.",INVALID_WRITE_BEYOND_BOUNDS:"Attempted to write beyond the bounds of the managed data."};exports.ERRORS=ERRORS;function checkEncoding(encoding){if(!buffer_1.Buffer.isEncoding(encoding))throw new Error(ERRORS.INVALID_ENCODING)}exports.checkEncoding=checkEncoding;function isFiniteInteger(value){return typeof value=="number"&&isFinite(value)&&isInteger(value)}exports.isFiniteInteger=isFiniteInteger;function checkOffsetOrLengthValue(value,offset){if(typeof value=="number"){if(!isFiniteInteger(value)||value<0)throw new Error(offset?ERRORS.INVALID_OFFSET:ERRORS.INVALID_LENGTH)}else throw new Error(offset?ERRORS.INVALID_OFFSET_NON_NUMBER:ERRORS.INVALID_LENGTH_NON_NUMBER)}function checkLengthValue(length){checkOffsetOrLengthValue(length,!1)}exports.checkLengthValue=checkLengthValue;function checkOffsetValue(offset){checkOffsetOrLengthValue(offset,!0)}exports.checkOffsetValue=checkOffsetValue;function checkTargetOffset(offset,buff){if(offset<0||offset>buff.length)throw new Error(ERRORS.INVALID_TARGET_OFFSET)}exports.checkTargetOffset=checkTargetOffset;function isInteger(value){return typeof value=="number"&&isFinite(value)&&Math.floor(value)===value}function bigIntAndBufferInt64Check(bufferMethod){if(typeof BigInt>"u")throw new Error("Platform does not support JS BigInt type.");if(typeof buffer_1.Buffer.prototype[bufferMethod]>"u")throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`)}exports.bigIntAndBufferInt64Check=bigIntAndBufferInt64Check}});var require_smartbuffer=__commonJS({"../../node_modules/.pnpm/smart-buffer@4.2.0/node_modules/smart-buffer/build/smartbuffer.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var utils_1=require_utils(),DEFAULT_SMARTBUFFER_SIZE=4096,DEFAULT_SMARTBUFFER_ENCODING="utf8",SmartBuffer=class _SmartBuffer{constructor(options){if(this.length=0,this._encoding=DEFAULT_SMARTBUFFER_ENCODING,this._writeOffset=0,this._readOffset=0,_SmartBuffer.isSmartBufferOptions(options))if(options.encoding&&(utils_1.checkEncoding(options.encoding),this._encoding=options.encoding),options.size)if(utils_1.isFiniteInteger(options.size)&&options.size>0)this._buff=Buffer.allocUnsafe(options.size);else throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE);else if(options.buff)if(Buffer.isBuffer(options.buff))this._buff=options.buff,this.length=options.buff.length;else throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER);else this._buff=Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE);else{if(typeof options<"u")throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE)}}static fromSize(size,encoding){return new this({size,encoding})}static fromBuffer(buff,encoding){return new this({buff,encoding})}static fromOptions(options){return new this(options)}static isSmartBufferOptions(options){let castOptions=options;return castOptions&&(castOptions.encoding!==void 0||castOptions.size!==void 0||castOptions.buff!==void 0)}readInt8(offset){return this._readNumberValue(Buffer.prototype.readInt8,1,offset)}readInt16BE(offset){return this._readNumberValue(Buffer.prototype.readInt16BE,2,offset)}readInt16LE(offset){return this._readNumberValue(Buffer.prototype.readInt16LE,2,offset)}readInt32BE(offset){return this._readNumberValue(Buffer.prototype.readInt32BE,4,offset)}readInt32LE(offset){return this._readNumberValue(Buffer.prototype.readInt32LE,4,offset)}readBigInt64BE(offset){return utils_1.bigIntAndBufferInt64Check("readBigInt64BE"),this._readNumberValue(Buffer.prototype.readBigInt64BE,8,offset)}readBigInt64LE(offset){return utils_1.bigIntAndBufferInt64Check("readBigInt64LE"),this._readNumberValue(Buffer.prototype.readBigInt64LE,8,offset)}writeInt8(value,offset){return this._writeNumberValue(Buffer.prototype.writeInt8,1,value,offset),this}insertInt8(value,offset){return this._insertNumberValue(Buffer.prototype.writeInt8,1,value,offset)}writeInt16BE(value,offset){return this._writeNumberValue(Buffer.prototype.writeInt16BE,2,value,offset)}insertInt16BE(value,offset){return this._insertNumberValue(Buffer.prototype.writeInt16BE,2,value,offset)}writeInt16LE(value,offset){return this._writeNumberValue(Buffer.prototype.writeInt16LE,2,value,offset)}insertInt16LE(value,offset){return this._insertNumberValue(Buffer.prototype.writeInt16LE,2,value,offset)}writeInt32BE(value,offset){return this._writeNumberValue(Buffer.prototype.writeInt32BE,4,value,offset)}insertInt32BE(value,offset){return this._insertNumberValue(Buffer.prototype.writeInt32BE,4,value,offset)}writeInt32LE(value,offset){return this._writeNumberValue(Buffer.prototype.writeInt32LE,4,value,offset)}insertInt32LE(value,offset){return this._insertNumberValue(Buffer.prototype.writeInt32LE,4,value,offset)}writeBigInt64BE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigInt64BE,8,value,offset)}insertBigInt64BE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigInt64BE,8,value,offset)}writeBigInt64LE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigInt64LE,8,value,offset)}insertBigInt64LE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigInt64LE,8,value,offset)}readUInt8(offset){return this._readNumberValue(Buffer.prototype.readUInt8,1,offset)}readUInt16BE(offset){return this._readNumberValue(Buffer.prototype.readUInt16BE,2,offset)}readUInt16LE(offset){return this._readNumberValue(Buffer.prototype.readUInt16LE,2,offset)}readUInt32BE(offset){return this._readNumberValue(Buffer.prototype.readUInt32BE,4,offset)}readUInt32LE(offset){return this._readNumberValue(Buffer.prototype.readUInt32LE,4,offset)}readBigUInt64BE(offset){return utils_1.bigIntAndBufferInt64Check("readBigUInt64BE"),this._readNumberValue(Buffer.prototype.readBigUInt64BE,8,offset)}readBigUInt64LE(offset){return utils_1.bigIntAndBufferInt64Check("readBigUInt64LE"),this._readNumberValue(Buffer.prototype.readBigUInt64LE,8,offset)}writeUInt8(value,offset){return this._writeNumberValue(Buffer.prototype.writeUInt8,1,value,offset)}insertUInt8(value,offset){return this._insertNumberValue(Buffer.prototype.writeUInt8,1,value,offset)}writeUInt16BE(value,offset){return this._writeNumberValue(Buffer.prototype.writeUInt16BE,2,value,offset)}insertUInt16BE(value,offset){return this._insertNumberValue(Buffer.prototype.writeUInt16BE,2,value,offset)}writeUInt16LE(value,offset){return this._writeNumberValue(Buffer.prototype.writeUInt16LE,2,value,offset)}insertUInt16LE(value,offset){return this._insertNumberValue(Buffer.prototype.writeUInt16LE,2,value,offset)}writeUInt32BE(value,offset){return this._writeNumberValue(Buffer.prototype.writeUInt32BE,4,value,offset)}insertUInt32BE(value,offset){return this._insertNumberValue(Buffer.prototype.writeUInt32BE,4,value,offset)}writeUInt32LE(value,offset){return this._writeNumberValue(Buffer.prototype.writeUInt32LE,4,value,offset)}insertUInt32LE(value,offset){return this._insertNumberValue(Buffer.prototype.writeUInt32LE,4,value,offset)}writeBigUInt64BE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64BE,8,value,offset)}insertBigUInt64BE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64BE,8,value,offset)}writeBigUInt64LE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64LE,8,value,offset)}insertBigUInt64LE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64LE,8,value,offset)}readFloatBE(offset){return this._readNumberValue(Buffer.prototype.readFloatBE,4,offset)}readFloatLE(offset){return this._readNumberValue(Buffer.prototype.readFloatLE,4,offset)}writeFloatBE(value,offset){return this._writeNumberValue(Buffer.prototype.writeFloatBE,4,value,offset)}insertFloatBE(value,offset){return this._insertNumberValue(Buffer.prototype.writeFloatBE,4,value,offset)}writeFloatLE(value,offset){return this._writeNumberValue(Buffer.prototype.writeFloatLE,4,value,offset)}insertFloatLE(value,offset){return this._insertNumberValue(Buffer.prototype.writeFloatLE,4,value,offset)}readDoubleBE(offset){return this._readNumberValue(Buffer.prototype.readDoubleBE,8,offset)}readDoubleLE(offset){return this._readNumberValue(Buffer.prototype.readDoubleLE,8,offset)}writeDoubleBE(value,offset){return this._writeNumberValue(Buffer.prototype.writeDoubleBE,8,value,offset)}insertDoubleBE(value,offset){return this._insertNumberValue(Buffer.prototype.writeDoubleBE,8,value,offset)}writeDoubleLE(value,offset){return this._writeNumberValue(Buffer.prototype.writeDoubleLE,8,value,offset)}insertDoubleLE(value,offset){return this._insertNumberValue(Buffer.prototype.writeDoubleLE,8,value,offset)}readString(arg1,encoding){let lengthVal;typeof arg1=="number"?(utils_1.checkLengthValue(arg1),lengthVal=Math.min(arg1,this.length-this._readOffset)):(encoding=arg1,lengthVal=this.length-this._readOffset),typeof encoding<"u"&&utils_1.checkEncoding(encoding);let value=this._buff.slice(this._readOffset,this._readOffset+lengthVal).toString(encoding||this._encoding);return this._readOffset+=lengthVal,value}insertString(value,offset,encoding){return utils_1.checkOffsetValue(offset),this._handleString(value,!0,offset,encoding)}writeString(value,arg2,encoding){return this._handleString(value,!1,arg2,encoding)}readStringNT(encoding){typeof encoding<"u"&&utils_1.checkEncoding(encoding);let nullPos=this.length;for(let i=this._readOffset;i<this.length;i++)if(this._buff[i]===0){nullPos=i;break}let value=this._buff.slice(this._readOffset,nullPos);return this._readOffset=nullPos+1,value.toString(encoding||this._encoding)}insertStringNT(value,offset,encoding){return utils_1.checkOffsetValue(offset),this.insertString(value,offset,encoding),this.insertUInt8(0,offset+value.length),this}writeStringNT(value,arg2,encoding){return this.writeString(value,arg2,encoding),this.writeUInt8(0,typeof arg2=="number"?arg2+value.length:this.writeOffset),this}readBuffer(length){typeof length<"u"&&utils_1.checkLengthValue(length);let lengthVal=typeof length=="number"?length:this.length,endPoint=Math.min(this.length,this._readOffset+lengthVal),value=this._buff.slice(this._readOffset,endPoint);return this._readOffset=endPoint,value}insertBuffer(value,offset){return utils_1.checkOffsetValue(offset),this._handleBuffer(value,!0,offset)}writeBuffer(value,offset){return this._handleBuffer(value,!1,offset)}readBufferNT(){let nullPos=this.length;for(let i=this._readOffset;i<this.length;i++)if(this._buff[i]===0){nullPos=i;break}let value=this._buff.slice(this._readOffset,nullPos);return this._readOffset=nullPos+1,value}insertBufferNT(value,offset){return utils_1.checkOffsetValue(offset),this.insertBuffer(value,offset),this.insertUInt8(0,offset+value.length),this}writeBufferNT(value,offset){return typeof offset<"u"&&utils_1.checkOffsetValue(offset),this.writeBuffer(value,offset),this.writeUInt8(0,typeof offset=="number"?offset+value.length:this._writeOffset),this}clear(){return this._writeOffset=0,this._readOffset=0,this.length=0,this}remaining(){return this.length-this._readOffset}get readOffset(){return this._readOffset}set readOffset(offset){utils_1.checkOffsetValue(offset),utils_1.checkTargetOffset(offset,this),this._readOffset=offset}get writeOffset(){return this._writeOffset}set writeOffset(offset){utils_1.checkOffsetValue(offset),utils_1.checkTargetOffset(offset,this),this._writeOffset=offset}get encoding(){return this._encoding}set encoding(encoding){utils_1.checkEncoding(encoding),this._encoding=encoding}get internalBuffer(){return this._buff}toBuffer(){return this._buff.slice(0,this.length)}toString(encoding){let encodingVal=typeof encoding=="string"?encoding:this._encoding;return utils_1.checkEncoding(encodingVal),this._buff.toString(encodingVal,0,this.length)}destroy(){return this.clear(),this}_handleString(value,isInsert,arg3,encoding){let offsetVal=this._writeOffset,encodingVal=this._encoding;typeof arg3=="number"?offsetVal=arg3:typeof arg3=="string"&&(utils_1.checkEncoding(arg3),encodingVal=arg3),typeof encoding=="string"&&(utils_1.checkEncoding(encoding),encodingVal=encoding);let byteLength2=Buffer.byteLength(value,encodingVal);return isInsert?this.ensureInsertable(byteLength2,offsetVal):this._ensureWriteable(byteLength2,offsetVal),this._buff.write(value,offsetVal,byteLength2,encodingVal),isInsert?this._writeOffset+=byteLength2:typeof arg3=="number"?this._writeOffset=Math.max(this._writeOffset,offsetVal+byteLength2):this._writeOffset+=byteLength2,this}_handleBuffer(value,isInsert,offset){let offsetVal=typeof offset=="number"?offset:this._writeOffset;return isInsert?this.ensureInsertable(value.length,offsetVal):this._ensureWriteable(value.length,offsetVal),value.copy(this._buff,offsetVal),isInsert?this._writeOffset+=value.length:typeof offset=="number"?this._writeOffset=Math.max(this._writeOffset,offsetVal+value.length):this._writeOffset+=value.length,this}ensureReadable(length,offset){let offsetVal=this._readOffset;if(typeof offset<"u"&&(utils_1.checkOffsetValue(offset),offsetVal=offset),offsetVal<0||offsetVal+length>this.length)throw new Error(utils_1.ERRORS.INVALID_READ_BEYOND_BOUNDS)}ensureInsertable(dataLength,offset){utils_1.checkOffsetValue(offset),this._ensureCapacity(this.length+dataLength),offset<this.length&&this._buff.copy(this._buff,offset+dataLength,offset,this._buff.length),offset+dataLength>this.length?this.length=offset+dataLength:this.length+=dataLength}_ensureWriteable(dataLength,offset){let offsetVal=typeof offset=="number"?offset:this._writeOffset;this._ensureCapacity(offsetVal+dataLength),offsetVal+dataLength>this.length&&(this.length=offsetVal+dataLength)}_ensureCapacity(minLength){let oldLength=this._buff.length;if(minLength>oldLength){let data=this._buff,newLength=oldLength*3/2+1;newLength<minLength&&(newLength=minLength),this._buff=Buffer.allocUnsafe(newLength),data.copy(this._buff,0,0,oldLength)}}_readNumberValue(func,byteSize,offset){this.ensureReadable(byteSize,offset);let value=func.call(this._buff,typeof offset=="number"?offset:this._readOffset);return typeof offset>"u"&&(this._readOffset+=byteSize),value}_insertNumberValue(func,byteSize,value,offset){return utils_1.checkOffsetValue(offset),this.ensureInsertable(byteSize,offset),func.call(this._buff,value,offset),this._writeOffset+=byteSize,this}_writeNumberValue(func,byteSize,value,offset){if(typeof offset=="number"){if(offset<0)throw new Error(utils_1.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);utils_1.checkOffsetValue(offset)}let offsetVal=typeof offset=="number"?offset:this._writeOffset;return this._ensureWriteable(byteSize,offsetVal),func.call(this._buff,value,offsetVal),typeof offset=="number"?this._writeOffset=Math.max(this._writeOffset,offsetVal+byteSize):this._writeOffset+=byteSize,this}};exports.SmartBuffer=SmartBuffer}});var require_constants=__commonJS({"../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/common/constants.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.SOCKS5_NO_ACCEPTABLE_AUTH=exports.SOCKS5_CUSTOM_AUTH_END=exports.SOCKS5_CUSTOM_AUTH_START=exports.SOCKS_INCOMING_PACKET_SIZES=exports.SocksClientState=exports.Socks5Response=exports.Socks5HostType=exports.Socks5Auth=exports.Socks4Response=exports.SocksCommand=exports.ERRORS=exports.DEFAULT_TIMEOUT=void 0;var DEFAULT_TIMEOUT=3e4;exports.DEFAULT_TIMEOUT=DEFAULT_TIMEOUT;var ERRORS={InvalidSocksCommand:"An invalid SOCKS command was provided. Valid options are connect, bind, and associate.",InvalidSocksCommandForOperation:"An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.",InvalidSocksCommandChain:"An invalid SOCKS command was provided. Chaining currently only supports the connect command.",InvalidSocksClientOptionsDestination:"An invalid destination host was provided.",InvalidSocksClientOptionsExistingSocket:"An invalid existing socket was provided. This should be an instance of stream.Duplex.",InvalidSocksClientOptionsProxy:"Invalid SOCKS proxy details were provided.",InvalidSocksClientOptionsTimeout:"An invalid timeout value was provided. Please enter a value above 0 (in ms).",InvalidSocksClientOptionsProxiesLength:"At least two socks proxies must be provided for chaining.",InvalidSocksClientOptionsCustomAuthRange:"Custom auth must be a value between 0x80 and 0xFE.",InvalidSocksClientOptionsCustomAuthOptions:"When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.",NegotiationError:"Negotiation error",SocketClosed:"Socket closed",ProxyConnectionTimedOut:"Proxy connection timed out",InternalError:"SocksClient internal error (this should not happen)",InvalidSocks4HandshakeResponse:"Received invalid Socks4 handshake response",Socks4ProxyRejectedConnection:"Socks4 Proxy rejected connection",InvalidSocks4IncomingConnectionResponse:"Socks4 invalid incoming connection response",Socks4ProxyRejectedIncomingBoundConnection:"Socks4 Proxy rejected incoming bound connection",InvalidSocks5InitialHandshakeResponse:"Received invalid Socks5 initial handshake response",InvalidSocks5IntiailHandshakeSocksVersion:"Received invalid Socks5 initial handshake (invalid socks version)",InvalidSocks5InitialHandshakeNoAcceptedAuthType:"Received invalid Socks5 initial handshake (no accepted authentication type)",InvalidSocks5InitialHandshakeUnknownAuthType:"Received invalid Socks5 initial handshake (unknown authentication type)",Socks5AuthenticationFailed:"Socks5 Authentication failed",InvalidSocks5FinalHandshake:"Received invalid Socks5 final handshake response",InvalidSocks5FinalHandshakeRejected:"Socks5 proxy rejected connection",InvalidSocks5IncomingConnectionResponse:"Received invalid Socks5 incoming connection response",Socks5ProxyRejectedIncomingBoundConnection:"Socks5 Proxy rejected incoming bound connection"};exports.ERRORS=ERRORS;var SOCKS_INCOMING_PACKET_SIZES={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:hostNameLength=>hostNameLength+7,Socks4Response:8};exports.SOCKS_INCOMING_PACKET_SIZES=SOCKS_INCOMING_PACKET_SIZES;var SocksCommand;(function(SocksCommand2){SocksCommand2[SocksCommand2.connect=1]="connect",SocksCommand2[SocksCommand2.bind=2]="bind",SocksCommand2[SocksCommand2.associate=3]="associate"})(SocksCommand||(exports.SocksCommand=SocksCommand={}));var Socks4Response;(function(Socks4Response2){Socks4Response2[Socks4Response2.Granted=90]="Granted",Socks4Response2[Socks4Response2.Failed=91]="Failed",Socks4Response2[Socks4Response2.Rejected=92]="Rejected",Socks4Response2[Socks4Response2.RejectedIdent=93]="RejectedIdent"})(Socks4Response||(exports.Socks4Response=Socks4Response={}));var Socks5Auth;(function(Socks5Auth2){Socks5Auth2[Socks5Auth2.NoAuth=0]="NoAuth",Socks5Auth2[Socks5Auth2.GSSApi=1]="GSSApi",Socks5Auth2[Socks5Auth2.UserPass=2]="UserPass"})(Socks5Auth||(exports.Socks5Auth=Socks5Auth={}));var SOCKS5_CUSTOM_AUTH_START=128;exports.SOCKS5_CUSTOM_AUTH_START=SOCKS5_CUSTOM_AUTH_START;var SOCKS5_CUSTOM_AUTH_END=254;exports.SOCKS5_CUSTOM_AUTH_END=SOCKS5_CUSTOM_AUTH_END;var SOCKS5_NO_ACCEPTABLE_AUTH=255;exports.SOCKS5_NO_ACCEPTABLE_AUTH=SOCKS5_NO_ACCEPTABLE_AUTH;var Socks5Response;(function(Socks5Response2){Socks5Response2[Socks5Response2.Granted=0]="Granted",Socks5Response2[Socks5Response2.Failure=1]="Failure",Socks5Response2[Socks5Response2.NotAllowed=2]="NotAllowed",Socks5Response2[Socks5Response2.NetworkUnreachable=3]="NetworkUnreachable",Socks5Response2[Socks5Response2.HostUnreachable=4]="HostUnreachable",Socks5Response2[Socks5Response2.ConnectionRefused=5]="ConnectionRefused",Socks5Response2[Socks5Response2.TTLExpired=6]="TTLExpired",Socks5Response2[Socks5Response2.CommandNotSupported=7]="CommandNotSupported",Socks5Response2[Socks5Response2.AddressNotSupported=8]="AddressNotSupported"})(Socks5Response||(exports.Socks5Response=Socks5Response={}));var Socks5HostType;(function(Socks5HostType2){Socks5HostType2[Socks5HostType2.IPv4=1]="IPv4",Socks5HostType2[Socks5HostType2.Hostname=3]="Hostname",Socks5HostType2[Socks5HostType2.IPv6=4]="IPv6"})(Socks5HostType||(exports.Socks5HostType=Socks5HostType={}));var SocksClientState;(function(SocksClientState2){SocksClientState2[SocksClientState2.Created=0]="Created",SocksClientState2[SocksClientState2.Connecting=1]="Connecting",SocksClientState2[SocksClientState2.Connected=2]="Connected",SocksClientState2[SocksClientState2.SentInitialHandshake=3]="SentInitialHandshake",SocksClientState2[SocksClientState2.ReceivedInitialHandshakeResponse=4]="ReceivedInitialHandshakeResponse",SocksClientState2[SocksClientState2.SentAuthentication=5]="SentAuthentication",SocksClientState2[SocksClientState2.ReceivedAuthenticationResponse=6]="ReceivedAuthenticationResponse",SocksClientState2[SocksClientState2.SentFinalHandshake=7]="SentFinalHandshake",SocksClientState2[SocksClientState2.ReceivedFinalResponse=8]="ReceivedFinalResponse",SocksClientState2[SocksClientState2.BoundWaitingForConnection=9]="BoundWaitingForConnection",SocksClientState2[SocksClientState2.Established=10]="Established",SocksClientState2[SocksClientState2.Disconnected=11]="Disconnected",SocksClientState2[SocksClientState2.Error=99]="Error"})(SocksClientState||(exports.SocksClientState=SocksClientState={}))}});var require_util=__commonJS({"../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/common/util.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.shuffleArray=exports.SocksClientError=void 0;var SocksClientError=class extends Error{constructor(message,options){super(message),this.options=options}};exports.SocksClientError=SocksClientError;function shuffleArray(array2){for(let i=array2.length-1;i>0;i--){let j=Math.floor(Math.random()*(i+1));[array2[i],array2[j]]=[array2[j],array2[i]]}}exports.shuffleArray=shuffleArray}});var require_address_error=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/address-error.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.AddressError=void 0;var AddressError=class extends Error{constructor(message,parseMessage){super(message),this.name="AddressError",this.parseMessage=parseMessage}};exports.AddressError=AddressError}});var require_common2=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/common.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.isInSubnet=isInSubnet;exports.isHostInSubnet=isHostInSubnet;exports.isCorrect=isCorrect;exports.prefixLengthFromMask=prefixLengthFromMask;exports.assertByteArray=assertByteArray;exports.numberToPaddedHex=numberToPaddedHex;exports.stringToPaddedHex=stringToPaddedHex;exports.testBit=testBit;var address_error_1=require_address_error();function isInSubnet(address){return this.subnetMask<address.subnetMask?!1:isHostInSubnet.call(this,address)}function isHostInSubnet(address){return this.mask(address.subnetMask)===address.mask()}function isCorrect(defaultBits){return function(){return this.addressMinusSuffix!==this.correctForm()?!1:this.subnetMask===defaultBits&&!this.parsedSubnet?!0:this.parsedSubnet===String(this.subnetMask)}}function prefixLengthFromMask(value,totalBits){let binary=value.toString(2).padStart(totalBits,"0");if(binary.length>totalBits)throw new address_error_1.AddressError("Invalid subnet mask.");let firstZero=binary.indexOf("0");if(firstZero===-1)return totalBits;if(binary.slice(firstZero).includes("1"))throw new address_error_1.AddressError("Invalid subnet mask.");return firstZero}function assertByteArray(bytes,byteCount,family,minimum){if(bytes.length!==byteCount)throw new address_error_1.AddressError(`${family} addresses require exactly ${byteCount} bytes`);for(let i=0;i<bytes.length;i++)if(!Number.isInteger(bytes[i])||bytes[i]<minimum||bytes[i]>255)throw new address_error_1.AddressError(`All bytes must be integers between ${minimum} and 255`)}function numberToPaddedHex(number4){return number4.toString(16).padStart(2,"0")}function stringToPaddedHex(numberString){return numberToPaddedHex(parseInt(numberString,10))}function testBit(binaryValue,position){let{length}=binaryValue;if(position>length)return!1;let positionInString=length-position;return binaryValue.substring(positionInString,positionInString+1)==="1"}}});var require_constants2=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/v4/constants.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.RE_SUBNET_STRING=exports.RE_ADDRESS=exports.GROUPS=exports.BITS=void 0;exports.BITS=32;exports.GROUPS=4;exports.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/g;exports.RE_SUBNET_STRING=/\/\d{1,2}$/}});var require_ipv4=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/ipv4.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result};Object.defineProperty(exports,"__esModule",{value:!0});exports.Address4=void 0;var common=__importStar(require_common2()),constants=__importStar(require_constants2()),address_error_1=require_address_error(),isCorrect4=common.isCorrect(constants.BITS),Address4=class _Address4{constructor(address){this.addressMinusSuffix="",this.groups=constants.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=isCorrect4,this.isInSubnet=common.isInSubnet,this.isHostInSubnet=common.isHostInSubnet,this.address=address;let subnet=constants.RE_SUBNET_STRING.exec(address);if(subnet){if(this.parsedSubnet=subnet[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>constants.BITS)throw new address_error_1.AddressError("Invalid subnet mask.");address=address.replace(constants.RE_SUBNET_STRING,"")}this.addressMinusSuffix=address,this.parsedAddress=this.parse(address)}static isValid(address){try{return new _Address4(address),!0}catch{return!1}}parse(address){let groups=address.split(".");if(groups.some(group=>/^0\d/.test(group)))throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.");if(!address.match(constants.RE_ADDRESS))throw new address_error_1.AddressError("Invalid IPv4 address.");return groups}correctForm(){return this.parsedAddress.map(part=>parseInt(part,10)).join(".")}static fromAddressAndMask(address,mask){let bits=common.prefixLengthFromMask(new _Address4(mask).bigInt(),constants.BITS);return new _Address4(`${address}/${bits}`)}static fromAddressAndWildcardMask(address,wildcardMask){let wildcard=new _Address4(wildcardMask).bigInt(),allOnes=(BigInt(1)<<BigInt(constants.BITS))-BigInt(1),mask=wildcard^allOnes,bits=common.prefixLengthFromMask(mask,constants.BITS);return new _Address4(`${address}/${bits}`)}static fromWildcard(input2){let groups=input2.split(".");if(groups.length!==constants.GROUPS)throw new address_error_1.AddressError("Wildcard pattern must have 4 octets");let firstWildcard=-1;for(let i=0;i<groups.length;i++)if(groups[i]==="*")firstWildcard===-1&&(firstWildcard=i);else if(firstWildcard!==-1)throw new address_error_1.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)");let trailing=firstWildcard===-1?0:groups.length-firstWildcard,replaced=groups.map(g=>g==="*"?"0":g),subnetBits=constants.BITS-trailing*8;return new _Address4(`${replaced.join(".")}/${subnetBits}`)}static fromHex(hex3){let stripped=hex3.replace(/:/g,"");if(!/^[0-9a-fA-F]{8}$/.test(stripped))throw new address_error_1.AddressError("IPv4 hex must be exactly 8 hex digits");let groups=[];for(let i=0;i<8;i+=2)groups.push(parseInt(stripped.slice(i,i+2),16));return new _Address4(groups.join("."))}static fromInteger(integer2){if(!Number.isInteger(integer2)||integer2<0||integer2>4294967295)throw new address_error_1.AddressError("IPv4 integer must be in the range 0 to 2**32 - 1");return _Address4.fromHex(integer2.toString(16).padStart(8,"0"))}static fromArpa(arpaFormAddress){let address=arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new _Address4(address)}toHex(){return this.parsedAddress.map(part=>common.stringToPaddedHex(part)).join(":")}toArray(){return this.parsedAddress.map(part=>parseInt(part,10))}toGroup6(){let output2=[],i;for(i=0;i<constants.GROUPS;i+=2)output2.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i+1])}`);return output2.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(n=>common.stringToPaddedHex(n)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(constants.BITS-this.subnetMask)}`)}startAddress(){return _Address4.fromBigInt(this._startAddress())}startAddressExclusive(){let adjust=BigInt("1");return _Address4.fromBigInt(this._startAddress()+adjust)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(constants.BITS-this.subnetMask)}`)}endAddress(){return _Address4.fromBigInt(this._endAddress())}endAddressExclusive(){let adjust=BigInt("1");return _Address4.fromBigInt(this._endAddress()-adjust)}subnetMaskAddress(){return _Address4.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(constants.BITS-this.subnetMask)}`))}wildcardMask(){return _Address4.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(constants.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}static fromBigInt(bigInt){if(bigInt<BigInt(0)||bigInt>BigInt(4294967295))throw new address_error_1.AddressError("IPv4 BigInt must be in the range 0 to 2**32 - 1");return _Address4.fromHex(bigInt.toString(16).padStart(8,"0"))}static fromByteArray(bytes){return common.assertByteArray(bytes,4,"IPv4",0),this.fromUnsignedByteArray(bytes)}static fromUnsignedByteArray(bytes){if(bytes.length!==4)throw new address_error_1.AddressError("IPv4 addresses require exactly 4 bytes");let address=bytes.join(".");return new _Address4(address)}mask(mask){return mask===void 0&&(mask=this.subnetMask),this.getBitsBase2(0,mask)}getBitsBase2(start,end){return this.binaryZeroPad().slice(start,end)}reverseForm(options){options||(options={});let reversed=this.correctForm().split(".").reverse().join(".");return options.omitSuffix?reversed:`${reversed}.in-addr.arpa.`}isMulticast(){return this.isHostInSubnet(MULTICAST_V4)}isPrivate(){return PRIVATE_V4.some(subnet=>this.isHostInSubnet(subnet))}isLoopback(){return this.isHostInSubnet(LOOPBACK_V4)}isLinkLocal(){return this.isHostInSubnet(LINK_LOCAL_V4)}isUnspecified(){return this.isHostInSubnet(UNSPECIFIED_V4)}isBroadcast(){return this.isHostInSubnet(BROADCAST_V4)}isCGNAT(){return this.isHostInSubnet(CGNAT_V4)}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(constants.BITS,"0")),this._binaryZeroPad}groupForV6(){let segments=this.parsedAddress;return this.correctForm().replace(constants.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${segments.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${segments.slice(2,4).join(".")}</span>`)}};exports.Address4=Address4;var MULTICAST_V4=new Address4("224.0.0.0/4"),PRIVATE_V4=[new Address4("10.0.0.0/8"),new Address4("172.16.0.0/12"),new Address4("192.168.0.0/16")],LOOPBACK_V4=new Address4("127.0.0.0/8"),LINK_LOCAL_V4=new Address4("169.254.0.0/16"),UNSPECIFIED_V4=new Address4("0.0.0.0/32"),BROADCAST_V4=new Address4("255.255.255.255/32"),CGNAT_V4=new Address4("100.64.0.0/10")}});var require_constants3=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/v6/constants.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.RE_URL_WITH_PORT=exports.RE_URL=exports.RE_ZONE_STRING=exports.RE_SUBNET_STRING=exports.RE_BAD_ADDRESS=exports.RE_BAD_CHARACTERS=exports.TYPES=exports.SCOPES=exports.GROUPS=exports.BITS=void 0;exports.BITS=128;exports.GROUPS=8;exports.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};exports.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","::ffff:0:0/96":"IPv4-mapped","ff00::/8":"Multicast","fe80::/10":"Link-local unicast","fc00::/7":"Unique local","2002::/16":"6to4","2001:db8::/32":"Documentation","64:ff9b::/96":"NAT64 (well-known)","64:ff9b:1::/48":"NAT64 (local-use)"};exports.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;exports.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;exports.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;exports.RE_ZONE_STRING=/%.*$/;exports.RE_URL=/^(?:\[([0-9a-f:.]+)\]|([0-9a-f:.]+))(?:[/?#].*)?$/i;exports.RE_URL_WITH_PORT=/^\[([0-9a-f:.]+)\]:([0-9]{1,5})(?:[/?#].*)?$/i}});var require_helpers=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/v6/helpers.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.escapeHtml=escapeHtml;exports.spanAllZeroes=spanAllZeroes;exports.spanAll=spanAll;exports.spanLeadingZeroes=spanLeadingZeroes;exports.simpleGroup=simpleGroup;function escapeHtml(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function spanAllZeroes(s){return escapeHtml(s).replace(/(0+)/g,'<span class="zero">$1</span>')}function spanAll(s,offset=0){return s.split("").map((n,i)=>`<span class="digit value-${escapeHtml(n)} position-${i+offset}">${spanAllZeroes(n)}</span>`).join("")}function spanLeadingZeroesSimple(group){return escapeHtml(group).replace(/^(0+)/,'<span class="zero">$1</span>')}function spanLeadingZeroes(address){return address.split(":").map(g=>spanLeadingZeroesSimple(g)).join(":")}function simpleGroup(addressString,offset=0){return addressString.split(":").map((g,i)=>/group-v4/.test(g)?g:`<span class="hover-group group-${i+offset}">${spanLeadingZeroesSimple(g)}</span>`)}}});var require_regular_expressions=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/v6/regular-expressions.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result};Object.defineProperty(exports,"__esModule",{value:!0});exports.ADDRESS_BOUNDARY=void 0;exports.groupPossibilities=groupPossibilities;exports.padGroup=padGroup;exports.simpleRegularExpression=simpleRegularExpression;exports.possibleElisions=possibleElisions;var v6=__importStar(require_constants3());function groupPossibilities(possibilities){return`(${possibilities.join("|")})`}function padGroup(group){return group.length<4?`0{0,${4-group.length}}${group}`:group}exports.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function simpleRegularExpression(groups){let zeroIndexes=[];groups.forEach((group,i)=>{parseInt(group,16)===0&&zeroIndexes.push(i)});let possibilities=zeroIndexes.map(zeroIndex=>groups.map((group,i)=>{if(i===zeroIndex){let elision=i===0||i===v6.GROUPS-1?":":"";return groupPossibilities([padGroup(group),elision])}return padGroup(group)}).join(":"));return possibilities.push(groups.map(padGroup).join(":")),groupPossibilities(possibilities)}function possibleElisions(elidedGroups,moreLeft,moreRight){let left=moreLeft?"":":",right=moreRight?"":":",possibilities=[];!moreLeft&&!moreRight&&possibilities.push("::"),moreLeft&&moreRight&&possibilities.push(""),(moreRight&&!moreLeft||!moreRight&&moreLeft)&&possibilities.push(":"),possibilities.push(`${left}(:0{1,4}){1,${elidedGroups-1}}`),possibilities.push(`(0{1,4}:){1,${elidedGroups-1}}${right}`),possibilities.push(`(0{1,4}:){${elidedGroups-1}}0{1,4}`);for(let groups=1;groups<elidedGroups-1;groups++)for(let position=1;position<elidedGroups-groups;position++)possibilities.push(`(0{1,4}:){${position}}:(0{1,4}:){${elidedGroups-position-groups-1}}0{1,4}`);return groupPossibilities(possibilities)}}});var require_ipv6=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/ipv6.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result};Object.defineProperty(exports,"__esModule",{value:!0});exports.Address6=void 0;var common=__importStar(require_common2()),constants4=__importStar(require_constants2()),constants6=__importStar(require_constants3()),helpers=__importStar(require_helpers()),ipv4_1=require_ipv4(),regular_expressions_1=require_regular_expressions(),address_error_1=require_address_error(),common_1=require_common2(),isCorrect6=common.isCorrect(constants6.BITS);function assert2(condition){if(!condition)throw new Error("Assertion failed.")}function addCommas(number4){let r=/(\d+)(\d{3})/;for(;r.test(number4);)number4=number4.replace(r,"$1,$2");return number4}function spanLeadingZeroes4(n){return n=n.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2'),n=n.replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2'),n}function compact(address,slice){let s1=[],s2=[],i;for(i=0;i<address.length;i++)i<slice[0]?s1.push(address[i]):i>slice[1]&&s2.push(address[i]);return s1.concat(["compact"]).concat(s2)}function paddedHex(octet){return parseInt(octet,16).toString(16).padStart(4,"0")}function unsignByte(b){return b&255}var Address6=class _Address6{constructor(address,optionalGroups){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=common.isInSubnet,this.isHostInSubnet=common.isHostInSubnet,this.isCorrect=isCorrect6,optionalGroups===void 0?this.groups=constants6.GROUPS:this.groups=optionalGroups,this.address=address;let subnet=constants6.RE_SUBNET_STRING.exec(address);if(subnet){if(this.parsedSubnet=subnet[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>constants6.BITS)throw new address_error_1.AddressError("Invalid subnet mask.");address=address.replace(constants6.RE_SUBNET_STRING,"")}if(/\//.test(address))throw new address_error_1.AddressError("Invalid subnet mask.");let zone=constants6.RE_ZONE_STRING.exec(address);zone&&(this.zone=zone[0],address=address.replace(constants6.RE_ZONE_STRING,"")),this.addressMinusSuffix=address,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(address){try{return new _Address6(address),!0}catch{return!1}}static fromBigInt(bigInt){if(bigInt<BigInt(0)||bigInt>(BigInt(1)<<BigInt(constants6.BITS))-BigInt(1))throw new address_error_1.AddressError("IPv6 BigInt must be in the range 0 to 2**128 - 1");let hex3=bigInt.toString(16).padStart(32,"0"),groups=[];for(let i=0;i<constants6.GROUPS;i++)groups.push(hex3.slice(i*4,(i+1)*4));return new _Address6(groups.join(":"))}static fromURL(url2){var _a2;let host,port=null,result,error48,stripped=url2.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"");if(stripped.indexOf("[")!==-1&&stripped.indexOf("]:")!==-1){if(error48="failed to parse address with port",result=constants6.RE_URL_WITH_PORT.exec(stripped),result===null)return{error:error48,address:null,port:null};host=result[1],port=result[2]}else{if(error48="failed to parse address from URL",result=constants6.RE_URL.exec(stripped),result===null)return{error:error48,address:null,port:null};host=(_a2=result[1])!==null&&_a2!==void 0?_a2:result[2]}port?(port=parseInt(port,10),(port<0||port>65535)&&(port=null)):port=null;let address;try{address=new _Address6(host)}catch{return{error:error48,address:null,port:null}}return{address,port}}static fromAddressAndMask(address,mask){let bits=common.prefixLengthFromMask(new _Address6(mask).bigInt(),constants6.BITS);return new _Address6(`${address}/${bits}`)}static fromAddressAndWildcardMask(address,wildcardMask){let wildcard=new _Address6(wildcardMask).bigInt(),allOnes=(BigInt(1)<<BigInt(constants6.BITS))-BigInt(1),mask=wildcard^allOnes,bits=common.prefixLengthFromMask(mask,constants6.BITS);return new _Address6(`${address}/${bits}`)}static fromWildcard(input2){if(input2.includes("%")||input2.includes("/"))throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix");let halves=input2.split("::");if(halves.length>2)throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'");let groups;if(halves.length===2){let left=halves[0]===""?[]:halves[0].split(":"),right=halves[1]===""?[]:halves[1].split(":"),remaining=constants6.GROUPS-left.length-right.length;if(remaining<1)throw new address_error_1.AddressError("Wildcard pattern with '::' has too many groups");groups=[...left,...new Array(remaining).fill("0"),...right]}else groups=input2.split(":");if(groups.length!==constants6.GROUPS)throw new address_error_1.AddressError("Wildcard pattern must have 8 groups");let firstWildcard=-1;for(let i=0;i<groups.length;i++)if(groups[i]==="*")firstWildcard===-1&&(firstWildcard=i);else if(firstWildcard!==-1)throw new address_error_1.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)");let trailing=firstWildcard===-1?0:groups.length-firstWildcard,replaced=groups.map(g=>g==="*"?"0":g),subnetBits=constants6.BITS-trailing*16;return new _Address6(`${replaced.join(":")}/${subnetBits}`)}static fromAddress4(address){let address4=new ipv4_1.Address4(address),mask6=constants6.BITS-(constants4.BITS-address4.subnetMask);return new _Address6(`::ffff:${address4.correctForm()}/${mask6}`)}static fromArpa(arpaFormAddress){let address=arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/,""),semicolonAmount=7;if(address.length!==63)throw new address_error_1.AddressError("Invalid 'ip6.arpa' form.");let parts=address.split(".").reverse();for(let i=semicolonAmount;i>0;i--){let insertIndex=i*4;parts.splice(insertIndex,0,":")}return address=parts.join(""),new _Address6(address)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(mask=this.subnetMask){return this.getBitsBase2(0,mask)}possibleSubnets(subnetSize=128){let availableBits=constants6.BITS-this.subnetMask,subnetBits=Math.abs(subnetSize-constants6.BITS),subnetPowers=availableBits-subnetBits;return subnetPowers<0?"0":addCommas((BigInt("2")**BigInt(subnetPowers)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(constants6.BITS-this.subnetMask)}`)}startAddress(){return _Address6.fromBigInt(this._startAddress())}startAddressExclusive(){let adjust=BigInt("1");return _Address6.fromBigInt(this._startAddress()+adjust)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(constants6.BITS-this.subnetMask)}`)}endAddress(){return _Address6.fromBigInt(this._endAddress())}endAddressExclusive(){let adjust=BigInt("1");return _Address6.fromBigInt(this._endAddress()-adjust)}subnetMaskAddress(){return _Address6.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(constants6.BITS-this.subnetMask)}`))}wildcardMask(){return _Address6.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(constants6.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}getScope(){let type=this.getType();return type==="Multicast"||type.startsWith("Multicast ")?constants6.SCOPES[parseInt(this.getBits(12,16).toString(10),10)]||"Unknown":type==="Link-local unicast"||type==="Loopback"?"Link local":type==="Unspecified"?"Unknown":"Global"}getType(){for(let i=0;i<TYPE_SUBNETS.length;i++){let entry=TYPE_SUBNETS[i];if(this.isHostInSubnet(entry[0]))return entry[1]}return"Global unicast"}getBits(start,end){return BigInt(`0b${this.getBitsBase2(start,end)}`)}getBitsBase2(start,end){return this.binaryZeroPad().slice(start,end)}getBitsBase16(start,end){let length=end-start;if(length%4!==0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(start,end).toString(16).padStart(length/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,constants6.BITS)}reverseForm(options){options||(options={});let characters=Math.floor(this.subnetMask/4),reversed=this.canonicalForm().replace(/:/g,"").split("").slice(0,characters).reverse().join(".");return characters>0?options.omitSuffix?reversed:`${reversed}.ip6.arpa.`:options.omitSuffix?"":"ip6.arpa."}correctForm(){let i,groups=[],zeroCounter=0,zeroes=[];for(i=0;i<this.parsedAddress.length;i++){let value=parseInt(this.parsedAddress[i],16);value===0&&zeroCounter++,value!==0&&zeroCounter>0&&(zeroCounter>1&&zeroes.push([i-zeroCounter,i-1]),zeroCounter=0)}zeroCounter>1&&zeroes.push([this.parsedAddress.length-zeroCounter,this.parsedAddress.length-1]);let zeroLengths=zeroes.map(n=>n[1]-n[0]+1);if(zeroes.length>0){let index=zeroLengths.indexOf(Math.max(...zeroLengths));groups=compact(this.parsedAddress,zeroes[index])}else groups=this.parsedAddress;for(i=0;i<groups.length;i++)groups[i]!=="compact"&&(groups[i]=parseInt(groups[i],16).toString(16));let correct=groups.join(":");return correct=correct.replace(/^compact$/,"::"),correct=correct.replace(/(^compact)|(compact$)/,":"),correct=correct.replace(/compact/,""),correct}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(constants6.BITS,"0")),this._binaryZeroPad}parse4in6(address){if(address.indexOf(".")===-1)return address;let groups=address.split(":"),lastGroup=groups.slice(-1)[0],v4Octets=lastGroup.split(".");if(v4Octets.length===constants4.GROUPS&&v4Octets.every(octet=>/^\d{1,3}$/.test(octet))&&v4Octets.some(octet=>/^0\d/.test(octet))){let highlighted=v4Octets.map(spanLeadingZeroes4).join("."),prefix=groups.slice(0,-1).map(helpers.escapeHtml).join(":"),separator=groups.length>1?":":"";throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.",`${prefix}${separator}${highlighted}`)}let address4=lastGroup.match(constants4.RE_ADDRESS);if(address4){this.parsedAddress4=address4[0];let v4Suffix=this.subnetMask>=96?`/${this.subnetMask-96}`:"";this.address4=new ipv4_1.Address4(`${this.parsedAddress4}${v4Suffix}`),this.v4=!0,groups[groups.length-1]=this.address4.toGroup6(),address=groups.join(":")}return address}parse(address){address=this.parse4in6(address);let badCharacters=address.match(constants6.RE_BAD_CHARACTERS);if(badCharacters)throw new address_error_1.AddressError(`Bad character${badCharacters.length>1?"s":""} detected in address: ${badCharacters.join("")}`,address.replace(constants6.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let badAddress=address.match(constants6.RE_BAD_ADDRESS);if(badAddress)throw new address_error_1.AddressError(`Address failed regex: ${badAddress.join("")}`,address.replace(constants6.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let groups=[],halves=address.split("::");if(halves.length===2){let first=halves[0].split(":"),last=halves[1].split(":");first.length===1&&first[0]===""&&(first=[]),last.length===1&&last[0]===""&&(last=[]);let remaining=this.groups-(first.length+last.length);if(!remaining)throw new address_error_1.AddressError("Error parsing groups");this.elidedGroups=remaining,this.elisionBegin=first.length,this.elisionEnd=first.length+this.elidedGroups,groups=groups.concat(first);for(let i=0;i<remaining;i++)groups.push("0");groups=groups.concat(last)}else if(halves.length===1)groups=address.split(":"),this.elidedGroups=0;else throw new address_error_1.AddressError("Too many :: groups found");if(groups=groups.map(group=>parseInt(group,16).toString(16)),groups.length!==this.groups)throw new address_error_1.AddressError("Incorrect number of groups found");return groups}canonicalForm(){return this.parsedAddress.map(paddedHex).join(":")}decimal(){return this.parsedAddress.map(n=>parseInt(n,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(paddedHex).join("")}`)}to4(){let binary=this.binaryZeroPad().split(""),hex3=BigInt(`0b${binary.slice(96,128).join("")}`).toString(16).padStart(8,"0");if(this.subnetMask>=96){let v4Mask=this.subnetMask-96,groups=[];for(let i=0;i<8;i+=2)groups.push(parseInt(hex3.slice(i,i+2),16));return new ipv4_1.Address4(`${groups.join(".")}/${v4Mask}`)}return ipv4_1.Address4.fromHex(hex3)}to4in6(){let address4=this.to4(),correct=new _Address6(this.parsedAddress.slice(0,6).join(":"),6).correctForm(),infix="";return/:$/.test(correct)||(infix=":"),correct+infix+address4.correctForm()}inspectTeredo(){let prefix=this.getBitsBase16(0,32),udpPort=(this.getBits(80,96)^BigInt("0xffff")).toString(),server4=ipv4_1.Address4.fromHex(this.getBitsBase16(32,64)),bitsForClient4=this.getBits(96,128),client4=ipv4_1.Address4.fromHex((bitsForClient4^BigInt("0xffffffff")).toString(16).padStart(8,"0")),flagsBase2=this.getBitsBase2(64,80),coneNat=(0,common_1.testBit)(flagsBase2,15),reserved=(0,common_1.testBit)(flagsBase2,14),groupIndividual=(0,common_1.testBit)(flagsBase2,8),universalLocal=(0,common_1.testBit)(flagsBase2,9),nonce=BigInt(`0b${flagsBase2.slice(2,6)+flagsBase2.slice(8,16)}`).toString(10);return{prefix:`${prefix.slice(0,4)}:${prefix.slice(4,8)}`,server4:server4.address,client4:client4.address,flags:flagsBase2,coneNat,microsoft:{reserved,universalLocal,groupIndividual,nonce},udpPort}}inspect6to4(){let prefix=this.getBitsBase16(0,16),gateway=ipv4_1.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:prefix.slice(0,4),gateway:gateway.address}}to6to4(){if(!this.is4())return null;let addr6to4=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new _Address6(addr6to4)}static fromAddress4Nat64(address,prefix="64:ff9b::/96"){let v4=new ipv4_1.Address4(address),prefix6=new _Address6(prefix),pl=prefix6.subnetMask;if(pl!==32&&pl!==40&&pl!==48&&pl!==56&&pl!==64&&pl!==96)throw new address_error_1.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");let prefixBits=prefix6.binaryZeroPad(),v4Bits=v4.binaryZeroPad(),bits;if(pl===96)bits=prefixBits.slice(0,96)+v4Bits;else{let beforeU=64-pl;bits=[prefixBits.slice(0,pl),v4Bits.slice(0,beforeU),"00000000",v4Bits.slice(beforeU),"0".repeat(56-(32-beforeU))].join("")}let hex3=BigInt(`0b${bits}`).toString(16).padStart(32,"0"),groups=[];for(let i=0;i<8;i++)groups.push(hex3.slice(i*4,(i+1)*4));return new _Address6(groups.join(":"))}toAddress4Nat64(prefix="64:ff9b::/96"){let prefix6=new _Address6(prefix),pl=prefix6.subnetMask;if(pl!==32&&pl!==40&&pl!==48&&pl!==56&&pl!==64&&pl!==96)throw new address_error_1.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");if(!this.isHostInSubnet(prefix6))return null;let bits=this.binaryZeroPad(),v4Bits;if(pl===96)v4Bits=bits.slice(96,128);else{let beforeU=64-pl;v4Bits=bits.slice(pl,pl+beforeU)+bits.slice(72,72+(32-beforeU))}let octets=[];for(let i=0;i<4;i++)octets.push(parseInt(v4Bits.slice(i*8,(i+1)*8),2).toString());return new ipv4_1.Address4(octets.join("."))}toByteArray(){let value=this.bigInt().toString(16).padStart(constants6.BITS/4,"0"),bytes=[];for(let i=0,length=value.length;i<length;i+=2)bytes.push(parseInt(value.substring(i,i+2),16));return bytes}toUnsignedByteArray(){return this.toByteArray().map(unsignByte)}static fromByteArray(bytes){return common.assertByteArray(bytes,16,"IPv6",-128),this.fromUnsignedByteArray(bytes.map(unsignByte))}static fromUnsignedByteArray(bytes){common.assertByteArray(bytes,16,"IPv6",0);let BYTE_MAX=BigInt("256"),result=BigInt("0"),multiplier=BigInt("1");for(let i=bytes.length-1;i>=0;i--)result+=multiplier*BigInt(bytes[i].toString(10)),multiplier*=BYTE_MAX;return _Address6.fromBigInt(result)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){let embedded=this.embeddedIPv4();return embedded?embedded.isLinkLocal():this.getBitsBase2(0,64)==="1111111010000000000000000000000000000000000000000000000000000000"}isMulticast(){let embedded=this.embeddedIPv4();if(embedded)return embedded.isMulticast();let type=this.getType();return type==="Multicast"||type.startsWith("Multicast ")}is4(){return this.v4}isMapped4(){return this.isHostInSubnet(IPV4_MAPPED_SUBNET)}embeddedIPv4(){return this.isMapped4()||this.isHostInSubnet(NAT64_WELL_KNOWN_SUBNET)?this.to4():null}isTeredo(){return this.isHostInSubnet(TEREDO_SUBNET)}is6to4(){return this.isHostInSubnet(SIX_TO_FOUR_SUBNET)}isLoopback(){let embedded=this.embeddedIPv4();return embedded?embedded.isLoopback():this.getType()==="Loopback"}isULA(){return this.isHostInSubnet(ULA_SUBNET)}isPrivate(){let embedded=this.embeddedIPv4();return embedded?embedded.isPrivate():this.isULA()}isCGNAT(){let embedded=this.embeddedIPv4();return embedded?embedded.isCGNAT():!1}isBroadcast(){let embedded=this.embeddedIPv4();return embedded?embedded.isBroadcast():!1}isUnspecified(){let embedded=this.embeddedIPv4();return embedded?embedded.isUnspecified():this.getType()==="Unspecified"}isDocumentation(){return this.isHostInSubnet(DOCUMENTATION_SUBNET)}href(optionalPort){return optionalPort===void 0?optionalPort="":optionalPort=`:${optionalPort}`,`http://[${this.correctForm()}]${optionalPort}/`}link(options){options||(options={}),options.className===void 0&&(options.className=""),options.prefix===void 0&&(options.prefix="/#address="),options.v4===void 0&&(options.v4=!1);let formFunction=this.correctForm;options.v4&&(formFunction=this.to4in6);let form=formFunction.call(this),safeHref=helpers.escapeHtml(`${options.prefix}${form}`),safeForm=helpers.escapeHtml(form);if(options.className){let safeClass=helpers.escapeHtml(options.className);return`<a href="${safeHref}" class="${safeClass}">${safeForm}</a>`}return`<a href="${safeHref}">${safeForm}</a>`}group(){if(this.elidedGroups===0)return helpers.simpleGroup(this.addressMinusSuffix).join(":");assert2(typeof this.elidedGroups=="number"),assert2(typeof this.elisionBegin=="number");let output2=[],[left,right]=this.addressMinusSuffix.split("::");left.length?output2.push(...helpers.simpleGroup(left)):output2.push("");let classes=["hover-group"];for(let i=this.elisionBegin;i<this.elisionBegin+this.elidedGroups;i++)classes.push(`group-${i}`);return output2.push(`<span class="${classes.join(" ")}"></span>`),right.length?output2.push(...helpers.simpleGroup(right,this.elisionEnd)):output2.push(""),this.is4()&&(assert2(this.address4 instanceof ipv4_1.Address4),output2.pop(),output2.push(this.address4.groupForV6())),output2.join(":")}regularExpressionString(substringSearch=!1){let output2=[],address6=new _Address6(this.correctForm());if(address6.elidedGroups===0)output2.push((0,regular_expressions_1.simpleRegularExpression)(address6.parsedAddress));else if(address6.elidedGroups===constants6.GROUPS)output2.push((0,regular_expressions_1.possibleElisions)(constants6.GROUPS));else{let halves=address6.address.split("::");halves[0].length&&output2.push((0,regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))),assert2(typeof address6.elidedGroups=="number"),output2.push((0,regular_expressions_1.possibleElisions)(address6.elidedGroups,halves[0].length!==0,halves[1].length!==0)),halves[1].length&&output2.push((0,regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))),output2=[output2.join(":")]}return substringSearch||(output2=["(?=^|",regular_expressions_1.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...output2,")(?=[^\\w\\:]|",regular_expressions_1.ADDRESS_BOUNDARY,"|$)"]),output2.join("")}regularExpression(substringSearch=!1){return new RegExp(this.regularExpressionString(substringSearch),"i")}};exports.Address6=Address6;var TYPE_SUBNETS=Object.keys(constants6.TYPES).map(subnet=>[new Address6(subnet),constants6.TYPES[subnet]]),TEREDO_SUBNET=new Address6("2001::/32"),SIX_TO_FOUR_SUBNET=new Address6("2002::/16"),ULA_SUBNET=new Address6("fc00::/7"),DOCUMENTATION_SUBNET=new Address6("2001:db8::/32"),IPV4_MAPPED_SUBNET=new Address6("::ffff:0:0/96"),NAT64_WELL_KNOWN_SUBNET=new Address6("64:ff9b::/96")}});var require_ip_address=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/ip-address.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result};Object.defineProperty(exports,"__esModule",{value:!0});exports.v6=exports.AddressError=exports.Address6=exports.Address4=void 0;var ipv4_1=require_ipv4();Object.defineProperty(exports,"Address4",{enumerable:!0,get:function(){return ipv4_1.Address4}});var ipv6_1=require_ipv6();Object.defineProperty(exports,"Address6",{enumerable:!0,get:function(){return ipv6_1.Address6}});var address_error_1=require_address_error();Object.defineProperty(exports,"AddressError",{enumerable:!0,get:function(){return address_error_1.AddressError}});var helpers=__importStar(require_helpers());exports.v6={helpers}}});var require_helpers2=__commonJS({"../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/common/helpers.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.ipToBuffer=exports.int32ToIpv4=exports.ipv4ToInt32=exports.validateSocksClientChainOptions=exports.validateSocksClientOptions=void 0;var util_1=require_util(),constants_1=require_constants(),stream=__require("stream"),ip_address_1=require_ip_address(),net4=__require("net");function validateSocksClientOptions(options,acceptedCommands=["connect","bind","associate"]){if(!constants_1.SocksCommand[options.command])throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommand,options);if(acceptedCommands.indexOf(options.command)===-1)throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandForOperation,options);if(!isValidSocksRemoteHost(options.destination))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination,options);if(!isValidSocksProxy(options.proxy))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy,options);if(validateCustomProxyAuth(options.proxy,options),options.timeout&&!isValidTimeoutValue(options.timeout))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout,options);if(options.existing_socket&&!(options.existing_socket instanceof stream.Duplex))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsExistingSocket,options)}exports.validateSocksClientOptions=validateSocksClientOptions;function validateSocksClientChainOptions(options){if(options.command!=="connect")throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandChain,options);if(!isValidSocksRemoteHost(options.destination))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination,options);if(!(options.proxies&&Array.isArray(options.proxies)&&options.proxies.length>=2))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxiesLength,options);if(options.proxies.forEach(proxy=>{if(!isValidSocksProxy(proxy))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy,options);validateCustomProxyAuth(proxy,options)}),options.timeout&&!isValidTimeoutValue(options.timeout))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout,options)}exports.validateSocksClientChainOptions=validateSocksClientChainOptions;function validateCustomProxyAuth(proxy,options){if(proxy.custom_auth_method!==void 0){if(proxy.custom_auth_method<constants_1.SOCKS5_CUSTOM_AUTH_START||proxy.custom_auth_method>constants_1.SOCKS5_CUSTOM_AUTH_END)throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthRange,options);if(proxy.custom_auth_request_handler===void 0||typeof proxy.custom_auth_request_handler!="function")throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,options);if(proxy.custom_auth_response_size===void 0)throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,options);if(proxy.custom_auth_response_handler===void 0||typeof proxy.custom_auth_response_handler!="function")throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,options)}}function isValidSocksRemoteHost(remoteHost){return remoteHost&&typeof remoteHost.host=="string"&&Buffer.byteLength(remoteHost.host)<256&&typeof remoteHost.port=="number"&&remoteHost.port>=0&&remoteHost.port<=65535}function isValidSocksProxy(proxy){return proxy&&(typeof proxy.host=="string"||typeof proxy.ipaddress=="string")&&typeof proxy.port=="number"&&proxy.port>=0&&proxy.port<=65535&&(proxy.type===4||proxy.type===5)}function isValidTimeoutValue(value){return typeof value=="number"&&value>0}function ipv4ToInt32(ip){return new ip_address_1.Address4(ip).toArray().reduce((acc,part)=>(acc<<8)+part,0)>>>0}exports.ipv4ToInt32=ipv4ToInt32;function int32ToIpv4(int322){let octet1=int322>>>24&255,octet2=int322>>>16&255,octet3=int322>>>8&255,octet4=int322&255;return[octet1,octet2,octet3,octet4].join(".")}exports.int32ToIpv4=int32ToIpv4;function ipToBuffer(ip){if(net4.isIPv4(ip)){let address=new ip_address_1.Address4(ip);return Buffer.from(address.toArray())}else if(net4.isIPv6(ip)){let address=new ip_address_1.Address6(ip);return Buffer.from(address.canonicalForm().split(":").map(segment=>segment.padStart(4,"0")).join(""),"hex")}else throw new Error("Invalid IP address format")}exports.ipToBuffer=ipToBuffer}});var require_receivebuffer=__commonJS({"../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/common/receivebuffer.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.ReceiveBuffer=void 0;var ReceiveBuffer=class{constructor(size=4096){this.buffer=Buffer.allocUnsafe(size),this.offset=0,this.originalSize=size}get length(){return this.offset}append(data){if(!Buffer.isBuffer(data))throw new Error("Attempted to append a non-buffer instance to ReceiveBuffer.");if(this.offset+data.length>=this.buffer.length){let tmp=this.buffer;this.buffer=Buffer.allocUnsafe(Math.max(this.buffer.length+this.originalSize,this.buffer.length+data.length)),tmp.copy(this.buffer)}return data.copy(this.buffer,this.offset),this.offset+=data.length}peek(length){if(length>this.offset)throw new Error("Attempted to read beyond the bounds of the managed internal data.");return this.buffer.slice(0,length)}get(length){if(length>this.offset)throw new Error("Attempted to read beyond the bounds of the managed internal data.");let value=Buffer.allocUnsafe(length);return this.buffer.slice(0,length).copy(value),this.buffer.copyWithin(0,length,length+this.offset-length),this.offset-=length,value}};exports.ReceiveBuffer=ReceiveBuffer}});var require_socksclient=__commonJS({"../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/client/socksclient.js"(exports){"use strict";var __awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve5){resolve5(value)})}return new(P||(P=Promise))(function(resolve5,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve5(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0});exports.SocksClientError=exports.SocksClient=void 0;var events_1=__require("events"),net4=__require("net"),smart_buffer_1=require_smartbuffer(),constants_1=require_constants(),helpers_1=require_helpers2(),receivebuffer_1=require_receivebuffer(),util_1=require_util();Object.defineProperty(exports,"SocksClientError",{enumerable:!0,get:function(){return util_1.SocksClientError}});var ip_address_1=require_ip_address(),SocksClient=class _SocksClient extends events_1.EventEmitter{constructor(options){super(),this.options=Object.assign({},options),(0,helpers_1.validateSocksClientOptions)(options),this.setState(constants_1.SocksClientState.Created)}static createConnection(options,callback){return new Promise((resolve5,reject)=>{try{(0,helpers_1.validateSocksClientOptions)(options,["connect"])}catch(err){return typeof callback=="function"?(callback(err),resolve5(err)):reject(err)}let client2=new _SocksClient(options);client2.connect(options.existing_socket),client2.once("established",info=>{client2.removeAllListeners(),typeof callback=="function"&&callback(null,info),resolve5(info)}),client2.once("error",err=>{client2.removeAllListeners(),typeof callback=="function"?(callback(err),resolve5(err)):reject(err)})})}static createConnectionChain(options,callback){return new Promise((resolve5,reject)=>__awaiter(this,void 0,void 0,function*(){try{(0,helpers_1.validateSocksClientChainOptions)(options)}catch(err){return typeof callback=="function"?(callback(err),resolve5(err)):reject(err)}options.randomizeChain&&(0,util_1.shuffleArray)(options.proxies);try{let sock;for(let i=0;i<options.proxies.length;i++){let nextProxy=options.proxies[i],nextDestination=i===options.proxies.length-1?options.destination:{host:options.proxies[i+1].host||options.proxies[i+1].ipaddress,port:options.proxies[i+1].port},result=yield _SocksClient.createConnection({command:"connect",proxy:nextProxy,destination:nextDestination,existing_socket:sock});sock=sock||result.socket}typeof callback=="function"?(callback(null,{socket:sock}),resolve5({socket:sock})):resolve5({socket:sock})}catch(err){typeof callback=="function"?(callback(err),resolve5(err)):reject(err)}}))}static createUDPFrame(options){let buff=new smart_buffer_1.SmartBuffer;return buff.writeUInt16BE(0),buff.writeUInt8(options.frameNumber||0),net4.isIPv4(options.remoteHost.host)?(buff.writeUInt8(constants_1.Socks5HostType.IPv4),buff.writeUInt32BE((0,helpers_1.ipv4ToInt32)(options.remoteHost.host))):net4.isIPv6(options.remoteHost.host)?(buff.writeUInt8(constants_1.Socks5HostType.IPv6),buff.writeBuffer((0,helpers_1.ipToBuffer)(options.remoteHost.host))):(buff.writeUInt8(constants_1.Socks5HostType.Hostname),buff.writeUInt8(Buffer.byteLength(options.remoteHost.host)),buff.writeString(options.remoteHost.host)),buff.writeUInt16BE(options.remoteHost.port),buff.writeBuffer(options.data),buff.toBuffer()}static parseUDPFrame(data){let buff=smart_buffer_1.SmartBuffer.fromBuffer(data);buff.readOffset=2;let frameNumber=buff.readUInt8(),hostType=buff.readUInt8(),remoteHost;hostType===constants_1.Socks5HostType.IPv4?remoteHost=(0,helpers_1.int32ToIpv4)(buff.readUInt32BE()):hostType===constants_1.Socks5HostType.IPv6?remoteHost=ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm():remoteHost=buff.readString(buff.readUInt8());let remotePort=buff.readUInt16BE();return{frameNumber,remoteHost:{host:remoteHost,port:remotePort},data:buff.readBuffer()}}setState(newState){this.state!==constants_1.SocksClientState.Error&&(this.state=newState)}connect(existingSocket){this.onDataReceived=data=>this.onDataReceivedHandler(data),this.onClose=()=>this.onCloseHandler(),this.onError=err=>this.onErrorHandler(err),this.onConnect=()=>this.onConnectHandler();let timer=setTimeout(()=>this.onEstablishedTimeout(),this.options.timeout||constants_1.DEFAULT_TIMEOUT);timer.unref&&typeof timer.unref=="function"&&timer.unref(),existingSocket?this.socket=existingSocket:this.socket=new net4.Socket,this.socket.once("close",this.onClose),this.socket.once("error",this.onError),this.socket.once("connect",this.onConnect),this.socket.on("data",this.onDataReceived),this.setState(constants_1.SocksClientState.Connecting),this.receiveBuffer=new receivebuffer_1.ReceiveBuffer,existingSocket?this.socket.emit("connect"):(this.socket.connect(this.getSocketOptions()),this.options.set_tcp_nodelay!==void 0&&this.options.set_tcp_nodelay!==null&&this.socket.setNoDelay(!!this.options.set_tcp_nodelay)),this.prependOnceListener("established",info=>{setImmediate(()=>{if(this.receiveBuffer.length>0){let excessData=this.receiveBuffer.get(this.receiveBuffer.length);info.socket.emit("data",excessData)}info.socket.resume()})})}getSocketOptions(){return Object.assign(Object.assign({},this.options.socket_options),{host:this.options.proxy.host||this.options.proxy.ipaddress,port:this.options.proxy.port})}onEstablishedTimeout(){this.state!==constants_1.SocksClientState.Established&&this.state!==constants_1.SocksClientState.BoundWaitingForConnection&&this.closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut)}onConnectHandler(){this.setState(constants_1.SocksClientState.Connected),this.options.proxy.type===4?this.sendSocks4InitialHandshake():this.sendSocks5InitialHandshake(),this.setState(constants_1.SocksClientState.SentInitialHandshake)}onDataReceivedHandler(data){this.receiveBuffer.append(data),this.processData()}processData(){for(;this.state!==constants_1.SocksClientState.Established&&this.state!==constants_1.SocksClientState.Error&&this.receiveBuffer.length>=this.nextRequiredPacketBufferSize;)if(this.state===constants_1.SocksClientState.SentInitialHandshake)this.options.proxy.type===4?this.handleSocks4FinalHandshakeResponse():this.handleInitialSocks5HandshakeResponse();else if(this.state===constants_1.SocksClientState.SentAuthentication)this.handleInitialSocks5AuthenticationHandshakeResponse();else if(this.state===constants_1.SocksClientState.SentFinalHandshake)this.handleSocks5FinalHandshakeResponse();else if(this.state===constants_1.SocksClientState.BoundWaitingForConnection)this.options.proxy.type===4?this.handleSocks4IncomingConnectionResponse():this.handleSocks5IncomingConnectionResponse();else{this.closeSocket(constants_1.ERRORS.InternalError);break}}onCloseHandler(){this.closeSocket(constants_1.ERRORS.SocketClosed)}onErrorHandler(err){this.closeSocket(err.message)}removeInternalSocketHandlers(){this.socket.pause(),this.socket.removeListener("data",this.onDataReceived),this.socket.removeListener("close",this.onClose),this.socket.removeListener("error",this.onError),this.socket.removeListener("connect",this.onConnect)}closeSocket(err){this.state!==constants_1.SocksClientState.Error&&(this.setState(constants_1.SocksClientState.Error),this.socket.destroy(),this.removeInternalSocketHandlers(),this.emit("error",new util_1.SocksClientError(err,this.options)))}sendSocks4InitialHandshake(){let userId=this.options.proxy.userId||"",buff=new smart_buffer_1.SmartBuffer;buff.writeUInt8(4),buff.writeUInt8(constants_1.SocksCommand[this.options.command]),buff.writeUInt16BE(this.options.destination.port),net4.isIPv4(this.options.destination.host)?(buff.writeBuffer((0,helpers_1.ipToBuffer)(this.options.destination.host)),buff.writeStringNT(userId)):(buff.writeUInt8(0),buff.writeUInt8(0),buff.writeUInt8(0),buff.writeUInt8(1),buff.writeStringNT(userId),buff.writeStringNT(this.options.destination.host)),this.nextRequiredPacketBufferSize=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response,this.socket.write(buff.toBuffer())}handleSocks4FinalHandshakeResponse(){let data=this.receiveBuffer.get(8);if(data[1]!==constants_1.Socks4Response.Granted)this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`);else if(constants_1.SocksCommand[this.options.command]===constants_1.SocksCommand.bind){let buff=smart_buffer_1.SmartBuffer.fromBuffer(data);buff.readOffset=2;let remoteHost={port:buff.readUInt16BE(),host:(0,helpers_1.int32ToIpv4)(buff.readUInt32BE())};remoteHost.host==="0.0.0.0"&&(remoteHost.host=this.options.proxy.ipaddress),this.setState(constants_1.SocksClientState.BoundWaitingForConnection),this.emit("bound",{remoteHost,socket:this.socket})}else this.setState(constants_1.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{socket:this.socket})}handleSocks4IncomingConnectionResponse(){let data=this.receiveBuffer.get(8);if(data[1]!==constants_1.Socks4Response.Granted)this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`);else{let buff=smart_buffer_1.SmartBuffer.fromBuffer(data);buff.readOffset=2;let remoteHost={port:buff.readUInt16BE(),host:(0,helpers_1.int32ToIpv4)(buff.readUInt32BE())};this.setState(constants_1.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost,socket:this.socket})}}sendSocks5InitialHandshake(){let buff=new smart_buffer_1.SmartBuffer,supportedAuthMethods=[constants_1.Socks5Auth.NoAuth];(this.options.proxy.userId||this.options.proxy.password)&&supportedAuthMethods.push(constants_1.Socks5Auth.UserPass),this.options.proxy.custom_auth_method!==void 0&&supportedAuthMethods.push(this.options.proxy.custom_auth_method),buff.writeUInt8(5),buff.writeUInt8(supportedAuthMethods.length);for(let authMethod of supportedAuthMethods)buff.writeUInt8(authMethod);this.nextRequiredPacketBufferSize=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse,this.socket.write(buff.toBuffer()),this.setState(constants_1.SocksClientState.SentInitialHandshake)}handleInitialSocks5HandshakeResponse(){let data=this.receiveBuffer.get(2);data[0]!==5?this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion):data[1]===constants_1.SOCKS5_NO_ACCEPTABLE_AUTH?this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType):data[1]===constants_1.Socks5Auth.NoAuth?(this.socks5ChosenAuthType=constants_1.Socks5Auth.NoAuth,this.sendSocks5CommandRequest()):data[1]===constants_1.Socks5Auth.UserPass?(this.socks5ChosenAuthType=constants_1.Socks5Auth.UserPass,this.sendSocks5UserPassAuthentication()):data[1]===this.options.proxy.custom_auth_method?(this.socks5ChosenAuthType=this.options.proxy.custom_auth_method,this.sendSocks5CustomAuthentication()):this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType)}sendSocks5UserPassAuthentication(){let userId=this.options.proxy.userId||"",password=this.options.proxy.password||"",buff=new smart_buffer_1.SmartBuffer;buff.writeUInt8(1),buff.writeUInt8(Buffer.byteLength(userId)),buff.writeString(userId),buff.writeUInt8(Buffer.byteLength(password)),buff.writeString(password),this.nextRequiredPacketBufferSize=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse,this.socket.write(buff.toBuffer()),this.setState(constants_1.SocksClientState.SentAuthentication)}sendSocks5CustomAuthentication(){return __awaiter(this,void 0,void 0,function*(){this.nextRequiredPacketBufferSize=this.options.proxy.custom_auth_response_size,this.socket.write(yield this.options.proxy.custom_auth_request_handler()),this.setState(constants_1.SocksClientState.SentAuthentication)})}handleSocks5CustomAuthHandshakeResponse(data){return __awaiter(this,void 0,void 0,function*(){return yield this.options.proxy.custom_auth_response_handler(data)})}handleSocks5AuthenticationNoAuthHandshakeResponse(data){return __awaiter(this,void 0,void 0,function*(){return data[1]===0})}handleSocks5AuthenticationUserPassHandshakeResponse(data){return __awaiter(this,void 0,void 0,function*(){return data[1]===0})}handleInitialSocks5AuthenticationHandshakeResponse(){return __awaiter(this,void 0,void 0,function*(){this.setState(constants_1.SocksClientState.ReceivedAuthenticationResponse);let authResult=!1;this.socks5ChosenAuthType===constants_1.Socks5Auth.NoAuth?authResult=yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2)):this.socks5ChosenAuthType===constants_1.Socks5Auth.UserPass?authResult=yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2)):this.socks5ChosenAuthType===this.options.proxy.custom_auth_method&&(authResult=yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size))),authResult?this.sendSocks5CommandRequest():this.closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed)})}sendSocks5CommandRequest(){let buff=new smart_buffer_1.SmartBuffer;buff.writeUInt8(5),buff.writeUInt8(constants_1.SocksCommand[this.options.command]),buff.writeUInt8(0),net4.isIPv4(this.options.destination.host)?(buff.writeUInt8(constants_1.Socks5HostType.IPv4),buff.writeBuffer((0,helpers_1.ipToBuffer)(this.options.destination.host))):net4.isIPv6(this.options.destination.host)?(buff.writeUInt8(constants_1.Socks5HostType.IPv6),buff.writeBuffer((0,helpers_1.ipToBuffer)(this.options.destination.host))):(buff.writeUInt8(constants_1.Socks5HostType.Hostname),buff.writeUInt8(this.options.destination.host.length),buff.writeString(this.options.destination.host)),buff.writeUInt16BE(this.options.destination.port),this.nextRequiredPacketBufferSize=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.socket.write(buff.toBuffer()),this.setState(constants_1.SocksClientState.SentFinalHandshake)}handleSocks5FinalHandshakeResponse(){let header=this.receiveBuffer.peek(5);if(header[0]!==5||header[1]!==constants_1.Socks5Response.Granted)this.closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`);else{let addressType=header[3],remoteHost,buff;if(addressType===constants_1.Socks5HostType.IPv4){let dataNeeded=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<dataNeeded){this.nextRequiredPacketBufferSize=dataNeeded;return}buff=smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)),remoteHost={host:(0,helpers_1.int32ToIpv4)(buff.readUInt32BE()),port:buff.readUInt16BE()},remoteHost.host==="0.0.0.0"&&(remoteHost.host=this.options.proxy.ipaddress)}else if(addressType===constants_1.Socks5HostType.Hostname){let hostLength=header[4],dataNeeded=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength);if(this.receiveBuffer.length<dataNeeded){this.nextRequiredPacketBufferSize=dataNeeded;return}buff=smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5)),remoteHost={host:buff.readString(hostLength),port:buff.readUInt16BE()}}else if(addressType===constants_1.Socks5HostType.IPv6){let dataNeeded=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<dataNeeded){this.nextRequiredPacketBufferSize=dataNeeded;return}buff=smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)),remoteHost={host:ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(),port:buff.readUInt16BE()}}this.setState(constants_1.SocksClientState.ReceivedFinalResponse),constants_1.SocksCommand[this.options.command]===constants_1.SocksCommand.connect?(this.setState(constants_1.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost,socket:this.socket})):constants_1.SocksCommand[this.options.command]===constants_1.SocksCommand.bind?(this.setState(constants_1.SocksClientState.BoundWaitingForConnection),this.nextRequiredPacketBufferSize=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.emit("bound",{remoteHost,socket:this.socket})):constants_1.SocksCommand[this.options.command]===constants_1.SocksCommand.associate&&(this.setState(constants_1.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost,socket:this.socket}))}}handleSocks5IncomingConnectionResponse(){let header=this.receiveBuffer.peek(5);if(header[0]!==5||header[1]!==constants_1.Socks5Response.Granted)this.closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`);else{let addressType=header[3],remoteHost,buff;if(addressType===constants_1.Socks5HostType.IPv4){let dataNeeded=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<dataNeeded){this.nextRequiredPacketBufferSize=dataNeeded;return}buff=smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)),remoteHost={host:(0,helpers_1.int32ToIpv4)(buff.readUInt32BE()),port:buff.readUInt16BE()},remoteHost.host==="0.0.0.0"&&(remoteHost.host=this.options.proxy.ipaddress)}else if(addressType===constants_1.Socks5HostType.Hostname){let hostLength=header[4],dataNeeded=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength);if(this.receiveBuffer.length<dataNeeded){this.nextRequiredPacketBufferSize=dataNeeded;return}buff=smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5)),remoteHost={host:buff.readString(hostLength),port:buff.readUInt16BE()}}else if(addressType===constants_1.Socks5HostType.IPv6){let dataNeeded=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<dataNeeded){this.nextRequiredPacketBufferSize=dataNeeded;return}buff=smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)),remoteHost={host:ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(),port:buff.readUInt16BE()}}this.setState(constants_1.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost,socket:this.socket})}}get socksClientOptions(){return Object.assign({},this.options)}};exports.SocksClient=SocksClient}});var require_build=__commonJS({"../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/index.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});__exportStar(require_socksclient(),exports)}});var require_dist4=__commonJS({"../../node_modules/.pnpm/socks-proxy-agent@6.2.1/node_modules/socks-proxy-agent/dist/index.js"(exports){"use strict";var __awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve5){resolve5(value)})}return new(P||(P=Promise))(function(resolve5,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve5(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.SocksProxyAgent=void 0;var socks_1=require_build(),agent_base_1=require_src2(),debug_1=__importDefault(require_src()),dns_1=__importDefault(__require("dns")),tls_1=__importDefault(__require("tls")),debug=(0,debug_1.default)("socks-proxy-agent");function parseSocksProxy(opts){var _a2;let port=0,lookup=!1,type=5,host=opts.hostname||opts.host;if(host==null)throw new TypeError('No "hostname"');if(typeof opts.port=="number"?port=opts.port:typeof opts.port=="string"&&(port=parseInt(opts.port,10)),port==null&&(port=1080),opts.protocol!=null)switch(opts.protocol.replace(":","")){case"socks4":lookup=!0;case"socks4a":type=4;break;case"socks5":lookup=!0;case"socks":case"socks5h":type=5;break;default:throw new TypeError(`A "socks" protocol must be specified! Got: ${String(opts.protocol)}`)}if(typeof opts.type<"u")if(opts.type===4||opts.type===5)type=opts.type;else throw new TypeError(`"type" must be 4 or 5, got: ${String(opts.type)}`);let proxy={host,port,type},userId=(_a2=opts.userId)!==null&&_a2!==void 0?_a2:opts.username,password=opts.password;if(opts.auth!=null){let auth=opts.auth.split(":");userId=auth[0],password=auth[1]}return userId!=null&&Object.defineProperty(proxy,"userId",{value:userId,enumerable:!1}),password!=null&&Object.defineProperty(proxy,"password",{value:password,enumerable:!1}),{lookup,proxy}}var normalizeProxyOptions=input2=>{let proxyOptions;if(typeof input2=="string"?proxyOptions=new URL(input2):proxyOptions=input2,proxyOptions==null)throw new TypeError("a SOCKS proxy server `hostname` and `port` must be specified!");return proxyOptions},SocksProxyAgent=class extends agent_base_1.Agent{constructor(input2,options){var _a2;let proxyOptions=normalizeProxyOptions(input2);super(proxyOptions);let parsedProxy=parseSocksProxy(proxyOptions);this.shouldLookup=parsedProxy.lookup,this.proxy=parsedProxy.proxy,this.tlsConnectionOptions=proxyOptions.tls!=null?proxyOptions.tls:{},this.timeout=(_a2=options?.timeout)!==null&&_a2!==void 0?_a2:null}callback(req,opts){var _a2;return __awaiter(this,void 0,void 0,function*(){let{shouldLookup,proxy,timeout}=this,{host,port,lookup:lookupCallback}=opts;if(host==null)throw new Error("No `host` defined!");shouldLookup&&(host=yield new Promise((resolve5,reject)=>{(lookupCallback??dns_1.default.lookup)(host,{},(err,res)=>{err?reject(err):resolve5(res)})}));let socksOpts={proxy,destination:{host,port},command:"connect",timeout:timeout??void 0},cleanup=tlsSocket=>{req.destroy(),socket.destroy(),tlsSocket&&tlsSocket.destroy()};debug("Creating socks proxy connection: %o",socksOpts);let{socket}=yield socks_1.SocksClient.createConnection(socksOpts);if(debug("Successfully created socks proxy connection"),timeout!==null&&(socket.setTimeout(timeout),socket.on("timeout",()=>cleanup())),opts.secureEndpoint){debug("Upgrading socket connection to TLS");let servername=(_a2=opts.servername)!==null&&_a2!==void 0?_a2:opts.host,tlsSocket=tls_1.default.connect(Object.assign(Object.assign(Object.assign({},omit2(opts,"host","hostname","path","port")),{socket,servername}),this.tlsConnectionOptions));return tlsSocket.once("error",error48=>{debug("socket TLS error",error48.message),cleanup(tlsSocket)}),tlsSocket}return socket})}};exports.SocksProxyAgent=SocksProxyAgent;function omit2(obj,...keys){let ret={},key;for(key in obj)keys.includes(key)||(ret[key]=obj[key]);return ret}}});var require_websocket=__commonJS({"../../node_modules/.pnpm/@darabonba+typescript@1.0.5/node_modules/@darabonba/typescript/dist/websocket.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve5){resolve5(value)})}return new(P||(P=Promise))(function(resolve5,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve5(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__generator=exports&&exports.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol=="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=op[0]&2?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[op[0]&2,t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(t=_.trys,!(t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}},__importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.convertToWebSocketMessageType=exports.buildWebSocketURL=exports.newWebSocketClientAndConnect=exports.newDefaultWebSocketClient=exports.DefaultWebSocketClient=exports.AbstractWebSocketHandler=exports.newWebSocketResponse=exports.getWebSocketHandler=exports.getWebSocketHandshakeTimeout=exports.getWebSocketWriteTimeout=exports.getWebSocketMaxReconnectTimes=exports.getWebSocketReconnectInterval=exports.getWebSocketEnableReconnect=exports.getWebSocketPongTimeout=exports.getWebSocketPingInterval=exports.WebSocketMessageType=void 0;var crypto4=__importStar(__require("crypto")),querystring=__importStar(__require("querystring")),url_1=__require("url"),ws_1=__importDefault(__require("ws")),https_proxy_agent_1=__importDefault(require_dist()),http_proxy_agent_1=__importDefault(require_dist3()),socks_proxy_agent_1=require_dist4(),core_1=require_core(),PolyfillAbortSignal=(function(){function PolyfillAbortSignal2(){this.aborted=!1,this.listeners=[]}return PolyfillAbortSignal2.prototype.addEventListener=function(type,listener,options){var _this=this;if(type==="abort"){var wrapped=options&&options.once?function(){_this.removeListener(wrapped),listener()}:listener;this.listeners.push(wrapped)}},PolyfillAbortSignal2.prototype.removeListener=function(listener){var idx=this.listeners.indexOf(listener);idx>=0&&this.listeners.splice(idx,1)},PolyfillAbortSignal2.prototype.dispatchAbort=function(){if(!this.aborted){this.aborted=!0;var copy=this.listeners.slice();this.listeners=[],copy.forEach(function(fn){return fn()})}},PolyfillAbortSignal2})(),PolyfillAbortController=(function(){function PolyfillAbortController2(){this.signal=new PolyfillAbortSignal}return PolyfillAbortController2.prototype.abort=function(){this.signal.dispatchAbort()},PolyfillAbortController2})();function createAbortController(){return typeof AbortController<"u"?new AbortController:new PolyfillAbortController}var WebSocketMessageType;(function(WebSocketMessageType2){WebSocketMessageType2[WebSocketMessageType2.Text=0]="Text",WebSocketMessageType2[WebSocketMessageType2.Binary=1]="Binary",WebSocketMessageType2[WebSocketMessageType2.Ping=2]="Ping",WebSocketMessageType2[WebSocketMessageType2.Pong=3]="Pong",WebSocketMessageType2[WebSocketMessageType2.Close=4]="Close"})(WebSocketMessageType=exports.WebSocketMessageType||(exports.WebSocketMessageType={}));var STATE_DISCONNECTED=0,STATE_CONNECTING=1,STATE_CONNECTED=2,STATE_DISCONNECTING=3;function getWebSocketPingInterval(runtime){return runtime?.webSocketPingInterval}exports.getWebSocketPingInterval=getWebSocketPingInterval;function getWebSocketPongTimeout(runtime){return runtime?.webSocketPongTimeout}exports.getWebSocketPongTimeout=getWebSocketPongTimeout;function getWebSocketEnableReconnect(runtime){return runtime?.webSocketEnableReconnect}exports.getWebSocketEnableReconnect=getWebSocketEnableReconnect;function getWebSocketReconnectInterval(runtime){return runtime?.webSocketReconnectInterval}exports.getWebSocketReconnectInterval=getWebSocketReconnectInterval;function getWebSocketMaxReconnectTimes(runtime){return runtime?.webSocketMaxReconnectTimes}exports.getWebSocketMaxReconnectTimes=getWebSocketMaxReconnectTimes;function getWebSocketWriteTimeout(runtime){return runtime?.webSocketWriteTimeout}exports.getWebSocketWriteTimeout=getWebSocketWriteTimeout;function getWebSocketHandshakeTimeout(runtime){return runtime?.webSocketHandshakeTimeout}exports.getWebSocketHandshakeTimeout=getWebSocketHandshakeTimeout;function getWebSocketHandler(runtime){return runtime?.webSocketHandler}exports.getWebSocketHandler=getWebSocketHandler;function newWebSocketResponse(statusCode,statusMessage,headers){var fakeResponse={statusCode,statusMessage,headers},res=new core_1.Response(fakeResponse),normalizedHeaders={};return Object.keys(headers||{}).forEach(function(key){var val=headers[key];val&&(normalizedHeaders[key.toLowerCase()]=Array.isArray(val)?val[0]:"".concat(val))}),res.headers=normalizedHeaders,res}exports.newWebSocketResponse=newWebSocketResponse;var AbstractWebSocketHandler=(function(){function AbstractWebSocketHandler2(){}return AbstractWebSocketHandler2.prototype.afterConnectionEstablished=function(_session){},AbstractWebSocketHandler2.prototype.handleRawMessage=function(_session,_message){},AbstractWebSocketHandler2.prototype.handleError=function(_session,_err){},AbstractWebSocketHandler2.prototype.afterConnectionClosed=function(_session,_code,_reason){},AbstractWebSocketHandler2})();exports.AbstractWebSocketHandler=AbstractWebSocketHandler;var DefaultWebSocketClient=(function(){function DefaultWebSocketClient2(handler){if(this.stopped=!1,this.pongReceived=!1,this.state=STATE_DISCONNECTED,this.conn=null,this.session=null,this.request=null,this.runtimeObject=null,this.reconnectCount=0,this.pingTimer=null,this.pingInterval=3e4,this.reconnectInterval=5e3,this.writeTimeout=3e4,this.readTimeout=0,this.pongTimeout=5e3,this.maxReconnectTimes=5,this.reconnectLock=!1,this.abortController=null,this.messageHandlersStarted=!1,!handler)throw new Error("handler cannot be nil");this.handler=handler}return DefaultWebSocketClient2.prototype.connect=function(request,runtimeObject){return __awaiter(this,void 0,void 0,function(){var requestURL,parsed,handshakeTimeout,connectTimeout,headers,wsOptions,tlsOptions,_this=this;return __generator(this,function(_a2){if(!request)throw new Error("request cannot be nil");if(!runtimeObject)throw new Error("runtimeObject cannot be nil");if(this.request=request,this.runtimeObject=runtimeObject,this.updateTimeoutConfig(runtimeObject),this.state=STATE_CONNECTING,this.stopped=!1,this.pongReceived=!1,this.abortController&&this.abortController.abort(),this.abortController=createAbortController(),requestURL=buildWebSocketURL(request),parsed=(0,url_1.parse)(requestURL),!parsed.protocol||!parsed.host)throw this.state=STATE_DISCONNECTED,new Error("invalid websocket url: ".concat(requestURL));return handshakeTimeout=runtimeObject.webSocketHandshakeTimeout&&runtimeObject.webSocketHandshakeTimeout>0?runtimeObject.webSocketHandshakeTimeout:3e4,connectTimeout=runtimeObject.connectTimeout&&runtimeObject.connectTimeout>0?runtimeObject.connectTimeout:1e4,headers={},request.headers&&Object.keys(request.headers).forEach(function(k){var v=request.headers[k];v&&k!=="host"&&k!=="content-length"&&(headers[k]=v)}),wsOptions={handshakeTimeout,headers,rejectUnauthorized:!runtimeObject.ignoreSSL},(parsed.protocol==="wss:"||parsed.protocol==="https:")&&(tlsOptions=this.configureTLS(runtimeObject),wsOptions.rejectUnauthorized=tlsOptions.rejectUnauthorized,tlsOptions.cert&&(wsOptions.cert=tlsOptions.cert),tlsOptions.key&&(wsOptions.key=tlsOptions.key),tlsOptions.ca&&(wsOptions.ca=tlsOptions.ca)),this.configureProxy(wsOptions,parsed,runtimeObject,request),[2,new Promise(function(resolve5,reject){var timeoutId=setTimeout(function(){_this.state===STATE_CONNECTING&&(_this.state=STATE_DISCONNECTED,reject(new Error("WebSocket connection timeout")))},connectTimeout),upgradeResponse=null,ws=new ws_1.default(requestURL,wsOptions);ws.on("upgrade",function(response){upgradeResponse=response}),ws.on("open",function(){return __awaiter(_this,void 0,void 0,function(){var sessionID,requestID,err_1,statusCode,statusMessage;return __generator(this,function(_a3){switch(_a3.label){case 0:clearTimeout(timeoutId),this.conn=ws,this.state=STATE_CONNECTED,this.setupPongHandler(),this.startMessageHandlers(),this.pingInterval>0&&this.startPingPong(),sessionID=upgradeResponse?.headers["x-acs-ws-session-id"]||upgradeResponse?.headers["X-Acs-Ws-Session-Id"]||generateSessionID(),requestID=upgradeResponse?.headers["x-acs-request-id"]||upgradeResponse?.headers["X-Acs-Request-Id"]||"",this.session={sessionID:Array.isArray(sessionID)?sessionID[0]:"".concat(sessionID),requestID:Array.isArray(requestID)?requestID[0]:"".concat(requestID),connectedAt:new Date,remoteAddr:"".concat(ws.url),localAddr:"",attributes:{}},_a3.label=1;case 1:return _a3.trys.push([1,3,,5]),[4,this.handler.afterConnectionEstablished(this.session)];case 2:return _a3.sent(),[3,5];case 3:return err_1=_a3.sent(),[4,this.cleanupConnection()];case 4:return _a3.sent(),this.state=STATE_DISCONNECTED,reject(err_1),[2];case 5:return statusCode=upgradeResponse?.statusCode||101,statusMessage=upgradeResponse?.statusMessage||"Switching Protocols",resolve5(newWebSocketResponse(statusCode,statusMessage,upgradeResponse?.headers||{})),[2]}})})}),ws.on("error",function(err){clearTimeout(timeoutId),_this.state===STATE_CONNECTING&&(_this.state=STATE_DISCONNECTED,reject(err))}),ws.on("unexpected-response",function(_req,res){clearTimeout(timeoutId),_this.state=STATE_DISCONNECTED,reject(new Error("WebSocket handshake failed with status ".concat(res.statusCode)))})})]})})},DefaultWebSocketClient2.prototype.disconnect=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a2){return[2,this.disconnectInternal(1e3,"Normal closure")]})})},DefaultWebSocketClient2.prototype.disconnectInternal=function(code,reason){return __awaiter(this,void 0,void 0,function(){var conn;return __generator(this,function(_a2){switch(_a2.label){case 0:if(this.state===STATE_DISCONNECTED&&!this.abortController)return[2];if(this.state=STATE_DISCONNECTING,this.stopPingPong(),this.stopped=!0,conn=this.conn,this.conn=null,conn&&conn.readyState===ws_1.default.OPEN)try{conn.close(code,reason)}catch{}else conn&&conn.terminate();return[4,this.waitForClose(conn)];case 1:return _a2.sent(),this.session?[4,this.handler.afterConnectionClosed(this.session,code,reason)]:[3,3];case 2:_a2.sent(),_a2.label=3;case 3:return this.state=STATE_DISCONNECTED,this.abortController&&(this.abortController.abort(),this.abortController=null),[2]}})})},DefaultWebSocketClient2.prototype.reconnect=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a2){return[2,this.reconnectInternal(!1)]})})},DefaultWebSocketClient2.prototype.reconnectGracefully=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a2){return[2,this.reconnectInternal(!0)]})})},DefaultWebSocketClient2.prototype.reconnectInternal=function(graceful){var _a2,_b,_c,_d;return __awaiter(this,void 0,void 0,function(){var previousSessionID,result;return __generator(this,function(_e){switch(_e.label){case 0:if(!graceful&&this.isConnected())throw new Error("already connected");if(!((_a2=this.abortController)===null||_a2===void 0)&&_a2.signal.aborted)throw new Error("connection aborted");if(this.reconnectLock)throw new Error("reconnect already in progress");this.reconnectLock=!0,_e.label=1;case 1:if(_e.trys.push([1,,5,6]),!(!((_b=this.runtimeObject)===null||_b===void 0)&&_b.webSocketEnableReconnect))throw new Error("reconnect is disabled");if(this.reconnectCount>=this.maxReconnectTimes)throw new Error("max reconnect times reached: ".concat(this.maxReconnectTimes));if(previousSessionID="",graceful)if(!((_c=this.session)===null||_c===void 0)&&_c.sessionID)previousSessionID=this.session.sessionID;else throw new Error("graceful reconnection requires existing session ID");return[4,this.cleanupResources()];case 2:if(_e.sent(),this.stopped=!1,this.reconnectCount++,!this.request)throw new Error("request is nil, cannot reconnect");return graceful&&previousSessionID?(this.request.headers=this.request.headers||{},this.request.headers["X-Acs-Ws-Session-Id"]=previousSessionID):this.request.headers&&delete this.request.headers["X-Acs-Ws-Session-Id"],[4,this.sleepInterruptible(this.reconnectInterval)];case 3:if(_e.sent(),!((_d=this.abortController)===null||_d===void 0)&&_d.signal.aborted)throw new Error("connection aborted");return[4,this.connect(this.request,this.runtimeObject)];case 4:return result=_e.sent(),this.reconnectCount=0,[2,result];case 5:return this.reconnectLock=!1,[7];case 6:return[2]}})})},DefaultWebSocketClient2.prototype.cleanupResources=function(){return __awaiter(this,void 0,void 0,function(){var conn;return __generator(this,function(_a2){switch(_a2.label){case 0:if(this.state=STATE_DISCONNECTING,this.stopPingPong(),this.stopped=!0,conn=this.conn,this.conn=null,!conn)return[3,2];try{conn.readyState===ws_1.default.OPEN?conn.close(1001,"Reconnecting"):conn.terminate()}catch{}return[4,this.waitForClose(conn)];case 1:_a2.sent(),_a2.label=2;case 2:return this.session=null,this.messageHandlersStarted=!1,this.state=STATE_DISCONNECTED,[2]}})})},DefaultWebSocketClient2.prototype.isConnected=function(){return this.state===STATE_CONNECTED},DefaultWebSocketClient2.prototype.sendText=function(text){return __awaiter(this,void 0,void 0,function(){var conn;return __generator(this,function(_a2){switch(_a2.label){case 0:if(!this.isConnected())throw new Error("not connected");if(conn=this.conn,!conn)throw new Error("connection is nil");return[4,this.sendWithTimeout(conn,text,!1)];case 1:return _a2.sent(),[2]}})})},DefaultWebSocketClient2.prototype.sendBinary=function(data){return __awaiter(this,void 0,void 0,function(){var conn;return __generator(this,function(_a2){switch(_a2.label){case 0:if(!this.isConnected())throw new Error("not connected");if(conn=this.conn,!conn)throw new Error("connection is nil");return[4,this.sendWithTimeout(conn,data,!0)];case 1:return _a2.sent(),[2]}})})},DefaultWebSocketClient2.prototype.getSessionInfo=function(){return this.session},DefaultWebSocketClient2.prototype.close=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a2){return[2,this.disconnectInternal(1e3,"Client closed")]})})},DefaultWebSocketClient2.prototype.configureTLS=function(runtimeObject){if(runtimeObject.ignoreSSL)return{rejectUnauthorized:!1};var tlsOptions={rejectUnauthorized:!0};return runtimeObject.key&&runtimeObject.cert&&(tlsOptions.cert=runtimeObject.cert,tlsOptions.key=runtimeObject.key),runtimeObject.ca&&(tlsOptions.ca=runtimeObject.ca),tlsOptions},DefaultWebSocketClient2.prototype.configureProxy=function(wsOptions,parsed,runtimeObject,request){if(runtimeObject.socks5Proxy){this.configureSOCKS5Proxy(wsOptions,runtimeObject);return}this.configureHTTPProxy(wsOptions,parsed,runtimeObject,request)},DefaultWebSocketClient2.prototype.configureSOCKS5Proxy=function(wsOptions,runtimeObject){var socks5Proxy=runtimeObject.socks5Proxy;socks5Proxy&&(wsOptions.agent=new socks_proxy_agent_1.SocksProxyAgent(socks5Proxy))},DefaultWebSocketClient2.prototype.configureHTTPProxy=function(wsOptions,parsed,runtimeObject,request){if(parsed){for(var protocol=parsed.protocol.replace(":",""),host=parsed.hostname,noProxyList=getNoProxy(protocol,runtimeObject),_i=0,noProxyList_1=noProxyList;_i<noProxyList_1.length;_i++){var noProxyHost=noProxyList_1[_i];if(noProxyHost===host)return}var proxyURL=getHttpProxyURL(protocol,host,runtimeObject);if(proxyURL){protocol==="wss"||protocol==="https"?wsOptions.agent=(0,https_proxy_agent_1.default)(proxyURL):wsOptions.agent=(0,http_proxy_agent_1.default)(proxyURL);var parsedProxy=(0,url_1.parse)(proxyURL);parsedProxy.auth&&(request.headers=request.headers||{},request.headers["Proxy-Authorization"]="Basic ".concat(Buffer.from(parsedProxy.auth).toString("base64")))}}},DefaultWebSocketClient2.prototype.configureNetDialer=function(_wsOptions,_runtimeObject,_connectTimeout){},DefaultWebSocketClient2.prototype.updateTimeoutConfig=function(runtimeObject){this.pingInterval=runtimeObject.webSocketPingInterval&&runtimeObject.webSocketPingInterval>0?runtimeObject.webSocketPingInterval:3e4,this.reconnectInterval=runtimeObject.webSocketReconnectInterval&&runtimeObject.webSocketReconnectInterval>0?runtimeObject.webSocketReconnectInterval:5e3,this.writeTimeout=runtimeObject.webSocketWriteTimeout&&runtimeObject.webSocketWriteTimeout>0?runtimeObject.webSocketWriteTimeout:3e4,this.readTimeout=runtimeObject.readTimeout&&runtimeObject.readTimeout>0?runtimeObject.readTimeout:0,this.pongTimeout=runtimeObject.webSocketPongTimeout&&runtimeObject.webSocketPongTimeout>0?runtimeObject.webSocketPongTimeout:5e3,this.maxReconnectTimes=runtimeObject.webSocketMaxReconnectTimes&&runtimeObject.webSocketMaxReconnectTimes>0?runtimeObject.webSocketMaxReconnectTimes:5},DefaultWebSocketClient2.prototype.setupPongHandler=function(){var _this=this,conn=this.conn;conn&&conn.on("pong",function(){_this.pongReceived=!0})},DefaultWebSocketClient2.prototype.startMessageHandlers=function(){var _this=this;if(!this.messageHandlersStarted){this.messageHandlersStarted=!0;var conn=this.conn;conn&&(conn.on("message",function(data,isBinary){return __awaiter(_this,void 0,void 0,function(){var payload,msg,err_2;return __generator(this,function(_a2){switch(_a2.label){case 0:if(this.stopped)return[2];if(payload=Buffer.isBuffer(data)?data:Buffer.from(data),msg={type:isBinary?WebSocketMessageType.Binary:WebSocketMessageType.Text,payload,headers:{},timestamp:new Date},!this.session)return[2];_a2.label=1;case 1:return _a2.trys.push([1,3,,5]),[4,this.handler.handleRawMessage(this.session,msg)];case 2:return _a2.sent(),[3,5];case 3:return err_2=_a2.sent(),[4,this.handler.handleError(this.session,err_2)];case 4:return _a2.sent(),[3,5];case 5:return[2]}})})}),conn.on("close",function(code,reasonBuffer){return __awaiter(_this,void 0,void 0,function(){var reason,_a2;return __generator(this,function(_b){switch(_b.label){case 0:return this.stopped?[2]:(reason=reasonBuffer.toString(),this.session&&code!==1e3&&code!==1001?[4,this.handler.handleError(this.session,new Error("WebSocket closed: ".concat(code," ").concat(reason)))]:[3,2]);case 1:_b.sent(),_b.label=2;case 2:return!((_a2=this.runtimeObject)===null||_a2===void 0)&&_a2.webSocketEnableReconnect&&this.request&&!this.stopped&&this.reconnect().catch(function(){}),[2]}})})}),conn.on("error",function(err){return __awaiter(_this,void 0,void 0,function(){return __generator(this,function(_a2){switch(_a2.label){case 0:return this.stopped||!this.session?[2]:[4,this.handler.handleError(this.session,err)];case 1:return _a2.sent(),[2]}})})}))}},DefaultWebSocketClient2.prototype.startPingPong=function(){var _this=this;this.pingInterval<=0||(this.stopPingPong(),this.pingTimer=setInterval(function(){return __awaiter(_this,void 0,void 0,function(){var err_3,_a2;return __generator(this,function(_b){switch(_b.label){case 0:if(this.stopped||!this.conn||this.conn.readyState!==ws_1.default.OPEN)return[2];this.pongReceived=!1,_b.label=1;case 1:return _b.trys.push([1,2,,5]),this.conn.ping(),[3,5];case 2:return err_3=_b.sent(),this.session?[4,this.handler.handleError(this.session,err_3)]:[3,4];case 3:_b.sent(),_b.label=4;case 4:return[2];case 5:return[4,this.sleepInterruptible(this.pongTimeout)];case 6:return _b.sent(),!this.pongReceived&&(!((_a2=this.runtimeObject)===null||_a2===void 0)&&_a2.webSocketEnableReconnect)&&this.reconnect().catch(function(){}),[2]}})})},this.pingInterval))},DefaultWebSocketClient2.prototype.stopPingPong=function(){this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=null)},DefaultWebSocketClient2.prototype.cleanupConnection=function(){return __awaiter(this,void 0,void 0,function(){var conn;return __generator(this,function(_a2){switch(_a2.label){case 0:return this.stopPingPong(),this.stopped=!0,conn=this.conn,this.conn=null,conn?(conn.terminate(),[4,this.waitForClose(conn)]):[3,2];case 1:_a2.sent(),_a2.label=2;case 2:return[2]}})})},DefaultWebSocketClient2.prototype.sendWithTimeout=function(conn,data,binary){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a2){return[2,new Promise(function(resolve5,reject){var timer=_this.writeTimeout>0?setTimeout(function(){return reject(new Error("write timeout"))},_this.writeTimeout):null;conn.send(data,{binary},function(err){timer&&clearTimeout(timer),err?reject(err):resolve5()})})]})})},DefaultWebSocketClient2.prototype.waitForClose=function(conn){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a2){switch(_a2.label){case 0:return conn?conn.readyState===ws_1.default.CLOSED?[2]:[4,new Promise(function(resolve5){var timer=setTimeout(resolve5,5e3);conn.once("close",function(){clearTimeout(timer),resolve5()})})]:[2];case 1:return _a2.sent(),[2]}})})},DefaultWebSocketClient2.prototype.sleepInterruptible=function(ms){var _this=this;return new Promise(function(resolve5){var timer=setTimeout(resolve5,ms);_this.abortController&&_this.abortController.signal.addEventListener("abort",function(){clearTimeout(timer),resolve5()},{once:!0})})},DefaultWebSocketClient2})();exports.DefaultWebSocketClient=DefaultWebSocketClient;function newDefaultWebSocketClient(handler){return new DefaultWebSocketClient(handler)}exports.newDefaultWebSocketClient=newDefaultWebSocketClient;function newWebSocketClientAndConnect(request,runtimeObject){return __awaiter(this,void 0,void 0,function(){var handler,client2,response;return __generator(this,function(_a2){switch(_a2.label){case 0:if(!runtimeObject)throw new Error("runtimeObject cannot be nil");if(handler=runtimeObject.webSocketHandler,!handler)throw new Error("WebSocketHandler is required: please set it in runtimeObject.webSocketHandler");return client2=new DefaultWebSocketClient(handler),[4,client2.connect(request,runtimeObject)];case 1:return response=_a2.sent(),[2,{client:client2,response}]}})})}exports.newWebSocketClientAndConnect=newWebSocketClientAndConnect;function buildWebSocketURL(request){if(!request)throw new Error("request cannot be nil");var protocol=request.protocol||"ws";protocol=protocol.toLowerCase(),protocol==="http"?protocol="ws":protocol==="https"&&(protocol="wss");var domain2=request.domain;if(domain2||(domain2=request.headers.host),!domain2)throw new Error('domain is required (set in request.headers["host"] or request.domain)');var requestURL="".concat(protocol,"://").concat(domain2);if(requestURL+=request.pathname||"/",request.query&&Object.keys(request.query).length>0){var qs=querystring.stringify(request.query);qs&&(requestURL+=requestURL.indexOf("?")>=0?"&".concat(qs):"?".concat(qs))}return requestURL}exports.buildWebSocketURL=buildWebSocketURL;function convertToWebSocketMessageType(messageType){switch(messageType){case 1:return WebSocketMessageType.Text;case 2:return WebSocketMessageType.Binary;case 9:return WebSocketMessageType.Ping;case 10:return WebSocketMessageType.Pong;case 8:return WebSocketMessageType.Close;default:return WebSocketMessageType.Binary}}exports.convertToWebSocketMessageType=convertToWebSocketMessageType;function generateSessionID(){return"ws-session-".concat(Date.now()).concat(crypto4.randomBytes(4).toString("hex"))}function getNoProxy(protocol,runtime){return runtime.noProxy?runtime.noProxy.split(","):process.env.NO_PROXY?process.env.NO_PROXY.split(","):process.env.no_proxy?process.env.no_proxy.split(","):[]}function getHttpProxyURL(protocol,host,runtime){for(var noProxyList=getNoProxy(protocol,runtime),_i=0,noProxyList_2=noProxyList;_i<noProxyList_2.length;_i++){var noProxyHost=noProxyList_2[_i];if(noProxyHost===host)return null}var proxyProtocol=protocol;if(protocol==="wss"?proxyProtocol="https":protocol==="ws"&&(proxyProtocol="http"),proxyProtocol==="https"){if(runtime.httpsProxy)return runtime.httpsProxy;if(process.env.HTTPS_PROXY)return process.env.HTTPS_PROXY;if(process.env.https_proxy)return process.env.https_proxy}else{if(runtime.httpProxy)return runtime.httpProxy;if(process.env.HTTP_PROXY)return process.env.HTTP_PROXY;if(process.env.http_proxy)return process.env.http_proxy}return null}}});var require_moment=__commonJS({"../../node_modules/.pnpm/moment@2.30.1/node_modules/moment/moment.js"(exports,module){(function(global2,factory){typeof exports=="object"&&typeof module<"u"?module.exports=factory():typeof define=="function"&&define.amd?define(factory):global2.moment=factory()})(exports,(function(){"use strict";var hookCallback;function hooks(){return hookCallback.apply(null,arguments)}function setHookCallback(callback){hookCallback=callback}function isArray(input2){return input2 instanceof Array||Object.prototype.toString.call(input2)==="[object Array]"}function isObject2(input2){return input2!=null&&Object.prototype.toString.call(input2)==="[object Object]"}function hasOwnProp(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function isObjectEmpty(obj){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(obj).length===0;var k;for(k in obj)if(hasOwnProp(obj,k))return!1;return!0}function isUndefined(input2){return input2===void 0}function isNumber(input2){return typeof input2=="number"||Object.prototype.toString.call(input2)==="[object Number]"}function isDate(input2){return input2 instanceof Date||Object.prototype.toString.call(input2)==="[object Date]"}function map2(arr,fn){var res=[],i,arrLen=arr.length;for(i=0;i<arrLen;++i)res.push(fn(arr[i],i));return res}function extend2(a,b){for(var i in b)hasOwnProp(b,i)&&(a[i]=b[i]);return hasOwnProp(b,"toString")&&(a.toString=b.toString),hasOwnProp(b,"valueOf")&&(a.valueOf=b.valueOf),a}function createUTC(input2,format2,locale2,strict){return createLocalOrUTC(input2,format2,locale2,strict,!0).utc()}function defaultParsingFlags(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}}function getParsingFlags(m){return m._pf==null&&(m._pf=defaultParsingFlags()),m._pf}var some;Array.prototype.some?some=Array.prototype.some:some=function(fun){var t=Object(this),len=t.length>>>0,i;for(i=0;i<len;i++)if(i in t&&fun.call(this,t[i],i,t))return!0;return!1};function isValid2(m){var flags=null,parsedParts=!1,isNowValid=m._d&&!isNaN(m._d.getTime());if(isNowValid&&(flags=getParsingFlags(m),parsedParts=some.call(flags.parsedDateParts,function(i){return i!=null}),isNowValid=flags.overflow<0&&!flags.empty&&!flags.invalidEra&&!flags.invalidMonth&&!flags.invalidWeekday&&!flags.weekdayMismatch&&!flags.nullInput&&!flags.invalidFormat&&!flags.userInvalidated&&(!flags.meridiem||flags.meridiem&&parsedParts),m._strict&&(isNowValid=isNowValid&&flags.charsLeftOver===0&&flags.unusedTokens.length===0&&flags.bigHour===void 0)),Object.isFrozen==null||!Object.isFrozen(m))m._isValid=isNowValid;else return isNowValid;return m._isValid}function createInvalid(flags){var m=createUTC(NaN);return flags!=null?extend2(getParsingFlags(m),flags):getParsingFlags(m).userInvalidated=!0,m}var momentProperties=hooks.momentProperties=[],updateInProgress=!1;function copyConfig(to2,from2){var i,prop,val,momentPropertiesLen=momentProperties.length;if(isUndefined(from2._isAMomentObject)||(to2._isAMomentObject=from2._isAMomentObject),isUndefined(from2._i)||(to2._i=from2._i),isUndefined(from2._f)||(to2._f=from2._f),isUndefined(from2._l)||(to2._l=from2._l),isUndefined(from2._strict)||(to2._strict=from2._strict),isUndefined(from2._tzm)||(to2._tzm=from2._tzm),isUndefined(from2._isUTC)||(to2._isUTC=from2._isUTC),isUndefined(from2._offset)||(to2._offset=from2._offset),isUndefined(from2._pf)||(to2._pf=getParsingFlags(from2)),isUndefined(from2._locale)||(to2._locale=from2._locale),momentPropertiesLen>0)for(i=0;i<momentPropertiesLen;i++)prop=momentProperties[i],val=from2[prop],isUndefined(val)||(to2[prop]=val);return to2}function Moment(config2){copyConfig(this,config2),this._d=new Date(config2._d!=null?config2._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),updateInProgress===!1&&(updateInProgress=!0,hooks.updateOffset(this),updateInProgress=!1)}function isMoment(obj){return obj instanceof Moment||obj!=null&&obj._isAMomentObject!=null}function warn(msg){hooks.suppressDeprecationWarnings===!1&&typeof console<"u"&&console.warn&&console.warn("Deprecation warning: "+msg)}function deprecate(msg,fn){var firstTime=!0;return extend2(function(){if(hooks.deprecationHandler!=null&&hooks.deprecationHandler(null,msg),firstTime){var args=[],arg,i,key,argLen=arguments.length;for(i=0;i<argLen;i++){if(arg="",typeof arguments[i]=="object"){arg+=`
|
|
22
|
+
`)+4,req.outputData[0].data=req._header+first.substring(endOfHeaders),debug("Output buffer: %o",req.outputData[0].data))}return yield(0,once_1.default)(socket,"connect"),socket})}};exports.default=HttpProxyAgent}});var require_dist3=__commonJS({"../../node_modules/.pnpm/http-proxy-agent@5.0.0/node_modules/http-proxy-agent/dist/index.js"(exports,module){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}},agent_1=__importDefault(require_agent2());function createHttpProxyAgent(opts){return new agent_1.default(opts)}(function(createHttpProxyAgent2){createHttpProxyAgent2.HttpProxyAgent=agent_1.default,createHttpProxyAgent2.prototype=agent_1.default.prototype})(createHttpProxyAgent||(createHttpProxyAgent={}));module.exports=createHttpProxyAgent}});var require_utils=__commonJS({"../../node_modules/.pnpm/smart-buffer@4.2.0/node_modules/smart-buffer/build/utils.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var buffer_1=__require("buffer"),ERRORS={INVALID_ENCODING:"Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",INVALID_SMARTBUFFER_SIZE:"Invalid size provided. Size must be a valid integer greater than zero.",INVALID_SMARTBUFFER_BUFFER:"Invalid Buffer provided in SmartBufferOptions.",INVALID_SMARTBUFFER_OBJECT:"Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",INVALID_OFFSET:"An invalid offset value was provided.",INVALID_OFFSET_NON_NUMBER:"An invalid offset value was provided. A numeric value is required.",INVALID_LENGTH:"An invalid length value was provided.",INVALID_LENGTH_NON_NUMBER:"An invalid length value was provived. A numeric value is required.",INVALID_TARGET_OFFSET:"Target offset is beyond the bounds of the internal SmartBuffer data.",INVALID_TARGET_LENGTH:"Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",INVALID_READ_BEYOND_BOUNDS:"Attempted to read beyond the bounds of the managed data.",INVALID_WRITE_BEYOND_BOUNDS:"Attempted to write beyond the bounds of the managed data."};exports.ERRORS=ERRORS;function checkEncoding(encoding){if(!buffer_1.Buffer.isEncoding(encoding))throw new Error(ERRORS.INVALID_ENCODING)}exports.checkEncoding=checkEncoding;function isFiniteInteger(value){return typeof value=="number"&&isFinite(value)&&isInteger(value)}exports.isFiniteInteger=isFiniteInteger;function checkOffsetOrLengthValue(value,offset){if(typeof value=="number"){if(!isFiniteInteger(value)||value<0)throw new Error(offset?ERRORS.INVALID_OFFSET:ERRORS.INVALID_LENGTH)}else throw new Error(offset?ERRORS.INVALID_OFFSET_NON_NUMBER:ERRORS.INVALID_LENGTH_NON_NUMBER)}function checkLengthValue(length){checkOffsetOrLengthValue(length,!1)}exports.checkLengthValue=checkLengthValue;function checkOffsetValue(offset){checkOffsetOrLengthValue(offset,!0)}exports.checkOffsetValue=checkOffsetValue;function checkTargetOffset(offset,buff){if(offset<0||offset>buff.length)throw new Error(ERRORS.INVALID_TARGET_OFFSET)}exports.checkTargetOffset=checkTargetOffset;function isInteger(value){return typeof value=="number"&&isFinite(value)&&Math.floor(value)===value}function bigIntAndBufferInt64Check(bufferMethod){if(typeof BigInt>"u")throw new Error("Platform does not support JS BigInt type.");if(typeof buffer_1.Buffer.prototype[bufferMethod]>"u")throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`)}exports.bigIntAndBufferInt64Check=bigIntAndBufferInt64Check}});var require_smartbuffer=__commonJS({"../../node_modules/.pnpm/smart-buffer@4.2.0/node_modules/smart-buffer/build/smartbuffer.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var utils_1=require_utils(),DEFAULT_SMARTBUFFER_SIZE=4096,DEFAULT_SMARTBUFFER_ENCODING="utf8",SmartBuffer=class _SmartBuffer{constructor(options){if(this.length=0,this._encoding=DEFAULT_SMARTBUFFER_ENCODING,this._writeOffset=0,this._readOffset=0,_SmartBuffer.isSmartBufferOptions(options))if(options.encoding&&(utils_1.checkEncoding(options.encoding),this._encoding=options.encoding),options.size)if(utils_1.isFiniteInteger(options.size)&&options.size>0)this._buff=Buffer.allocUnsafe(options.size);else throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE);else if(options.buff)if(Buffer.isBuffer(options.buff))this._buff=options.buff,this.length=options.buff.length;else throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER);else this._buff=Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE);else{if(typeof options<"u")throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE)}}static fromSize(size,encoding){return new this({size,encoding})}static fromBuffer(buff,encoding){return new this({buff,encoding})}static fromOptions(options){return new this(options)}static isSmartBufferOptions(options){let castOptions=options;return castOptions&&(castOptions.encoding!==void 0||castOptions.size!==void 0||castOptions.buff!==void 0)}readInt8(offset){return this._readNumberValue(Buffer.prototype.readInt8,1,offset)}readInt16BE(offset){return this._readNumberValue(Buffer.prototype.readInt16BE,2,offset)}readInt16LE(offset){return this._readNumberValue(Buffer.prototype.readInt16LE,2,offset)}readInt32BE(offset){return this._readNumberValue(Buffer.prototype.readInt32BE,4,offset)}readInt32LE(offset){return this._readNumberValue(Buffer.prototype.readInt32LE,4,offset)}readBigInt64BE(offset){return utils_1.bigIntAndBufferInt64Check("readBigInt64BE"),this._readNumberValue(Buffer.prototype.readBigInt64BE,8,offset)}readBigInt64LE(offset){return utils_1.bigIntAndBufferInt64Check("readBigInt64LE"),this._readNumberValue(Buffer.prototype.readBigInt64LE,8,offset)}writeInt8(value,offset){return this._writeNumberValue(Buffer.prototype.writeInt8,1,value,offset),this}insertInt8(value,offset){return this._insertNumberValue(Buffer.prototype.writeInt8,1,value,offset)}writeInt16BE(value,offset){return this._writeNumberValue(Buffer.prototype.writeInt16BE,2,value,offset)}insertInt16BE(value,offset){return this._insertNumberValue(Buffer.prototype.writeInt16BE,2,value,offset)}writeInt16LE(value,offset){return this._writeNumberValue(Buffer.prototype.writeInt16LE,2,value,offset)}insertInt16LE(value,offset){return this._insertNumberValue(Buffer.prototype.writeInt16LE,2,value,offset)}writeInt32BE(value,offset){return this._writeNumberValue(Buffer.prototype.writeInt32BE,4,value,offset)}insertInt32BE(value,offset){return this._insertNumberValue(Buffer.prototype.writeInt32BE,4,value,offset)}writeInt32LE(value,offset){return this._writeNumberValue(Buffer.prototype.writeInt32LE,4,value,offset)}insertInt32LE(value,offset){return this._insertNumberValue(Buffer.prototype.writeInt32LE,4,value,offset)}writeBigInt64BE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigInt64BE,8,value,offset)}insertBigInt64BE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigInt64BE,8,value,offset)}writeBigInt64LE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigInt64LE,8,value,offset)}insertBigInt64LE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigInt64LE,8,value,offset)}readUInt8(offset){return this._readNumberValue(Buffer.prototype.readUInt8,1,offset)}readUInt16BE(offset){return this._readNumberValue(Buffer.prototype.readUInt16BE,2,offset)}readUInt16LE(offset){return this._readNumberValue(Buffer.prototype.readUInt16LE,2,offset)}readUInt32BE(offset){return this._readNumberValue(Buffer.prototype.readUInt32BE,4,offset)}readUInt32LE(offset){return this._readNumberValue(Buffer.prototype.readUInt32LE,4,offset)}readBigUInt64BE(offset){return utils_1.bigIntAndBufferInt64Check("readBigUInt64BE"),this._readNumberValue(Buffer.prototype.readBigUInt64BE,8,offset)}readBigUInt64LE(offset){return utils_1.bigIntAndBufferInt64Check("readBigUInt64LE"),this._readNumberValue(Buffer.prototype.readBigUInt64LE,8,offset)}writeUInt8(value,offset){return this._writeNumberValue(Buffer.prototype.writeUInt8,1,value,offset)}insertUInt8(value,offset){return this._insertNumberValue(Buffer.prototype.writeUInt8,1,value,offset)}writeUInt16BE(value,offset){return this._writeNumberValue(Buffer.prototype.writeUInt16BE,2,value,offset)}insertUInt16BE(value,offset){return this._insertNumberValue(Buffer.prototype.writeUInt16BE,2,value,offset)}writeUInt16LE(value,offset){return this._writeNumberValue(Buffer.prototype.writeUInt16LE,2,value,offset)}insertUInt16LE(value,offset){return this._insertNumberValue(Buffer.prototype.writeUInt16LE,2,value,offset)}writeUInt32BE(value,offset){return this._writeNumberValue(Buffer.prototype.writeUInt32BE,4,value,offset)}insertUInt32BE(value,offset){return this._insertNumberValue(Buffer.prototype.writeUInt32BE,4,value,offset)}writeUInt32LE(value,offset){return this._writeNumberValue(Buffer.prototype.writeUInt32LE,4,value,offset)}insertUInt32LE(value,offset){return this._insertNumberValue(Buffer.prototype.writeUInt32LE,4,value,offset)}writeBigUInt64BE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64BE,8,value,offset)}insertBigUInt64BE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64BE,8,value,offset)}writeBigUInt64LE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64LE,8,value,offset)}insertBigUInt64LE(value,offset){return utils_1.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64LE,8,value,offset)}readFloatBE(offset){return this._readNumberValue(Buffer.prototype.readFloatBE,4,offset)}readFloatLE(offset){return this._readNumberValue(Buffer.prototype.readFloatLE,4,offset)}writeFloatBE(value,offset){return this._writeNumberValue(Buffer.prototype.writeFloatBE,4,value,offset)}insertFloatBE(value,offset){return this._insertNumberValue(Buffer.prototype.writeFloatBE,4,value,offset)}writeFloatLE(value,offset){return this._writeNumberValue(Buffer.prototype.writeFloatLE,4,value,offset)}insertFloatLE(value,offset){return this._insertNumberValue(Buffer.prototype.writeFloatLE,4,value,offset)}readDoubleBE(offset){return this._readNumberValue(Buffer.prototype.readDoubleBE,8,offset)}readDoubleLE(offset){return this._readNumberValue(Buffer.prototype.readDoubleLE,8,offset)}writeDoubleBE(value,offset){return this._writeNumberValue(Buffer.prototype.writeDoubleBE,8,value,offset)}insertDoubleBE(value,offset){return this._insertNumberValue(Buffer.prototype.writeDoubleBE,8,value,offset)}writeDoubleLE(value,offset){return this._writeNumberValue(Buffer.prototype.writeDoubleLE,8,value,offset)}insertDoubleLE(value,offset){return this._insertNumberValue(Buffer.prototype.writeDoubleLE,8,value,offset)}readString(arg1,encoding){let lengthVal;typeof arg1=="number"?(utils_1.checkLengthValue(arg1),lengthVal=Math.min(arg1,this.length-this._readOffset)):(encoding=arg1,lengthVal=this.length-this._readOffset),typeof encoding<"u"&&utils_1.checkEncoding(encoding);let value=this._buff.slice(this._readOffset,this._readOffset+lengthVal).toString(encoding||this._encoding);return this._readOffset+=lengthVal,value}insertString(value,offset,encoding){return utils_1.checkOffsetValue(offset),this._handleString(value,!0,offset,encoding)}writeString(value,arg2,encoding){return this._handleString(value,!1,arg2,encoding)}readStringNT(encoding){typeof encoding<"u"&&utils_1.checkEncoding(encoding);let nullPos=this.length;for(let i=this._readOffset;i<this.length;i++)if(this._buff[i]===0){nullPos=i;break}let value=this._buff.slice(this._readOffset,nullPos);return this._readOffset=nullPos+1,value.toString(encoding||this._encoding)}insertStringNT(value,offset,encoding){return utils_1.checkOffsetValue(offset),this.insertString(value,offset,encoding),this.insertUInt8(0,offset+value.length),this}writeStringNT(value,arg2,encoding){return this.writeString(value,arg2,encoding),this.writeUInt8(0,typeof arg2=="number"?arg2+value.length:this.writeOffset),this}readBuffer(length){typeof length<"u"&&utils_1.checkLengthValue(length);let lengthVal=typeof length=="number"?length:this.length,endPoint=Math.min(this.length,this._readOffset+lengthVal),value=this._buff.slice(this._readOffset,endPoint);return this._readOffset=endPoint,value}insertBuffer(value,offset){return utils_1.checkOffsetValue(offset),this._handleBuffer(value,!0,offset)}writeBuffer(value,offset){return this._handleBuffer(value,!1,offset)}readBufferNT(){let nullPos=this.length;for(let i=this._readOffset;i<this.length;i++)if(this._buff[i]===0){nullPos=i;break}let value=this._buff.slice(this._readOffset,nullPos);return this._readOffset=nullPos+1,value}insertBufferNT(value,offset){return utils_1.checkOffsetValue(offset),this.insertBuffer(value,offset),this.insertUInt8(0,offset+value.length),this}writeBufferNT(value,offset){return typeof offset<"u"&&utils_1.checkOffsetValue(offset),this.writeBuffer(value,offset),this.writeUInt8(0,typeof offset=="number"?offset+value.length:this._writeOffset),this}clear(){return this._writeOffset=0,this._readOffset=0,this.length=0,this}remaining(){return this.length-this._readOffset}get readOffset(){return this._readOffset}set readOffset(offset){utils_1.checkOffsetValue(offset),utils_1.checkTargetOffset(offset,this),this._readOffset=offset}get writeOffset(){return this._writeOffset}set writeOffset(offset){utils_1.checkOffsetValue(offset),utils_1.checkTargetOffset(offset,this),this._writeOffset=offset}get encoding(){return this._encoding}set encoding(encoding){utils_1.checkEncoding(encoding),this._encoding=encoding}get internalBuffer(){return this._buff}toBuffer(){return this._buff.slice(0,this.length)}toString(encoding){let encodingVal=typeof encoding=="string"?encoding:this._encoding;return utils_1.checkEncoding(encodingVal),this._buff.toString(encodingVal,0,this.length)}destroy(){return this.clear(),this}_handleString(value,isInsert,arg3,encoding){let offsetVal=this._writeOffset,encodingVal=this._encoding;typeof arg3=="number"?offsetVal=arg3:typeof arg3=="string"&&(utils_1.checkEncoding(arg3),encodingVal=arg3),typeof encoding=="string"&&(utils_1.checkEncoding(encoding),encodingVal=encoding);let byteLength2=Buffer.byteLength(value,encodingVal);return isInsert?this.ensureInsertable(byteLength2,offsetVal):this._ensureWriteable(byteLength2,offsetVal),this._buff.write(value,offsetVal,byteLength2,encodingVal),isInsert?this._writeOffset+=byteLength2:typeof arg3=="number"?this._writeOffset=Math.max(this._writeOffset,offsetVal+byteLength2):this._writeOffset+=byteLength2,this}_handleBuffer(value,isInsert,offset){let offsetVal=typeof offset=="number"?offset:this._writeOffset;return isInsert?this.ensureInsertable(value.length,offsetVal):this._ensureWriteable(value.length,offsetVal),value.copy(this._buff,offsetVal),isInsert?this._writeOffset+=value.length:typeof offset=="number"?this._writeOffset=Math.max(this._writeOffset,offsetVal+value.length):this._writeOffset+=value.length,this}ensureReadable(length,offset){let offsetVal=this._readOffset;if(typeof offset<"u"&&(utils_1.checkOffsetValue(offset),offsetVal=offset),offsetVal<0||offsetVal+length>this.length)throw new Error(utils_1.ERRORS.INVALID_READ_BEYOND_BOUNDS)}ensureInsertable(dataLength,offset){utils_1.checkOffsetValue(offset),this._ensureCapacity(this.length+dataLength),offset<this.length&&this._buff.copy(this._buff,offset+dataLength,offset,this._buff.length),offset+dataLength>this.length?this.length=offset+dataLength:this.length+=dataLength}_ensureWriteable(dataLength,offset){let offsetVal=typeof offset=="number"?offset:this._writeOffset;this._ensureCapacity(offsetVal+dataLength),offsetVal+dataLength>this.length&&(this.length=offsetVal+dataLength)}_ensureCapacity(minLength){let oldLength=this._buff.length;if(minLength>oldLength){let data=this._buff,newLength=oldLength*3/2+1;newLength<minLength&&(newLength=minLength),this._buff=Buffer.allocUnsafe(newLength),data.copy(this._buff,0,0,oldLength)}}_readNumberValue(func,byteSize,offset){this.ensureReadable(byteSize,offset);let value=func.call(this._buff,typeof offset=="number"?offset:this._readOffset);return typeof offset>"u"&&(this._readOffset+=byteSize),value}_insertNumberValue(func,byteSize,value,offset){return utils_1.checkOffsetValue(offset),this.ensureInsertable(byteSize,offset),func.call(this._buff,value,offset),this._writeOffset+=byteSize,this}_writeNumberValue(func,byteSize,value,offset){if(typeof offset=="number"){if(offset<0)throw new Error(utils_1.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);utils_1.checkOffsetValue(offset)}let offsetVal=typeof offset=="number"?offset:this._writeOffset;return this._ensureWriteable(byteSize,offsetVal),func.call(this._buff,value,offsetVal),typeof offset=="number"?this._writeOffset=Math.max(this._writeOffset,offsetVal+byteSize):this._writeOffset+=byteSize,this}};exports.SmartBuffer=SmartBuffer}});var require_constants=__commonJS({"../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/common/constants.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.SOCKS5_NO_ACCEPTABLE_AUTH=exports.SOCKS5_CUSTOM_AUTH_END=exports.SOCKS5_CUSTOM_AUTH_START=exports.SOCKS_INCOMING_PACKET_SIZES=exports.SocksClientState=exports.Socks5Response=exports.Socks5HostType=exports.Socks5Auth=exports.Socks4Response=exports.SocksCommand=exports.ERRORS=exports.DEFAULT_TIMEOUT=void 0;var DEFAULT_TIMEOUT=3e4;exports.DEFAULT_TIMEOUT=DEFAULT_TIMEOUT;var ERRORS={InvalidSocksCommand:"An invalid SOCKS command was provided. Valid options are connect, bind, and associate.",InvalidSocksCommandForOperation:"An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.",InvalidSocksCommandChain:"An invalid SOCKS command was provided. Chaining currently only supports the connect command.",InvalidSocksClientOptionsDestination:"An invalid destination host was provided.",InvalidSocksClientOptionsExistingSocket:"An invalid existing socket was provided. This should be an instance of stream.Duplex.",InvalidSocksClientOptionsProxy:"Invalid SOCKS proxy details were provided.",InvalidSocksClientOptionsTimeout:"An invalid timeout value was provided. Please enter a value above 0 (in ms).",InvalidSocksClientOptionsProxiesLength:"At least two socks proxies must be provided for chaining.",InvalidSocksClientOptionsCustomAuthRange:"Custom auth must be a value between 0x80 and 0xFE.",InvalidSocksClientOptionsCustomAuthOptions:"When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.",NegotiationError:"Negotiation error",SocketClosed:"Socket closed",ProxyConnectionTimedOut:"Proxy connection timed out",InternalError:"SocksClient internal error (this should not happen)",InvalidSocks4HandshakeResponse:"Received invalid Socks4 handshake response",Socks4ProxyRejectedConnection:"Socks4 Proxy rejected connection",InvalidSocks4IncomingConnectionResponse:"Socks4 invalid incoming connection response",Socks4ProxyRejectedIncomingBoundConnection:"Socks4 Proxy rejected incoming bound connection",InvalidSocks5InitialHandshakeResponse:"Received invalid Socks5 initial handshake response",InvalidSocks5IntiailHandshakeSocksVersion:"Received invalid Socks5 initial handshake (invalid socks version)",InvalidSocks5InitialHandshakeNoAcceptedAuthType:"Received invalid Socks5 initial handshake (no accepted authentication type)",InvalidSocks5InitialHandshakeUnknownAuthType:"Received invalid Socks5 initial handshake (unknown authentication type)",Socks5AuthenticationFailed:"Socks5 Authentication failed",InvalidSocks5FinalHandshake:"Received invalid Socks5 final handshake response",InvalidSocks5FinalHandshakeRejected:"Socks5 proxy rejected connection",InvalidSocks5IncomingConnectionResponse:"Received invalid Socks5 incoming connection response",Socks5ProxyRejectedIncomingBoundConnection:"Socks5 Proxy rejected incoming bound connection"};exports.ERRORS=ERRORS;var SOCKS_INCOMING_PACKET_SIZES={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:hostNameLength=>hostNameLength+7,Socks4Response:8};exports.SOCKS_INCOMING_PACKET_SIZES=SOCKS_INCOMING_PACKET_SIZES;var SocksCommand;(function(SocksCommand2){SocksCommand2[SocksCommand2.connect=1]="connect",SocksCommand2[SocksCommand2.bind=2]="bind",SocksCommand2[SocksCommand2.associate=3]="associate"})(SocksCommand||(exports.SocksCommand=SocksCommand={}));var Socks4Response;(function(Socks4Response2){Socks4Response2[Socks4Response2.Granted=90]="Granted",Socks4Response2[Socks4Response2.Failed=91]="Failed",Socks4Response2[Socks4Response2.Rejected=92]="Rejected",Socks4Response2[Socks4Response2.RejectedIdent=93]="RejectedIdent"})(Socks4Response||(exports.Socks4Response=Socks4Response={}));var Socks5Auth;(function(Socks5Auth2){Socks5Auth2[Socks5Auth2.NoAuth=0]="NoAuth",Socks5Auth2[Socks5Auth2.GSSApi=1]="GSSApi",Socks5Auth2[Socks5Auth2.UserPass=2]="UserPass"})(Socks5Auth||(exports.Socks5Auth=Socks5Auth={}));var SOCKS5_CUSTOM_AUTH_START=128;exports.SOCKS5_CUSTOM_AUTH_START=SOCKS5_CUSTOM_AUTH_START;var SOCKS5_CUSTOM_AUTH_END=254;exports.SOCKS5_CUSTOM_AUTH_END=SOCKS5_CUSTOM_AUTH_END;var SOCKS5_NO_ACCEPTABLE_AUTH=255;exports.SOCKS5_NO_ACCEPTABLE_AUTH=SOCKS5_NO_ACCEPTABLE_AUTH;var Socks5Response;(function(Socks5Response2){Socks5Response2[Socks5Response2.Granted=0]="Granted",Socks5Response2[Socks5Response2.Failure=1]="Failure",Socks5Response2[Socks5Response2.NotAllowed=2]="NotAllowed",Socks5Response2[Socks5Response2.NetworkUnreachable=3]="NetworkUnreachable",Socks5Response2[Socks5Response2.HostUnreachable=4]="HostUnreachable",Socks5Response2[Socks5Response2.ConnectionRefused=5]="ConnectionRefused",Socks5Response2[Socks5Response2.TTLExpired=6]="TTLExpired",Socks5Response2[Socks5Response2.CommandNotSupported=7]="CommandNotSupported",Socks5Response2[Socks5Response2.AddressNotSupported=8]="AddressNotSupported"})(Socks5Response||(exports.Socks5Response=Socks5Response={}));var Socks5HostType;(function(Socks5HostType2){Socks5HostType2[Socks5HostType2.IPv4=1]="IPv4",Socks5HostType2[Socks5HostType2.Hostname=3]="Hostname",Socks5HostType2[Socks5HostType2.IPv6=4]="IPv6"})(Socks5HostType||(exports.Socks5HostType=Socks5HostType={}));var SocksClientState;(function(SocksClientState2){SocksClientState2[SocksClientState2.Created=0]="Created",SocksClientState2[SocksClientState2.Connecting=1]="Connecting",SocksClientState2[SocksClientState2.Connected=2]="Connected",SocksClientState2[SocksClientState2.SentInitialHandshake=3]="SentInitialHandshake",SocksClientState2[SocksClientState2.ReceivedInitialHandshakeResponse=4]="ReceivedInitialHandshakeResponse",SocksClientState2[SocksClientState2.SentAuthentication=5]="SentAuthentication",SocksClientState2[SocksClientState2.ReceivedAuthenticationResponse=6]="ReceivedAuthenticationResponse",SocksClientState2[SocksClientState2.SentFinalHandshake=7]="SentFinalHandshake",SocksClientState2[SocksClientState2.ReceivedFinalResponse=8]="ReceivedFinalResponse",SocksClientState2[SocksClientState2.BoundWaitingForConnection=9]="BoundWaitingForConnection",SocksClientState2[SocksClientState2.Established=10]="Established",SocksClientState2[SocksClientState2.Disconnected=11]="Disconnected",SocksClientState2[SocksClientState2.Error=99]="Error"})(SocksClientState||(exports.SocksClientState=SocksClientState={}))}});var require_util=__commonJS({"../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/common/util.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.shuffleArray=exports.SocksClientError=void 0;var SocksClientError=class extends Error{constructor(message,options){super(message),this.options=options}};exports.SocksClientError=SocksClientError;function shuffleArray(array2){for(let i=array2.length-1;i>0;i--){let j=Math.floor(Math.random()*(i+1));[array2[i],array2[j]]=[array2[j],array2[i]]}}exports.shuffleArray=shuffleArray}});var require_address_error=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/address-error.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.AddressError=void 0;var AddressError=class extends Error{constructor(message,parseMessage){super(message),this.name="AddressError",this.parseMessage=parseMessage}};exports.AddressError=AddressError}});var require_common2=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/common.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.isInSubnet=isInSubnet;exports.isHostInSubnet=isHostInSubnet;exports.isCorrect=isCorrect;exports.prefixLengthFromMask=prefixLengthFromMask;exports.assertByteArray=assertByteArray;exports.numberToPaddedHex=numberToPaddedHex;exports.stringToPaddedHex=stringToPaddedHex;exports.testBit=testBit;var address_error_1=require_address_error();function isInSubnet(address){return this.subnetMask<address.subnetMask?!1:isHostInSubnet.call(this,address)}function isHostInSubnet(address){return this.mask(address.subnetMask)===address.mask()}function isCorrect(defaultBits){return function(){return this.addressMinusSuffix!==this.correctForm()?!1:this.subnetMask===defaultBits&&!this.parsedSubnet?!0:this.parsedSubnet===String(this.subnetMask)}}function prefixLengthFromMask(value,totalBits){let binary=value.toString(2).padStart(totalBits,"0");if(binary.length>totalBits)throw new address_error_1.AddressError("Invalid subnet mask.");let firstZero=binary.indexOf("0");if(firstZero===-1)return totalBits;if(binary.slice(firstZero).includes("1"))throw new address_error_1.AddressError("Invalid subnet mask.");return firstZero}function assertByteArray(bytes,byteCount,family,minimum){if(bytes.length!==byteCount)throw new address_error_1.AddressError(`${family} addresses require exactly ${byteCount} bytes`);for(let i=0;i<bytes.length;i++)if(!Number.isInteger(bytes[i])||bytes[i]<minimum||bytes[i]>255)throw new address_error_1.AddressError(`All bytes must be integers between ${minimum} and 255`)}function numberToPaddedHex(number4){return number4.toString(16).padStart(2,"0")}function stringToPaddedHex(numberString){return numberToPaddedHex(parseInt(numberString,10))}function testBit(binaryValue,position){let{length}=binaryValue;if(position>length)return!1;let positionInString=length-position;return binaryValue.substring(positionInString,positionInString+1)==="1"}}});var require_constants2=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/v4/constants.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.RE_SUBNET_STRING=exports.RE_ADDRESS=exports.GROUPS=exports.BITS=void 0;exports.BITS=32;exports.GROUPS=4;exports.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/g;exports.RE_SUBNET_STRING=/\/\d{1,2}$/}});var require_ipv4=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/ipv4.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result};Object.defineProperty(exports,"__esModule",{value:!0});exports.Address4=void 0;var common=__importStar(require_common2()),constants=__importStar(require_constants2()),address_error_1=require_address_error(),isCorrect4=common.isCorrect(constants.BITS),Address4=class _Address4{constructor(address){this.addressMinusSuffix="",this.groups=constants.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=isCorrect4,this.isInSubnet=common.isInSubnet,this.isHostInSubnet=common.isHostInSubnet,this.address=address;let subnet=constants.RE_SUBNET_STRING.exec(address);if(subnet){if(this.parsedSubnet=subnet[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>constants.BITS)throw new address_error_1.AddressError("Invalid subnet mask.");address=address.replace(constants.RE_SUBNET_STRING,"")}this.addressMinusSuffix=address,this.parsedAddress=this.parse(address)}static isValid(address){try{return new _Address4(address),!0}catch{return!1}}parse(address){let groups=address.split(".");if(groups.some(group=>/^0\d/.test(group)))throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.");if(!address.match(constants.RE_ADDRESS))throw new address_error_1.AddressError("Invalid IPv4 address.");return groups}correctForm(){return this.parsedAddress.map(part=>parseInt(part,10)).join(".")}static fromAddressAndMask(address,mask){let bits=common.prefixLengthFromMask(new _Address4(mask).bigInt(),constants.BITS);return new _Address4(`${address}/${bits}`)}static fromAddressAndWildcardMask(address,wildcardMask){let wildcard=new _Address4(wildcardMask).bigInt(),allOnes=(BigInt(1)<<BigInt(constants.BITS))-BigInt(1),mask=wildcard^allOnes,bits=common.prefixLengthFromMask(mask,constants.BITS);return new _Address4(`${address}/${bits}`)}static fromWildcard(input2){let groups=input2.split(".");if(groups.length!==constants.GROUPS)throw new address_error_1.AddressError("Wildcard pattern must have 4 octets");let firstWildcard=-1;for(let i=0;i<groups.length;i++)if(groups[i]==="*")firstWildcard===-1&&(firstWildcard=i);else if(firstWildcard!==-1)throw new address_error_1.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)");let trailing=firstWildcard===-1?0:groups.length-firstWildcard,replaced=groups.map(g=>g==="*"?"0":g),subnetBits=constants.BITS-trailing*8;return new _Address4(`${replaced.join(".")}/${subnetBits}`)}static fromHex(hex3){let stripped=hex3.replace(/:/g,"");if(!/^[0-9a-fA-F]{8}$/.test(stripped))throw new address_error_1.AddressError("IPv4 hex must be exactly 8 hex digits");let groups=[];for(let i=0;i<8;i+=2)groups.push(parseInt(stripped.slice(i,i+2),16));return new _Address4(groups.join("."))}static fromInteger(integer2){if(!Number.isInteger(integer2)||integer2<0||integer2>4294967295)throw new address_error_1.AddressError("IPv4 integer must be in the range 0 to 2**32 - 1");return _Address4.fromHex(integer2.toString(16).padStart(8,"0"))}static fromArpa(arpaFormAddress){let address=arpaFormAddress.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new _Address4(address)}toHex(){return this.parsedAddress.map(part=>common.stringToPaddedHex(part)).join(":")}toArray(){return this.parsedAddress.map(part=>parseInt(part,10))}toGroup6(){let output2=[],i;for(i=0;i<constants.GROUPS;i+=2)output2.push(`${common.stringToPaddedHex(this.parsedAddress[i])}${common.stringToPaddedHex(this.parsedAddress[i+1])}`);return output2.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(n=>common.stringToPaddedHex(n)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(constants.BITS-this.subnetMask)}`)}startAddress(){return _Address4.fromBigInt(this._startAddress())}startAddressExclusive(){let adjust=BigInt("1");return _Address4.fromBigInt(this._startAddress()+adjust)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(constants.BITS-this.subnetMask)}`)}endAddress(){return _Address4.fromBigInt(this._endAddress())}endAddressExclusive(){let adjust=BigInt("1");return _Address4.fromBigInt(this._endAddress()-adjust)}subnetMaskAddress(){return _Address4.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(constants.BITS-this.subnetMask)}`))}wildcardMask(){return _Address4.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(constants.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}static fromBigInt(bigInt){if(bigInt<BigInt(0)||bigInt>BigInt(4294967295))throw new address_error_1.AddressError("IPv4 BigInt must be in the range 0 to 2**32 - 1");return _Address4.fromHex(bigInt.toString(16).padStart(8,"0"))}static fromByteArray(bytes){return common.assertByteArray(bytes,4,"IPv4",0),this.fromUnsignedByteArray(bytes)}static fromUnsignedByteArray(bytes){if(bytes.length!==4)throw new address_error_1.AddressError("IPv4 addresses require exactly 4 bytes");let address=bytes.join(".");return new _Address4(address)}mask(mask){return mask===void 0&&(mask=this.subnetMask),this.getBitsBase2(0,mask)}getBitsBase2(start,end){return this.binaryZeroPad().slice(start,end)}reverseForm(options){options||(options={});let reversed=this.correctForm().split(".").reverse().join(".");return options.omitSuffix?reversed:`${reversed}.in-addr.arpa.`}isMulticast(){return this.isHostInSubnet(MULTICAST_V4)}isPrivate(){return PRIVATE_V4.some(subnet=>this.isHostInSubnet(subnet))}isLoopback(){return this.isHostInSubnet(LOOPBACK_V4)}isLinkLocal(){return this.isHostInSubnet(LINK_LOCAL_V4)}isUnspecified(){return this.isHostInSubnet(UNSPECIFIED_V4)}isBroadcast(){return this.isHostInSubnet(BROADCAST_V4)}isCGNAT(){return this.isHostInSubnet(CGNAT_V4)}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(constants.BITS,"0")),this._binaryZeroPad}groupForV6(){let segments=this.parsedAddress;return this.correctForm().replace(constants.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${segments.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${segments.slice(2,4).join(".")}</span>`)}};exports.Address4=Address4;var MULTICAST_V4=new Address4("224.0.0.0/4"),PRIVATE_V4=[new Address4("10.0.0.0/8"),new Address4("172.16.0.0/12"),new Address4("192.168.0.0/16")],LOOPBACK_V4=new Address4("127.0.0.0/8"),LINK_LOCAL_V4=new Address4("169.254.0.0/16"),UNSPECIFIED_V4=new Address4("0.0.0.0/32"),BROADCAST_V4=new Address4("255.255.255.255/32"),CGNAT_V4=new Address4("100.64.0.0/10")}});var require_constants3=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/v6/constants.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.RE_URL_WITH_PORT=exports.RE_URL=exports.RE_ZONE_STRING=exports.RE_SUBNET_STRING=exports.RE_BAD_ADDRESS=exports.RE_BAD_CHARACTERS=exports.TYPES=exports.SCOPES=exports.GROUPS=exports.BITS=void 0;exports.BITS=128;exports.GROUPS=8;exports.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};exports.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","::ffff:0:0/96":"IPv4-mapped","ff00::/8":"Multicast","fe80::/10":"Link-local unicast","fc00::/7":"Unique local","2002::/16":"6to4","2001:db8::/32":"Documentation","64:ff9b::/96":"NAT64 (well-known)","64:ff9b:1::/48":"NAT64 (local-use)"};exports.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;exports.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;exports.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;exports.RE_ZONE_STRING=/%.*$/;exports.RE_URL=/^(?:\[([0-9a-f:.]+)\]|([0-9a-f:.]+))(?:[/?#].*)?$/i;exports.RE_URL_WITH_PORT=/^\[([0-9a-f:.]+)\]:([0-9]{1,5})(?:[/?#].*)?$/i}});var require_helpers=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/v6/helpers.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.escapeHtml=escapeHtml;exports.spanAllZeroes=spanAllZeroes;exports.spanAll=spanAll;exports.spanLeadingZeroes=spanLeadingZeroes;exports.simpleGroup=simpleGroup;function escapeHtml(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function spanAllZeroes(s){return escapeHtml(s).replace(/(0+)/g,'<span class="zero">$1</span>')}function spanAll(s,offset=0){return s.split("").map((n,i)=>`<span class="digit value-${escapeHtml(n)} position-${i+offset}">${spanAllZeroes(n)}</span>`).join("")}function spanLeadingZeroesSimple(group){return escapeHtml(group).replace(/^(0+)/,'<span class="zero">$1</span>')}function spanLeadingZeroes(address){return address.split(":").map(g=>spanLeadingZeroesSimple(g)).join(":")}function simpleGroup(addressString,offset=0){return addressString.split(":").map((g,i)=>/group-v4/.test(g)?g:`<span class="hover-group group-${i+offset}">${spanLeadingZeroesSimple(g)}</span>`)}}});var require_regular_expressions=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/v6/regular-expressions.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result};Object.defineProperty(exports,"__esModule",{value:!0});exports.ADDRESS_BOUNDARY=void 0;exports.groupPossibilities=groupPossibilities;exports.padGroup=padGroup;exports.simpleRegularExpression=simpleRegularExpression;exports.possibleElisions=possibleElisions;var v6=__importStar(require_constants3());function groupPossibilities(possibilities){return`(${possibilities.join("|")})`}function padGroup(group){return group.length<4?`0{0,${4-group.length}}${group}`:group}exports.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function simpleRegularExpression(groups){let zeroIndexes=[];groups.forEach((group,i)=>{parseInt(group,16)===0&&zeroIndexes.push(i)});let possibilities=zeroIndexes.map(zeroIndex=>groups.map((group,i)=>{if(i===zeroIndex){let elision=i===0||i===v6.GROUPS-1?":":"";return groupPossibilities([padGroup(group),elision])}return padGroup(group)}).join(":"));return possibilities.push(groups.map(padGroup).join(":")),groupPossibilities(possibilities)}function possibleElisions(elidedGroups,moreLeft,moreRight){let left=moreLeft?"":":",right=moreRight?"":":",possibilities=[];!moreLeft&&!moreRight&&possibilities.push("::"),moreLeft&&moreRight&&possibilities.push(""),(moreRight&&!moreLeft||!moreRight&&moreLeft)&&possibilities.push(":"),possibilities.push(`${left}(:0{1,4}){1,${elidedGroups-1}}`),possibilities.push(`(0{1,4}:){1,${elidedGroups-1}}${right}`),possibilities.push(`(0{1,4}:){${elidedGroups-1}}0{1,4}`);for(let groups=1;groups<elidedGroups-1;groups++)for(let position=1;position<elidedGroups-groups;position++)possibilities.push(`(0{1,4}:){${position}}:(0{1,4}:){${elidedGroups-position-groups-1}}0{1,4}`);return groupPossibilities(possibilities)}}});var require_ipv6=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/ipv6.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result};Object.defineProperty(exports,"__esModule",{value:!0});exports.Address6=void 0;var common=__importStar(require_common2()),constants4=__importStar(require_constants2()),constants6=__importStar(require_constants3()),helpers=__importStar(require_helpers()),ipv4_1=require_ipv4(),regular_expressions_1=require_regular_expressions(),address_error_1=require_address_error(),common_1=require_common2(),isCorrect6=common.isCorrect(constants6.BITS);function assert2(condition){if(!condition)throw new Error("Assertion failed.")}function addCommas(number4){let r=/(\d+)(\d{3})/;for(;r.test(number4);)number4=number4.replace(r,"$1,$2");return number4}function spanLeadingZeroes4(n){return n=n.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2'),n=n.replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2'),n}function compact(address,slice){let s1=[],s2=[],i;for(i=0;i<address.length;i++)i<slice[0]?s1.push(address[i]):i>slice[1]&&s2.push(address[i]);return s1.concat(["compact"]).concat(s2)}function paddedHex(octet){return parseInt(octet,16).toString(16).padStart(4,"0")}function unsignByte(b){return b&255}var Address6=class _Address6{constructor(address,optionalGroups){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=common.isInSubnet,this.isHostInSubnet=common.isHostInSubnet,this.isCorrect=isCorrect6,optionalGroups===void 0?this.groups=constants6.GROUPS:this.groups=optionalGroups,this.address=address;let subnet=constants6.RE_SUBNET_STRING.exec(address);if(subnet){if(this.parsedSubnet=subnet[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>constants6.BITS)throw new address_error_1.AddressError("Invalid subnet mask.");address=address.replace(constants6.RE_SUBNET_STRING,"")}if(/\//.test(address))throw new address_error_1.AddressError("Invalid subnet mask.");let zone=constants6.RE_ZONE_STRING.exec(address);zone&&(this.zone=zone[0],address=address.replace(constants6.RE_ZONE_STRING,"")),this.addressMinusSuffix=address,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(address){try{return new _Address6(address),!0}catch{return!1}}static fromBigInt(bigInt){if(bigInt<BigInt(0)||bigInt>(BigInt(1)<<BigInt(constants6.BITS))-BigInt(1))throw new address_error_1.AddressError("IPv6 BigInt must be in the range 0 to 2**128 - 1");let hex3=bigInt.toString(16).padStart(32,"0"),groups=[];for(let i=0;i<constants6.GROUPS;i++)groups.push(hex3.slice(i*4,(i+1)*4));return new _Address6(groups.join(":"))}static fromURL(url2){var _a2;let host,port=null,result,error48,stripped=url2.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"");if(stripped.indexOf("[")!==-1&&stripped.indexOf("]:")!==-1){if(error48="failed to parse address with port",result=constants6.RE_URL_WITH_PORT.exec(stripped),result===null)return{error:error48,address:null,port:null};host=result[1],port=result[2]}else{if(error48="failed to parse address from URL",result=constants6.RE_URL.exec(stripped),result===null)return{error:error48,address:null,port:null};host=(_a2=result[1])!==null&&_a2!==void 0?_a2:result[2]}port?(port=parseInt(port,10),(port<0||port>65535)&&(port=null)):port=null;let address;try{address=new _Address6(host)}catch{return{error:error48,address:null,port:null}}return{address,port}}static fromAddressAndMask(address,mask){let bits=common.prefixLengthFromMask(new _Address6(mask).bigInt(),constants6.BITS);return new _Address6(`${address}/${bits}`)}static fromAddressAndWildcardMask(address,wildcardMask){let wildcard=new _Address6(wildcardMask).bigInt(),allOnes=(BigInt(1)<<BigInt(constants6.BITS))-BigInt(1),mask=wildcard^allOnes,bits=common.prefixLengthFromMask(mask,constants6.BITS);return new _Address6(`${address}/${bits}`)}static fromWildcard(input2){if(input2.includes("%")||input2.includes("/"))throw new address_error_1.AddressError("Wildcard pattern must not include a zone or CIDR suffix");let halves=input2.split("::");if(halves.length>2)throw new address_error_1.AddressError("Wildcard pattern cannot contain more than one '::'");let groups;if(halves.length===2){let left=halves[0]===""?[]:halves[0].split(":"),right=halves[1]===""?[]:halves[1].split(":"),remaining=constants6.GROUPS-left.length-right.length;if(remaining<1)throw new address_error_1.AddressError("Wildcard pattern with '::' has too many groups");groups=[...left,...new Array(remaining).fill("0"),...right]}else groups=input2.split(":");if(groups.length!==constants6.GROUPS)throw new address_error_1.AddressError("Wildcard pattern must have 8 groups");let firstWildcard=-1;for(let i=0;i<groups.length;i++)if(groups[i]==="*")firstWildcard===-1&&(firstWildcard=i);else if(firstWildcard!==-1)throw new address_error_1.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)");let trailing=firstWildcard===-1?0:groups.length-firstWildcard,replaced=groups.map(g=>g==="*"?"0":g),subnetBits=constants6.BITS-trailing*16;return new _Address6(`${replaced.join(":")}/${subnetBits}`)}static fromAddress4(address){let address4=new ipv4_1.Address4(address),mask6=constants6.BITS-(constants4.BITS-address4.subnetMask);return new _Address6(`::ffff:${address4.correctForm()}/${mask6}`)}static fromArpa(arpaFormAddress){let address=arpaFormAddress.replace(/(\.ip6\.arpa)?\.$/,""),semicolonAmount=7;if(address.length!==63)throw new address_error_1.AddressError("Invalid 'ip6.arpa' form.");let parts=address.split(".").reverse();for(let i=semicolonAmount;i>0;i--){let insertIndex=i*4;parts.splice(insertIndex,0,":")}return address=parts.join(""),new _Address6(address)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(mask=this.subnetMask){return this.getBitsBase2(0,mask)}possibleSubnets(subnetSize=128){let availableBits=constants6.BITS-this.subnetMask,subnetBits=Math.abs(subnetSize-constants6.BITS),subnetPowers=availableBits-subnetBits;return subnetPowers<0?"0":addCommas((BigInt("2")**BigInt(subnetPowers)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(constants6.BITS-this.subnetMask)}`)}startAddress(){return _Address6.fromBigInt(this._startAddress())}startAddressExclusive(){let adjust=BigInt("1");return _Address6.fromBigInt(this._startAddress()+adjust)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(constants6.BITS-this.subnetMask)}`)}endAddress(){return _Address6.fromBigInt(this._endAddress())}endAddressExclusive(){let adjust=BigInt("1");return _Address6.fromBigInt(this._endAddress()-adjust)}subnetMaskAddress(){return _Address6.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(constants6.BITS-this.subnetMask)}`))}wildcardMask(){return _Address6.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(constants6.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}getScope(){let type=this.getType();return type==="Multicast"||type.startsWith("Multicast ")?constants6.SCOPES[parseInt(this.getBits(12,16).toString(10),10)]||"Unknown":type==="Link-local unicast"||type==="Loopback"?"Link local":type==="Unspecified"?"Unknown":"Global"}getType(){for(let i=0;i<TYPE_SUBNETS.length;i++){let entry=TYPE_SUBNETS[i];if(this.isHostInSubnet(entry[0]))return entry[1]}return"Global unicast"}getBits(start,end){return BigInt(`0b${this.getBitsBase2(start,end)}`)}getBitsBase2(start,end){return this.binaryZeroPad().slice(start,end)}getBitsBase16(start,end){let length=end-start;if(length%4!==0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(start,end).toString(16).padStart(length/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,constants6.BITS)}reverseForm(options){options||(options={});let characters=Math.floor(this.subnetMask/4),reversed=this.canonicalForm().replace(/:/g,"").split("").slice(0,characters).reverse().join(".");return characters>0?options.omitSuffix?reversed:`${reversed}.ip6.arpa.`:options.omitSuffix?"":"ip6.arpa."}correctForm(){let i,groups=[],zeroCounter=0,zeroes=[];for(i=0;i<this.parsedAddress.length;i++){let value=parseInt(this.parsedAddress[i],16);value===0&&zeroCounter++,value!==0&&zeroCounter>0&&(zeroCounter>1&&zeroes.push([i-zeroCounter,i-1]),zeroCounter=0)}zeroCounter>1&&zeroes.push([this.parsedAddress.length-zeroCounter,this.parsedAddress.length-1]);let zeroLengths=zeroes.map(n=>n[1]-n[0]+1);if(zeroes.length>0){let index=zeroLengths.indexOf(Math.max(...zeroLengths));groups=compact(this.parsedAddress,zeroes[index])}else groups=this.parsedAddress;for(i=0;i<groups.length;i++)groups[i]!=="compact"&&(groups[i]=parseInt(groups[i],16).toString(16));let correct=groups.join(":");return correct=correct.replace(/^compact$/,"::"),correct=correct.replace(/(^compact)|(compact$)/,":"),correct=correct.replace(/compact/,""),correct}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(constants6.BITS,"0")),this._binaryZeroPad}parse4in6(address){if(address.indexOf(".")===-1)return address;let groups=address.split(":"),lastGroup=groups.slice(-1)[0],v4Octets=lastGroup.split(".");if(v4Octets.length===constants4.GROUPS&&v4Octets.every(octet=>/^\d{1,3}$/.test(octet))&&v4Octets.some(octet=>/^0\d/.test(octet))){let highlighted=v4Octets.map(spanLeadingZeroes4).join("."),prefix=groups.slice(0,-1).map(helpers.escapeHtml).join(":"),separator=groups.length>1?":":"";throw new address_error_1.AddressError("IPv4 addresses can't have leading zeroes.",`${prefix}${separator}${highlighted}`)}let address4=lastGroup.match(constants4.RE_ADDRESS);if(address4){this.parsedAddress4=address4[0];let v4Suffix=this.subnetMask>=96?`/${this.subnetMask-96}`:"";this.address4=new ipv4_1.Address4(`${this.parsedAddress4}${v4Suffix}`),this.v4=!0,groups[groups.length-1]=this.address4.toGroup6(),address=groups.join(":")}return address}parse(address){address=this.parse4in6(address);let badCharacters=address.match(constants6.RE_BAD_CHARACTERS);if(badCharacters)throw new address_error_1.AddressError(`Bad character${badCharacters.length>1?"s":""} detected in address: ${badCharacters.join("")}`,address.replace(constants6.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let badAddress=address.match(constants6.RE_BAD_ADDRESS);if(badAddress)throw new address_error_1.AddressError(`Address failed regex: ${badAddress.join("")}`,address.replace(constants6.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let groups=[],halves=address.split("::");if(halves.length===2){let first=halves[0].split(":"),last=halves[1].split(":");first.length===1&&first[0]===""&&(first=[]),last.length===1&&last[0]===""&&(last=[]);let remaining=this.groups-(first.length+last.length);if(!remaining)throw new address_error_1.AddressError("Error parsing groups");this.elidedGroups=remaining,this.elisionBegin=first.length,this.elisionEnd=first.length+this.elidedGroups,groups=groups.concat(first);for(let i=0;i<remaining;i++)groups.push("0");groups=groups.concat(last)}else if(halves.length===1)groups=address.split(":"),this.elidedGroups=0;else throw new address_error_1.AddressError("Too many :: groups found");if(groups=groups.map(group=>parseInt(group,16).toString(16)),groups.length!==this.groups)throw new address_error_1.AddressError("Incorrect number of groups found");return groups}canonicalForm(){return this.parsedAddress.map(paddedHex).join(":")}decimal(){return this.parsedAddress.map(n=>parseInt(n,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(paddedHex).join("")}`)}to4(){let binary=this.binaryZeroPad().split(""),hex3=BigInt(`0b${binary.slice(96,128).join("")}`).toString(16).padStart(8,"0");if(this.subnetMask>=96){let v4Mask=this.subnetMask-96,groups=[];for(let i=0;i<8;i+=2)groups.push(parseInt(hex3.slice(i,i+2),16));return new ipv4_1.Address4(`${groups.join(".")}/${v4Mask}`)}return ipv4_1.Address4.fromHex(hex3)}to4in6(){let address4=this.to4(),correct=new _Address6(this.parsedAddress.slice(0,6).join(":"),6).correctForm(),infix="";return/:$/.test(correct)||(infix=":"),correct+infix+address4.correctForm()}inspectTeredo(){let prefix=this.getBitsBase16(0,32),udpPort=(this.getBits(80,96)^BigInt("0xffff")).toString(),server4=ipv4_1.Address4.fromHex(this.getBitsBase16(32,64)),bitsForClient4=this.getBits(96,128),client4=ipv4_1.Address4.fromHex((bitsForClient4^BigInt("0xffffffff")).toString(16).padStart(8,"0")),flagsBase2=this.getBitsBase2(64,80),coneNat=(0,common_1.testBit)(flagsBase2,15),reserved=(0,common_1.testBit)(flagsBase2,14),groupIndividual=(0,common_1.testBit)(flagsBase2,8),universalLocal=(0,common_1.testBit)(flagsBase2,9),nonce=BigInt(`0b${flagsBase2.slice(2,6)+flagsBase2.slice(8,16)}`).toString(10);return{prefix:`${prefix.slice(0,4)}:${prefix.slice(4,8)}`,server4:server4.address,client4:client4.address,flags:flagsBase2,coneNat,microsoft:{reserved,universalLocal,groupIndividual,nonce},udpPort}}inspect6to4(){let prefix=this.getBitsBase16(0,16),gateway=ipv4_1.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:prefix.slice(0,4),gateway:gateway.address}}to6to4(){if(!this.is4())return null;let addr6to4=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new _Address6(addr6to4)}static fromAddress4Nat64(address,prefix="64:ff9b::/96"){let v4=new ipv4_1.Address4(address),prefix6=new _Address6(prefix),pl=prefix6.subnetMask;if(pl!==32&&pl!==40&&pl!==48&&pl!==56&&pl!==64&&pl!==96)throw new address_error_1.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");let prefixBits=prefix6.binaryZeroPad(),v4Bits=v4.binaryZeroPad(),bits;if(pl===96)bits=prefixBits.slice(0,96)+v4Bits;else{let beforeU=64-pl;bits=[prefixBits.slice(0,pl),v4Bits.slice(0,beforeU),"00000000",v4Bits.slice(beforeU),"0".repeat(56-(32-beforeU))].join("")}let hex3=BigInt(`0b${bits}`).toString(16).padStart(32,"0"),groups=[];for(let i=0;i<8;i++)groups.push(hex3.slice(i*4,(i+1)*4));return new _Address6(groups.join(":"))}toAddress4Nat64(prefix="64:ff9b::/96"){let prefix6=new _Address6(prefix),pl=prefix6.subnetMask;if(pl!==32&&pl!==40&&pl!==48&&pl!==56&&pl!==64&&pl!==96)throw new address_error_1.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");if(!this.isHostInSubnet(prefix6))return null;let bits=this.binaryZeroPad(),v4Bits;if(pl===96)v4Bits=bits.slice(96,128);else{let beforeU=64-pl;v4Bits=bits.slice(pl,pl+beforeU)+bits.slice(72,72+(32-beforeU))}let octets=[];for(let i=0;i<4;i++)octets.push(parseInt(v4Bits.slice(i*8,(i+1)*8),2).toString());return new ipv4_1.Address4(octets.join("."))}toByteArray(){let value=this.bigInt().toString(16).padStart(constants6.BITS/4,"0"),bytes=[];for(let i=0,length=value.length;i<length;i+=2)bytes.push(parseInt(value.substring(i,i+2),16));return bytes}toUnsignedByteArray(){return this.toByteArray().map(unsignByte)}static fromByteArray(bytes){return common.assertByteArray(bytes,16,"IPv6",-128),this.fromUnsignedByteArray(bytes.map(unsignByte))}static fromUnsignedByteArray(bytes){common.assertByteArray(bytes,16,"IPv6",0);let BYTE_MAX=BigInt("256"),result=BigInt("0"),multiplier=BigInt("1");for(let i=bytes.length-1;i>=0;i--)result+=multiplier*BigInt(bytes[i].toString(10)),multiplier*=BYTE_MAX;return _Address6.fromBigInt(result)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){let embedded=this.embeddedIPv4();return embedded?embedded.isLinkLocal():this.getBitsBase2(0,64)==="1111111010000000000000000000000000000000000000000000000000000000"}isMulticast(){let embedded=this.embeddedIPv4();if(embedded)return embedded.isMulticast();let type=this.getType();return type==="Multicast"||type.startsWith("Multicast ")}is4(){return this.v4}isMapped4(){return this.isHostInSubnet(IPV4_MAPPED_SUBNET)}embeddedIPv4(){return this.isMapped4()||this.isHostInSubnet(NAT64_WELL_KNOWN_SUBNET)?this.to4():null}isTeredo(){return this.isHostInSubnet(TEREDO_SUBNET)}is6to4(){return this.isHostInSubnet(SIX_TO_FOUR_SUBNET)}isLoopback(){let embedded=this.embeddedIPv4();return embedded?embedded.isLoopback():this.getType()==="Loopback"}isULA(){return this.isHostInSubnet(ULA_SUBNET)}isPrivate(){let embedded=this.embeddedIPv4();return embedded?embedded.isPrivate():this.isULA()}isCGNAT(){let embedded=this.embeddedIPv4();return embedded?embedded.isCGNAT():!1}isBroadcast(){let embedded=this.embeddedIPv4();return embedded?embedded.isBroadcast():!1}isUnspecified(){let embedded=this.embeddedIPv4();return embedded?embedded.isUnspecified():this.getType()==="Unspecified"}isDocumentation(){return this.isHostInSubnet(DOCUMENTATION_SUBNET)}href(optionalPort){return optionalPort===void 0?optionalPort="":optionalPort=`:${optionalPort}`,`http://[${this.correctForm()}]${optionalPort}/`}link(options){options||(options={}),options.className===void 0&&(options.className=""),options.prefix===void 0&&(options.prefix="/#address="),options.v4===void 0&&(options.v4=!1);let formFunction=this.correctForm;options.v4&&(formFunction=this.to4in6);let form=formFunction.call(this),safeHref=helpers.escapeHtml(`${options.prefix}${form}`),safeForm=helpers.escapeHtml(form);if(options.className){let safeClass=helpers.escapeHtml(options.className);return`<a href="${safeHref}" class="${safeClass}">${safeForm}</a>`}return`<a href="${safeHref}">${safeForm}</a>`}group(){if(this.elidedGroups===0)return helpers.simpleGroup(this.addressMinusSuffix).join(":");assert2(typeof this.elidedGroups=="number"),assert2(typeof this.elisionBegin=="number");let output2=[],[left,right]=this.addressMinusSuffix.split("::");left.length?output2.push(...helpers.simpleGroup(left)):output2.push("");let classes=["hover-group"];for(let i=this.elisionBegin;i<this.elisionBegin+this.elidedGroups;i++)classes.push(`group-${i}`);return output2.push(`<span class="${classes.join(" ")}"></span>`),right.length?output2.push(...helpers.simpleGroup(right,this.elisionEnd)):output2.push(""),this.is4()&&(assert2(this.address4 instanceof ipv4_1.Address4),output2.pop(),output2.push(this.address4.groupForV6())),output2.join(":")}regularExpressionString(substringSearch=!1){let output2=[],address6=new _Address6(this.correctForm());if(address6.elidedGroups===0)output2.push((0,regular_expressions_1.simpleRegularExpression)(address6.parsedAddress));else if(address6.elidedGroups===constants6.GROUPS)output2.push((0,regular_expressions_1.possibleElisions)(constants6.GROUPS));else{let halves=address6.address.split("::");halves[0].length&&output2.push((0,regular_expressions_1.simpleRegularExpression)(halves[0].split(":"))),assert2(typeof address6.elidedGroups=="number"),output2.push((0,regular_expressions_1.possibleElisions)(address6.elidedGroups,halves[0].length!==0,halves[1].length!==0)),halves[1].length&&output2.push((0,regular_expressions_1.simpleRegularExpression)(halves[1].split(":"))),output2=[output2.join(":")]}return substringSearch||(output2=["(?=^|",regular_expressions_1.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...output2,")(?=[^\\w\\:]|",regular_expressions_1.ADDRESS_BOUNDARY,"|$)"]),output2.join("")}regularExpression(substringSearch=!1){return new RegExp(this.regularExpressionString(substringSearch),"i")}};exports.Address6=Address6;var TYPE_SUBNETS=Object.keys(constants6.TYPES).map(subnet=>[new Address6(subnet),constants6.TYPES[subnet]]),TEREDO_SUBNET=new Address6("2001::/32"),SIX_TO_FOUR_SUBNET=new Address6("2002::/16"),ULA_SUBNET=new Address6("fc00::/7"),DOCUMENTATION_SUBNET=new Address6("2001:db8::/32"),IPV4_MAPPED_SUBNET=new Address6("::ffff:0:0/96"),NAT64_WELL_KNOWN_SUBNET=new Address6("64:ff9b::/96")}});var require_ip_address=__commonJS({"../../node_modules/.pnpm/ip-address@10.5.0/node_modules/ip-address/dist/ip-address.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result};Object.defineProperty(exports,"__esModule",{value:!0});exports.v6=exports.AddressError=exports.Address6=exports.Address4=void 0;var ipv4_1=require_ipv4();Object.defineProperty(exports,"Address4",{enumerable:!0,get:function(){return ipv4_1.Address4}});var ipv6_1=require_ipv6();Object.defineProperty(exports,"Address6",{enumerable:!0,get:function(){return ipv6_1.Address6}});var address_error_1=require_address_error();Object.defineProperty(exports,"AddressError",{enumerable:!0,get:function(){return address_error_1.AddressError}});var helpers=__importStar(require_helpers());exports.v6={helpers}}});var require_helpers2=__commonJS({"../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/common/helpers.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.ipToBuffer=exports.int32ToIpv4=exports.ipv4ToInt32=exports.validateSocksClientChainOptions=exports.validateSocksClientOptions=void 0;var util_1=require_util(),constants_1=require_constants(),stream=__require("stream"),ip_address_1=require_ip_address(),net5=__require("net");function validateSocksClientOptions(options,acceptedCommands=["connect","bind","associate"]){if(!constants_1.SocksCommand[options.command])throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommand,options);if(acceptedCommands.indexOf(options.command)===-1)throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandForOperation,options);if(!isValidSocksRemoteHost(options.destination))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination,options);if(!isValidSocksProxy(options.proxy))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy,options);if(validateCustomProxyAuth(options.proxy,options),options.timeout&&!isValidTimeoutValue(options.timeout))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout,options);if(options.existing_socket&&!(options.existing_socket instanceof stream.Duplex))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsExistingSocket,options)}exports.validateSocksClientOptions=validateSocksClientOptions;function validateSocksClientChainOptions(options){if(options.command!=="connect")throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksCommandChain,options);if(!isValidSocksRemoteHost(options.destination))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsDestination,options);if(!(options.proxies&&Array.isArray(options.proxies)&&options.proxies.length>=2))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxiesLength,options);if(options.proxies.forEach(proxy=>{if(!isValidSocksProxy(proxy))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsProxy,options);validateCustomProxyAuth(proxy,options)}),options.timeout&&!isValidTimeoutValue(options.timeout))throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsTimeout,options)}exports.validateSocksClientChainOptions=validateSocksClientChainOptions;function validateCustomProxyAuth(proxy,options){if(proxy.custom_auth_method!==void 0){if(proxy.custom_auth_method<constants_1.SOCKS5_CUSTOM_AUTH_START||proxy.custom_auth_method>constants_1.SOCKS5_CUSTOM_AUTH_END)throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthRange,options);if(proxy.custom_auth_request_handler===void 0||typeof proxy.custom_auth_request_handler!="function")throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,options);if(proxy.custom_auth_response_size===void 0)throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,options);if(proxy.custom_auth_response_handler===void 0||typeof proxy.custom_auth_response_handler!="function")throw new util_1.SocksClientError(constants_1.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,options)}}function isValidSocksRemoteHost(remoteHost){return remoteHost&&typeof remoteHost.host=="string"&&Buffer.byteLength(remoteHost.host)<256&&typeof remoteHost.port=="number"&&remoteHost.port>=0&&remoteHost.port<=65535}function isValidSocksProxy(proxy){return proxy&&(typeof proxy.host=="string"||typeof proxy.ipaddress=="string")&&typeof proxy.port=="number"&&proxy.port>=0&&proxy.port<=65535&&(proxy.type===4||proxy.type===5)}function isValidTimeoutValue(value){return typeof value=="number"&&value>0}function ipv4ToInt32(ip){return new ip_address_1.Address4(ip).toArray().reduce((acc,part)=>(acc<<8)+part,0)>>>0}exports.ipv4ToInt32=ipv4ToInt32;function int32ToIpv4(int322){let octet1=int322>>>24&255,octet2=int322>>>16&255,octet3=int322>>>8&255,octet4=int322&255;return[octet1,octet2,octet3,octet4].join(".")}exports.int32ToIpv4=int32ToIpv4;function ipToBuffer(ip){if(net5.isIPv4(ip)){let address=new ip_address_1.Address4(ip);return Buffer.from(address.toArray())}else if(net5.isIPv6(ip)){let address=new ip_address_1.Address6(ip);return Buffer.from(address.canonicalForm().split(":").map(segment=>segment.padStart(4,"0")).join(""),"hex")}else throw new Error("Invalid IP address format")}exports.ipToBuffer=ipToBuffer}});var require_receivebuffer=__commonJS({"../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/common/receivebuffer.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.ReceiveBuffer=void 0;var ReceiveBuffer=class{constructor(size=4096){this.buffer=Buffer.allocUnsafe(size),this.offset=0,this.originalSize=size}get length(){return this.offset}append(data){if(!Buffer.isBuffer(data))throw new Error("Attempted to append a non-buffer instance to ReceiveBuffer.");if(this.offset+data.length>=this.buffer.length){let tmp=this.buffer;this.buffer=Buffer.allocUnsafe(Math.max(this.buffer.length+this.originalSize,this.buffer.length+data.length)),tmp.copy(this.buffer)}return data.copy(this.buffer,this.offset),this.offset+=data.length}peek(length){if(length>this.offset)throw new Error("Attempted to read beyond the bounds of the managed internal data.");return this.buffer.slice(0,length)}get(length){if(length>this.offset)throw new Error("Attempted to read beyond the bounds of the managed internal data.");let value=Buffer.allocUnsafe(length);return this.buffer.slice(0,length).copy(value),this.buffer.copyWithin(0,length,length+this.offset-length),this.offset-=length,value}};exports.ReceiveBuffer=ReceiveBuffer}});var require_socksclient=__commonJS({"../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/client/socksclient.js"(exports){"use strict";var __awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve5){resolve5(value)})}return new(P||(P=Promise))(function(resolve5,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve5(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Object.defineProperty(exports,"__esModule",{value:!0});exports.SocksClientError=exports.SocksClient=void 0;var events_1=__require("events"),net5=__require("net"),smart_buffer_1=require_smartbuffer(),constants_1=require_constants(),helpers_1=require_helpers2(),receivebuffer_1=require_receivebuffer(),util_1=require_util();Object.defineProperty(exports,"SocksClientError",{enumerable:!0,get:function(){return util_1.SocksClientError}});var ip_address_1=require_ip_address(),SocksClient=class _SocksClient extends events_1.EventEmitter{constructor(options){super(),this.options=Object.assign({},options),(0,helpers_1.validateSocksClientOptions)(options),this.setState(constants_1.SocksClientState.Created)}static createConnection(options,callback){return new Promise((resolve5,reject)=>{try{(0,helpers_1.validateSocksClientOptions)(options,["connect"])}catch(err){return typeof callback=="function"?(callback(err),resolve5(err)):reject(err)}let client2=new _SocksClient(options);client2.connect(options.existing_socket),client2.once("established",info=>{client2.removeAllListeners(),typeof callback=="function"&&callback(null,info),resolve5(info)}),client2.once("error",err=>{client2.removeAllListeners(),typeof callback=="function"?(callback(err),resolve5(err)):reject(err)})})}static createConnectionChain(options,callback){return new Promise((resolve5,reject)=>__awaiter(this,void 0,void 0,function*(){try{(0,helpers_1.validateSocksClientChainOptions)(options)}catch(err){return typeof callback=="function"?(callback(err),resolve5(err)):reject(err)}options.randomizeChain&&(0,util_1.shuffleArray)(options.proxies);try{let sock;for(let i=0;i<options.proxies.length;i++){let nextProxy=options.proxies[i],nextDestination=i===options.proxies.length-1?options.destination:{host:options.proxies[i+1].host||options.proxies[i+1].ipaddress,port:options.proxies[i+1].port},result=yield _SocksClient.createConnection({command:"connect",proxy:nextProxy,destination:nextDestination,existing_socket:sock});sock=sock||result.socket}typeof callback=="function"?(callback(null,{socket:sock}),resolve5({socket:sock})):resolve5({socket:sock})}catch(err){typeof callback=="function"?(callback(err),resolve5(err)):reject(err)}}))}static createUDPFrame(options){let buff=new smart_buffer_1.SmartBuffer;return buff.writeUInt16BE(0),buff.writeUInt8(options.frameNumber||0),net5.isIPv4(options.remoteHost.host)?(buff.writeUInt8(constants_1.Socks5HostType.IPv4),buff.writeUInt32BE((0,helpers_1.ipv4ToInt32)(options.remoteHost.host))):net5.isIPv6(options.remoteHost.host)?(buff.writeUInt8(constants_1.Socks5HostType.IPv6),buff.writeBuffer((0,helpers_1.ipToBuffer)(options.remoteHost.host))):(buff.writeUInt8(constants_1.Socks5HostType.Hostname),buff.writeUInt8(Buffer.byteLength(options.remoteHost.host)),buff.writeString(options.remoteHost.host)),buff.writeUInt16BE(options.remoteHost.port),buff.writeBuffer(options.data),buff.toBuffer()}static parseUDPFrame(data){let buff=smart_buffer_1.SmartBuffer.fromBuffer(data);buff.readOffset=2;let frameNumber=buff.readUInt8(),hostType=buff.readUInt8(),remoteHost;hostType===constants_1.Socks5HostType.IPv4?remoteHost=(0,helpers_1.int32ToIpv4)(buff.readUInt32BE()):hostType===constants_1.Socks5HostType.IPv6?remoteHost=ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm():remoteHost=buff.readString(buff.readUInt8());let remotePort=buff.readUInt16BE();return{frameNumber,remoteHost:{host:remoteHost,port:remotePort},data:buff.readBuffer()}}setState(newState){this.state!==constants_1.SocksClientState.Error&&(this.state=newState)}connect(existingSocket){this.onDataReceived=data=>this.onDataReceivedHandler(data),this.onClose=()=>this.onCloseHandler(),this.onError=err=>this.onErrorHandler(err),this.onConnect=()=>this.onConnectHandler();let timer=setTimeout(()=>this.onEstablishedTimeout(),this.options.timeout||constants_1.DEFAULT_TIMEOUT);timer.unref&&typeof timer.unref=="function"&&timer.unref(),existingSocket?this.socket=existingSocket:this.socket=new net5.Socket,this.socket.once("close",this.onClose),this.socket.once("error",this.onError),this.socket.once("connect",this.onConnect),this.socket.on("data",this.onDataReceived),this.setState(constants_1.SocksClientState.Connecting),this.receiveBuffer=new receivebuffer_1.ReceiveBuffer,existingSocket?this.socket.emit("connect"):(this.socket.connect(this.getSocketOptions()),this.options.set_tcp_nodelay!==void 0&&this.options.set_tcp_nodelay!==null&&this.socket.setNoDelay(!!this.options.set_tcp_nodelay)),this.prependOnceListener("established",info=>{setImmediate(()=>{if(this.receiveBuffer.length>0){let excessData=this.receiveBuffer.get(this.receiveBuffer.length);info.socket.emit("data",excessData)}info.socket.resume()})})}getSocketOptions(){return Object.assign(Object.assign({},this.options.socket_options),{host:this.options.proxy.host||this.options.proxy.ipaddress,port:this.options.proxy.port})}onEstablishedTimeout(){this.state!==constants_1.SocksClientState.Established&&this.state!==constants_1.SocksClientState.BoundWaitingForConnection&&this.closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut)}onConnectHandler(){this.setState(constants_1.SocksClientState.Connected),this.options.proxy.type===4?this.sendSocks4InitialHandshake():this.sendSocks5InitialHandshake(),this.setState(constants_1.SocksClientState.SentInitialHandshake)}onDataReceivedHandler(data){this.receiveBuffer.append(data),this.processData()}processData(){for(;this.state!==constants_1.SocksClientState.Established&&this.state!==constants_1.SocksClientState.Error&&this.receiveBuffer.length>=this.nextRequiredPacketBufferSize;)if(this.state===constants_1.SocksClientState.SentInitialHandshake)this.options.proxy.type===4?this.handleSocks4FinalHandshakeResponse():this.handleInitialSocks5HandshakeResponse();else if(this.state===constants_1.SocksClientState.SentAuthentication)this.handleInitialSocks5AuthenticationHandshakeResponse();else if(this.state===constants_1.SocksClientState.SentFinalHandshake)this.handleSocks5FinalHandshakeResponse();else if(this.state===constants_1.SocksClientState.BoundWaitingForConnection)this.options.proxy.type===4?this.handleSocks4IncomingConnectionResponse():this.handleSocks5IncomingConnectionResponse();else{this.closeSocket(constants_1.ERRORS.InternalError);break}}onCloseHandler(){this.closeSocket(constants_1.ERRORS.SocketClosed)}onErrorHandler(err){this.closeSocket(err.message)}removeInternalSocketHandlers(){this.socket.pause(),this.socket.removeListener("data",this.onDataReceived),this.socket.removeListener("close",this.onClose),this.socket.removeListener("error",this.onError),this.socket.removeListener("connect",this.onConnect)}closeSocket(err){this.state!==constants_1.SocksClientState.Error&&(this.setState(constants_1.SocksClientState.Error),this.socket.destroy(),this.removeInternalSocketHandlers(),this.emit("error",new util_1.SocksClientError(err,this.options)))}sendSocks4InitialHandshake(){let userId=this.options.proxy.userId||"",buff=new smart_buffer_1.SmartBuffer;buff.writeUInt8(4),buff.writeUInt8(constants_1.SocksCommand[this.options.command]),buff.writeUInt16BE(this.options.destination.port),net5.isIPv4(this.options.destination.host)?(buff.writeBuffer((0,helpers_1.ipToBuffer)(this.options.destination.host)),buff.writeStringNT(userId)):(buff.writeUInt8(0),buff.writeUInt8(0),buff.writeUInt8(0),buff.writeUInt8(1),buff.writeStringNT(userId),buff.writeStringNT(this.options.destination.host)),this.nextRequiredPacketBufferSize=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response,this.socket.write(buff.toBuffer())}handleSocks4FinalHandshakeResponse(){let data=this.receiveBuffer.get(8);if(data[1]!==constants_1.Socks4Response.Granted)this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`);else if(constants_1.SocksCommand[this.options.command]===constants_1.SocksCommand.bind){let buff=smart_buffer_1.SmartBuffer.fromBuffer(data);buff.readOffset=2;let remoteHost={port:buff.readUInt16BE(),host:(0,helpers_1.int32ToIpv4)(buff.readUInt32BE())};remoteHost.host==="0.0.0.0"&&(remoteHost.host=this.options.proxy.ipaddress),this.setState(constants_1.SocksClientState.BoundWaitingForConnection),this.emit("bound",{remoteHost,socket:this.socket})}else this.setState(constants_1.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{socket:this.socket})}handleSocks4IncomingConnectionResponse(){let data=this.receiveBuffer.get(8);if(data[1]!==constants_1.Socks4Response.Granted)this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`);else{let buff=smart_buffer_1.SmartBuffer.fromBuffer(data);buff.readOffset=2;let remoteHost={port:buff.readUInt16BE(),host:(0,helpers_1.int32ToIpv4)(buff.readUInt32BE())};this.setState(constants_1.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost,socket:this.socket})}}sendSocks5InitialHandshake(){let buff=new smart_buffer_1.SmartBuffer,supportedAuthMethods=[constants_1.Socks5Auth.NoAuth];(this.options.proxy.userId||this.options.proxy.password)&&supportedAuthMethods.push(constants_1.Socks5Auth.UserPass),this.options.proxy.custom_auth_method!==void 0&&supportedAuthMethods.push(this.options.proxy.custom_auth_method),buff.writeUInt8(5),buff.writeUInt8(supportedAuthMethods.length);for(let authMethod of supportedAuthMethods)buff.writeUInt8(authMethod);this.nextRequiredPacketBufferSize=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse,this.socket.write(buff.toBuffer()),this.setState(constants_1.SocksClientState.SentInitialHandshake)}handleInitialSocks5HandshakeResponse(){let data=this.receiveBuffer.get(2);data[0]!==5?this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion):data[1]===constants_1.SOCKS5_NO_ACCEPTABLE_AUTH?this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType):data[1]===constants_1.Socks5Auth.NoAuth?(this.socks5ChosenAuthType=constants_1.Socks5Auth.NoAuth,this.sendSocks5CommandRequest()):data[1]===constants_1.Socks5Auth.UserPass?(this.socks5ChosenAuthType=constants_1.Socks5Auth.UserPass,this.sendSocks5UserPassAuthentication()):data[1]===this.options.proxy.custom_auth_method?(this.socks5ChosenAuthType=this.options.proxy.custom_auth_method,this.sendSocks5CustomAuthentication()):this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType)}sendSocks5UserPassAuthentication(){let userId=this.options.proxy.userId||"",password=this.options.proxy.password||"",buff=new smart_buffer_1.SmartBuffer;buff.writeUInt8(1),buff.writeUInt8(Buffer.byteLength(userId)),buff.writeString(userId),buff.writeUInt8(Buffer.byteLength(password)),buff.writeString(password),this.nextRequiredPacketBufferSize=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse,this.socket.write(buff.toBuffer()),this.setState(constants_1.SocksClientState.SentAuthentication)}sendSocks5CustomAuthentication(){return __awaiter(this,void 0,void 0,function*(){this.nextRequiredPacketBufferSize=this.options.proxy.custom_auth_response_size,this.socket.write(yield this.options.proxy.custom_auth_request_handler()),this.setState(constants_1.SocksClientState.SentAuthentication)})}handleSocks5CustomAuthHandshakeResponse(data){return __awaiter(this,void 0,void 0,function*(){return yield this.options.proxy.custom_auth_response_handler(data)})}handleSocks5AuthenticationNoAuthHandshakeResponse(data){return __awaiter(this,void 0,void 0,function*(){return data[1]===0})}handleSocks5AuthenticationUserPassHandshakeResponse(data){return __awaiter(this,void 0,void 0,function*(){return data[1]===0})}handleInitialSocks5AuthenticationHandshakeResponse(){return __awaiter(this,void 0,void 0,function*(){this.setState(constants_1.SocksClientState.ReceivedAuthenticationResponse);let authResult=!1;this.socks5ChosenAuthType===constants_1.Socks5Auth.NoAuth?authResult=yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2)):this.socks5ChosenAuthType===constants_1.Socks5Auth.UserPass?authResult=yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2)):this.socks5ChosenAuthType===this.options.proxy.custom_auth_method&&(authResult=yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size))),authResult?this.sendSocks5CommandRequest():this.closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed)})}sendSocks5CommandRequest(){let buff=new smart_buffer_1.SmartBuffer;buff.writeUInt8(5),buff.writeUInt8(constants_1.SocksCommand[this.options.command]),buff.writeUInt8(0),net5.isIPv4(this.options.destination.host)?(buff.writeUInt8(constants_1.Socks5HostType.IPv4),buff.writeBuffer((0,helpers_1.ipToBuffer)(this.options.destination.host))):net5.isIPv6(this.options.destination.host)?(buff.writeUInt8(constants_1.Socks5HostType.IPv6),buff.writeBuffer((0,helpers_1.ipToBuffer)(this.options.destination.host))):(buff.writeUInt8(constants_1.Socks5HostType.Hostname),buff.writeUInt8(this.options.destination.host.length),buff.writeString(this.options.destination.host)),buff.writeUInt16BE(this.options.destination.port),this.nextRequiredPacketBufferSize=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.socket.write(buff.toBuffer()),this.setState(constants_1.SocksClientState.SentFinalHandshake)}handleSocks5FinalHandshakeResponse(){let header=this.receiveBuffer.peek(5);if(header[0]!==5||header[1]!==constants_1.Socks5Response.Granted)this.closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`);else{let addressType=header[3],remoteHost,buff;if(addressType===constants_1.Socks5HostType.IPv4){let dataNeeded=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<dataNeeded){this.nextRequiredPacketBufferSize=dataNeeded;return}buff=smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)),remoteHost={host:(0,helpers_1.int32ToIpv4)(buff.readUInt32BE()),port:buff.readUInt16BE()},remoteHost.host==="0.0.0.0"&&(remoteHost.host=this.options.proxy.ipaddress)}else if(addressType===constants_1.Socks5HostType.Hostname){let hostLength=header[4],dataNeeded=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength);if(this.receiveBuffer.length<dataNeeded){this.nextRequiredPacketBufferSize=dataNeeded;return}buff=smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5)),remoteHost={host:buff.readString(hostLength),port:buff.readUInt16BE()}}else if(addressType===constants_1.Socks5HostType.IPv6){let dataNeeded=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<dataNeeded){this.nextRequiredPacketBufferSize=dataNeeded;return}buff=smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)),remoteHost={host:ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(),port:buff.readUInt16BE()}}this.setState(constants_1.SocksClientState.ReceivedFinalResponse),constants_1.SocksCommand[this.options.command]===constants_1.SocksCommand.connect?(this.setState(constants_1.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost,socket:this.socket})):constants_1.SocksCommand[this.options.command]===constants_1.SocksCommand.bind?(this.setState(constants_1.SocksClientState.BoundWaitingForConnection),this.nextRequiredPacketBufferSize=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.emit("bound",{remoteHost,socket:this.socket})):constants_1.SocksCommand[this.options.command]===constants_1.SocksCommand.associate&&(this.setState(constants_1.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost,socket:this.socket}))}}handleSocks5IncomingConnectionResponse(){let header=this.receiveBuffer.peek(5);if(header[0]!==5||header[1]!==constants_1.Socks5Response.Granted)this.closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`);else{let addressType=header[3],remoteHost,buff;if(addressType===constants_1.Socks5HostType.IPv4){let dataNeeded=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<dataNeeded){this.nextRequiredPacketBufferSize=dataNeeded;return}buff=smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)),remoteHost={host:(0,helpers_1.int32ToIpv4)(buff.readUInt32BE()),port:buff.readUInt16BE()},remoteHost.host==="0.0.0.0"&&(remoteHost.host=this.options.proxy.ipaddress)}else if(addressType===constants_1.Socks5HostType.Hostname){let hostLength=header[4],dataNeeded=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength);if(this.receiveBuffer.length<dataNeeded){this.nextRequiredPacketBufferSize=dataNeeded;return}buff=smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5)),remoteHost={host:buff.readString(hostLength),port:buff.readUInt16BE()}}else if(addressType===constants_1.Socks5HostType.IPv6){let dataNeeded=constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<dataNeeded){this.nextRequiredPacketBufferSize=dataNeeded;return}buff=smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4)),remoteHost={host:ip_address_1.Address6.fromByteArray(Array.from(buff.readBuffer(16))).canonicalForm(),port:buff.readUInt16BE()}}this.setState(constants_1.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost,socket:this.socket})}}get socksClientOptions(){return Object.assign({},this.options)}};exports.SocksClient=SocksClient}});var require_build=__commonJS({"../../node_modules/.pnpm/socks@2.8.9/node_modules/socks/build/index.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});__exportStar(require_socksclient(),exports)}});var require_dist4=__commonJS({"../../node_modules/.pnpm/socks-proxy-agent@6.2.1/node_modules/socks-proxy-agent/dist/index.js"(exports){"use strict";var __awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve5){resolve5(value)})}return new(P||(P=Promise))(function(resolve5,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve5(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.SocksProxyAgent=void 0;var socks_1=require_build(),agent_base_1=require_src2(),debug_1=__importDefault(require_src()),dns_1=__importDefault(__require("dns")),tls_1=__importDefault(__require("tls")),debug=(0,debug_1.default)("socks-proxy-agent");function parseSocksProxy(opts){var _a2;let port=0,lookup=!1,type=5,host=opts.hostname||opts.host;if(host==null)throw new TypeError('No "hostname"');if(typeof opts.port=="number"?port=opts.port:typeof opts.port=="string"&&(port=parseInt(opts.port,10)),port==null&&(port=1080),opts.protocol!=null)switch(opts.protocol.replace(":","")){case"socks4":lookup=!0;case"socks4a":type=4;break;case"socks5":lookup=!0;case"socks":case"socks5h":type=5;break;default:throw new TypeError(`A "socks" protocol must be specified! Got: ${String(opts.protocol)}`)}if(typeof opts.type<"u")if(opts.type===4||opts.type===5)type=opts.type;else throw new TypeError(`"type" must be 4 or 5, got: ${String(opts.type)}`);let proxy={host,port,type},userId=(_a2=opts.userId)!==null&&_a2!==void 0?_a2:opts.username,password=opts.password;if(opts.auth!=null){let auth=opts.auth.split(":");userId=auth[0],password=auth[1]}return userId!=null&&Object.defineProperty(proxy,"userId",{value:userId,enumerable:!1}),password!=null&&Object.defineProperty(proxy,"password",{value:password,enumerable:!1}),{lookup,proxy}}var normalizeProxyOptions=input2=>{let proxyOptions;if(typeof input2=="string"?proxyOptions=new URL(input2):proxyOptions=input2,proxyOptions==null)throw new TypeError("a SOCKS proxy server `hostname` and `port` must be specified!");return proxyOptions},SocksProxyAgent=class extends agent_base_1.Agent{constructor(input2,options){var _a2;let proxyOptions=normalizeProxyOptions(input2);super(proxyOptions);let parsedProxy=parseSocksProxy(proxyOptions);this.shouldLookup=parsedProxy.lookup,this.proxy=parsedProxy.proxy,this.tlsConnectionOptions=proxyOptions.tls!=null?proxyOptions.tls:{},this.timeout=(_a2=options?.timeout)!==null&&_a2!==void 0?_a2:null}callback(req,opts){var _a2;return __awaiter(this,void 0,void 0,function*(){let{shouldLookup,proxy,timeout}=this,{host,port,lookup:lookupCallback}=opts;if(host==null)throw new Error("No `host` defined!");shouldLookup&&(host=yield new Promise((resolve5,reject)=>{(lookupCallback??dns_1.default.lookup)(host,{},(err,res)=>{err?reject(err):resolve5(res)})}));let socksOpts={proxy,destination:{host,port},command:"connect",timeout:timeout??void 0},cleanup=tlsSocket=>{req.destroy(),socket.destroy(),tlsSocket&&tlsSocket.destroy()};debug("Creating socks proxy connection: %o",socksOpts);let{socket}=yield socks_1.SocksClient.createConnection(socksOpts);if(debug("Successfully created socks proxy connection"),timeout!==null&&(socket.setTimeout(timeout),socket.on("timeout",()=>cleanup())),opts.secureEndpoint){debug("Upgrading socket connection to TLS");let servername=(_a2=opts.servername)!==null&&_a2!==void 0?_a2:opts.host,tlsSocket=tls_1.default.connect(Object.assign(Object.assign(Object.assign({},omit2(opts,"host","hostname","path","port")),{socket,servername}),this.tlsConnectionOptions));return tlsSocket.once("error",error48=>{debug("socket TLS error",error48.message),cleanup(tlsSocket)}),tlsSocket}return socket})}};exports.SocksProxyAgent=SocksProxyAgent;function omit2(obj,...keys){let ret={},key;for(key in obj)keys.includes(key)||(ret[key]=obj[key]);return ret}}});var require_websocket=__commonJS({"../../node_modules/.pnpm/@darabonba+typescript@1.0.5/node_modules/@darabonba/typescript/dist/websocket.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve5){resolve5(value)})}return new(P||(P=Promise))(function(resolve5,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve5(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__generator=exports&&exports.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol=="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=op[0]&2?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[op[0]&2,t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(t=_.trys,!(t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}},__importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.convertToWebSocketMessageType=exports.buildWebSocketURL=exports.newWebSocketClientAndConnect=exports.newDefaultWebSocketClient=exports.DefaultWebSocketClient=exports.AbstractWebSocketHandler=exports.newWebSocketResponse=exports.getWebSocketHandler=exports.getWebSocketHandshakeTimeout=exports.getWebSocketWriteTimeout=exports.getWebSocketMaxReconnectTimes=exports.getWebSocketReconnectInterval=exports.getWebSocketEnableReconnect=exports.getWebSocketPongTimeout=exports.getWebSocketPingInterval=exports.WebSocketMessageType=void 0;var crypto4=__importStar(__require("crypto")),querystring=__importStar(__require("querystring")),url_1=__require("url"),ws_1=__importDefault(__require("ws")),https_proxy_agent_1=__importDefault(require_dist()),http_proxy_agent_1=__importDefault(require_dist3()),socks_proxy_agent_1=require_dist4(),core_1=require_core(),PolyfillAbortSignal=(function(){function PolyfillAbortSignal2(){this.aborted=!1,this.listeners=[]}return PolyfillAbortSignal2.prototype.addEventListener=function(type,listener,options){var _this=this;if(type==="abort"){var wrapped=options&&options.once?function(){_this.removeListener(wrapped),listener()}:listener;this.listeners.push(wrapped)}},PolyfillAbortSignal2.prototype.removeListener=function(listener){var idx=this.listeners.indexOf(listener);idx>=0&&this.listeners.splice(idx,1)},PolyfillAbortSignal2.prototype.dispatchAbort=function(){if(!this.aborted){this.aborted=!0;var copy=this.listeners.slice();this.listeners=[],copy.forEach(function(fn){return fn()})}},PolyfillAbortSignal2})(),PolyfillAbortController=(function(){function PolyfillAbortController2(){this.signal=new PolyfillAbortSignal}return PolyfillAbortController2.prototype.abort=function(){this.signal.dispatchAbort()},PolyfillAbortController2})();function createAbortController(){return typeof AbortController<"u"?new AbortController:new PolyfillAbortController}var WebSocketMessageType;(function(WebSocketMessageType2){WebSocketMessageType2[WebSocketMessageType2.Text=0]="Text",WebSocketMessageType2[WebSocketMessageType2.Binary=1]="Binary",WebSocketMessageType2[WebSocketMessageType2.Ping=2]="Ping",WebSocketMessageType2[WebSocketMessageType2.Pong=3]="Pong",WebSocketMessageType2[WebSocketMessageType2.Close=4]="Close"})(WebSocketMessageType=exports.WebSocketMessageType||(exports.WebSocketMessageType={}));var STATE_DISCONNECTED=0,STATE_CONNECTING=1,STATE_CONNECTED=2,STATE_DISCONNECTING=3;function getWebSocketPingInterval(runtime){return runtime?.webSocketPingInterval}exports.getWebSocketPingInterval=getWebSocketPingInterval;function getWebSocketPongTimeout(runtime){return runtime?.webSocketPongTimeout}exports.getWebSocketPongTimeout=getWebSocketPongTimeout;function getWebSocketEnableReconnect(runtime){return runtime?.webSocketEnableReconnect}exports.getWebSocketEnableReconnect=getWebSocketEnableReconnect;function getWebSocketReconnectInterval(runtime){return runtime?.webSocketReconnectInterval}exports.getWebSocketReconnectInterval=getWebSocketReconnectInterval;function getWebSocketMaxReconnectTimes(runtime){return runtime?.webSocketMaxReconnectTimes}exports.getWebSocketMaxReconnectTimes=getWebSocketMaxReconnectTimes;function getWebSocketWriteTimeout(runtime){return runtime?.webSocketWriteTimeout}exports.getWebSocketWriteTimeout=getWebSocketWriteTimeout;function getWebSocketHandshakeTimeout(runtime){return runtime?.webSocketHandshakeTimeout}exports.getWebSocketHandshakeTimeout=getWebSocketHandshakeTimeout;function getWebSocketHandler(runtime){return runtime?.webSocketHandler}exports.getWebSocketHandler=getWebSocketHandler;function newWebSocketResponse(statusCode,statusMessage,headers){var fakeResponse={statusCode,statusMessage,headers},res=new core_1.Response(fakeResponse),normalizedHeaders={};return Object.keys(headers||{}).forEach(function(key){var val=headers[key];val&&(normalizedHeaders[key.toLowerCase()]=Array.isArray(val)?val[0]:"".concat(val))}),res.headers=normalizedHeaders,res}exports.newWebSocketResponse=newWebSocketResponse;var AbstractWebSocketHandler=(function(){function AbstractWebSocketHandler2(){}return AbstractWebSocketHandler2.prototype.afterConnectionEstablished=function(_session){},AbstractWebSocketHandler2.prototype.handleRawMessage=function(_session,_message){},AbstractWebSocketHandler2.prototype.handleError=function(_session,_err){},AbstractWebSocketHandler2.prototype.afterConnectionClosed=function(_session,_code,_reason){},AbstractWebSocketHandler2})();exports.AbstractWebSocketHandler=AbstractWebSocketHandler;var DefaultWebSocketClient=(function(){function DefaultWebSocketClient2(handler){if(this.stopped=!1,this.pongReceived=!1,this.state=STATE_DISCONNECTED,this.conn=null,this.session=null,this.request=null,this.runtimeObject=null,this.reconnectCount=0,this.pingTimer=null,this.pingInterval=3e4,this.reconnectInterval=5e3,this.writeTimeout=3e4,this.readTimeout=0,this.pongTimeout=5e3,this.maxReconnectTimes=5,this.reconnectLock=!1,this.abortController=null,this.messageHandlersStarted=!1,!handler)throw new Error("handler cannot be nil");this.handler=handler}return DefaultWebSocketClient2.prototype.connect=function(request,runtimeObject){return __awaiter(this,void 0,void 0,function(){var requestURL,parsed,handshakeTimeout,connectTimeout,headers,wsOptions,tlsOptions,_this=this;return __generator(this,function(_a2){if(!request)throw new Error("request cannot be nil");if(!runtimeObject)throw new Error("runtimeObject cannot be nil");if(this.request=request,this.runtimeObject=runtimeObject,this.updateTimeoutConfig(runtimeObject),this.state=STATE_CONNECTING,this.stopped=!1,this.pongReceived=!1,this.abortController&&this.abortController.abort(),this.abortController=createAbortController(),requestURL=buildWebSocketURL(request),parsed=(0,url_1.parse)(requestURL),!parsed.protocol||!parsed.host)throw this.state=STATE_DISCONNECTED,new Error("invalid websocket url: ".concat(requestURL));return handshakeTimeout=runtimeObject.webSocketHandshakeTimeout&&runtimeObject.webSocketHandshakeTimeout>0?runtimeObject.webSocketHandshakeTimeout:3e4,connectTimeout=runtimeObject.connectTimeout&&runtimeObject.connectTimeout>0?runtimeObject.connectTimeout:1e4,headers={},request.headers&&Object.keys(request.headers).forEach(function(k){var v=request.headers[k];v&&k!=="host"&&k!=="content-length"&&(headers[k]=v)}),wsOptions={handshakeTimeout,headers,rejectUnauthorized:!runtimeObject.ignoreSSL},(parsed.protocol==="wss:"||parsed.protocol==="https:")&&(tlsOptions=this.configureTLS(runtimeObject),wsOptions.rejectUnauthorized=tlsOptions.rejectUnauthorized,tlsOptions.cert&&(wsOptions.cert=tlsOptions.cert),tlsOptions.key&&(wsOptions.key=tlsOptions.key),tlsOptions.ca&&(wsOptions.ca=tlsOptions.ca)),this.configureProxy(wsOptions,parsed,runtimeObject,request),[2,new Promise(function(resolve5,reject){var timeoutId=setTimeout(function(){_this.state===STATE_CONNECTING&&(_this.state=STATE_DISCONNECTED,reject(new Error("WebSocket connection timeout")))},connectTimeout),upgradeResponse=null,ws=new ws_1.default(requestURL,wsOptions);ws.on("upgrade",function(response){upgradeResponse=response}),ws.on("open",function(){return __awaiter(_this,void 0,void 0,function(){var sessionID,requestID,err_1,statusCode,statusMessage;return __generator(this,function(_a3){switch(_a3.label){case 0:clearTimeout(timeoutId),this.conn=ws,this.state=STATE_CONNECTED,this.setupPongHandler(),this.startMessageHandlers(),this.pingInterval>0&&this.startPingPong(),sessionID=upgradeResponse?.headers["x-acs-ws-session-id"]||upgradeResponse?.headers["X-Acs-Ws-Session-Id"]||generateSessionID(),requestID=upgradeResponse?.headers["x-acs-request-id"]||upgradeResponse?.headers["X-Acs-Request-Id"]||"",this.session={sessionID:Array.isArray(sessionID)?sessionID[0]:"".concat(sessionID),requestID:Array.isArray(requestID)?requestID[0]:"".concat(requestID),connectedAt:new Date,remoteAddr:"".concat(ws.url),localAddr:"",attributes:{}},_a3.label=1;case 1:return _a3.trys.push([1,3,,5]),[4,this.handler.afterConnectionEstablished(this.session)];case 2:return _a3.sent(),[3,5];case 3:return err_1=_a3.sent(),[4,this.cleanupConnection()];case 4:return _a3.sent(),this.state=STATE_DISCONNECTED,reject(err_1),[2];case 5:return statusCode=upgradeResponse?.statusCode||101,statusMessage=upgradeResponse?.statusMessage||"Switching Protocols",resolve5(newWebSocketResponse(statusCode,statusMessage,upgradeResponse?.headers||{})),[2]}})})}),ws.on("error",function(err){clearTimeout(timeoutId),_this.state===STATE_CONNECTING&&(_this.state=STATE_DISCONNECTED,reject(err))}),ws.on("unexpected-response",function(_req,res){clearTimeout(timeoutId),_this.state=STATE_DISCONNECTED,reject(new Error("WebSocket handshake failed with status ".concat(res.statusCode)))})})]})})},DefaultWebSocketClient2.prototype.disconnect=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a2){return[2,this.disconnectInternal(1e3,"Normal closure")]})})},DefaultWebSocketClient2.prototype.disconnectInternal=function(code,reason){return __awaiter(this,void 0,void 0,function(){var conn;return __generator(this,function(_a2){switch(_a2.label){case 0:if(this.state===STATE_DISCONNECTED&&!this.abortController)return[2];if(this.state=STATE_DISCONNECTING,this.stopPingPong(),this.stopped=!0,conn=this.conn,this.conn=null,conn&&conn.readyState===ws_1.default.OPEN)try{conn.close(code,reason)}catch{}else conn&&conn.terminate();return[4,this.waitForClose(conn)];case 1:return _a2.sent(),this.session?[4,this.handler.afterConnectionClosed(this.session,code,reason)]:[3,3];case 2:_a2.sent(),_a2.label=3;case 3:return this.state=STATE_DISCONNECTED,this.abortController&&(this.abortController.abort(),this.abortController=null),[2]}})})},DefaultWebSocketClient2.prototype.reconnect=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a2){return[2,this.reconnectInternal(!1)]})})},DefaultWebSocketClient2.prototype.reconnectGracefully=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a2){return[2,this.reconnectInternal(!0)]})})},DefaultWebSocketClient2.prototype.reconnectInternal=function(graceful){var _a2,_b,_c,_d;return __awaiter(this,void 0,void 0,function(){var previousSessionID,result;return __generator(this,function(_e){switch(_e.label){case 0:if(!graceful&&this.isConnected())throw new Error("already connected");if(!((_a2=this.abortController)===null||_a2===void 0)&&_a2.signal.aborted)throw new Error("connection aborted");if(this.reconnectLock)throw new Error("reconnect already in progress");this.reconnectLock=!0,_e.label=1;case 1:if(_e.trys.push([1,,5,6]),!(!((_b=this.runtimeObject)===null||_b===void 0)&&_b.webSocketEnableReconnect))throw new Error("reconnect is disabled");if(this.reconnectCount>=this.maxReconnectTimes)throw new Error("max reconnect times reached: ".concat(this.maxReconnectTimes));if(previousSessionID="",graceful)if(!((_c=this.session)===null||_c===void 0)&&_c.sessionID)previousSessionID=this.session.sessionID;else throw new Error("graceful reconnection requires existing session ID");return[4,this.cleanupResources()];case 2:if(_e.sent(),this.stopped=!1,this.reconnectCount++,!this.request)throw new Error("request is nil, cannot reconnect");return graceful&&previousSessionID?(this.request.headers=this.request.headers||{},this.request.headers["X-Acs-Ws-Session-Id"]=previousSessionID):this.request.headers&&delete this.request.headers["X-Acs-Ws-Session-Id"],[4,this.sleepInterruptible(this.reconnectInterval)];case 3:if(_e.sent(),!((_d=this.abortController)===null||_d===void 0)&&_d.signal.aborted)throw new Error("connection aborted");return[4,this.connect(this.request,this.runtimeObject)];case 4:return result=_e.sent(),this.reconnectCount=0,[2,result];case 5:return this.reconnectLock=!1,[7];case 6:return[2]}})})},DefaultWebSocketClient2.prototype.cleanupResources=function(){return __awaiter(this,void 0,void 0,function(){var conn;return __generator(this,function(_a2){switch(_a2.label){case 0:if(this.state=STATE_DISCONNECTING,this.stopPingPong(),this.stopped=!0,conn=this.conn,this.conn=null,!conn)return[3,2];try{conn.readyState===ws_1.default.OPEN?conn.close(1001,"Reconnecting"):conn.terminate()}catch{}return[4,this.waitForClose(conn)];case 1:_a2.sent(),_a2.label=2;case 2:return this.session=null,this.messageHandlersStarted=!1,this.state=STATE_DISCONNECTED,[2]}})})},DefaultWebSocketClient2.prototype.isConnected=function(){return this.state===STATE_CONNECTED},DefaultWebSocketClient2.prototype.sendText=function(text){return __awaiter(this,void 0,void 0,function(){var conn;return __generator(this,function(_a2){switch(_a2.label){case 0:if(!this.isConnected())throw new Error("not connected");if(conn=this.conn,!conn)throw new Error("connection is nil");return[4,this.sendWithTimeout(conn,text,!1)];case 1:return _a2.sent(),[2]}})})},DefaultWebSocketClient2.prototype.sendBinary=function(data){return __awaiter(this,void 0,void 0,function(){var conn;return __generator(this,function(_a2){switch(_a2.label){case 0:if(!this.isConnected())throw new Error("not connected");if(conn=this.conn,!conn)throw new Error("connection is nil");return[4,this.sendWithTimeout(conn,data,!0)];case 1:return _a2.sent(),[2]}})})},DefaultWebSocketClient2.prototype.getSessionInfo=function(){return this.session},DefaultWebSocketClient2.prototype.close=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a2){return[2,this.disconnectInternal(1e3,"Client closed")]})})},DefaultWebSocketClient2.prototype.configureTLS=function(runtimeObject){if(runtimeObject.ignoreSSL)return{rejectUnauthorized:!1};var tlsOptions={rejectUnauthorized:!0};return runtimeObject.key&&runtimeObject.cert&&(tlsOptions.cert=runtimeObject.cert,tlsOptions.key=runtimeObject.key),runtimeObject.ca&&(tlsOptions.ca=runtimeObject.ca),tlsOptions},DefaultWebSocketClient2.prototype.configureProxy=function(wsOptions,parsed,runtimeObject,request){if(runtimeObject.socks5Proxy){this.configureSOCKS5Proxy(wsOptions,runtimeObject);return}this.configureHTTPProxy(wsOptions,parsed,runtimeObject,request)},DefaultWebSocketClient2.prototype.configureSOCKS5Proxy=function(wsOptions,runtimeObject){var socks5Proxy=runtimeObject.socks5Proxy;socks5Proxy&&(wsOptions.agent=new socks_proxy_agent_1.SocksProxyAgent(socks5Proxy))},DefaultWebSocketClient2.prototype.configureHTTPProxy=function(wsOptions,parsed,runtimeObject,request){if(parsed){for(var protocol=parsed.protocol.replace(":",""),host=parsed.hostname,noProxyList=getNoProxy(protocol,runtimeObject),_i=0,noProxyList_1=noProxyList;_i<noProxyList_1.length;_i++){var noProxyHost=noProxyList_1[_i];if(noProxyHost===host)return}var proxyURL=getHttpProxyURL(protocol,host,runtimeObject);if(proxyURL){protocol==="wss"||protocol==="https"?wsOptions.agent=(0,https_proxy_agent_1.default)(proxyURL):wsOptions.agent=(0,http_proxy_agent_1.default)(proxyURL);var parsedProxy=(0,url_1.parse)(proxyURL);parsedProxy.auth&&(request.headers=request.headers||{},request.headers["Proxy-Authorization"]="Basic ".concat(Buffer.from(parsedProxy.auth).toString("base64")))}}},DefaultWebSocketClient2.prototype.configureNetDialer=function(_wsOptions,_runtimeObject,_connectTimeout){},DefaultWebSocketClient2.prototype.updateTimeoutConfig=function(runtimeObject){this.pingInterval=runtimeObject.webSocketPingInterval&&runtimeObject.webSocketPingInterval>0?runtimeObject.webSocketPingInterval:3e4,this.reconnectInterval=runtimeObject.webSocketReconnectInterval&&runtimeObject.webSocketReconnectInterval>0?runtimeObject.webSocketReconnectInterval:5e3,this.writeTimeout=runtimeObject.webSocketWriteTimeout&&runtimeObject.webSocketWriteTimeout>0?runtimeObject.webSocketWriteTimeout:3e4,this.readTimeout=runtimeObject.readTimeout&&runtimeObject.readTimeout>0?runtimeObject.readTimeout:0,this.pongTimeout=runtimeObject.webSocketPongTimeout&&runtimeObject.webSocketPongTimeout>0?runtimeObject.webSocketPongTimeout:5e3,this.maxReconnectTimes=runtimeObject.webSocketMaxReconnectTimes&&runtimeObject.webSocketMaxReconnectTimes>0?runtimeObject.webSocketMaxReconnectTimes:5},DefaultWebSocketClient2.prototype.setupPongHandler=function(){var _this=this,conn=this.conn;conn&&conn.on("pong",function(){_this.pongReceived=!0})},DefaultWebSocketClient2.prototype.startMessageHandlers=function(){var _this=this;if(!this.messageHandlersStarted){this.messageHandlersStarted=!0;var conn=this.conn;conn&&(conn.on("message",function(data,isBinary){return __awaiter(_this,void 0,void 0,function(){var payload,msg,err_2;return __generator(this,function(_a2){switch(_a2.label){case 0:if(this.stopped)return[2];if(payload=Buffer.isBuffer(data)?data:Buffer.from(data),msg={type:isBinary?WebSocketMessageType.Binary:WebSocketMessageType.Text,payload,headers:{},timestamp:new Date},!this.session)return[2];_a2.label=1;case 1:return _a2.trys.push([1,3,,5]),[4,this.handler.handleRawMessage(this.session,msg)];case 2:return _a2.sent(),[3,5];case 3:return err_2=_a2.sent(),[4,this.handler.handleError(this.session,err_2)];case 4:return _a2.sent(),[3,5];case 5:return[2]}})})}),conn.on("close",function(code,reasonBuffer){return __awaiter(_this,void 0,void 0,function(){var reason,_a2;return __generator(this,function(_b){switch(_b.label){case 0:return this.stopped?[2]:(reason=reasonBuffer.toString(),this.session&&code!==1e3&&code!==1001?[4,this.handler.handleError(this.session,new Error("WebSocket closed: ".concat(code," ").concat(reason)))]:[3,2]);case 1:_b.sent(),_b.label=2;case 2:return!((_a2=this.runtimeObject)===null||_a2===void 0)&&_a2.webSocketEnableReconnect&&this.request&&!this.stopped&&this.reconnect().catch(function(){}),[2]}})})}),conn.on("error",function(err){return __awaiter(_this,void 0,void 0,function(){return __generator(this,function(_a2){switch(_a2.label){case 0:return this.stopped||!this.session?[2]:[4,this.handler.handleError(this.session,err)];case 1:return _a2.sent(),[2]}})})}))}},DefaultWebSocketClient2.prototype.startPingPong=function(){var _this=this;this.pingInterval<=0||(this.stopPingPong(),this.pingTimer=setInterval(function(){return __awaiter(_this,void 0,void 0,function(){var err_3,_a2;return __generator(this,function(_b){switch(_b.label){case 0:if(this.stopped||!this.conn||this.conn.readyState!==ws_1.default.OPEN)return[2];this.pongReceived=!1,_b.label=1;case 1:return _b.trys.push([1,2,,5]),this.conn.ping(),[3,5];case 2:return err_3=_b.sent(),this.session?[4,this.handler.handleError(this.session,err_3)]:[3,4];case 3:_b.sent(),_b.label=4;case 4:return[2];case 5:return[4,this.sleepInterruptible(this.pongTimeout)];case 6:return _b.sent(),!this.pongReceived&&(!((_a2=this.runtimeObject)===null||_a2===void 0)&&_a2.webSocketEnableReconnect)&&this.reconnect().catch(function(){}),[2]}})})},this.pingInterval))},DefaultWebSocketClient2.prototype.stopPingPong=function(){this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=null)},DefaultWebSocketClient2.prototype.cleanupConnection=function(){return __awaiter(this,void 0,void 0,function(){var conn;return __generator(this,function(_a2){switch(_a2.label){case 0:return this.stopPingPong(),this.stopped=!0,conn=this.conn,this.conn=null,conn?(conn.terminate(),[4,this.waitForClose(conn)]):[3,2];case 1:_a2.sent(),_a2.label=2;case 2:return[2]}})})},DefaultWebSocketClient2.prototype.sendWithTimeout=function(conn,data,binary){return __awaiter(this,void 0,void 0,function(){var _this=this;return __generator(this,function(_a2){return[2,new Promise(function(resolve5,reject){var timer=_this.writeTimeout>0?setTimeout(function(){return reject(new Error("write timeout"))},_this.writeTimeout):null;conn.send(data,{binary},function(err){timer&&clearTimeout(timer),err?reject(err):resolve5()})})]})})},DefaultWebSocketClient2.prototype.waitForClose=function(conn){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a2){switch(_a2.label){case 0:return conn?conn.readyState===ws_1.default.CLOSED?[2]:[4,new Promise(function(resolve5){var timer=setTimeout(resolve5,5e3);conn.once("close",function(){clearTimeout(timer),resolve5()})})]:[2];case 1:return _a2.sent(),[2]}})})},DefaultWebSocketClient2.prototype.sleepInterruptible=function(ms){var _this=this;return new Promise(function(resolve5){var timer=setTimeout(resolve5,ms);_this.abortController&&_this.abortController.signal.addEventListener("abort",function(){clearTimeout(timer),resolve5()},{once:!0})})},DefaultWebSocketClient2})();exports.DefaultWebSocketClient=DefaultWebSocketClient;function newDefaultWebSocketClient(handler){return new DefaultWebSocketClient(handler)}exports.newDefaultWebSocketClient=newDefaultWebSocketClient;function newWebSocketClientAndConnect(request,runtimeObject){return __awaiter(this,void 0,void 0,function(){var handler,client2,response;return __generator(this,function(_a2){switch(_a2.label){case 0:if(!runtimeObject)throw new Error("runtimeObject cannot be nil");if(handler=runtimeObject.webSocketHandler,!handler)throw new Error("WebSocketHandler is required: please set it in runtimeObject.webSocketHandler");return client2=new DefaultWebSocketClient(handler),[4,client2.connect(request,runtimeObject)];case 1:return response=_a2.sent(),[2,{client:client2,response}]}})})}exports.newWebSocketClientAndConnect=newWebSocketClientAndConnect;function buildWebSocketURL(request){if(!request)throw new Error("request cannot be nil");var protocol=request.protocol||"ws";protocol=protocol.toLowerCase(),protocol==="http"?protocol="ws":protocol==="https"&&(protocol="wss");var domain2=request.domain;if(domain2||(domain2=request.headers.host),!domain2)throw new Error('domain is required (set in request.headers["host"] or request.domain)');var requestURL="".concat(protocol,"://").concat(domain2);if(requestURL+=request.pathname||"/",request.query&&Object.keys(request.query).length>0){var qs=querystring.stringify(request.query);qs&&(requestURL+=requestURL.indexOf("?")>=0?"&".concat(qs):"?".concat(qs))}return requestURL}exports.buildWebSocketURL=buildWebSocketURL;function convertToWebSocketMessageType(messageType){switch(messageType){case 1:return WebSocketMessageType.Text;case 2:return WebSocketMessageType.Binary;case 9:return WebSocketMessageType.Ping;case 10:return WebSocketMessageType.Pong;case 8:return WebSocketMessageType.Close;default:return WebSocketMessageType.Binary}}exports.convertToWebSocketMessageType=convertToWebSocketMessageType;function generateSessionID(){return"ws-session-".concat(Date.now()).concat(crypto4.randomBytes(4).toString("hex"))}function getNoProxy(protocol,runtime){return runtime.noProxy?runtime.noProxy.split(","):process.env.NO_PROXY?process.env.NO_PROXY.split(","):process.env.no_proxy?process.env.no_proxy.split(","):[]}function getHttpProxyURL(protocol,host,runtime){for(var noProxyList=getNoProxy(protocol,runtime),_i=0,noProxyList_2=noProxyList;_i<noProxyList_2.length;_i++){var noProxyHost=noProxyList_2[_i];if(noProxyHost===host)return null}var proxyProtocol=protocol;if(protocol==="wss"?proxyProtocol="https":protocol==="ws"&&(proxyProtocol="http"),proxyProtocol==="https"){if(runtime.httpsProxy)return runtime.httpsProxy;if(process.env.HTTPS_PROXY)return process.env.HTTPS_PROXY;if(process.env.https_proxy)return process.env.https_proxy}else{if(runtime.httpProxy)return runtime.httpProxy;if(process.env.HTTP_PROXY)return process.env.HTTP_PROXY;if(process.env.http_proxy)return process.env.http_proxy}return null}}});var require_moment=__commonJS({"../../node_modules/.pnpm/moment@2.30.1/node_modules/moment/moment.js"(exports,module){(function(global2,factory){typeof exports=="object"&&typeof module<"u"?module.exports=factory():typeof define=="function"&&define.amd?define(factory):global2.moment=factory()})(exports,(function(){"use strict";var hookCallback;function hooks(){return hookCallback.apply(null,arguments)}function setHookCallback(callback){hookCallback=callback}function isArray(input2){return input2 instanceof Array||Object.prototype.toString.call(input2)==="[object Array]"}function isObject2(input2){return input2!=null&&Object.prototype.toString.call(input2)==="[object Object]"}function hasOwnProp(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function isObjectEmpty(obj){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(obj).length===0;var k;for(k in obj)if(hasOwnProp(obj,k))return!1;return!0}function isUndefined(input2){return input2===void 0}function isNumber(input2){return typeof input2=="number"||Object.prototype.toString.call(input2)==="[object Number]"}function isDate(input2){return input2 instanceof Date||Object.prototype.toString.call(input2)==="[object Date]"}function map2(arr,fn){var res=[],i,arrLen=arr.length;for(i=0;i<arrLen;++i)res.push(fn(arr[i],i));return res}function extend2(a,b){for(var i in b)hasOwnProp(b,i)&&(a[i]=b[i]);return hasOwnProp(b,"toString")&&(a.toString=b.toString),hasOwnProp(b,"valueOf")&&(a.valueOf=b.valueOf),a}function createUTC(input2,format2,locale2,strict){return createLocalOrUTC(input2,format2,locale2,strict,!0).utc()}function defaultParsingFlags(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}}function getParsingFlags(m){return m._pf==null&&(m._pf=defaultParsingFlags()),m._pf}var some;Array.prototype.some?some=Array.prototype.some:some=function(fun){var t=Object(this),len=t.length>>>0,i;for(i=0;i<len;i++)if(i in t&&fun.call(this,t[i],i,t))return!0;return!1};function isValid2(m){var flags=null,parsedParts=!1,isNowValid=m._d&&!isNaN(m._d.getTime());if(isNowValid&&(flags=getParsingFlags(m),parsedParts=some.call(flags.parsedDateParts,function(i){return i!=null}),isNowValid=flags.overflow<0&&!flags.empty&&!flags.invalidEra&&!flags.invalidMonth&&!flags.invalidWeekday&&!flags.weekdayMismatch&&!flags.nullInput&&!flags.invalidFormat&&!flags.userInvalidated&&(!flags.meridiem||flags.meridiem&&parsedParts),m._strict&&(isNowValid=isNowValid&&flags.charsLeftOver===0&&flags.unusedTokens.length===0&&flags.bigHour===void 0)),Object.isFrozen==null||!Object.isFrozen(m))m._isValid=isNowValid;else return isNowValid;return m._isValid}function createInvalid(flags){var m=createUTC(NaN);return flags!=null?extend2(getParsingFlags(m),flags):getParsingFlags(m).userInvalidated=!0,m}var momentProperties=hooks.momentProperties=[],updateInProgress=!1;function copyConfig(to2,from2){var i,prop,val,momentPropertiesLen=momentProperties.length;if(isUndefined(from2._isAMomentObject)||(to2._isAMomentObject=from2._isAMomentObject),isUndefined(from2._i)||(to2._i=from2._i),isUndefined(from2._f)||(to2._f=from2._f),isUndefined(from2._l)||(to2._l=from2._l),isUndefined(from2._strict)||(to2._strict=from2._strict),isUndefined(from2._tzm)||(to2._tzm=from2._tzm),isUndefined(from2._isUTC)||(to2._isUTC=from2._isUTC),isUndefined(from2._offset)||(to2._offset=from2._offset),isUndefined(from2._pf)||(to2._pf=getParsingFlags(from2)),isUndefined(from2._locale)||(to2._locale=from2._locale),momentPropertiesLen>0)for(i=0;i<momentPropertiesLen;i++)prop=momentProperties[i],val=from2[prop],isUndefined(val)||(to2[prop]=val);return to2}function Moment(config2){copyConfig(this,config2),this._d=new Date(config2._d!=null?config2._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),updateInProgress===!1&&(updateInProgress=!0,hooks.updateOffset(this),updateInProgress=!1)}function isMoment(obj){return obj instanceof Moment||obj!=null&&obj._isAMomentObject!=null}function warn(msg){hooks.suppressDeprecationWarnings===!1&&typeof console<"u"&&console.warn&&console.warn("Deprecation warning: "+msg)}function deprecate(msg,fn){var firstTime=!0;return extend2(function(){if(hooks.deprecationHandler!=null&&hooks.deprecationHandler(null,msg),firstTime){var args=[],arg,i,key,argLen=arguments.length;for(i=0;i<argLen;i++){if(arg="",typeof arguments[i]=="object"){arg+=`
|
|
23
23
|
[`+i+"] ";for(key in arguments[0])hasOwnProp(arguments[0],key)&&(arg+=key+": "+arguments[0][key]+", ");arg=arg.slice(0,-2)}else arg=arguments[i];args.push(arg)}warn(msg+`
|
|
24
24
|
Arguments: `+Array.prototype.slice.call(args).join("")+`
|
|
25
25
|
`+new Error().stack),firstTime=!1}return fn.apply(this,arguments)},fn)}var deprecations={};function deprecateSimple(name,msg){hooks.deprecationHandler!=null&&hooks.deprecationHandler(name,msg),deprecations[name]||(warn(msg),deprecations[name]=!0)}hooks.suppressDeprecationWarnings=!1,hooks.deprecationHandler=null;function isFunction(input2){return typeof Function<"u"&&input2 instanceof Function||Object.prototype.toString.call(input2)==="[object Function]"}function set2(config2){var prop,i;for(i in config2)hasOwnProp(config2,i)&&(prop=config2[i],isFunction(prop)?this[i]=prop:this["_"+i]=prop);this._config=config2,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function mergeConfigs(parentConfig,childConfig){var res=extend2({},parentConfig),prop;for(prop in childConfig)hasOwnProp(childConfig,prop)&&(isObject2(parentConfig[prop])&&isObject2(childConfig[prop])?(res[prop]={},extend2(res[prop],parentConfig[prop]),extend2(res[prop],childConfig[prop])):childConfig[prop]!=null?res[prop]=childConfig[prop]:delete res[prop]);for(prop in parentConfig)hasOwnProp(parentConfig,prop)&&!hasOwnProp(childConfig,prop)&&isObject2(parentConfig[prop])&&(res[prop]=extend2({},res[prop]));return res}function Locale(config2){config2!=null&&this.set(config2)}var keys;Object.keys?keys=Object.keys:keys=function(obj){var i,res=[];for(i in obj)hasOwnProp(obj,i)&&res.push(i);return res};var defaultCalendar={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function calendar(key,mom,now2){var output2=this._calendar[key]||this._calendar.sameElse;return isFunction(output2)?output2.call(mom,now2):output2}function zeroFill(number4,targetLength,forceSign){var absNumber=""+Math.abs(number4),zerosToFill=targetLength-absNumber.length,sign2=number4>=0;return(sign2?forceSign?"+":"":"-")+Math.pow(10,Math.max(0,zerosToFill)).toString().substr(1)+absNumber}var formattingTokens=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,localFormattingTokens=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,formatFunctions={},formatTokenFunctions={};function addFormatToken(token2,padded,ordinal2,callback){var func=callback;typeof callback=="string"&&(func=function(){return this[callback]()}),token2&&(formatTokenFunctions[token2]=func),padded&&(formatTokenFunctions[padded[0]]=function(){return zeroFill(func.apply(this,arguments),padded[1],padded[2])}),ordinal2&&(formatTokenFunctions[ordinal2]=function(){return this.localeData().ordinal(func.apply(this,arguments),token2)})}function removeFormattingTokens(input2){return input2.match(/\[[\s\S]/)?input2.replace(/^\[|\]$/g,""):input2.replace(/\\/g,"")}function makeFormatFunction(format2){var array2=format2.match(formattingTokens),i,length;for(i=0,length=array2.length;i<length;i++)formatTokenFunctions[array2[i]]?array2[i]=formatTokenFunctions[array2[i]]:array2[i]=removeFormattingTokens(array2[i]);return function(mom){var output2="",i2;for(i2=0;i2<length;i2++)output2+=isFunction(array2[i2])?array2[i2].call(mom,format2):array2[i2];return output2}}function formatMoment(m,format2){return m.isValid()?(format2=expandFormat(format2,m.localeData()),formatFunctions[format2]=formatFunctions[format2]||makeFormatFunction(format2),formatFunctions[format2](m)):m.localeData().invalidDate()}function expandFormat(format2,locale2){var i=5;function replaceLongDateFormatTokens(input2){return locale2.longDateFormat(input2)||input2}for(localFormattingTokens.lastIndex=0;i>=0&&localFormattingTokens.test(format2);)format2=format2.replace(localFormattingTokens,replaceLongDateFormatTokens),localFormattingTokens.lastIndex=0,i-=1;return format2}var defaultLongDateFormat={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};function longDateFormat(key){var format2=this._longDateFormat[key],formatUpper=this._longDateFormat[key.toUpperCase()];return format2||!formatUpper?format2:(this._longDateFormat[key]=formatUpper.match(formattingTokens).map(function(tok){return tok==="MMMM"||tok==="MM"||tok==="DD"||tok==="dddd"?tok.slice(1):tok}).join(""),this._longDateFormat[key])}var defaultInvalidDate="Invalid date";function invalidDate(){return this._invalidDate}var defaultOrdinal="%d",defaultDayOfMonthOrdinalParse=/\d{1,2}/;function ordinal(number4){return this._ordinal.replace("%d",number4)}var defaultRelativeTime={future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function relativeTime(number4,withoutSuffix,string4,isFuture){var output2=this._relativeTime[string4];return isFunction(output2)?output2(number4,withoutSuffix,string4,isFuture):output2.replace(/%d/i,number4)}function pastFuture(diff2,output2){var format2=this._relativeTime[diff2>0?"future":"past"];return isFunction(format2)?format2(output2):format2.replace(/%s/i,output2)}var aliases={D:"date",dates:"date",date:"date",d:"day",days:"day",day:"day",e:"weekday",weekdays:"weekday",weekday:"weekday",E:"isoWeekday",isoweekdays:"isoWeekday",isoweekday:"isoWeekday",DDD:"dayOfYear",dayofyears:"dayOfYear",dayofyear:"dayOfYear",h:"hour",hours:"hour",hour:"hour",ms:"millisecond",milliseconds:"millisecond",millisecond:"millisecond",m:"minute",minutes:"minute",minute:"minute",M:"month",months:"month",month:"month",Q:"quarter",quarters:"quarter",quarter:"quarter",s:"second",seconds:"second",second:"second",gg:"weekYear",weekyears:"weekYear",weekyear:"weekYear",GG:"isoWeekYear",isoweekyears:"isoWeekYear",isoweekyear:"isoWeekYear",w:"week",weeks:"week",week:"week",W:"isoWeek",isoweeks:"isoWeek",isoweek:"isoWeek",y:"year",years:"year",year:"year"};function normalizeUnits(units){return typeof units=="string"?aliases[units]||aliases[units.toLowerCase()]:void 0}function normalizeObjectUnits(inputObject){var normalizedInput={},normalizedProp,prop;for(prop in inputObject)hasOwnProp(inputObject,prop)&&(normalizedProp=normalizeUnits(prop),normalizedProp&&(normalizedInput[normalizedProp]=inputObject[prop]));return normalizedInput}var priorities={date:9,day:11,weekday:11,isoWeekday:11,dayOfYear:4,hour:13,millisecond:16,minute:14,month:8,quarter:7,second:15,weekYear:1,isoWeekYear:1,week:5,isoWeek:5,year:1};function getPrioritizedUnits(unitsObj){var units=[],u;for(u in unitsObj)hasOwnProp(unitsObj,u)&&units.push({unit:u,priority:priorities[u]});return units.sort(function(a,b){return a.priority-b.priority}),units}var match1=/\d/,match2=/\d\d/,match3=/\d{3}/,match4=/\d{4}/,match6=/[+-]?\d{6}/,match1to2=/\d\d?/,match3to4=/\d\d\d\d?/,match5to6=/\d\d\d\d\d\d?/,match1to3=/\d{1,3}/,match1to4=/\d{1,4}/,match1to6=/[+-]?\d{1,6}/,matchUnsigned=/\d+/,matchSigned=/[+-]?\d+/,matchOffset=/Z|[+-]\d\d:?\d\d/gi,matchShortOffset=/Z|[+-]\d\d(?::?\d\d)?/gi,matchTimestamp=/[+-]?\d+(\.\d{1,3})?/,matchWord=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,match1to2NoLeadingZero=/^[1-9]\d?/,match1to2HasZero=/^([1-9]\d|\d)/,regexes;regexes={};function addRegexToken(token2,regex,strictRegex){regexes[token2]=isFunction(regex)?regex:function(isStrict,localeData2){return isStrict&&strictRegex?strictRegex:regex}}function getParseRegexForToken(token2,config2){return hasOwnProp(regexes,token2)?regexes[token2](config2._strict,config2._locale):new RegExp(unescapeFormat(token2))}function unescapeFormat(s){return regexEscape(s.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(matched,p1,p2,p3,p4){return p1||p2||p3||p4}))}function regexEscape(s){return s.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function absFloor(number4){return number4<0?Math.ceil(number4)||0:Math.floor(number4)}function toInt(argumentForCoercion){var coercedNumber=+argumentForCoercion,value=0;return coercedNumber!==0&&isFinite(coercedNumber)&&(value=absFloor(coercedNumber)),value}var tokens={};function addParseToken(token2,callback){var i,func=callback,tokenLen;for(typeof token2=="string"&&(token2=[token2]),isNumber(callback)&&(func=function(input2,array2){array2[callback]=toInt(input2)}),tokenLen=token2.length,i=0;i<tokenLen;i++)tokens[token2[i]]=func}function addWeekParseToken(token2,callback){addParseToken(token2,function(input2,array2,config2,token3){config2._w=config2._w||{},callback(input2,config2._w,config2,token3)})}function addTimeToArrayFromToken(token2,input2,config2){input2!=null&&hasOwnProp(tokens,token2)&&tokens[token2](input2,config2._a,config2,token2)}function isLeapYear(year){return year%4===0&&year%100!==0||year%400===0}var YEAR=0,MONTH=1,DATE=2,HOUR=3,MINUTE=4,SECOND=5,MILLISECOND=6,WEEK=7,WEEKDAY=8;addFormatToken("Y",0,0,function(){var y=this.year();return y<=9999?zeroFill(y,4):"+"+y}),addFormatToken(0,["YY",2],0,function(){return this.year()%100}),addFormatToken(0,["YYYY",4],0,"year"),addFormatToken(0,["YYYYY",5],0,"year"),addFormatToken(0,["YYYYYY",6,!0],0,"year"),addRegexToken("Y",matchSigned),addRegexToken("YY",match1to2,match2),addRegexToken("YYYY",match1to4,match4),addRegexToken("YYYYY",match1to6,match6),addRegexToken("YYYYYY",match1to6,match6),addParseToken(["YYYYY","YYYYYY"],YEAR),addParseToken("YYYY",function(input2,array2){array2[YEAR]=input2.length===2?hooks.parseTwoDigitYear(input2):toInt(input2)}),addParseToken("YY",function(input2,array2){array2[YEAR]=hooks.parseTwoDigitYear(input2)}),addParseToken("Y",function(input2,array2){array2[YEAR]=parseInt(input2,10)});function daysInYear(year){return isLeapYear(year)?366:365}hooks.parseTwoDigitYear=function(input2){return toInt(input2)+(toInt(input2)>68?1900:2e3)};var getSetYear=makeGetSet("FullYear",!0);function getIsLeapYear(){return isLeapYear(this.year())}function makeGetSet(unit,keepTime){return function(value){return value!=null?(set$1(this,unit,value),hooks.updateOffset(this,keepTime),this):get(this,unit)}}function get(mom,unit){if(!mom.isValid())return NaN;var d=mom._d,isUTC=mom._isUTC;switch(unit){case"Milliseconds":return isUTC?d.getUTCMilliseconds():d.getMilliseconds();case"Seconds":return isUTC?d.getUTCSeconds():d.getSeconds();case"Minutes":return isUTC?d.getUTCMinutes():d.getMinutes();case"Hours":return isUTC?d.getUTCHours():d.getHours();case"Date":return isUTC?d.getUTCDate():d.getDate();case"Day":return isUTC?d.getUTCDay():d.getDay();case"Month":return isUTC?d.getUTCMonth():d.getMonth();case"FullYear":return isUTC?d.getUTCFullYear():d.getFullYear();default:return NaN}}function set$1(mom,unit,value){var d,isUTC,year,month,date5;if(!(!mom.isValid()||isNaN(value))){switch(d=mom._d,isUTC=mom._isUTC,unit){case"Milliseconds":return void(isUTC?d.setUTCMilliseconds(value):d.setMilliseconds(value));case"Seconds":return void(isUTC?d.setUTCSeconds(value):d.setSeconds(value));case"Minutes":return void(isUTC?d.setUTCMinutes(value):d.setMinutes(value));case"Hours":return void(isUTC?d.setUTCHours(value):d.setHours(value));case"Date":return void(isUTC?d.setUTCDate(value):d.setDate(value));case"FullYear":break;default:return}year=value,month=mom.month(),date5=mom.date(),date5=date5===29&&month===1&&!isLeapYear(year)?28:date5,isUTC?d.setUTCFullYear(year,month,date5):d.setFullYear(year,month,date5)}}function stringGet(units){return units=normalizeUnits(units),isFunction(this[units])?this[units]():this}function stringSet(units,value){if(typeof units=="object"){units=normalizeObjectUnits(units);var prioritized=getPrioritizedUnits(units),i,prioritizedLen=prioritized.length;for(i=0;i<prioritizedLen;i++)this[prioritized[i].unit](units[prioritized[i].unit])}else if(units=normalizeUnits(units),isFunction(this[units]))return this[units](value);return this}function mod(n,x){return(n%x+x)%x}var indexOf;Array.prototype.indexOf?indexOf=Array.prototype.indexOf:indexOf=function(o){var i;for(i=0;i<this.length;++i)if(this[i]===o)return i;return-1};function daysInMonth(year,month){if(isNaN(year)||isNaN(month))return NaN;var modMonth=mod(month,12);return year+=(month-modMonth)/12,modMonth===1?isLeapYear(year)?29:28:31-modMonth%7%2}addFormatToken("M",["MM",2],"Mo",function(){return this.month()+1}),addFormatToken("MMM",0,0,function(format2){return this.localeData().monthsShort(this,format2)}),addFormatToken("MMMM",0,0,function(format2){return this.localeData().months(this,format2)}),addRegexToken("M",match1to2,match1to2NoLeadingZero),addRegexToken("MM",match1to2,match2),addRegexToken("MMM",function(isStrict,locale2){return locale2.monthsShortRegex(isStrict)}),addRegexToken("MMMM",function(isStrict,locale2){return locale2.monthsRegex(isStrict)}),addParseToken(["M","MM"],function(input2,array2){array2[MONTH]=toInt(input2)-1}),addParseToken(["MMM","MMMM"],function(input2,array2,config2,token2){var month=config2._locale.monthsParse(input2,token2,config2._strict);month!=null?array2[MONTH]=month:getParsingFlags(config2).invalidMonth=input2});var defaultLocaleMonths="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),defaultLocaleMonthsShort="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),MONTHS_IN_FORMAT=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,defaultMonthsShortRegex=matchWord,defaultMonthsRegex=matchWord;function localeMonths(m,format2){return m?isArray(this._months)?this._months[m.month()]:this._months[(this._months.isFormat||MONTHS_IN_FORMAT).test(format2)?"format":"standalone"][m.month()]:isArray(this._months)?this._months:this._months.standalone}function localeMonthsShort(m,format2){return m?isArray(this._monthsShort)?this._monthsShort[m.month()]:this._monthsShort[MONTHS_IN_FORMAT.test(format2)?"format":"standalone"][m.month()]:isArray(this._monthsShort)?this._monthsShort:this._monthsShort.standalone}function handleStrictParse(monthName,format2,strict){var i,ii,mom,llc=monthName.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],i=0;i<12;++i)mom=createUTC([2e3,i]),this._shortMonthsParse[i]=this.monthsShort(mom,"").toLocaleLowerCase(),this._longMonthsParse[i]=this.months(mom,"").toLocaleLowerCase();return strict?format2==="MMM"?(ii=indexOf.call(this._shortMonthsParse,llc),ii!==-1?ii:null):(ii=indexOf.call(this._longMonthsParse,llc),ii!==-1?ii:null):format2==="MMM"?(ii=indexOf.call(this._shortMonthsParse,llc),ii!==-1?ii:(ii=indexOf.call(this._longMonthsParse,llc),ii!==-1?ii:null)):(ii=indexOf.call(this._longMonthsParse,llc),ii!==-1?ii:(ii=indexOf.call(this._shortMonthsParse,llc),ii!==-1?ii:null))}function localeMonthsParse(monthName,format2,strict){var i,mom,regex;if(this._monthsParseExact)return handleStrictParse.call(this,monthName,format2,strict);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),i=0;i<12;i++){if(mom=createUTC([2e3,i]),strict&&!this._longMonthsParse[i]&&(this._longMonthsParse[i]=new RegExp("^"+this.months(mom,"").replace(".","")+"$","i"),this._shortMonthsParse[i]=new RegExp("^"+this.monthsShort(mom,"").replace(".","")+"$","i")),!strict&&!this._monthsParse[i]&&(regex="^"+this.months(mom,"")+"|^"+this.monthsShort(mom,""),this._monthsParse[i]=new RegExp(regex.replace(".",""),"i")),strict&&format2==="MMMM"&&this._longMonthsParse[i].test(monthName))return i;if(strict&&format2==="MMM"&&this._shortMonthsParse[i].test(monthName))return i;if(!strict&&this._monthsParse[i].test(monthName))return i}}function setMonth(mom,value){if(!mom.isValid())return mom;if(typeof value=="string"){if(/^\d+$/.test(value))value=toInt(value);else if(value=mom.localeData().monthsParse(value),!isNumber(value))return mom}var month=value,date5=mom.date();return date5=date5<29?date5:Math.min(date5,daysInMonth(mom.year(),month)),mom._isUTC?mom._d.setUTCMonth(month,date5):mom._d.setMonth(month,date5),mom}function getSetMonth(value){return value!=null?(setMonth(this,value),hooks.updateOffset(this,!0),this):get(this,"Month")}function getDaysInMonth(){return daysInMonth(this.year(),this.month())}function monthsShortRegex(isStrict){return this._monthsParseExact?(hasOwnProp(this,"_monthsRegex")||computeMonthsParse.call(this),isStrict?this._monthsShortStrictRegex:this._monthsShortRegex):(hasOwnProp(this,"_monthsShortRegex")||(this._monthsShortRegex=defaultMonthsShortRegex),this._monthsShortStrictRegex&&isStrict?this._monthsShortStrictRegex:this._monthsShortRegex)}function monthsRegex(isStrict){return this._monthsParseExact?(hasOwnProp(this,"_monthsRegex")||computeMonthsParse.call(this),isStrict?this._monthsStrictRegex:this._monthsRegex):(hasOwnProp(this,"_monthsRegex")||(this._monthsRegex=defaultMonthsRegex),this._monthsStrictRegex&&isStrict?this._monthsStrictRegex:this._monthsRegex)}function computeMonthsParse(){function cmpLenRev(a,b){return b.length-a.length}var shortPieces=[],longPieces=[],mixedPieces=[],i,mom,shortP,longP;for(i=0;i<12;i++)mom=createUTC([2e3,i]),shortP=regexEscape(this.monthsShort(mom,"")),longP=regexEscape(this.months(mom,"")),shortPieces.push(shortP),longPieces.push(longP),mixedPieces.push(longP),mixedPieces.push(shortP);shortPieces.sort(cmpLenRev),longPieces.sort(cmpLenRev),mixedPieces.sort(cmpLenRev),this._monthsRegex=new RegExp("^("+mixedPieces.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+longPieces.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+shortPieces.join("|")+")","i")}function createDate(y,m,d,h,M,s,ms){var date5;return y<100&&y>=0?(date5=new Date(y+400,m,d,h,M,s,ms),isFinite(date5.getFullYear())&&date5.setFullYear(y)):date5=new Date(y,m,d,h,M,s,ms),date5}function createUTCDate(y){var date5,args;return y<100&&y>=0?(args=Array.prototype.slice.call(arguments),args[0]=y+400,date5=new Date(Date.UTC.apply(null,args)),isFinite(date5.getUTCFullYear())&&date5.setUTCFullYear(y)):date5=new Date(Date.UTC.apply(null,arguments)),date5}function firstWeekOffset(year,dow,doy){var fwd=7+dow-doy,fwdlw=(7+createUTCDate(year,0,fwd).getUTCDay()-dow)%7;return-fwdlw+fwd-1}function dayOfYearFromWeeks(year,week,weekday,dow,doy){var localWeekday=(7+weekday-dow)%7,weekOffset=firstWeekOffset(year,dow,doy),dayOfYear=1+7*(week-1)+localWeekday+weekOffset,resYear,resDayOfYear;return dayOfYear<=0?(resYear=year-1,resDayOfYear=daysInYear(resYear)+dayOfYear):dayOfYear>daysInYear(year)?(resYear=year+1,resDayOfYear=dayOfYear-daysInYear(year)):(resYear=year,resDayOfYear=dayOfYear),{year:resYear,dayOfYear:resDayOfYear}}function weekOfYear(mom,dow,doy){var weekOffset=firstWeekOffset(mom.year(),dow,doy),week=Math.floor((mom.dayOfYear()-weekOffset-1)/7)+1,resWeek,resYear;return week<1?(resYear=mom.year()-1,resWeek=week+weeksInYear(resYear,dow,doy)):week>weeksInYear(mom.year(),dow,doy)?(resWeek=week-weeksInYear(mom.year(),dow,doy),resYear=mom.year()+1):(resYear=mom.year(),resWeek=week),{week:resWeek,year:resYear}}function weeksInYear(year,dow,doy){var weekOffset=firstWeekOffset(year,dow,doy),weekOffsetNext=firstWeekOffset(year+1,dow,doy);return(daysInYear(year)-weekOffset+weekOffsetNext)/7}addFormatToken("w",["ww",2],"wo","week"),addFormatToken("W",["WW",2],"Wo","isoWeek"),addRegexToken("w",match1to2,match1to2NoLeadingZero),addRegexToken("ww",match1to2,match2),addRegexToken("W",match1to2,match1to2NoLeadingZero),addRegexToken("WW",match1to2,match2),addWeekParseToken(["w","ww","W","WW"],function(input2,week,config2,token2){week[token2.substr(0,1)]=toInt(input2)});function localeWeek(mom){return weekOfYear(mom,this._week.dow,this._week.doy).week}var defaultLocaleWeek={dow:0,doy:6};function localeFirstDayOfWeek(){return this._week.dow}function localeFirstDayOfYear(){return this._week.doy}function getSetWeek(input2){var week=this.localeData().week(this);return input2==null?week:this.add((input2-week)*7,"d")}function getSetISOWeek(input2){var week=weekOfYear(this,1,4).week;return input2==null?week:this.add((input2-week)*7,"d")}addFormatToken("d",0,"do","day"),addFormatToken("dd",0,0,function(format2){return this.localeData().weekdaysMin(this,format2)}),addFormatToken("ddd",0,0,function(format2){return this.localeData().weekdaysShort(this,format2)}),addFormatToken("dddd",0,0,function(format2){return this.localeData().weekdays(this,format2)}),addFormatToken("e",0,0,"weekday"),addFormatToken("E",0,0,"isoWeekday"),addRegexToken("d",match1to2),addRegexToken("e",match1to2),addRegexToken("E",match1to2),addRegexToken("dd",function(isStrict,locale2){return locale2.weekdaysMinRegex(isStrict)}),addRegexToken("ddd",function(isStrict,locale2){return locale2.weekdaysShortRegex(isStrict)}),addRegexToken("dddd",function(isStrict,locale2){return locale2.weekdaysRegex(isStrict)}),addWeekParseToken(["dd","ddd","dddd"],function(input2,week,config2,token2){var weekday=config2._locale.weekdaysParse(input2,token2,config2._strict);weekday!=null?week.d=weekday:getParsingFlags(config2).invalidWeekday=input2}),addWeekParseToken(["d","e","E"],function(input2,week,config2,token2){week[token2]=toInt(input2)});function parseWeekday(input2,locale2){return typeof input2!="string"?input2:isNaN(input2)?(input2=locale2.weekdaysParse(input2),typeof input2=="number"?input2:null):parseInt(input2,10)}function parseIsoWeekday(input2,locale2){return typeof input2=="string"?locale2.weekdaysParse(input2)%7||7:isNaN(input2)?null:input2}function shiftWeekdays(ws,n){return ws.slice(n,7).concat(ws.slice(0,n))}var defaultLocaleWeekdays="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),defaultLocaleWeekdaysShort="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),defaultLocaleWeekdaysMin="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),defaultWeekdaysRegex=matchWord,defaultWeekdaysShortRegex=matchWord,defaultWeekdaysMinRegex=matchWord;function localeWeekdays(m,format2){var weekdays=isArray(this._weekdays)?this._weekdays:this._weekdays[m&&m!==!0&&this._weekdays.isFormat.test(format2)?"format":"standalone"];return m===!0?shiftWeekdays(weekdays,this._week.dow):m?weekdays[m.day()]:weekdays}function localeWeekdaysShort(m){return m===!0?shiftWeekdays(this._weekdaysShort,this._week.dow):m?this._weekdaysShort[m.day()]:this._weekdaysShort}function localeWeekdaysMin(m){return m===!0?shiftWeekdays(this._weekdaysMin,this._week.dow):m?this._weekdaysMin[m.day()]:this._weekdaysMin}function handleStrictParse$1(weekdayName,format2,strict){var i,ii,mom,llc=weekdayName.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],i=0;i<7;++i)mom=createUTC([2e3,1]).day(i),this._minWeekdaysParse[i]=this.weekdaysMin(mom,"").toLocaleLowerCase(),this._shortWeekdaysParse[i]=this.weekdaysShort(mom,"").toLocaleLowerCase(),this._weekdaysParse[i]=this.weekdays(mom,"").toLocaleLowerCase();return strict?format2==="dddd"?(ii=indexOf.call(this._weekdaysParse,llc),ii!==-1?ii:null):format2==="ddd"?(ii=indexOf.call(this._shortWeekdaysParse,llc),ii!==-1?ii:null):(ii=indexOf.call(this._minWeekdaysParse,llc),ii!==-1?ii:null):format2==="dddd"?(ii=indexOf.call(this._weekdaysParse,llc),ii!==-1||(ii=indexOf.call(this._shortWeekdaysParse,llc),ii!==-1)?ii:(ii=indexOf.call(this._minWeekdaysParse,llc),ii!==-1?ii:null)):format2==="ddd"?(ii=indexOf.call(this._shortWeekdaysParse,llc),ii!==-1||(ii=indexOf.call(this._weekdaysParse,llc),ii!==-1)?ii:(ii=indexOf.call(this._minWeekdaysParse,llc),ii!==-1?ii:null)):(ii=indexOf.call(this._minWeekdaysParse,llc),ii!==-1||(ii=indexOf.call(this._weekdaysParse,llc),ii!==-1)?ii:(ii=indexOf.call(this._shortWeekdaysParse,llc),ii!==-1?ii:null))}function localeWeekdaysParse(weekdayName,format2,strict){var i,mom,regex;if(this._weekdaysParseExact)return handleStrictParse$1.call(this,weekdayName,format2,strict);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),i=0;i<7;i++){if(mom=createUTC([2e3,1]).day(i),strict&&!this._fullWeekdaysParse[i]&&(this._fullWeekdaysParse[i]=new RegExp("^"+this.weekdays(mom,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[i]=new RegExp("^"+this.weekdaysShort(mom,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[i]=new RegExp("^"+this.weekdaysMin(mom,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[i]||(regex="^"+this.weekdays(mom,"")+"|^"+this.weekdaysShort(mom,"")+"|^"+this.weekdaysMin(mom,""),this._weekdaysParse[i]=new RegExp(regex.replace(".",""),"i")),strict&&format2==="dddd"&&this._fullWeekdaysParse[i].test(weekdayName))return i;if(strict&&format2==="ddd"&&this._shortWeekdaysParse[i].test(weekdayName))return i;if(strict&&format2==="dd"&&this._minWeekdaysParse[i].test(weekdayName))return i;if(!strict&&this._weekdaysParse[i].test(weekdayName))return i}}function getSetDayOfWeek(input2){if(!this.isValid())return input2!=null?this:NaN;var day=get(this,"Day");return input2!=null?(input2=parseWeekday(input2,this.localeData()),this.add(input2-day,"d")):day}function getSetLocaleDayOfWeek(input2){if(!this.isValid())return input2!=null?this:NaN;var weekday=(this.day()+7-this.localeData()._week.dow)%7;return input2==null?weekday:this.add(input2-weekday,"d")}function getSetISODayOfWeek(input2){if(!this.isValid())return input2!=null?this:NaN;if(input2!=null){var weekday=parseIsoWeekday(input2,this.localeData());return this.day(this.day()%7?weekday:weekday-7)}else return this.day()||7}function weekdaysRegex(isStrict){return this._weekdaysParseExact?(hasOwnProp(this,"_weekdaysRegex")||computeWeekdaysParse.call(this),isStrict?this._weekdaysStrictRegex:this._weekdaysRegex):(hasOwnProp(this,"_weekdaysRegex")||(this._weekdaysRegex=defaultWeekdaysRegex),this._weekdaysStrictRegex&&isStrict?this._weekdaysStrictRegex:this._weekdaysRegex)}function weekdaysShortRegex(isStrict){return this._weekdaysParseExact?(hasOwnProp(this,"_weekdaysRegex")||computeWeekdaysParse.call(this),isStrict?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(hasOwnProp(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=defaultWeekdaysShortRegex),this._weekdaysShortStrictRegex&&isStrict?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)}function weekdaysMinRegex(isStrict){return this._weekdaysParseExact?(hasOwnProp(this,"_weekdaysRegex")||computeWeekdaysParse.call(this),isStrict?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(hasOwnProp(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=defaultWeekdaysMinRegex),this._weekdaysMinStrictRegex&&isStrict?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)}function computeWeekdaysParse(){function cmpLenRev(a,b){return b.length-a.length}var minPieces=[],shortPieces=[],longPieces=[],mixedPieces=[],i,mom,minp,shortp,longp;for(i=0;i<7;i++)mom=createUTC([2e3,1]).day(i),minp=regexEscape(this.weekdaysMin(mom,"")),shortp=regexEscape(this.weekdaysShort(mom,"")),longp=regexEscape(this.weekdays(mom,"")),minPieces.push(minp),shortPieces.push(shortp),longPieces.push(longp),mixedPieces.push(minp),mixedPieces.push(shortp),mixedPieces.push(longp);minPieces.sort(cmpLenRev),shortPieces.sort(cmpLenRev),longPieces.sort(cmpLenRev),mixedPieces.sort(cmpLenRev),this._weekdaysRegex=new RegExp("^("+mixedPieces.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+longPieces.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+shortPieces.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+minPieces.join("|")+")","i")}function hFormat(){return this.hours()%12||12}function kFormat(){return this.hours()||24}addFormatToken("H",["HH",2],0,"hour"),addFormatToken("h",["hh",2],0,hFormat),addFormatToken("k",["kk",2],0,kFormat),addFormatToken("hmm",0,0,function(){return""+hFormat.apply(this)+zeroFill(this.minutes(),2)}),addFormatToken("hmmss",0,0,function(){return""+hFormat.apply(this)+zeroFill(this.minutes(),2)+zeroFill(this.seconds(),2)}),addFormatToken("Hmm",0,0,function(){return""+this.hours()+zeroFill(this.minutes(),2)}),addFormatToken("Hmmss",0,0,function(){return""+this.hours()+zeroFill(this.minutes(),2)+zeroFill(this.seconds(),2)});function meridiem(token2,lowercase2){addFormatToken(token2,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),lowercase2)})}meridiem("a",!0),meridiem("A",!1);function matchMeridiem(isStrict,locale2){return locale2._meridiemParse}addRegexToken("a",matchMeridiem),addRegexToken("A",matchMeridiem),addRegexToken("H",match1to2,match1to2HasZero),addRegexToken("h",match1to2,match1to2NoLeadingZero),addRegexToken("k",match1to2,match1to2NoLeadingZero),addRegexToken("HH",match1to2,match2),addRegexToken("hh",match1to2,match2),addRegexToken("kk",match1to2,match2),addRegexToken("hmm",match3to4),addRegexToken("hmmss",match5to6),addRegexToken("Hmm",match3to4),addRegexToken("Hmmss",match5to6),addParseToken(["H","HH"],HOUR),addParseToken(["k","kk"],function(input2,array2,config2){var kInput=toInt(input2);array2[HOUR]=kInput===24?0:kInput}),addParseToken(["a","A"],function(input2,array2,config2){config2._isPm=config2._locale.isPM(input2),config2._meridiem=input2}),addParseToken(["h","hh"],function(input2,array2,config2){array2[HOUR]=toInt(input2),getParsingFlags(config2).bigHour=!0}),addParseToken("hmm",function(input2,array2,config2){var pos=input2.length-2;array2[HOUR]=toInt(input2.substr(0,pos)),array2[MINUTE]=toInt(input2.substr(pos)),getParsingFlags(config2).bigHour=!0}),addParseToken("hmmss",function(input2,array2,config2){var pos1=input2.length-4,pos2=input2.length-2;array2[HOUR]=toInt(input2.substr(0,pos1)),array2[MINUTE]=toInt(input2.substr(pos1,2)),array2[SECOND]=toInt(input2.substr(pos2)),getParsingFlags(config2).bigHour=!0}),addParseToken("Hmm",function(input2,array2,config2){var pos=input2.length-2;array2[HOUR]=toInt(input2.substr(0,pos)),array2[MINUTE]=toInt(input2.substr(pos))}),addParseToken("Hmmss",function(input2,array2,config2){var pos1=input2.length-4,pos2=input2.length-2;array2[HOUR]=toInt(input2.substr(0,pos1)),array2[MINUTE]=toInt(input2.substr(pos1,2)),array2[SECOND]=toInt(input2.substr(pos2))});function localeIsPM(input2){return(input2+"").toLowerCase().charAt(0)==="p"}var defaultLocaleMeridiemParse=/[ap]\.?m?\.?/i,getSetHour=makeGetSet("Hours",!0);function localeMeridiem(hours2,minutes2,isLower){return hours2>11?isLower?"pm":"PM":isLower?"am":"AM"}var baseConfig={calendar:defaultCalendar,longDateFormat:defaultLongDateFormat,invalidDate:defaultInvalidDate,ordinal:defaultOrdinal,dayOfMonthOrdinalParse:defaultDayOfMonthOrdinalParse,relativeTime:defaultRelativeTime,months:defaultLocaleMonths,monthsShort:defaultLocaleMonthsShort,week:defaultLocaleWeek,weekdays:defaultLocaleWeekdays,weekdaysMin:defaultLocaleWeekdaysMin,weekdaysShort:defaultLocaleWeekdaysShort,meridiemParse:defaultLocaleMeridiemParse},locales={},localeFamilies={},globalLocale;function commonPrefix(arr1,arr2){var i,minl=Math.min(arr1.length,arr2.length);for(i=0;i<minl;i+=1)if(arr1[i]!==arr2[i])return i;return minl}function normalizeLocale(key){return key&&key.toLowerCase().replace("_","-")}function chooseLocale(names){for(var i=0,j,next,locale2,split;i<names.length;){for(split=normalizeLocale(names[i]).split("-"),j=split.length,next=normalizeLocale(names[i+1]),next=next?next.split("-"):null;j>0;){if(locale2=loadLocale(split.slice(0,j).join("-")),locale2)return locale2;if(next&&next.length>=j&&commonPrefix(split,next)>=j-1)break;j--}i++}return globalLocale}function isLocaleNameSane(name){return!!(name&&name.match("^[^/\\\\]*$"))}function loadLocale(name){var oldLocale=null,aliasedRequire;if(locales[name]===void 0&&typeof module<"u"&&module&&module.exports&&isLocaleNameSane(name))try{oldLocale=globalLocale._abbr,aliasedRequire=__require,aliasedRequire("./locale/"+name),getSetGlobalLocale(oldLocale)}catch{locales[name]=null}return locales[name]}function getSetGlobalLocale(key,values){var data;return key&&(isUndefined(values)?data=getLocale(key):data=defineLocale(key,values),data?globalLocale=data:typeof console<"u"&&console.warn&&console.warn("Locale "+key+" not found. Did you forget to load it?")),globalLocale._abbr}function defineLocale(name,config2){if(config2!==null){var locale2,parentConfig=baseConfig;if(config2.abbr=name,locales[name]!=null)deprecateSimple("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),parentConfig=locales[name]._config;else if(config2.parentLocale!=null)if(locales[config2.parentLocale]!=null)parentConfig=locales[config2.parentLocale]._config;else if(locale2=loadLocale(config2.parentLocale),locale2!=null)parentConfig=locale2._config;else return localeFamilies[config2.parentLocale]||(localeFamilies[config2.parentLocale]=[]),localeFamilies[config2.parentLocale].push({name,config:config2}),null;return locales[name]=new Locale(mergeConfigs(parentConfig,config2)),localeFamilies[name]&&localeFamilies[name].forEach(function(x){defineLocale(x.name,x.config)}),getSetGlobalLocale(name),locales[name]}else return delete locales[name],null}function updateLocale(name,config2){if(config2!=null){var locale2,tmpLocale,parentConfig=baseConfig;locales[name]!=null&&locales[name].parentLocale!=null?locales[name].set(mergeConfigs(locales[name]._config,config2)):(tmpLocale=loadLocale(name),tmpLocale!=null&&(parentConfig=tmpLocale._config),config2=mergeConfigs(parentConfig,config2),tmpLocale==null&&(config2.abbr=name),locale2=new Locale(config2),locale2.parentLocale=locales[name],locales[name]=locale2),getSetGlobalLocale(name)}else locales[name]!=null&&(locales[name].parentLocale!=null?(locales[name]=locales[name].parentLocale,name===getSetGlobalLocale()&&getSetGlobalLocale(name)):locales[name]!=null&&delete locales[name]);return locales[name]}function getLocale(key){var locale2;if(key&&key._locale&&key._locale._abbr&&(key=key._locale._abbr),!key)return globalLocale;if(!isArray(key)){if(locale2=loadLocale(key),locale2)return locale2;key=[key]}return chooseLocale(key)}function listLocales(){return keys(locales)}function checkOverflow(m){var overflow,a=m._a;return a&&getParsingFlags(m).overflow===-2&&(overflow=a[MONTH]<0||a[MONTH]>11?MONTH:a[DATE]<1||a[DATE]>daysInMonth(a[YEAR],a[MONTH])?DATE:a[HOUR]<0||a[HOUR]>24||a[HOUR]===24&&(a[MINUTE]!==0||a[SECOND]!==0||a[MILLISECOND]!==0)?HOUR:a[MINUTE]<0||a[MINUTE]>59?MINUTE:a[SECOND]<0||a[SECOND]>59?SECOND:a[MILLISECOND]<0||a[MILLISECOND]>999?MILLISECOND:-1,getParsingFlags(m)._overflowDayOfYear&&(overflow<YEAR||overflow>DATE)&&(overflow=DATE),getParsingFlags(m)._overflowWeeks&&overflow===-1&&(overflow=WEEK),getParsingFlags(m)._overflowWeekday&&overflow===-1&&(overflow=WEEKDAY),getParsingFlags(m).overflow=overflow),m}var extendedIsoRegex=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,basicIsoRegex=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,tzRegex=/Z|[+-]\d\d(?::?\d\d)?/,isoDates=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/],["YYYYMM",/\d{6}/,!1],["YYYY",/\d{4}/,!1]],isoTimes=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],aspNetJsonRegex=/^\/?Date\((-?\d+)/i,rfc2822=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,obsOffsets={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function configFromISO(config2){var i,l,string4=config2._i,match=extendedIsoRegex.exec(string4)||basicIsoRegex.exec(string4),allowTime,dateFormat,timeFormat,tzFormat,isoDatesLen=isoDates.length,isoTimesLen=isoTimes.length;if(match){for(getParsingFlags(config2).iso=!0,i=0,l=isoDatesLen;i<l;i++)if(isoDates[i][1].exec(match[1])){dateFormat=isoDates[i][0],allowTime=isoDates[i][2]!==!1;break}if(dateFormat==null){config2._isValid=!1;return}if(match[3]){for(i=0,l=isoTimesLen;i<l;i++)if(isoTimes[i][1].exec(match[3])){timeFormat=(match[2]||" ")+isoTimes[i][0];break}if(timeFormat==null){config2._isValid=!1;return}}if(!allowTime&&timeFormat!=null){config2._isValid=!1;return}if(match[4])if(tzRegex.exec(match[4]))tzFormat="Z";else{config2._isValid=!1;return}config2._f=dateFormat+(timeFormat||"")+(tzFormat||""),configFromStringAndFormat(config2)}else config2._isValid=!1}function extractFromRFC2822Strings(yearStr,monthStr,dayStr,hourStr,minuteStr,secondStr){var result=[untruncateYear(yearStr),defaultLocaleMonthsShort.indexOf(monthStr),parseInt(dayStr,10),parseInt(hourStr,10),parseInt(minuteStr,10)];return secondStr&&result.push(parseInt(secondStr,10)),result}function untruncateYear(yearStr){var year=parseInt(yearStr,10);return year<=49?2e3+year:year<=999?1900+year:year}function preprocessRFC2822(s){return s.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,"")}function checkWeekday(weekdayStr,parsedInput,config2){if(weekdayStr){var weekdayProvided=defaultLocaleWeekdaysShort.indexOf(weekdayStr),weekdayActual=new Date(parsedInput[0],parsedInput[1],parsedInput[2]).getDay();if(weekdayProvided!==weekdayActual)return getParsingFlags(config2).weekdayMismatch=!0,config2._isValid=!1,!1}return!0}function calculateOffset(obsOffset,militaryOffset,numOffset){if(obsOffset)return obsOffsets[obsOffset];if(militaryOffset)return 0;var hm=parseInt(numOffset,10),m=hm%100,h=(hm-m)/100;return h*60+m}function configFromRFC2822(config2){var match=rfc2822.exec(preprocessRFC2822(config2._i)),parsedArray;if(match){if(parsedArray=extractFromRFC2822Strings(match[4],match[3],match[2],match[5],match[6],match[7]),!checkWeekday(match[1],parsedArray,config2))return;config2._a=parsedArray,config2._tzm=calculateOffset(match[8],match[9],match[10]),config2._d=createUTCDate.apply(null,config2._a),config2._d.setUTCMinutes(config2._d.getUTCMinutes()-config2._tzm),getParsingFlags(config2).rfc2822=!0}else config2._isValid=!1}function configFromString(config2){var matched=aspNetJsonRegex.exec(config2._i);if(matched!==null){config2._d=new Date(+matched[1]);return}if(configFromISO(config2),config2._isValid===!1)delete config2._isValid;else return;if(configFromRFC2822(config2),config2._isValid===!1)delete config2._isValid;else return;config2._strict?config2._isValid=!1:hooks.createFromInputFallback(config2)}hooks.createFromInputFallback=deprecate("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(config2){config2._d=new Date(config2._i+(config2._useUTC?" UTC":""))});function defaults(a,b,c){return a??b??c}function currentDateArray(config2){var nowValue=new Date(hooks.now());return config2._useUTC?[nowValue.getUTCFullYear(),nowValue.getUTCMonth(),nowValue.getUTCDate()]:[nowValue.getFullYear(),nowValue.getMonth(),nowValue.getDate()]}function configFromArray(config2){var i,date5,input2=[],currentDate,expectedWeekday,yearToUse;if(!config2._d){for(currentDate=currentDateArray(config2),config2._w&&config2._a[DATE]==null&&config2._a[MONTH]==null&&dayOfYearFromWeekInfo(config2),config2._dayOfYear!=null&&(yearToUse=defaults(config2._a[YEAR],currentDate[YEAR]),(config2._dayOfYear>daysInYear(yearToUse)||config2._dayOfYear===0)&&(getParsingFlags(config2)._overflowDayOfYear=!0),date5=createUTCDate(yearToUse,0,config2._dayOfYear),config2._a[MONTH]=date5.getUTCMonth(),config2._a[DATE]=date5.getUTCDate()),i=0;i<3&&config2._a[i]==null;++i)config2._a[i]=input2[i]=currentDate[i];for(;i<7;i++)config2._a[i]=input2[i]=config2._a[i]==null?i===2?1:0:config2._a[i];config2._a[HOUR]===24&&config2._a[MINUTE]===0&&config2._a[SECOND]===0&&config2._a[MILLISECOND]===0&&(config2._nextDay=!0,config2._a[HOUR]=0),config2._d=(config2._useUTC?createUTCDate:createDate).apply(null,input2),expectedWeekday=config2._useUTC?config2._d.getUTCDay():config2._d.getDay(),config2._tzm!=null&&config2._d.setUTCMinutes(config2._d.getUTCMinutes()-config2._tzm),config2._nextDay&&(config2._a[HOUR]=24),config2._w&&typeof config2._w.d<"u"&&config2._w.d!==expectedWeekday&&(getParsingFlags(config2).weekdayMismatch=!0)}}function dayOfYearFromWeekInfo(config2){var w,weekYear,week,weekday,dow,doy,temp,weekdayOverflow,curWeek;w=config2._w,w.GG!=null||w.W!=null||w.E!=null?(dow=1,doy=4,weekYear=defaults(w.GG,config2._a[YEAR],weekOfYear(createLocal(),1,4).year),week=defaults(w.W,1),weekday=defaults(w.E,1),(weekday<1||weekday>7)&&(weekdayOverflow=!0)):(dow=config2._locale._week.dow,doy=config2._locale._week.doy,curWeek=weekOfYear(createLocal(),dow,doy),weekYear=defaults(w.gg,config2._a[YEAR],curWeek.year),week=defaults(w.w,curWeek.week),w.d!=null?(weekday=w.d,(weekday<0||weekday>6)&&(weekdayOverflow=!0)):w.e!=null?(weekday=w.e+dow,(w.e<0||w.e>6)&&(weekdayOverflow=!0)):weekday=dow),week<1||week>weeksInYear(weekYear,dow,doy)?getParsingFlags(config2)._overflowWeeks=!0:weekdayOverflow!=null?getParsingFlags(config2)._overflowWeekday=!0:(temp=dayOfYearFromWeeks(weekYear,week,weekday,dow,doy),config2._a[YEAR]=temp.year,config2._dayOfYear=temp.dayOfYear)}hooks.ISO_8601=function(){},hooks.RFC_2822=function(){};function configFromStringAndFormat(config2){if(config2._f===hooks.ISO_8601){configFromISO(config2);return}if(config2._f===hooks.RFC_2822){configFromRFC2822(config2);return}config2._a=[],getParsingFlags(config2).empty=!0;var string4=""+config2._i,i,parsedInput,tokens2,token2,skipped,stringLength=string4.length,totalParsedInputLength=0,era,tokenLen;for(tokens2=expandFormat(config2._f,config2._locale).match(formattingTokens)||[],tokenLen=tokens2.length,i=0;i<tokenLen;i++)token2=tokens2[i],parsedInput=(string4.match(getParseRegexForToken(token2,config2))||[])[0],parsedInput&&(skipped=string4.substr(0,string4.indexOf(parsedInput)),skipped.length>0&&getParsingFlags(config2).unusedInput.push(skipped),string4=string4.slice(string4.indexOf(parsedInput)+parsedInput.length),totalParsedInputLength+=parsedInput.length),formatTokenFunctions[token2]?(parsedInput?getParsingFlags(config2).empty=!1:getParsingFlags(config2).unusedTokens.push(token2),addTimeToArrayFromToken(token2,parsedInput,config2)):config2._strict&&!parsedInput&&getParsingFlags(config2).unusedTokens.push(token2);getParsingFlags(config2).charsLeftOver=stringLength-totalParsedInputLength,string4.length>0&&getParsingFlags(config2).unusedInput.push(string4),config2._a[HOUR]<=12&&getParsingFlags(config2).bigHour===!0&&config2._a[HOUR]>0&&(getParsingFlags(config2).bigHour=void 0),getParsingFlags(config2).parsedDateParts=config2._a.slice(0),getParsingFlags(config2).meridiem=config2._meridiem,config2._a[HOUR]=meridiemFixWrap(config2._locale,config2._a[HOUR],config2._meridiem),era=getParsingFlags(config2).era,era!==null&&(config2._a[YEAR]=config2._locale.erasConvertYear(era,config2._a[YEAR])),configFromArray(config2),checkOverflow(config2)}function meridiemFixWrap(locale2,hour,meridiem2){var isPm;return meridiem2==null?hour:locale2.meridiemHour!=null?locale2.meridiemHour(hour,meridiem2):(locale2.isPM!=null&&(isPm=locale2.isPM(meridiem2),isPm&&hour<12&&(hour+=12),!isPm&&hour===12&&(hour=0)),hour)}function configFromStringAndArray(config2){var tempConfig,bestMoment,scoreToBeat,i,currentScore,validFormatFound,bestFormatIsValid=!1,configfLen=config2._f.length;if(configfLen===0){getParsingFlags(config2).invalidFormat=!0,config2._d=new Date(NaN);return}for(i=0;i<configfLen;i++)currentScore=0,validFormatFound=!1,tempConfig=copyConfig({},config2),config2._useUTC!=null&&(tempConfig._useUTC=config2._useUTC),tempConfig._f=config2._f[i],configFromStringAndFormat(tempConfig),isValid2(tempConfig)&&(validFormatFound=!0),currentScore+=getParsingFlags(tempConfig).charsLeftOver,currentScore+=getParsingFlags(tempConfig).unusedTokens.length*10,getParsingFlags(tempConfig).score=currentScore,bestFormatIsValid?currentScore<scoreToBeat&&(scoreToBeat=currentScore,bestMoment=tempConfig):(scoreToBeat==null||currentScore<scoreToBeat||validFormatFound)&&(scoreToBeat=currentScore,bestMoment=tempConfig,validFormatFound&&(bestFormatIsValid=!0));extend2(config2,bestMoment||tempConfig)}function configFromObject(config2){if(!config2._d){var i=normalizeObjectUnits(config2._i),dayOrDate=i.day===void 0?i.date:i.day;config2._a=map2([i.year,i.month,dayOrDate,i.hour,i.minute,i.second,i.millisecond],function(obj){return obj&&parseInt(obj,10)}),configFromArray(config2)}}function createFromConfig(config2){var res=new Moment(checkOverflow(prepareConfig(config2)));return res._nextDay&&(res.add(1,"d"),res._nextDay=void 0),res}function prepareConfig(config2){var input2=config2._i,format2=config2._f;return config2._locale=config2._locale||getLocale(config2._l),input2===null||format2===void 0&&input2===""?createInvalid({nullInput:!0}):(typeof input2=="string"&&(config2._i=input2=config2._locale.preparse(input2)),isMoment(input2)?new Moment(checkOverflow(input2)):(isDate(input2)?config2._d=input2:isArray(format2)?configFromStringAndArray(config2):format2?configFromStringAndFormat(config2):configFromInput(config2),isValid2(config2)||(config2._d=null),config2))}function configFromInput(config2){var input2=config2._i;isUndefined(input2)?config2._d=new Date(hooks.now()):isDate(input2)?config2._d=new Date(input2.valueOf()):typeof input2=="string"?configFromString(config2):isArray(input2)?(config2._a=map2(input2.slice(0),function(obj){return parseInt(obj,10)}),configFromArray(config2)):isObject2(input2)?configFromObject(config2):isNumber(input2)?config2._d=new Date(input2):hooks.createFromInputFallback(config2)}function createLocalOrUTC(input2,format2,locale2,strict,isUTC){var c={};return(format2===!0||format2===!1)&&(strict=format2,format2=void 0),(locale2===!0||locale2===!1)&&(strict=locale2,locale2=void 0),(isObject2(input2)&&isObjectEmpty(input2)||isArray(input2)&&input2.length===0)&&(input2=void 0),c._isAMomentObject=!0,c._useUTC=c._isUTC=isUTC,c._l=locale2,c._i=input2,c._f=format2,c._strict=strict,createFromConfig(c)}function createLocal(input2,format2,locale2,strict){return createLocalOrUTC(input2,format2,locale2,strict,!1)}var prototypeMin=deprecate("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var other=createLocal.apply(null,arguments);return this.isValid()&&other.isValid()?other<this?this:other:createInvalid()}),prototypeMax=deprecate("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var other=createLocal.apply(null,arguments);return this.isValid()&&other.isValid()?other>this?this:other:createInvalid()});function pickBy(fn,moments){var res,i;if(moments.length===1&&isArray(moments[0])&&(moments=moments[0]),!moments.length)return createLocal();for(res=moments[0],i=1;i<moments.length;++i)(!moments[i].isValid()||moments[i][fn](res))&&(res=moments[i]);return res}function min(){var args=[].slice.call(arguments,0);return pickBy("isBefore",args)}function max(){var args=[].slice.call(arguments,0);return pickBy("isAfter",args)}var now=function(){return Date.now?Date.now():+new Date},ordering=["year","quarter","month","week","day","hour","minute","second","millisecond"];function isDurationValid(m){var key,unitHasDecimal=!1,i,orderLen=ordering.length;for(key in m)if(hasOwnProp(m,key)&&!(indexOf.call(ordering,key)!==-1&&(m[key]==null||!isNaN(m[key]))))return!1;for(i=0;i<orderLen;++i)if(m[ordering[i]]){if(unitHasDecimal)return!1;parseFloat(m[ordering[i]])!==toInt(m[ordering[i]])&&(unitHasDecimal=!0)}return!0}function isValid$1(){return this._isValid}function createInvalid$1(){return createDuration(NaN)}function Duration(duration3){var normalizedInput=normalizeObjectUnits(duration3),years2=normalizedInput.year||0,quarters=normalizedInput.quarter||0,months2=normalizedInput.month||0,weeks2=normalizedInput.week||normalizedInput.isoWeek||0,days2=normalizedInput.day||0,hours2=normalizedInput.hour||0,minutes2=normalizedInput.minute||0,seconds2=normalizedInput.second||0,milliseconds2=normalizedInput.millisecond||0;this._isValid=isDurationValid(normalizedInput),this._milliseconds=+milliseconds2+seconds2*1e3+minutes2*6e4+hours2*1e3*60*60,this._days=+days2+weeks2*7,this._months=+months2+quarters*3+years2*12,this._data={},this._locale=getLocale(),this._bubble()}function isDuration(obj){return obj instanceof Duration}function absRound(number4){return number4<0?Math.round(-1*number4)*-1:Math.round(number4)}function compareArrays(array1,array2,dontConvert){var len=Math.min(array1.length,array2.length),lengthDiff=Math.abs(array1.length-array2.length),diffs=0,i;for(i=0;i<len;i++)(dontConvert&&array1[i]!==array2[i]||!dontConvert&&toInt(array1[i])!==toInt(array2[i]))&&diffs++;return diffs+lengthDiff}function offset(token2,separator){addFormatToken(token2,0,0,function(){var offset2=this.utcOffset(),sign2="+";return offset2<0&&(offset2=-offset2,sign2="-"),sign2+zeroFill(~~(offset2/60),2)+separator+zeroFill(~~offset2%60,2)})}offset("Z",":"),offset("ZZ",""),addRegexToken("Z",matchShortOffset),addRegexToken("ZZ",matchShortOffset),addParseToken(["Z","ZZ"],function(input2,array2,config2){config2._useUTC=!0,config2._tzm=offsetFromString(matchShortOffset,input2)});var chunkOffset=/([\+\-]|\d\d)/gi;function offsetFromString(matcher,string4){var matches=(string4||"").match(matcher),chunk,parts,minutes2;return matches===null?null:(chunk=matches[matches.length-1]||[],parts=(chunk+"").match(chunkOffset)||["-",0,0],minutes2=+(parts[1]*60)+toInt(parts[2]),minutes2===0?0:parts[0]==="+"?minutes2:-minutes2)}function cloneWithOffset(input2,model){var res,diff2;return model._isUTC?(res=model.clone(),diff2=(isMoment(input2)||isDate(input2)?input2.valueOf():createLocal(input2).valueOf())-res.valueOf(),res._d.setTime(res._d.valueOf()+diff2),hooks.updateOffset(res,!1),res):createLocal(input2).local()}function getDateOffset(m){return-Math.round(m._d.getTimezoneOffset())}hooks.updateOffset=function(){};function getSetOffset(input2,keepLocalTime,keepMinutes){var offset2=this._offset||0,localAdjust;if(!this.isValid())return input2!=null?this:NaN;if(input2!=null){if(typeof input2=="string"){if(input2=offsetFromString(matchShortOffset,input2),input2===null)return this}else Math.abs(input2)<16&&!keepMinutes&&(input2=input2*60);return!this._isUTC&&keepLocalTime&&(localAdjust=getDateOffset(this)),this._offset=input2,this._isUTC=!0,localAdjust!=null&&this.add(localAdjust,"m"),offset2!==input2&&(!keepLocalTime||this._changeInProgress?addSubtract(this,createDuration(input2-offset2,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,hooks.updateOffset(this,!0),this._changeInProgress=null)),this}else return this._isUTC?offset2:getDateOffset(this)}function getSetZone(input2,keepLocalTime){return input2!=null?(typeof input2!="string"&&(input2=-input2),this.utcOffset(input2,keepLocalTime),this):-this.utcOffset()}function setOffsetToUTC(keepLocalTime){return this.utcOffset(0,keepLocalTime)}function setOffsetToLocal(keepLocalTime){return this._isUTC&&(this.utcOffset(0,keepLocalTime),this._isUTC=!1,keepLocalTime&&this.subtract(getDateOffset(this),"m")),this}function setOffsetToParsedOffset(){if(this._tzm!=null)this.utcOffset(this._tzm,!1,!0);else if(typeof this._i=="string"){var tZone=offsetFromString(matchOffset,this._i);tZone!=null?this.utcOffset(tZone):this.utcOffset(0,!0)}return this}function hasAlignedHourOffset(input2){return this.isValid()?(input2=input2?createLocal(input2).utcOffset():0,(this.utcOffset()-input2)%60===0):!1}function isDaylightSavingTime(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function isDaylightSavingTimeShifted(){if(!isUndefined(this._isDSTShifted))return this._isDSTShifted;var c={},other;return copyConfig(c,this),c=prepareConfig(c),c._a?(other=c._isUTC?createUTC(c._a):createLocal(c._a),this._isDSTShifted=this.isValid()&&compareArrays(c._a,other.toArray())>0):this._isDSTShifted=!1,this._isDSTShifted}function isLocal(){return this.isValid()?!this._isUTC:!1}function isUtcOffset(){return this.isValid()?this._isUTC:!1}function isUtc(){return this.isValid()?this._isUTC&&this._offset===0:!1}var aspNetRegex=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,isoRegex=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function createDuration(input2,key){var duration3=input2,match=null,sign2,ret,diffRes;return isDuration(input2)?duration3={ms:input2._milliseconds,d:input2._days,M:input2._months}:isNumber(input2)||!isNaN(+input2)?(duration3={},key?duration3[key]=+input2:duration3.milliseconds=+input2):(match=aspNetRegex.exec(input2))?(sign2=match[1]==="-"?-1:1,duration3={y:0,d:toInt(match[DATE])*sign2,h:toInt(match[HOUR])*sign2,m:toInt(match[MINUTE])*sign2,s:toInt(match[SECOND])*sign2,ms:toInt(absRound(match[MILLISECOND]*1e3))*sign2}):(match=isoRegex.exec(input2))?(sign2=match[1]==="-"?-1:1,duration3={y:parseIso(match[2],sign2),M:parseIso(match[3],sign2),w:parseIso(match[4],sign2),d:parseIso(match[5],sign2),h:parseIso(match[6],sign2),m:parseIso(match[7],sign2),s:parseIso(match[8],sign2)}):duration3==null?duration3={}:typeof duration3=="object"&&("from"in duration3||"to"in duration3)&&(diffRes=momentsDifference(createLocal(duration3.from),createLocal(duration3.to)),duration3={},duration3.ms=diffRes.milliseconds,duration3.M=diffRes.months),ret=new Duration(duration3),isDuration(input2)&&hasOwnProp(input2,"_locale")&&(ret._locale=input2._locale),isDuration(input2)&&hasOwnProp(input2,"_isValid")&&(ret._isValid=input2._isValid),ret}createDuration.fn=Duration.prototype,createDuration.invalid=createInvalid$1;function parseIso(inp,sign2){var res=inp&&parseFloat(inp.replace(",","."));return(isNaN(res)?0:res)*sign2}function positiveMomentsDifference(base,other){var res={};return res.months=other.month()-base.month()+(other.year()-base.year())*12,base.clone().add(res.months,"M").isAfter(other)&&--res.months,res.milliseconds=+other-+base.clone().add(res.months,"M"),res}function momentsDifference(base,other){var res;return base.isValid()&&other.isValid()?(other=cloneWithOffset(other,base),base.isBefore(other)?res=positiveMomentsDifference(base,other):(res=positiveMomentsDifference(other,base),res.milliseconds=-res.milliseconds,res.months=-res.months),res):{milliseconds:0,months:0}}function createAdder(direction,name){return function(val,period){var dur,tmp;return period!==null&&!isNaN(+period)&&(deprecateSimple(name,"moment()."+name+"(period, number) is deprecated. Please use moment()."+name+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),tmp=val,val=period,period=tmp),dur=createDuration(val,period),addSubtract(this,dur,direction),this}}function addSubtract(mom,duration3,isAdding,updateOffset){var milliseconds2=duration3._milliseconds,days2=absRound(duration3._days),months2=absRound(duration3._months);mom.isValid()&&(updateOffset=updateOffset??!0,months2&&setMonth(mom,get(mom,"Month")+months2*isAdding),days2&&set$1(mom,"Date",get(mom,"Date")+days2*isAdding),milliseconds2&&mom._d.setTime(mom._d.valueOf()+milliseconds2*isAdding),updateOffset&&hooks.updateOffset(mom,days2||months2))}var add=createAdder(1,"add"),subtract=createAdder(-1,"subtract");function isString(input2){return typeof input2=="string"||input2 instanceof String}function isMomentInput(input2){return isMoment(input2)||isDate(input2)||isString(input2)||isNumber(input2)||isNumberOrStringArray(input2)||isMomentInputObject(input2)||input2===null||input2===void 0}function isMomentInputObject(input2){var objectTest=isObject2(input2)&&!isObjectEmpty(input2),propertyTest=!1,properties=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],i,property,propertyLen=properties.length;for(i=0;i<propertyLen;i+=1)property=properties[i],propertyTest=propertyTest||hasOwnProp(input2,property);return objectTest&&propertyTest}function isNumberOrStringArray(input2){var arrayTest=isArray(input2),dataTypeTest=!1;return arrayTest&&(dataTypeTest=input2.filter(function(item){return!isNumber(item)&&isString(input2)}).length===0),arrayTest&&dataTypeTest}function isCalendarSpec(input2){var objectTest=isObject2(input2)&&!isObjectEmpty(input2),propertyTest=!1,properties=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"],i,property;for(i=0;i<properties.length;i+=1)property=properties[i],propertyTest=propertyTest||hasOwnProp(input2,property);return objectTest&&propertyTest}function getCalendarFormat(myMoment,now2){var diff2=myMoment.diff(now2,"days",!0);return diff2<-6?"sameElse":diff2<-1?"lastWeek":diff2<0?"lastDay":diff2<1?"sameDay":diff2<2?"nextDay":diff2<7?"nextWeek":"sameElse"}function calendar$1(time3,formats){arguments.length===1&&(arguments[0]?isMomentInput(arguments[0])?(time3=arguments[0],formats=void 0):isCalendarSpec(arguments[0])&&(formats=arguments[0],time3=void 0):(time3=void 0,formats=void 0));var now2=time3||createLocal(),sod=cloneWithOffset(now2,this).startOf("day"),format2=hooks.calendarFormat(this,sod)||"sameElse",output2=formats&&(isFunction(formats[format2])?formats[format2].call(this,now2):formats[format2]);return this.format(output2||this.localeData().calendar(format2,this,createLocal(now2)))}function clone2(){return new Moment(this)}function isAfter(input2,units){var localInput=isMoment(input2)?input2:createLocal(input2);return this.isValid()&&localInput.isValid()?(units=normalizeUnits(units)||"millisecond",units==="millisecond"?this.valueOf()>localInput.valueOf():localInput.valueOf()<this.clone().startOf(units).valueOf()):!1}function isBefore(input2,units){var localInput=isMoment(input2)?input2:createLocal(input2);return this.isValid()&&localInput.isValid()?(units=normalizeUnits(units)||"millisecond",units==="millisecond"?this.valueOf()<localInput.valueOf():this.clone().endOf(units).valueOf()<localInput.valueOf()):!1}function isBetween(from2,to2,units,inclusivity){var localFrom=isMoment(from2)?from2:createLocal(from2),localTo=isMoment(to2)?to2:createLocal(to2);return this.isValid()&&localFrom.isValid()&&localTo.isValid()?(inclusivity=inclusivity||"()",(inclusivity[0]==="("?this.isAfter(localFrom,units):!this.isBefore(localFrom,units))&&(inclusivity[1]===")"?this.isBefore(localTo,units):!this.isAfter(localTo,units))):!1}function isSame(input2,units){var localInput=isMoment(input2)?input2:createLocal(input2),inputMs;return this.isValid()&&localInput.isValid()?(units=normalizeUnits(units)||"millisecond",units==="millisecond"?this.valueOf()===localInput.valueOf():(inputMs=localInput.valueOf(),this.clone().startOf(units).valueOf()<=inputMs&&inputMs<=this.clone().endOf(units).valueOf())):!1}function isSameOrAfter(input2,units){return this.isSame(input2,units)||this.isAfter(input2,units)}function isSameOrBefore(input2,units){return this.isSame(input2,units)||this.isBefore(input2,units)}function diff(input2,units,asFloat){var that,zoneDelta,output2;if(!this.isValid())return NaN;if(that=cloneWithOffset(input2,this),!that.isValid())return NaN;switch(zoneDelta=(that.utcOffset()-this.utcOffset())*6e4,units=normalizeUnits(units),units){case"year":output2=monthDiff(this,that)/12;break;case"month":output2=monthDiff(this,that);break;case"quarter":output2=monthDiff(this,that)/3;break;case"second":output2=(this-that)/1e3;break;case"minute":output2=(this-that)/6e4;break;case"hour":output2=(this-that)/36e5;break;case"day":output2=(this-that-zoneDelta)/864e5;break;case"week":output2=(this-that-zoneDelta)/6048e5;break;default:output2=this-that}return asFloat?output2:absFloor(output2)}function monthDiff(a,b){if(a.date()<b.date())return-monthDiff(b,a);var wholeMonthDiff=(b.year()-a.year())*12+(b.month()-a.month()),anchor=a.clone().add(wholeMonthDiff,"months"),anchor2,adjust;return b-anchor<0?(anchor2=a.clone().add(wholeMonthDiff-1,"months"),adjust=(b-anchor)/(anchor-anchor2)):(anchor2=a.clone().add(wholeMonthDiff+1,"months"),adjust=(b-anchor)/(anchor2-anchor)),-(wholeMonthDiff+adjust)||0}hooks.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",hooks.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";function toString(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function toISOString(keepOffset){if(!this.isValid())return null;var utc=keepOffset!==!0,m=utc?this.clone().utc():this;return m.year()<0||m.year()>9999?formatMoment(m,utc?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):isFunction(Date.prototype.toISOString)?utc?this.toDate().toISOString():new Date(this.valueOf()+this.utcOffset()*60*1e3).toISOString().replace("Z",formatMoment(m,"Z")):formatMoment(m,utc?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")}function inspect(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var func="moment",zone="",prefix,year,datetime3,suffix;return this.isLocal()||(func=this.utcOffset()===0?"moment.utc":"moment.parseZone",zone="Z"),prefix="["+func+'("]',year=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",datetime3="-MM-DD[T]HH:mm:ss.SSS",suffix=zone+'[")]',this.format(prefix+year+datetime3+suffix)}function format(inputString){inputString||(inputString=this.isUtc()?hooks.defaultFormatUtc:hooks.defaultFormat);var output2=formatMoment(this,inputString);return this.localeData().postformat(output2)}function from(time3,withoutSuffix){return this.isValid()&&(isMoment(time3)&&time3.isValid()||createLocal(time3).isValid())?createDuration({to:this,from:time3}).locale(this.locale()).humanize(!withoutSuffix):this.localeData().invalidDate()}function fromNow(withoutSuffix){return this.from(createLocal(),withoutSuffix)}function to(time3,withoutSuffix){return this.isValid()&&(isMoment(time3)&&time3.isValid()||createLocal(time3).isValid())?createDuration({from:this,to:time3}).locale(this.locale()).humanize(!withoutSuffix):this.localeData().invalidDate()}function toNow(withoutSuffix){return this.to(createLocal(),withoutSuffix)}function locale(key){var newLocaleData;return key===void 0?this._locale._abbr:(newLocaleData=getLocale(key),newLocaleData!=null&&(this._locale=newLocaleData),this)}var lang=deprecate("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(key){return key===void 0?this.localeData():this.locale(key)});function localeData(){return this._locale}var MS_PER_SECOND=1e3,MS_PER_MINUTE=60*MS_PER_SECOND,MS_PER_HOUR=60*MS_PER_MINUTE,MS_PER_400_YEARS=(365*400+97)*24*MS_PER_HOUR;function mod$1(dividend,divisor){return(dividend%divisor+divisor)%divisor}function localStartOfDate(y,m,d){return y<100&&y>=0?new Date(y+400,m,d)-MS_PER_400_YEARS:new Date(y,m,d).valueOf()}function utcStartOfDate(y,m,d){return y<100&&y>=0?Date.UTC(y+400,m,d)-MS_PER_400_YEARS:Date.UTC(y,m,d)}function startOf(units){var time3,startOfDate;if(units=normalizeUnits(units),units===void 0||units==="millisecond"||!this.isValid())return this;switch(startOfDate=this._isUTC?utcStartOfDate:localStartOfDate,units){case"year":time3=startOfDate(this.year(),0,1);break;case"quarter":time3=startOfDate(this.year(),this.month()-this.month()%3,1);break;case"month":time3=startOfDate(this.year(),this.month(),1);break;case"week":time3=startOfDate(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":time3=startOfDate(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":time3=startOfDate(this.year(),this.month(),this.date());break;case"hour":time3=this._d.valueOf(),time3-=mod$1(time3+(this._isUTC?0:this.utcOffset()*MS_PER_MINUTE),MS_PER_HOUR);break;case"minute":time3=this._d.valueOf(),time3-=mod$1(time3,MS_PER_MINUTE);break;case"second":time3=this._d.valueOf(),time3-=mod$1(time3,MS_PER_SECOND);break}return this._d.setTime(time3),hooks.updateOffset(this,!0),this}function endOf(units){var time3,startOfDate;if(units=normalizeUnits(units),units===void 0||units==="millisecond"||!this.isValid())return this;switch(startOfDate=this._isUTC?utcStartOfDate:localStartOfDate,units){case"year":time3=startOfDate(this.year()+1,0,1)-1;break;case"quarter":time3=startOfDate(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":time3=startOfDate(this.year(),this.month()+1,1)-1;break;case"week":time3=startOfDate(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":time3=startOfDate(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":time3=startOfDate(this.year(),this.month(),this.date()+1)-1;break;case"hour":time3=this._d.valueOf(),time3+=MS_PER_HOUR-mod$1(time3+(this._isUTC?0:this.utcOffset()*MS_PER_MINUTE),MS_PER_HOUR)-1;break;case"minute":time3=this._d.valueOf(),time3+=MS_PER_MINUTE-mod$1(time3,MS_PER_MINUTE)-1;break;case"second":time3=this._d.valueOf(),time3+=MS_PER_SECOND-mod$1(time3,MS_PER_SECOND)-1;break}return this._d.setTime(time3),hooks.updateOffset(this,!0),this}function valueOf(){return this._d.valueOf()-(this._offset||0)*6e4}function unix(){return Math.floor(this.valueOf()/1e3)}function toDate(){return new Date(this.valueOf())}function toArray(){var m=this;return[m.year(),m.month(),m.date(),m.hour(),m.minute(),m.second(),m.millisecond()]}function toObject(){var m=this;return{years:m.year(),months:m.month(),date:m.date(),hours:m.hours(),minutes:m.minutes(),seconds:m.seconds(),milliseconds:m.milliseconds()}}function toJSON(){return this.isValid()?this.toISOString():null}function isValid$2(){return isValid2(this)}function parsingFlags(){return extend2({},getParsingFlags(this))}function invalidAt(){return getParsingFlags(this).overflow}function creationData(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}addFormatToken("N",0,0,"eraAbbr"),addFormatToken("NN",0,0,"eraAbbr"),addFormatToken("NNN",0,0,"eraAbbr"),addFormatToken("NNNN",0,0,"eraName"),addFormatToken("NNNNN",0,0,"eraNarrow"),addFormatToken("y",["y",1],"yo","eraYear"),addFormatToken("y",["yy",2],0,"eraYear"),addFormatToken("y",["yyy",3],0,"eraYear"),addFormatToken("y",["yyyy",4],0,"eraYear"),addRegexToken("N",matchEraAbbr),addRegexToken("NN",matchEraAbbr),addRegexToken("NNN",matchEraAbbr),addRegexToken("NNNN",matchEraName),addRegexToken("NNNNN",matchEraNarrow),addParseToken(["N","NN","NNN","NNNN","NNNNN"],function(input2,array2,config2,token2){var era=config2._locale.erasParse(input2,token2,config2._strict);era?getParsingFlags(config2).era=era:getParsingFlags(config2).invalidEra=input2}),addRegexToken("y",matchUnsigned),addRegexToken("yy",matchUnsigned),addRegexToken("yyy",matchUnsigned),addRegexToken("yyyy",matchUnsigned),addRegexToken("yo",matchEraYearOrdinal),addParseToken(["y","yy","yyy","yyyy"],YEAR),addParseToken(["yo"],function(input2,array2,config2,token2){var match;config2._locale._eraYearOrdinalRegex&&(match=input2.match(config2._locale._eraYearOrdinalRegex)),config2._locale.eraYearOrdinalParse?array2[YEAR]=config2._locale.eraYearOrdinalParse(input2,match):array2[YEAR]=parseInt(input2,10)});function localeEras(m,format2){var i,l,date5,eras=this._eras||getLocale("en")._eras;for(i=0,l=eras.length;i<l;++i){switch(typeof eras[i].since){case"string":date5=hooks(eras[i].since).startOf("day"),eras[i].since=date5.valueOf();break}switch(typeof eras[i].until){case"undefined":eras[i].until=1/0;break;case"string":date5=hooks(eras[i].until).startOf("day").valueOf(),eras[i].until=date5.valueOf();break}}return eras}function localeErasParse(eraName,format2,strict){var i,l,eras=this.eras(),name,abbr,narrow;for(eraName=eraName.toUpperCase(),i=0,l=eras.length;i<l;++i)if(name=eras[i].name.toUpperCase(),abbr=eras[i].abbr.toUpperCase(),narrow=eras[i].narrow.toUpperCase(),strict)switch(format2){case"N":case"NN":case"NNN":if(abbr===eraName)return eras[i];break;case"NNNN":if(name===eraName)return eras[i];break;case"NNNNN":if(narrow===eraName)return eras[i];break}else if([name,abbr,narrow].indexOf(eraName)>=0)return eras[i]}function localeErasConvertYear(era,year){var dir=era.since<=era.until?1:-1;return year===void 0?hooks(era.since).year():hooks(era.since).year()+(year-era.offset)*dir}function getEraName(){var i,l,val,eras=this.localeData().eras();for(i=0,l=eras.length;i<l;++i)if(val=this.clone().startOf("day").valueOf(),eras[i].since<=val&&val<=eras[i].until||eras[i].until<=val&&val<=eras[i].since)return eras[i].name;return""}function getEraNarrow(){var i,l,val,eras=this.localeData().eras();for(i=0,l=eras.length;i<l;++i)if(val=this.clone().startOf("day").valueOf(),eras[i].since<=val&&val<=eras[i].until||eras[i].until<=val&&val<=eras[i].since)return eras[i].narrow;return""}function getEraAbbr(){var i,l,val,eras=this.localeData().eras();for(i=0,l=eras.length;i<l;++i)if(val=this.clone().startOf("day").valueOf(),eras[i].since<=val&&val<=eras[i].until||eras[i].until<=val&&val<=eras[i].since)return eras[i].abbr;return""}function getEraYear(){var i,l,dir,val,eras=this.localeData().eras();for(i=0,l=eras.length;i<l;++i)if(dir=eras[i].since<=eras[i].until?1:-1,val=this.clone().startOf("day").valueOf(),eras[i].since<=val&&val<=eras[i].until||eras[i].until<=val&&val<=eras[i].since)return(this.year()-hooks(eras[i].since).year())*dir+eras[i].offset;return this.year()}function erasNameRegex(isStrict){return hasOwnProp(this,"_erasNameRegex")||computeErasParse.call(this),isStrict?this._erasNameRegex:this._erasRegex}function erasAbbrRegex(isStrict){return hasOwnProp(this,"_erasAbbrRegex")||computeErasParse.call(this),isStrict?this._erasAbbrRegex:this._erasRegex}function erasNarrowRegex(isStrict){return hasOwnProp(this,"_erasNarrowRegex")||computeErasParse.call(this),isStrict?this._erasNarrowRegex:this._erasRegex}function matchEraAbbr(isStrict,locale2){return locale2.erasAbbrRegex(isStrict)}function matchEraName(isStrict,locale2){return locale2.erasNameRegex(isStrict)}function matchEraNarrow(isStrict,locale2){return locale2.erasNarrowRegex(isStrict)}function matchEraYearOrdinal(isStrict,locale2){return locale2._eraYearOrdinalRegex||matchUnsigned}function computeErasParse(){var abbrPieces=[],namePieces=[],narrowPieces=[],mixedPieces=[],i,l,erasName,erasAbbr,erasNarrow,eras=this.eras();for(i=0,l=eras.length;i<l;++i)erasName=regexEscape(eras[i].name),erasAbbr=regexEscape(eras[i].abbr),erasNarrow=regexEscape(eras[i].narrow),namePieces.push(erasName),abbrPieces.push(erasAbbr),narrowPieces.push(erasNarrow),mixedPieces.push(erasName),mixedPieces.push(erasAbbr),mixedPieces.push(erasNarrow);this._erasRegex=new RegExp("^("+mixedPieces.join("|")+")","i"),this._erasNameRegex=new RegExp("^("+namePieces.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+abbrPieces.join("|")+")","i"),this._erasNarrowRegex=new RegExp("^("+narrowPieces.join("|")+")","i")}addFormatToken(0,["gg",2],0,function(){return this.weekYear()%100}),addFormatToken(0,["GG",2],0,function(){return this.isoWeekYear()%100});function addWeekYearFormatToken(token2,getter){addFormatToken(0,[token2,token2.length],0,getter)}addWeekYearFormatToken("gggg","weekYear"),addWeekYearFormatToken("ggggg","weekYear"),addWeekYearFormatToken("GGGG","isoWeekYear"),addWeekYearFormatToken("GGGGG","isoWeekYear"),addRegexToken("G",matchSigned),addRegexToken("g",matchSigned),addRegexToken("GG",match1to2,match2),addRegexToken("gg",match1to2,match2),addRegexToken("GGGG",match1to4,match4),addRegexToken("gggg",match1to4,match4),addRegexToken("GGGGG",match1to6,match6),addRegexToken("ggggg",match1to6,match6),addWeekParseToken(["gggg","ggggg","GGGG","GGGGG"],function(input2,week,config2,token2){week[token2.substr(0,2)]=toInt(input2)}),addWeekParseToken(["gg","GG"],function(input2,week,config2,token2){week[token2]=hooks.parseTwoDigitYear(input2)});function getSetWeekYear(input2){return getSetWeekYearHelper.call(this,input2,this.week(),this.weekday()+this.localeData()._week.dow,this.localeData()._week.dow,this.localeData()._week.doy)}function getSetISOWeekYear(input2){return getSetWeekYearHelper.call(this,input2,this.isoWeek(),this.isoWeekday(),1,4)}function getISOWeeksInYear(){return weeksInYear(this.year(),1,4)}function getISOWeeksInISOWeekYear(){return weeksInYear(this.isoWeekYear(),1,4)}function getWeeksInYear(){var weekInfo=this.localeData()._week;return weeksInYear(this.year(),weekInfo.dow,weekInfo.doy)}function getWeeksInWeekYear(){var weekInfo=this.localeData()._week;return weeksInYear(this.weekYear(),weekInfo.dow,weekInfo.doy)}function getSetWeekYearHelper(input2,week,weekday,dow,doy){var weeksTarget;return input2==null?weekOfYear(this,dow,doy).year:(weeksTarget=weeksInYear(input2,dow,doy),week>weeksTarget&&(week=weeksTarget),setWeekAll.call(this,input2,week,weekday,dow,doy))}function setWeekAll(weekYear,week,weekday,dow,doy){var dayOfYearData=dayOfYearFromWeeks(weekYear,week,weekday,dow,doy),date5=createUTCDate(dayOfYearData.year,0,dayOfYearData.dayOfYear);return this.year(date5.getUTCFullYear()),this.month(date5.getUTCMonth()),this.date(date5.getUTCDate()),this}addFormatToken("Q",0,"Qo","quarter"),addRegexToken("Q",match1),addParseToken("Q",function(input2,array2){array2[MONTH]=(toInt(input2)-1)*3});function getSetQuarter(input2){return input2==null?Math.ceil((this.month()+1)/3):this.month((input2-1)*3+this.month()%3)}addFormatToken("D",["DD",2],"Do","date"),addRegexToken("D",match1to2,match1to2NoLeadingZero),addRegexToken("DD",match1to2,match2),addRegexToken("Do",function(isStrict,locale2){return isStrict?locale2._dayOfMonthOrdinalParse||locale2._ordinalParse:locale2._dayOfMonthOrdinalParseLenient}),addParseToken(["D","DD"],DATE),addParseToken("Do",function(input2,array2){array2[DATE]=toInt(input2.match(match1to2)[0])});var getSetDayOfMonth=makeGetSet("Date",!0);addFormatToken("DDD",["DDDD",3],"DDDo","dayOfYear"),addRegexToken("DDD",match1to3),addRegexToken("DDDD",match3),addParseToken(["DDD","DDDD"],function(input2,array2,config2){config2._dayOfYear=toInt(input2)});function getSetDayOfYear(input2){var dayOfYear=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return input2==null?dayOfYear:this.add(input2-dayOfYear,"d")}addFormatToken("m",["mm",2],0,"minute"),addRegexToken("m",match1to2,match1to2HasZero),addRegexToken("mm",match1to2,match2),addParseToken(["m","mm"],MINUTE);var getSetMinute=makeGetSet("Minutes",!1);addFormatToken("s",["ss",2],0,"second"),addRegexToken("s",match1to2,match1to2HasZero),addRegexToken("ss",match1to2,match2),addParseToken(["s","ss"],SECOND);var getSetSecond=makeGetSet("Seconds",!1);addFormatToken("S",0,0,function(){return~~(this.millisecond()/100)}),addFormatToken(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),addFormatToken(0,["SSS",3],0,"millisecond"),addFormatToken(0,["SSSS",4],0,function(){return this.millisecond()*10}),addFormatToken(0,["SSSSS",5],0,function(){return this.millisecond()*100}),addFormatToken(0,["SSSSSS",6],0,function(){return this.millisecond()*1e3}),addFormatToken(0,["SSSSSSS",7],0,function(){return this.millisecond()*1e4}),addFormatToken(0,["SSSSSSSS",8],0,function(){return this.millisecond()*1e5}),addFormatToken(0,["SSSSSSSSS",9],0,function(){return this.millisecond()*1e6}),addRegexToken("S",match1to3,match1),addRegexToken("SS",match1to3,match2),addRegexToken("SSS",match1to3,match3);var token,getSetMillisecond;for(token="SSSS";token.length<=9;token+="S")addRegexToken(token,matchUnsigned);function parseMs(input2,array2){array2[MILLISECOND]=toInt(("0."+input2)*1e3)}for(token="S";token.length<=9;token+="S")addParseToken(token,parseMs);getSetMillisecond=makeGetSet("Milliseconds",!1),addFormatToken("z",0,0,"zoneAbbr"),addFormatToken("zz",0,0,"zoneName");function getZoneAbbr(){return this._isUTC?"UTC":""}function getZoneName(){return this._isUTC?"Coordinated Universal Time":""}var proto=Moment.prototype;proto.add=add,proto.calendar=calendar$1,proto.clone=clone2,proto.diff=diff,proto.endOf=endOf,proto.format=format,proto.from=from,proto.fromNow=fromNow,proto.to=to,proto.toNow=toNow,proto.get=stringGet,proto.invalidAt=invalidAt,proto.isAfter=isAfter,proto.isBefore=isBefore,proto.isBetween=isBetween,proto.isSame=isSame,proto.isSameOrAfter=isSameOrAfter,proto.isSameOrBefore=isSameOrBefore,proto.isValid=isValid$2,proto.lang=lang,proto.locale=locale,proto.localeData=localeData,proto.max=prototypeMax,proto.min=prototypeMin,proto.parsingFlags=parsingFlags,proto.set=stringSet,proto.startOf=startOf,proto.subtract=subtract,proto.toArray=toArray,proto.toObject=toObject,proto.toDate=toDate,proto.toISOString=toISOString,proto.inspect=inspect,typeof Symbol<"u"&&Symbol.for!=null&&(proto[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),proto.toJSON=toJSON,proto.toString=toString,proto.unix=unix,proto.valueOf=valueOf,proto.creationData=creationData,proto.eraName=getEraName,proto.eraNarrow=getEraNarrow,proto.eraAbbr=getEraAbbr,proto.eraYear=getEraYear,proto.year=getSetYear,proto.isLeapYear=getIsLeapYear,proto.weekYear=getSetWeekYear,proto.isoWeekYear=getSetISOWeekYear,proto.quarter=proto.quarters=getSetQuarter,proto.month=getSetMonth,proto.daysInMonth=getDaysInMonth,proto.week=proto.weeks=getSetWeek,proto.isoWeek=proto.isoWeeks=getSetISOWeek,proto.weeksInYear=getWeeksInYear,proto.weeksInWeekYear=getWeeksInWeekYear,proto.isoWeeksInYear=getISOWeeksInYear,proto.isoWeeksInISOWeekYear=getISOWeeksInISOWeekYear,proto.date=getSetDayOfMonth,proto.day=proto.days=getSetDayOfWeek,proto.weekday=getSetLocaleDayOfWeek,proto.isoWeekday=getSetISODayOfWeek,proto.dayOfYear=getSetDayOfYear,proto.hour=proto.hours=getSetHour,proto.minute=proto.minutes=getSetMinute,proto.second=proto.seconds=getSetSecond,proto.millisecond=proto.milliseconds=getSetMillisecond,proto.utcOffset=getSetOffset,proto.utc=setOffsetToUTC,proto.local=setOffsetToLocal,proto.parseZone=setOffsetToParsedOffset,proto.hasAlignedHourOffset=hasAlignedHourOffset,proto.isDST=isDaylightSavingTime,proto.isLocal=isLocal,proto.isUtcOffset=isUtcOffset,proto.isUtc=isUtc,proto.isUTC=isUtc,proto.zoneAbbr=getZoneAbbr,proto.zoneName=getZoneName,proto.dates=deprecate("dates accessor is deprecated. Use date instead.",getSetDayOfMonth),proto.months=deprecate("months accessor is deprecated. Use month instead",getSetMonth),proto.years=deprecate("years accessor is deprecated. Use year instead",getSetYear),proto.zone=deprecate("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",getSetZone),proto.isDSTShifted=deprecate("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",isDaylightSavingTimeShifted);function createUnix(input2){return createLocal(input2*1e3)}function createInZone(){return createLocal.apply(null,arguments).parseZone()}function preParsePostFormat(string4){return string4}var proto$1=Locale.prototype;proto$1.calendar=calendar,proto$1.longDateFormat=longDateFormat,proto$1.invalidDate=invalidDate,proto$1.ordinal=ordinal,proto$1.preparse=preParsePostFormat,proto$1.postformat=preParsePostFormat,proto$1.relativeTime=relativeTime,proto$1.pastFuture=pastFuture,proto$1.set=set2,proto$1.eras=localeEras,proto$1.erasParse=localeErasParse,proto$1.erasConvertYear=localeErasConvertYear,proto$1.erasAbbrRegex=erasAbbrRegex,proto$1.erasNameRegex=erasNameRegex,proto$1.erasNarrowRegex=erasNarrowRegex,proto$1.months=localeMonths,proto$1.monthsShort=localeMonthsShort,proto$1.monthsParse=localeMonthsParse,proto$1.monthsRegex=monthsRegex,proto$1.monthsShortRegex=monthsShortRegex,proto$1.week=localeWeek,proto$1.firstDayOfYear=localeFirstDayOfYear,proto$1.firstDayOfWeek=localeFirstDayOfWeek,proto$1.weekdays=localeWeekdays,proto$1.weekdaysMin=localeWeekdaysMin,proto$1.weekdaysShort=localeWeekdaysShort,proto$1.weekdaysParse=localeWeekdaysParse,proto$1.weekdaysRegex=weekdaysRegex,proto$1.weekdaysShortRegex=weekdaysShortRegex,proto$1.weekdaysMinRegex=weekdaysMinRegex,proto$1.isPM=localeIsPM,proto$1.meridiem=localeMeridiem;function get$1(format2,index,field,setter){var locale2=getLocale(),utc=createUTC().set(setter,index);return locale2[field](utc,format2)}function listMonthsImpl(format2,index,field){if(isNumber(format2)&&(index=format2,format2=void 0),format2=format2||"",index!=null)return get$1(format2,index,field,"month");var i,out=[];for(i=0;i<12;i++)out[i]=get$1(format2,i,field,"month");return out}function listWeekdaysImpl(localeSorted,format2,index,field){typeof localeSorted=="boolean"?(isNumber(format2)&&(index=format2,format2=void 0),format2=format2||""):(format2=localeSorted,index=format2,localeSorted=!1,isNumber(format2)&&(index=format2,format2=void 0),format2=format2||"");var locale2=getLocale(),shift=localeSorted?locale2._week.dow:0,i,out=[];if(index!=null)return get$1(format2,(index+shift)%7,field,"day");for(i=0;i<7;i++)out[i]=get$1(format2,(i+shift)%7,field,"day");return out}function listMonths(format2,index){return listMonthsImpl(format2,index,"months")}function listMonthsShort(format2,index){return listMonthsImpl(format2,index,"monthsShort")}function listWeekdays(localeSorted,format2,index){return listWeekdaysImpl(localeSorted,format2,index,"weekdays")}function listWeekdaysShort(localeSorted,format2,index){return listWeekdaysImpl(localeSorted,format2,index,"weekdaysShort")}function listWeekdaysMin(localeSorted,format2,index){return listWeekdaysImpl(localeSorted,format2,index,"weekdaysMin")}getSetGlobalLocale("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(number4){var b=number4%10,output2=toInt(number4%100/10)===1?"th":b===1?"st":b===2?"nd":b===3?"rd":"th";return number4+output2}}),hooks.lang=deprecate("moment.lang is deprecated. Use moment.locale instead.",getSetGlobalLocale),hooks.langData=deprecate("moment.langData is deprecated. Use moment.localeData instead.",getLocale);var mathAbs=Math.abs;function abs(){var data=this._data;return this._milliseconds=mathAbs(this._milliseconds),this._days=mathAbs(this._days),this._months=mathAbs(this._months),data.milliseconds=mathAbs(data.milliseconds),data.seconds=mathAbs(data.seconds),data.minutes=mathAbs(data.minutes),data.hours=mathAbs(data.hours),data.months=mathAbs(data.months),data.years=mathAbs(data.years),this}function addSubtract$1(duration3,input2,value,direction){var other=createDuration(input2,value);return duration3._milliseconds+=direction*other._milliseconds,duration3._days+=direction*other._days,duration3._months+=direction*other._months,duration3._bubble()}function add$1(input2,value){return addSubtract$1(this,input2,value,1)}function subtract$1(input2,value){return addSubtract$1(this,input2,value,-1)}function absCeil(number4){return number4<0?Math.floor(number4):Math.ceil(number4)}function bubble(){var milliseconds2=this._milliseconds,days2=this._days,months2=this._months,data=this._data,seconds2,minutes2,hours2,years2,monthsFromDays;return milliseconds2>=0&&days2>=0&&months2>=0||milliseconds2<=0&&days2<=0&&months2<=0||(milliseconds2+=absCeil(monthsToDays(months2)+days2)*864e5,days2=0,months2=0),data.milliseconds=milliseconds2%1e3,seconds2=absFloor(milliseconds2/1e3),data.seconds=seconds2%60,minutes2=absFloor(seconds2/60),data.minutes=minutes2%60,hours2=absFloor(minutes2/60),data.hours=hours2%24,days2+=absFloor(hours2/24),monthsFromDays=absFloor(daysToMonths(days2)),months2+=monthsFromDays,days2-=absCeil(monthsToDays(monthsFromDays)),years2=absFloor(months2/12),months2%=12,data.days=days2,data.months=months2,data.years=years2,this}function daysToMonths(days2){return days2*4800/146097}function monthsToDays(months2){return months2*146097/4800}function as(units){if(!this.isValid())return NaN;var days2,months2,milliseconds2=this._milliseconds;if(units=normalizeUnits(units),units==="month"||units==="quarter"||units==="year")switch(days2=this._days+milliseconds2/864e5,months2=this._months+daysToMonths(days2),units){case"month":return months2;case"quarter":return months2/3;case"year":return months2/12}else switch(days2=this._days+Math.round(monthsToDays(this._months)),units){case"week":return days2/7+milliseconds2/6048e5;case"day":return days2+milliseconds2/864e5;case"hour":return days2*24+milliseconds2/36e5;case"minute":return days2*1440+milliseconds2/6e4;case"second":return days2*86400+milliseconds2/1e3;case"millisecond":return Math.floor(days2*864e5)+milliseconds2;default:throw new Error("Unknown unit "+units)}}function makeAs(alias){return function(){return this.as(alias)}}var asMilliseconds=makeAs("ms"),asSeconds=makeAs("s"),asMinutes=makeAs("m"),asHours=makeAs("h"),asDays=makeAs("d"),asWeeks=makeAs("w"),asMonths=makeAs("M"),asQuarters=makeAs("Q"),asYears=makeAs("y"),valueOf$1=asMilliseconds;function clone$1(){return createDuration(this)}function get$2(units){return units=normalizeUnits(units),this.isValid()?this[units+"s"]():NaN}function makeGetter(name){return function(){return this.isValid()?this._data[name]:NaN}}var milliseconds=makeGetter("milliseconds"),seconds=makeGetter("seconds"),minutes=makeGetter("minutes"),hours=makeGetter("hours"),days=makeGetter("days"),months=makeGetter("months"),years=makeGetter("years");function weeks(){return absFloor(this.days()/7)}var round=Math.round,thresholds={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function substituteTimeAgo(string4,number4,withoutSuffix,isFuture,locale2){return locale2.relativeTime(number4||1,!!withoutSuffix,string4,isFuture)}function relativeTime$1(posNegDuration,withoutSuffix,thresholds2,locale2){var duration3=createDuration(posNegDuration).abs(),seconds2=round(duration3.as("s")),minutes2=round(duration3.as("m")),hours2=round(duration3.as("h")),days2=round(duration3.as("d")),months2=round(duration3.as("M")),weeks2=round(duration3.as("w")),years2=round(duration3.as("y")),a=seconds2<=thresholds2.ss&&["s",seconds2]||seconds2<thresholds2.s&&["ss",seconds2]||minutes2<=1&&["m"]||minutes2<thresholds2.m&&["mm",minutes2]||hours2<=1&&["h"]||hours2<thresholds2.h&&["hh",hours2]||days2<=1&&["d"]||days2<thresholds2.d&&["dd",days2];return thresholds2.w!=null&&(a=a||weeks2<=1&&["w"]||weeks2<thresholds2.w&&["ww",weeks2]),a=a||months2<=1&&["M"]||months2<thresholds2.M&&["MM",months2]||years2<=1&&["y"]||["yy",years2],a[2]=withoutSuffix,a[3]=+posNegDuration>0,a[4]=locale2,substituteTimeAgo.apply(null,a)}function getSetRelativeTimeRounding(roundingFunction){return roundingFunction===void 0?round:typeof roundingFunction=="function"?(round=roundingFunction,!0):!1}function getSetRelativeTimeThreshold(threshold,limit){return thresholds[threshold]===void 0?!1:limit===void 0?thresholds[threshold]:(thresholds[threshold]=limit,threshold==="s"&&(thresholds.ss=limit-1),!0)}function humanize(argWithSuffix,argThresholds){if(!this.isValid())return this.localeData().invalidDate();var withSuffix=!1,th=thresholds,locale2,output2;return typeof argWithSuffix=="object"&&(argThresholds=argWithSuffix,argWithSuffix=!1),typeof argWithSuffix=="boolean"&&(withSuffix=argWithSuffix),typeof argThresholds=="object"&&(th=Object.assign({},thresholds,argThresholds),argThresholds.s!=null&&argThresholds.ss==null&&(th.ss=argThresholds.s-1)),locale2=this.localeData(),output2=relativeTime$1(this,!withSuffix,th,locale2),withSuffix&&(output2=locale2.pastFuture(+this,output2)),locale2.postformat(output2)}var abs$1=Math.abs;function sign(x){return(x>0)-(x<0)||+x}function toISOString$1(){if(!this.isValid())return this.localeData().invalidDate();var seconds2=abs$1(this._milliseconds)/1e3,days2=abs$1(this._days),months2=abs$1(this._months),minutes2,hours2,years2,s,total=this.asSeconds(),totalSign,ymSign,daysSign,hmsSign;return total?(minutes2=absFloor(seconds2/60),hours2=absFloor(minutes2/60),seconds2%=60,minutes2%=60,years2=absFloor(months2/12),months2%=12,s=seconds2?seconds2.toFixed(3).replace(/\.?0+$/,""):"",totalSign=total<0?"-":"",ymSign=sign(this._months)!==sign(total)?"-":"",daysSign=sign(this._days)!==sign(total)?"-":"",hmsSign=sign(this._milliseconds)!==sign(total)?"-":"",totalSign+"P"+(years2?ymSign+years2+"Y":"")+(months2?ymSign+months2+"M":"")+(days2?daysSign+days2+"D":"")+(hours2||minutes2||seconds2?"T":"")+(hours2?hmsSign+hours2+"H":"")+(minutes2?hmsSign+minutes2+"M":"")+(seconds2?hmsSign+s+"S":"")):"P0D"}var proto$2=Duration.prototype;proto$2.isValid=isValid$1,proto$2.abs=abs,proto$2.add=add$1,proto$2.subtract=subtract$1,proto$2.as=as,proto$2.asMilliseconds=asMilliseconds,proto$2.asSeconds=asSeconds,proto$2.asMinutes=asMinutes,proto$2.asHours=asHours,proto$2.asDays=asDays,proto$2.asWeeks=asWeeks,proto$2.asMonths=asMonths,proto$2.asQuarters=asQuarters,proto$2.asYears=asYears,proto$2.valueOf=valueOf$1,proto$2._bubble=bubble,proto$2.clone=clone$1,proto$2.get=get$2,proto$2.milliseconds=milliseconds,proto$2.seconds=seconds,proto$2.minutes=minutes,proto$2.hours=hours,proto$2.days=days,proto$2.weeks=weeks,proto$2.months=months,proto$2.years=years,proto$2.humanize=humanize,proto$2.toISOString=toISOString$1,proto$2.toString=toISOString$1,proto$2.toJSON=toISOString$1,proto$2.locale=locale,proto$2.localeData=localeData,proto$2.toIsoString=deprecate("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",toISOString$1),proto$2.lang=lang,addFormatToken("X",0,0,"unix"),addFormatToken("x",0,0,"valueOf"),addRegexToken("x",matchSigned),addRegexToken("X",matchTimestamp),addParseToken("X",function(input2,array2,config2){config2._d=new Date(parseFloat(input2)*1e3)}),addParseToken("x",function(input2,array2,config2){config2._d=new Date(toInt(input2))});return hooks.version="2.30.1",setHookCallback(createLocal),hooks.fn=proto,hooks.min=min,hooks.max=max,hooks.now=now,hooks.utc=createUTC,hooks.unix=createUnix,hooks.months=listMonths,hooks.isDate=isDate,hooks.locale=getSetGlobalLocale,hooks.invalid=createInvalid,hooks.duration=createDuration,hooks.isMoment=isMoment,hooks.weekdays=listWeekdays,hooks.parseZone=createInZone,hooks.localeData=getLocale,hooks.isDuration=isDuration,hooks.monthsShort=listMonthsShort,hooks.weekdaysMin=listWeekdaysMin,hooks.defineLocale=defineLocale,hooks.updateLocale=updateLocale,hooks.locales=listLocales,hooks.weekdaysShort=listWeekdaysShort,hooks.normalizeUnits=normalizeUnits,hooks.relativeTimeRounding=getSetRelativeTimeRounding,hooks.relativeTimeThreshold=getSetRelativeTimeThreshold,hooks.calendarFormat=getCalendarFormat,hooks.prototype=proto,hooks.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},hooks}))}});var require_date=__commonJS({"../../node_modules/.pnpm/@darabonba+typescript@1.0.5/node_modules/@darabonba/typescript/dist/date.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});var moment_1=__importDefault(require_moment()),TeaDate=(function(){function TeaDate2(date5){this.date=(0,moment_1.default)(date5)}return TeaDate2.prototype.format=function(layout){return layout=layout.replace(/y/g,"Y").replace(/d/g,"D").replace(/h/g,"H").replace(/a/g,"A").replace(/E/g,"d"),this.date.format(layout)},TeaDate2.prototype.unix=function(){return this.date.unix()},TeaDate2.prototype.sub=function(amount,unit){var date5=(0,moment_1.default)(this.date).subtract(unit,amount);return new TeaDate2(date5)},TeaDate2.prototype.add=function(amount,unit){var date5=(0,moment_1.default)(this.date).add(unit,amount);return new TeaDate2(date5)},TeaDate2.prototype.diff=function(amount,diffDate){return this.date.diff(diffDate.date,amount)},TeaDate2.prototype.hour=function(){return this.date.hour()},TeaDate2.prototype.minute=function(){return this.date.minute()},TeaDate2.prototype.second=function(){return this.date.second()},TeaDate2.prototype.month=function(){return this.date.month()+1},TeaDate2.prototype.year=function(){return this.date.year()},TeaDate2.prototype.dayOfMonth=function(){return this.date.date()},TeaDate2.prototype.dayOfWeek=function(){var weekday=this.date.weekday();return weekday===0?7:weekday+1},TeaDate2.prototype.weekOfMonth=function(){var startWeek=(0,moment_1.default)(this.date).startOf("month").week(),dateWeek=this.date.week();if(this.date.weekday()===0&&(dateWeek=dateWeek-1),dateWeek===0&&this.date.date()>1)return this.sub("day",1).weekOfMonth();var monthWeek=dateWeek-startWeek;return monthWeek<0?1:monthWeek+1},TeaDate2.prototype.weekOfYear=function(){var weekday=this.date.weekday(),week=this.date.week();return weekday===0&&week===1&&this.date.date()>1?this.sub("day",1).weekOfYear():this.date.week()},TeaDate2})();exports.default=TeaDate}});var require_file=__commonJS({"../../node_modules/.pnpm/@darabonba+typescript@1.0.5/node_modules/@darabonba/typescript/dist/file.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports&&exports.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports&&exports.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=exports&&exports.__awaiter||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve5){resolve5(value)})}return new(P||(P=Promise))(function(resolve5,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){result.done?resolve5(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__generator=exports&&exports.__generator||function(thisArg,body){var _={label:0,sent:function(){if(t[0]&1)throw t[1];return t[1]},trys:[],ops:[]},f,y,t,g;return g={next:verb(0),throw:verb(1),return:verb(2)},typeof Symbol=="function"&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return step([n,v])}}function step(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=op[0]&2?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[op[0]&2,t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(t=_.trys,!(t=t.length>0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(op[0]===6&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(op[0]&5)throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}},__importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});var fs24=__importStar(__require("fs")),util2=__importStar(__require("util")),date_1=__importDefault(require_date()),exists=util2.promisify(fs24.exists),stat2=util2.promisify(fs24.stat),read=util2.promisify(fs24.read),write=util2.promisify(fs24.write),open2=util2.promisify(fs24.open),close=util2.promisify(fs24.close),TeaFile=(function(){function TeaFile2(path25){this._path=path25,this._position=0}return TeaFile2.prototype.path=function(){return this._path},TeaFile2.prototype.createTime=function(){return __awaiter(this,void 0,void 0,function(){var _a2;return __generator(this,function(_b){switch(_b.label){case 0:return this._stat?[3,2]:(_a2=this,[4,stat2(this._path)]);case 1:_a2._stat=_b.sent(),_b.label=2;case 2:return[2,new date_1.default(this._stat.birthtime)]}})})},TeaFile2.prototype.modifyTime=function(){return __awaiter(this,void 0,void 0,function(){var _a2;return __generator(this,function(_b){switch(_b.label){case 0:return this._stat?[3,2]:(_a2=this,[4,stat2(this._path)]);case 1:_a2._stat=_b.sent(),_b.label=2;case 2:return[2,new date_1.default(this._stat.mtime)]}})})},TeaFile2.prototype.length=function(){return __awaiter(this,void 0,void 0,function(){var _a2;return __generator(this,function(_b){switch(_b.label){case 0:return this._stat?[3,2]:(_a2=this,[4,stat2(this._path)]);case 1:_a2._stat=_b.sent(),_b.label=2;case 2:return[2,this._stat.size]}})})},TeaFile2.prototype.read=function(size){return __awaiter(this,void 0,void 0,function(){var _a2,buf,_b,bytesRead,buffer;return __generator(this,function(_c){switch(_c.label){case 0:return this._fd?[3,2]:(_a2=this,[4,open2(this._path,"a+")]);case 1:_a2._fd=_c.sent(),_c.label=2;case 2:return buf=Buffer.alloc(size),[4,read(this._fd,buf,0,size,this._position)];case 3:return _b=_c.sent(),bytesRead=_b.bytesRead,buffer=_b.buffer,bytesRead?(this._position+=bytesRead,[2,buffer]):[2,null]}})})},TeaFile2.prototype.write=function(data){return __awaiter(this,void 0,void 0,function(){var _a2,_b;return __generator(this,function(_c){switch(_c.label){case 0:return this._fd?[3,2]:(_a2=this,[4,open2(this._path,"a+")]);case 1:_a2._fd=_c.sent(),_c.label=2;case 2:return[4,write(this._fd,data)];case 3:return _c.sent(),_b=this,[4,stat2(this._path)];case 4:return _b._stat=_c.sent(),[2]}})})},TeaFile2.prototype.close=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a2){switch(_a2.label){case 0:return this._fd?[4,close(this._fd)]:[2];case 1:return _a2.sent(),[2]}})})},TeaFile2.exists=function(path25){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a2){switch(_a2.label){case 0:return[4,exists(path25)];case 1:return[2,_a2.sent()]}})})},TeaFile2.createReadStream=function(path25){return fs24.createReadStream(path25)},TeaFile2.createWriteStream=function(path25){return fs24.createWriteStream(path25)},TeaFile2})();exports.default=TeaFile}});var require_form=__commonJS({"../../node_modules/.pnpm/@darabonba+typescript@1.0.5/node_modules/@darabonba/typescript/dist/form.js"(exports){"use strict";var __extends=exports&&exports.__extends||(function(){var extendStatics=function(d,b){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d2,b2){d2.__proto__=b2}||function(d2,b2){for(var p in b2)Object.prototype.hasOwnProperty.call(b2,p)&&(d2[p]=b2[p])},extendStatics(d,b)};return function(d,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}})();Object.defineProperty(exports,"__esModule",{value:!0});exports.FileFormStream=void 0;var stream_1=__require("stream"),querystring_1=__require("querystring"),FileFormStream=(function(_super){__extends(FileFormStream2,_super);function FileFormStream2(form,boundary){var _this=_super.call(this)||this;return _this.form=form,_this.keys=Object.keys(form),_this.index=0,_this.boundary=boundary,_this.streaming=!1,_this}return FileFormStream2.prototype._read=function(){var _this=this;if(!this.streaming){var separator=this.boundary;if(this.index<this.keys.length){var name_1=this.keys[this.index],fieldValue=this.form[name_1];if(typeof fieldValue.filename=="string"&&typeof fieldValue.contentType=="string"&&fieldValue.content instanceof stream_1.Readable){var body="--".concat(separator,`\r
|
|
@@ -457,9 +457,9 @@ Next steps:
|
|
|
457
457
|
|
|
458
458
|
Verify:
|
|
459
459
|
mearl get_requests --payload '{"count":1}'
|
|
460
|
-
`),success2?0:1}var DEFAULT_EXTENSION_ID,__filename,__dirname2,ALL_MODES,init_install=__esm({"src/install.ts"(){"use strict";init_nativeHost();DEFAULT_EXTENSION_ID="aoehhjnofngknnjefamjbplchbolghkm",__filename=fileURLToPath4(import.meta.url),__dirname2=path23.dirname(__filename),ALL_MODES=["skills","mcp"]}});import net3 from"node:net";import fs23 from"node:fs";import http4 from"node:http";import os11 from"node:os";import path24 from"node:path";import{fileURLToPath as fileURLToPath5}from"node:url";import{spawn as spawn2}from"node:child_process";import{randomUUID as randomUUID2}from"node:crypto";import{closeSync as closeSync3,existsSync as existsSync4,mkdirSync as mkdirSync2,openSync as openSync3}from"node:fs";import{join as join4}from"node:path";function isAlive(pid){if(!pid||pid<=0)return!1;try{return process.kill(pid,0),!0}catch(error48){return error48.code==="EPERM"}}import{join}from"node:path";import{homedir}from"node:os";import{createHash}from"node:crypto";var DAEMON_HOME=join(homedir(),".mearl");function hashKey(key){return createHash("sha256").update(key).digest("hex").slice(0,16)}function keyedDir(subdir){return join(DAEMON_HOME,subdir)}function keyedConfigFile(subdir,key){return join(keyedDir(subdir),`${hashKey(key)}.json`)}import{closeSync,existsSync,linkSync,openSync,statSync,mkdirSync,readFileSync,writeFileSync,renameSync,rmSync,readdirSync}from"node:fs";import{dirname,join as join2}from"node:path";import{randomUUID}from"node:crypto";var LOCK_WAIT_MS=10,LOCK_TIMEOUT_MS=5e3,OWNER_WRITE_GRACE_MS=1e3,lockWaitBuffer=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));function ensureDir(dir){existsSync(dir)||mkdirSync(dir,{recursive:!0,mode:448})}function pauseForLock(){Atomics.wait(lockWaitBuffer,0,0,LOCK_WAIT_MS)}function readRecordUnlocked(file2){try{if(!existsSync(file2))return null;let parsed=JSON.parse(readFileSync(file2,"utf-8"));return parsed&&typeof parsed.pid=="number"?parsed:null}catch{return null}}function removeRecordUnlocked(file2){rmSync(file2,{force:!0})}function writeRecordUnlocked(file2,record2){let tmp=`${file2}.${process.pid}.${randomUUID()}.tmp`;try{writeFileSync(tmp,JSON.stringify(record2),{mode:384}),renameSync(tmp,file2)}catch(error48){try{rmSync(tmp,{force:!0})}catch{}throw error48}}function removeStaleLock(lockDir){let ownerFile=join2(lockDir,"owner.json"),owner=readRecordUnlocked(ownerFile);if(owner){if(isAlive(owner.pid))return!1}else try{if(Date.now()-statSync(lockDir).mtimeMs<OWNER_WRITE_GRACE_MS)return!1}catch{return!0}try{return rmSync(lockDir,{recursive:!0,force:!0}),!0}catch{return!1}}function withRecordLock(file2,operation){ensureDir(dirname(file2));let lockDir=`${file2}.registry.lock`,ownerFile=join2(lockDir,"owner.json"),token=randomUUID(),deadline=Date.now()+LOCK_TIMEOUT_MS;for(;;){try{mkdirSync(lockDir,{mode:448})}catch(error48){if(error48.code!=="EEXIST")throw error48;if(!removeStaleLock(lockDir)){if(Date.now()>=deadline)throw new Error(`Timed out waiting for registry lock: ${file2}`,{cause:error48});pauseForLock()}continue}let ownerFd=null;try{ownerFd=openSync(ownerFile,"wx",384),writeFileSync(ownerFd,JSON.stringify({pid:process.pid,token}))}catch(error48){if(ownerFd!==null&&closeSync(ownerFd),ownerFd=null,error48.code==="EEXIST"){if(Date.now()>=deadline)throw new Error(`Timed out acquiring registry lock: ${file2}`,{cause:error48});pauseForLock();continue}throw error48}finally{ownerFd!==null&&closeSync(ownerFd)}try{return operation()}finally{readRecordUnlocked(ownerFile)?.token===token&&rmSync(lockDir,{recursive:!0,force:!0})}}}function writeRecord(file2,record2){withRecordLock(file2,()=>writeRecordUnlocked(file2,record2))}function claimRecord(file2,record2){return withRecordLock(file2,()=>{let candidate=`${file2}.${process.pid}.${randomUUID()}.claim`;try{return writeFileSync(candidate,JSON.stringify(record2),{mode:384}),linkSync(candidate,file2),!0}catch(error48){if(error48.code==="EEXIST")return!1;throw error48}finally{rmSync(candidate,{force:!0})}})}function readRecord(file2){return readRecordUnlocked(file2)}function removeRecord(file2){try{withRecordLock(file2,()=>removeRecordUnlocked(file2))}catch{}}function removeRecordIfPid(file2,pid){try{return withRecordLock(file2,()=>readRecordUnlocked(file2)?.pid!==pid?!1:(removeRecordUnlocked(file2),!0))}catch{return!1}}function writeRecordIfPid(file2,pid,record2){return withRecordLock(file2,()=>readRecordUnlocked(file2)?.pid!==pid?!1:(writeRecordUnlocked(file2,record2),!0))}function removeInvalidRecord(file2){try{return withRecordLock(file2,()=>!existsSync(file2)||readRecordUnlocked(file2)?!1:(removeRecordUnlocked(file2),!0))}catch{return!1}}function listRecordFiles(dir){try{return readdirSync(dir).filter(name=>name.endsWith(".json")).map(name=>join2(dir,name))}catch{return[]}}function readLiveRecords(dir){let out=[];for(let file2 of listRecordFiles(dir)){let rec=readRecord(file2);rec&&isAlive(rec.pid)?out.push(rec):rec?removeRecordIfPid(file2,rec.pid):removeInvalidRecord(file2)}return out}import{existsSync as existsSync2,statSync as statSync2,renameSync as renameSync2,readFileSync as readFileSync2}from"node:fs";var DEFAULT_MAX_LOG_BYTES=5*1024*1024;function rotateLogIfNeeded(logFile,maxBytes=DEFAULT_MAX_LOG_BYTES){try{if(!existsSync2(logFile)||statSync2(logFile).size<maxBytes)return;renameSync2(logFile,`${logFile}.1`)}catch{}}import{spawn}from"node:child_process";import{closeSync as closeSync2,openSync as openSync2}from"node:fs";import{dirname as dirname2}from"node:path";import{existsSync as existsSync3,readFileSync as readFileSync3,renameSync as renameSync3,rmSync as rmSync2,statSync as statSync3,writeFileSync as writeFileSync2}from"node:fs";import{isAbsolute,join as join3,relative,resolve,sep}from"node:path";var INSTALLED_PROVIDERS_SUBDIR="providers/installed",LIVE_PROVIDERS_SUBDIR="providers/live",STARTING_PROVIDERS_SUBDIR="providers/starting";var PROVIDER_START_TOKEN_ENV="MEARL_PROVIDER_START_TOKEN";function providerBrowserKey(providerId,browserId){return`provider:${encodeURIComponent(providerId)}:${encodeURIComponent(browserId)}`}function liveProviderFile(providerId){return keyedConfigFile(LIVE_PROVIDERS_SUBDIR,providerId)}function startingProviderFile(providerId){return keyedConfigFile(STARTING_PROVIDERS_SUBDIR,providerId)}function claimProviderStart(providerId,token,pid=process.pid){let file2=startingProviderFile(providerId),existing=readRecord(file2);return existing&&isAlive(existing.pid)?existing.token===token:(existing?removeRecordIfPid(file2,existing.pid):removeInvalidRecord(file2),claimRecord(file2,{pid,providerId,token,startedAt:new Date().toISOString()}))}function readProviderStart(providerId){let record2=readRecord(startingProviderFile(providerId));return record2&&isAlive(record2.pid)?record2:null}function transferProviderStart(providerId,token,pid){let file2=startingProviderFile(providerId),record2=readRecord(file2);return!record2||record2.token!==token?!1:writeRecordIfPid(file2,record2.pid,{...record2,pid})}function releaseProviderStart(providerId,token){let file2=startingProviderFile(providerId),record2=readRecord(file2);return record2?.token===token?removeRecordIfPid(file2,record2.pid):!1}function validateInstalledProviderManifest(manifest){if(!manifest||typeof manifest.providerId!="string"||!manifest.providerId.trim()||typeof manifest.name!="string"||!manifest.name.trim()||typeof manifest.version!="string"||!manifest.version.trim())return"manifest is incomplete";if(manifest.protocolVersion!==1)return`protocol ${manifest.protocolVersion} is unsupported`;if(!isProviderBrowserType(manifest.browserType))return"browserType is invalid";if(typeof manifest.packageName!="string"||!manifest.packageName.trim())return"packageName is required";if(typeof manifest.packageRoot!="string"||!isAbsolute(manifest.packageRoot))return"packageRoot must be an absolute path";if(typeof manifest.entryPath!="string"||!isAbsolute(manifest.entryPath))return"entryPath must be an absolute path";let entryRelative=relative(manifest.packageRoot,manifest.entryPath);return entryRelative===""||isAbsolute(entryRelative)||entryRelative===".."||entryRelative.startsWith(`..${sep}`)?"entryPath must be a file inside packageRoot":isFile(manifest.entryPath)?null:"entryPath does not exist or is not a file"}function isFile(filePath){try{return statSync3(filePath).isFile()}catch{return!1}}function isProviderBrowserType(value){if(!value||typeof value!="object")return!1;let browserType=value;if(typeof browserType.name!="string"||!browserType.name.trim()||!Array.isArray(browserType.parameters))return!1;let keys=new Set;for(let parameter of browserType.parameters){if(!parameter||typeof parameter!="object"||typeof parameter.key!="string"||!/^[A-Za-z][A-Za-z0-9_]*$/.test(parameter.key)||typeof parameter.label!="string"||!parameter.label.trim()||parameter.required!==void 0&&typeof parameter.required!="boolean"||parameter.placeholder!==void 0&&typeof parameter.placeholder!="string"||parameter.description!==void 0&&typeof parameter.description!="string"||keys.has(parameter.key))return!1;keys.add(parameter.key)}return!0}function listInstalledProviders(){let manifests=[];for(let file2 of listRecordFiles(keyedDir(INSTALLED_PROVIDERS_SUBDIR)))try{let parsed=JSON.parse(readFileSync3(file2,"utf8"));parsed&&typeof parsed.providerId=="string"&&typeof parsed.packageName=="string"&&manifests.push(parsed)}catch{}return manifests.sort((a,b)=>a.providerId.localeCompare(b.providerId))}function readLiveProvider(providerId){let record2=readRecord(liveProviderFile(providerId));return record2&&isAlive(record2.pid)?record2:null}function listLiveProviders(){return readLiveRecords(keyedDir(LIVE_PROVIDERS_SUBDIR))}var PROVIDER_LOGS_SUBDIR="providers/logs";function providerLogFile(providerId){let hash2=hashKey(providerId);return join4(keyedDir(PROVIDER_LOGS_SUBDIR),`${hash2}.log`)}function liveProviderIds(){return new Set(listLiveProviders().map(record2=>record2.providerId))}function delay(ms){return new Promise(resolve5=>setTimeout(resolve5,ms))}async function spawnProvider(manifest,logFile,startToken){mkdirSync2(keyedDir(PROVIDER_LOGS_SUBDIR),{recursive:!0,mode:448}),rotateLogIfNeeded(logFile);let output2=openSync3(logFile,"a");try{return await new Promise((resolve5,reject)=>{let child=spawn2(process.execPath,[manifest.entryPath],{cwd:manifest.packageRoot,env:{...process.env,[PROVIDER_START_TOKEN_ENV]:startToken},detached:!0,stdio:["ignore",output2,output2],windowsHide:!0});child.once("error",reject),child.once("spawn",()=>{child.removeAllListeners("error"),child.on("error",()=>{}),child.unref(),child.pid?resolve5(child.pid):reject(new Error("spawned process has no pid"))})})}finally{closeSync3(output2)}}async function ensureInstalledProvidersRunning(){let warnings=[],installed=listInstalledProviders(),live=liveProviderIds(),starting=new Map;for(let manifest of installed){if(live.has(manifest.providerId))continue;let invalid=validateInstalledProviderManifest(manifest);if(invalid){warnings.push(`provider ${manifest.providerId||"(unknown)"}: ${invalid}`);continue}let startToken=randomUUID2();if(!claimProviderStart(manifest.providerId,startToken)){if(readLiveProvider(manifest.providerId))continue;readProviderStart(manifest.providerId)?starting.set(manifest.providerId,null):warnings.push(`provider ${manifest.providerId}: failed to acquire startup ownership`);continue}if(readLiveProvider(manifest.providerId)){releaseProviderStart(manifest.providerId,startToken);continue}let logFile=providerLogFile(manifest.providerId);try{let childPid=await spawnProvider(manifest,logFile,startToken);transferProviderStart(manifest.providerId,startToken,childPid),starting.set(manifest.providerId,startToken)}catch(error48){releaseProviderStart(manifest.providerId,startToken),warnings.push(`provider ${manifest.providerId}: ${error48 instanceof Error?error48.message:String(error48)}`)}}if(starting.size===0)return warnings;let deadline=Date.now()+2e3,remaining=[...starting.keys()];for(;remaining.length>0&&Date.now()<deadline;){await delay(100);let current=liveProviderIds();remaining=remaining.filter(providerId=>!current.has(providerId))}for(let[providerId,token]of starting)!remaining.includes(providerId)&&token&&releaseProviderStart(providerId,token);for(let providerId of remaining){let logFile=providerLogFile(providerId);warnings.push(`provider ${providerId}: did not become ready within 2s${existsSync4(logFile)?`; see ${logFile}`:""}`)}return await delay(100),warnings}import{StringDecoder}from"node:string_decoder";var Utf8LineBuffer=class{constructor(maxBufferBytes){this.maxBufferBytes=maxBufferBytes}buffer="";decoder=new StringDecoder("utf8");push(chunk){if(this.buffer+=this.decoder.write(chunk),Buffer.byteLength(this.buffer,"utf8")>this.maxBufferBytes)return this.buffer="",{lines:[],overflow:!0};let lines=[],newlineIndex;for(;(newlineIndex=this.buffer.indexOf(`
|
|
460
|
+
`),success2?0:1}var DEFAULT_EXTENSION_ID,__filename,__dirname2,ALL_MODES,init_install=__esm({"src/install.ts"(){"use strict";init_nativeHost();DEFAULT_EXTENSION_ID="aoehhjnofngknnjefamjbplchbolghkm",__filename=fileURLToPath4(import.meta.url),__dirname2=path23.dirname(__filename),ALL_MODES=["skills","mcp"]}});import net4 from"node:net";import fs23 from"node:fs";import http4 from"node:http";import os11 from"node:os";import path24 from"node:path";import{fileURLToPath as fileURLToPath5}from"node:url";import{spawn as spawn2}from"node:child_process";import{randomUUID as randomUUID2}from"node:crypto";import{closeSync as closeSync3,existsSync as existsSync4,mkdirSync as mkdirSync2,openSync as openSync3}from"node:fs";import{join as join4}from"node:path";function isAlive(pid){if(!pid||pid<=0)return!1;try{return process.kill(pid,0),!0}catch(error48){return error48.code==="EPERM"}}import{join}from"node:path";import{homedir}from"node:os";import{createHash}from"node:crypto";var DAEMON_HOME=join(homedir(),".mearl");function hashKey(key){return createHash("sha256").update(key).digest("hex").slice(0,16)}function keyedDir(subdir){return join(DAEMON_HOME,subdir)}function keyedConfigFile(subdir,key){return join(keyedDir(subdir),`${hashKey(key)}.json`)}import{closeSync,existsSync,linkSync,openSync,statSync,mkdirSync,readFileSync,writeFileSync,renameSync,rmSync,readdirSync}from"node:fs";import{dirname,join as join2}from"node:path";import{randomUUID}from"node:crypto";var LOCK_WAIT_MS=10,LOCK_TIMEOUT_MS=5e3,OWNER_WRITE_GRACE_MS=1e3,lockWaitBuffer=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));function ensureDir(dir){existsSync(dir)||mkdirSync(dir,{recursive:!0,mode:448})}function pauseForLock(){Atomics.wait(lockWaitBuffer,0,0,LOCK_WAIT_MS)}function readRecordUnlocked(file2){try{if(!existsSync(file2))return null;let parsed=JSON.parse(readFileSync(file2,"utf-8"));return parsed&&typeof parsed.pid=="number"?parsed:null}catch{return null}}function removeRecordUnlocked(file2){rmSync(file2,{force:!0})}function writeRecordUnlocked(file2,record2){let tmp=`${file2}.${process.pid}.${randomUUID()}.tmp`;try{writeFileSync(tmp,JSON.stringify(record2),{mode:384}),renameSync(tmp,file2)}catch(error48){try{rmSync(tmp,{force:!0})}catch{}throw error48}}function removeStaleLock(lockDir){let ownerFile=join2(lockDir,"owner.json"),owner=readRecordUnlocked(ownerFile);if(owner){if(isAlive(owner.pid))return!1}else try{if(Date.now()-statSync(lockDir).mtimeMs<OWNER_WRITE_GRACE_MS)return!1}catch{return!0}try{return rmSync(lockDir,{recursive:!0,force:!0}),!0}catch{return!1}}function withRecordLock(file2,operation){ensureDir(dirname(file2));let lockDir=`${file2}.registry.lock`,ownerFile=join2(lockDir,"owner.json"),token=randomUUID(),deadline=Date.now()+LOCK_TIMEOUT_MS;for(;;){try{mkdirSync(lockDir,{mode:448})}catch(error48){if(error48.code!=="EEXIST")throw error48;if(!removeStaleLock(lockDir)){if(Date.now()>=deadline)throw new Error(`Timed out waiting for registry lock: ${file2}`,{cause:error48});pauseForLock()}continue}let ownerFd=null;try{ownerFd=openSync(ownerFile,"wx",384),writeFileSync(ownerFd,JSON.stringify({pid:process.pid,token}))}catch(error48){if(ownerFd!==null&&closeSync(ownerFd),ownerFd=null,error48.code==="EEXIST"){if(Date.now()>=deadline)throw new Error(`Timed out acquiring registry lock: ${file2}`,{cause:error48});pauseForLock();continue}throw error48}finally{ownerFd!==null&&closeSync(ownerFd)}try{return operation()}finally{readRecordUnlocked(ownerFile)?.token===token&&rmSync(lockDir,{recursive:!0,force:!0})}}}function writeRecord(file2,record2){withRecordLock(file2,()=>writeRecordUnlocked(file2,record2))}function claimRecord(file2,record2){return withRecordLock(file2,()=>{let candidate=`${file2}.${process.pid}.${randomUUID()}.claim`;try{return writeFileSync(candidate,JSON.stringify(record2),{mode:384}),linkSync(candidate,file2),!0}catch(error48){if(error48.code==="EEXIST")return!1;throw error48}finally{rmSync(candidate,{force:!0})}})}function readRecord(file2){return readRecordUnlocked(file2)}function removeRecord(file2){try{withRecordLock(file2,()=>removeRecordUnlocked(file2))}catch{}}function removeRecordIfPid(file2,pid){try{return withRecordLock(file2,()=>readRecordUnlocked(file2)?.pid!==pid?!1:(removeRecordUnlocked(file2),!0))}catch{return!1}}function writeRecordIfPid(file2,pid,record2){return withRecordLock(file2,()=>readRecordUnlocked(file2)?.pid!==pid?!1:(writeRecordUnlocked(file2,record2),!0))}function removeInvalidRecord(file2){try{return withRecordLock(file2,()=>!existsSync(file2)||readRecordUnlocked(file2)?!1:(removeRecordUnlocked(file2),!0))}catch{return!1}}function listRecordFiles(dir){try{return readdirSync(dir).filter(name=>name.endsWith(".json")).map(name=>join2(dir,name))}catch{return[]}}function readLiveRecords(dir){let out=[];for(let file2 of listRecordFiles(dir)){let rec=readRecord(file2);rec&&isAlive(rec.pid)?out.push(rec):rec?removeRecordIfPid(file2,rec.pid):removeInvalidRecord(file2)}return out}import{existsSync as existsSync2,statSync as statSync2,renameSync as renameSync2,readFileSync as readFileSync2}from"node:fs";var DEFAULT_MAX_LOG_BYTES=5*1024*1024;function rotateLogIfNeeded(logFile,maxBytes=DEFAULT_MAX_LOG_BYTES){try{if(!existsSync2(logFile)||statSync2(logFile).size<maxBytes)return;renameSync2(logFile,`${logFile}.1`)}catch{}}import{spawn}from"node:child_process";import{closeSync as closeSync2,openSync as openSync2}from"node:fs";import{dirname as dirname2}from"node:path";import{existsSync as existsSync3,readFileSync as readFileSync3,renameSync as renameSync3,rmSync as rmSync2,statSync as statSync3,writeFileSync as writeFileSync2}from"node:fs";import{isAbsolute,join as join3,relative,resolve,sep}from"node:path";var PROVIDER_ACTIONS=["tab_checkpoint","capture_checkpoint","get_requests","get_logs","get_events","get_api_schema","set_mock","get_mocks","set_rule","get_rules","send_request","send_mtop_request","tdbank_account","browser_release","page_screenshot","page_selected_element","tab_open","tab_close","tab_list","page_click","page_drag","page_type","page_scroll","page_hover","page_eval","page_snapshot","page_press","page_wait","page_navigate","page_upload","page_frames","set_device_emulation","set_app_profile","set_timezone","get_cookie","set_cookie","record_start","record_stop","request_domain_permission","get_user_info","run_actions"],providerActionSet=new Set(PROVIDER_ACTIONS);function isProviderAction(value){return typeof value=="string"&&providerActionSet.has(value)}var LIFECYCLE_OPERATIONS=new Set(["start","close","detach","deleteData","access","syncCookies"]);function isJsonValue(value,depth=0){return depth>32?!1:value===null||["string","boolean"].includes(typeof value)?!0:typeof value=="number"?Number.isFinite(value):Array.isArray(value)?value.every(item=>isJsonValue(item,depth+1)):typeof value=="object"&&Object.values(value).every(item=>isJsonValue(item,depth+1))}function isOptionalString(value){return value===void 0||typeof value=="string"}function isOptionalFiniteNumber(value){return value===void 0||typeof value=="number"&&Number.isFinite(value)}function isOptionalCount(value){return value===void 0||Number.isInteger(value)&&Number(value)>=0}function isProviderInputSchema(value,depth=0){if(!value||typeof value!="object"||Array.isArray(value)||depth>32)return!1;let schema=value;if(!isOptionalString(schema.title)||!isOptionalString(schema.description)||schema.default!==void 0&&!isJsonValue(schema.default))return!1;if(schema.type==="string"){let validPattern=!0;if(schema.pattern!==void 0)try{new RegExp(String(schema.pattern))}catch{validPattern=!1}if(!((schema.enum===void 0||Array.isArray(schema.enum)&&schema.enum.every(item=>typeof item=="string"))&&(schema.secret===void 0||typeof schema.secret=="boolean")&&isOptionalCount(schema.minLength)&&isOptionalCount(schema.maxLength)&&(schema.minLength===void 0||schema.maxLength===void 0||Number(schema.minLength)<=Number(schema.maxLength))&&isOptionalString(schema.pattern)&&validPattern&&isOptionalString(schema.placeholder)))return!1}else if(schema.type==="number"){if(!((schema.integer===void 0||typeof schema.integer=="boolean")&&isOptionalFiniteNumber(schema.minimum)&&isOptionalFiniteNumber(schema.maximum)&&(schema.minimum===void 0||schema.maximum===void 0||Number(schema.minimum)<=Number(schema.maximum))))return!1}else if(schema.type!=="boolean")if(schema.type==="array"){if(!isProviderInputSchema(schema.items,depth+1)||!isOptionalCount(schema.minItems)||!isOptionalCount(schema.maxItems)||schema.minItems!==void 0&&schema.maxItems!==void 0&&Number(schema.minItems)>Number(schema.maxItems))return!1}else{if(schema.type!=="object"||!schema.properties||typeof schema.properties!="object"||Array.isArray(schema.properties)||schema.additionalProperties!==void 0&&typeof schema.additionalProperties!="boolean")return!1;let properties=schema.properties;if(!Object.values(properties).every(item=>isProviderInputSchema(item,depth+1))||schema.not!==void 0&&(!isProviderInputSchema(schema.not,depth+1)||schema.not.type!=="object")||schema.oneOf!==void 0&&(!Array.isArray(schema.oneOf)||schema.oneOf.length===0||schema.oneOf.some(branch=>!isProviderInputSchema(branch,depth+1)||branch.type!=="object"))||schema.required!==void 0&&(!Array.isArray(schema.required)||schema.required.some(item=>typeof item!="string"||!(item in properties))||new Set(schema.required).size!==schema.required.length))return!1}if(schema.default!==void 0)try{validateSchemaValue(value,schema.default,"default")}catch{return!1}return!0}function fail(path25,message){throw new Error(`${path25} ${message}`)}function validateSchemaValue(schema,value,path25){if(schema.type==="string"){typeof value!="string"&&fail(path25,"must be a string"),schema.enum&&!schema.enum.includes(value)&&fail(path25,"has an unsupported value"),schema.minLength!==void 0&&value.length<schema.minLength&&fail(path25,`must contain at least ${schema.minLength} characters`),schema.maxLength!==void 0&&value.length>schema.maxLength&&fail(path25,`must contain at most ${schema.maxLength} characters`),schema.pattern!==void 0&&!new RegExp(schema.pattern).test(value)&&fail(path25,"has an invalid format");return}if(schema.type==="number"){(typeof value!="number"||!Number.isFinite(value))&&fail(path25,"must be a number"),schema.integer&&!Number.isInteger(value)&&fail(path25,"must be an integer"),schema.minimum!==void 0&&value<schema.minimum&&fail(path25,`must be at least ${schema.minimum}`),schema.maximum!==void 0&&value>schema.maximum&&fail(path25,`must be at most ${schema.maximum}`);return}if(schema.type==="boolean"){typeof value!="boolean"&&fail(path25,"must be a boolean");return}if(schema.type==="array"){Array.isArray(value)||fail(path25,"must be an array"),schema.minItems!==void 0&&value.length<schema.minItems&&fail(path25,`must contain at least ${schema.minItems} items`),schema.maxItems!==void 0&&value.length>schema.maxItems&&fail(path25,`must contain at most ${schema.maxItems} items`),value.forEach((item,index)=>validateSchemaValue(schema.items,item,`${path25}[${index}]`));return}validateObject(schema,value,path25)}function validateObject(schema,value,path25){(!value||typeof value!="object"||Array.isArray(value))&&fail(path25,"must be an object");let input2=value;for(let key of schema.required??[])input2[key]===void 0&&fail(`${path25}.${key}`,"is required");if(schema.not){let matches=!1;try{validateObject(schema.not,input2,path25),matches=!0}catch{}matches&&fail(path25,"matches a forbidden field combination")}if(schema.oneOf&&schema.oneOf.filter(branch=>{try{return validateObject(branch,input2,path25),!0}catch{return!1}}).length!==1&&fail(path25,"must match exactly one launch form"),schema.additionalProperties!==!0)for(let key of Object.keys(input2))schema.properties[key]||fail(`${path25}.${key}`,"is not supported");for(let[key,item]of Object.entries(input2)){let property=schema.properties[key];property&&validateSchemaValue(property,item,`${path25}.${key}`)}}function validateProviderInput(schema,value){validateObject(schema,value,"options")}function validateProviderBrowser(browser){if(!browser||typeof browser!="object")throw new Error("Provider returned no browser");if(typeof browser.browserId!="string"||!browser.browserId.trim())throw new Error("Provider browserId is required");if(typeof browser.name!="string"||!browser.name.trim())throw new Error(`Provider browser ${browser.browserId} needs a name`);if(!["connected","pairing","running_disconnected","stopped"].includes(browser.status))throw new Error(`Provider browser ${browser.browserId} has an invalid status`);if(!["ephemeral","persistent"].includes(browser.persistence))throw new Error(`Provider browser ${browser.browserId} has invalid persistence`);if(browser.ownership!==void 0&&!["owned","attached"].includes(browser.ownership))throw new Error(`Provider browser ${browser.browserId} has invalid ownership`);if(!browser.control||!["provider","host","none"].includes(browser.control.kind))throw new Error(`Provider browser ${browser.browserId} has invalid control`);if(!Array.isArray(browser.operations)||new Set(browser.operations).size!==browser.operations.length||browser.operations.some(operation=>!LIFECYCLE_OPERATIONS.has(operation)))throw new Error(`Provider browser ${browser.browserId} has invalid lifecycle operations`);if(browser.status==="pairing"){if(browser.pairing?.kind!=="qr"||typeof browser.pairing.url!="string"||!browser.pairing.url.trim())throw new Error(`Pairing browser ${browser.browserId} needs a pairing URL`)}else if(browser.pairing)throw new Error(`Pairing metadata requires a pairing state: ${browser.browserId}`);if(browser.pairing&&(!isOptionalString(browser.pairing.code)||!isOptionalString(browser.pairing.label)))throw new Error(`Provider browser ${browser.browserId} has invalid pairing metadata`);if(browser.lastFocusedAt!==void 0&&(!Number.isFinite(browser.lastFocusedAt)||browser.lastFocusedAt<0))throw new Error(`Provider browser ${browser.browserId} has an invalid lastFocusedAt`);if(browser.status==="stopped"&&browser.control.kind!=="none")throw new Error(`Stopped Provider browser ${browser.browserId} cannot expose live control`);if(browser.status==="connected"&&browser.control.kind==="none")throw new Error(`Connected Provider browser ${browser.browserId} must expose control`);let capabilities=browser.control.kind==="provider"||browser.control.kind==="host"?browser.control.capabilities:void 0;if(browser.control.kind==="provider"||capabilities){if(!Array.isArray(capabilities?.actions))throw new Error(`Provider browser ${browser.browserId} needs action capabilities`);if(capabilities.actions.some(action=>!isProviderAction(action))||new Set(capabilities.actions).size!==capabilities.actions.length)throw new Error(`Provider browser ${browser.browserId} has invalid action capabilities`);if(!["native","reconstructed","none"].includes(capabilities.screenshot))throw new Error(`Provider browser ${browser.browserId} has invalid screenshot capabilities`);if(capabilities.actions.includes("page_screenshot")===(capabilities.screenshot==="none"))throw new Error(`Provider browser ${browser.browserId} has inconsistent screenshot capabilities`)}if(browser.control.kind==="host"&&(!["extension","cdp"].includes(browser.control.transport)||typeof browser.control.browserId!="string"||!browser.control.browserId.trim()))throw new Error(`Provider browser ${browser.browserId} has invalid host control`);if(browser.references!==void 0&&(!Array.isArray(browser.references)||browser.references.some(reference=>!reference||typeof reference.kind!="string"||!reference.kind.trim()||typeof reference.id!="string"||!reference.id.trim()||!isOptionalString(reference.label))||new Set(browser.references.map(reference=>`${reference.kind}:${reference.id}`)).size!==browser.references.length))throw new Error(`Provider browser ${browser.browserId} has invalid references`);if(browser.details!==void 0&&(!browser.details||typeof browser.details!="object"||Array.isArray(browser.details)||!isJsonValue(browser.details)))throw new Error(`Provider browser ${browser.browserId} has invalid details`);if(browser.details){let details=browser.details,strings=value=>Array.isArray(value)&&value.every(item=>typeof item=="string");if(details.headless!==void 0&&typeof details.headless!="boolean"||details.createdAt!==void 0&&(typeof details.createdAt!="string"||!Number.isFinite(Date.parse(details.createdAt)))||details.cdpPort!==void 0&&(!Number.isInteger(details.cdpPort)||details.cdpPort<1||details.cdpPort>65535)||details.account!==void 0&&(!details.account||typeof details.account.nickname!="string"||!isOptionalString(details.account.accountId)||!isOptionalString(details.account.loginId))||details.copiedCookies!==void 0&&(!details.copiedCookies||!strings(details.copiedCookies.domains)||!Number.isInteger(details.copiedCookies.count)||details.copiedCookies.count<0))throw new Error(`Provider browser ${browser.browserId} has invalid common details`)}}function validateDefinition(definition){let{providerId,name,version:version2,protocolVersion}=definition.descriptor;if(!providerId?.trim())throw new Error("providerId is required");if(!name?.trim())throw new Error("provider name is required");if(!version2?.trim())throw new Error("provider version is required");if(protocolVersion!==void 0&&protocolVersion!==2)throw new Error(`Unsupported provider protocol ${protocolVersion}; expected ${2}`);if(!definition.browserType.name?.trim())throw new Error("provider browser type name is required");if(!isProviderInputSchema(definition.browserType.inputSchema)||definition.browserType.inputSchema.type!=="object")throw new Error("Provider input schema is invalid");if(definition.browserType.documentationUrl!==void 0&&(typeof definition.browserType.documentationUrl!="string"||!/^https?:\/\//.test(definition.browserType.documentationUrl)))throw new Error("Provider documentation URL must use HTTP(S)");let configuration=definition.browserType.configuration;if(configuration&&(!isProviderInputSchema(configuration.inputSchema)||configuration.inputSchema.type!=="object"))throw new Error("Provider configuration schema is invalid")}function createProviderRuntime(definition){validateDefinition(definition);let publishedBrowsers=[],validateRuntimeBrowser=browser=>{validateProviderBrowser(browser);let implementations={start:definition.start,detach:definition.detach,access:definition.getAccess,syncCookies:definition.syncCookies};for(let[operation,implementation]of Object.entries(implementations))if(browser.operations.includes(operation)&&!implementation)throw new Error(`Provider browser ${browser.browserId} advertises ${operation} without implementing it`)},listBrowsers=async(context={})=>{let browsers=definition.listBrowsers?await definition.listBrowsers(context):publishedBrowsers,seen=new Set;for(let browser of browsers){if(validateRuntimeBrowser(browser),seen.has(browser.browserId))throw new Error(`Duplicate provider browserId: ${browser.browserId}`);seen.add(browser.browserId)}return browsers},requireBrowser=async(browserId,operation,context)=>{let browser=(await listBrowsers(context)).find(item=>item.browserId===browserId);if(!browser)throw new Error(`Provider browser not found: ${browserId}`);if(!browser.operations.includes(operation))throw new Error(`Provider browser ${browserId} does not support ${operation}`);return browser};return{definition,listBrowsers,updateBrowsers(browsers){if(browsers.forEach(validateRuntimeBrowser),new Set(browsers.map(browser=>browser.browserId)).size!==browsers.length)throw new Error("Provider browser ids must be unique");publishedBrowsers=[...browsers]},async launch(options,context={}){validateProviderInput(definition.browserType.inputSchema,options);let browser=await definition.launch(options,context);return validateRuntimeBrowser(browser),browser},async start(request,context={}){if(await requireBrowser(request.browserId,"start",context),!definition.start)throw new Error("Provider does not implement start");let browser=await definition.start(request,context);return validateRuntimeBrowser(browser),browser},async close(request,context={}){return await requireBrowser(request.browserId,request.deleteData?"deleteData":"close",context),definition.close(request,context)},async detach(request,context={}){if(await requireBrowser(request.browserId,"detach",context),!definition.detach)throw new Error("Provider does not implement detach");return definition.detach(request,context)},async syncCookies(request,context={}){if(await requireBrowser(request.browserId,"syncCookies",context),!definition.syncCookies)throw new Error("Provider does not implement cookie sync");if(!request.scope||typeof request.scope!="object"||Array.isArray(request.scope)||!isJsonValue(request.scope))throw new Error("Cookie sync scope must be a JSON object");return definition.syncCookies(request,context)},async getAccess(request,context={}){if(await requireBrowser(request.browserId,"access",context),!definition.getAccess)throw new Error("Provider does not expose browser access");let access=await definition.getAccess(request,context);if(!access||typeof access.kind!="string"||!access.kind.trim()||typeof access.url!="string")throw new Error("Provider returned an invalid browser access result");let url2=new URL(access.url);if(!["http:","https:"].includes(url2.protocol)||access.sensitive!==!0)throw new Error("Provider returned an invalid browser access result");return{...access,url:url2.toString()}},async configure(options,context={}){let configuration=definition.browserType.configuration;if(!configuration||!definition.configure)throw new Error("Provider does not support configuration");return validateProviderInput(configuration.inputSchema,options),definition.configure(options,context)},async invokeAction(actionContext){let browser=(await listBrowsers({controlSource:actionContext.controlSource})).find(item=>item.browserId===actionContext.browserId);if(!browser)throw new Error(`Provider browser not found: ${actionContext.browserId}`);if(browser.status!=="connected")throw new Error(`Provider browser ${actionContext.browserId} is not connected`);if(browser.control.kind!=="provider")throw new Error(`Provider browser ${actionContext.browserId} uses host control`);if(!browser.control.capabilities.actions.includes(actionContext.action))throw new Error(`Provider browser ${actionContext.browserId} does not support ${actionContext.action}`);if(!definition.handleAction)throw new Error("Provider does not implement browser actions");return definition.handleAction(actionContext)}}}var INSTALLED_PROVIDERS_SUBDIR="providers/installed",LIVE_PROVIDERS_SUBDIR="providers/live",STARTING_PROVIDERS_SUBDIR="providers/starting";var PROVIDER_START_TOKEN_ENV="MEARL_PROVIDER_START_TOKEN",RESERVED_PROVIDER_IDS=new Set(["local","agentbay"]);function providerBrowserKey(providerId,browserId){return`provider:${encodeURIComponent(providerId)}:${encodeURIComponent(browserId)}`}function liveProviderFile(providerId){return keyedConfigFile(LIVE_PROVIDERS_SUBDIR,providerId)}function startingProviderFile(providerId){return keyedConfigFile(STARTING_PROVIDERS_SUBDIR,providerId)}function claimProviderStart(providerId,token,pid=process.pid){let file2=startingProviderFile(providerId),existing=readRecord(file2);return existing&&isAlive(existing.pid)?existing.token===token:(existing?removeRecordIfPid(file2,existing.pid):removeInvalidRecord(file2),claimRecord(file2,{pid,providerId,token,startedAt:new Date().toISOString()}))}function readProviderStart(providerId){let record2=readRecord(startingProviderFile(providerId));return record2&&isAlive(record2.pid)?record2:null}function transferProviderStart(providerId,token,pid){let file2=startingProviderFile(providerId),record2=readRecord(file2);return!record2||record2.token!==token?!1:writeRecordIfPid(file2,record2.pid,{...record2,pid})}function releaseProviderStart(providerId,token){let file2=startingProviderFile(providerId),record2=readRecord(file2);return record2?.token===token?removeRecordIfPid(file2,record2.pid):!1}function validateInstalledProviderManifest(manifest){if(!manifest||typeof manifest.providerId!="string"||!manifest.providerId.trim()||typeof manifest.name!="string"||!manifest.name.trim()||typeof manifest.version!="string"||!manifest.version.trim())return"manifest is incomplete";if(manifest.protocolVersion!==2)return`protocol ${manifest.protocolVersion} is unsupported`;if(RESERVED_PROVIDER_IDS.has(manifest.providerId))return`providerId ${manifest.providerId} is reserved for a built-in Provider`;if(!isProviderBrowserType(manifest.browserType))return"browserType is invalid";if(typeof manifest.packageName!="string"||!manifest.packageName.trim())return"packageName is required";if(typeof manifest.packageRoot!="string"||!isAbsolute(manifest.packageRoot))return"packageRoot must be an absolute path";if(typeof manifest.entryPath!="string"||!isAbsolute(manifest.entryPath))return"entryPath must be an absolute path";let entryRelative=relative(manifest.packageRoot,manifest.entryPath);return entryRelative===""||isAbsolute(entryRelative)||entryRelative===".."||entryRelative.startsWith(`..${sep}`)?"entryPath must be a file inside packageRoot":isFile(manifest.entryPath)?null:"entryPath does not exist or is not a file"}function isFile(filePath){try{return statSync3(filePath).isFile()}catch{return!1}}function isProviderBrowserType(value){if(!value||typeof value!="object")return!1;let browserType=value;return typeof browserType.name!="string"||!browserType.name.trim()||browserType.documentationUrl!==void 0&&(typeof browserType.documentationUrl!="string"||!/^https?:\/\//.test(browserType.documentationUrl))||!isProviderObjectSchema(browserType.inputSchema)?!1:browserType.configuration===void 0||!!browserType.configuration&&typeof browserType.configuration=="object"&&isProviderObjectSchema(browserType.configuration.inputSchema)}function isProviderObjectSchema(value){return isProviderInputSchema(value)&&value.type==="object"}function listInstalledProviders(){let manifests=[];for(let file2 of listRecordFiles(keyedDir(INSTALLED_PROVIDERS_SUBDIR)))try{let parsed=JSON.parse(readFileSync3(file2,"utf8"));parsed&&typeof parsed.providerId=="string"&&typeof parsed.packageName=="string"&&manifests.push(parsed)}catch{}return manifests.sort((a,b)=>a.providerId.localeCompare(b.providerId))}function readLiveProvider(providerId){let record2=readRecord(liveProviderFile(providerId));return record2&&isAlive(record2.pid)?record2:null}function listLiveProviders(){return readLiveRecords(keyedDir(LIVE_PROVIDERS_SUBDIR))}var PROVIDER_LOGS_SUBDIR="providers/logs";function providerLogFile(providerId){let hash2=hashKey(providerId);return join4(keyedDir(PROVIDER_LOGS_SUBDIR),`${hash2}.log`)}function liveProviderIds(){return new Set(listLiveProviders().map(record2=>record2.providerId))}function delay(ms){return new Promise(resolve5=>setTimeout(resolve5,ms))}async function spawnProvider(manifest,logFile,startToken){mkdirSync2(keyedDir(PROVIDER_LOGS_SUBDIR),{recursive:!0,mode:448}),rotateLogIfNeeded(logFile);let output2=openSync3(logFile,"a");try{return await new Promise((resolve5,reject)=>{let child=spawn2(process.execPath,[manifest.entryPath],{cwd:manifest.packageRoot,env:{...process.env,[PROVIDER_START_TOKEN_ENV]:startToken},detached:!0,stdio:["ignore",output2,output2],windowsHide:!0});child.once("error",reject),child.once("spawn",()=>{child.removeAllListeners("error"),child.on("error",()=>{}),child.unref(),child.pid?resolve5(child.pid):reject(new Error("spawned process has no pid"))})})}finally{closeSync3(output2)}}async function ensureInstalledProvidersRunning(){let warnings=[],installed=listInstalledProviders(),live=liveProviderIds(),starting=new Map;for(let manifest of installed){if(live.has(manifest.providerId))continue;let invalid=validateInstalledProviderManifest(manifest);if(invalid){warnings.push(`provider ${manifest.providerId||"(unknown)"}: ${invalid}`);continue}let startToken=randomUUID2();if(!claimProviderStart(manifest.providerId,startToken)){if(readLiveProvider(manifest.providerId))continue;readProviderStart(manifest.providerId)?starting.set(manifest.providerId,null):warnings.push(`provider ${manifest.providerId}: failed to acquire startup ownership`);continue}if(readLiveProvider(manifest.providerId)){releaseProviderStart(manifest.providerId,startToken);continue}let logFile=providerLogFile(manifest.providerId);try{let childPid=await spawnProvider(manifest,logFile,startToken);transferProviderStart(manifest.providerId,startToken,childPid),starting.set(manifest.providerId,startToken)}catch(error48){releaseProviderStart(manifest.providerId,startToken),warnings.push(`provider ${manifest.providerId}: ${error48 instanceof Error?error48.message:String(error48)}`)}}if(starting.size===0)return warnings;let deadline=Date.now()+2e3,remaining=[...starting.keys()];for(;remaining.length>0&&Date.now()<deadline;){await delay(100);let current=liveProviderIds();remaining=remaining.filter(providerId=>!current.has(providerId))}for(let[providerId,token]of starting)!remaining.includes(providerId)&&token&&releaseProviderStart(providerId,token);for(let providerId of remaining){let logFile=providerLogFile(providerId);warnings.push(`provider ${providerId}: did not become ready within 2s${existsSync4(logFile)?`; see ${logFile}`:""}`)}return await delay(100),warnings}import{StringDecoder}from"node:string_decoder";var Utf8LineBuffer=class{constructor(maxBufferBytes){this.maxBufferBytes=maxBufferBytes}buffer="";decoder=new StringDecoder("utf8");push(chunk){if(this.buffer+=this.decoder.write(chunk),Buffer.byteLength(this.buffer,"utf8")>this.maxBufferBytes)return this.buffer="",{lines:[],overflow:!0};let lines=[],newlineIndex;for(;(newlineIndex=this.buffer.indexOf(`
|
|
461
461
|
`))!==-1;)lines.push(this.buffer.slice(0,newlineIndex)),this.buffer=this.buffer.slice(newlineIndex+1);return{lines,overflow:!1}}};import net from"node:net";var MAX_RESPONSE_BUFFER_SIZE=16*1024*1024;function requestBrowserSocket(socketPath,action,data,version2,timeoutMs=6e4,browserId){let id=`browser_manager_${Date.now()}_${Math.random().toString(36).slice(2,10)}`;return new Promise((resolve5,reject)=>{let client2=net.createConnection(socketPath),lines=new Utf8LineBuffer(MAX_RESPONSE_BUFFER_SIZE),settled=!1,finish=(error48,result)=>{settled||(settled=!0,clearTimeout(timer),client2.removeAllListeners(),client2.destroy(),error48?reject(error48):resolve5(result))},timer=setTimeout(()=>finish(new Error(`Browser request timeout after ${timeoutMs}ms`)),timeoutMs);client2.on("connect",()=>{client2.write(`${JSON.stringify({id,action,data,version:version2,controlSource:"local",...browserId?{browserId}:{}})}
|
|
462
|
-
`)}),client2.on("data",chunk=>{let result=lines.push(chunk);if(result.overflow){finish(new Error("Browser response exceeded the supported size"));return}for(let line of result.lines){let response;try{response=JSON.parse(line)}catch{continue}if(response.id===id){response.success?finish(void 0,response.data):finish(new Error(response.error||"Browser request failed"));return}}}),client2.on("error",error48=>finish(error48)),client2.on("end",()=>finish(new Error("Browser connection closed before responding"))),client2.on("close",()=>finish(new Error("Browser connection closed before responding")))})}import http2 from"node:http";import WebSocket from"ws";var CdpChildSession=class{constructor(parent,sessionId){this.parent=parent;this.sessionId=sessionId}sendCommand(method,params,timeoutMs=3e4){return this.parent.sendCommandInSession(this.sessionId,method,params,timeoutMs)}on(method,callback){return this.parent.onSession(this.sessionId,method,callback)}createChildSession(sessionId){return this.parent.createChildSession(sessionId)}get closed(){return this.parent.closed}close(){}},CdpClient=class _CdpClient{constructor(socket){this.socket=socket;socket.on("message",data=>this.consumeMessage(data)),socket.on("close",()=>this.handleClosed()),socket.on("error",()=>this.handleClosed())}nextId=1;pending=new Map;eventHandlers=new Map;sessionEventHandlers=new Map;_closed=!1;static connect(wsUrl){return new Promise((resolve5,reject)=>{let url2;try{url2=new URL(wsUrl)}catch{reject(new Error("Invalid CDP WebSocket URL"));return}if(url2.protocol!=="ws:"&&url2.protocol!=="wss:"){reject(new Error(`Unsupported CDP WebSocket protocol: ${url2.protocol}`));return}let socket=new WebSocket(url2,{handshakeTimeout:5e3,maxPayload:64*1024*1024,perMessageDeflate:!1}),settled=!1,fail=error48=>{settled||(settled=!0,socket.terminate(),reject(error48))};socket.once("open",()=>{settled||(settled=!0,resolve5(new _CdpClient(socket)))}),socket.once("error",fail),socket.once("unexpected-response",(_request,response)=>{response.resume(),fail(new Error(`CDP WebSocket upgrade failed with status ${response.statusCode??0}`))})})}createChildSession(sessionId){return new CdpChildSession(this,sessionId)}sendCommandInSession(sessionId,method,params,timeoutMs=3e4){return this.sendRequest(method,params,timeoutMs,sessionId)}onSession(sessionId,method,callback){this.sessionEventHandlers.has(sessionId)||this.sessionEventHandlers.set(sessionId,new Map);let sessionMap=this.sessionEventHandlers.get(sessionId);return sessionMap.has(method)||sessionMap.set(method,new Set),sessionMap.get(method).add(callback),()=>sessionMap.get(method)?.delete(callback)}sendCommand(method,params,timeoutMs=3e4){return this.sendRequest(method,params,timeoutMs)}on(method,callback){return this.eventHandlers.has(method)||this.eventHandlers.set(method,new Set),this.eventHandlers.get(method).add(callback),()=>this.eventHandlers.get(method)?.delete(callback)}close(){this._closed||(this._closed=!0,this.socket.terminate(),this.rejectPending("CDP connection closed"))}get closed(){return this._closed}sendRequest(method,params,timeoutMs,sessionId){return new Promise((resolve5,reject)=>{if(this._closed||this.socket.readyState!==WebSocket.OPEN){reject(new Error("CDP client is closed"));return}let id=this.nextId++,timer=setTimeout(()=>{this.pending.delete(id),reject(new Error(`CDP command timeout: ${method}`))},timeoutMs);this.pending.set(id,{resolve:resolve5,reject,timer,sessionId}),this.socket.send(JSON.stringify({id,method,params:params??{},...sessionId?{sessionId}:{}}),error48=>{if(!error48)return;let pending=this.pending.get(id);pending&&(clearTimeout(pending.timer),this.pending.delete(id),pending.reject(error48))})})}consumeMessage(data){try{let text=Array.isArray(data)?Buffer.concat(data).toString("utf8"):Buffer.isBuffer(data)?data.toString("utf8"):Buffer.from(data).toString("utf8");this.handleMessage(JSON.parse(text))}catch{}}handleMessage(msg){if(msg.id!==void 0){let pending=this.pending.get(msg.id);if(!pending)return;clearTimeout(pending.timer),this.pending.delete(msg.id),msg.error?pending.reject(new Error(msg.error.message??JSON.stringify(msg.error))):pending.resolve(msg.result??{});return}if(!msg.method)return;let handlers=msg.sessionId?this.sessionEventHandlers.get(msg.sessionId)?.get(msg.method):this.eventHandlers.get(msg.method);if(handlers)for(let callback of handlers)try{callback(msg.params)}catch{}}handleClosed(){this._closed||(this._closed=!0,this.rejectPending("CDP connection closed"))}rejectPending(message){for(let[id,pending]of this.pending)clearTimeout(pending.timer),pending.reject(new Error(message)),this.pending.delete(id)}};import{TextDecoder as TextDecoder2}from"node:util";var TDBANK_ORIGIN="https://tdbank.alibaba-inc.com",TDBANK_QR_LOGIN_URL="https://login.alibaba-inc.com/ssoLogin.htm?APP_NAME=tdbank&BACK_URL=https%3A%2F%2Ftdbank.alibaba-inc.com%2FmyAccount.html",TDBANK_PASSWORDLESS_TARGET_URL="https://main.m.taobao.com",TDBANK_LOGIN_REQUIRED_MESSAGE=`TDBANK_LOGIN_REQUIRED: TDBank 登录态已失效。可执行 mearl tdbank_account --payload '{"operation":"login"}' 获取扫码登录二维码;如果只需切换淘宝测试账号,请先向用户索取 havanaId 和 ssoKey,再执行 mearl tdbank_account --payload '{"operation":"switch","havanaId":"<Havana ID>","ssoKey":"<秘钥>"}' 免密切换。`,GENERATE_QRCODE_API="/rpc/login/generateQrcode.json",CHECK_QRCODE_API="/rpc/login/checkQrcode.json",LOGIN_API="/rpc/login/doLoginV2.json";function buildTdbankQrImageUrl(qrcode){let url2=new URL("/common/generateQRCode.do",TDBANK_QR_LOGIN_URL);return url2.searchParams.set("qrCode",qrcode),url2.toString()}function buildTdbankPasswordlessSsoUrl(havanaId,ssoKey){let normalizedHavanaId=String(havanaId).trim();if(!/^\d+$/.test(normalizedHavanaId))throw new Error("havanaId must be a numeric ID for passwordless TDBank switch");let url2=new URL("/oneStepSso.do",TDBANK_ORIGIN);return url2.searchParams.set("havanaId",normalizedHavanaId),url2.searchParams.set("site","taobao"),url2.searchParams.set("ssoKey",ssoKey),url2.searchParams.set("targetUrl",TDBANK_PASSWORDLESS_TARGET_URL),url2.toString()}function isTdbankSecretField(key){return key.replace(/[_-]/g,"").toLowerCase()==="ssokey"}function sanitizeTdbankSecrets(value){if(Array.isArray(value))return value.map(item=>sanitizeTdbankSecrets(item));if(!value||typeof value!="object")return value;let prototype=Object.getPrototypeOf(value);if(prototype!==Object.prototype&&prototype!==null)return value;let sanitized={};for(let[key,item]of Object.entries(value))isTdbankSecretField(key)||(sanitized[key]=sanitizeTdbankSecrets(item));return sanitized}function asRecord(value){return!value||typeof value!="object"||Array.isArray(value)?null:value}function parseResponseBody(value){if(typeof value=="string")try{return asRecord(JSON.parse(value))}catch{return null}return asRecord(value)}function findLatestParsed(requests,apiName,parse4){let latest=null;for(let request of requests){let capturedName=request.apiName.split(/[?#]/,1)[0].replace(/^\/+/,""),expectedName=apiName.replace(/^\/+/,"");if(capturedName!==expectedName&&!capturedName.endsWith(`/${expectedName}`)&&!expectedName.endsWith(`/${capturedName}`))continue;let value=parse4(request.responseBody);value&&(!latest||request.timestampMs>=latest.timestampMs)&&(latest={timestampMs:request.timestampMs,value})}return latest?.value??null}function parseTdbankLoginQrCode(responseBody){let body=parseResponseBody(responseBody),envelope=asRecord(body?.content),content=asRecord(envelope?.content);if(envelope?.success!==!0)return null;let qrcode=typeof content?.qrcode=="string"?content.qrcode:"",qrcodeId=typeof content?.qrcodeId=="string"?content.qrcodeId:"";return qrcode&&qrcodeId?{qrcode,qrcodeId}:null}function findLatestTdbankLoginQrCode(requests){return findLatestParsed(requests,GENERATE_QRCODE_API,parseTdbankLoginQrCode)}function parseTdbankLoginQrCheck(responseBody){let body=parseResponseBody(responseBody),envelope=asRecord(body?.content);if(!envelope||typeof envelope.code!="number")return null;let code=envelope.code,message=typeof envelope.msg=="string"&&envelope.msg?envelope.msg:void 0;return code!==0?{status:"failed",code,...message?{message}:{}}:{status:envelope.content===!0?"scanned":"waiting_for_scan",code,...message?{message}:{}}}function findLatestTdbankLoginQrCheck(requests){return findLatestParsed(requests,CHECK_QRCODE_API,parseTdbankLoginQrCheck)}function parseTdbankLoginIdentityPrompt(responseBody){let body=parseResponseBody(responseBody),envelope=asRecord(body?.content),next=asRecord(asRecord(envelope?.content)?.next),data=asRecord(next?.data),loginUser=asRecord(data?.loginUser);if(envelope?.success!==!0||next?.action!=="switchIdentity"||!loginUser)return null;let loginUserId=String(loginUser.id??"").trim(),personalAccount=String(loginUser.account??"").trim();if(!loginUserId||!personalAccount)return null;let identities=[{identityId:loginUserId,identityType:"personal",account:personalAccount,displayName:String(loginUser.displayName??personalAccount),available:!0}];for(let candidate of Array.isArray(data?.proxy)?data.proxy:[]){let proxy=asRecord(candidate),identityId=String(proxy?.id??"").trim(),account=String(proxy?.account??"").trim();!identityId||!account||identities.push({identityId,identityType:"proxy",account,displayName:String(proxy?.accountNick??account),...proxy?.accountType?{accountType:String(proxy.accountType)}:{},...proxy?.accountSite?{accountSite:String(proxy.accountSite)}:{},available:proxy?.available!=="F"})}return{loginUserId,identities}}function findLatestTdbankLoginIdentityPrompt(requests){return findLatestParsed(requests,LOGIN_API,parseTdbankLoginIdentityPrompt)}function parseTdbankLoginContinuation(responseBody){let body=parseResponseBody(responseBody),envelope=asRecord(body?.content);if(envelope?.success!==!0)return null;let next=asRecord(asRecord(envelope.content)?.next);if(typeof next?.action=="string"){let data=asRecord(next.data);return{action:next.action,...typeof data?.url=="string"&&data.url?{redirectUrl:data.url}:{}}}let extInfo=asRecord(envelope.extInfo);return typeof extInfo?.redirectURL=="string"&&extInfo.redirectURL?{action:"redirect",redirectUrl:extInfo.redirectURL}:null}function findLatestTdbankLoginContinuation(requests){return findLatestParsed(requests,LOGIN_API,parseTdbankLoginContinuation)}function md5(input2){function rotateLeft(v,s){return v<<s|v>>>32-s}function addUnsigned(x,y){let lsw=(x&65535)+(y&65535);return(x>>16)+(y>>16)+(lsw>>16)<<16|lsw&65535}function cmn(q,a2,b2,x,s,t){return addUnsigned(rotateLeft(addUnsigned(addUnsigned(a2,q),addUnsigned(x,t)),s),b2)}function ff(a2,b2,c2,d2,x,s,t){return cmn(b2&c2|~b2&d2,a2,b2,x,s,t)}function gg(a2,b2,c2,d2,x,s,t){return cmn(b2&d2|c2&~d2,a2,b2,x,s,t)}function hh(a2,b2,c2,d2,x,s,t){return cmn(b2^c2^d2,a2,b2,x,s,t)}function ii(a2,b2,c2,d2,x,s,t){return cmn(c2^(b2|~d2),a2,b2,x,s,t)}let str=input2.replace(/\r\n/g,`
|
|
462
|
+
`)}),client2.on("data",chunk=>{let result=lines.push(chunk);if(result.overflow){finish(new Error("Browser response exceeded the supported size"));return}for(let line of result.lines){let response;try{response=JSON.parse(line)}catch{continue}if(response.id===id){response.success?finish(void 0,response.data):finish(new Error(response.error||"Browser request failed"));return}}}),client2.on("error",error48=>finish(error48)),client2.on("end",()=>finish(new Error("Browser connection closed before responding"))),client2.on("close",()=>finish(new Error("Browser connection closed before responding")))})}import http2 from"node:http";import WebSocket from"ws";var CdpChildSession=class{constructor(parent,sessionId){this.parent=parent;this.sessionId=sessionId}sendCommand(method,params,timeoutMs=3e4){return this.parent.sendCommandInSession(this.sessionId,method,params,timeoutMs)}on(method,callback){return this.parent.onSession(this.sessionId,method,callback)}createChildSession(sessionId){return this.parent.createChildSession(sessionId)}get closed(){return this.parent.closed}close(){}},CdpClient=class _CdpClient{constructor(socket){this.socket=socket;socket.on("message",data=>this.consumeMessage(data)),socket.on("close",()=>this.handleClosed()),socket.on("error",()=>this.handleClosed())}nextId=1;pending=new Map;eventHandlers=new Map;sessionEventHandlers=new Map;_closed=!1;static connect(wsUrl){return new Promise((resolve5,reject)=>{let url2;try{url2=new URL(wsUrl)}catch{reject(new Error("Invalid CDP WebSocket URL"));return}if(url2.protocol!=="ws:"&&url2.protocol!=="wss:"){reject(new Error(`Unsupported CDP WebSocket protocol: ${url2.protocol}`));return}let socket=new WebSocket(url2,{handshakeTimeout:5e3,maxPayload:64*1024*1024,perMessageDeflate:!1}),settled=!1,fail2=error48=>{settled||(settled=!0,socket.terminate(),reject(error48))};socket.once("open",()=>{settled||(settled=!0,resolve5(new _CdpClient(socket)))}),socket.once("error",fail2),socket.once("unexpected-response",(_request,response)=>{response.resume(),fail2(new Error(`CDP WebSocket upgrade failed with status ${response.statusCode??0}`))})})}createChildSession(sessionId){return new CdpChildSession(this,sessionId)}sendCommandInSession(sessionId,method,params,timeoutMs=3e4){return this.sendRequest(method,params,timeoutMs,sessionId)}onSession(sessionId,method,callback){this.sessionEventHandlers.has(sessionId)||this.sessionEventHandlers.set(sessionId,new Map);let sessionMap=this.sessionEventHandlers.get(sessionId);return sessionMap.has(method)||sessionMap.set(method,new Set),sessionMap.get(method).add(callback),()=>sessionMap.get(method)?.delete(callback)}sendCommand(method,params,timeoutMs=3e4){return this.sendRequest(method,params,timeoutMs)}on(method,callback){return this.eventHandlers.has(method)||this.eventHandlers.set(method,new Set),this.eventHandlers.get(method).add(callback),()=>this.eventHandlers.get(method)?.delete(callback)}close(){this._closed||(this._closed=!0,this.socket.terminate(),this.rejectPending("CDP connection closed"))}get closed(){return this._closed}sendRequest(method,params,timeoutMs,sessionId){return new Promise((resolve5,reject)=>{if(this._closed||this.socket.readyState!==WebSocket.OPEN){reject(new Error("CDP client is closed"));return}let id=this.nextId++,timer=setTimeout(()=>{this.pending.delete(id),reject(new Error(`CDP command timeout: ${method}`))},timeoutMs);this.pending.set(id,{resolve:resolve5,reject,timer,sessionId}),this.socket.send(JSON.stringify({id,method,params:params??{},...sessionId?{sessionId}:{}}),error48=>{if(!error48)return;let pending=this.pending.get(id);pending&&(clearTimeout(pending.timer),this.pending.delete(id),pending.reject(error48))})})}consumeMessage(data){try{let text=Array.isArray(data)?Buffer.concat(data).toString("utf8"):Buffer.isBuffer(data)?data.toString("utf8"):Buffer.from(data).toString("utf8");this.handleMessage(JSON.parse(text))}catch{}}handleMessage(msg){if(msg.id!==void 0){let pending=this.pending.get(msg.id);if(!pending)return;clearTimeout(pending.timer),this.pending.delete(msg.id),msg.error?pending.reject(new Error(msg.error.message??JSON.stringify(msg.error))):pending.resolve(msg.result??{});return}if(!msg.method)return;let handlers=msg.sessionId?this.sessionEventHandlers.get(msg.sessionId)?.get(msg.method):this.eventHandlers.get(msg.method);if(handlers)for(let callback of handlers)try{callback(msg.params)}catch{}}handleClosed(){this._closed||(this._closed=!0,this.rejectPending("CDP connection closed"))}rejectPending(message){for(let[id,pending]of this.pending)clearTimeout(pending.timer),pending.reject(new Error(message)),this.pending.delete(id)}};import{TextDecoder as TextDecoder2}from"node:util";var TDBANK_ORIGIN="https://tdbank.alibaba-inc.com",TDBANK_QR_LOGIN_URL="https://login.alibaba-inc.com/ssoLogin.htm?APP_NAME=tdbank&BACK_URL=https%3A%2F%2Ftdbank.alibaba-inc.com%2FmyAccount.html",TDBANK_PASSWORDLESS_TARGET_URL="https://main.m.taobao.com",TDBANK_LOGIN_REQUIRED_MESSAGE=`TDBANK_LOGIN_REQUIRED: TDBank 登录态已失效。可执行 mearl tdbank_account --payload '{"operation":"login"}' 获取扫码登录二维码;如果只需切换淘宝测试账号,请先向用户索取 havanaId 和 ssoKey,再执行 mearl tdbank_account --payload '{"operation":"switch","havanaId":"<Havana ID>","ssoKey":"<秘钥>"}' 免密切换。`,GENERATE_QRCODE_API="/rpc/login/generateQrcode.json",CHECK_QRCODE_API="/rpc/login/checkQrcode.json",LOGIN_API="/rpc/login/doLoginV2.json";function buildTdbankQrImageUrl(qrcode){let url2=new URL("/common/generateQRCode.do",TDBANK_QR_LOGIN_URL);return url2.searchParams.set("qrCode",qrcode),url2.toString()}function buildTdbankPasswordlessSsoUrl(havanaId,ssoKey){let normalizedHavanaId=String(havanaId).trim();if(!/^\d+$/.test(normalizedHavanaId))throw new Error("havanaId must be a numeric ID for passwordless TDBank switch");let url2=new URL("/oneStepSso.do",TDBANK_ORIGIN);return url2.searchParams.set("havanaId",normalizedHavanaId),url2.searchParams.set("site","taobao"),url2.searchParams.set("ssoKey",ssoKey),url2.searchParams.set("targetUrl",TDBANK_PASSWORDLESS_TARGET_URL),url2.toString()}function isTdbankSecretField(key){return key.replace(/[_-]/g,"").toLowerCase()==="ssokey"}function sanitizeTdbankSecrets(value){if(Array.isArray(value))return value.map(item=>sanitizeTdbankSecrets(item));if(!value||typeof value!="object")return value;let prototype=Object.getPrototypeOf(value);if(prototype!==Object.prototype&&prototype!==null)return value;let sanitized={};for(let[key,item]of Object.entries(value))isTdbankSecretField(key)||(sanitized[key]=sanitizeTdbankSecrets(item));return sanitized}function asRecord(value){return!value||typeof value!="object"||Array.isArray(value)?null:value}function parseResponseBody(value){if(typeof value=="string")try{return asRecord(JSON.parse(value))}catch{return null}return asRecord(value)}function findLatestParsed(requests,apiName,parse4){let latest=null;for(let request of requests){let capturedName=request.apiName.split(/[?#]/,1)[0].replace(/^\/+/,""),expectedName=apiName.replace(/^\/+/,"");if(capturedName!==expectedName&&!capturedName.endsWith(`/${expectedName}`)&&!expectedName.endsWith(`/${capturedName}`))continue;let value=parse4(request.responseBody);value&&(!latest||request.timestampMs>=latest.timestampMs)&&(latest={timestampMs:request.timestampMs,value})}return latest?.value??null}function parseTdbankLoginQrCode(responseBody){let body=parseResponseBody(responseBody),envelope=asRecord(body?.content),content=asRecord(envelope?.content);if(envelope?.success!==!0)return null;let qrcode=typeof content?.qrcode=="string"?content.qrcode:"",qrcodeId=typeof content?.qrcodeId=="string"?content.qrcodeId:"";return qrcode&&qrcodeId?{qrcode,qrcodeId}:null}function findLatestTdbankLoginQrCode(requests){return findLatestParsed(requests,GENERATE_QRCODE_API,parseTdbankLoginQrCode)}function parseTdbankLoginQrCheck(responseBody){let body=parseResponseBody(responseBody),envelope=asRecord(body?.content);if(!envelope||typeof envelope.code!="number")return null;let code=envelope.code,message=typeof envelope.msg=="string"&&envelope.msg?envelope.msg:void 0;return code!==0?{status:"failed",code,...message?{message}:{}}:{status:envelope.content===!0?"scanned":"waiting_for_scan",code,...message?{message}:{}}}function findLatestTdbankLoginQrCheck(requests){return findLatestParsed(requests,CHECK_QRCODE_API,parseTdbankLoginQrCheck)}function parseTdbankLoginIdentityPrompt(responseBody){let body=parseResponseBody(responseBody),envelope=asRecord(body?.content),next=asRecord(asRecord(envelope?.content)?.next),data=asRecord(next?.data),loginUser=asRecord(data?.loginUser);if(envelope?.success!==!0||next?.action!=="switchIdentity"||!loginUser)return null;let loginUserId=String(loginUser.id??"").trim(),personalAccount=String(loginUser.account??"").trim();if(!loginUserId||!personalAccount)return null;let identities=[{identityId:loginUserId,identityType:"personal",account:personalAccount,displayName:String(loginUser.displayName??personalAccount),available:!0}];for(let candidate of Array.isArray(data?.proxy)?data.proxy:[]){let proxy=asRecord(candidate),identityId=String(proxy?.id??"").trim(),account=String(proxy?.account??"").trim();!identityId||!account||identities.push({identityId,identityType:"proxy",account,displayName:String(proxy?.accountNick??account),...proxy?.accountType?{accountType:String(proxy.accountType)}:{},...proxy?.accountSite?{accountSite:String(proxy.accountSite)}:{},available:proxy?.available!=="F"})}return{loginUserId,identities}}function findLatestTdbankLoginIdentityPrompt(requests){return findLatestParsed(requests,LOGIN_API,parseTdbankLoginIdentityPrompt)}function parseTdbankLoginContinuation(responseBody){let body=parseResponseBody(responseBody),envelope=asRecord(body?.content);if(envelope?.success!==!0)return null;let next=asRecord(asRecord(envelope.content)?.next);if(typeof next?.action=="string"){let data=asRecord(next.data);return{action:next.action,...typeof data?.url=="string"&&data.url?{redirectUrl:data.url}:{}}}let extInfo=asRecord(envelope.extInfo);return typeof extInfo?.redirectURL=="string"&&extInfo.redirectURL?{action:"redirect",redirectUrl:extInfo.redirectURL}:null}function findLatestTdbankLoginContinuation(requests){return findLatestParsed(requests,LOGIN_API,parseTdbankLoginContinuation)}function md5(input2){function rotateLeft(v,s){return v<<s|v>>>32-s}function addUnsigned(x,y){let lsw=(x&65535)+(y&65535);return(x>>16)+(y>>16)+(lsw>>16)<<16|lsw&65535}function cmn(q,a2,b2,x,s,t){return addUnsigned(rotateLeft(addUnsigned(addUnsigned(a2,q),addUnsigned(x,t)),s),b2)}function ff(a2,b2,c2,d2,x,s,t){return cmn(b2&c2|~b2&d2,a2,b2,x,s,t)}function gg(a2,b2,c2,d2,x,s,t){return cmn(b2&d2|c2&~d2,a2,b2,x,s,t)}function hh(a2,b2,c2,d2,x,s,t){return cmn(b2^c2^d2,a2,b2,x,s,t)}function ii(a2,b2,c2,d2,x,s,t){return cmn(c2^(b2|~d2),a2,b2,x,s,t)}let str=input2.replace(/\r\n/g,`
|
|
463
463
|
`),encoded="";for(let n=0;n<str.length;n++){let c2=str.charCodeAt(n);c2<128?encoded+=String.fromCharCode(c2):c2<2048?(encoded+=String.fromCharCode(c2>>6|192),encoded+=String.fromCharCode(c2&63|128)):(encoded+=String.fromCharCode(c2>>12|224),encoded+=String.fromCharCode(c2>>6&63|128),encoded+=String.fromCharCode(c2&63|128))}str=encoded;let len=str.length,nw=(len+8>>>6)+1<<4,words=new Array(nw).fill(0);for(let i=0;i<len;i++)words[i>>2]|=str.charCodeAt(i)<<i%4*8;words[len>>2]|=128<<len%4*8,words[nw-2]=len<<3,words[nw-1]=len>>>29;let a=1732584193,b=4023233417,c=2562383102,d=271733878;for(let k=0;k<words.length;k+=16){let aa=a,bb=b,cc=c,dd=d;a=ff(a,b,c,d,words[k],7,3614090360),d=ff(d,a,b,c,words[k+1],12,3905402710),c=ff(c,d,a,b,words[k+2],17,606105819),b=ff(b,c,d,a,words[k+3],22,3250441966),a=ff(a,b,c,d,words[k+4],7,4118548399),d=ff(d,a,b,c,words[k+5],12,1200080426),c=ff(c,d,a,b,words[k+6],17,2821735955),b=ff(b,c,d,a,words[k+7],22,4249261313),a=ff(a,b,c,d,words[k+8],7,1770035416),d=ff(d,a,b,c,words[k+9],12,2336552879),c=ff(c,d,a,b,words[k+10],17,4294925233),b=ff(b,c,d,a,words[k+11],22,2304563134),a=ff(a,b,c,d,words[k+12],7,1804603682),d=ff(d,a,b,c,words[k+13],12,4254626195),c=ff(c,d,a,b,words[k+14],17,2792965006),b=ff(b,c,d,a,words[k+15],22,1236535329),a=gg(a,b,c,d,words[k+1],5,4129170786),d=gg(d,a,b,c,words[k+6],9,3225465664),c=gg(c,d,a,b,words[k+11],14,643717713),b=gg(b,c,d,a,words[k],20,3921069994),a=gg(a,b,c,d,words[k+5],5,3593408605),d=gg(d,a,b,c,words[k+10],9,38016083),c=gg(c,d,a,b,words[k+15],14,3634488961),b=gg(b,c,d,a,words[k+4],20,3889429448),a=gg(a,b,c,d,words[k+9],5,568446438),d=gg(d,a,b,c,words[k+14],9,3275163606),c=gg(c,d,a,b,words[k+3],14,4107603335),b=gg(b,c,d,a,words[k+8],20,1163531501),a=gg(a,b,c,d,words[k+13],5,2850285829),d=gg(d,a,b,c,words[k+2],9,4243563512),c=gg(c,d,a,b,words[k+7],14,1735328473),b=gg(b,c,d,a,words[k+12],20,2368359562),a=hh(a,b,c,d,words[k+5],4,4294588738),d=hh(d,a,b,c,words[k+8],11,2272392833),c=hh(c,d,a,b,words[k+11],16,1839030562),b=hh(b,c,d,a,words[k+14],23,4259657740),a=hh(a,b,c,d,words[k+1],4,2763975236),d=hh(d,a,b,c,words[k+4],11,1272893353),c=hh(c,d,a,b,words[k+7],16,4139469664),b=hh(b,c,d,a,words[k+10],23,3200236656),a=hh(a,b,c,d,words[k+13],4,681279174),d=hh(d,a,b,c,words[k],11,3936430074),c=hh(c,d,a,b,words[k+3],16,3572445317),b=hh(b,c,d,a,words[k+6],23,76029189),a=hh(a,b,c,d,words[k+9],4,3654602809),d=hh(d,a,b,c,words[k+12],11,3873151461),c=hh(c,d,a,b,words[k+15],16,530742520),b=hh(b,c,d,a,words[k+2],23,3299628645),a=ii(a,b,c,d,words[k],6,4096336452),d=ii(d,a,b,c,words[k+7],10,1126891415),c=ii(c,d,a,b,words[k+14],15,2878612391),b=ii(b,c,d,a,words[k+5],21,4237533241),a=ii(a,b,c,d,words[k+12],6,1700485571),d=ii(d,a,b,c,words[k+3],10,2399980690),c=ii(c,d,a,b,words[k+10],15,4293915773),b=ii(b,c,d,a,words[k+1],21,2240044497),a=ii(a,b,c,d,words[k+8],6,1873313359),d=ii(d,a,b,c,words[k+15],10,4264355552),c=ii(c,d,a,b,words[k+6],15,2734768916),b=ii(b,c,d,a,words[k+13],21,1309151649),a=ii(a,b,c,d,words[k+4],6,4149444226),d=ii(d,a,b,c,words[k+11],10,3174756917),c=ii(c,d,a,b,words[k+2],15,718787259),b=ii(b,c,d,a,words[k+9],21,3951481745),a=addUnsigned(a,aa),b=addUnsigned(b,bb),c=addUnsigned(c,cc),d=addUnsigned(d,dd)}let hex3=v=>{let s="";for(let i=0;i<=3;i++){let byte=v>>>i*8&255;s+=("0"+byte.toString(16)).slice(-2)}return s};return(hex3(a)+hex3(b)+hex3(c)+hex3(d)).toLowerCase()}function extractMtopToken(cookieMap,isMopen){if(isMopen){let mTk=cookieMap.get("m_tk"),tbToken=cookieMap.get("_tb_token_");if(mTk)return mTk.split("_")[0]||"";if(tbToken)return tbToken;throw new Error("Missing m_tk or _tb_token_ cookie. Please ensure the user is logged in.")}let h5Tk=cookieMap.get("_m_h5_tk");if(h5Tk)return h5Tk.split("_")[0]||"";throw new Error("Missing _m_h5_tk cookie. Please ensure the user is logged in.")}function computeMtopSign(params){let{api,version:version2,timestamp,appKey,token,dataStr,isMopen}=params;return md5(isMopen?`${api}&${version2}&${timestamp}&${appKey}&${token}&${md5(dataStr)}`:`${token}&${timestamp}&${appKey}&${dataStr}`)}var MTOP_HOST_MAP={online:"h5api.m.taobao.com",pre:"h5api.wapa.taobao.com"};function buildCookieHeaderValue(cookieMap){return[...cookieMap.entries()].map(([k,v])=>`${k}=${v}`).join("; ")}function parseSseDataValue(value){try{return JSON.parse(value)}catch{return value}}function createSseEventParser(){let buffer="",eventName="",lastEventId,dataLines=[],hasData=!1,dispatch=()=>{if(!hasData)return eventName="",dataLines=[],[];let rawData=dataLines.join(`
|
|
464
464
|
`);if(eventName=eventName||"message",dataLines=[],hasData=!1,rawData==="[DONE]")return eventName="",[];let event={event:eventName,data:parseSseDataValue(rawData),...lastEventId!==void 0?{eventId:lastEventId}:{}};return eventName="",[event]},consumeLine=line=>{if(line==="")return dispatch();if(line.startsWith(":"))return[];let separator=line.indexOf(":"),field=separator===-1?line:line.slice(0,separator),value=separator===-1?"":line.slice(separator+1);return value.startsWith(" ")&&(value=value.slice(1)),field==="data"?(dataLines.push(value),hasData=!0):field==="event"?eventName=value:field==="id"&&!value.includes("\0")&&(lastEventId=value),[]},drain=final=>{let events=[];for(;buffer.length>0;){let newlineIndex=-1;for(let index=0;index<buffer.length;index++)if(buffer[index]===`
|
|
465
465
|
`||buffer[index]==="\r"){newlineIndex=index;break}if(newlineIndex===-1){final&&(events.push(...consumeLine(buffer)),buffer="");break}if(buffer[newlineIndex]==="\r"&&newlineIndex===buffer.length-1&&!final)break;let line=buffer.slice(0,newlineIndex),separatorLength=buffer[newlineIndex]==="\r"&&buffer[newlineIndex+1]===`
|
|
@@ -1016,7 +1016,7 @@ ${SOURCE_BADGES[source]}
|
|
|
1016
1016
|
window.__mtopRecording = false;
|
|
1017
1017
|
return { endUrl: endUrl };
|
|
1018
1018
|
})()
|
|
1019
|
-
`,RECORDING_BINDING_NAME="__mtopRecordReport",cdpRecordingSessions=new Map,RECORDING_MAX_REQUESTS=500,RECORDING_MAX_ACTIONS=1e3;async function cdpRecordStart(session,_data){if(cdpRecordingSessions.has(session.targetId))throw new Error(`Already recording on target ${session.targetId}. Call record_stop before starting a new recording.`);let pageClient=(await resolveCdpDeviceShellPageEndpoint(session)).client,recordingSession={targetId:session.targetId,startTime:Date.now(),startUrl:"",actions:[],client:pageClient};try{await pageClient.sendCommand("Runtime.addBinding",{name:RECORDING_BINDING_NAME})}catch(err){throw new Error(`Failed to register recording binding: ${err?.message??err}. CDP target may not support Runtime domain.`,{cause:err})}let nextSeq=1,onBindingCalled=params=>{if(params?.name===RECORDING_BINDING_NAME)try{let action=JSON.parse(params.payload);action.seq=nextSeq++,recordingSession.actions.push(action),recordingSession.actions.length>RECORDING_MAX_ACTIONS&&recordingSession.actions.splice(0,recordingSession.actions.length-RECORDING_MAX_ACTIONS)}catch{}};recordingSession.removeBindingListener=pageClient.on("Runtime.bindingCalled",onBindingCalled);try{let result=await pageClient.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source:RECORDING_INJECTED_SCRIPT});recordingSession.scriptIdentifier=result?.identifier}catch(err){throw recordingSession.removeBindingListener?.(),new Error(`Failed to register recording script: ${err?.message??err}.`,{cause:err})}try{let value=(await sendCdpDeviceShellPageCommand(session,"Runtime.evaluate",{expression:RECORDING_BOOTSTRAP_SCRIPT,returnByValue:!0})).result?.value??{};recordingSession.startUrl=value.startUrl??""}catch{recordingSession.startUrl=""}return cdpRecordingSessions.set(session.targetId,recordingSession),{recording:!0,tabId:session.targetId,startTime:recordingSession.startTime}}async function cdpRecordStop(session,_data){let recordingSession=cdpRecordingSessions.get(session.targetId);if(!recordingSession)return{wasRecording:!1,actions:[],requests:[],requestsTruncated:!1,duration:0,startUrl:"",endUrl:""};if(cdpRecordingSessions.delete(session.targetId),recordingSession.removeBindingListener?.(),recordingSession.scriptIdentifier)try{await recordingSession.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier:recordingSession.scriptIdentifier})}catch{}let endUrl="";try{endUrl=(await sendCdpDeviceShellPageCommand(session,"Runtime.evaluate",{expression:RECORDING_TEARDOWN_SCRIPT,returnByValue:!0})).result?.value?.endUrl??""}catch{}try{await recordingSession.client.sendCommand("Runtime.removeBinding",{name:RECORDING_BINDING_NAME})}catch{}let endTime=Date.now(),startTime=recordingSession.startTime,duration3=Math.round((endTime-startTime)/1e3),allRequests=session.buffers.requests.filter(r=>r.timestampMs>=startTime),requests=allRequests.length>RECORDING_MAX_REQUESTS?allRequests.slice(-RECORDING_MAX_REQUESTS):allRequests;return{wasRecording:!0,actions:annotateActionsWithRequests(recordingSession.actions,requests,endTime),requests:serializeRecordingRequests(requests),requestsTruncated:allRequests.length>RECORDING_MAX_REQUESTS,duration:duration3,startUrl:recordingSession.startUrl,endUrl}}async function releaseCdpRecordings(sessions){await Promise.allSettled(sessions.filter(session=>cdpRecordingSessions.has(session.targetId)).map(session=>cdpRecordStop(session,{})));for(let recordingSession of cdpRecordingSessions.values())recordingSession.removeBindingListener?.();cdpRecordingSessions.clear()}registerActions([{name:"record_start",session:"page",handler:cdpRecordStart},{name:"record_stop",session:"page",handler:cdpRecordStop}]);var WINDVANE="WindVane/8.7.0",WV_BRIDGE={global:"WindVane",style:"windvane"},MEGA_BRIDGE={global:"__megability_bridge__",style:"mega"},WV_NATIVE_BACK={event:"wvBackClickEvent",controlFunction:"_windvane_backControl"},FLIGGY_NATIVE_BACK={event:"WV.Back"},ALIPAY_NATIVE_BACK={event:"back"},FLIGGY_OVERLAY={enabledParam:"_fli_overlay",topRatioParam:"_fli_overlay_ratio",radiusParam:"_fli_overlay_radius",maskAlphaParam:"_fli_overlay_mask_alpha",tapCloseParam:"_fli_overlay_tap_close",tapCloseSelectors:["#qwen-titlebar .qwen-titlebar-icon-wrapper:last-child"],silentTapClose:!0,defaultTopRatio:.2,defaultRadius:0,defaultMaskAlpha:.3,defaultTapClose:!0},TAOBAO_OVERLAY={enabledParam:"useWebdialog",topRatioParam:"topRatio",heightRatioParam:"height_pct",radiusParam:"cornerRadius",maskAlphaParam:"maskAlpha",tapCloseParam:"tapEnable",tapCloseSelectors:["#qwen-titlebar .qwen-titlebar-icon-wrapper:last-child"],defaultTopRatio:.2,defaultRadius:6,defaultMaskAlpha:.5,defaultTapClose:!0},FLIGGY_IMAGE_PICKER={schemes:["page://ask_take_photo"],api:"mtop.trip.serverless.api.gateway",version:"2.0",fcId:"240417431173407785",fcGroup:"fl-images",uploadUrlFunction:"uploadByTokenUrl",prefix:"temp",region:"CN"},FLIGGY_LAYER_URL_PROXY={sourceHostPrefix:"edith.",pathPrefix:"/proxy/",targetHostSuffixes:["wapa.taobao.com"],defaultTargetHost:"market.wapa.taobao.com"},FLIGGY_ROOT_CONTAINER={statusBarHeightCookie:{name:"_fli_barHeight",domain:"taobao.com",path:"/"}},FLIGGY_TITLE_BAR_HIDDEN_PATHNAMES=["/app/trip/rx-home/pages/home","/app/trip/rx-trip-ai/pages/home"],FLIGGY_STATUS_BAR_BACKGROUND_COLORS={"/app/trip/rx-home/pages/home":"#fff","/app/trip/rx-trip-ai/pages/home":"#dbdbff"};function emptyActions(){return{open:[],close:[],title:[],navigationBar:[],statusBar:[],systemInfo:[],mtop:[],kvGet:[],kvSet:[],kvDelete:[],pageContext:[],responses:{},behaviors:{},noop:[],silent:[]}}function mergeActions(...maps){let out=emptyActions();for(let m of maps)out.open.push(...m.open),out.close.push(...m.close),out.title.push(...m.title),out.navigationBar.push(...m.navigationBar??[]),out.statusBar.push(...m.statusBar??[]),out.systemInfo.push(...m.systemInfo),out.mtop.push(...m.mtop),out.kvGet.push(...m.kvGet??[]),out.kvSet.push(...m.kvSet??[]),out.kvDelete.push(...m.kvDelete??[]),out.pageContext.push(...m.pageContext??[]),Object.assign(out.responses,m.responses??{}),Object.assign(out.behaviors,m.behaviors??{}),out.noop.push(...m.noop),out.silent.push(...m.silent??[]);return out}var APP_BRIDGE_BEHAVIORS=["navigate","closeAll","closeBackData","postMessage","notifySubscribe","notifyUnsubscribe","notifyPost","sharedFileRead","sharedFileWrite","sharedDataGet","sharedDataSet","legacyBroadcastCreate","legacyBroadcastPost","legacyBroadcastClose","memoryGet","memorySet","memoryDelete","availabilityMap","userInfo","networkInfo","geolocation","permission","prefetch","fptTrack","mtopStream","previewFile","toast","unsupportedNativeInput","payment","userTrack","calendar","networkQualityMonitor","beaconRequest"],APP_BRIDGE_BEHAVIOR_SET=new Set(APP_BRIDGE_BEHAVIORS),BRIDGE_ACTION_ARRAY_KEYS=["open","close","title","navigationBar","statusBar","systemInfo","mtop","kvGet","kvSet","kvDelete","pageContext","noop"];function isJsonValue(value,seen=new Set){if(value===null||typeof value=="string"||typeof value=="boolean")return!0;if(typeof value=="number")return Number.isFinite(value);if(typeof value!="object"||seen.has(value))return!1;seen.add(value);let valid=Array.isArray(value)?value.every(item=>isJsonValue(item,seen)):Object.values(value).every(item=>isJsonValue(item,seen));return seen.delete(value),valid}function validateAppBridgeConfig(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("bridgeConfig must be an object");let root=value;if(Object.keys(root).some(key=>key!=="methods"))throw new Error('bridgeConfig only supports the "methods" field');if(!root.methods||typeof root.methods!="object"||Array.isArray(root.methods))throw new Error("bridgeConfig.methods must be an object");let entries=Object.entries(root.methods);if(entries.length>200)throw new Error("bridgeConfig supports at most 200 methods");let methods2={};for(let[method,rawConfig]of entries){if(!method.trim()||method.length>200)throw new Error("bridgeConfig method names must contain 1-200 characters");if(method==="__proto__"||method==="prototype"||method==="constructor")throw new Error(`bridgeConfig method name "${method}" is reserved`);if(!rawConfig||typeof rawConfig!="object"||Array.isArray(rawConfig))throw new Error(`bridgeConfig.methods.${method} must be an object`);let methodConfig=rawConfig,supportedKeys=new Set(["behavior","response","noop","silent"]);if(Object.keys(methodConfig).some(key=>!supportedKeys.has(key)))throw new Error(`bridgeConfig.methods.${method} contains an unsupported field`);if("behavior"in methodConfig&&typeof methodConfig.behavior!="string")throw new Error(`bridgeConfig.methods.${method}.behavior must be a string`);let hasBehavior=typeof methodConfig.behavior=="string",hasResponse=Object.prototype.hasOwnProperty.call(methodConfig,"response"),hasNoop=methodConfig.noop===!0;if(Number(hasBehavior)+Number(hasResponse)+Number(hasNoop)!==1)throw new Error(`bridgeConfig.methods.${method} must define exactly one of behavior, response, or noop=true`);if(hasBehavior&&!APP_BRIDGE_BEHAVIOR_SET.has(methodConfig.behavior))throw new Error(`bridgeConfig.methods.${method} has an unsupported behavior`);if(hasResponse&&!isJsonValue(methodConfig.response))throw new Error(`bridgeConfig.methods.${method}.response must be valid JSON data`);if("noop"in methodConfig&&methodConfig.noop!==!0)throw new Error(`bridgeConfig.methods.${method}.noop must be true when provided`);if("silent"in methodConfig&&typeof methodConfig.silent!="boolean")throw new Error(`bridgeConfig.methods.${method}.silent must be a boolean`);methods2[method]={...hasBehavior&&{behavior:methodConfig.behavior},...hasResponse&&{response:JSON.parse(JSON.stringify(methodConfig.response))},...hasNoop&&{noop:!0},...methodConfig.silent===!0&&{silent:!0}}}let normalized={methods:methods2};if(JSON.stringify(normalized).length>65536)throw new Error("bridgeConfig must not exceed 64 KiB");return normalized}function applyAppBridgeConfig(actions,config2){let out=mergeActions(actions);if(!config2)return out;let{methods:methods2}=validateAppBridgeConfig(config2);for(let[method,methodConfig]of Object.entries(methods2)){for(let key of BRIDGE_ACTION_ARRAY_KEYS){let values=out[key];values&&(out[key]=values.filter(value=>value!==method))}out.silent=(out.silent??[]).filter(value=>value!==method),delete out.responses?.[method],delete out.behaviors?.[method],methodConfig.behavior?out.behaviors[method]=methodConfig.behavior:Object.prototype.hasOwnProperty.call(methodConfig,"response")?out.responses[method]=methodConfig.response:methodConfig.noop&&out.noop.push(method),methodConfig.silent&&out.silent.push(method)}return out}var WV_ACTIONS={open:["WVNative.openWindow","Base.openBrowser","EtaoJsbridgeUtil.openWindow","TMBridge.pushWindow","Third.openThirdWeb"],close:["WebAppInterface.pop","Triver.pop","TMBridge.popWindow","EleWVHybridAPI.popWindow","Third.closeWebView"],title:["WebAppInterface.setCustomPageTitle"],navigationBar:["Triver.setNavigationBarStyle"],statusBar:["WebAppInterface.setStatusBarStyle","Application.setStatusBarStyle"],systemInfo:[],mtop:["MtopWVPlugin.send"],behaviors:{"WVNetwork.getNetworkType":"networkInfo","WVFile.read":"sharedFileRead","WVFile.write":"sharedFileWrite","SharedData.getSharedData":"sharedDataGet","SharedData.setSharedData":"sharedDataSet","WVBroadcast.createChannel":"legacyBroadcastCreate","WVBroadcast.postMessage":"legacyBroadcastPost","WVBroadcast.close":"legacyBroadcastClose"},noop:["WVNative.enableHookNativeBack","WVNative.forbidPanGesture","WVNative.setGestureBack","WVTBUserTrack.toUT","WVTBUserTrack.toUT2"],silent:["WVNetwork.getNetworkType","WVTBUserTrack.toUT","WVTBUserTrack.toUT2"]},COMMON_SCHEME_RULES=[{match:"page:",param:"params"},{match:"taobaotravel:",param:"params"},{match:"alipays://platformapi/starth5app",param:"url"},{match:"alipays://platformapi/startapp",param:"page"},{match:"eleme://web",param:"url"},{match:"amapuri://webview/",param:"url"}],FEIZHU_WECHAT_HOST_SUFFIXES=["feizhu.com"],WECHAT_SCHEME_RULES=[{match:"/pages/main/webview",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES,param:"url",useCurrentOrigin:!0},...COMMON_SCHEME_RULES],WECHAT_MINI_PROGRAM={paymentRoutes:[{pathname:"/pages/utils/common-pay/index",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES,paymentParamsParam:"signStr",successUrlParams:["backUrl","successUrl"],failureUrlParams:["unSuccessUrl","errorUrl"],successResultParam:"__paymentRes",forwardParams:["ttid"],useCurrentOrigin:!0}],nativeRoutes:[{pathname:"/pages/utils/webview-bridge/index",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES,actions:["navigateMiniProgram","subscribeMessage"]}],messageRules:[{type:"BACK_DATA",action:"stageBackData",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES},{type:"BACK_MINI_APP",action:"closeAll",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES}]},WECHAT_TITLE_BAR_HOST_STYLES=[{hostSuffix:"feizhu.com",titleBarBackgroundColor:"#ffe033",statusBarBackgroundColor:"#ffe033"}],FLIGGY_SCHEME_RULES=[{match:"fliggy://order/detail",targetPath:"/app/trip/rx-flight-detail/pages/index",targetHostPrefix:"market",targetParams:{titleBarHidden:"2"}},...COMMON_SCHEME_RULES],WV_ACTIVE_EVENTS=["WV.Event.APP.Active"],FLIGGY_AI_UI_NOOPS=["handleLiveActivity","ai_ask_scroll_position","ai_ask_input_status","ai_ask_set_keyboard_tags","ai_ask_h5_awaken_input","ai_ask_reset_input","ai_ask_hide_input","home_ai_page_scroll","ai_ask_hide_keyboard","ai_ask_clear_keyboard_tags","ai_ask_init_mask","ai_ask_hide_mask","ai_ask_transfer_to_wenwen","ai_ask_transfer_to_mask","close_loading_view","open_loading_view","set_ai_ask_container_status","to_set_notifaction","home_refresh","ai_ask_page_load_success","ai_ask_set_session_info","ai_ask_input_set_mention_url","ai_ask_input_set_scene","ai_float_brain_panel_back_to_top_panel_page","ai_float_brain_panel_set_tools"],APP_PROFILES={fliggy:{name:"fliggy",label:"飞猪",appName:"LX",defaultAppVersion:"10.0.0",uaTokens:["AliTrip/{v}",WINDVANE],globals:{},bridges:[WV_BRIDGE,{global:"alitripBridge",style:"fliggy"},{global:"core",style:"fliggy"},{global:"methodChannel",style:"callback"}],activeEvents:WV_ACTIVE_EVENTS,actions:mergeActions(WV_ACTIONS,{...emptyActions(),open:["goto","ai_float_brain_panel_collapse_and_open_url"],close:[],title:["set_webview_title"],navigationBar:["set_ui"],statusBar:["set_status_bar_style"],systemInfo:["client_info","WVNativeDetector.getModelInfo"],kvGet:["get_kvcache"],kvSet:["set_kvcache"],kvDelete:["del_kvcache"],pageContext:["ai_float_brain_panel_get_page_context"],responses:{is_open_push:{is_open:!1},get_unread_message:{style:"POINT",count:0},get_v10_ab_info:{v10Version:!0},get_ai_ask_container_status:{status:"FULL"},ai_ask_get_keyboard_height:{height:0},get_idfa:{},get_caid:{},get_theme_conf:{},cppay_app_install:{result:""}},behaviors:{"page://goto":"navigate","page://close":"closeBackData",back:"closeBackData",user_info:"userInfo",ai_ask_get_memory_cache:"memoryGet",ai_ask_set_memory_cache:"memorySet",ai_ask_del_memory_cache:"memoryDelete",channelJudgeJsBridge:"availabilityMap",networktype:"networkInfo",network_quality_monitor:"networkQualityMonitor",request:"beaconRequest",store_calendar_event:"calendar",remove_calendar_event:"calendar",check_batch_calendar:"calendar",search_batch_calendar_events:"calendar",lbs:"geolocation",permission:"permission",cacheFetch:"prefetch",fptTrack:"fptTrack",toUT:"userTrack","WVTBUserTrack.toUT":"userTrack","WVTBUserTrack.toUT2":"userTrack",mtop_stream:"mtopStream",ai_ask_preview_file:"previewFile",toast:"toast",ai_ask_input_bridge:"unsupportedNativeInput",cppay:"payment",minipay:"payment",union_pay:"payment"},noop:["swipe_back","track_error_with_alarm","cacheUpdate","long_press_save_image",...FLIGGY_AI_UI_NOOPS],silent:["native://biz/mtop_normal_sign","toUT","get_idfa","get_caid","channelJudgeJsBridge","get_unread_message","get_v10_ab_info","lbs","networktype","network_quality_monitor","request","long_press_save_image","WVNativeDetector.getModelInfo","set_status_bar_style","get_theme_conf","cacheFetch","cppay_app_install","track_error_with_alarm",...FLIGGY_AI_UI_NOOPS]}),schemes:FLIGGY_SCHEME_RULES,imagePicker:FLIGGY_IMAGE_PICKER,layerUrlProxy:FLIGGY_LAYER_URL_PROXY,rootContainer:FLIGGY_ROOT_CONTAINER,titleBarHiddenPathnames:FLIGGY_TITLE_BAR_HIDDEN_PATHNAMES,statusBarBackgroundColors:FLIGGY_STATUS_BAR_BACKGROUND_COLORS,urlSyncHostSuffixes:["m.taobao.com","wapa.taobao.com"],overlay:FLIGGY_OVERLAY,popBeforeOpenParam:"_fli_popBeforeOpen",nativeBack:FLIGGY_NATIVE_BACK,forceH5Mtop:!0},taobao:{name:"taobao",label:"手机淘宝",appName:"TB",defaultAppVersion:"10.65.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE,MEGA_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,overlay:TAOBAO_OVERLAY,nativeBack:WV_NATIVE_BACK},wechat:{name:"wechat",label:"微信",appName:"WeChat",defaultAppVersion:"8.0.58",uaFamily:"wechatMiniProgram",uaTokens:[],globals:{__wxjs_environment:"miniprogram"},bridges:[{global:"wx.miniProgram",style:"wechatMiniProgram",persistent:!0}],activeEvents:[],actions:{...emptyActions(),open:["navigateTo","redirectTo","switchTab","reLaunch"],close:["navigateBack"],behaviors:{postMessage:"postMessage"}},schemes:WECHAT_SCHEME_RULES,miniProgram:WECHAT_MINI_PROGRAM,titleBarHostStyles:WECHAT_TITLE_BAR_HOST_STYLES},tmall:{name:"tmall",label:"天猫",appName:"TM",defaultAppVersion:"15.22.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},alipay:{name:"alipay",label:"支付宝",appName:"AP",defaultAppVersion:"10.8.0",uaTokens:["AlipayClient/{v}"],globals:{},bridges:[{global:"AlipayJSBridge",style:"alipay"}],activeEvents:[],actions:{open:["pushWindow","startApp"],close:["popWindow"],title:["setTitle"],navigationBar:["hideBackButton","showBackButton"],systemInfo:["getSystemInfo"],mtop:[],behaviors:{getNetworkType:"networkInfo",addNotifyListener:"notifySubscribe",removeNotifyListener:"notifyUnsubscribe",postNotification:"notifyPost"},noop:["postWebViewMessage","setGestureBack"],silent:["getNetworkType"]},schemes:COMMON_SCHEME_RULES,nativeBack:ALIPAY_NATIVE_BACK},koubei:{name:"koubei",label:"口碑",appName:"KB",defaultAppVersion:"9.5.0",uaTokens:["KoubeiClient/{v}"],globals:{},bridges:[{global:"AlipayJSBridge",style:"alipay"}],activeEvents:[],actions:{open:["pushWindow","startApp"],close:["popWindow"],title:["setTitle"],navigationBar:["hideBackButton","showBackButton"],systemInfo:["getSystemInfo"],mtop:[],behaviors:{getNetworkType:"networkInfo",addNotifyListener:"notifySubscribe",removeNotifyListener:"notifyUnsubscribe",postNotification:"notifyPost"},noop:["postWebViewMessage","setGestureBack"],silent:["getNetworkType"]},schemes:COMMON_SCHEME_RULES,nativeBack:ALIPAY_NATIVE_BACK},"taobao-tj":{name:"taobao-tj",label:"淘宝特价版",appName:"LT",defaultAppVersion:"10.32.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},"taobao-live":{name:"taobao-live",label:"淘宝直播",appName:"TAOBAOLIVEAPP",defaultAppVersion:"3.10.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},xianyu:{name:"xianyu",label:"闲鱼",appName:"FM",defaultAppVersion:"7.15.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},etao:{name:"etao",label:"一淘",appName:"ET",defaultAppVersion:"9.27.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},eleme:{name:"eleme",label:"饿了么",appName:"ELMC",defaultAppVersion:"11.12.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},damai:{name:"damai",label:"大麦",appName:"DM",defaultAppVersion:"8.9.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},btrip:{name:"btrip",label:"阿里商旅",appName:"BLX",defaultAppVersion:"9.12.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE,{global:"methodChannel",style:"btrip"}],activeEvents:WV_ACTIVE_EVENTS,actions:mergeActions(WV_ACTIONS,{...emptyActions(),open:["goto"],behaviors:{back:"closeBackData"}}),schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},amap:{name:"amap",label:"高德地图",appName:"amap",defaultAppVersion:"13.8.0",uaTokens:[],globals:{},bridges:[{global:"AmapApp.bridge",style:"amap"}],activeEvents:[],actions:{open:["loadSchema","infoH5JsAction"],close:[],title:["setWebViewTitle"],systemInfo:[],mtop:[],noop:["interceptNativeBackEvent"]},schemes:COMMON_SCHEME_RULES,nativeBack:{handler:"onNativeBackEvent"}},qianwen:{name:"qianwen",label:"千问",appName:"TONGYI",defaultAppVersion:"3.20.0",uaTokens:[],globals:{},bridges:[{global:"ucapi",style:"invoke"}],activeEvents:[],actions:{open:["biz.openPageUrl","webdialog.show"],close:["biz.closeWebPage","webdialog.pop"],title:[],systemInfo:[],mtop:[],behaviors:{"base.postmessage":"postMessage","biz.popToRootWindow":"closeAll","biz.popToTopChatWindow":"closeAll"},noop:[]},schemes:COMMON_SCHEME_RULES,messageEvent:"QKEVT_OnReceiveMessage"},lingyou:{name:"lingyou",label:"翎游",appName:"hongtu",defaultAppVersion:"1.5.0",uaTokens:["hongtu/{v}"],globals:{},bridges:[{global:"WKWebViewJavascriptBridge",style:"callHandler"},{global:"WebViewJavascriptBridge",style:"callHandler"}],activeEvents:[],actions:{...emptyActions(),open:["jumpPage"],close:["closePage"],title:["setPageTitle"]},schemes:COMMON_SCHEME_RULES},didi:{name:"didi",label:"滴滴出行",appName:"didi.passenger",defaultAppVersion:"6.9.0",uaTokens:["didi.passenger/{v}"],globals:{},bridges:[{global:"didiBridge",style:"didi"},{global:"Fusion",style:"didi"}],activeEvents:[],actions:{...emptyActions(),open:["openPage"],close:["closePage"]},schemes:COMMON_SCHEME_RULES},easybike:{name:"easybike",label:"易到用车",appName:"easybike",defaultAppVersion:"9.0.0",uaTokens:["app=easybike;"],globals:{},bridges:[{global:"webkit.messageHandlers.callNative",style:"easybikeNative"},{global:"AppFunctions",style:"easybikeNative"}],activeEvents:[],actions:mergeActions(WV_ACTIONS,{...emptyActions(),close:["business/hitch.closeWebView"]}),schemes:COMMON_SCHEME_RULES}};function buildAppProfileUa(profile,options={}){let os12=options.os??(options.devicePreset?DEVICE_PRESETS[options.devicePreset]?.appProfileOs:void 0)??"ios",version2=options.appVersion??profile.defaultAppVersion,deviceModel=options.deviceModel??(options.devicePreset?DEVICE_PRESETS[options.devicePreset]?.appProfileModel:void 0)??"Pixel 11";if(profile.uaFamily==="wechatMiniProgram")return os12==="android"?`Mozilla/5.0 (Linux; Android 17; ${deviceModel}; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/152.0.0.0 Mobile MicroMessenger/${version2} WeChat/arm64 NetType/WIFI Language/zh_CN miniProgram`:`Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/${version2} NetType/WIFI Language/zh_CN miniProgram`;let tokens=profile.uaTokens.map(t=>t.replaceAll("{v}",version2)).filter(Boolean),tail=tokens.length>0?` ${tokens.join(" ")}`:"";return os12==="android"?`Mozilla/5.0 (Linux; Android 17; ${deviceModel}) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/152.0.0.0 Mobile Safari/537.36 AliApp(${profile.appName}/${version2})${tail}`:`Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) AliApp(${profile.appName}/${version2})${tail}`}function resolveAppProfile(name,options={}){let profile=APP_PROFILES[name];if(!profile)throw new Error(`Unknown app profile "${name}". Available: ${Object.keys(APP_PROFILES).join(", ")}`);let os12=options.os??(options.devicePreset?DEVICE_PRESETS[options.devicePreset]?.appProfileOs:void 0)??"ios",version2=options.appVersion??profile.defaultAppVersion,recommendedPreset=os12==="android"?"pixel-11":"iphone-17-pro",devicePreset=options.devicePreset??recommendedPreset,emulation=resolveEmulationConfig({enabled:!0,preset:devicePreset,orientation:options.orientation}),deviceModel=options.deviceModel??DEVICE_PRESETS[devicePreset].appProfileModel,globals={...profile.globals,__APP_NAME__:profile.appName,__APP_VERSION__:version2,__FLI_DEVICE_MODEL__:deviceModel,__DEVICE_MODEL__:deviceModel},ua=buildAppProfileUa(profile,{...options,os:os12,deviceModel});return{profile:profile.name,label:profile.label,ua,injected:{profile:profile.name,label:profile.label,globals,bridges:profile.bridges,activeEvents:profile.activeEvents,maxTouchPoints:5,statusBarHeight:emulation.safeAreaInsets.top,safeAreaInsets:emulation.safeAreaInsets,deviceAppearance:{preset:devicePreset,orientation:emulation.orientation,cutout:emulation.appearance.cutout},language:"zh-Hans",userAgent:ua,navigatorPlatform:os12==="android"?"Linux armv8l":"iPhone",platform:os12==="android"?"Android":"iOS",systemVersion:os12==="android"?"17":"26.0",clientType:os12==="android"?"android":"iphone",actions:applyAppBridgeConfig(profile.actions,options.bridgeConfig),schemes:profile.schemes,...profile.miniProgram&&{miniProgram:profile.miniProgram},...profile.imagePicker&&{imagePicker:profile.imagePicker},...profile.overlay&&{overlay:profile.overlay},...profile.popBeforeOpenParam&&{popBeforeOpenParam:profile.popBeforeOpenParam},...profile.messageEvent&&{messageEvent:profile.messageEvent},...profile.nativeBack&&{nativeBack:profile.nativeBack},...profile.layerUrlProxy&&{layerUrlProxy:profile.layerUrlProxy},...profile.urlSyncHostSuffixes&&{urlSyncHostSuffixes:profile.urlSyncHostSuffixes},...profile.forceH5Mtop&&{forceH5Mtop:!0},simulateSystemBars:!1,rootContainer:{enabled:!1,...profile.rootContainer?.statusBarHeightCookie&&{initialCookies:[{...profile.rootContainer.statusBarHeightCookie,value:String(emulation.safeAreaInsets.top)}]}},titleBar:{navigationBarHeight:os12==="android"?48:44,backgroundColor:"#ffffff",textColor:"#0f131a",...profile.titleBarHiddenPathnames&&{hiddenPathnames:profile.titleBarHiddenPathnames},...profile.statusBarBackgroundColors&&{statusBarBackgroundColors:profile.statusBarBackgroundColors},...profile.titleBarHostStyles&&{hostStyles:profile.titleBarHostStyles}}},recommendedPreset}}function installAppProfileEnvironment(config2){let w=window;if(w.__mearlAppProfile__)return null;w.__mearlAppProfile__=config2.profile;let SRC="mearl-app-bridge",TAG=`[AppBridge:${config2.label}]`,ROOT_FRAME_NAME="__mearl_root__",LAYER_FRAME_NAME="__mearl_layer__",isTop=window===window.top,isRootFrame=!isTop&&window.name===ROOT_FRAME_NAME,isLayerFrame=!isTop&&window.name===LAYER_FRAME_NAME,isContainerFrame=isTop||isRootFrame||isLayerFrame,usesRootContainer=isTop&&config2.rootContainer?.enabled===!0,simulateSystemBars=config2.simulateSystemBars!==!1,safeAreaInsets=config2.safeAreaInsets??{top:config2.statusBarHeight,right:0,bottom:0,left:0},log3=(...args)=>console.info(TAG,...args);for(let[key,value]of Object.entries(config2.globals))try{w[key]=value}catch{}typeof w.__STATUS_BAR_HEIGHT__!="number"&&(w.__STATUS_BAR_HEIGHT__=config2.statusBarHeight),typeof w.__SAFE_AREA_INSET_BOTTOM__!="number"&&(w.__SAFE_AREA_INSET_BOTTOM__=safeAreaInsets.bottom);let applySafeAreaCssVariables=()=>{let root=document.documentElement;if(!root)return!1;try{return root.style.setProperty("--safe-area-inset-top",`${safeAreaInsets.top}px`),root.style.setProperty("--safe-area-inset-right",`${safeAreaInsets.right}px`),root.style.setProperty("--safe-area-inset-bottom",`${safeAreaInsets.bottom}px`),root.style.setProperty("--safe-area-inset-left",`${safeAreaInsets.left}px`),!0}catch{return!1}};if(!applySafeAreaCssVariables()){let observer=new MutationObserver(()=>{applySafeAreaCssVariables()&&observer.disconnect()});observer.observe(document,{childList:!0})}if(config2.forceH5Mtop){let downstreamMtopParamsHandler=w.MTOP_PARAMS_HANDLER,forceH5Mtop=params=>{let resolved=params;if(typeof downstreamMtopParamsHandler=="function")try{resolved=downstreamMtopParamsHandler.call(window,params)??params}catch{resolved=params}return{...resolved&&typeof resolved=="object"?resolved:{},useNative:!1}};try{Object.defineProperty(w,"MTOP_PARAMS_HANDLER",{configurable:!0,get:()=>forceH5Mtop,set:handler=>{handler!==forceH5Mtop&&(downstreamMtopParamsHandler=handler)}})}catch{w.MTOP_PARAMS_HANDLER=forceH5Mtop}}for(let[key,value]of[["userAgent",config2.userAgent],["platform",config2.navigatorPlatform],["vendor","Apple Computer, Inc."],["appVersion",config2.userAgent.replace(/^Mozilla\//,"")]])try{Object.defineProperty(navigator,key,{get:()=>value,configurable:!0})}catch{}try{Object.defineProperty(navigator,"maxTouchPoints",{get:()=>config2.maxTouchPoints})}catch{}return{w,SRC,TAG,ROOT_FRAME_NAME,LAYER_FRAME_NAME,isTop,isRootFrame,isLayerFrame,isContainerFrame,usesRootContainer,simulateSystemBars,safeAreaInsets,log:log3}}function installAppProfileSystemBars(config2,environment,host){let{SRC,isTop,isContainerFrame,simulateSystemBars,safeAreaInsets}=environment,externalDeviceChrome=config2.externalDeviceChrome===!0,titleBarMode="auto",titleBarRoot=null,titleBarSpacer=null,systemStatusView=null,systemBottomRoot=null,systemBottomSurface=null,rootTitleBarView=null,titleBarTitleVisible=!0,titleBarBackVisible=!0,titleBarBackground=config2.titleBar?.backgroundColor??"#ffffff",titleBarTextColor=config2.titleBar?.textColor??"#111111",titleBarStateExplicit=!1,presentedRootTitleBarState=null,normalizeProxyPathPrefix=prefix=>{let withLeadingSlash=prefix.startsWith("/")?prefix:`/${prefix}`;return withLeadingSlash.endsWith("/")?withLeadingSlash:`${withLeadingSlash}/`},matchesProxyTarget=(hostname3,suffixes)=>suffixes.some(suffix=>hostname3===suffix||hostname3.endsWith(`.${suffix}`)),normalizePathname=pathname=>{let withLeadingSlash=pathname.startsWith("/")?pathname:`/${pathname}`;return withLeadingSlash.length>1&&withLeadingSlash.endsWith("/")?withLeadingSlash.slice(0,-1):withLeadingSlash},businessPathname=href=>{try{let current=new URL(href,location.href),proxy=config2.layerUrlProxy;if(!proxy)return normalizePathname(current.pathname);let prefix=normalizeProxyPathPrefix(proxy.pathPrefix);if(!current.pathname.startsWith(prefix))return normalizePathname(current.pathname);let rest=current.pathname.slice(prefix.length),slash=rest.indexOf("/"),hostName=slash===-1?rest:rest.slice(0,slash),pathname=slash===-1?"/":rest.slice(slash),hostname3=new URL(`${current.protocol}//${hostName}`).hostname;return matchesProxyTarget(hostname3,proxy.targetHostSuffixes)?normalizePathname(pathname):normalizePathname(current.pathname)}catch{return null}},matchesConfiguredPathname=(href,pathnames)=>{let pathname=businessPathname(href);return pathname!==null&&pathnames.some(configuredPathname=>normalizePathname(configuredPathname)===pathname)},configuredHostStyle=(href=location.href)=>{try{let hostname3=new URL(href,location.href).hostname.toLowerCase();return(config2.titleBar?.hostStyles??[]).find(rule=>{let suffix=rule.hostSuffix.trim().replace(/^\.+/,"").toLowerCase();return suffix!==""&&(hostname3===suffix||hostname3.endsWith(`.${suffix}`))})}catch{return}},configuredTitleBarBackground=(href,fallback)=>configuredHostStyle(href)?.titleBarBackgroundColor??fallback,supportsWindVaneNavigationMeta=config2.bridges.some(bridge=>bridge.style==="windvane"),isTruthyParam=value=>value==="1"||value?.toLowerCase()==="true"||value?.toUpperCase()==="YES",isTransparentColor=value=>{let normalized=value.replace(/\s/g,"").toLowerCase();return normalized==="transparent"||normalized==="#0000"||normalized==="#00000000"||normalized==="rgba(0,0,0,0)"},fixedContainerTitleBarMode=()=>config2.profile==="wechat"?"normal":null,pageRequestedTitleBarMode=(href=location.href,includeMeta=!0)=>{try{let params=new URL(href,location.href).searchParams,webviewOptions=new URLSearchParams(params.get("__webview_options__")??""),option=key=>params.get(key)??webviewOptions.get(key);if(config2.profile==="fliggy"||config2.profile==="taobao"){let hidden=option("titleBarHidden");if(hidden==="1")return"status-inset";if(hidden==="2")return"status"}if(config2.profile==="taobao"&&option("disableNav")?.toUpperCase()==="YES")return isTruthyParam(option("status_bar_transparent"))?"status":"status-inset";if(config2.profile==="alipay"||config2.profile==="koubei"){if(option("showTitleBar")?.toUpperCase()==="NO")return"status-inset";let transparentTitle=option("transparentTitle")?.toLowerCase();if(transparentTitle&&["always","auto","custom"].includes(transparentTitle))return"overlay"}let overlayParam=config2.overlay?.enabledParam;return overlayParam&&isTruthyParam(params.get(overlayParam))?"status":!includeMeta||!supportsWindVaneNavigationMeta?null:document.getElementById("WV.Meta.Nav.HideNavBar")?.getAttribute("value")==="HideStatusBar"?"status":null}catch{return null}},pageRequestsHiddenTitleBar=(href=location.href)=>matchesConfiguredPathname(href,config2.titleBar?.hiddenPathnames??[]),configuredStatusBarBackground=(href=location.href)=>{let colors=config2.titleBar?.statusBarBackgroundColors??{},pathname=businessPathname(href);return pathname===null?null:Object.entries(colors).find(([configuredPathname])=>normalizePathname(configuredPathname)===pathname)?.[1]??configuredHostStyle(href)?.statusBarBackgroundColor??null},pageRequestsHiddenStatusBar=(href=location.href)=>{try{let params=new URL(href,location.href).searchParams;return isTruthyParam(params.get("statusBarHidden"))||isTruthyParam(params.get("hideStatusBar"))?!0:/(?:^|&)showStatusBar=NO(?:&|$)/i.test(params.get("__webview_options__")??"")}catch{return!1}},resolveTitleBarMode=(href,fallback,includeMeta)=>{let fixedMode=fixedContainerTitleBarMode();if(fixedMode)return fixedMode;if(titleBarMode!=="auto")return titleBarMode;if(pageRequestsHiddenStatusBar(href))return"hidden";if(pageRequestsHiddenTitleBar(href))return"status-inset";let requestedMode=pageRequestedTitleBarMode(href,includeMeta);return requestedMode||fallback},resolveStatusBarBackground=(href,mode,navigationBarBackground)=>configuredStatusBarBackground(href)??(mode==="normal"||mode==="status-inset"?navigationBarBackground:"transparent"),ownTitleBarState=()=>{let mode=resolveTitleBarMode(location.href,"normal",!0),background=configuredTitleBarBackground(location.href,titleBarBackground);return{mode,title:document.title||config2.label,titleVisible:titleBarTitleVisible,backVisible:titleBarBackVisible,background,statusBarBackground:resolveStatusBarBackground(location.href,mode,background),textColor:titleBarTextColor}},initialLayerTitleBarState=url2=>{let mode=fixedContainerTitleBarMode()??(pageRequestsHiddenStatusBar(url2)?"hidden":pageRequestsHiddenTitleBar(url2)?"status-inset":pageRequestedTitleBarMode(url2,!1)??"normal"),background=configuredTitleBarBackground(url2,config2.titleBar?.backgroundColor??"#ffffff");return{mode,title:config2.label,titleVisible:!0,backVisible:!0,background,statusBarBackground:mode==="status-inset"?background:resolveStatusBarBackground(url2,mode,background),textColor:config2.titleBar?.textColor??"#111111"}},parseReportedTitleBarState=value=>{if(!value||typeof value!="object")return null;let state=value;return!["normal","overlay","status","status-inset","hidden"].includes(String(state.mode))||typeof state.title!="string"||typeof state.titleVisible!="boolean"||typeof state.backVisible!="boolean"||typeof state.background!="string"||typeof state.textColor!="string"?null:{...state,statusBarBackground:typeof state.statusBarBackground=="string"?state.statusBarBackground:state.mode==="normal"||state.mode==="status-inset"?String(state.background):"transparent"}},resolvedTitleBarState=layer=>layer?layer.titleBarState??initialLayerTitleBarState(layer.url):presentedRootTitleBarState??ownTitleBarState(),resolvedRootTitleBarState=(fallback=ownTitleBarState())=>presentedRootTitleBarState??(host.getRootFrame()?{...fallback,statusBarBackground:configuredHostStyle(location.href)?.statusBarBackgroundColor??config2.titleBar?.backgroundColor??"#ffffff"}:fallback),renderNavigationBarView=(view,state)=>{let visible=state.mode==="normal"||state.mode==="overlay";view.root.style.display=visible?"block":"none",view.surface.style.visibility=visible?"visible":"hidden",view.surface.style.background=state.mode==="overlay"?"transparent":state.background,view.surface.style.borderBottom="none",view.surface.style.color=state.textColor,view.title.textContent=state.title,view.title.style.display=state.titleVisible?"block":"none",view.back.style.display=state.backVisible?"flex":"none",view.back.style.color=state.textColor},topFullLayer=()=>{let layers=host.getLayers();for(let index=layers.length-1;index>=0;index-=1)if(!layers[index].overlay&&!layers[index].closing)return layers[index]},activeTitleBarState=()=>{let layer=topFullLayer();return layer?resolvedTitleBarState(layer):resolvedRootTitleBarState()},syncActiveSystemBars=()=>{let state=activeTitleBarState();if(externalDeviceChrome&&isTop&&window.postMessage({source:"mearl-app-profile-runtime",type:"device-chrome-state",state:{statusBarBackground:state.statusBarBackground,textColor:state.textColor,bridgeConfig:{profile:config2.profile,actions:config2.actions}}},"*"),systemStatusView){let visible=state.mode!=="hidden";systemStatusView.root.style.display=visible?"block":"none",systemStatusView.surface.style.visibility=visible?"visible":"hidden",systemStatusView.surface.style.background=state.statusBarBackground,systemStatusView.surface.style.color=state.textColor}systemBottomRoot&&systemBottomSurface&&(systemBottomRoot.style.display=safeAreaInsets.bottom>0?"block":"none",systemBottomSurface.style.color=state.textColor)},syncLayerViewport=(layer,state)=>{if(layer.overlay)return;if(!simulateSystemBars){layer.frame.style.top="0px",layer.frame.style.height="100%";return}let totalHeight=config2.statusBarHeight+(config2.titleBar?.navigationBarHeight??0),offset=state.mode==="normal"?totalHeight:state.mode==="status-inset"?config2.statusBarHeight:0;layer.frame.style.top=`${offset}px`,layer.frame.style.height=offset>0?`calc(100% - ${offset}px)`:"100%",layer.frame.setAttribute("data-mearl-app-viewport-mode",state.mode),layer.frame.style.setProperty("--mearl-app-navigation-bar-height",`${config2.titleBar?.navigationBarHeight??0}px`),layer.frame.style.opacity=state.mode==="status-inset"&&!layer.titleBarStateReady?"0":"1",layer.titleBarView&&renderNavigationBarView(layer.titleBarView,state),topFullLayer()===layer&&syncActiveSystemBars()},syncRootFrameViewport=state=>{let rootFrame=host.getRootFrame();if(!rootFrame)return;if(!simulateSystemBars){rootFrame.style.top="0px",rootFrame.style.height="100%";return}let totalHeight=config2.statusBarHeight+(config2.titleBar?.navigationBarHeight??0),offset=state.mode==="normal"?totalHeight:state.mode==="status-inset"?config2.statusBarHeight:0;rootFrame.style.top=`${offset}px`,rootFrame.style.height=offset>0?`calc(100% - ${offset}px)`:"100%",rootFrame.setAttribute("data-mearl-app-viewport-mode",state.mode),rootFrame.style.setProperty("--mearl-app-navigation-bar-height",`${config2.titleBar?.navigationBarHeight??0}px`),rootFrame.style.opacity=state.mode==="status-inset"&&presentedRootTitleBarState===null&&!rootFrame.hasAttribute("data-mearl-webview-ready")?"0":"1"},syncSimulatedTitleBar=()=>{let ownState=ownTitleBarState();if(!isTop){if(isContainerFrame){if(!titleBarStateExplicit&&document.readyState==="loading")return;window.top?.postMessage({source:SRC,type:"titleBarState",state:ownState,explicit:titleBarStateExplicit},"*")}return}if(!titleBarRoot||!titleBarSpacer||!rootTitleBarView)return;let rootFrame=host.getRootFrame();!rootFrame&&host.getLayers().length===0&&host.getClosingLayerCount()===0&&(presentedRootTitleBarState=ownState);let state=resolvedRootTitleBarState(ownState);renderNavigationBarView(rootTitleBarView,state);let spacerHeight=state.mode==="normal"?config2.statusBarHeight+(config2.titleBar?.navigationBarHeight??0):state.mode==="status-inset"?config2.statusBarHeight:0;titleBarSpacer.style.display=!rootFrame&&spacerHeight>0?"block":"none",titleBarSpacer.style.height=`${spacerHeight}px`,titleBarSpacer.style.minHeight=`${spacerHeight}px`,syncRootFrameViewport(state),syncActiveSystemBars()},applyNavigationBarState=(api,params)=>{titleBarStateExplicit=!0;let p=params&&typeof params=="object"?params:{},displayValue=p.titlebar_display??p.titlebarDisplay??p.titleBarDisplay,display=typeof displayValue=="string"?displayValue.toLowerCase():"";api==="hideBackButton"&&(titleBarBackVisible=!1),api==="showBackButton"&&(titleBarBackVisible=!0),display==="hide"&&(titleBarMode="status"),display==="show"&&(titleBarMode="normal"),(p.isImmersive===!0||p.isTransparent===!0)&&(titleBarMode="overlay"),p.isImmersive===!1&&p.isTransparent===!1&&(titleBarMode="normal"),typeof p.isTitleVisible=="boolean"&&(titleBarTitleVisible=p.isTitleVisible),typeof p.title=="string"&&(document.title=p.title),typeof p.backgroundColor=="string"&&(titleBarBackground=p.backgroundColor,isTransparentColor(p.backgroundColor)&&(titleBarMode="overlay")),typeof p.barTextStyle=="string"&&(titleBarTextColor=p.barTextStyle==="white"?"#ffffff":"#111111"),syncSimulatedTitleBar()},applyStatusBarState=params=>{titleBarStateExplicit=!0;let p=params&&typeof params=="object"?params:{},style=typeof p.style=="string"?p.style.toLowerCase():"";style&&(titleBarTextColor=style==="white"||style.includes("light")?"#ffffff":"#111111"),syncSimulatedTitleBar()},createNavigationBarView=(placement,onBack)=>{let titleBar=config2.titleBar,root=document.createElement("div");root.setAttribute("data-mearl-app-titlebar",config2.profile),root.setAttribute("data-mearl-titlebar-owner",placement),root.style.cssText=`${placement==="root"?"position:fixed":"position:absolute"};left:0;right:0;top:${config2.statusBarHeight}px;height:${titleBar.navigationBarHeight}px;z-index:${placement==="root"?"2147482900":"2"};overflow:hidden;box-sizing:border-box;font-family:"PingFang SC",-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;`;let shadow=root.attachShadow({mode:"open"});shadow.innerHTML=`<style>
|
|
1019
|
+
`,RECORDING_BINDING_NAME="__mtopRecordReport",cdpRecordingSessions=new Map,RECORDING_MAX_REQUESTS=500,RECORDING_MAX_ACTIONS=1e3;async function cdpRecordStart(session,_data){if(cdpRecordingSessions.has(session.targetId))throw new Error(`Already recording on target ${session.targetId}. Call record_stop before starting a new recording.`);let pageClient=(await resolveCdpDeviceShellPageEndpoint(session)).client,recordingSession={targetId:session.targetId,startTime:Date.now(),startUrl:"",actions:[],client:pageClient};try{await pageClient.sendCommand("Runtime.addBinding",{name:RECORDING_BINDING_NAME})}catch(err){throw new Error(`Failed to register recording binding: ${err?.message??err}. CDP target may not support Runtime domain.`,{cause:err})}let nextSeq=1,onBindingCalled=params=>{if(params?.name===RECORDING_BINDING_NAME)try{let action=JSON.parse(params.payload);action.seq=nextSeq++,recordingSession.actions.push(action),recordingSession.actions.length>RECORDING_MAX_ACTIONS&&recordingSession.actions.splice(0,recordingSession.actions.length-RECORDING_MAX_ACTIONS)}catch{}};recordingSession.removeBindingListener=pageClient.on("Runtime.bindingCalled",onBindingCalled);try{let result=await pageClient.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source:RECORDING_INJECTED_SCRIPT});recordingSession.scriptIdentifier=result?.identifier}catch(err){throw recordingSession.removeBindingListener?.(),new Error(`Failed to register recording script: ${err?.message??err}.`,{cause:err})}try{let value=(await sendCdpDeviceShellPageCommand(session,"Runtime.evaluate",{expression:RECORDING_BOOTSTRAP_SCRIPT,returnByValue:!0})).result?.value??{};recordingSession.startUrl=value.startUrl??""}catch{recordingSession.startUrl=""}return cdpRecordingSessions.set(session.targetId,recordingSession),{recording:!0,tabId:session.targetId,startTime:recordingSession.startTime}}async function cdpRecordStop(session,_data){let recordingSession=cdpRecordingSessions.get(session.targetId);if(!recordingSession)return{wasRecording:!1,actions:[],requests:[],requestsTruncated:!1,duration:0,startUrl:"",endUrl:""};if(cdpRecordingSessions.delete(session.targetId),recordingSession.removeBindingListener?.(),recordingSession.scriptIdentifier)try{await recordingSession.client.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier:recordingSession.scriptIdentifier})}catch{}let endUrl="";try{endUrl=(await sendCdpDeviceShellPageCommand(session,"Runtime.evaluate",{expression:RECORDING_TEARDOWN_SCRIPT,returnByValue:!0})).result?.value?.endUrl??""}catch{}try{await recordingSession.client.sendCommand("Runtime.removeBinding",{name:RECORDING_BINDING_NAME})}catch{}let endTime=Date.now(),startTime=recordingSession.startTime,duration3=Math.round((endTime-startTime)/1e3),allRequests=session.buffers.requests.filter(r=>r.timestampMs>=startTime),requests=allRequests.length>RECORDING_MAX_REQUESTS?allRequests.slice(-RECORDING_MAX_REQUESTS):allRequests;return{wasRecording:!0,actions:annotateActionsWithRequests(recordingSession.actions,requests,endTime),requests:serializeRecordingRequests(requests),requestsTruncated:allRequests.length>RECORDING_MAX_REQUESTS,duration:duration3,startUrl:recordingSession.startUrl,endUrl}}async function releaseCdpRecordings(sessions){await Promise.allSettled(sessions.filter(session=>cdpRecordingSessions.has(session.targetId)).map(session=>cdpRecordStop(session,{})));for(let recordingSession of cdpRecordingSessions.values())recordingSession.removeBindingListener?.();cdpRecordingSessions.clear()}registerActions([{name:"record_start",session:"page",handler:cdpRecordStart},{name:"record_stop",session:"page",handler:cdpRecordStop}]);var WINDVANE="WindVane/8.7.0",WV_BRIDGE={global:"WindVane",style:"windvane"},MEGA_BRIDGE={global:"__megability_bridge__",style:"mega"},WV_NATIVE_BACK={event:"wvBackClickEvent",controlFunction:"_windvane_backControl"},FLIGGY_NATIVE_BACK={event:"WV.Back"},ALIPAY_NATIVE_BACK={event:"back"},FLIGGY_OVERLAY={enabledParam:"_fli_overlay",topRatioParam:"_fli_overlay_ratio",radiusParam:"_fli_overlay_radius",maskAlphaParam:"_fli_overlay_mask_alpha",tapCloseParam:"_fli_overlay_tap_close",tapCloseSelectors:["#qwen-titlebar .qwen-titlebar-icon-wrapper:last-child"],silentTapClose:!0,defaultTopRatio:.2,defaultRadius:0,defaultMaskAlpha:.3,defaultTapClose:!0},TAOBAO_OVERLAY={enabledParam:"useWebdialog",topRatioParam:"topRatio",heightRatioParam:"height_pct",radiusParam:"cornerRadius",maskAlphaParam:"maskAlpha",tapCloseParam:"tapEnable",tapCloseSelectors:["#qwen-titlebar .qwen-titlebar-icon-wrapper:last-child"],defaultTopRatio:.2,defaultRadius:6,defaultMaskAlpha:.5,defaultTapClose:!0},FLIGGY_IMAGE_PICKER={schemes:["page://ask_take_photo"],api:"mtop.trip.serverless.api.gateway",version:"2.0",fcId:"240417431173407785",fcGroup:"fl-images",uploadUrlFunction:"uploadByTokenUrl",prefix:"temp",region:"CN"},FLIGGY_LAYER_URL_PROXY={sourceHostPrefix:"edith.",pathPrefix:"/proxy/",targetHostSuffixes:["wapa.taobao.com"],defaultTargetHost:"market.wapa.taobao.com"},FLIGGY_ROOT_CONTAINER={statusBarHeightCookie:{name:"_fli_barHeight",domain:"taobao.com",path:"/"}},FLIGGY_TITLE_BAR_HIDDEN_PATHNAMES=["/app/trip/rx-home/pages/home","/app/trip/rx-trip-ai/pages/home"],FLIGGY_STATUS_BAR_BACKGROUND_COLORS={"/app/trip/rx-home/pages/home":"#fff","/app/trip/rx-trip-ai/pages/home":"#dbdbff"};function emptyActions(){return{open:[],close:[],title:[],navigationBar:[],statusBar:[],systemInfo:[],mtop:[],kvGet:[],kvSet:[],kvDelete:[],pageContext:[],responses:{},behaviors:{},noop:[],silent:[]}}function mergeActions(...maps){let out=emptyActions();for(let m of maps)out.open.push(...m.open),out.close.push(...m.close),out.title.push(...m.title),out.navigationBar.push(...m.navigationBar??[]),out.statusBar.push(...m.statusBar??[]),out.systemInfo.push(...m.systemInfo),out.mtop.push(...m.mtop),out.kvGet.push(...m.kvGet??[]),out.kvSet.push(...m.kvSet??[]),out.kvDelete.push(...m.kvDelete??[]),out.pageContext.push(...m.pageContext??[]),Object.assign(out.responses,m.responses??{}),Object.assign(out.behaviors,m.behaviors??{}),out.noop.push(...m.noop),out.silent.push(...m.silent??[]);return out}var APP_BRIDGE_BEHAVIORS=["navigate","closeAll","closeBackData","postMessage","notifySubscribe","notifyUnsubscribe","notifyPost","sharedFileRead","sharedFileWrite","sharedDataGet","sharedDataSet","legacyBroadcastCreate","legacyBroadcastPost","legacyBroadcastClose","memoryGet","memorySet","memoryDelete","availabilityMap","userInfo","networkInfo","geolocation","permission","prefetch","fptTrack","mtopStream","previewFile","toast","unsupportedNativeInput","payment","userTrack","calendar","networkQualityMonitor","beaconRequest"],APP_BRIDGE_BEHAVIOR_SET=new Set(APP_BRIDGE_BEHAVIORS),BRIDGE_ACTION_ARRAY_KEYS=["open","close","title","navigationBar","statusBar","systemInfo","mtop","kvGet","kvSet","kvDelete","pageContext","noop"];function isJsonValue2(value,seen=new Set){if(value===null||typeof value=="string"||typeof value=="boolean")return!0;if(typeof value=="number")return Number.isFinite(value);if(typeof value!="object"||seen.has(value))return!1;seen.add(value);let valid=Array.isArray(value)?value.every(item=>isJsonValue2(item,seen)):Object.values(value).every(item=>isJsonValue2(item,seen));return seen.delete(value),valid}function validateAppBridgeConfig(value){if(!value||typeof value!="object"||Array.isArray(value))throw new Error("bridgeConfig must be an object");let root=value;if(Object.keys(root).some(key=>key!=="methods"))throw new Error('bridgeConfig only supports the "methods" field');if(!root.methods||typeof root.methods!="object"||Array.isArray(root.methods))throw new Error("bridgeConfig.methods must be an object");let entries=Object.entries(root.methods);if(entries.length>200)throw new Error("bridgeConfig supports at most 200 methods");let methods2={};for(let[method,rawConfig]of entries){if(!method.trim()||method.length>200)throw new Error("bridgeConfig method names must contain 1-200 characters");if(method==="__proto__"||method==="prototype"||method==="constructor")throw new Error(`bridgeConfig method name "${method}" is reserved`);if(!rawConfig||typeof rawConfig!="object"||Array.isArray(rawConfig))throw new Error(`bridgeConfig.methods.${method} must be an object`);let methodConfig=rawConfig,supportedKeys=new Set(["behavior","response","noop","silent"]);if(Object.keys(methodConfig).some(key=>!supportedKeys.has(key)))throw new Error(`bridgeConfig.methods.${method} contains an unsupported field`);if("behavior"in methodConfig&&typeof methodConfig.behavior!="string")throw new Error(`bridgeConfig.methods.${method}.behavior must be a string`);let hasBehavior=typeof methodConfig.behavior=="string",hasResponse=Object.prototype.hasOwnProperty.call(methodConfig,"response"),hasNoop=methodConfig.noop===!0;if(Number(hasBehavior)+Number(hasResponse)+Number(hasNoop)!==1)throw new Error(`bridgeConfig.methods.${method} must define exactly one of behavior, response, or noop=true`);if(hasBehavior&&!APP_BRIDGE_BEHAVIOR_SET.has(methodConfig.behavior))throw new Error(`bridgeConfig.methods.${method} has an unsupported behavior`);if(hasResponse&&!isJsonValue2(methodConfig.response))throw new Error(`bridgeConfig.methods.${method}.response must be valid JSON data`);if("noop"in methodConfig&&methodConfig.noop!==!0)throw new Error(`bridgeConfig.methods.${method}.noop must be true when provided`);if("silent"in methodConfig&&typeof methodConfig.silent!="boolean")throw new Error(`bridgeConfig.methods.${method}.silent must be a boolean`);methods2[method]={...hasBehavior&&{behavior:methodConfig.behavior},...hasResponse&&{response:JSON.parse(JSON.stringify(methodConfig.response))},...hasNoop&&{noop:!0},...methodConfig.silent===!0&&{silent:!0}}}let normalized={methods:methods2};if(JSON.stringify(normalized).length>65536)throw new Error("bridgeConfig must not exceed 64 KiB");return normalized}function applyAppBridgeConfig(actions,config2){let out=mergeActions(actions);if(!config2)return out;let{methods:methods2}=validateAppBridgeConfig(config2);for(let[method,methodConfig]of Object.entries(methods2)){for(let key of BRIDGE_ACTION_ARRAY_KEYS){let values=out[key];values&&(out[key]=values.filter(value=>value!==method))}out.silent=(out.silent??[]).filter(value=>value!==method),delete out.responses?.[method],delete out.behaviors?.[method],methodConfig.behavior?out.behaviors[method]=methodConfig.behavior:Object.prototype.hasOwnProperty.call(methodConfig,"response")?out.responses[method]=methodConfig.response:methodConfig.noop&&out.noop.push(method),methodConfig.silent&&out.silent.push(method)}return out}var WV_ACTIONS={open:["WVNative.openWindow","Base.openBrowser","EtaoJsbridgeUtil.openWindow","TMBridge.pushWindow","Third.openThirdWeb"],close:["WebAppInterface.pop","Triver.pop","TMBridge.popWindow","EleWVHybridAPI.popWindow","Third.closeWebView"],title:["WebAppInterface.setCustomPageTitle"],navigationBar:["Triver.setNavigationBarStyle"],statusBar:["WebAppInterface.setStatusBarStyle","Application.setStatusBarStyle"],systemInfo:[],mtop:["MtopWVPlugin.send"],behaviors:{"WVNetwork.getNetworkType":"networkInfo","WVFile.read":"sharedFileRead","WVFile.write":"sharedFileWrite","SharedData.getSharedData":"sharedDataGet","SharedData.setSharedData":"sharedDataSet","WVBroadcast.createChannel":"legacyBroadcastCreate","WVBroadcast.postMessage":"legacyBroadcastPost","WVBroadcast.close":"legacyBroadcastClose"},noop:["WVNative.enableHookNativeBack","WVNative.forbidPanGesture","WVNative.setGestureBack","WVTBUserTrack.toUT","WVTBUserTrack.toUT2"],silent:["WVNetwork.getNetworkType","WVTBUserTrack.toUT","WVTBUserTrack.toUT2"]},COMMON_SCHEME_RULES=[{match:"page:",param:"params"},{match:"taobaotravel:",param:"params"},{match:"alipays://platformapi/starth5app",param:"url"},{match:"alipays://platformapi/startapp",param:"page"},{match:"eleme://web",param:"url"},{match:"amapuri://webview/",param:"url"}],FEIZHU_WECHAT_HOST_SUFFIXES=["feizhu.com"],WECHAT_SCHEME_RULES=[{match:"/pages/main/webview",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES,param:"url",useCurrentOrigin:!0},...COMMON_SCHEME_RULES],WECHAT_MINI_PROGRAM={paymentRoutes:[{pathname:"/pages/utils/common-pay/index",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES,paymentParamsParam:"signStr",successUrlParams:["backUrl","successUrl"],failureUrlParams:["unSuccessUrl","errorUrl"],successResultParam:"__paymentRes",forwardParams:["ttid"],useCurrentOrigin:!0}],nativeRoutes:[{pathname:"/pages/utils/webview-bridge/index",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES,actions:["navigateMiniProgram","subscribeMessage"]}],messageRules:[{type:"BACK_DATA",action:"stageBackData",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES},{type:"BACK_MINI_APP",action:"closeAll",hostSuffixes:FEIZHU_WECHAT_HOST_SUFFIXES}]},WECHAT_TITLE_BAR_HOST_STYLES=[{hostSuffix:"feizhu.com",titleBarBackgroundColor:"#ffe033",statusBarBackgroundColor:"#ffe033"}],FLIGGY_SCHEME_RULES=[{match:"fliggy://order/detail",targetPath:"/app/trip/rx-flight-detail/pages/index",targetHostPrefix:"market",targetParams:{titleBarHidden:"2"}},...COMMON_SCHEME_RULES],WV_ACTIVE_EVENTS=["WV.Event.APP.Active"],FLIGGY_AI_UI_NOOPS=["handleLiveActivity","ai_ask_scroll_position","ai_ask_input_status","ai_ask_set_keyboard_tags","ai_ask_h5_awaken_input","ai_ask_reset_input","ai_ask_hide_input","home_ai_page_scroll","ai_ask_hide_keyboard","ai_ask_clear_keyboard_tags","ai_ask_init_mask","ai_ask_hide_mask","ai_ask_transfer_to_wenwen","ai_ask_transfer_to_mask","close_loading_view","open_loading_view","set_ai_ask_container_status","to_set_notifaction","home_refresh","ai_ask_page_load_success","ai_ask_set_session_info","ai_ask_input_set_mention_url","ai_ask_input_set_scene","ai_float_brain_panel_back_to_top_panel_page","ai_float_brain_panel_set_tools"],APP_PROFILES={fliggy:{name:"fliggy",label:"飞猪",appName:"LX",defaultAppVersion:"10.0.0",uaTokens:["AliTrip/{v}",WINDVANE],globals:{},bridges:[WV_BRIDGE,{global:"alitripBridge",style:"fliggy"},{global:"core",style:"fliggy"},{global:"methodChannel",style:"callback"}],activeEvents:WV_ACTIVE_EVENTS,actions:mergeActions(WV_ACTIONS,{...emptyActions(),open:["goto","ai_float_brain_panel_collapse_and_open_url"],close:[],title:["set_webview_title"],navigationBar:["set_ui"],statusBar:["set_status_bar_style"],systemInfo:["client_info","WVNativeDetector.getModelInfo"],kvGet:["get_kvcache"],kvSet:["set_kvcache"],kvDelete:["del_kvcache"],pageContext:["ai_float_brain_panel_get_page_context"],responses:{is_open_push:{is_open:!1},get_unread_message:{style:"POINT",count:0},get_v10_ab_info:{v10Version:!0},get_ai_ask_container_status:{status:"FULL"},ai_ask_get_keyboard_height:{height:0},get_idfa:{},get_caid:{},get_theme_conf:{},cppay_app_install:{result:""}},behaviors:{"page://goto":"navigate","page://close":"closeBackData",back:"closeBackData",user_info:"userInfo",ai_ask_get_memory_cache:"memoryGet",ai_ask_set_memory_cache:"memorySet",ai_ask_del_memory_cache:"memoryDelete",channelJudgeJsBridge:"availabilityMap",networktype:"networkInfo",network_quality_monitor:"networkQualityMonitor",request:"beaconRequest",store_calendar_event:"calendar",remove_calendar_event:"calendar",check_batch_calendar:"calendar",search_batch_calendar_events:"calendar",lbs:"geolocation",permission:"permission",cacheFetch:"prefetch",fptTrack:"fptTrack",toUT:"userTrack","WVTBUserTrack.toUT":"userTrack","WVTBUserTrack.toUT2":"userTrack",mtop_stream:"mtopStream",ai_ask_preview_file:"previewFile",toast:"toast",ai_ask_input_bridge:"unsupportedNativeInput",cppay:"payment",minipay:"payment",union_pay:"payment"},noop:["swipe_back","track_error_with_alarm","cacheUpdate","long_press_save_image",...FLIGGY_AI_UI_NOOPS],silent:["native://biz/mtop_normal_sign","toUT","get_idfa","get_caid","channelJudgeJsBridge","get_unread_message","get_v10_ab_info","lbs","networktype","network_quality_monitor","request","long_press_save_image","WVNativeDetector.getModelInfo","set_status_bar_style","get_theme_conf","cacheFetch","cppay_app_install","track_error_with_alarm",...FLIGGY_AI_UI_NOOPS]}),schemes:FLIGGY_SCHEME_RULES,imagePicker:FLIGGY_IMAGE_PICKER,layerUrlProxy:FLIGGY_LAYER_URL_PROXY,rootContainer:FLIGGY_ROOT_CONTAINER,titleBarHiddenPathnames:FLIGGY_TITLE_BAR_HIDDEN_PATHNAMES,statusBarBackgroundColors:FLIGGY_STATUS_BAR_BACKGROUND_COLORS,urlSyncHostSuffixes:["m.taobao.com","wapa.taobao.com"],overlay:FLIGGY_OVERLAY,popBeforeOpenParam:"_fli_popBeforeOpen",nativeBack:FLIGGY_NATIVE_BACK,forceH5Mtop:!0},taobao:{name:"taobao",label:"手机淘宝",appName:"TB",defaultAppVersion:"10.65.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE,MEGA_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,overlay:TAOBAO_OVERLAY,nativeBack:WV_NATIVE_BACK},wechat:{name:"wechat",label:"微信",appName:"WeChat",defaultAppVersion:"8.0.58",uaFamily:"wechatMiniProgram",uaTokens:[],globals:{__wxjs_environment:"miniprogram"},bridges:[{global:"wx.miniProgram",style:"wechatMiniProgram",persistent:!0}],activeEvents:[],actions:{...emptyActions(),open:["navigateTo","redirectTo","switchTab","reLaunch"],close:["navigateBack"],behaviors:{postMessage:"postMessage"}},schemes:WECHAT_SCHEME_RULES,miniProgram:WECHAT_MINI_PROGRAM,titleBarHostStyles:WECHAT_TITLE_BAR_HOST_STYLES},tmall:{name:"tmall",label:"天猫",appName:"TM",defaultAppVersion:"15.22.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},alipay:{name:"alipay",label:"支付宝",appName:"AP",defaultAppVersion:"10.8.0",uaTokens:["AlipayClient/{v}"],globals:{},bridges:[{global:"AlipayJSBridge",style:"alipay"}],activeEvents:[],actions:{open:["pushWindow","startApp"],close:["popWindow"],title:["setTitle"],navigationBar:["hideBackButton","showBackButton"],systemInfo:["getSystemInfo"],mtop:[],behaviors:{getNetworkType:"networkInfo",addNotifyListener:"notifySubscribe",removeNotifyListener:"notifyUnsubscribe",postNotification:"notifyPost"},noop:["postWebViewMessage","setGestureBack"],silent:["getNetworkType"]},schemes:COMMON_SCHEME_RULES,nativeBack:ALIPAY_NATIVE_BACK},koubei:{name:"koubei",label:"口碑",appName:"KB",defaultAppVersion:"9.5.0",uaTokens:["KoubeiClient/{v}"],globals:{},bridges:[{global:"AlipayJSBridge",style:"alipay"}],activeEvents:[],actions:{open:["pushWindow","startApp"],close:["popWindow"],title:["setTitle"],navigationBar:["hideBackButton","showBackButton"],systemInfo:["getSystemInfo"],mtop:[],behaviors:{getNetworkType:"networkInfo",addNotifyListener:"notifySubscribe",removeNotifyListener:"notifyUnsubscribe",postNotification:"notifyPost"},noop:["postWebViewMessage","setGestureBack"],silent:["getNetworkType"]},schemes:COMMON_SCHEME_RULES,nativeBack:ALIPAY_NATIVE_BACK},"taobao-tj":{name:"taobao-tj",label:"淘宝特价版",appName:"LT",defaultAppVersion:"10.32.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},"taobao-live":{name:"taobao-live",label:"淘宝直播",appName:"TAOBAOLIVEAPP",defaultAppVersion:"3.10.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},xianyu:{name:"xianyu",label:"闲鱼",appName:"FM",defaultAppVersion:"7.15.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},etao:{name:"etao",label:"一淘",appName:"ET",defaultAppVersion:"9.27.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},eleme:{name:"eleme",label:"饿了么",appName:"ELMC",defaultAppVersion:"11.12.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},damai:{name:"damai",label:"大麦",appName:"DM",defaultAppVersion:"8.9.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE],activeEvents:WV_ACTIVE_EVENTS,actions:WV_ACTIONS,schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},btrip:{name:"btrip",label:"阿里商旅",appName:"BLX",defaultAppVersion:"9.12.0",uaTokens:[WINDVANE],globals:{},bridges:[WV_BRIDGE,{global:"methodChannel",style:"btrip"}],activeEvents:WV_ACTIVE_EVENTS,actions:mergeActions(WV_ACTIONS,{...emptyActions(),open:["goto"],behaviors:{back:"closeBackData"}}),schemes:COMMON_SCHEME_RULES,nativeBack:WV_NATIVE_BACK},amap:{name:"amap",label:"高德地图",appName:"amap",defaultAppVersion:"13.8.0",uaTokens:[],globals:{},bridges:[{global:"AmapApp.bridge",style:"amap"}],activeEvents:[],actions:{open:["loadSchema","infoH5JsAction"],close:[],title:["setWebViewTitle"],systemInfo:[],mtop:[],noop:["interceptNativeBackEvent"]},schemes:COMMON_SCHEME_RULES,nativeBack:{handler:"onNativeBackEvent"}},qianwen:{name:"qianwen",label:"千问",appName:"TONGYI",defaultAppVersion:"3.20.0",uaTokens:[],globals:{},bridges:[{global:"ucapi",style:"invoke"}],activeEvents:[],actions:{open:["biz.openPageUrl","webdialog.show"],close:["biz.closeWebPage","webdialog.pop"],title:[],systemInfo:[],mtop:[],behaviors:{"base.postmessage":"postMessage","biz.popToRootWindow":"closeAll","biz.popToTopChatWindow":"closeAll"},noop:[]},schemes:COMMON_SCHEME_RULES,messageEvent:"QKEVT_OnReceiveMessage"},lingyou:{name:"lingyou",label:"翎游",appName:"hongtu",defaultAppVersion:"1.5.0",uaTokens:["hongtu/{v}"],globals:{},bridges:[{global:"WKWebViewJavascriptBridge",style:"callHandler"},{global:"WebViewJavascriptBridge",style:"callHandler"}],activeEvents:[],actions:{...emptyActions(),open:["jumpPage"],close:["closePage"],title:["setPageTitle"]},schemes:COMMON_SCHEME_RULES},didi:{name:"didi",label:"滴滴出行",appName:"didi.passenger",defaultAppVersion:"6.9.0",uaTokens:["didi.passenger/{v}"],globals:{},bridges:[{global:"didiBridge",style:"didi"},{global:"Fusion",style:"didi"}],activeEvents:[],actions:{...emptyActions(),open:["openPage"],close:["closePage"]},schemes:COMMON_SCHEME_RULES},easybike:{name:"easybike",label:"易到用车",appName:"easybike",defaultAppVersion:"9.0.0",uaTokens:["app=easybike;"],globals:{},bridges:[{global:"webkit.messageHandlers.callNative",style:"easybikeNative"},{global:"AppFunctions",style:"easybikeNative"}],activeEvents:[],actions:mergeActions(WV_ACTIONS,{...emptyActions(),close:["business/hitch.closeWebView"]}),schemes:COMMON_SCHEME_RULES}};function buildAppProfileUa(profile,options={}){let os12=options.os??(options.devicePreset?DEVICE_PRESETS[options.devicePreset]?.appProfileOs:void 0)??"ios",version2=options.appVersion??profile.defaultAppVersion,deviceModel=options.deviceModel??(options.devicePreset?DEVICE_PRESETS[options.devicePreset]?.appProfileModel:void 0)??"Pixel 11";if(profile.uaFamily==="wechatMiniProgram")return os12==="android"?`Mozilla/5.0 (Linux; Android 17; ${deviceModel}; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/152.0.0.0 Mobile MicroMessenger/${version2} WeChat/arm64 NetType/WIFI Language/zh_CN miniProgram`:`Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/${version2} NetType/WIFI Language/zh_CN miniProgram`;let tokens=profile.uaTokens.map(t=>t.replaceAll("{v}",version2)).filter(Boolean),tail=tokens.length>0?` ${tokens.join(" ")}`:"";return os12==="android"?`Mozilla/5.0 (Linux; Android 17; ${deviceModel}) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/152.0.0.0 Mobile Safari/537.36 AliApp(${profile.appName}/${version2})${tail}`:`Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) AliApp(${profile.appName}/${version2})${tail}`}function resolveAppProfile(name,options={}){let profile=APP_PROFILES[name];if(!profile)throw new Error(`Unknown app profile "${name}". Available: ${Object.keys(APP_PROFILES).join(", ")}`);let os12=options.os??(options.devicePreset?DEVICE_PRESETS[options.devicePreset]?.appProfileOs:void 0)??"ios",version2=options.appVersion??profile.defaultAppVersion,recommendedPreset=os12==="android"?"pixel-11":"iphone-17-pro",devicePreset=options.devicePreset??recommendedPreset,emulation=resolveEmulationConfig({enabled:!0,preset:devicePreset,orientation:options.orientation}),deviceModel=options.deviceModel??DEVICE_PRESETS[devicePreset].appProfileModel,globals={...profile.globals,__APP_NAME__:profile.appName,__APP_VERSION__:version2,__FLI_DEVICE_MODEL__:deviceModel,__DEVICE_MODEL__:deviceModel},ua=buildAppProfileUa(profile,{...options,os:os12,deviceModel});return{profile:profile.name,label:profile.label,ua,injected:{profile:profile.name,label:profile.label,globals,bridges:profile.bridges,activeEvents:profile.activeEvents,maxTouchPoints:5,statusBarHeight:emulation.safeAreaInsets.top,safeAreaInsets:emulation.safeAreaInsets,deviceAppearance:{preset:devicePreset,orientation:emulation.orientation,cutout:emulation.appearance.cutout},language:"zh-Hans",userAgent:ua,navigatorPlatform:os12==="android"?"Linux armv8l":"iPhone",platform:os12==="android"?"Android":"iOS",systemVersion:os12==="android"?"17":"26.0",clientType:os12==="android"?"android":"iphone",actions:applyAppBridgeConfig(profile.actions,options.bridgeConfig),schemes:profile.schemes,...profile.miniProgram&&{miniProgram:profile.miniProgram},...profile.imagePicker&&{imagePicker:profile.imagePicker},...profile.overlay&&{overlay:profile.overlay},...profile.popBeforeOpenParam&&{popBeforeOpenParam:profile.popBeforeOpenParam},...profile.messageEvent&&{messageEvent:profile.messageEvent},...profile.nativeBack&&{nativeBack:profile.nativeBack},...profile.layerUrlProxy&&{layerUrlProxy:profile.layerUrlProxy},...profile.urlSyncHostSuffixes&&{urlSyncHostSuffixes:profile.urlSyncHostSuffixes},...profile.forceH5Mtop&&{forceH5Mtop:!0},simulateSystemBars:!1,rootContainer:{enabled:!1,...profile.rootContainer?.statusBarHeightCookie&&{initialCookies:[{...profile.rootContainer.statusBarHeightCookie,value:String(emulation.safeAreaInsets.top)}]}},titleBar:{navigationBarHeight:os12==="android"?48:44,backgroundColor:"#ffffff",textColor:"#0f131a",...profile.titleBarHiddenPathnames&&{hiddenPathnames:profile.titleBarHiddenPathnames},...profile.statusBarBackgroundColors&&{statusBarBackgroundColors:profile.statusBarBackgroundColors},...profile.titleBarHostStyles&&{hostStyles:profile.titleBarHostStyles}}},recommendedPreset}}function installAppProfileEnvironment(config2){let w=window;if(w.__mearlAppProfile__)return null;w.__mearlAppProfile__=config2.profile;let SRC="mearl-app-bridge",TAG=`[AppBridge:${config2.label}]`,ROOT_FRAME_NAME="__mearl_root__",LAYER_FRAME_NAME="__mearl_layer__",isTop=window===window.top,isRootFrame=!isTop&&window.name===ROOT_FRAME_NAME,isLayerFrame=!isTop&&window.name===LAYER_FRAME_NAME,isContainerFrame=isTop||isRootFrame||isLayerFrame,usesRootContainer=isTop&&config2.rootContainer?.enabled===!0,simulateSystemBars=config2.simulateSystemBars!==!1,safeAreaInsets=config2.safeAreaInsets??{top:config2.statusBarHeight,right:0,bottom:0,left:0},log3=(...args)=>console.info(TAG,...args);for(let[key,value]of Object.entries(config2.globals))try{w[key]=value}catch{}typeof w.__STATUS_BAR_HEIGHT__!="number"&&(w.__STATUS_BAR_HEIGHT__=config2.statusBarHeight),typeof w.__SAFE_AREA_INSET_BOTTOM__!="number"&&(w.__SAFE_AREA_INSET_BOTTOM__=safeAreaInsets.bottom);let applySafeAreaCssVariables=()=>{let root=document.documentElement;if(!root)return!1;try{return root.style.setProperty("--safe-area-inset-top",`${safeAreaInsets.top}px`),root.style.setProperty("--safe-area-inset-right",`${safeAreaInsets.right}px`),root.style.setProperty("--safe-area-inset-bottom",`${safeAreaInsets.bottom}px`),root.style.setProperty("--safe-area-inset-left",`${safeAreaInsets.left}px`),!0}catch{return!1}};if(!applySafeAreaCssVariables()){let observer=new MutationObserver(()=>{applySafeAreaCssVariables()&&observer.disconnect()});observer.observe(document,{childList:!0})}if(config2.forceH5Mtop){let downstreamMtopParamsHandler=w.MTOP_PARAMS_HANDLER,forceH5Mtop=params=>{let resolved=params;if(typeof downstreamMtopParamsHandler=="function")try{resolved=downstreamMtopParamsHandler.call(window,params)??params}catch{resolved=params}return{...resolved&&typeof resolved=="object"?resolved:{},useNative:!1}};try{Object.defineProperty(w,"MTOP_PARAMS_HANDLER",{configurable:!0,get:()=>forceH5Mtop,set:handler=>{handler!==forceH5Mtop&&(downstreamMtopParamsHandler=handler)}})}catch{w.MTOP_PARAMS_HANDLER=forceH5Mtop}}for(let[key,value]of[["userAgent",config2.userAgent],["platform",config2.navigatorPlatform],["vendor","Apple Computer, Inc."],["appVersion",config2.userAgent.replace(/^Mozilla\//,"")]])try{Object.defineProperty(navigator,key,{get:()=>value,configurable:!0})}catch{}try{Object.defineProperty(navigator,"maxTouchPoints",{get:()=>config2.maxTouchPoints})}catch{}return{w,SRC,TAG,ROOT_FRAME_NAME,LAYER_FRAME_NAME,isTop,isRootFrame,isLayerFrame,isContainerFrame,usesRootContainer,simulateSystemBars,safeAreaInsets,log:log3}}function installAppProfileSystemBars(config2,environment,host){let{SRC,isTop,isContainerFrame,simulateSystemBars,safeAreaInsets}=environment,externalDeviceChrome=config2.externalDeviceChrome===!0,titleBarMode="auto",titleBarRoot=null,titleBarSpacer=null,systemStatusView=null,systemBottomRoot=null,systemBottomSurface=null,rootTitleBarView=null,titleBarTitleVisible=!0,titleBarBackVisible=!0,titleBarBackground=config2.titleBar?.backgroundColor??"#ffffff",titleBarTextColor=config2.titleBar?.textColor??"#111111",titleBarStateExplicit=!1,presentedRootTitleBarState=null,normalizeProxyPathPrefix=prefix=>{let withLeadingSlash=prefix.startsWith("/")?prefix:`/${prefix}`;return withLeadingSlash.endsWith("/")?withLeadingSlash:`${withLeadingSlash}/`},matchesProxyTarget=(hostname3,suffixes)=>suffixes.some(suffix=>hostname3===suffix||hostname3.endsWith(`.${suffix}`)),normalizePathname=pathname=>{let withLeadingSlash=pathname.startsWith("/")?pathname:`/${pathname}`;return withLeadingSlash.length>1&&withLeadingSlash.endsWith("/")?withLeadingSlash.slice(0,-1):withLeadingSlash},businessPathname=href=>{try{let current=new URL(href,location.href),proxy=config2.layerUrlProxy;if(!proxy)return normalizePathname(current.pathname);let prefix=normalizeProxyPathPrefix(proxy.pathPrefix);if(!current.pathname.startsWith(prefix))return normalizePathname(current.pathname);let rest=current.pathname.slice(prefix.length),slash=rest.indexOf("/"),hostName=slash===-1?rest:rest.slice(0,slash),pathname=slash===-1?"/":rest.slice(slash),hostname3=new URL(`${current.protocol}//${hostName}`).hostname;return matchesProxyTarget(hostname3,proxy.targetHostSuffixes)?normalizePathname(pathname):normalizePathname(current.pathname)}catch{return null}},matchesConfiguredPathname=(href,pathnames)=>{let pathname=businessPathname(href);return pathname!==null&&pathnames.some(configuredPathname=>normalizePathname(configuredPathname)===pathname)},configuredHostStyle=(href=location.href)=>{try{let hostname3=new URL(href,location.href).hostname.toLowerCase();return(config2.titleBar?.hostStyles??[]).find(rule=>{let suffix=rule.hostSuffix.trim().replace(/^\.+/,"").toLowerCase();return suffix!==""&&(hostname3===suffix||hostname3.endsWith(`.${suffix}`))})}catch{return}},configuredTitleBarBackground=(href,fallback)=>configuredHostStyle(href)?.titleBarBackgroundColor??fallback,supportsWindVaneNavigationMeta=config2.bridges.some(bridge=>bridge.style==="windvane"),isTruthyParam=value=>value==="1"||value?.toLowerCase()==="true"||value?.toUpperCase()==="YES",isTransparentColor=value=>{let normalized=value.replace(/\s/g,"").toLowerCase();return normalized==="transparent"||normalized==="#0000"||normalized==="#00000000"||normalized==="rgba(0,0,0,0)"},fixedContainerTitleBarMode=()=>config2.profile==="wechat"?"normal":null,pageRequestedTitleBarMode=(href=location.href,includeMeta=!0)=>{try{let params=new URL(href,location.href).searchParams,webviewOptions=new URLSearchParams(params.get("__webview_options__")??""),option=key=>params.get(key)??webviewOptions.get(key);if(config2.profile==="fliggy"||config2.profile==="taobao"){let hidden=option("titleBarHidden");if(hidden==="1")return"status-inset";if(hidden==="2")return"status"}if(config2.profile==="taobao"&&option("disableNav")?.toUpperCase()==="YES")return isTruthyParam(option("status_bar_transparent"))?"status":"status-inset";if(config2.profile==="alipay"||config2.profile==="koubei"){if(option("showTitleBar")?.toUpperCase()==="NO")return"status-inset";let transparentTitle=option("transparentTitle")?.toLowerCase();if(transparentTitle&&["always","auto","custom"].includes(transparentTitle))return"overlay"}let overlayParam=config2.overlay?.enabledParam;return overlayParam&&isTruthyParam(params.get(overlayParam))?"status":!includeMeta||!supportsWindVaneNavigationMeta?null:document.getElementById("WV.Meta.Nav.HideNavBar")?.getAttribute("value")==="HideStatusBar"?"status":null}catch{return null}},pageRequestsHiddenTitleBar=(href=location.href)=>matchesConfiguredPathname(href,config2.titleBar?.hiddenPathnames??[]),configuredStatusBarBackground=(href=location.href)=>{let colors=config2.titleBar?.statusBarBackgroundColors??{},pathname=businessPathname(href);return pathname===null?null:Object.entries(colors).find(([configuredPathname])=>normalizePathname(configuredPathname)===pathname)?.[1]??configuredHostStyle(href)?.statusBarBackgroundColor??null},pageRequestsHiddenStatusBar=(href=location.href)=>{try{let params=new URL(href,location.href).searchParams;return isTruthyParam(params.get("statusBarHidden"))||isTruthyParam(params.get("hideStatusBar"))?!0:/(?:^|&)showStatusBar=NO(?:&|$)/i.test(params.get("__webview_options__")??"")}catch{return!1}},resolveTitleBarMode=(href,fallback,includeMeta)=>{let fixedMode=fixedContainerTitleBarMode();if(fixedMode)return fixedMode;if(titleBarMode!=="auto")return titleBarMode;if(pageRequestsHiddenStatusBar(href))return"hidden";if(pageRequestsHiddenTitleBar(href))return"status-inset";let requestedMode=pageRequestedTitleBarMode(href,includeMeta);return requestedMode||fallback},resolveStatusBarBackground=(href,mode,navigationBarBackground)=>configuredStatusBarBackground(href)??(mode==="normal"||mode==="status-inset"?navigationBarBackground:"transparent"),ownTitleBarState=()=>{let mode=resolveTitleBarMode(location.href,"normal",!0),background=configuredTitleBarBackground(location.href,titleBarBackground);return{mode,title:document.title||config2.label,titleVisible:titleBarTitleVisible,backVisible:titleBarBackVisible,background,statusBarBackground:resolveStatusBarBackground(location.href,mode,background),textColor:titleBarTextColor}},initialLayerTitleBarState=url2=>{let mode=fixedContainerTitleBarMode()??(pageRequestsHiddenStatusBar(url2)?"hidden":pageRequestsHiddenTitleBar(url2)?"status-inset":pageRequestedTitleBarMode(url2,!1)??"normal"),background=configuredTitleBarBackground(url2,config2.titleBar?.backgroundColor??"#ffffff");return{mode,title:config2.label,titleVisible:!0,backVisible:!0,background,statusBarBackground:mode==="status-inset"?background:resolveStatusBarBackground(url2,mode,background),textColor:config2.titleBar?.textColor??"#111111"}},parseReportedTitleBarState=value=>{if(!value||typeof value!="object")return null;let state=value;return!["normal","overlay","status","status-inset","hidden"].includes(String(state.mode))||typeof state.title!="string"||typeof state.titleVisible!="boolean"||typeof state.backVisible!="boolean"||typeof state.background!="string"||typeof state.textColor!="string"?null:{...state,statusBarBackground:typeof state.statusBarBackground=="string"?state.statusBarBackground:state.mode==="normal"||state.mode==="status-inset"?String(state.background):"transparent"}},resolvedTitleBarState=layer=>layer?layer.titleBarState??initialLayerTitleBarState(layer.url):presentedRootTitleBarState??ownTitleBarState(),resolvedRootTitleBarState=(fallback=ownTitleBarState())=>presentedRootTitleBarState??(host.getRootFrame()?{...fallback,statusBarBackground:configuredHostStyle(location.href)?.statusBarBackgroundColor??config2.titleBar?.backgroundColor??"#ffffff"}:fallback),renderNavigationBarView=(view,state)=>{let visible=state.mode==="normal"||state.mode==="overlay";view.root.style.display=visible?"block":"none",view.surface.style.visibility=visible?"visible":"hidden",view.surface.style.background=state.mode==="overlay"?"transparent":state.background,view.surface.style.borderBottom="none",view.surface.style.color=state.textColor,view.title.textContent=state.title,view.title.style.display=state.titleVisible?"block":"none",view.back.style.display=state.backVisible?"flex":"none",view.back.style.color=state.textColor},topFullLayer=()=>{let layers=host.getLayers();for(let index=layers.length-1;index>=0;index-=1)if(!layers[index].overlay&&!layers[index].closing)return layers[index]},activeTitleBarState=()=>{let layer=topFullLayer();return layer?resolvedTitleBarState(layer):resolvedRootTitleBarState()},syncActiveSystemBars=()=>{let state=activeTitleBarState();if(externalDeviceChrome&&isTop&&window.postMessage({source:"mearl-app-profile-runtime",type:"device-chrome-state",state:{statusBarBackground:state.statusBarBackground,textColor:state.textColor,bridgeConfig:{profile:config2.profile,actions:config2.actions}}},"*"),systemStatusView){let visible=state.mode!=="hidden";systemStatusView.root.style.display=visible?"block":"none",systemStatusView.surface.style.visibility=visible?"visible":"hidden",systemStatusView.surface.style.background=state.statusBarBackground,systemStatusView.surface.style.color=state.textColor}systemBottomRoot&&systemBottomSurface&&(systemBottomRoot.style.display=safeAreaInsets.bottom>0?"block":"none",systemBottomSurface.style.color=state.textColor)},syncLayerViewport=(layer,state)=>{if(layer.overlay)return;if(!simulateSystemBars){layer.frame.style.top="0px",layer.frame.style.height="100%";return}let totalHeight=config2.statusBarHeight+(config2.titleBar?.navigationBarHeight??0),offset=state.mode==="normal"?totalHeight:state.mode==="status-inset"?config2.statusBarHeight:0;layer.frame.style.top=`${offset}px`,layer.frame.style.height=offset>0?`calc(100% - ${offset}px)`:"100%",layer.frame.setAttribute("data-mearl-app-viewport-mode",state.mode),layer.frame.style.setProperty("--mearl-app-navigation-bar-height",`${config2.titleBar?.navigationBarHeight??0}px`),layer.frame.style.opacity=state.mode==="status-inset"&&!layer.titleBarStateReady?"0":"1",layer.titleBarView&&renderNavigationBarView(layer.titleBarView,state),topFullLayer()===layer&&syncActiveSystemBars()},syncRootFrameViewport=state=>{let rootFrame=host.getRootFrame();if(!rootFrame)return;if(!simulateSystemBars){rootFrame.style.top="0px",rootFrame.style.height="100%";return}let totalHeight=config2.statusBarHeight+(config2.titleBar?.navigationBarHeight??0),offset=state.mode==="normal"?totalHeight:state.mode==="status-inset"?config2.statusBarHeight:0;rootFrame.style.top=`${offset}px`,rootFrame.style.height=offset>0?`calc(100% - ${offset}px)`:"100%",rootFrame.setAttribute("data-mearl-app-viewport-mode",state.mode),rootFrame.style.setProperty("--mearl-app-navigation-bar-height",`${config2.titleBar?.navigationBarHeight??0}px`),rootFrame.style.opacity=state.mode==="status-inset"&&presentedRootTitleBarState===null&&!rootFrame.hasAttribute("data-mearl-webview-ready")?"0":"1"},syncSimulatedTitleBar=()=>{let ownState=ownTitleBarState();if(!isTop){if(isContainerFrame){if(!titleBarStateExplicit&&document.readyState==="loading")return;window.top?.postMessage({source:SRC,type:"titleBarState",state:ownState,explicit:titleBarStateExplicit},"*")}return}if(!titleBarRoot||!titleBarSpacer||!rootTitleBarView)return;let rootFrame=host.getRootFrame();!rootFrame&&host.getLayers().length===0&&host.getClosingLayerCount()===0&&(presentedRootTitleBarState=ownState);let state=resolvedRootTitleBarState(ownState);renderNavigationBarView(rootTitleBarView,state);let spacerHeight=state.mode==="normal"?config2.statusBarHeight+(config2.titleBar?.navigationBarHeight??0):state.mode==="status-inset"?config2.statusBarHeight:0;titleBarSpacer.style.display=!rootFrame&&spacerHeight>0?"block":"none",titleBarSpacer.style.height=`${spacerHeight}px`,titleBarSpacer.style.minHeight=`${spacerHeight}px`,syncRootFrameViewport(state),syncActiveSystemBars()},applyNavigationBarState=(api,params)=>{titleBarStateExplicit=!0;let p=params&&typeof params=="object"?params:{},displayValue=p.titlebar_display??p.titlebarDisplay??p.titleBarDisplay,display=typeof displayValue=="string"?displayValue.toLowerCase():"";api==="hideBackButton"&&(titleBarBackVisible=!1),api==="showBackButton"&&(titleBarBackVisible=!0),display==="hide"&&(titleBarMode="status"),display==="show"&&(titleBarMode="normal"),(p.isImmersive===!0||p.isTransparent===!0)&&(titleBarMode="overlay"),p.isImmersive===!1&&p.isTransparent===!1&&(titleBarMode="normal"),typeof p.isTitleVisible=="boolean"&&(titleBarTitleVisible=p.isTitleVisible),typeof p.title=="string"&&(document.title=p.title),typeof p.backgroundColor=="string"&&(titleBarBackground=p.backgroundColor,isTransparentColor(p.backgroundColor)&&(titleBarMode="overlay")),typeof p.barTextStyle=="string"&&(titleBarTextColor=p.barTextStyle==="white"?"#ffffff":"#111111"),syncSimulatedTitleBar()},applyStatusBarState=params=>{titleBarStateExplicit=!0;let p=params&&typeof params=="object"?params:{},style=typeof p.style=="string"?p.style.toLowerCase():"";style&&(titleBarTextColor=style==="white"||style.includes("light")?"#ffffff":"#111111"),syncSimulatedTitleBar()},createNavigationBarView=(placement,onBack)=>{let titleBar=config2.titleBar,root=document.createElement("div");root.setAttribute("data-mearl-app-titlebar",config2.profile),root.setAttribute("data-mearl-titlebar-owner",placement),root.style.cssText=`${placement==="root"?"position:fixed":"position:absolute"};left:0;right:0;top:${config2.statusBarHeight}px;height:${titleBar.navigationBarHeight}px;z-index:${placement==="root"?"2147482900":"2"};overflow:hidden;box-sizing:border-box;font-family:"PingFang SC",-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;`;let shadow=root.attachShadow({mode:"open"});shadow.innerHTML=`<style>
|
|
1020
1020
|
:host{all:initial}#surface{position:relative;width:100%;height:100%;box-sizing:border-box;color:#0f131a;-webkit-font-smoothing:antialiased;text-rendering:geometricPrecision}
|
|
1021
1021
|
#nav{height:100%;position:relative;display:grid;align-items:start}#back{appearance:none;border:0;background:transparent;position:absolute;left:9px;top:0;width:28px;height:42px;display:flex;align-items:center;justify-content:center;padding:0;color:inherit;cursor:pointer;-webkit-tap-highlight-color:transparent}
|
|
1022
1022
|
#back svg{width:24px;height:24px;fill:none;stroke:currentColor;stroke-width:1.75;stroke-linecap:round;stroke-linejoin:round}#title{position:absolute;left:80px;right:80px;top:0;height:42px;box-sizing:border-box;display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:10px 0;text-align:center;font-size:18px;font-weight:700;line-height:22px}
|
|
@@ -1044,7 +1044,7 @@ ${SOURCE_BADGES[source]}
|
|
|
1044
1044
|
#surface[data-platform="android"]{font-family:Roboto,"Noto Sans SC",sans-serif}
|
|
1045
1045
|
#surface[data-platform="android"] #status{padding:0 12px;font-size:12px;font-weight:500;letter-spacing:0}
|
|
1046
1046
|
#surface[data-platform="android"] #indicators{gap:5px;transform:scale(.86);transform-origin:right center}
|
|
1047
|
-
</style><div id="surface" data-platform="${config2.platform.toLowerCase()}" data-cutout="${String(cutoutKind!=="none")}" data-cutout-kind="${cutoutKind}"><div id="status"><span id="time"></span>${cutoutMarkup}<span id="indicators" aria-hidden="true"><svg id="signal" viewBox="0 0 18 12"><rect x="0" y="8" width="3" height="4" rx="1"/><rect x="5" y="6" width="3" height="6" rx="1"/><rect x="10" y="3" width="3" height="9" rx="1"/><rect x="15" y="0" width="3" height="12" rx="1"/></svg><svg id="wifi" viewBox="1 3.8 22 17.2"><path d="M2 8.82a15 15 0 0 1 20 0"/><path d="M5 12.859a10 10 0 0 1 14 0"/><path d="M8.5 16.429a5 5 0 0 1 7 0"/><path d="M12 20h.01"/></svg><svg id="battery" viewBox="0 0 28 13"><rect id="battery-outline" x=".65" y=".65" width="23" height="11.7" rx="3.1"/><rect id="battery-level" x="2.35" y="2.35" width="19.6" height="8.3" rx="1.7"/><path id="battery-cap" d="M25 4.1c1.1.35 1.7 1.15 1.7 2.4s-.6 2.05-1.7 2.4z"/></svg></span></div></div>`;let surface=shadow.getElementById("surface"),time3=shadow.getElementById("time"),cutout=shadow.getElementById("device-cutout"),cutoutStatusPath=shadow.querySelector("#cutout-check path"),localizedScreenshotText=config2.language.toLowerCase().startsWith("zh")?{idle:"截图",copied:"已复制",downloaded:"已下载",failed:"截图失败"}:{idle:"Screenshot",copied:"Copied",downloaded:"Downloaded",failed:"Capture failed"},setCutoutState=state=>{cutout&&(cutout.dataset.state=state,cutout.setAttribute("aria-label",localizedScreenshotText[state]),cutout.title=localizedScreenshotText[state],cutoutStatusPath&&cutoutStatusPath.setAttribute("d",state==="failed"?"M5.5 5.5l9 9m0-9-9 9":"m4.5 10.5 3.2 3.2 7.8-7.8"))},screenshotPending=!1,screenshotBlob=data=>{let binary=atob(data),bytes=new Uint8Array(binary.length);for(let index=0;index<binary.length;index+=1)bytes[index]=binary.charCodeAt(index);return new Blob([bytes],{type:"image/png"})},downloadScreenshot=blob=>{let link=document.createElement("a"),objectUrl=URL.createObjectURL(blob);link.href=objectUrl,link.download=`mearl-screenshot-${new Date().toISOString().replace(/[:.]/g,"-")}.png`,link.style.display="none",document.body.appendChild(link),link.click(),link.remove(),window.setTimeout(()=>URL.revokeObjectURL(objectUrl),1e3)},captureScreenshot=async()=>{if(!cutout||screenshotPending||cutout.dataset.state!=="idle")return;screenshotPending=!0,cutout.setAttribute("aria-busy","true");let requestId=Date.now()*1e3+Math.floor(Math.random()*1e3),timeoutTimer=0,onResponse=null,image=new Promise((resolve5,reject)=>{let cleanup=()=>{timeoutTimer&&window.clearTimeout(timeoutTimer),onResponse&&window.removeEventListener("message",onResponse)};onResponse=event=>{if(event.source!==window)return;let message=event.data;if(!message||message.source!=="mearl-content"||message.type!=="APP_BRIDGE_SCREENSHOT_RESPONSE"||message.requestId!==requestId)return;cleanup();let result=message.result;result?.success===!0&&typeof result.data=="string"?resolve5({data:result.data}):reject(new Error(String(result?.error??"screenshot failed")))},window.addEventListener("message",onResponse),timeoutTimer=window.setTimeout(()=>{cleanup(),reject(new Error("screenshot timeout"))},35e3)}).then(result=>screenshotBlob(result.data)),clipboardWrite=null;if(navigator.clipboard?.write&&typeof ClipboardItem<"u")try{clipboardWrite=navigator.clipboard.write([new ClipboardItem({"image/png":image})]),clipboardWrite.catch(()=>{})}catch{clipboardWrite=null}window.postMessage({source:SRC,type:"screenshot",requestId},"*");try{let blob=await image;if(clipboardWrite)try{await clipboardWrite,setCutoutState("copied")}catch{downloadScreenshot(blob),setCutoutState("downloaded")}else downloadScreenshot(blob),setCutoutState("downloaded")}catch{setCutoutState("failed")}finally{screenshotPending=!1,cutout.setAttribute("aria-busy","false")}window.setTimeout(()=>{screenshotPending||setCutoutState("idle")},1600)};hasDynamicIsland&&cutout&&(setCutoutState("idle"),cutout.addEventListener("click",()=>void captureScreenshot()));let updateTime=()=>{let now=new Date;time3&&(time3.textContent=`${String(now.getHours()).padStart(2,"0")}:${String(now.getMinutes()).padStart(2,"0")}`)};return window.addEventListener("mearl:page-time-change",updateTime),updateTime(),{root,surface,timeTimer:window.setInterval(updateTime,3e4)}},install=()=>{let titleBar=config2.titleBar;if(!titleBar||!isContainerFrame||!simulateSystemBars)return;let observeState=()=>{new MutationObserver(syncSimulatedTitleBar).observe(document.head??document.documentElement,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["content","value"]}),window.addEventListener("popstate",syncSimulatedTitleBar),window.addEventListener("hashchange",syncSimulatedTitleBar),document.readyState==="loading"&&document.addEventListener("DOMContentLoaded",syncSimulatedTitleBar,{once:!0});try{let pushState=history.pushState.bind(history),replaceState=history.replaceState.bind(history);history.pushState=function(...args){pushState(...args),syncSimulatedTitleBar()},history.replaceState=function(...args){replaceState(...args),syncSimulatedTitleBar()}}catch{}};if(!isTop){observeState(),syncSimulatedTitleBar();return}let mount=()=>{if(titleBarRoot||!document.body)return;let totalHeight=config2.statusBarHeight+titleBar.navigationBarHeight,navigationView=createNavigationBarView("root",host.requestNativeBack),statusView=externalDeviceChrome||config2.statusBarHeight<=0?null:createStatusBarView(),spacer=document.createElement("div");if(spacer.setAttribute("data-mearl-app-titlebar-spacer",""),spacer.style.cssText=`display:block;width:100%;height:${totalHeight}px;min-height:${totalHeight}px;flex:none;`,spacer.style.setProperty("--mearl-app-navigation-bar-height",`${titleBar.navigationBarHeight}px`),document.body.insertBefore(spacer,document.body.firstChild),document.body.appendChild(navigationView.root),statusView&&document.body.appendChild(statusView.root),!externalDeviceChrome&&safeAreaInsets.bottom>0){let bottomRoot=document.createElement("div");bottomRoot.setAttribute("data-mearl-app-system-bottom",config2.profile),bottomRoot.style.cssText=`position:fixed;left:0;right:0;bottom:0;height:${safeAreaInsets.bottom}px;z-index:2147483600;box-sizing:border-box;pointer-events:none;color:#111111;`;let bottomShadow=bottomRoot.attachShadow({mode:"open"});bottomShadow.innerHTML=`<style>:host{all:initial}#surface{appearance:none;border:0;padding:0;width:166px;max-width:100%;height:24px;position:absolute;left:50%;bottom:0;transform:translateX(-50%);display:block;box-sizing:border-box;pointer-events:auto;color:#111;background:transparent;cursor:pointer;-webkit-tap-highlight-color:transparent}#surface:focus-visible{outline:2px solid #2563eb;outline-offset:-2px}#indicator{position:absolute;left:50%;bottom:8px;transform:translateX(-50%);width:134px;height:5px;border-radius:999px;background:currentColor;opacity:.92;transition:transform 120ms ease,opacity 120ms ease}#surface:hover #indicator{opacity:1;transform:translateX(-50%) scaleX(1.05)}#surface[data-platform="android"] #indicator{bottom:6px;width:108px;height:4px;opacity:.82}</style><button id="surface" type="button" aria-label="打开桥模拟配置" title="桥模拟配置" data-platform="${config2.platform.toLowerCase()}"><span id="indicator" aria-hidden="true"></span></button>`,document.body.appendChild(bottomRoot),systemBottomRoot=bottomRoot,systemBottomSurface=bottomShadow.getElementById("surface"),systemBottomSurface?.addEventListener("click",()=>{window.postMessage({source:SRC,type:"showBridgeConfig",profile:config2.profile,actions:config2.actions},"*")})}rootTitleBarView=navigationView,systemStatusView=statusView,titleBarRoot=navigationView.root,titleBarSpacer=spacer,syncSimulatedTitleBar(),observeState()};document.body?mount():document.addEventListener("DOMContentLoaded",mount,{once:!0})},service={initialLayerTitleBarState,resolvedTitleBarState,parseReportedTitleBarState,setPresentedRootTitleBarState:state=>{presentedRootTitleBarState=state,syncSimulatedTitleBar()},markStateExplicit:()=>{titleBarStateExplicit=!0},applyNavigationBarState,applyStatusBarState,createNavigationBarView,destroyNavigationBarView:view=>view?.root.remove(),syncLayerViewport,syncActiveSystemBars,syncSimulatedTitleBar};return install(),service}function installAppProfilePageTransport(config2,environment){let{SRC,TAG,log:log3}=environment,appToast=null,appToastHideTimer=null,appToastRemoveTimer=null;function showAppToast(params){let p=params&&typeof params=="object"?params:{},messageValue=[p.message,p.msg,p.content,p.text].find(value=>typeof value=="string"&&value.trim().length>0);if(typeof messageValue!="string")return"missing message";let durationValue=Number(p.milliseconds??p.duration),duration3=Number.isFinite(durationValue)&&durationValue>0?durationValue:2e3,hideAfter=Math.min(6e4,Math.max(300,Math.round(duration3)));appToastHideTimer!==null&&window.clearTimeout(appToastHideTimer),appToastRemoveTimer!==null&&window.clearTimeout(appToastRemoveTimer);let toast=appToast?.isConnected===!0?appToast:document.createElement("div");return toast!==appToast&&(appToast=toast,toast.setAttribute("data-mearl-app-toast",""),toast.setAttribute("role","status"),toast.setAttribute("aria-live","polite"),Object.assign(toast.style,{position:"fixed",left:"50%",top:"50%",zIndex:"2147483647",maxWidth:"calc(100vw - 64px)",boxSizing:"border-box",padding:"14px 20px",borderRadius:"12px",background:"rgba(20, 20, 20, 0.88)",color:"#ffffff",fontFamily:'-apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, sans-serif',fontSize:"16px",fontWeight:"400",lineHeight:"24px",textAlign:"center",whiteSpace:"pre-wrap",overflowWrap:"anywhere",pointerEvents:"none",opacity:"0",transform:"translate(-50%, -50%) scale(0.96)",transition:"opacity 180ms ease, transform 180ms ease"}),(document.body??document.documentElement).appendChild(toast)),toast.textContent=messageValue,toast.style.opacity="0",toast.style.transform="translate(-50%, -50%) scale(0.96)",toast.offsetWidth,toast.style.opacity="1",toast.style.transform="translate(-50%, -50%) scale(1)",appToastHideTimer=window.setTimeout(()=>{appToastHideTimer=null,toast.style.opacity="0",toast.style.transform="translate(-50%, -50%) scale(0.96)",appToastRemoveTimer=window.setTimeout(()=>{appToastRemoveTimer=null,appToast===toast&&(appToast=null),toast.remove()},180)},hideAfter),null}let bridgeRequestSeq=0,pendingMtop={},pendingMtopStreams={},pendingUserInfo={};function callMtop(params,succ,fail){let id=++bridgeRequestSeq;pendingMtop[id]={succ,fail};let post=params.post,rawTimeout=params.timeout??params.timer,timeout=typeof rawTimeout=="number"?rawTimeout:typeof rawTimeout=="string"&&rawTimeout.trim()!==""?Number(rawTimeout):void 0,payload={...params,data:params.data!==void 0?params.data:params.param??{},method:params.method??(post===!0||post===1||post==="1"||post==="true"?"POST":"GET"),env:params.env??(/(^|\.)wapa\.taobao\.com$/i.test(location.hostname)?"pre":"online"),...Number.isFinite(timeout)&&{timeout}};window.postMessage({source:SRC,type:"mtop",requestId:id,payload},"*"),log3("mtop 代发 →",params.api)}function callMtopAsync(params){return new Promise((resolve5,reject)=>callMtop(params,resolve5,reject))}function callMtopStream(params,succ,fail){let sessionId=typeof params.id=="string"?params.id:String(params.id??""),request=params.request&&typeof params.request=="object"?params.request:null;if(!sessionId||!request||typeof request.api!="string"){fail?.("invalid mtop_stream params");return}let requestId=++bridgeRequestSeq;pendingMtopStreams[requestId]={sessionId},window.postMessage({source:SRC,type:"mtopStream",requestId,payload:{...request,timeout:params.timeout,method:params.method??request.method,env:/(^|\.)wapa\.taobao\.com$/i.test(location.hostname)?"pre":"online"}},"*"),succ?.({}),log3("mtop 流式代发 →",request.api)}function callUserInfo(fallback,succ){if(fallback.userId){succ?.(fallback);return}let requestId=++bridgeRequestSeq,timer=setTimeout(()=>{let pending=pendingUserInfo[requestId];pending&&(delete pendingUserInfo[requestId],pending.succ?.(pending.fallback))},1e3);pendingUserInfo[requestId]={fallback,succ,timer},window.postMessage({source:SRC,type:"userInfo",requestId},"*")}function emitMtopStreamEvent(sessionId,eventType,data){let detail=data&&typeof data=="object"?{...data,eventType}:{data,eventType};document.dispatchEvent(new CustomEvent(`mtop_stream${sessionId}`,{detail}))}function createUploadId(){try{if(typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch{}return`${Date.now()}-${Math.random().toString(36).slice(2)}`}function pickDirectUploadTarget(response){if(!response||typeof response!="object")return null;let data=response.data;if(data?.success===!1)return null;let result=data?.result,target=Array.isArray(result?.urls)?result.urls[0]:void 0;if(!target||typeof target!="object")return null;let item=target;if(typeof item.put!="string"||!item.put||typeof item.get!="string"||!item.get)return null;let rawHeaders=item.putHeaders&&typeof item.putHeaders=="object"?item.putHeaders:{},putHeaders=Object.fromEntries(Object.entries(rawHeaders).map(([key,value])=>[key,String(value)]));return{put:item.put,get:item.get,putHeaders}}async function uploadImage(file2){let uploader=config2.imagePicker;if(!uploader)throw new Error("图片上传能力未配置");let env=/(^|\.)wapa\.taobao\.com$/i.test(location.hostname)?"pre":"online",response=await callMtopAsync({api:uploader.api,v:uploader.version,method:"POST",env,timeout:6e4,data:{fcId:uploader.fcId,fcGroup:uploader.fcGroup,fcName:uploader.uploadUrlFunction,fcData:JSON.stringify({requestType:"url",mimes:[file2.type||"image/jpeg"],prefix:uploader.prefix,region:uploader.region,uploadNumber:1}),fcConfig:JSON.stringify({timeout:6e4,disasterRecover:!0})}}),target=pickDirectUploadTarget(response);if(!target)throw new Error("获取图片上传地址失败");let uploadUrl=`${target.put}${target.put.includes("?")?"&":"?"}getAvatar=1`,uploadResponse=await fetch(uploadUrl,{method:"PUT",headers:target.putHeaders,body:file2});if(uploadResponse.status!==200)throw new Error(`图片直传失败: HTTP ${uploadResponse.status}`);return target.get}function openImagePicker(callbackCommandFn){let input2=document.createElement("input");input2.type="file",input2.accept="image/*",input2.style.display="none";let settled=!1,finish=()=>{settled=!0,input2.remove()};input2.addEventListener("cancel",finish,{once:!0}),input2.addEventListener("change",()=>{let file2=input2.files?.[0];if(!file2){finish();return}if(!file2.type.startsWith("image/")){finish(),console.error(TAG,"仅支持选择图片文件");return}uploadImage(file2).then(pic=>{typeof callbackCommandFn=="function"&&callbackCommandFn({pic,uuid:createUploadId(),timeStamp:Date.now()}),log3("图片选择并上传完成:",pic)}).catch(error48=>console.error(TAG,"图片上传失败:",error48)).finally(finish)},{once:!0}),(document.body??document.documentElement).appendChild(input2),input2.click(),window.addEventListener("focus",()=>{setTimeout(()=>{!settled&&!input2.files?.length&&finish()},1e3)},{once:!0})}function showPaymentDialog(api,params,succeed,failed){document.querySelector('[data-mearl-payment-dialog="true"]')?.remove();let overlay=document.createElement("div");overlay.setAttribute("data-mearl-payment-dialog","true"),Object.assign(overlay.style,{position:"fixed",inset:"0",zIndex:"2147483647",display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.5)"});let card=document.createElement("div");Object.assign(card.style,{background:"#fff",borderRadius:"12px",padding:"24px",width:"300px",textAlign:"center",fontFamily:"system-ui, sans-serif"});let title=document.createElement("div");Object.assign(title.style,{fontSize:"17px",fontWeight:"600",marginBottom:"8px"}),title.textContent="支付确认";let desc=document.createElement("div");Object.assign(desc.style,{fontSize:"14px",color:"#666",marginBottom:"20px"}),desc.textContent=`模拟 ${api} 支付,请选择操作`;let btnRow=document.createElement("div");Object.assign(btnRow.style,{display:"flex",gap:"12px"});let btnBase=(text,bg,color,action)=>{let btn=document.createElement("button");return btn.textContent=text,btn.setAttribute("data-mearl-action",action),Object.assign(btn.style,{flex:"1",padding:"10px 0",border:"none",borderRadius:"8px",fontSize:"15px",fontWeight:"500",cursor:"pointer",background:bg,color}),btn},confirmBtn=btnBase("完成支付","#1677ff","#fff","payment-confirm"),cancelBtn=btnBase("取消支付","#f5f5f5","#333","payment-cancel"),cleanup=()=>{overlay.remove()};confirmBtn.addEventListener("click",()=>{cleanup(),log3("用户完成支付",api),succeed(api==="wx.requestPayment"?{errMsg:"requestPayment:ok"}:{ResultStatus:"9000",resultStatus:"9000"})}),cancelBtn.addEventListener("click",()=>{cleanup(),log3("用户取消支付",api),failed(api==="wx.requestPayment"?{errMsg:"requestPayment:fail cancel"}:{ResultStatus:"6001",resultStatus:"6001"})}),btnRow.appendChild(cancelBtn),btnRow.appendChild(confirmBtn),card.appendChild(title),card.appendChild(desc),card.appendChild(btnRow),overlay.appendChild(card),(document.body??document.documentElement).appendChild(overlay)}function showMiniProgramActionDialog(action,params,confirmed,cancelled){document.querySelector('[data-mearl-mini-program-dialog="true"]')?.remove();let overlay=document.createElement("div");overlay.setAttribute("data-mearl-mini-program-dialog","true"),overlay.setAttribute("data-mearl-mini-program-action",action),Object.assign(overlay.style,{position:"fixed",inset:"0",zIndex:"2147483647",display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.5)"});let card=document.createElement("div");Object.assign(card.style,{background:"#fff",borderRadius:"12px",padding:"24px",width:"300px",textAlign:"center",fontFamily:"system-ui, sans-serif"});let title=document.createElement("div");Object.assign(title.style,{fontSize:"17px",fontWeight:"600",marginBottom:"8px"}),title.textContent=action==="navigateMiniProgram"?"打开其他小程序":"订阅消息";let desc=document.createElement("div");Object.assign(desc.style,{fontSize:"14px",color:"#666",marginBottom:"20px"});let targetTitle=params.title?.trim()||"其他";desc.textContent=action==="navigateMiniProgram"?`即将打开“${targetTitle}”小程序,是否继续?`:"模拟微信订阅消息授权,请选择操作";let btnRow=document.createElement("div");Object.assign(btnRow.style,{display:"flex",gap:"12px"});let createButton=(text,background,color,actionName)=>{let button=document.createElement("button");return button.textContent=text,button.setAttribute("data-mearl-action",actionName),Object.assign(button.style,{flex:"1",padding:"10px 0",border:"none",borderRadius:"8px",fontSize:"15px",fontWeight:"500",cursor:"pointer",background,color}),button},confirmButton=createButton(action==="navigateMiniProgram"?"确定":"允许","#1677ff","#fff","mini-program-confirm"),cancelButton=createButton("取消","#f5f5f5","#333","mini-program-cancel"),cleanup=()=>overlay.remove();confirmButton.addEventListener("click",()=>{cleanup();let result=action==="navigateMiniProgram"?{errMsg:"navigateToMiniProgram:ok"}:{result:"SUCCESS",data:{totalCount:1,acceptCount:1}};log3("用户确认小程序原生能力",action,params.appId??params.scene??""),confirmed(result)}),cancelButton.addEventListener("click",()=>{cleanup();let result=action==="navigateMiniProgram"?{errMsg:"navigateToMiniProgram:fail cancel"}:{result:"CLOSE_BY_USER"};log3("用户取消小程序原生能力",action),cancelled(result)}),btnRow.appendChild(cancelButton),btnRow.appendChild(confirmButton),card.appendChild(title),card.appendChild(desc),card.appendChild(btnRow),overlay.appendChild(card),(document.body??document.documentElement).appendChild(overlay)}function handleMessage(msg){if(msg.source==="mearl-content"&&msg.type==="APP_BRIDGE_MTOP_RESPONSE"){let pending=pendingMtop[msg.requestId];if(!pending)return!0;delete pendingMtop[msg.requestId];let result=msg.result;return result?.success?pending.succ?.(result.response):pending.fail?.(result?.error??"mtop delegate failed"),!0}if(msg.source==="mearl-content"&&msg.type==="APP_BRIDGE_USER_INFO_RESPONSE"){let requestId=msg.requestId,pending=pendingUserInfo[requestId];if(!pending)return!0;delete pendingUserInfo[requestId],clearTimeout(pending.timer);let result=msg.result,response=result?.success&&result.response&&typeof result.response=="object"?result.response:{};return pending.succ?.({...pending.fallback,...response}),!0}if(msg.source==="mearl-content"&&msg.type==="APP_BRIDGE_MTOP_STREAM_EVENT"){let requestId=msg.requestId,pending=pendingMtopStreams[requestId];if(!pending)return!0;let eventType=msg.eventType;return emitMtopStreamEvent(pending.sessionId,eventType,msg.data),(eventType==="onFinish"||eventType==="onError")&&delete pendingMtopStreams[requestId],!0}return!1}return{showAppToast,callMtop,callMtopStream,callUserInfo,openImagePicker,showPaymentDialog,showMiniProgramActionDialog,handleMessage}}function installAppProfileBridgeProtocol(config2,environment,host){let{w,SRC,TAG,isTop,log:log3}=environment,{pageTransport,systemBars,requestOpen,requestClose,requestCloseAll,requestContainerData}=host,{showAppToast,callMtop,callMtopStream,callUserInfo,openImagePicker,showPaymentDialog,showMiniProgramActionDialog}=pageTransport,{applyNavigationBarState,applyStatusBarState,syncSimulatedTitleBar}=systemBars,NOT_IMPLEMENTED_PAYLOAD=JSON.stringify({ret:["HY_FAILED"],msg:"not implemented"}),FPT_STORAGE_KEY=`__mearl_app_fpt__:${config2.profile}`,CALENDAR_STORAGE_KEY=`__mearl_app_calendar_events__:${config2.profile}`,unsupportedNativeInputNotified=!1,stopNetworkQualityMonitor=null,simulatedPageHidden=!1,simulatedVisibilityInstalled=!1,hasPendingMiniProgramBackData=!1,pendingMiniProgramBackData,notificationListeners=new Map,megaListenerSeq=0,megaBroadcastListeners=new Map,megaLifeCycleListeners=new Set,megaPageCloseListeners=new Set,megaSystemBackListener=null,megaKVMutationVersion=0,MEGA_KV_TOTAL_SIZE=5*1024*1024,MEGA_KV_STORAGE_KEY=`__mearl_mega_kv__:${config2.profile}`;function readMegaKVStorage(){let storage=new Map;try{let parsed=JSON.parse(localStorage.getItem(MEGA_KV_STORAGE_KEY)??"{}");if(!parsed||typeof parsed!="object"||Array.isArray(parsed))return storage;for(let[bizId,rawEntries]of Object.entries(parsed)){if(!rawEntries||typeof rawEntries!="object"||Array.isArray(rawEntries))continue;let entries=new Map;for(let[key,value]of Object.entries(rawEntries))typeof value=="string"&&entries.set(key,value);storage.set(bizId,entries)}}catch{}return storage}let megaKVStorage=readMegaKVStorage();function megaKVSnapshot(){let snapshot={};for(let[bizId,values]of megaKVStorage)snapshot[bizId]=Object.fromEntries(values);return snapshot}function persistMegaKVStorage(){try{localStorage.setItem(MEGA_KV_STORAGE_KEY,JSON.stringify(megaKVSnapshot()))}catch{}}function replaceMegaKVStorage(value){if(!(!value||typeof value!="object"||Array.isArray(value))){megaKVStorage.clear();for(let[bizId,rawEntries]of Object.entries(value)){if(!rawEntries||typeof rawEntries!="object"||Array.isArray(rawEntries))continue;let entries=new Map;for(let[key,entryValue]of Object.entries(rawEntries))typeof entryValue=="string"&&entries.set(key,entryValue);megaKVStorage.set(bizId,entries)}persistMegaKVStorage()}}function applyMegaKVMutation(payload){let operation=typeof payload.operation=="string"?payload.operation:"",bizId=typeof payload.bizId=="string"?payload.bizId:"",key=typeof payload.key=="string"?payload.key:"";if(bizId){if(operation==="set"&&key&&typeof payload.value=="string"){let entries=megaKVStorage.get(bizId)??new Map;entries.set(key,payload.value),megaKVStorage.set(bizId,entries)}else if(operation==="remove"&&key){let entries=megaKVStorage.get(bizId);entries?.delete(key),entries?.size===0&&megaKVStorage.delete(bizId)}else if(operation==="clear")megaKVStorage.delete(bizId);else return;megaKVMutationVersion+=1,persistMegaKVStorage()}}function emitMegaCallback(callback,value){callback&&setTimeout(()=>callback(value),0)}function megaBroadcastBizId(value){return typeof value=="string"&&value?value:"__MEGA_GLOBAL_MESSAGE__"}function dispatchMegaBroadcast(payload){let bizId=megaBroadcastBizId(payload.bizId),eventName=typeof payload.eventName=="string"?payload.eventName:"";if(eventName)for(let listener of Array.from(megaBroadcastListeners.values()))listener.bizId!==bizId||listener.eventName!==eventName||(listener.once&&megaBroadcastListeners.delete(listener.id),emitMegaCallback(listener.callback,{statusCode:1,type:"onEvent",data:{detail:payload.detail}}),listener.once&&emitMegaCallback(listener.callback,{statusCode:99,type:"finish"}))}let documentPrototype=typeof Document=="function"?Document.prototype:null,nativeHiddenDescriptor=documentPrototype?Object.getOwnPropertyDescriptor(documentPrototype,"hidden"):void 0,nativeVisibilityDescriptor=documentPrototype?Object.getOwnPropertyDescriptor(documentPrototype,"visibilityState"):void 0;function installSimulatedVisibilityState(){if(!simulatedVisibilityInstalled){simulatedVisibilityInstalled=!0;try{Object.defineProperty(document,"hidden",{configurable:!0,get:()=>simulatedPageHidden||!!(nativeHiddenDescriptor?.get?.call(document)??!1)}),Object.defineProperty(document,"visibilityState",{configurable:!0,get:()=>simulatedPageHidden?"hidden":nativeVisibilityDescriptor?.get?.call(document)??"visible"})}catch{}}}function dispatchPageTransitionEvent(type){try{let event=typeof PageTransitionEvent=="function"?new PageTransitionEvent(type,{persisted:!1}):new Event(type);window.dispatchEvent(event)}catch{}}function dispatchActiveEvents(){for(let name of config2.activeEvents)try{document.dispatchEvent(new Event(name))}catch{}}function handlePageVisibility(hidden){if(hidden===simulatedPageHidden)return;installSimulatedVisibilityState(),simulatedPageHidden=hidden;let lifeCycleType=hidden?"onPageDisappear":"onPageAppear";for(let callback of megaLifeCycleListeners)emitMegaCallback(callback,{statusCode:1,type:lifeCycleType,data:{pageId:location.href}});try{document.dispatchEvent(new Event("visibilitychange"))}catch{}if(hidden){try{window.dispatchEvent(new Event("blur"))}catch{}dispatchPageTransitionEvent("pagehide");return}dispatchPageTransitionEvent("pageshow");try{window.dispatchEvent(new Event("focus"))}catch{}dispatchActiveEvents()}function resolveWindowFunction(path25){let parts=path25.split(".").filter(Boolean),owner=w;for(let index=0;index<parts.length-1;index+=1){let next=owner[parts[index]];if(!next||typeof next!="object")return null;owner=next}let fn=owner[parts[parts.length-1]];return typeof fn=="function"?fn.bind(owner):null}function handleNativeBack(){let megaHandled=!1;for(let callback of megaPageCloseListeners)megaHandled=!0,emitMegaCallback(callback,{statusCode:1,type:"onClose",data:{}});if(megaSystemBackListener&&(megaHandled=!0,emitMegaCallback(megaSystemBackListener,{statusCode:1,type:"onSuccess",data:{}})),megaHandled)return!0;let nativeBack=config2.nativeBack;if(!nativeBack)return!1;if(nativeBack.handler){let handler=resolveWindowFunction(nativeBack.handler);if(!handler)return!1;try{return handler(),!0}catch{return!1}}let controlled=!1;if(nativeBack.controlFunction){let control=resolveWindowFunction(nativeBack.controlFunction);if(!control)return!1;try{controlled=control()===!0}catch{return!1}if(!controlled)return!1}if(!nativeBack.event)return controlled;try{let event=new Event(nativeBack.event,{cancelable:!0});return document.dispatchEvent(event),controlled||event.defaultPrevented}catch{return controlled}}function handleAppMessage(message){if(!message||typeof message!="object")return;let payload=message;if(payload.kind==="megaBroadcast"){dispatchMegaBroadcast(payload);return}if(payload.kind==="megaKVStorage"){applyMegaKVMutation(payload);return}if(payload.kind==="legacyBroadcast"&&typeof payload.instanceId=="string"){try{let event=new CustomEvent(`Broadcast.Message.${payload.instanceId}`,{detail:payload.message});Object.defineProperty(event,"param",{configurable:!0,value:payload.message}),document.dispatchEvent(event)}catch{}return}if(payload.kind==="notification"&&typeof payload.name=="string"){let listener=notificationListeners.get(payload.name);listener&&setTimeout(()=>listener(payload.data),0);return}if(!(payload.kind!=="message"||!config2.messageEvent))try{document.dispatchEvent(new CustomEvent(config2.messageEvent,{detail:{data:payload.data}}))}catch{}}function sendAppMessage(message){if(isTop){handleAppMessage(message);return}window.top?.postMessage({source:SRC,type:"appMessageToOpener",message},"*")}function applyRuntimeResponses(responses){let current=config2.actions.responses??{};for(let[api,response]of Object.entries(responses))!response||typeof response!="object"||Array.isArray(response)||(current[api]=response);config2.actions.responses=current}function parseFpt(value){let entries=[],normalized=value.trim();if(!normalized)return entries;let pattern=/([0-9A-Za-z._-]+)\(([0-9A-Za-z._-]+)\)/g,consumed="";for(let match of normalized.matchAll(pattern))consumed+=match[0],entries.push([match[1],match[2]]);return consumed===normalized?entries:[]}function setFptEntry(entries,key,value){entries.delete(key),entries.set(key,value)}function readInitialFptEntries(){let entries=new Map;try{for(let[key,value]of parseFpt(sessionStorage.getItem(FPT_STORAGE_KEY)??""))setFptEntry(entries,key,value)}catch{}try{let currentFpt=new URL(location.href).searchParams.get("fpt")??"";for(let[key,value]of parseFpt(currentFpt))setFptEntry(entries,key,value)}catch{}return entries}let fptEntries=readInitialFptEntries();function serializeFpt(entries){return Array.from(entries,([key,value])=>`${key}(${value})`).join("")}function persistFpt(){try{let value=serializeFpt(fptEntries);value?sessionStorage.setItem(FPT_STORAGE_KEY,value):sessionStorage.removeItem(FPT_STORAGE_KEY)}catch{}}function decorateUrlWithFpt(rawUrl){let targetUrl=mapScheme(rawUrl)??rawUrl;if(fptEntries.size===0)return targetUrl;try{let url2=new URL(targetUrl,location.href);if(url2.protocol!=="http:"&&url2.protocol!=="https:")return targetUrl;let merged=new Map(fptEntries);for(let[key,value]of parseFpt(url2.searchParams.get("fpt")??""))setFptEntry(merged,key,value);return url2.searchParams.set("fpt",serializeFpt(merged)),url2.href}catch{return targetUrl}}function classify(api){let a=config2.actions;return a.open.includes(api)?"open":a.close.includes(api)?"close":a.title.includes(api)?"title":a.navigationBar?.includes(api)?"navigationBar":a.statusBar?.includes(api)?"statusBar":a.systemInfo.includes(api)?"systemInfo":a.mtop.includes(api)?"mtop":a.kvGet?.includes(api)?"kvGet":a.kvSet?.includes(api)?"kvSet":a.kvDelete?.includes(api)?"kvDelete":a.pageContext?.includes(api)?"pageContext":a.responses&&Object.prototype.hasOwnProperty.call(a.responses,api)?"response":a.behaviors&&Object.prototype.hasOwnProperty.call(a.behaviors,api)?a.behaviors[api]:a.noop.includes(api)?"noop":"unknown"}function pickUrl(params){if(!params||typeof params!="object")return null;let p=params,candidates=[p.url,p.data?.url,p.param?.url,p.value?.params?.url];for(let c of candidates)if(typeof c=="string"&&c)return c;return null}function pickCloseData(params){if(params&&typeof params=="object"){let p=params;if("data"in p&&p.data!==void 0)return p.data;if(Object.keys(p).length>0)return p}}function decodeCookieValue2(raw){let value=raw;for(let i=0;i<2;i+=1)try{let decoded=decodeURIComponent(value);if(decoded===value)break;value=decoded}catch{break}return value.replace(/\\u([0-9a-f]{4})/gi,(_match,hex3)=>String.fromCharCode(Number.parseInt(hex3,16)))}function readCookie(name){let prefix=`${name}=`,pair=document.cookie.split(";").map(value=>value.trim()).find(value=>value.startsWith(prefix));return pair?decodeCookieValue2(pair.slice(prefix.length)):""}function readUserCookie(name){let pageUserCookie=w.userCookie;if(!pageUserCookie||typeof pageUserCookie!="object")return"";let value=pageUserCookie[name];return typeof value=="string"?decodeCookieValue2(value):""}function readFirstUserCookie(names){for(let name of names){let value=readCookie(name)||readUserCookie(name);if(value&&value!=="null")return value}return""}let cbSeq=0,callbacks={};function stashCallback(fn){if(typeof fn!="function")return 0;let id=++cbSeq;return callbacks[id]=fn,id}function extractQuery(url2,param){let q=url2.indexOf("?");if(q===-1)return null;for(let pair of url2.slice(q+1).split("&")){let eq=pair.indexOf("=");if(eq>0&&pair.slice(0,eq)===param)return pair.slice(eq+1)}return null}function matchesHostSuffix(hostname3,suffixes){if(!suffixes?.length)return!0;let normalizedHost=hostname3.toLowerCase().replace(/\.$/,"");return suffixes.some(value=>{let suffix=value.toLowerCase().replace(/^\./,"").replace(/\.$/,"");return normalizedHost===suffix||normalizedHost.endsWith(`.${suffix}`)})}function matchesRouteHost(rawUrl,suffixes){if(!suffixes?.length)return!0;try{let parsed=new URL(rawUrl,location.href),hostname3=parsed.protocol==="http:"||parsed.protocol==="https:"?parsed.hostname:location.hostname;return matchesHostSuffix(hostname3,suffixes)}catch{return matchesHostSuffix(location.hostname,suffixes)}}function resolveSchemeValue(raw,depth){if(depth>3)return null;let value=raw;try{value=decodeURIComponent(raw)}catch{}if(value.startsWith("{"))try{let found=pickUrl(JSON.parse(value));if(!found)return null;value=found}catch{return null}if(/^https?:/i.test(value))return value;if(/^[a-z][a-z0-9+.-]*:/i.test(value))return mapScheme(value,depth+1);let nestedUrl=extractQuery(value,"url");return nestedUrl?resolveSchemeValue(nestedUrl,depth+1):null}function mapScheme(url2,depth=0){if(depth>3)return null;let lower=url2.toLowerCase();for(let rule of config2.schemes){if(!matchesRouteHost(url2,rule.hostSuffixes))continue;let normalizedMatch=rule.match.toLowerCase(),matchedUrl=url2;if(!lower.startsWith(normalizedMatch)){if(!normalizedMatch.startsWith("/"))continue;try{let parsed=new URL(url2,location.href);if(matchedUrl=`${parsed.pathname}${parsed.search}${parsed.hash}`,!matchedUrl.toLowerCase().startsWith(normalizedMatch))continue}catch{continue}}if(rule.targetPath){let suffix=matchedUrl.slice(rule.match.length);if(suffix&&!suffix.startsWith("?")&&!suffix.startsWith("#"))continue;try{let source=new URL(matchedUrl),origin=location.origin;if(rule.targetHostPrefix){let hostname3=location.hostname.toLowerCase(),domainSuffix=hostname3==="wapa.taobao.com"||hostname3.endsWith(".wapa.taobao.com")?"wapa.taobao.com":hostname3==="m.taobao.com"||hostname3.endsWith(".m.taobao.com")?"m.taobao.com":"";domainSuffix&&(origin=`https://${rule.targetHostPrefix}.${domainSuffix}`)}let target=new URL(rule.targetPath,`${origin}/`);target.search=source.search,target.hash=source.hash;for(let[key,value]of Object.entries(rule.targetParams??{}))target.searchParams.has(key)||target.searchParams.set(key,value);return target.href}catch{return null}}if(!rule.param)continue;let raw=extractQuery(matchedUrl,rule.param);if(!raw)return null;let resolved=resolveSchemeValue(raw,depth);if(!resolved||!rule.useCurrentOrigin)return resolved;try{let target=new URL(resolved);return`${location.origin}${target.pathname}${target.search}${target.hash}`}catch{return resolved}}return null}function firstRouteParam(params,names){for(let name of names){let value=params.get(name);if(value)return value}return""}function resolvePaymentCallbackUrl(rawUrl,paymentPageUrl,useCurrentOrigin,forwardParams,resultParam){if(!rawUrl)return null;try{let target=new URL(rawUrl,location.href);for(let name of forwardParams){let value=paymentPageUrl.searchParams.get(name);value&&!target.searchParams.get(name)&&target.searchParams.set(name,value)}resultParam&&target.searchParams.set(resultParam.name,JSON.stringify(resultParam.value));let resolved=useCurrentOrigin&&(target.protocol==="http:"||target.protocol==="https:")?`${location.origin}${target.pathname}${target.search}${target.hash}`:target.href;return decorateUrlWithFpt(resolved)}catch{return null}}function openPaymentCallback(rawUrl,paymentPageUrl,useCurrentOrigin,forwardParams,resultParam){let target=resolvePaymentCallbackUrl(rawUrl,paymentPageUrl,useCurrentOrigin,forwardParams,resultParam);target&&requestOpen(target,0,!1)}function handleMiniProgramPaymentRoute(rawUrl){let paymentPageUrl;try{paymentPageUrl=new URL(rawUrl,location.href)}catch{return!1}let normalizedPathname=paymentPageUrl.pathname.replace(/\/+$/,"")||"/",rule=config2.miniProgram?.paymentRoutes?.find(candidate=>(candidate.pathname.replace(/\/+$/,"")||"/")===normalizedPathname&&matchesHostSuffix(paymentPageUrl.hostname,candidate.hostSuffixes));if(!rule)return!1;let successUrl=firstRouteParam(paymentPageUrl.searchParams,rule.successUrlParams),failureUrl=firstRouteParam(paymentPageUrl.searchParams,rule.failureUrlParams),forwardParams=rule.forwardParams??[],useCurrentOrigin=rule.useCurrentOrigin===!0,paymentParams;try{let parsed=JSON.parse(paymentPageUrl.searchParams.get(rule.paymentParamsParam)??"");if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error;paymentParams=parsed,paymentParams.timeStamp!==void 0&&(paymentParams.timeStamp=String(paymentParams.timeStamp))}catch{return log3("微信支付参数解析失败,执行失败回跳",rawUrl),openPaymentCallback(failureUrl,paymentPageUrl,useCurrentOrigin,forwardParams),!0}return showPaymentDialog("wx.requestPayment",paymentParams,result=>{openPaymentCallback(successUrl,paymentPageUrl,useCurrentOrigin,forwardParams,rule.successResultParam?{name:rule.successResultParam,value:result}:void 0)},()=>{openPaymentCallback(failureUrl,paymentPageUrl,useCurrentOrigin,forwardParams)}),!0}function finishMiniProgramNativeRoute(action,result,storageId){handleResume({data:action==="subscribeMessage"?result:void 0,storageId,callbackId:0,final:!0})}function handleMiniProgramNativeRoute(rawUrl){let nativePageUrl;try{nativePageUrl=new URL(rawUrl,location.href)}catch{return!1}let normalizedPathname=nativePageUrl.pathname.replace(/\/+$/,"")||"/",action=nativePageUrl.searchParams.get("action");if(action!=="navigateMiniProgram"&&action!=="subscribeMessage"||!config2.miniProgram?.nativeRoutes?.find(candidate=>(candidate.pathname.replace(/\/+$/,"")||"/")===normalizedPathname&&candidate.actions.includes(action)&&matchesHostSuffix(nativePageUrl.hostname,candidate.hostSuffixes)))return!1;let params={};nativePageUrl.searchParams.forEach((value,name)=>{params[name]=value});let storageId=nativePageUrl.searchParams.get("__storage_id");return handlePageVisibility(!0),showMiniProgramActionDialog(action,params,result=>finishMiniProgramNativeRoute(action,result,storageId),result=>finishMiniProgramNativeRoute(action,result,storageId)),!0}function handleMiniProgramPostMessage(data){let rules=config2.miniProgram?.messageRules;if(!rules?.length)return!1;let messages=Array.isArray(data)?data:[data],handled=!1;for(let value of messages){if(!value||typeof value!="object"||Array.isArray(value))continue;let message=value;if(typeof message.type!="string")continue;let rule=rules.find(candidate=>candidate.type===message.type&&matchesHostSuffix(location.hostname,candidate.hostSuffixes));rule&&(handled=!0,rule.action==="stageBackData"?(pendingMiniProgramBackData=message.data,hasPendingMiniProgramBackData=!0):rule.action==="closeAll"&&(isTop?requestCloseAll(message.data)||requestClose(message.data):window.top?.postMessage({source:SRC,type:"closeAll",data:message.data},"*")))}return handled}function matchesImagePickerScheme(url2){let lower=url2.toLowerCase();return config2.imagePicker?.schemes.some(scheme=>lower.startsWith(scheme))===!0}function handleMaybeScheme(url2){if(typeof url2!="string"||!url2||!/^[a-z][a-z0-9+.-]*:/i.test(url2)||/^(https?|about|blob|data|javascript):/i.test(url2))return!1;let mapped=mapScheme(url2);return mapped?(log3("scheme 映射为 H5 open:",url2,"→",mapped),requestOpen(decorateUrlWithFpt(mapped),0,!1)):log3("外部 scheme 已拦截(真机表现为唤端):",url2),!0}function handleResume(msg){let{data,storageId,callbackId,final,gotoEvent,silent}=msg;if(gotoEvent&&dispatchGotoEvent(data),callbackId&&callbacks[callbackId]){if(!silent)try{callbacks[callbackId]({backdata:data})}catch(e){console.error(TAG,"callbackCommand 执行失败",e)}final&&delete callbacks[callbackId]}if(data&&typeof data=="object"&&storageId)try{let d={...data};d.__$data=!0,d.__$storageId=String(storageId),localStorage.setItem("XPI_BACK_LISTENER_DATA_STORAGE",JSON.stringify(d))}catch{}simulatedPageHidden?handlePageVisibility(!1):dispatchActiveEvents()}function dispatchGotoEvent(data){if(data!==void 0)try{document.dispatchEvent(new CustomEvent("WV.GotoEvent",{detail:{data}}))}catch{}}function sendUserTrack(params){if(!params||typeof params!="object")return;let p=params,logkey=typeof p.logkey=="string"?p.logkey:"",gmkey=typeof p.gmkey=="string"?p.gmkey:typeof p.event=="string"?p.event:"",gokey=typeof p.gokey=="string"?p.gokey:"";if(!/^\/[0-9A-Za-z._/-]+$/.test(logkey)||!/^[0-9A-Za-z_-]+$/.test(gmkey))return;let pageWindow=w,aplus=pageWindow.goldlog??pageWindow.aplus;if(typeof aplus?.send!="function")return;let configuredHost=aplus.getMetaInfo?.("aplus-rhost-g"),host2=(typeof configuredHost=="string"?configuredHost:"gm.mmstat.com").replace(/^https?:\/\//i,"").replace(/^\/\//,"").split("/")[0];if(!(!host2||!/^[0-9A-Za-z.-]+$/.test(host2)))try{aplus.send(`//${host2}${logkey}`,`gmkey=${encodeURIComponent(gmkey)}&gokey=${gokey}&ts=${Date.now()}`,"GET")}catch{}}function readNetworkState(){let connection=navigator.connection;return navigator.onLine?connection?.type==="wifi"?"wifi":connection?.effectiveType??"unknown":"fail"}function networkTypeNumber(state){return{wifi:2,"slow-2g":3,"2g":3,"3g":4,"4g":5,"5g":6,fail:7}[state]??0}function calendarTimestamp(value){if(typeof value=="number"&&Number.isFinite(value))return value;if(typeof value!="string"||!value.trim())return null;let numeric=Number(value);if(Number.isFinite(numeric)&&numeric>0)return numeric;let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}function calendarEventFromParams(params){let p=params&&typeof params=="object"?params:{},stringValue=(...values)=>values.find(value=>typeof value=="string")??"";return{title:stringValue(p.calendar_title,p.title),startTime:calendarTimestamp(p.calendar_start_ms??p.start_time??p.calendar_start_datetime),endTime:calendarTimestamp(p.calendar_end_ms??p.end_time??p.calendar_end_datetime),url:stringValue(p.calendar_url,p.url),note:stringValue(p.calendar_note,p.note),location:stringValue(p.calendar_location,p.location)}}function readCalendarEvents(){try{let parsed=JSON.parse(localStorage.getItem(CALENDAR_STORAGE_KEY)??"[]");return Array.isArray(parsed)?parsed.filter(event=>event!==null&&typeof event=="object"&&typeof event.title=="string"):[]}catch{return[]}}function writeCalendarEvents(events){try{return localStorage.setItem(CALENDAR_STORAGE_KEY,JSON.stringify(events)),!0}catch{return!1}}function sameCalendarEvent(stored,candidate){return candidate.url?stored.url===candidate.url:!!candidate.title&&stored.title===candidate.title&&(candidate.startTime===null||stored.startTime===candidate.startTime)&&(candidate.endTime===null||stored.endTime===candidate.endTime)}function calendarEventResponse(event){return{title:event.title,start_time:event.startTime,end_time:event.endTime,url:event.url,note:event.note,location:event.location}}function dispatch(api,params,onSuccess,onFailure,callbackCommandFn){let succeed=value=>{onSuccess&&setTimeout(()=>onSuccess(value),0)},failed=reason=>{onFailure&&setTimeout(()=>onFailure(reason),0)},kind=classify(api),silent=config2.actions.silent?.includes(api)===!0;if(silent||log3("桥调用",api,`(${kind})`,params??""),kind==="open"||kind==="navigate"){let p=params&&typeof params=="object"?params:{},navigationData=p.data&&typeof p.data=="object"?p.data:void 0;if(kind==="navigate"&&navigationData?.type==="back"){isTop?requestCloseAll(navigationData.data,!0)||dispatchGotoEvent(navigationData.data):window.top?.postMessage({source:SRC,type:"closeAll",data:navigationData.data,gotoEvent:!0},"*"),succeed({});return}let url2=pickUrl(params);if(!url2){failed("missing url");return}if(matchesImagePickerScheme(url2)){openImagePicker(callbackCommandFn),succeed({});return}if(handleMiniProgramPaymentRoute(url2)){succeed({});return}if(handleMiniProgramNativeRoute(url2)){succeed({});return}let wd=p.useWebdialog===!0||p.useWebdialog==="true"||p.useWebdialog===1||p.useWebdialog==="1";requestOpen(decorateUrlWithFpt(url2),stashCallback(callbackCommandFn),wd,p),succeed({});return}if(kind==="closeAll"){isTop?requestCloseAll(void 0):window.top?.postMessage({source:SRC,type:"closeAll"},"*"),succeed({});return}if(kind==="closeBackData"){let p=params&&typeof params=="object"?params:{};requestClose(Object.prototype.hasOwnProperty.call(p,"backdata")?p.backdata:pickCloseData(p)),succeed({});return}if(kind==="close"){if(api==="navigateBack"&&hasPendingMiniProgramBackData){let data=pendingMiniProgramBackData;pendingMiniProgramBackData=void 0,hasPendingMiniProgramBackData=!1,requestClose(data)}else requestClose(pickCloseData(params));succeed({});return}if(kind==="postMessage"){let p=params&&typeof params=="object"?params:{},data=p.data??p;handleMiniProgramPostMessage(data)||sendAppMessage({kind:"message",data}),succeed({});return}if(kind==="notifySubscribe"){let p=params&&typeof params=="object"?params:{};if(typeof p.name!="string"||!p.name){failed("missing notification name");return}onSuccess&¬ificationListeners.set(p.name,onSuccess);return}if(kind==="notifyUnsubscribe"){let p=params&&typeof params=="object"?params:{};typeof p.name=="string"&¬ificationListeners.delete(p.name),succeed({});return}if(kind==="notifyPost"){let p=params&&typeof params=="object"?params:{};if(typeof p.name!="string"||!p.name){failed("missing notification name");return}sendAppMessage({kind:"notification",name:p.name,data:p.data}),succeed({});return}if(kind==="sharedFileRead"||kind==="sharedFileWrite"||kind==="sharedDataGet"||kind==="sharedDataSet"){requestContainerData(kind,params&&typeof params=="object"?params:{},succeed,failed);return}if(kind==="legacyBroadcastCreate"||kind==="legacyBroadcastPost"||kind==="legacyBroadcastClose"){requestContainerData(kind,params&&typeof params=="object"?params:{},succeed,failed);return}if(kind==="title"){let title=params&&typeof params=="object"?params.title??params.name:void 0;if(typeof title=="string"&&title){systemBars.markStateExplicit();try{document.title=title,syncSimulatedTitleBar()}catch{}isTop||window.top?.postMessage({source:SRC,type:"title",title},"*")}succeed({});return}if(kind==="navigationBar"){applyNavigationBarState(api,params),succeed({});return}if(kind==="statusBar"){applyStatusBarState(params),succeed({});return}if(kind==="systemInfo"){let model=config2.globals.__DEVICE_MODEL__||"iPhone";succeed({language:config2.language,model,systemVersion:config2.systemVersion,statusBarHeight:config2.statusBarHeight,platform:config2.platform,brand:config2.platform==="iOS"?"Apple":"Android",client_version:config2.globals.__APP_VERSION__??"",client_type:config2.clientType});return}if(kind==="mtop"){callMtop(params??{},onSuccess,onFailure);return}if(kind==="mtopStream"){callMtopStream(params??{},succeed,failed);return}if(kind==="kvGet"||kind==="kvSet"||kind==="kvDelete"){let p=params&&typeof params=="object"?params:{},key=typeof p.key=="string"?p.key:"";if(!key){failed("missing key");return}try{let storageKey=`__mearl_app_kv__:${key}`;if(kind==="kvGet"){let stored=localStorage.getItem(storageKey);stored!==null?succeed(stored):failed(JSON.stringify({ret:["HY_FAILED"],msg:"key not found"}))}else if(kind==="kvSet"){let value=typeof p.value=="string"?p.value:p.value===void 0?"":JSON.stringify(p.value);localStorage.setItem(storageKey,value),succeed({})}else localStorage.removeItem(storageKey),succeed({})}catch{failed(JSON.stringify({ret:["HY_FAILED"],msg:"kv storage unavailable"}))}return}if(kind==="pageContext"){succeed({pageContext:void 0});return}if(kind==="memoryGet"||kind==="memorySet"||kind==="memoryDelete"){let p=params&&typeof params=="object"?params:{},key=typeof p.key=="string"?p.key:"";if(!key){failed({error_message:"missing key"});return}try{let storageKey=`__mearl_app_memory__:${key}`;if(kind==="memoryGet"){let value=sessionStorage.getItem(storageKey);succeed(value===null?{}:{value})}else if(kind==="memorySet"){let value=typeof p.value=="string"?p.value:p.value===void 0?"":JSON.stringify(p.value);sessionStorage.setItem(storageKey,value),succeed({key,success:!0})}else sessionStorage.removeItem(storageKey),succeed({key,success:!0})}catch{failed({error_message:"memory cache unavailable"})}return}if(kind==="availabilityMap"){let p=params&&typeof params=="object"?params:{},channels=Array.isArray(p.data)?p.data.filter(value=>typeof value=="string"):[];succeed({res:"success",data:Object.fromEntries(channels.map(channel=>[channel,!1]))});return}if(kind==="userInfo"){let userId=readFirstUserCookie(["unb"]),userName=readFirstUserCookie(["_w_tb_nick","_nk_","snk","tracknick"]);callUserInfo({...userId&&{userId},...userName&&{userName}},succeed);return}if(kind==="networkInfo"){let state=readNetworkState();if(api==="WVNetwork.getNetworkType"){succeed({type:{wifi:"WIFI","slow-2g":"2G","2g":"2G","3g":"3G","4g":"4G"}[state]??"UNKNOWN"});return}if(config2.profile==="alipay"||config2.profile==="koubei"){succeed({networkAvailable:state!=="fail",networkType:{wifi:"WIFI","slow-2g":"2G","2g":"2G","3g":"3G","4g":"4G",fail:"NOTREACHABLE"}[state]??"UNKNOWN"});return}let type=networkTypeNumber(state);succeed({type,state:state==="slow-2g"?"2g":state});return}if(kind==="networkQualityMonitor"){let p=params&&typeof params=="object"?params:{},action=typeof p.action=="string"?p.action:"";if(action==="add_notify_network_quality"){if(!stopNetworkQualityMonitor){let notify=()=>{try{document.dispatchEvent(new CustomEvent("WV.NETWORK_TYPE_CHANGED",{detail:{new_network_type:networkTypeNumber(readNetworkState())}}))}catch{}},connection=navigator.connection;window.addEventListener("online",notify),window.addEventListener("offline",notify),connection?.addEventListener?.("change",notify),stopNetworkQualityMonitor=()=>{window.removeEventListener("online",notify),window.removeEventListener("offline",notify),connection?.removeEventListener?.("change",notify)}}succeed({});return}if(action==="remove_notify_network_quality"){stopNetworkQualityMonitor?.(),stopNetworkQualityMonitor=null,succeed({});return}failed({error_message:"unsupported network quality monitor action"});return}if(kind==="beaconRequest"){let url2=pickUrl(params);if(!url2){failed({error_message:"missing url"});return}try{let resolved=new URL(url2,location.href);if(resolved.protocol!=="http:"&&resolved.protocol!=="https:"){failed({error_message:"unsupported request protocol"});return}let image=new Image;image.referrerPolicy="no-referrer-when-downgrade",image.src=resolved.href,succeed({})}catch{failed({error_message:"invalid url"})}return}if(kind==="calendar"){let p=params&&typeof params=="object"?params:{},events=readCalendarEvents();if(api==="store_calendar_event"){let event=calendarEventFromParams(p);if(!event.title||event.startTime===null){failed({error_message:"calendar title and start time are required"});return}let next=events.filter(stored=>!sameCalendarEvent(stored,event));if(next.push(event),!writeCalendarEvents(next)){failed({error_message:"calendar storage unavailable"});return}succeed({success:!0});return}if(api==="remove_calendar_event"){let candidate=calendarEventFromParams(p),next=events.filter(stored=>!sameCalendarEvent(stored,candidate));if(!writeCalendarEvents(next)){failed({error_message:"calendar storage unavailable"});return}succeed({success:!0,removed:events.length-next.length});return}if(api==="check_batch_calendar"){let batch=Array.isArray(p.batch)?p.batch:[];succeed({batch:batch.map(item=>{let candidate=calendarEventFromParams(item);return{...item&&typeof item=="object"?item:{},success:events.some(stored=>sameCalendarEvent(stored,candidate))}})});return}let urls=Array.isArray(p.urls)?p.urls.filter(value=>typeof value=="string"):typeof p.url=="string"?[p.url]:[],titles=Array.isArray(p.calendar_titles)?p.calendar_titles.filter(value=>typeof value=="string"):typeof p.calendar_title=="string"?[p.calendar_title]:[],matched=events.filter(event=>(urls.length===0||urls.includes(event.url))&&(titles.length===0||titles.includes(event.title)));succeed({events:matched.map(calendarEventResponse)});return}if(kind==="geolocation"){if(!navigator.geolocation){failed({errorCode:2,errorMsg:"geolocation unavailable"});return}let locate=()=>navigator.geolocation.getCurrentPosition(position=>{let{latitude,longitude,accuracy,altitude,altitudeAccuracy,heading,speed}=position.coords;succeed({latitude,longitude,accuracy,altitude,altitudeAccuracy,heading,speed,timestamp:position.timestamp})},error48=>failed({errorCode:error48.code,errorMsg:error48.message}),{enableHighAccuracy:!1,timeout:1e4,maximumAge:3e5});navigator.permissions?.query?navigator.permissions.query({name:"geolocation"}).then(status=>{status.state==="granted"?locate():failed({errorCode:1,errorMsg:"location permission not granted"})}).catch(locate):locate();return}if(kind==="permission"){let p=params&&typeof params=="object"?params:{},action=typeof p.action=="string"?p.action:"",permission=typeof p.permission=="string"?p.permission:"",permissionFailed=message=>failed({error_code:-1,error_message:message});if(permission==="album"||permission==="MODIFY_AUDIO_SETTINGS"){action==="check"||action==="request"?succeed({}):permissionFailed("unsupported permission action");return}let browserPermission=permission==="mic"?"microphone":permission==="camera"?"camera":permission==="lbs"?"geolocation":"";if(!browserPermission){permissionFailed("unsupported permission");return}if(action==="check"&&navigator.permissions?.query){navigator.permissions.query({name:browserPermission}).then(status=>{status.state==="granted"?succeed({}):permissionFailed("permission not granted")}).catch(()=>permissionFailed("permission check failed"));return}if(action==="request"&&(permission==="mic"||permission==="camera")){if(!navigator.mediaDevices?.getUserMedia){permissionFailed("media permission unavailable");return}navigator.mediaDevices.getUserMedia({audio:permission==="mic",video:permission==="camera"}).then(stream=>{for(let track of stream.getTracks())track.stop();succeed({})}).catch(()=>permissionFailed("permission denied"));return}if(action==="request"&&permission==="lbs"&&navigator.geolocation){navigator.geolocation.getCurrentPosition(()=>succeed({}),()=>permissionFailed("permission denied"),{timeout:1e4});return}permissionFailed("unsupported permission action");return}if(kind==="prefetch"){let p=params&&typeof params=="object"?params:{},url2=typeof p.url=="string"?p.url:"";if(!url2){failed({code:-1,errorMsg:"url is empty"});return}let resolvedUrl;try{resolvedUrl=new URL(url2,location.href).href}catch{failed({code:-1,errorMsg:"invalid url"});return}if(!Array.from(document.querySelectorAll('link[rel="prefetch"]')).some(link=>link.href===resolvedUrl)){let link=document.createElement("link");link.rel="prefetch",link.href=url2,(document.head??document.documentElement).appendChild(link)}succeed({});return}if(kind==="fptTrack"){let p=params&&typeof params=="object"?params:{},action=typeof p.action=="string"?p.action:"",actionParams=p.params&&typeof p.params=="object"?p.params:{},key=typeof actionParams.key=="string"?actionParams.key:"";if(action==="setFpt"){let value=typeof actionParams.value=="string"?actionParams.value:"";if(!key||!value||!/^[0-9A-Za-z._-]+$/.test(key)||!/^[0-9A-Za-z._-]+$/.test(value)||`${key}(${value})`.length>100){failed({error_message:"invalid fpt key or value"});return}setFptEntry(fptEntries,key,value),persistFpt()}else action==="deleteFpt"&&key&&(fptEntries.delete(key),persistFpt());succeed({});return}if(kind==="previewFile"){let p=params&&typeof params=="object"?params:{},fileUrl=typeof p.file_url=="string"?p.file_url:"",remoteUrl=typeof p.file_remote_url=="string"?p.file_remote_url:"",url2=(fileUrl.startsWith("http")?fileUrl:remoteUrl)||fileUrl||remoteUrl;url2?(requestOpen(url2,0,!1),succeed({})):failed({code:-1,errorMsg:"file_url is empty"});return}if(kind==="toast"){let error48=showAppToast(params);error48?failed({error_message:error48}):succeed({});return}if(kind==="unsupportedNativeInput"){let containerType="";try{containerType=new URL(location.href).searchParams.get("containerType")??""}catch{}!unsupportedNativeInputNotified&&(containerType==="h5_dx"||containerType==="flutter_h5")&&(unsupportedNativeInputNotified=!0,showAppToast({message:"当前页面使用原生输入框,请移除 URL 中的 containerType 参数以正常操作",milliseconds:4e3})),succeed({});return}if(kind==="payment"){log3("桥调用支付,等待用户确认",api,params),showPaymentDialog(api,params,succeed,failed);return}if(kind==="userTrack"){sendUserTrack(params),succeed({});return}if(kind==="response"){succeed(config2.actions.responses?.[api]);return}if(kind==="noop"){succeed({});return}silent||log3("未覆盖桥方法,回调 failure(页面库将走 H5 兜底):",api),failed(NOT_IMPLEMENTED_PAYLOAD)}let MEGA_SUPPORTED_APIS={stdPop:["showWeex2","showWeex","showH5","changeSize","close"],broadcast:["addEventListener","dispatchEvent","removeEventListener"],kvStorage:["setItem","getItem","removeItem","getAllKeys","clear","getCurrentInfo","getCurrentInfoAndKeys"],LifeCycle:["addPageLifeCycleListener","removePageLifeCycleListener"],Container:["interceptPageClose","disableInterceptPageClose"],navigator:["openURL","close","replace","setSystemBackBlockListener","removeSystemBackBlockListener"],NavBar:["setTitle"],Router:["popPage"]};function isMegaApiSupported(ability,api){return typeof ability=="string"&&typeof api=="string"&&MEGA_SUPPORTED_APIS[ability]?.includes(api)===!0}function megaParams(value){return value&&typeof value=="object"&&!Array.isArray(value)?value:{}}function megaError(callback,statusCode,message){emitMegaCallback(callback,{statusCode,type:"result",data:{errorMessage:typeof message=="string"?message:String(message??"")}})}function cloneMegaDetail(value){if(value===void 0)return{success:!0,value:void 0};try{return{success:!0,value:JSON.parse(JSON.stringify(value))}}catch{return{success:!1}}}function megaSuccess(data={}){return{statusCode:0,type:"result",data}}function megaFailure(message){return{statusCode:500,type:"result",data:{errorMessage:message}}}function megaKVParams(params){return{bizId:typeof params.bizID=="string"?params.bizID:typeof params.bizId=="string"?params.bizId:"",key:typeof params.key=="string"?params.key:"",value:typeof params.value=="string"?params.value:null}}function megaStringByteLength(value){try{return typeof TextEncoder=="function"?new TextEncoder().encode(value).length:value.length}catch{return value.length}}function megaKVUsedSize(entries){let size=0;for(let value of entries.values())size+=megaStringByteLength(value);return size}function reportMegaKVMutation(operation,bizId,key="",value,onSuccess,onFailure){requestContainerData("megaKVMutation",{operation,bizId,key,...value===void 0?{}:{value}},()=>onSuccess?.(),reason=>{log3("KVStorage 容器同步失败:",reason),onFailure?.(reason)})}function completeMegaKVMutation(operation,bizId,key,value,synchronous,callback){let result=megaSuccess();return reportMegaKVMutation(operation,bizId,key,value,synchronous?void 0:()=>emitMegaCallback(callback,result),synchronous?void 0:reason=>emitMegaCallback(callback,megaFailure(String(reason??"container sync failed")))),synchronous?result:null}function executeMegaKVStorage(api,params,synchronous,callback){let{bizId,key,value}=megaKVParams(params);if(!bizId)return megaFailure("missing bizID");let entries=megaKVStorage.get(bizId)??new Map;if(api==="setItem"){if(!key)return megaFailure("missing key");if(value===null||value==="")return megaFailure("missing value");let previousSize=megaStringByteLength(entries.get(key)??"");return megaKVUsedSize(entries)-previousSize+megaStringByteLength(value)>MEGA_KV_TOTAL_SIZE?megaFailure("KVStorage quota exceeded"):(entries.set(key,value),megaKVStorage.set(bizId,entries),megaKVMutationVersion+=1,persistMegaKVStorage(),completeMegaKVMutation("set",bizId,key,value,synchronous,callback))}if(api==="getItem"){if(!key)return megaFailure("missing key");let result=entries.get(key)??"";return megaSuccess(synchronous?{result}:result)}if(api==="removeItem")return key?(entries.delete(key),entries.size===0&&megaKVStorage.delete(bizId),megaKVMutationVersion+=1,persistMegaKVStorage(),completeMegaKVMutation("remove",bizId,key,void 0,synchronous,callback)):megaFailure("missing key");if(api==="getAllKeys"){let result=Array.from(entries.keys());return megaSuccess(synchronous?{result}:result)}if(api==="clear")return megaKVStorage.delete(bizId),megaKVMutationVersion+=1,persistMegaKVStorage(),completeMegaKVMutation("clear",bizId,"",void 0,synchronous,callback);if(api==="getCurrentInfo"||api==="getCurrentInfoAndKeys"){let data={totalSize:MEGA_KV_TOTAL_SIZE,freeSize:Math.max(MEGA_KV_TOTAL_SIZE-megaKVUsedSize(entries),0)};return api==="getCurrentInfoAndKeys"&&(data.keys=Array.from(entries.keys())),megaSuccess(data)}return{statusCode:405,type:"result",data:{}}}function handleMegaLifeCycle(api,callback){if(api==="addPageLifeCycleListener"){callback&&megaLifeCycleListeners.add(callback),emitMegaCallback(callback,megaSuccess());return}if(api==="removePageLifeCycleListener"){let listeners=Array.from(megaLifeCycleListeners);megaLifeCycleListeners.clear(),emitMegaCallback(callback,megaSuccess());for(let listener of listeners)emitMegaCallback(listener,{statusCode:99,type:"finish",data:{}});return}megaError(callback,405,`LifeCycle.${api} is not supported`)}function handleMegaContainer(api,callback){if(api==="interceptPageClose"){callback&&megaPageCloseListeners.add(callback),emitMegaCallback(callback,megaSuccess());return}if(api==="disableInterceptPageClose"){let listeners=Array.from(megaPageCloseListeners);megaPageCloseListeners.clear(),emitMegaCallback(callback,megaSuccess());for(let listener of listeners)emitMegaCallback(listener,{statusCode:99,type:"finish",data:{}});return}megaError(callback,405,`Container.${api} is not supported`)}function megaNavigationUrl(params){let rawUrl=pickUrl(params);if(!rawUrl)return null;if(!params.extQuery||typeof params.extQuery!="object"||Array.isArray(params.extQuery))return rawUrl;try{let target=new URL(rawUrl,location.href);for(let[key,value]of Object.entries(params.extQuery))value!=null&&target.searchParams.set(key,String(value));return target.href}catch{return rawUrl}}function handleMegaNavigator(api,params,callback){if(api==="openURL"||api==="replace"){let url2=megaNavigationUrl(params);if(!url2){megaError(callback,500,"missing url");return}let callbackId=api==="openURL"&&callback?stashCallback(value=>{let backdata=value&&typeof value=="object"?value.backdata:void 0;emitMegaCallback(callback,{statusCode:1,type:"onResult",data:{result:!0,...backdata===void 0?{}:{data:backdata}}}),emitMegaCallback(callback,{statusCode:99,type:"finish",data:{}})}):0;requestOpen(url2,callbackId,!1,{...params,...api==="replace"?{__mearlReplace:!0}:{}}),emitMegaCallback(callback,megaSuccess());return}if(api==="close"){emitMegaCallback(callback,megaSuccess()),requestClose(void 0);return}if(api==="setSystemBackBlockListener"){megaSystemBackListener&&megaSystemBackListener!==callback&&emitMegaCallback(megaSystemBackListener,{statusCode:99,type:"finish",data:{}}),megaSystemBackListener=callback??null,emitMegaCallback(callback,megaSuccess());return}if(api==="removeSystemBackBlockListener"){let listener=megaSystemBackListener;megaSystemBackListener=null,emitMegaCallback(callback,megaSuccess()),listener&&emitMegaCallback(listener,{statusCode:99,type:"finish",data:{}});return}megaError(callback,405,`navigator.${api} is not supported`)}function handleMegaNavBar(api,params,callback){if(api!=="setTitle"){megaError(callback,405,`NavBar.${api} is not supported`);return}applyNavigationBarState(api,params),emitMegaCallback(callback,megaSuccess())}function handleMegaRouter(api,callback){if(api!=="popPage"){megaError(callback,405,`Router.${api} is not supported`);return}emitMegaCallback(callback,megaSuccess()),requestClose(void 0)}function handleMegaStdPop(api,params,callback){if(api==="showH5"||api==="showWeex2"||api==="showWeex"){let url2=pickUrl(params),popId=typeof params.popId=="string"?params.popId.trim():"";if(!url2||!popId){megaError(callback,500,url2?"missing popId":"missing url");return}let callbackId=stashCallback(value=>{let result=value&&typeof value=="object"&&"backdata"in value?value.backdata:void 0;emitMegaCallback(callback,{statusCode:1,type:"onClose",data:result}),emitMegaCallback(callback,{statusCode:99,type:"finish"})});requestOpen(url2,callbackId,!0,{...params,__mearlMegaPopId:popId}),emitMegaCallback(callback,{statusCode:0,type:"result",data:{}});return}if(api==="close"){let popId=typeof params.popId=="string"?params.popId.trim():"";if(!popId){megaError(callback,500,"missing popId");return}let cloned=cloneMegaDetail(params.result);if(!cloned.success){megaError(callback,500,"result is not serializable");return}requestContainerData("megaPopClose",{popId,result:cloned.value},()=>emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),reason=>megaError(callback,500,reason));return}if(api==="changeSize"){let popId=typeof params.popId=="string"?params.popId.trim():"";if(!popId){megaError(callback,500,"missing popId");return}requestContainerData("megaPopResize",{...params,popId},()=>emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),reason=>megaError(callback,500,reason));return}megaError(callback,405,`stdPop.${api} is not supported`)}function handleMegaBroadcast(api,params,callback){let bizId=megaBroadcastBizId(params.bizId),eventName=typeof params.eventName=="string"?params.eventName.trim():"";if(!eventName){megaError(callback,500,"missing eventName");return}if(api==="addEventListener"){if(!callback)return;let id=`mearl-mega-listener-${++megaListenerSeq}`;megaBroadcastListeners.set(id,{id,bizId,eventName,once:params.once===!0,callback}),emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),emitMegaCallback(callback,{statusCode:1,type:"onAdd",data:{listenerId:id}});return}if(api==="dispatchEvent"){let detail=cloneMegaDetail(params.detail);if(!detail.success){megaError(callback,500,"detail is not serializable");return}requestContainerData("megaBroadcast",{message:{kind:"megaBroadcast",bizId,eventName,detail:detail.value}},()=>emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),reason=>megaError(callback,500,reason));return}if(api==="removeEventListener"){let listenerId=typeof params.listenerId=="string"?params.listenerId:"",removed=[];for(let listener of Array.from(megaBroadcastListeners.values()))listener.bizId!==bizId||listener.eventName!==eventName||listenerId&&listener.id!==listenerId||(megaBroadcastListeners.delete(listener.id),removed.push(listener));emitMegaCallback(callback,{statusCode:0,type:"result",data:{}});for(let listener of removed)emitMegaCallback(listener.callback,{statusCode:99,type:"finish"});return}megaError(callback,405,`broadcast.${api} is not supported`)}function makeMegaBridge(){return{asyncCall:(ability,api,rawParams,callback)=>{let params=megaParams(rawParams);if(ability==="ability"&&api==="available"){emitMegaCallback(callback,{statusCode:0,type:isMegaApiSupported(params.ability,params.api)?"YES":"NO",data:{}});return}if(ability==="ability"&&api==="batchFinishTrace"){emitMegaCallback(callback,{statusCode:0,type:"result",data:{}});return}if(!isMegaApiSupported(ability,api)){megaError(callback,405,`${ability}.${api} is not supported`);return}if(ability==="stdPop")handleMegaStdPop(api,params,callback);else if(ability==="broadcast")handleMegaBroadcast(api,params,callback);else if(ability==="kvStorage"){let result=executeMegaKVStorage(api,params,!1,callback);result&&emitMegaCallback(callback,result)}else ability==="LifeCycle"?handleMegaLifeCycle(api,callback):ability==="Container"?handleMegaContainer(api,callback):ability==="navigator"?handleMegaNavigator(api,params,callback):ability==="NavBar"?handleMegaNavBar(api,params,callback):handleMegaRouter(api,callback)},syncCall:(ability,api,rawParams)=>{let params=megaParams(rawParams);return ability==="ability"&&api==="available"?{statusCode:0,type:isMegaApiSupported(params.ability,params.api)?"YES":"NO",data:{}}:ability==="kvStorage"&&isMegaApiSupported(ability,api)?executeMegaKVStorage(api,params,!0)??megaFailure("container sync pending"):{statusCode:405,type:"result",data:{}}}}}function makeBridge(style){if(style==="mega")return makeMegaBridge();if(style==="easybikeNative"){let callNative=rawPayload=>{let payload;try{payload=typeof rawPayload=="string"?JSON.parse(rawPayload):rawPayload??{}}catch{return}let classMap=typeof payload.classMap=="string"?payload.classMap:"",method=typeof payload.method=="string"?payload.method:"",callbackId=typeof payload.callbackId=="string"||typeof payload.callbackId=="number"?String(payload.callbackId):"",params;try{params=typeof payload.params=="string"?payload.params?JSON.parse(payload.params):{}:payload.params??{}}catch{params={}}let complete=(code,data,msg="")=>{let callback=resolveWindowFunction("callBack");callbackId&&callback&&callback({callbackId,code,data,msg})};dispatch(`${classMap}.${method}`,params,value=>complete(0,value),error48=>complete(1,void 0,typeof error48=="string"?error48:String(error48??"")))};return{postMessage:callNative,callNative}}if(style==="windvane")return{isAvailable:!0,version:"8.7.0",call:(cls,method,params,succ,fail)=>dispatch(`${cls}.${method}`,params,succ,fail)};if(style==="fliggy"||style==="alipay"||style==="callback"){let bridge={call:(api,params,succ,fail)=>{typeof params=="function"&&(fail=succ,succ=params,params=void 0);let p=params&&typeof params=="object"?params:{},successFn=succ??(typeof p.success_callback=="function"?p.success_callback:void 0)??(typeof p.successCallback=="function"?p.successCallback:void 0),failureFn=fail??(typeof p.fail_callback=="function"?p.fail_callback:void 0)??(typeof p.failure_callback=="function"?p.failure_callback:void 0)??(typeof p.failCallback=="function"?p.failCallback:void 0)??(typeof p.failureCallback=="function"?p.failureCallback:void 0);dispatch(api,p,res=>successFn?.(res),err=>{failureFn?failureFn(err):successFn?.({error:err})},p.callbackCommand??p.callback_command)},pushBack:(prefixOrApi,apiOrParams,paramsOrSucc,succ)=>{let api=prefixOrApi,params=apiOrParams,success2=paramsOrSucc;typeof apiOrParams=="string"&&(api=apiOrParams,params=paramsOrSucc,success2=succ);let p=params??{},successFn=(typeof success2=="function"?success2:void 0)??(typeof p.successCallback=="function"?p.successCallback:void 0);return dispatch(api,p,res=>successFn?.(res),void 0,p.callbackCommand??p.callback_command),bridge},sendUriScheme:uri=>(handleMaybeScheme(uri),bridge)};if(style==="fliggy"){let normalizedAppName=(config2.globals.__APP_NAME__??"").toUpperCase(),os12=config2.clientType==="iphone"?"ios":"android",isAliApp=name=>normalizedAppName===name.toUpperCase();Object.assign(bridge,{version:"1.0.21",device:{os:os12,OS:config2.platform,type:os12,version:config2.systemVersion,model:config2.globals.__DEVICE_MODEL__??""},platform:os12,isAliApp,isTmall:isAliApp("TM"),isTaobao:isAliApp("TB"),isAlipay:isAliApp("AP"),isAlitrip:isAliApp("LX"),isKoubei:isAliApp("KB"),isElm:isAliApp("ELMC"),isGaode:isAliApp("amap"),isUC:/UCBrowser/i.test(config2.userAgent),isWeibo:/Weibo/i.test(config2.userAgent),isWeixin:/MicroMessenger/i.test(config2.userAgent),isWindVane:config2.bridges.some(item=>item.style==="windvane"),isAlipayClient:/AlipayClient/i.test(config2.userAgent)})}return bridge}if(style==="btrip")return{call:(api,params)=>dispatch(api,params??{},void 0,void 0)};if(style==="invoke")return{invoke:(api,params)=>{let p=params??{};dispatch(api,p,p.success,p.fail)}};if(style==="callHandler")return{callHandler:(api,params)=>dispatch(api,params??{},void 0,void 0)};if(style==="amap")return{ready:cb=>cb?.(),send:(msg,cb)=>{let m=msg??{};dispatch(typeof m.action=="string"?m.action:"",m,res=>cb?.(res),err=>cb?.({error:err}))}};if(style==="didi")return{openPage:params=>dispatch("openPage",params??{},void 0,void 0),closePage:params=>dispatch("closePage",params??{},void 0,void 0)};if(style==="wechatMiniProgram"){let invoke2=(api,params)=>{let p=params&&typeof params=="object"?params:{};dispatch(api,p,value=>{p.success?.(value),p.complete?.(value)},error48=>{p.fail?.(error48),p.complete?.(error48)})};return{navigateTo:params=>invoke2("navigateTo",params),redirectTo:params=>invoke2("redirectTo",params),switchTab:params=>invoke2("switchTab",params),reLaunch:params=>invoke2("reLaunch",params),navigateBack:params=>invoke2("navigateBack",params),postMessage:params=>invoke2("postMessage",params),getEnv:callback=>{callback&&setTimeout(()=>callback({miniprogram:!0}),0)}}}return{}}function setGlobal(path25,value){let parts=path25.split("."),obj=w;for(let i=0;i<parts.length-1;i++){let cur=obj[parts[i]];(!cur||typeof cur!="object")&&(obj[parts[i]]={}),obj=obj[parts[i]]}obj[parts[parts.length-1]]=value}function setPersistentGlobal(path25,value){let parts=path25.split(".").filter(Boolean);if(parts.length<2){setGlobal(path25,value);return}let[rootKey,...nestedParts]=parts,isObjectLike=candidate=>typeof candidate=="object"&&candidate!==null||typeof candidate=="function",attachBridge=candidate=>{let root=isObjectLike(candidate)?candidate:{},obj=root;for(let index=0;index<nestedParts.length-1;index+=1){let key=nestedParts[index],child=obj[key];if(!isObjectLike(child))try{obj[key]={}}catch{return root}obj=obj[key]}let leaf=nestedParts[nestedParts.length-1];try{Object.defineProperty(obj,leaf,{configurable:!1,enumerable:!0,get:()=>value,set:()=>{}})}catch{try{obj[leaf]=value}catch{}}return root},currentRoot=attachBridge(w[rootKey]);try{Object.defineProperty(w,rootKey,{configurable:!1,enumerable:!0,get:()=>currentRoot,set:next=>{currentRoot=attachBridge(next)}})}catch{w[rootKey]=currentRoot}}if(config2.bridges.some(spec=>spec.style==="mega")){let hydrationVersion=megaKVMutationVersion;requestContainerData("megaKVSnapshot",{},value=>{let entries=value&&typeof value=="object"?value.entries:void 0;megaKVMutationVersion===hydrationVersion&&replaceMegaKVStorage(entries)},()=>{})}for(let spec of config2.bridges)try{let bridge=makeBridge(spec.style);spec.persistent?setPersistentGlobal(spec.global,bridge):setGlobal(spec.global,bridge)}catch(e){console.error(TAG,"桥安装失败:",spec.global,e)}return{mapScheme,handleMaybeScheme,handleAppMessage,handleNativeBack,handleResume,handlePageVisibility,applyRuntimeResponses}}function installAppProfileContainerStack(config2,environment,links){let{SRC,TAG,simulateSystemBars,ROOT_FRAME_NAME,LAYER_FRAME_NAME,isTop,isRootFrame,isLayerFrame,isContainerFrame,usesRootContainer,log:log3}=environment,{pageTransport}=links,initialLayerTitleBarState=url2=>links.getSystemBars().initialLayerTitleBarState(url2),resolvedTitleBarState=layer=>links.getSystemBars().resolvedTitleBarState(layer),parseReportedTitleBarState=value=>links.getSystemBars().parseReportedTitleBarState(value),createSimulatedNavigationBarView=(placement,onBack)=>links.getSystemBars().createNavigationBarView(placement,onBack),destroySimulatedNavigationBarView=view=>links.getSystemBars().destroyNavigationBarView(view),syncLayerViewport=(layer,state)=>links.getSystemBars().syncLayerViewport(layer,state),syncActiveSystemBars=()=>links.getSystemBars().syncActiveSystemBars(),syncSimulatedTitleBar=()=>links.getSystemBars().syncSimulatedTitleBar(),rootContainerActive=!1,rootFrame=null,rootBusinessUrl=location.href,webViewEnvironmentRequestSeq=0,simulatedPageHidden=!1,runtimeResponses=null;function syncSimulatorStateToWindow(target){target&&(runtimeResponses&&target.postMessage({source:SRC,type:"runtimeResponses",profile:config2.profile,responses:runtimeResponses},"*"),simulatedPageHidden&&target.postMessage({source:SRC,type:"simulatorVisibility",hidden:!0},"*"))}function startPreparedWebViewNavigation(frame,target,canCommit,registerCleanup){let insets=config2.safeAreaInsets??{top:config2.statusBarHeight,right:0,bottom:0,left:0};if(!usesRootContainer||!Object.values(insets).some(value=>value>0)){canCommit()&&(frame.src=target);return}let requestId=++webViewEnvironmentRequestSeq,settled=!1,fallbackTimer=0,cleanup=()=>{settled||(settled=!0,clearTimeout(fallbackTimer),window.removeEventListener("message",handleResponse),registerCleanup?.(null))},commitNavigation=fallbackReason=>{cleanup(),fallbackReason&&console.warn(TAG,"WebView 环境准备未完成,降级提交导航",{target,requestId,reason:fallbackReason}),canCommit()&&(frame.src=target)},handleResponse=event=>{if(event.source!==window||event.data?.source!=="mearl-content"||event.data?.type!=="APP_BRIDGE_PREPARE_WEBVIEW_RESPONSE"||event.data?.requestId!==requestId)return;let result=event.data.result;result?.success===!0?commitNavigation():commitNavigation(String(result?.error??"unknown preparation failure"))};registerCleanup?.(cleanup),window.addEventListener("message",handleResponse),fallbackTimer=setTimeout(()=>commitNavigation("preparation timed out after 500ms"),500);try{window.postMessage({source:SRC,type:"prepareWebView",requestId},"*")}catch(error48){commitNavigation(error48 instanceof Error?error48.message:String(error48))}}function installRootContainer(){if(!usesRootContainer||!/^https?:$/i.test(location.protocol))return;let shellRoot,frame;try{for(let cookie of config2.rootContainer?.initialCookies??[]){if(!cookie.name)continue;let parts=[`${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`,`Path=${cookie.path??"/"}`];cookie.domain&&parts.push(`Domain=${cookie.domain}`),document.cookie=parts.join("; ")}shellRoot=document.createElement("html");let shellHead=document.createElement("head"),charset=document.createElement("meta"),viewport=document.createElement("meta"),title=document.createElement("title"),shellBody=document.createElement("body");frame=document.createElement("iframe"),shellRoot.setAttribute("data-mearl-app-shell",""),shellBody.setAttribute("data-mearl-app-shell",""),charset.setAttribute("charset","utf-8"),viewport.name="viewport",viewport.content="width=device-width,initial-scale=1,viewport-fit=cover",shellHead.append(charset,viewport,title),shellRoot.append(shellHead,shellBody),shellRoot.style.cssText="width:100%;height:100%;margin:0;overflow:hidden;background:#fff;",shellBody.style.cssText="width:100%;height:100%;margin:0;overflow:hidden;background:#fff;",frame.name=ROOT_FRAME_NAME,frame.setAttribute("data-mearl-root-webview",config2.profile),frame.style.cssText="position:fixed;left:0;right:0;top:0;bottom:0;width:100%;height:100%;border:0;display:block;background:#fff;z-index:0;opacity:1;",frame.addEventListener("load",()=>{let committedSrc=frame.getAttribute("src");!committedSrc||committedSrc==="about:blank"||(syncSimulatorStateToWindow(frame.contentWindow),requestAnimationFrame(()=>{rootFrame!==frame||!frame.isConnected||(frame.setAttribute("data-mearl-webview-ready",""),syncSimulatedTitleBar())}))}),shellBody.appendChild(frame);let currentRoot=document.documentElement;currentRoot?document.replaceChild(shellRoot,currentRoot):document.appendChild(shellRoot)}catch(error48){console.warn(TAG,"根 WebView 容器创建失败,保留当前页面",error48),rootFrame=null;return}rootFrame=frame,rootContainerActive=!0;try{typeof window.stop=="function"&&window.stop()}catch(error48){console.warn(TAG,"停止外层文档加载失败,继续启动根 WebView",error48)}try{startPreparedWebViewNavigation(frame,rootBusinessUrl,()=>rootFrame===frame&&frame.isConnected)}catch(error48){console.warn(TAG,"根 WebView 环境准备启动失败,直接提交业务导航",error48),rootFrame===frame&&frame.isConnected&&(frame.src=rootBusinessUrl)}}installRootContainer();function normalizeProxyPathPrefix(prefix){let withLeadingSlash=prefix.startsWith("/")?prefix:`/${prefix}`;return withLeadingSlash.endsWith("/")?withLeadingSlash:`${withLeadingSlash}/`}function matchesProxyTarget(hostname3,suffixes){return suffixes.some(suffix=>hostname3===suffix||hostname3.endsWith(`.${suffix}`))}function mapLayerFrameUrl(url2){let proxy=config2.layerUrlProxy;if(!proxy||!location.hostname.startsWith(proxy.sourceHostPrefix))return url2;try{let target=new URL(url2,location.href);if(!/^https?:$/.test(target.protocol))return url2;let prefix=normalizeProxyPathPrefix(proxy.pathPrefix);if(target.hostname===location.hostname){if(target.pathname.startsWith(prefix))return url2;let derivedHost=location.pathname.startsWith(prefix)?location.pathname.slice(prefix.length).split("/")[0]:proxy.defaultTargetHost;return!derivedHost||!matchesProxyTarget(derivedHost,proxy.targetHostSuffixes)?url2:`${location.origin}${prefix}${derivedHost}${target.pathname}${target.search}${target.hash}`}return matchesProxyTarget(target.hostname,proxy.targetHostSuffixes)?`${location.origin}${prefix}${target.host}${target.pathname}${target.search}${target.hash}`:url2}catch{return url2}}function restoreLayerBusinessUrl(url2){let proxy=config2.layerUrlProxy;if(!proxy)return url2;try{let current=new URL(url2,location.href),prefix=normalizeProxyPathPrefix(proxy.pathPrefix);if(current.origin!==location.origin||!current.pathname.startsWith(prefix))return url2;let rest=current.pathname.slice(prefix.length),slash=rest.indexOf("/"),host=slash===-1?rest:rest.slice(0,slash);if(!host)return url2;let hostname3=new URL(`${current.protocol}//${host}`).hostname;if(!matchesProxyTarget(hostname3,proxy.targetHostSuffixes))return url2;let pathname=slash===-1?"/":rest.slice(slash);return`${current.protocol}//${host}${pathname}${current.search}${current.hash}`}catch{return url2}}let ANIM_MS=config2.animationMs??300;function boolParam(value,fallback){return value===!0||value===1||value==="1"||value==="true"?!0:value===!1||value===0||value==="0"||value==="false"?!1:value===""?!0:fallback}function numberParam(value,fallback,min,max){let parsed=typeof value=="number"?value:Number(value);return Number.isFinite(parsed)?Math.min(Math.max(parsed,min),max):fallback}function resolveOverlayPresentation(url2,params,explicitWebdialog){let query=null;try{query=new URL(url2,location.href).searchParams}catch{}let records=[],addRecord=value=>{value&&typeof value=="object"&&!Array.isArray(value)&&records.push(value)};addRecord(params?.pageParams),addRecord(params?.page_params),addRecord(params?.popConfig),addRecord(params?.data),addRecord(params?.param),addRecord(params);let read=key=>{for(let record2 of records)if(Object.prototype.hasOwnProperty.call(record2,key))return record2[key];return query?.has(key)?query.get(key):void 0},protocol=config2.overlay;if(!explicitWebdialog&&(!protocol||!boolParam(read(protocol.enabledParam),!1)))return null;let configuredTopRatio=protocol?read(protocol.topRatioParam):void 0,configuredHeightRatio=protocol?.heightRatioParam?read(protocol.heightRatioParam):void 0,configuredMaxHeight=read("maxHeight")??configuredHeightRatio,defaultTopRatio=protocol?.defaultTopRatio??.2;return{topRatio:configuredTopRatio!==void 0?numberParam(configuredTopRatio,defaultTopRatio,0,1):configuredMaxHeight!==void 0?1-numberParam(configuredMaxHeight,1-defaultTopRatio,0,1):defaultTopRatio,widthRatio:numberParam(read("maxWidth"),1,0,1),radius:numberParam((protocol?read(protocol.radiusParam):void 0)??read("cornerRadius"),protocol?.defaultRadius??0,0,50),maskAlpha:numberParam(protocol?read(protocol.maskAlphaParam):void 0,protocol?.defaultMaskAlpha??.3,0,1),tapClose:boolParam((protocol?read(protocol.tapCloseParam):void 0)??read("tapEnable"),protocol?.defaultTapClose??!0)}}function requestsPopBeforeOpen(url2,params){if(params?.__mearlReplace===!0)return!0;let key=config2.popBeforeOpenParam;if(!key)return!1;let records=[params?.pageParams,params?.page_params,params?.data,params?.param,params];for(let value of records){if(!value||typeof value!="object"||Array.isArray(value))continue;let record2=value;if(Object.prototype.hasOwnProperty.call(record2,key))return boolParam(record2[key],!1)}try{let query=new URL(url2,location.href).searchParams;return query.has(key)&&boolParam(query.get(key),!1)}catch{return!1}}let layers=[],forwardStack=[],layerSeq=0,enteringLayerCount=0,closingLayerCount=0,explicitLayerTitleBarStates=new Map,rootScrollStyles=null,pendingClose=null,nativeBackRequestSeq=0,pendingNativeBack=null,containerDataRequestSeq=0,containerDataCallbacks=new Map,sharedFiles=new Map,sharedData=new Map,legacyBroadcastChannels=new Set,MEGA_KV_STORAGE_KEY=`__mearl_mega_kv__:${config2.profile}`;function readMegaKVStorage(){let storage=new Map;try{let parsed=JSON.parse(localStorage.getItem(MEGA_KV_STORAGE_KEY)??"{}");if(!parsed||typeof parsed!="object"||Array.isArray(parsed))return storage;for(let[bizId,rawEntries]of Object.entries(parsed)){if(!rawEntries||typeof rawEntries!="object"||Array.isArray(rawEntries))continue;let entries=new Map;for(let[key,value]of Object.entries(rawEntries))typeof value=="string"&&entries.set(key,value);storage.set(bizId,entries)}}catch{}return storage}let megaKVStorage=readMegaKVStorage();function megaKVSnapshot(){let snapshot={};for(let[bizId,values]of megaKVStorage)snapshot[bizId]=Object.fromEntries(values);return snapshot}function persistMegaKVStorage(){try{localStorage.setItem(MEGA_KV_STORAGE_KEY,JSON.stringify(megaKVSnapshot()))}catch{}}let PENDING_CLOSE_TIMEOUT_MS=400,pendingHistoryDepth=null;function clearPendingClose(){pendingClose&&(clearTimeout(pendingClose.timer),pendingClose=null)}function clearPendingNativeBack(){pendingNativeBack&&(clearTimeout(pendingNativeBack.timer),pendingNativeBack=null)}function clearPendingHistoryDepth(){pendingHistoryDepth&&(clearTimeout(pendingHistoryDepth.timer),pendingHistoryDepth=null)}function syncHistoryAfterDirectClose(){clearPendingHistoryDepth();let depth=layers.length,timer=setTimeout(()=>{pendingHistoryDepth=null,console.warn(TAG,"WebView 已出栈,但浏览器历史未在预期时间内同步",{depth})},PENDING_CLOSE_TIMEOUT_MS);pendingHistoryDepth={depth,timer},history.back()}function armPendingClose(data,retries){clearPendingClose();let timer=setTimeout(()=>{pendingClose=null,log3("close 未等到 popstate,直接关栈顶兜底"),closeToDepth(Math.max(layers.length-1,0),data,!0)},PENDING_CLOSE_TIMEOUT_MS);pendingClose={data,retries,timer},history.back()}function parseStorageId(url2){try{return new URL(url2,location.href).searchParams.get("__storage_id")}catch{return null}}function titleBarStateCacheKey(url2){try{let parsed=new URL(url2,location.href);return parsed.hash="",parsed.href}catch{return url2}}function cacheExplicitTitleBarState(layer,state){explicitLayerTitleBarStates.set(titleBarStateCacheKey(layer.entryUrl),state),explicitLayerTitleBarStates.set(titleBarStateCacheKey(layer.url),state)}function readDepth(state){if(state&&typeof state=="object"){let d=state.__mearl_layer__;if(typeof d=="number")return d}return null}function mapUrlForSync(url2){let suffixes=config2.urlSyncHostSuffixes??[];try{let u=new URL(url2,location.href);if(!/^https?:$/.test(u.protocol)||!(suffixes.length===0||suffixes.some(s=>u.host===s||u.host.endsWith(`.${s}`))))return;if(u.origin===location.origin)return u.pathname+u.search+u.hash;let proxy=config2.layerUrlProxy;return proxy&&location.hostname.startsWith(proxy.sourceHostPrefix)&&matchesProxyTarget(u.hostname,proxy.targetHostSuffixes)?`${normalizeProxyPathPrefix(proxy.pathPrefix)}${u.host}${u.pathname}${u.search}${u.hash}`:u.pathname+u.search+u.hash}catch{return}}function createLayerEl(overlay,id){let el=document.createElement("div");el.setAttribute("data-mearl-layer",String(id)),el.style.cssText=`position:fixed;inset:0;z-index:${2147483e3+id%100*2};`;let frame=document.createElement("iframe");if(frame.name=LAYER_FRAME_NAME,frame.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-modals allow-downloads allow-popups"),frame.style.cssText="position:absolute;inset:0;width:100%;height:100%;border:0;display:block;background:#fff;z-index:0;opacity:1;",overlay){el.style.pointerEvents="none";let mask=document.createElement("div");mask.style.cssText=`position:absolute;inset:0;background:rgba(0,0,0,${overlay.maskAlpha});opacity:0;pointer-events:auto;`;let sheet=document.createElement("div"),width=overlay.widthRatio*100,left=(1-overlay.widthRatio)/2*100;return sheet.style.cssText=`position:absolute;left:${left}%;right:auto;bottom:0;width:${width}%;height:${(1-overlay.topRatio)*100}%;background:#fff;border-radius:${overlay.radius}px ${overlay.radius}px 0 0;overflow:hidden;pointer-events:auto;`,sheet.appendChild(frame),el.appendChild(mask),el.appendChild(sheet),{el,frame,animEl:sheet,mask}}return el.style.background="#fff",el.appendChild(frame),{el,frame,animEl:el,mask:null}}function setLayerInteractive(layer,interactive){layer.frame.style.pointerEvents=interactive?"":"none",layer.titleBarView&&(layer.titleBarView.root.style.pointerEvents=interactive?"":"none"),interactive?(layer.frame.removeAttribute("inert"),layer.frame.removeAttribute("aria-hidden"),layer.frame.removeAttribute("tabindex")):(layer.frame.setAttribute("inert",""),layer.frame.setAttribute("aria-hidden","true"),layer.frame.setAttribute("tabindex","-1"),layer.frame.blur()),layer.overlay?(layer.el.style.pointerEvents="none",layer.animEl.style.pointerEvents=interactive?"auto":"none",layer.mask&&(layer.mask.style.pointerEvents=interactive?"auto":"none")):layer.el.style.pointerEvents=interactive?"":"none"}function setRootFrameInteractive(interactive){rootFrame&&(rootFrame.style.pointerEvents=interactive?"":"none",interactive?(rootFrame.removeAttribute("inert"),rootFrame.removeAttribute("aria-hidden"),rootFrame.removeAttribute("tabindex")):(rootFrame.setAttribute("inert",""),rootFrame.setAttribute("aria-hidden","true"),rootFrame.setAttribute("tabindex","-1"),rootFrame.blur()))}function blockClosingLayerInteractions(layer){setLayerInteractive(layer,!1),layer.el.style.pointerEvents="auto"}function syncRootScrollLock(locked){let body=document.body;if(locked&&!rootScrollStyles){rootScrollStyles={html:document.documentElement.style.overflow,body:body?.style.overflow??null},document.documentElement.style.overflow="hidden",body&&(body.style.overflow="hidden");return}!locked&&rootScrollStyles&&(document.documentElement.style.overflow=rootScrollStyles.html,body&&rootScrollStyles.body!==null&&(body.style.overflow=rootScrollStyles.body),rootScrollStyles=null)}function syncLayerInteractivity(){let activeLayer=closingLayerCount===0&&enteringLayerCount===0?layers[layers.length-1]:void 0;for(let layer of layers)setLayerInteractive(layer,layer===activeLayer),!activeLayer&&layer===layers[layers.length-1]&&(layer.el.style.pointerEvents="auto");setRootFrameInteractive(layers.length===0&&enteringLayerCount===0&&closingLayerCount===0),syncRootScrollLock(layers.length>0||enteringLayerCount>0||closingLayerCount>0)}function finishLayerEntry(layer){layer.entering&&(layer.entering=!1,layer.enterTimer!==null&&clearTimeout(layer.enterTimer),layer.enterTimer=null,layer.enterTransitionEnd&&(layer.animEl.removeEventListener("transitionend",layer.enterTransitionEnd),layer.enterTransitionEnd=null),enteringLayerCount=Math.max(enteringLayerCount-1,0),syncLayerInteractivity())}function animateIn(layer){let t=layer.animEl;if(t.style.transform=layer.overlay?"translateY(100%)":"translateX(100%)",t.offsetWidth,t.style.transition=`transform ${ANIM_MS}ms ease`,t.style.transform="translate(0px, 0px)",layer.mask&&(layer.mask.style.transition=`opacity ${ANIM_MS}ms ease`,layer.mask.style.opacity="1"),ANIM_MS<=0){finishLayerEntry(layer);return}layer.enterTransitionEnd=event=>{event.target===t&&event.propertyName==="transform"&&finishLayerEntry(layer)},t.addEventListener("transitionend",layer.enterTransitionEnd),layer.enterTimer=setTimeout(()=>finishLayerEntry(layer),ANIM_MS+60)}function animateOut(layer,done){let t=layer.animEl;if(ANIM_MS<=0){t.style.transform=layer.overlay?"translateY(100%)":"translateX(100%)",layer.mask&&(layer.mask.style.opacity="0"),setTimeout(done,0);return}let settled=!1,fallbackTimer=0,finish=()=>{settled||(settled=!0,t.removeEventListener("transitionend",onTransitionEnd),clearTimeout(fallbackTimer),done())},onTransitionEnd=event=>{event.target===t&&event.propertyName==="transform"&&finish()};t.addEventListener("transitionend",onTransitionEnd),t.style.transition=`transform ${ANIM_MS}ms ease`,t.style.transform=layer.overlay?"translateY(100%)":"translateX(100%)",layer.mask&&(layer.mask.style.opacity="0"),fallbackTimer=setTimeout(finish,ANIM_MS+60)}function startLayerNavigation(layer,target){startPreparedWebViewNavigation(layer.frame,target,()=>!layer.closing&&layer.el.isConnected,cleanup=>{layer.navigationPreparationCleanup=cleanup})}function setPageVisibility(target,hidden){if(target===window){links.getBridgeProtocol().handlePageVisibility(hidden);return}try{target.postMessage({source:SRC,type:"simulatorVisibility",hidden},"*")}catch{}}function openLayer(url2,callbackId,overlay,openerWin,pushHistory,popId=null){clearPendingClose();let target=url2;if(!/^https?:/i.test(target)){let mapped=links.getBridgeProtocol().mapScheme(target);if(!mapped)return log3("open 失败,scheme 未映射:",url2),null;target=mapped}location.protocol==="https:"&&target.startsWith("http:")&&(target="https:"+target.slice(5));let presentation=overlay??resolveOverlayPresentation(target,void 0,!1);log3("open →",presentation?"(webdialog) ":"",target);let parts=createLayerEl(presentation,++layerSeq),restoredTitleBarState=explicitLayerTitleBarStates.get(titleBarStateCacheKey(target)),layer={id:layerSeq,win:parts.frame.contentWindow,frame:parts.frame,entryUrl:target,url:target,overlay:presentation,openerWin,callbackId,storageId:parseStorageId(target),popId,el:parts.el,animEl:parts.animEl,mask:parts.mask,entering:!0,enterTimer:null,enterTransitionEnd:null,closing:!1,navigationPreparationCleanup:null,titleBarState:restoredTitleBarState??initialLayerTitleBarState(target),titleBarStateExplicit:restoredTitleBarState!==void 0,titleBarStateReady:restoredTitleBarState!==void 0,titleBarView:null};if(popId&&layer.el.setAttribute("data-mearl-pop-id",popId),layer.mask&&presentation?.tapClose&&layer.mask.addEventListener("click",()=>requestOverlayClose(layer)),!presentation&&simulateSystemBars&&config2.titleBar&&(layer.titleBarView=createSimulatedNavigationBarView("layer",()=>requestNativeBack()),layer.titleBarView.root.setAttribute("data-mearl-layer-titlebar",String(layer.id)),parts.el.appendChild(layer.titleBarView.root)),layers.push(layer),setPageVisibility(openerWin,!0),enteringLayerCount+=1,syncLayerViewport(layer,layer.titleBarState),syncLayerInteractivity(),parts.frame.addEventListener("load",()=>{layer.win=parts.frame.contentWindow,parts.frame.name=LAYER_FRAME_NAME;let committedSrc=parts.frame.getAttribute("src");!committedSrc||committedSrc==="about:blank"||(syncSimulatorStateToWindow(parts.frame.contentWindow),requestAnimationFrame(()=>{layer.titleBarStateReady||layer.closing||!layer.el.isConnected||(layer.titleBarStateReady=!0,syncLayerViewport(layer,resolvedTitleBarState(layer)))}))}),(document.body??document.documentElement).appendChild(parts.el),layer.win=parts.frame.contentWindow,startLayerNavigation(layer,mapLayerFrameUrl(target)),animateIn(layer),pushHistory){forwardStack.length=0;try{history.pushState({__mearl_layer__:layers.length},"",mapUrlForSync(target))}catch{}}return layer}function replaceLayer(sourceLayer,url2,callbackId,overlay,popId=null){if(sourceLayer.closing||layers[layers.length-1]!==sourceLayer){openLayer(url2,callbackId,overlay,sourceLayer.win??window,!0,popId);return}let replacement=openLayer(url2,callbackId,overlay,sourceLayer.openerWin,!1,popId);if(!replacement)return;sourceLayer.navigationPreparationCleanup?.(),sourceLayer.navigationPreparationCleanup=null,sourceLayer.entering&&(sourceLayer.entering=!1,enteringLayerCount=Math.max(enteringLayerCount-1,0),sourceLayer.enterTimer!==null&&clearTimeout(sourceLayer.enterTimer),sourceLayer.enterTransitionEnd&&sourceLayer.animEl.removeEventListener("transitionend",sourceLayer.enterTransitionEnd));let sourceIndex=layers.indexOf(sourceLayer);sourceIndex>=0&&layers.splice(sourceIndex,1),destroySimulatedNavigationBarView(sourceLayer.titleBarView),sourceLayer.el.remove(),forwardStack.length=0,syncLayerInteractivity(),syncActiveSystemBars();try{history.replaceState({__mearl_layer__:layers.length},"",mapUrlForSync(replacement.url))}catch{}}function closeLayer(layer,data,final,gotoEvent=!1,resumeOpener=!0,silent=!1){if(layer.closing)return;layer.navigationPreparationCleanup?.(),layer.navigationPreparationCleanup=null,layer.entering&&(layer.entering=!1,enteringLayerCount=Math.max(enteringLayerCount-1,0),layer.enterTimer!==null&&clearTimeout(layer.enterTimer),layer.enterTimer=null,layer.enterTransitionEnd&&(layer.animEl.removeEventListener("transitionend",layer.enterTransitionEnd),layer.enterTransitionEnd=null)),layer.closing=!0;let idx=layers.indexOf(layer);idx>=0&&layers.splice(idx,1),closingLayerCount+=1,blockClosingLayerInteractions(layer),syncLayerInteractivity(),syncActiveSystemBars(),final?forwardStack.length=0:forwardStack.push({url:layer.url,overlay:layer.overlay,openerWin:layer.openerWin,callbackId:layer.callbackId,storageId:layer.storageId,popId:layer.popId}),log3("close ←",layer.url,data===void 0?"":data),animateOut(layer,()=>{if(destroySimulatedNavigationBarView(layer.titleBarView),layer.el.remove(),closingLayerCount=Math.max(closingLayerCount-1,0),syncLayerInteractivity(),syncActiveSystemBars(),!!resumeOpener)if(layer.openerWin===window)links.getBridgeProtocol().handleResume({data,storageId:layer.storageId,callbackId:layer.callbackId,final,gotoEvent,silent});else try{layer.openerWin.postMessage({source:SRC,type:"resume",data,storageId:layer.storageId,callbackId:layer.callbackId,final,gotoEvent,silent},"*")}catch{}})}function closeToDepth(depth,data,final){for(;layers.length>depth;){let revealsTarget=layers.length===depth+1;closeLayer(layers[layers.length-1],revealsTarget?data:void 0,final,!1,revealsTarget)}}function closeAllLayers(data,gotoEvent=!1){let depth=layers.length;for(;layers.length>0;){let isRootmostLayer=layers.length===1;closeLayer(layers[layers.length-1],isRootmostLayer?data:void 0,!0,isRootmostLayer&&gotoEvent,isRootmostLayer)}if(depth>0)try{history.go(-depth)}catch{}return depth>0}function requestOverlayClose(layer){if(!(layer.closing||layers[layers.length-1]!==layer)){if(!config2.overlay?.silentTapClose){for(let selector of config2.overlay?.tapCloseSelectors??[])try{let control=layer.frame.contentDocument?.querySelector(selector);if(typeof control?.click!="function")continue;control.click();return}catch{}requestCloseOnTop(void 0);return}pendingClose||pendingHistoryDepth||(closeLayer(layer,void 0,!0,!1,!0,!0),syncHistoryAfterDirectClose())}}function forwardToDepth(depth){for(;layers.length<depth&&forwardStack.length>0;){let entry=forwardStack.pop();openLayer(entry.url,entry.callbackId,entry.overlay,entry.openerWin,!1,entry.popId)}}function requestCloseOnTop(data){if(layers.length===0){history.back();return}if(rootContainerActive){closeLayer(layers[layers.length-1],data,!0),syncHistoryAfterDirectClose();return}armPendingClose(data,8)}function isActiveBusinessWindow(target){let topLayer=layers[layers.length-1];return topLayer?topLayer.frame.contentWindow===target:rootFrame?rootFrame.contentWindow===target:target===window}function finishNativeBack(requestId,target,handled){pendingNativeBack?.requestId!==requestId||pendingNativeBack.target!==target||(clearPendingNativeBack(),!handled&&isActiveBusinessWindow(target)&&requestCloseOnTop(void 0))}function requestNativeBack(){if(!isTop||pendingNativeBack)return;let target=layers[layers.length-1]?.frame.contentWindow??rootFrame?.contentWindow??window;if(!target||target===window){links.getBridgeProtocol().handleNativeBack()||requestCloseOnTop(void 0);return}let requestId=++nativeBackRequestSeq,timer=setTimeout(()=>finishNativeBack(requestId,target,!1),120);pendingNativeBack={requestId,target,timer};try{target.postMessage({source:SRC,type:"nativeBack",requestId},"*")}catch{finishNativeBack(requestId,target,!1)}}function layerForWindow(source){if(source)for(let layer of layers){if(layer.win===source)return layer;let currentWindow=layer.frame.contentWindow;if(currentWindow&¤tWindow===source)return layer.win=currentWindow,layer}}if(isTop){if(!rootContainerActive){let rawPushState=history.pushState.bind(history),rawReplaceState=history.replaceState.bind(history),withDepth=state=>state==null?{__mearl_layer__:layers.length}:typeof state=="object"&&!Array.isArray(state)?{...state,__mearl_layer__:layers.length}:state;try{history.pushState=function(...args){rawPushState(withDepth(args[0]),args[1],args[2])},history.replaceState=function(...args){rawReplaceState(withDepth(args[0]),args[1],args[2])}}catch{}}try{readDepth(history.state)===null&&history.replaceState({__mearl_layer__:0},"")}catch{}window.addEventListener("popstate",e=>{let depth=readDepth(e.state);if(pendingHistoryDepth){let expectedDepth=pendingHistoryDepth.depth;if(clearPendingHistoryDepth(),depth===expectedDepth)return;console.warn(TAG,"浏览器历史深度与 WebView 出栈事务不一致",{expectedDepth,actualDepth:depth})}if(rootContainerActive){if(depth===null)return;depth<layers.length?closeToDepth(depth,void 0,!1):depth>layers.length&&forwardToDepth(depth);return}if(pendingClose){if(depth!==null&&depth<layers.length){let{data}=pendingClose;clearPendingClose(),closeToDepth(depth,data,!0)}else if(pendingClose.retries>0)armPendingClose(pendingClose.data,pendingClose.retries-1);else{let{data}=pendingClose;clearPendingClose(),closeToDepth(layers.length-1,data,!0)}return}depth!==null&&(depth<layers.length?closeToDepth(depth,void 0,!1):depth>layers.length&&forwardToDepth(depth))})}function broadcastAppMessage(message){links.getBridgeProtocol().handleAppMessage(message);let targets=[rootFrame?.contentWindow??null,...layers.filter(layer=>!layer.closing).map(layer=>layer.frame.contentWindow)];for(let target of targets)if(!(!target||target===window))try{target.postMessage({source:SRC,type:"appMessage",message},"*")}catch{}}function closeMegaPop(popId,data){let index=layers.findIndex(layer=>layer.popId===popId&&!layer.closing);if(index<0)return!1;let closingDepth=layers.length-index;closeToDepth(index,data,!0);try{history.go(-closingDepth)}catch{}return!0}function resizeMegaPop(popId,params){let layer=layers.find(candidate=>candidate.popId===popId&&!candidate.closing);if(!layer?.overlay)return!1;if(params.maxHeight!==void 0){let maxHeight=numberParam(params.maxHeight,1-layer.overlay.topRatio,0,1);layer.overlay.topRatio=1-maxHeight,layer.animEl.style.height=`${maxHeight*100}%`}if(params.maxWidth!==void 0){let maxWidth=numberParam(params.maxWidth,1,0,1);layer.overlay.widthRatio=maxWidth,layer.animEl.style.width=`${maxWidth*100}%`,layer.animEl.style.left=`${(1-maxWidth)/2*100}%`,layer.animEl.style.right="auto"}return params.animated===!0&&(layer.animEl.style.transition="height 200ms ease, width 200ms ease, left 200ms ease"),!0}function executeContainerData(action,params){if(action==="sharedFileRead"||action==="sharedFileWrite"){let fileName=typeof params.fileName=="string"?params.fileName:"";if(!fileName)return{success:!1,value:"missing fileName"};if(action==="sharedFileRead")return{success:!0,value:{data:sharedFiles.get(fileName)??""}};let data=typeof params.data=="string"?params.data:String(params.data??"");return sharedFiles.set(fileName,data),{success:!0,value:{}}}if(action==="sharedDataGet"){let keys=Array.isArray(params.keys)?params.keys.filter(key=>typeof key=="string"):[],data={};for(let key of keys)sharedData.has(key)&&(data[key]=sharedData.get(key));return{success:!0,value:{data}}}if(action==="sharedDataSet"){if(!params.data||typeof params.data!="object"||Array.isArray(params.data))return{success:!1,value:"missing shared data"};for(let[key,value]of Object.entries(params.data))value==null?sharedData.delete(key):sharedData.set(key,value);return{success:!0,value:{}}}if(action==="megaBroadcast")return!params.message||typeof params.message!="object"||Array.isArray(params.message)?{success:!1,value:"missing broadcast message"}:(broadcastAppMessage(params.message),{success:!0,value:{}});if(action==="megaKVSnapshot")return{success:!0,value:{entries:megaKVSnapshot()}};if(action==="megaKVMutation"){let operation=typeof params.operation=="string"?params.operation:"",bizId=typeof params.bizId=="string"?params.bizId:"";if(!bizId)return{success:!1,value:"missing bizID"};let key=typeof params.key=="string"?params.key:"";if((operation==="set"||operation==="remove")&&!key)return{success:!1,value:"missing key"};if(operation==="set"){if(typeof params.value!="string")return{success:!1,value:"missing value"};let entries=megaKVStorage.get(bizId)??new Map;entries.set(key,params.value),megaKVStorage.set(bizId,entries)}else if(operation==="remove"){let entries=megaKVStorage.get(bizId);entries?.delete(key),entries?.size===0&&megaKVStorage.delete(bizId)}else if(operation==="clear")megaKVStorage.delete(bizId);else return{success:!1,value:"unsupported KVStorage operation"};return persistMegaKVStorage(),broadcastAppMessage({kind:"megaKVStorage",operation,bizId,key,value:params.value}),{success:!0,value:{}}}if(action==="legacyBroadcastCreate"){let instanceId=typeof params.instanceId=="string"?params.instanceId:"";return instanceId?(legacyBroadcastChannels.add(instanceId),{success:!0,value:{}}):{success:!1,value:"missing instanceId"}}if(action==="legacyBroadcastPost"){let instanceId=typeof params.instanceId=="string"?params.instanceId:"";return instanceId?legacyBroadcastChannels.has(instanceId)?(broadcastAppMessage({kind:"legacyBroadcast",instanceId,message:params.message}),{success:!0,value:{}}):{success:!1,value:"broadcast channel not found"}:{success:!1,value:"missing instanceId"}}if(action==="legacyBroadcastClose"){let instanceId=typeof params.instanceId=="string"?params.instanceId:"";return instanceId?(legacyBroadcastChannels.delete(instanceId),{success:!0,value:{}}):{success:!1,value:"missing instanceId"}}if(action==="megaPopClose"){let popId=typeof params.popId=="string"?params.popId:"";return popId?closeMegaPop(popId,params.result)?{success:!0,value:{}}:{success:!1,value:"popId not found"}:{success:!1,value:"missing popId"}}if(action==="megaPopResize"){let popId=typeof params.popId=="string"?params.popId:"";return popId?resizeMegaPop(popId,params)?{success:!0,value:{}}:{success:!1,value:"popId not found"}:{success:!1,value:"missing popId"}}return{success:!1,value:"unsupported container data action"}}function requestContainerData(action,params,onSuccess,onFailure){if(isTop){let result=executeContainerData(action,params);setTimeout(()=>result.success?onSuccess(result.value):onFailure(result.value),0);return}let requestId=++containerDataRequestSeq;containerDataCallbacks.set(requestId,{success:onSuccess,failure:onFailure});try{window.top?.postMessage({source:SRC,type:"containerDataRequest",requestId,action,params},"*")}catch(error48){containerDataCallbacks.delete(requestId),onFailure(error48 instanceof Error?error48.message:String(error48))}}function requestOpen(url2,callbackId,webdialog,params){let overlay=resolveOverlayPresentation(url2,params,webdialog),popBeforeOpen=requestsPopBeforeOpen(url2,params),popId=typeof params?.__mearlMegaPopId=="string"?params.__mearlMegaPopId:null;isTop?openLayer(url2,callbackId,overlay,window,!0,popId):window.top?.postMessage({source:SRC,type:"open",url:url2,callbackId,overlay,popBeforeOpen,popId},"*")}function requestClose(data){let payload;try{payload=data===void 0?void 0:JSON.parse(JSON.stringify(data))}catch{payload=void 0}isTop?requestCloseOnTop(payload):window.top?.postMessage({source:SRC,type:"close",data:payload},"*")}if(window.addEventListener("message",event=>{let msg=event.data;if(!(!msg||typeof msg!="object")){if(msg.source==="mearl-content"&&(msg.type==="APP_BRIDGE_SIMULATOR_VISIBILITY"||msg.type==="APP_BRIDGE_RUNTIME_RESPONSES")){if(!isTop||event.source!==window)return;if(msg.type==="APP_BRIDGE_SIMULATOR_VISIBILITY"&&typeof msg.hidden=="boolean"){simulatedPageHidden=msg.hidden,links.getBridgeProtocol().handlePageVisibility(msg.hidden);let lifecycleMessage={source:SRC,type:"simulatorVisibility",hidden:msg.hidden};rootFrame?.contentWindow?.postMessage(lifecycleMessage,"*");for(let layer of layers)layer.closing||layer.frame.contentWindow?.postMessage(lifecycleMessage,"*")}else if(msg.type==="APP_BRIDGE_RUNTIME_RESPONSES"&&msg.profile===config2.profile&&msg.responses&&typeof msg.responses=="object"&&!Array.isArray(msg.responses)){let responses=msg.responses;runtimeResponses={...runtimeResponses??{},...responses},links.getBridgeProtocol().applyRuntimeResponses(responses);let configMessage={source:SRC,type:"runtimeResponses",profile:config2.profile,responses};rootFrame?.contentWindow?.postMessage(configMessage,"*");for(let layer of layers)layer.closing||layer.frame.contentWindow?.postMessage(configMessage,"*")}return}if(msg.source===SRC){if(isTop){let sourceLayer=layerForWindow(event.source),sourceIsRoot=!!(rootFrame?.contentWindow&&rootFrame.contentWindow===event.source);if(!sourceLayer&&!sourceIsRoot)return;if(msg.type==="open"&&typeof msg.url=="string"){let rawOverlay=msg.overlay&&typeof msg.overlay=="object"?msg.overlay:void 0,overlay=rawOverlay?{topRatio:numberParam(rawOverlay.topRatio,.2,0,1),widthRatio:numberParam(rawOverlay.widthRatio,1,0,1),radius:numberParam(rawOverlay.radius,0,0,50),maskAlpha:numberParam(rawOverlay.maskAlpha,.3,0,1),tapClose:boolParam(rawOverlay.tapClose,!0)}:resolveOverlayPresentation(msg.url,void 0,!1),callbackId=typeof msg.callbackId=="number"?msg.callbackId:0,popId=typeof msg.popId=="string"&&msg.popId?msg.popId:null;msg.popBeforeOpen===!0&&sourceLayer?replaceLayer(sourceLayer,msg.url,callbackId,overlay,popId):openLayer(msg.url,callbackId,overlay,event.source??window,!0,popId)}else if(msg.type==="close")requestCloseOnTop(msg.data);else if(msg.type==="closeAll"){let gotoEvent=msg.gotoEvent===!0;if(gotoEvent&&sourceIsRoot&&layers.length===0&&msg.data!==void 0)try{event.source.postMessage({source:SRC,type:"resume",data:msg.data,storageId:null,callbackId:0,final:!0,gotoEvent:!0},"*")}catch{}else closeAllLayers(msg.data,gotoEvent)}else if(msg.type==="appMessageToOpener"&&sourceLayer){let target=sourceLayer.openerWin;if(target===window)links.getBridgeProtocol().handleAppMessage(msg.message);else try{target.postMessage({source:SRC,type:"appMessage",message:msg.message},"*")}catch{}}else if(msg.type==="containerDataRequest"&&typeof msg.requestId=="number"&&typeof msg.action=="string"&&msg.params&&typeof msg.params=="object"&&!Array.isArray(msg.params)&&event.source){let result=executeContainerData(msg.action,msg.params);try{event.source.postMessage({source:SRC,type:"containerDataResponse",requestId:msg.requestId,success:result.success,value:result.value},"*")}catch{}}else if(msg.type==="nativeBackResult"&&typeof msg.requestId=="number"&&typeof msg.handled=="boolean"&&event.source)finishNativeBack(msg.requestId,event.source,msg.handled);else if(msg.type==="urlChanged"&&typeof msg.url=="string"){let topLayer=layers[layers.length-1];if(sourceIsRoot&&!topLayer){rootBusinessUrl=msg.url;let mapped=mapUrlForSync(msg.url);if(mapped)try{history.replaceState({__mearl_layer__:0},"",mapped)}catch{}}else if(topLayer&&!topLayer.closing&&sourceLayer===topLayer){topLayer.url=msg.url,topLayer.titleBarStateExplicit&&topLayer.titleBarState&&cacheExplicitTitleBarState(topLayer,topLayer.titleBarState);let mapped=mapUrlForSync(msg.url);if(mapped)try{history.replaceState({__mearl_layer__:layers.length},"",mapped)}catch{}}}else if(msg.type==="title"&&typeof msg.title=="string"){let topLayer=layers[layers.length-1];if(sourceIsRoot&&!topLayer)try{document.title=msg.title,syncSimulatedTitleBar()}catch{}else if(topLayer&&sourceLayer===topLayer){document.title=msg.title;let state=resolvedTitleBarState(topLayer);topLayer.titleBarState={...state,title:msg.title},syncLayerViewport(topLayer,topLayer.titleBarState)}}else if(msg.type==="titleBarState"){let state=parseReportedTitleBarState(msg.state);if(state&&sourceIsRoot)links.getSystemBars().setPresentedRootTitleBarState(state);else if(state&&sourceLayer){let explicit=msg.explicit===!0;sourceLayer.titleBarStateReady=!0,explicit?(sourceLayer.titleBarState=state,sourceLayer.titleBarStateExplicit=!0,cacheExplicitTitleBarState(sourceLayer,state)):sourceLayer.titleBarStateExplicit||(sourceLayer.titleBarState=state);let resolvedState=sourceLayer.titleBarState??state;syncLayerViewport(sourceLayer,resolvedState)}}}else if(msg.type==="simulatorVisibility"&&typeof msg.hidden=="boolean"){if(event.source!==window.top)return;links.getBridgeProtocol().handlePageVisibility(msg.hidden)}else if(msg.type==="appMessage"){if(event.source!==window.top)return;links.getBridgeProtocol().handleAppMessage(msg.message)}else if(msg.type==="nativeBack"&&typeof msg.requestId=="number"){if(event.source!==window.top)return;let handled=links.getBridgeProtocol().handleNativeBack();window.top?.postMessage({source:SRC,type:"nativeBackResult",requestId:msg.requestId,handled},"*")}else if(msg.type==="containerDataResponse"&&typeof msg.requestId=="number"){if(event.source!==window.top)return;let callback=containerDataCallbacks.get(msg.requestId);if(!callback)return;containerDataCallbacks.delete(msg.requestId),msg.success===!0?callback.success(msg.value):callback.failure(msg.value)}else if(msg.type==="runtimeResponses"&&msg.profile===config2.profile&&msg.responses&&typeof msg.responses=="object"&&!Array.isArray(msg.responses)){if(event.source!==window.top)return;links.getBridgeProtocol().applyRuntimeResponses(msg.responses)}else if(msg.type==="resume"){if(event.source!==window.top)return;links.getBridgeProtocol().handleResume({data:msg.data,storageId:msg.storageId??null,callbackId:typeof msg.callbackId=="number"?msg.callbackId:0,final:msg.final===!0,gotoEvent:msg.gotoEvent===!0,silent:msg.silent===!0})}else event.source!==window.top&&window.top?.postMessage(msg,"*");return}pageTransport.handleMessage(msg)}}),!isTop&&isContainerFrame){let reportUrl=()=>{try{window.top?.postMessage({source:SRC,type:"urlChanged",url:restoreLayerBusinessUrl(location.href)},"*")}catch{}};try{let origPushState=history.pushState.bind(history),origReplaceState=history.replaceState.bind(history);history.pushState=function(...args){origPushState(...args),reportUrl()},history.replaceState=function(...args){origReplaceState(...args),reportUrl()},window.addEventListener("popstate",reportUrl),window.addEventListener("hashchange",reportUrl)}catch{}}if(isContainerFrame){let requestProxyLocationOpen=url2=>{if(links.getBridgeProtocol().handleMaybeScheme(url2))return!0;try{let current=new URL(restoreLayerBusinessUrl(location.href)),target=new URL(url2,current);return!/^https?:$/.test(target.protocol)||target.origin===current.origin&&target.pathname===current.pathname&&target.search===current.search?!1:(requestOpen(target.href,0,!1),!0)}catch{return!1}};Object.defineProperty(window,"__PROXY_LOCATION__",{value:{get href(){return location.href},set href(url2){requestProxyLocationOpen(url2)||(location.href=mapLayerFrameUrl(url2))},replace(url2){links.getBridgeProtocol().handleMaybeScheme(url2)||location.replace(mapLayerFrameUrl(url2))},assign(url2){requestProxyLocationOpen(url2)||location.assign(mapLayerFrameUrl(url2))}},writable:!1,configurable:!0})}if(isContainerFrame){document.addEventListener("click",event=>{let el=event.target;for(;el&&el.tagName!=="A";)el=el.parentElement;if(!el)return;let href=el.getAttribute("href");if(href){if(links.getBridgeProtocol().handleMaybeScheme(href)){event.preventDefault(),event.stopPropagation();return}/^https?:/i.test(href)&&el.getAttribute("target")==="_blank"&&(event.preventDefault(),event.stopPropagation(),requestOpen(href,0,!1))}},!0);let origOpen=window.open;window.open=function(url2,target,features){let urlStr=typeof url2=="string"?url2:url2 instanceof URL?url2.href:"";return links.getBridgeProtocol().handleMaybeScheme(urlStr)?null:/^https?:/i.test(urlStr)?(requestOpen(urlStr,0,!1),null):origOpen?origOpen.call(window,url2,target,features):null};try{let proto=Location.prototype,origAssign=proto.assign,origReplace=proto.replace;origAssign&&(proto.assign=function(url2){if(links.getBridgeProtocol().handleMaybeScheme(url2))return;let upgraded=location.protocol==="https:"&&url2.startsWith("http:")?"https:"+url2.slice(5):url2;origAssign.call(this,upgraded)}),origReplace&&(proto.replace=function(url2){if(links.getBridgeProtocol().handleMaybeScheme(url2))return;let upgraded=location.protocol==="https:"&&url2.startsWith("http:")?"https:"+url2.slice(5):url2;origReplace.call(this,upgraded)})}catch{}}return log3("容器环境已就绪",isTop?"(top)":isRootFrame?"(root)":isLayerFrame?"(layer)":"(iframe,仅桥)"),{getRootFrame:()=>rootFrame,getLayers:()=>layers,getClosingLayerCount:()=>closingLayerCount,requestOpen,requestClose,requestNativeBack,requestContainerData,closeAllLayers}}var APP_PROFILE_RUNTIME_FACTORIES={environment:installAppProfileEnvironment,containerStack:installAppProfileContainerStack,bridgeProtocol:installAppProfileBridgeProtocol,pageTransport:installAppProfilePageTransport,systemBars:installAppProfileSystemBars};function buildAppProfileRuntimeCallSource(configExpression){return`(${installAppProfileRuntime.toString()})(${configExpression},{environment:${installAppProfileEnvironment.toString()},pageTransport:${installAppProfilePageTransport.toString()},containerStack:${installAppProfileContainerStack.toString()},systemBars:${installAppProfileSystemBars.toString()},bridgeProtocol:${installAppProfileBridgeProtocol.toString()}})`}function installAppProfileRuntime(config2,factories=APP_PROFILE_RUNTIME_FACTORIES){let environment=factories.environment(config2);if(!environment)return;let pageTransport=factories.pageTransport(config2,environment),containerStack=factories.containerStack(config2,environment,{pageTransport,getSystemBars:()=>systemBars,getBridgeProtocol:()=>bridgeProtocol}),systemBars=factories.systemBars(config2,environment,{getRootFrame:containerStack.getRootFrame,getLayers:containerStack.getLayers,getClosingLayerCount:containerStack.getClosingLayerCount,requestClose:containerStack.requestClose,requestNativeBack:containerStack.requestNativeBack}),bridgeProtocol=factories.bridgeProtocol(config2,environment,{pageTransport,systemBars,requestOpen:containerStack.requestOpen,requestClose:containerStack.requestClose,requestCloseAll:containerStack.closeAllLayers,requestContainerData:containerStack.requestContainerData})}import https from"node:https";import http3 from"node:http";var TYPE_INTO_ELEMENT_SRC=typeIntoElement.toString(),CLICK_ELEMENT_VIA_JS_SRC=clickElementViaJS.toString(),GET_CLICK_COORDS_FROM_NODE_SRC=getClickCoordsFromNode.toString();function nodeFetch(urlStr,options={}){return new Promise((resolve5,reject)=>{let url2=new URL(urlStr),isHttps=url2.protocol==="https:",lib=isHttps?https:http3,{method="GET",headers={},body,timeoutMs=3e4}=options,req=lib.request({host:url2.hostname,port:url2.port||(isHttps?443:80),path:url2.pathname+url2.search,method,headers},res=>{let responseHeaders={};for(let[key,value]of Object.entries(res.headers))typeof value=="string"?responseHeaders[key]=value:Array.isArray(value)&&(responseHeaders[key]=value.join(", "));let chunks=[];res.on("data",chunk=>chunks.push(Buffer.from(chunk))),res.on("end",()=>{let bodyBuffer=Buffer.concat(chunks);resolve5({status:res.statusCode??0,statusText:res.statusMessage??"",headers:responseHeaders,body:bodyBuffer.toString("utf-8"),bodyBuffer})})});req.on("error",reject),req.setTimeout(timeoutMs,()=>{req.destroy(),reject(new Error(`Request timeout: ${urlStr}`))}),body&&req.write(body),req.end()})}async function getCookiesForUrl(session,targetUrl){let result=await session.client.sendCommand("Network.getCookies",{urls:[targetUrl]}),map2=new Map;for(let cookie of result.cookies??[])map2.set(cookie.name,cookie.value);return map2}function decodeTracknick(raw){if(!raw)return"";try{return decodeURIComponent(raw).replace(/\\u([0-9a-fA-F]{4})/g,(_match,hex3)=>String.fromCharCode(parseInt(hex3,16)))}catch{return raw}}function buildMultipartFormBody(fields){let boundary=`----mearl-${Date.now()}-${Math.random().toString(36).slice(2)}`,body=[...Object.entries(fields).map(([name,value])=>`--${boundary}\r
|
|
1047
|
+
</style><div id="surface" data-platform="${config2.platform.toLowerCase()}" data-cutout="${String(cutoutKind!=="none")}" data-cutout-kind="${cutoutKind}"><div id="status"><span id="time"></span>${cutoutMarkup}<span id="indicators" aria-hidden="true"><svg id="signal" viewBox="0 0 18 12"><rect x="0" y="8" width="3" height="4" rx="1"/><rect x="5" y="6" width="3" height="6" rx="1"/><rect x="10" y="3" width="3" height="9" rx="1"/><rect x="15" y="0" width="3" height="12" rx="1"/></svg><svg id="wifi" viewBox="1 3.8 22 17.2"><path d="M2 8.82a15 15 0 0 1 20 0"/><path d="M5 12.859a10 10 0 0 1 14 0"/><path d="M8.5 16.429a5 5 0 0 1 7 0"/><path d="M12 20h.01"/></svg><svg id="battery" viewBox="0 0 28 13"><rect id="battery-outline" x=".65" y=".65" width="23" height="11.7" rx="3.1"/><rect id="battery-level" x="2.35" y="2.35" width="19.6" height="8.3" rx="1.7"/><path id="battery-cap" d="M25 4.1c1.1.35 1.7 1.15 1.7 2.4s-.6 2.05-1.7 2.4z"/></svg></span></div></div>`;let surface=shadow.getElementById("surface"),time3=shadow.getElementById("time"),cutout=shadow.getElementById("device-cutout"),cutoutStatusPath=shadow.querySelector("#cutout-check path"),localizedScreenshotText=config2.language.toLowerCase().startsWith("zh")?{idle:"截图",copied:"已复制",downloaded:"已下载",failed:"截图失败"}:{idle:"Screenshot",copied:"Copied",downloaded:"Downloaded",failed:"Capture failed"},setCutoutState=state=>{cutout&&(cutout.dataset.state=state,cutout.setAttribute("aria-label",localizedScreenshotText[state]),cutout.title=localizedScreenshotText[state],cutoutStatusPath&&cutoutStatusPath.setAttribute("d",state==="failed"?"M5.5 5.5l9 9m0-9-9 9":"m4.5 10.5 3.2 3.2 7.8-7.8"))},screenshotPending=!1,screenshotBlob=data=>{let binary=atob(data),bytes=new Uint8Array(binary.length);for(let index=0;index<binary.length;index+=1)bytes[index]=binary.charCodeAt(index);return new Blob([bytes],{type:"image/png"})},downloadScreenshot=blob=>{let link=document.createElement("a"),objectUrl=URL.createObjectURL(blob);link.href=objectUrl,link.download=`mearl-screenshot-${new Date().toISOString().replace(/[:.]/g,"-")}.png`,link.style.display="none",document.body.appendChild(link),link.click(),link.remove(),window.setTimeout(()=>URL.revokeObjectURL(objectUrl),1e3)},captureScreenshot=async()=>{if(!cutout||screenshotPending||cutout.dataset.state!=="idle")return;screenshotPending=!0,cutout.setAttribute("aria-busy","true");let requestId=Date.now()*1e3+Math.floor(Math.random()*1e3),timeoutTimer=0,onResponse=null,image=new Promise((resolve5,reject)=>{let cleanup=()=>{timeoutTimer&&window.clearTimeout(timeoutTimer),onResponse&&window.removeEventListener("message",onResponse)};onResponse=event=>{if(event.source!==window)return;let message=event.data;if(!message||message.source!=="mearl-content"||message.type!=="APP_BRIDGE_SCREENSHOT_RESPONSE"||message.requestId!==requestId)return;cleanup();let result=message.result;result?.success===!0&&typeof result.data=="string"?resolve5({data:result.data}):reject(new Error(String(result?.error??"screenshot failed")))},window.addEventListener("message",onResponse),timeoutTimer=window.setTimeout(()=>{cleanup(),reject(new Error("screenshot timeout"))},35e3)}).then(result=>screenshotBlob(result.data)),clipboardWrite=null;if(navigator.clipboard?.write&&typeof ClipboardItem<"u")try{clipboardWrite=navigator.clipboard.write([new ClipboardItem({"image/png":image})]),clipboardWrite.catch(()=>{})}catch{clipboardWrite=null}window.postMessage({source:SRC,type:"screenshot",requestId},"*");try{let blob=await image;if(clipboardWrite)try{await clipboardWrite,setCutoutState("copied")}catch{downloadScreenshot(blob),setCutoutState("downloaded")}else downloadScreenshot(blob),setCutoutState("downloaded")}catch{setCutoutState("failed")}finally{screenshotPending=!1,cutout.setAttribute("aria-busy","false")}window.setTimeout(()=>{screenshotPending||setCutoutState("idle")},1600)};hasDynamicIsland&&cutout&&(setCutoutState("idle"),cutout.addEventListener("click",()=>void captureScreenshot()));let updateTime=()=>{let now=new Date;time3&&(time3.textContent=`${String(now.getHours()).padStart(2,"0")}:${String(now.getMinutes()).padStart(2,"0")}`)};return window.addEventListener("mearl:page-time-change",updateTime),updateTime(),{root,surface,timeTimer:window.setInterval(updateTime,3e4)}},install=()=>{let titleBar=config2.titleBar;if(!titleBar||!isContainerFrame||!simulateSystemBars)return;let observeState=()=>{new MutationObserver(syncSimulatedTitleBar).observe(document.head??document.documentElement,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:["content","value"]}),window.addEventListener("popstate",syncSimulatedTitleBar),window.addEventListener("hashchange",syncSimulatedTitleBar),document.readyState==="loading"&&document.addEventListener("DOMContentLoaded",syncSimulatedTitleBar,{once:!0});try{let pushState=history.pushState.bind(history),replaceState=history.replaceState.bind(history);history.pushState=function(...args){pushState(...args),syncSimulatedTitleBar()},history.replaceState=function(...args){replaceState(...args),syncSimulatedTitleBar()}}catch{}};if(!isTop){observeState(),syncSimulatedTitleBar();return}let mount=()=>{if(titleBarRoot||!document.body)return;let totalHeight=config2.statusBarHeight+titleBar.navigationBarHeight,navigationView=createNavigationBarView("root",host.requestNativeBack),statusView=externalDeviceChrome||config2.statusBarHeight<=0?null:createStatusBarView(),spacer=document.createElement("div");if(spacer.setAttribute("data-mearl-app-titlebar-spacer",""),spacer.style.cssText=`display:block;width:100%;height:${totalHeight}px;min-height:${totalHeight}px;flex:none;`,spacer.style.setProperty("--mearl-app-navigation-bar-height",`${titleBar.navigationBarHeight}px`),document.body.insertBefore(spacer,document.body.firstChild),document.body.appendChild(navigationView.root),statusView&&document.body.appendChild(statusView.root),!externalDeviceChrome&&safeAreaInsets.bottom>0){let bottomRoot=document.createElement("div");bottomRoot.setAttribute("data-mearl-app-system-bottom",config2.profile),bottomRoot.style.cssText=`position:fixed;left:0;right:0;bottom:0;height:${safeAreaInsets.bottom}px;z-index:2147483600;box-sizing:border-box;pointer-events:none;color:#111111;`;let bottomShadow=bottomRoot.attachShadow({mode:"open"});bottomShadow.innerHTML=`<style>:host{all:initial}#surface{appearance:none;border:0;padding:0;width:166px;max-width:100%;height:24px;position:absolute;left:50%;bottom:0;transform:translateX(-50%);display:block;box-sizing:border-box;pointer-events:auto;color:#111;background:transparent;cursor:pointer;-webkit-tap-highlight-color:transparent}#surface:focus-visible{outline:2px solid #2563eb;outline-offset:-2px}#indicator{position:absolute;left:50%;bottom:8px;transform:translateX(-50%);width:134px;height:5px;border-radius:999px;background:currentColor;opacity:.92;transition:transform 120ms ease,opacity 120ms ease}#surface:hover #indicator{opacity:1;transform:translateX(-50%) scaleX(1.05)}#surface[data-platform="android"] #indicator{bottom:6px;width:108px;height:4px;opacity:.82}</style><button id="surface" type="button" aria-label="打开桥模拟配置" title="桥模拟配置" data-platform="${config2.platform.toLowerCase()}"><span id="indicator" aria-hidden="true"></span></button>`,document.body.appendChild(bottomRoot),systemBottomRoot=bottomRoot,systemBottomSurface=bottomShadow.getElementById("surface"),systemBottomSurface?.addEventListener("click",()=>{window.postMessage({source:SRC,type:"showBridgeConfig",profile:config2.profile,actions:config2.actions},"*")})}rootTitleBarView=navigationView,systemStatusView=statusView,titleBarRoot=navigationView.root,titleBarSpacer=spacer,syncSimulatedTitleBar(),observeState()};document.body?mount():document.addEventListener("DOMContentLoaded",mount,{once:!0})},service={initialLayerTitleBarState,resolvedTitleBarState,parseReportedTitleBarState,setPresentedRootTitleBarState:state=>{presentedRootTitleBarState=state,syncSimulatedTitleBar()},markStateExplicit:()=>{titleBarStateExplicit=!0},applyNavigationBarState,applyStatusBarState,createNavigationBarView,destroyNavigationBarView:view=>view?.root.remove(),syncLayerViewport,syncActiveSystemBars,syncSimulatedTitleBar};return install(),service}function installAppProfilePageTransport(config2,environment){let{SRC,TAG,log:log3}=environment,appToast=null,appToastHideTimer=null,appToastRemoveTimer=null;function showAppToast(params){let p=params&&typeof params=="object"?params:{},messageValue=[p.message,p.msg,p.content,p.text].find(value=>typeof value=="string"&&value.trim().length>0);if(typeof messageValue!="string")return"missing message";let durationValue=Number(p.milliseconds??p.duration),duration3=Number.isFinite(durationValue)&&durationValue>0?durationValue:2e3,hideAfter=Math.min(6e4,Math.max(300,Math.round(duration3)));appToastHideTimer!==null&&window.clearTimeout(appToastHideTimer),appToastRemoveTimer!==null&&window.clearTimeout(appToastRemoveTimer);let toast=appToast?.isConnected===!0?appToast:document.createElement("div");return toast!==appToast&&(appToast=toast,toast.setAttribute("data-mearl-app-toast",""),toast.setAttribute("role","status"),toast.setAttribute("aria-live","polite"),Object.assign(toast.style,{position:"fixed",left:"50%",top:"50%",zIndex:"2147483647",maxWidth:"calc(100vw - 64px)",boxSizing:"border-box",padding:"14px 20px",borderRadius:"12px",background:"rgba(20, 20, 20, 0.88)",color:"#ffffff",fontFamily:'-apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, sans-serif',fontSize:"16px",fontWeight:"400",lineHeight:"24px",textAlign:"center",whiteSpace:"pre-wrap",overflowWrap:"anywhere",pointerEvents:"none",opacity:"0",transform:"translate(-50%, -50%) scale(0.96)",transition:"opacity 180ms ease, transform 180ms ease"}),(document.body??document.documentElement).appendChild(toast)),toast.textContent=messageValue,toast.style.opacity="0",toast.style.transform="translate(-50%, -50%) scale(0.96)",toast.offsetWidth,toast.style.opacity="1",toast.style.transform="translate(-50%, -50%) scale(1)",appToastHideTimer=window.setTimeout(()=>{appToastHideTimer=null,toast.style.opacity="0",toast.style.transform="translate(-50%, -50%) scale(0.96)",appToastRemoveTimer=window.setTimeout(()=>{appToastRemoveTimer=null,appToast===toast&&(appToast=null),toast.remove()},180)},hideAfter),null}let bridgeRequestSeq=0,pendingMtop={},pendingMtopStreams={},pendingUserInfo={};function callMtop(params,succ,fail2){let id=++bridgeRequestSeq;pendingMtop[id]={succ,fail:fail2};let post=params.post,rawTimeout=params.timeout??params.timer,timeout=typeof rawTimeout=="number"?rawTimeout:typeof rawTimeout=="string"&&rawTimeout.trim()!==""?Number(rawTimeout):void 0,payload={...params,data:params.data!==void 0?params.data:params.param??{},method:params.method??(post===!0||post===1||post==="1"||post==="true"?"POST":"GET"),env:params.env??(/(^|\.)wapa\.taobao\.com$/i.test(location.hostname)?"pre":"online"),...Number.isFinite(timeout)&&{timeout}};window.postMessage({source:SRC,type:"mtop",requestId:id,payload},"*"),log3("mtop 代发 →",params.api)}function callMtopAsync(params){return new Promise((resolve5,reject)=>callMtop(params,resolve5,reject))}function callMtopStream(params,succ,fail2){let sessionId=typeof params.id=="string"?params.id:String(params.id??""),request=params.request&&typeof params.request=="object"?params.request:null;if(!sessionId||!request||typeof request.api!="string"){fail2?.("invalid mtop_stream params");return}let requestId=++bridgeRequestSeq;pendingMtopStreams[requestId]={sessionId},window.postMessage({source:SRC,type:"mtopStream",requestId,payload:{...request,timeout:params.timeout,method:params.method??request.method,env:/(^|\.)wapa\.taobao\.com$/i.test(location.hostname)?"pre":"online"}},"*"),succ?.({}),log3("mtop 流式代发 →",request.api)}function callUserInfo(fallback,succ){if(fallback.userId){succ?.(fallback);return}let requestId=++bridgeRequestSeq,timer=setTimeout(()=>{let pending=pendingUserInfo[requestId];pending&&(delete pendingUserInfo[requestId],pending.succ?.(pending.fallback))},1e3);pendingUserInfo[requestId]={fallback,succ,timer},window.postMessage({source:SRC,type:"userInfo",requestId},"*")}function emitMtopStreamEvent(sessionId,eventType,data){let detail=data&&typeof data=="object"?{...data,eventType}:{data,eventType};document.dispatchEvent(new CustomEvent(`mtop_stream${sessionId}`,{detail}))}function createUploadId(){try{if(typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch{}return`${Date.now()}-${Math.random().toString(36).slice(2)}`}function pickDirectUploadTarget(response){if(!response||typeof response!="object")return null;let data=response.data;if(data?.success===!1)return null;let result=data?.result,target=Array.isArray(result?.urls)?result.urls[0]:void 0;if(!target||typeof target!="object")return null;let item=target;if(typeof item.put!="string"||!item.put||typeof item.get!="string"||!item.get)return null;let rawHeaders=item.putHeaders&&typeof item.putHeaders=="object"?item.putHeaders:{},putHeaders=Object.fromEntries(Object.entries(rawHeaders).map(([key,value])=>[key,String(value)]));return{put:item.put,get:item.get,putHeaders}}async function uploadImage(file2){let uploader=config2.imagePicker;if(!uploader)throw new Error("图片上传能力未配置");let env=/(^|\.)wapa\.taobao\.com$/i.test(location.hostname)?"pre":"online",response=await callMtopAsync({api:uploader.api,v:uploader.version,method:"POST",env,timeout:6e4,data:{fcId:uploader.fcId,fcGroup:uploader.fcGroup,fcName:uploader.uploadUrlFunction,fcData:JSON.stringify({requestType:"url",mimes:[file2.type||"image/jpeg"],prefix:uploader.prefix,region:uploader.region,uploadNumber:1}),fcConfig:JSON.stringify({timeout:6e4,disasterRecover:!0})}}),target=pickDirectUploadTarget(response);if(!target)throw new Error("获取图片上传地址失败");let uploadUrl=`${target.put}${target.put.includes("?")?"&":"?"}getAvatar=1`,uploadResponse=await fetch(uploadUrl,{method:"PUT",headers:target.putHeaders,body:file2});if(uploadResponse.status!==200)throw new Error(`图片直传失败: HTTP ${uploadResponse.status}`);return target.get}function openImagePicker(callbackCommandFn){let input2=document.createElement("input");input2.type="file",input2.accept="image/*",input2.style.display="none";let settled=!1,finish=()=>{settled=!0,input2.remove()};input2.addEventListener("cancel",finish,{once:!0}),input2.addEventListener("change",()=>{let file2=input2.files?.[0];if(!file2){finish();return}if(!file2.type.startsWith("image/")){finish(),console.error(TAG,"仅支持选择图片文件");return}uploadImage(file2).then(pic=>{typeof callbackCommandFn=="function"&&callbackCommandFn({pic,uuid:createUploadId(),timeStamp:Date.now()}),log3("图片选择并上传完成:",pic)}).catch(error48=>console.error(TAG,"图片上传失败:",error48)).finally(finish)},{once:!0}),(document.body??document.documentElement).appendChild(input2),input2.click(),window.addEventListener("focus",()=>{setTimeout(()=>{!settled&&!input2.files?.length&&finish()},1e3)},{once:!0})}function showPaymentDialog(api,params,succeed,failed){document.querySelector('[data-mearl-payment-dialog="true"]')?.remove();let overlay=document.createElement("div");overlay.setAttribute("data-mearl-payment-dialog","true"),Object.assign(overlay.style,{position:"fixed",inset:"0",zIndex:"2147483647",display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.5)"});let card=document.createElement("div");Object.assign(card.style,{background:"#fff",borderRadius:"12px",padding:"24px",width:"300px",textAlign:"center",fontFamily:"system-ui, sans-serif"});let title=document.createElement("div");Object.assign(title.style,{fontSize:"17px",fontWeight:"600",marginBottom:"8px"}),title.textContent="支付确认";let desc=document.createElement("div");Object.assign(desc.style,{fontSize:"14px",color:"#666",marginBottom:"20px"}),desc.textContent=`模拟 ${api} 支付,请选择操作`;let btnRow=document.createElement("div");Object.assign(btnRow.style,{display:"flex",gap:"12px"});let btnBase=(text,bg,color,action)=>{let btn=document.createElement("button");return btn.textContent=text,btn.setAttribute("data-mearl-action",action),Object.assign(btn.style,{flex:"1",padding:"10px 0",border:"none",borderRadius:"8px",fontSize:"15px",fontWeight:"500",cursor:"pointer",background:bg,color}),btn},confirmBtn=btnBase("完成支付","#1677ff","#fff","payment-confirm"),cancelBtn=btnBase("取消支付","#f5f5f5","#333","payment-cancel"),cleanup=()=>{overlay.remove()};confirmBtn.addEventListener("click",()=>{cleanup(),log3("用户完成支付",api),succeed(api==="wx.requestPayment"?{errMsg:"requestPayment:ok"}:{ResultStatus:"9000",resultStatus:"9000"})}),cancelBtn.addEventListener("click",()=>{cleanup(),log3("用户取消支付",api),failed(api==="wx.requestPayment"?{errMsg:"requestPayment:fail cancel"}:{ResultStatus:"6001",resultStatus:"6001"})}),btnRow.appendChild(cancelBtn),btnRow.appendChild(confirmBtn),card.appendChild(title),card.appendChild(desc),card.appendChild(btnRow),overlay.appendChild(card),(document.body??document.documentElement).appendChild(overlay)}function showMiniProgramActionDialog(action,params,confirmed,cancelled){document.querySelector('[data-mearl-mini-program-dialog="true"]')?.remove();let overlay=document.createElement("div");overlay.setAttribute("data-mearl-mini-program-dialog","true"),overlay.setAttribute("data-mearl-mini-program-action",action),Object.assign(overlay.style,{position:"fixed",inset:"0",zIndex:"2147483647",display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.5)"});let card=document.createElement("div");Object.assign(card.style,{background:"#fff",borderRadius:"12px",padding:"24px",width:"300px",textAlign:"center",fontFamily:"system-ui, sans-serif"});let title=document.createElement("div");Object.assign(title.style,{fontSize:"17px",fontWeight:"600",marginBottom:"8px"}),title.textContent=action==="navigateMiniProgram"?"打开其他小程序":"订阅消息";let desc=document.createElement("div");Object.assign(desc.style,{fontSize:"14px",color:"#666",marginBottom:"20px"});let targetTitle=params.title?.trim()||"其他";desc.textContent=action==="navigateMiniProgram"?`即将打开“${targetTitle}”小程序,是否继续?`:"模拟微信订阅消息授权,请选择操作";let btnRow=document.createElement("div");Object.assign(btnRow.style,{display:"flex",gap:"12px"});let createButton=(text,background,color,actionName)=>{let button=document.createElement("button");return button.textContent=text,button.setAttribute("data-mearl-action",actionName),Object.assign(button.style,{flex:"1",padding:"10px 0",border:"none",borderRadius:"8px",fontSize:"15px",fontWeight:"500",cursor:"pointer",background,color}),button},confirmButton=createButton(action==="navigateMiniProgram"?"确定":"允许","#1677ff","#fff","mini-program-confirm"),cancelButton=createButton("取消","#f5f5f5","#333","mini-program-cancel"),cleanup=()=>overlay.remove();confirmButton.addEventListener("click",()=>{cleanup();let result=action==="navigateMiniProgram"?{errMsg:"navigateToMiniProgram:ok"}:{result:"SUCCESS",data:{totalCount:1,acceptCount:1}};log3("用户确认小程序原生能力",action,params.appId??params.scene??""),confirmed(result)}),cancelButton.addEventListener("click",()=>{cleanup();let result=action==="navigateMiniProgram"?{errMsg:"navigateToMiniProgram:fail cancel"}:{result:"CLOSE_BY_USER"};log3("用户取消小程序原生能力",action),cancelled(result)}),btnRow.appendChild(cancelButton),btnRow.appendChild(confirmButton),card.appendChild(title),card.appendChild(desc),card.appendChild(btnRow),overlay.appendChild(card),(document.body??document.documentElement).appendChild(overlay)}function handleMessage(msg){if(msg.source==="mearl-content"&&msg.type==="APP_BRIDGE_MTOP_RESPONSE"){let pending=pendingMtop[msg.requestId];if(!pending)return!0;delete pendingMtop[msg.requestId];let result=msg.result;return result?.success?pending.succ?.(result.response):pending.fail?.(result?.error??"mtop delegate failed"),!0}if(msg.source==="mearl-content"&&msg.type==="APP_BRIDGE_USER_INFO_RESPONSE"){let requestId=msg.requestId,pending=pendingUserInfo[requestId];if(!pending)return!0;delete pendingUserInfo[requestId],clearTimeout(pending.timer);let result=msg.result,response=result?.success&&result.response&&typeof result.response=="object"?result.response:{};return pending.succ?.({...pending.fallback,...response}),!0}if(msg.source==="mearl-content"&&msg.type==="APP_BRIDGE_MTOP_STREAM_EVENT"){let requestId=msg.requestId,pending=pendingMtopStreams[requestId];if(!pending)return!0;let eventType=msg.eventType;return emitMtopStreamEvent(pending.sessionId,eventType,msg.data),(eventType==="onFinish"||eventType==="onError")&&delete pendingMtopStreams[requestId],!0}return!1}return{showAppToast,callMtop,callMtopStream,callUserInfo,openImagePicker,showPaymentDialog,showMiniProgramActionDialog,handleMessage}}function installAppProfileBridgeProtocol(config2,environment,host){let{w,SRC,TAG,isTop,log:log3}=environment,{pageTransport,systemBars,requestOpen,requestClose,requestCloseAll,requestContainerData}=host,{showAppToast,callMtop,callMtopStream,callUserInfo,openImagePicker,showPaymentDialog,showMiniProgramActionDialog}=pageTransport,{applyNavigationBarState,applyStatusBarState,syncSimulatedTitleBar}=systemBars,NOT_IMPLEMENTED_PAYLOAD=JSON.stringify({ret:["HY_FAILED"],msg:"not implemented"}),FPT_STORAGE_KEY=`__mearl_app_fpt__:${config2.profile}`,CALENDAR_STORAGE_KEY=`__mearl_app_calendar_events__:${config2.profile}`,unsupportedNativeInputNotified=!1,stopNetworkQualityMonitor=null,simulatedPageHidden=!1,simulatedVisibilityInstalled=!1,hasPendingMiniProgramBackData=!1,pendingMiniProgramBackData,notificationListeners=new Map,megaListenerSeq=0,megaBroadcastListeners=new Map,megaLifeCycleListeners=new Set,megaPageCloseListeners=new Set,megaSystemBackListener=null,megaKVMutationVersion=0,MEGA_KV_TOTAL_SIZE=5*1024*1024,MEGA_KV_STORAGE_KEY=`__mearl_mega_kv__:${config2.profile}`;function readMegaKVStorage(){let storage=new Map;try{let parsed=JSON.parse(localStorage.getItem(MEGA_KV_STORAGE_KEY)??"{}");if(!parsed||typeof parsed!="object"||Array.isArray(parsed))return storage;for(let[bizId,rawEntries]of Object.entries(parsed)){if(!rawEntries||typeof rawEntries!="object"||Array.isArray(rawEntries))continue;let entries=new Map;for(let[key,value]of Object.entries(rawEntries))typeof value=="string"&&entries.set(key,value);storage.set(bizId,entries)}}catch{}return storage}let megaKVStorage=readMegaKVStorage();function megaKVSnapshot(){let snapshot={};for(let[bizId,values]of megaKVStorage)snapshot[bizId]=Object.fromEntries(values);return snapshot}function persistMegaKVStorage(){try{localStorage.setItem(MEGA_KV_STORAGE_KEY,JSON.stringify(megaKVSnapshot()))}catch{}}function replaceMegaKVStorage(value){if(!(!value||typeof value!="object"||Array.isArray(value))){megaKVStorage.clear();for(let[bizId,rawEntries]of Object.entries(value)){if(!rawEntries||typeof rawEntries!="object"||Array.isArray(rawEntries))continue;let entries=new Map;for(let[key,entryValue]of Object.entries(rawEntries))typeof entryValue=="string"&&entries.set(key,entryValue);megaKVStorage.set(bizId,entries)}persistMegaKVStorage()}}function applyMegaKVMutation(payload){let operation=typeof payload.operation=="string"?payload.operation:"",bizId=typeof payload.bizId=="string"?payload.bizId:"",key=typeof payload.key=="string"?payload.key:"";if(bizId){if(operation==="set"&&key&&typeof payload.value=="string"){let entries=megaKVStorage.get(bizId)??new Map;entries.set(key,payload.value),megaKVStorage.set(bizId,entries)}else if(operation==="remove"&&key){let entries=megaKVStorage.get(bizId);entries?.delete(key),entries?.size===0&&megaKVStorage.delete(bizId)}else if(operation==="clear")megaKVStorage.delete(bizId);else return;megaKVMutationVersion+=1,persistMegaKVStorage()}}function emitMegaCallback(callback,value){callback&&setTimeout(()=>callback(value),0)}function megaBroadcastBizId(value){return typeof value=="string"&&value?value:"__MEGA_GLOBAL_MESSAGE__"}function dispatchMegaBroadcast(payload){let bizId=megaBroadcastBizId(payload.bizId),eventName=typeof payload.eventName=="string"?payload.eventName:"";if(eventName)for(let listener of Array.from(megaBroadcastListeners.values()))listener.bizId!==bizId||listener.eventName!==eventName||(listener.once&&megaBroadcastListeners.delete(listener.id),emitMegaCallback(listener.callback,{statusCode:1,type:"onEvent",data:{detail:payload.detail}}),listener.once&&emitMegaCallback(listener.callback,{statusCode:99,type:"finish"}))}let documentPrototype=typeof Document=="function"?Document.prototype:null,nativeHiddenDescriptor=documentPrototype?Object.getOwnPropertyDescriptor(documentPrototype,"hidden"):void 0,nativeVisibilityDescriptor=documentPrototype?Object.getOwnPropertyDescriptor(documentPrototype,"visibilityState"):void 0;function installSimulatedVisibilityState(){if(!simulatedVisibilityInstalled){simulatedVisibilityInstalled=!0;try{Object.defineProperty(document,"hidden",{configurable:!0,get:()=>simulatedPageHidden||!!(nativeHiddenDescriptor?.get?.call(document)??!1)}),Object.defineProperty(document,"visibilityState",{configurable:!0,get:()=>simulatedPageHidden?"hidden":nativeVisibilityDescriptor?.get?.call(document)??"visible"})}catch{}}}function dispatchPageTransitionEvent(type){try{let event=typeof PageTransitionEvent=="function"?new PageTransitionEvent(type,{persisted:!1}):new Event(type);window.dispatchEvent(event)}catch{}}function dispatchActiveEvents(){for(let name of config2.activeEvents)try{document.dispatchEvent(new Event(name))}catch{}}function handlePageVisibility(hidden){if(hidden===simulatedPageHidden)return;installSimulatedVisibilityState(),simulatedPageHidden=hidden;let lifeCycleType=hidden?"onPageDisappear":"onPageAppear";for(let callback of megaLifeCycleListeners)emitMegaCallback(callback,{statusCode:1,type:lifeCycleType,data:{pageId:location.href}});try{document.dispatchEvent(new Event("visibilitychange"))}catch{}if(hidden){try{window.dispatchEvent(new Event("blur"))}catch{}dispatchPageTransitionEvent("pagehide");return}dispatchPageTransitionEvent("pageshow");try{window.dispatchEvent(new Event("focus"))}catch{}dispatchActiveEvents()}function resolveWindowFunction(path25){let parts=path25.split(".").filter(Boolean),owner=w;for(let index=0;index<parts.length-1;index+=1){let next=owner[parts[index]];if(!next||typeof next!="object")return null;owner=next}let fn=owner[parts[parts.length-1]];return typeof fn=="function"?fn.bind(owner):null}function handleNativeBack(){let megaHandled=!1;for(let callback of megaPageCloseListeners)megaHandled=!0,emitMegaCallback(callback,{statusCode:1,type:"onClose",data:{}});if(megaSystemBackListener&&(megaHandled=!0,emitMegaCallback(megaSystemBackListener,{statusCode:1,type:"onSuccess",data:{}})),megaHandled)return!0;let nativeBack=config2.nativeBack;if(!nativeBack)return!1;if(nativeBack.handler){let handler=resolveWindowFunction(nativeBack.handler);if(!handler)return!1;try{return handler(),!0}catch{return!1}}let controlled=!1;if(nativeBack.controlFunction){let control=resolveWindowFunction(nativeBack.controlFunction);if(!control)return!1;try{controlled=control()===!0}catch{return!1}if(!controlled)return!1}if(!nativeBack.event)return controlled;try{let event=new Event(nativeBack.event,{cancelable:!0});return document.dispatchEvent(event),controlled||event.defaultPrevented}catch{return controlled}}function handleAppMessage(message){if(!message||typeof message!="object")return;let payload=message;if(payload.kind==="megaBroadcast"){dispatchMegaBroadcast(payload);return}if(payload.kind==="megaKVStorage"){applyMegaKVMutation(payload);return}if(payload.kind==="legacyBroadcast"&&typeof payload.instanceId=="string"){try{let event=new CustomEvent(`Broadcast.Message.${payload.instanceId}`,{detail:payload.message});Object.defineProperty(event,"param",{configurable:!0,value:payload.message}),document.dispatchEvent(event)}catch{}return}if(payload.kind==="notification"&&typeof payload.name=="string"){let listener=notificationListeners.get(payload.name);listener&&setTimeout(()=>listener(payload.data),0);return}if(!(payload.kind!=="message"||!config2.messageEvent))try{document.dispatchEvent(new CustomEvent(config2.messageEvent,{detail:{data:payload.data}}))}catch{}}function sendAppMessage(message){if(isTop){handleAppMessage(message);return}window.top?.postMessage({source:SRC,type:"appMessageToOpener",message},"*")}function applyRuntimeResponses(responses){let current=config2.actions.responses??{};for(let[api,response]of Object.entries(responses))!response||typeof response!="object"||Array.isArray(response)||(current[api]=response);config2.actions.responses=current}function parseFpt(value){let entries=[],normalized=value.trim();if(!normalized)return entries;let pattern=/([0-9A-Za-z._-]+)\(([0-9A-Za-z._-]+)\)/g,consumed="";for(let match of normalized.matchAll(pattern))consumed+=match[0],entries.push([match[1],match[2]]);return consumed===normalized?entries:[]}function setFptEntry(entries,key,value){entries.delete(key),entries.set(key,value)}function readInitialFptEntries(){let entries=new Map;try{for(let[key,value]of parseFpt(sessionStorage.getItem(FPT_STORAGE_KEY)??""))setFptEntry(entries,key,value)}catch{}try{let currentFpt=new URL(location.href).searchParams.get("fpt")??"";for(let[key,value]of parseFpt(currentFpt))setFptEntry(entries,key,value)}catch{}return entries}let fptEntries=readInitialFptEntries();function serializeFpt(entries){return Array.from(entries,([key,value])=>`${key}(${value})`).join("")}function persistFpt(){try{let value=serializeFpt(fptEntries);value?sessionStorage.setItem(FPT_STORAGE_KEY,value):sessionStorage.removeItem(FPT_STORAGE_KEY)}catch{}}function decorateUrlWithFpt(rawUrl){let targetUrl=mapScheme(rawUrl)??rawUrl;if(fptEntries.size===0)return targetUrl;try{let url2=new URL(targetUrl,location.href);if(url2.protocol!=="http:"&&url2.protocol!=="https:")return targetUrl;let merged=new Map(fptEntries);for(let[key,value]of parseFpt(url2.searchParams.get("fpt")??""))setFptEntry(merged,key,value);return url2.searchParams.set("fpt",serializeFpt(merged)),url2.href}catch{return targetUrl}}function classify(api){let a=config2.actions;return a.open.includes(api)?"open":a.close.includes(api)?"close":a.title.includes(api)?"title":a.navigationBar?.includes(api)?"navigationBar":a.statusBar?.includes(api)?"statusBar":a.systemInfo.includes(api)?"systemInfo":a.mtop.includes(api)?"mtop":a.kvGet?.includes(api)?"kvGet":a.kvSet?.includes(api)?"kvSet":a.kvDelete?.includes(api)?"kvDelete":a.pageContext?.includes(api)?"pageContext":a.responses&&Object.prototype.hasOwnProperty.call(a.responses,api)?"response":a.behaviors&&Object.prototype.hasOwnProperty.call(a.behaviors,api)?a.behaviors[api]:a.noop.includes(api)?"noop":"unknown"}function pickUrl(params){if(!params||typeof params!="object")return null;let p=params,candidates=[p.url,p.data?.url,p.param?.url,p.value?.params?.url];for(let c of candidates)if(typeof c=="string"&&c)return c;return null}function pickCloseData(params){if(params&&typeof params=="object"){let p=params;if("data"in p&&p.data!==void 0)return p.data;if(Object.keys(p).length>0)return p}}function decodeCookieValue2(raw){let value=raw;for(let i=0;i<2;i+=1)try{let decoded=decodeURIComponent(value);if(decoded===value)break;value=decoded}catch{break}return value.replace(/\\u([0-9a-f]{4})/gi,(_match,hex3)=>String.fromCharCode(Number.parseInt(hex3,16)))}function readCookie(name){let prefix=`${name}=`,pair=document.cookie.split(";").map(value=>value.trim()).find(value=>value.startsWith(prefix));return pair?decodeCookieValue2(pair.slice(prefix.length)):""}function readUserCookie(name){let pageUserCookie=w.userCookie;if(!pageUserCookie||typeof pageUserCookie!="object")return"";let value=pageUserCookie[name];return typeof value=="string"?decodeCookieValue2(value):""}function readFirstUserCookie(names){for(let name of names){let value=readCookie(name)||readUserCookie(name);if(value&&value!=="null")return value}return""}let cbSeq=0,callbacks={};function stashCallback(fn){if(typeof fn!="function")return 0;let id=++cbSeq;return callbacks[id]=fn,id}function extractQuery(url2,param){let q=url2.indexOf("?");if(q===-1)return null;for(let pair of url2.slice(q+1).split("&")){let eq=pair.indexOf("=");if(eq>0&&pair.slice(0,eq)===param)return pair.slice(eq+1)}return null}function matchesHostSuffix(hostname3,suffixes){if(!suffixes?.length)return!0;let normalizedHost=hostname3.toLowerCase().replace(/\.$/,"");return suffixes.some(value=>{let suffix=value.toLowerCase().replace(/^\./,"").replace(/\.$/,"");return normalizedHost===suffix||normalizedHost.endsWith(`.${suffix}`)})}function matchesRouteHost(rawUrl,suffixes){if(!suffixes?.length)return!0;try{let parsed=new URL(rawUrl,location.href),hostname3=parsed.protocol==="http:"||parsed.protocol==="https:"?parsed.hostname:location.hostname;return matchesHostSuffix(hostname3,suffixes)}catch{return matchesHostSuffix(location.hostname,suffixes)}}function resolveSchemeValue(raw,depth){if(depth>3)return null;let value=raw;try{value=decodeURIComponent(raw)}catch{}if(value.startsWith("{"))try{let found=pickUrl(JSON.parse(value));if(!found)return null;value=found}catch{return null}if(/^https?:/i.test(value))return value;if(/^[a-z][a-z0-9+.-]*:/i.test(value))return mapScheme(value,depth+1);let nestedUrl=extractQuery(value,"url");return nestedUrl?resolveSchemeValue(nestedUrl,depth+1):null}function mapScheme(url2,depth=0){if(depth>3)return null;let lower=url2.toLowerCase();for(let rule of config2.schemes){if(!matchesRouteHost(url2,rule.hostSuffixes))continue;let normalizedMatch=rule.match.toLowerCase(),matchedUrl=url2;if(!lower.startsWith(normalizedMatch)){if(!normalizedMatch.startsWith("/"))continue;try{let parsed=new URL(url2,location.href);if(matchedUrl=`${parsed.pathname}${parsed.search}${parsed.hash}`,!matchedUrl.toLowerCase().startsWith(normalizedMatch))continue}catch{continue}}if(rule.targetPath){let suffix=matchedUrl.slice(rule.match.length);if(suffix&&!suffix.startsWith("?")&&!suffix.startsWith("#"))continue;try{let source=new URL(matchedUrl),origin=location.origin;if(rule.targetHostPrefix){let hostname3=location.hostname.toLowerCase(),domainSuffix=hostname3==="wapa.taobao.com"||hostname3.endsWith(".wapa.taobao.com")?"wapa.taobao.com":hostname3==="m.taobao.com"||hostname3.endsWith(".m.taobao.com")?"m.taobao.com":"";domainSuffix&&(origin=`https://${rule.targetHostPrefix}.${domainSuffix}`)}let target=new URL(rule.targetPath,`${origin}/`);target.search=source.search,target.hash=source.hash;for(let[key,value]of Object.entries(rule.targetParams??{}))target.searchParams.has(key)||target.searchParams.set(key,value);return target.href}catch{return null}}if(!rule.param)continue;let raw=extractQuery(matchedUrl,rule.param);if(!raw)return null;let resolved=resolveSchemeValue(raw,depth);if(!resolved||!rule.useCurrentOrigin)return resolved;try{let target=new URL(resolved);return`${location.origin}${target.pathname}${target.search}${target.hash}`}catch{return resolved}}return null}function firstRouteParam(params,names){for(let name of names){let value=params.get(name);if(value)return value}return""}function resolvePaymentCallbackUrl(rawUrl,paymentPageUrl,useCurrentOrigin,forwardParams,resultParam){if(!rawUrl)return null;try{let target=new URL(rawUrl,location.href);for(let name of forwardParams){let value=paymentPageUrl.searchParams.get(name);value&&!target.searchParams.get(name)&&target.searchParams.set(name,value)}resultParam&&target.searchParams.set(resultParam.name,JSON.stringify(resultParam.value));let resolved=useCurrentOrigin&&(target.protocol==="http:"||target.protocol==="https:")?`${location.origin}${target.pathname}${target.search}${target.hash}`:target.href;return decorateUrlWithFpt(resolved)}catch{return null}}function openPaymentCallback(rawUrl,paymentPageUrl,useCurrentOrigin,forwardParams,resultParam){let target=resolvePaymentCallbackUrl(rawUrl,paymentPageUrl,useCurrentOrigin,forwardParams,resultParam);target&&requestOpen(target,0,!1)}function handleMiniProgramPaymentRoute(rawUrl){let paymentPageUrl;try{paymentPageUrl=new URL(rawUrl,location.href)}catch{return!1}let normalizedPathname=paymentPageUrl.pathname.replace(/\/+$/,"")||"/",rule=config2.miniProgram?.paymentRoutes?.find(candidate=>(candidate.pathname.replace(/\/+$/,"")||"/")===normalizedPathname&&matchesHostSuffix(paymentPageUrl.hostname,candidate.hostSuffixes));if(!rule)return!1;let successUrl=firstRouteParam(paymentPageUrl.searchParams,rule.successUrlParams),failureUrl=firstRouteParam(paymentPageUrl.searchParams,rule.failureUrlParams),forwardParams=rule.forwardParams??[],useCurrentOrigin=rule.useCurrentOrigin===!0,paymentParams;try{let parsed=JSON.parse(paymentPageUrl.searchParams.get(rule.paymentParamsParam)??"");if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error;paymentParams=parsed,paymentParams.timeStamp!==void 0&&(paymentParams.timeStamp=String(paymentParams.timeStamp))}catch{return log3("微信支付参数解析失败,执行失败回跳",rawUrl),openPaymentCallback(failureUrl,paymentPageUrl,useCurrentOrigin,forwardParams),!0}return showPaymentDialog("wx.requestPayment",paymentParams,result=>{openPaymentCallback(successUrl,paymentPageUrl,useCurrentOrigin,forwardParams,rule.successResultParam?{name:rule.successResultParam,value:result}:void 0)},()=>{openPaymentCallback(failureUrl,paymentPageUrl,useCurrentOrigin,forwardParams)}),!0}function finishMiniProgramNativeRoute(action,result,storageId){handleResume({data:action==="subscribeMessage"?result:void 0,storageId,callbackId:0,final:!0})}function handleMiniProgramNativeRoute(rawUrl){let nativePageUrl;try{nativePageUrl=new URL(rawUrl,location.href)}catch{return!1}let normalizedPathname=nativePageUrl.pathname.replace(/\/+$/,"")||"/",action=nativePageUrl.searchParams.get("action");if(action!=="navigateMiniProgram"&&action!=="subscribeMessage"||!config2.miniProgram?.nativeRoutes?.find(candidate=>(candidate.pathname.replace(/\/+$/,"")||"/")===normalizedPathname&&candidate.actions.includes(action)&&matchesHostSuffix(nativePageUrl.hostname,candidate.hostSuffixes)))return!1;let params={};nativePageUrl.searchParams.forEach((value,name)=>{params[name]=value});let storageId=nativePageUrl.searchParams.get("__storage_id");return handlePageVisibility(!0),showMiniProgramActionDialog(action,params,result=>finishMiniProgramNativeRoute(action,result,storageId),result=>finishMiniProgramNativeRoute(action,result,storageId)),!0}function handleMiniProgramPostMessage(data){let rules=config2.miniProgram?.messageRules;if(!rules?.length)return!1;let messages=Array.isArray(data)?data:[data],handled=!1;for(let value of messages){if(!value||typeof value!="object"||Array.isArray(value))continue;let message=value;if(typeof message.type!="string")continue;let rule=rules.find(candidate=>candidate.type===message.type&&matchesHostSuffix(location.hostname,candidate.hostSuffixes));rule&&(handled=!0,rule.action==="stageBackData"?(pendingMiniProgramBackData=message.data,hasPendingMiniProgramBackData=!0):rule.action==="closeAll"&&(isTop?requestCloseAll(message.data)||requestClose(message.data):window.top?.postMessage({source:SRC,type:"closeAll",data:message.data},"*")))}return handled}function matchesImagePickerScheme(url2){let lower=url2.toLowerCase();return config2.imagePicker?.schemes.some(scheme=>lower.startsWith(scheme))===!0}function handleMaybeScheme(url2){if(typeof url2!="string"||!url2||!/^[a-z][a-z0-9+.-]*:/i.test(url2)||/^(https?|about|blob|data|javascript):/i.test(url2))return!1;let mapped=mapScheme(url2);return mapped?(log3("scheme 映射为 H5 open:",url2,"→",mapped),requestOpen(decorateUrlWithFpt(mapped),0,!1)):log3("外部 scheme 已拦截(真机表现为唤端):",url2),!0}function handleResume(msg){let{data,storageId,callbackId,final,gotoEvent,silent}=msg;if(gotoEvent&&dispatchGotoEvent(data),callbackId&&callbacks[callbackId]){if(!silent)try{callbacks[callbackId]({backdata:data})}catch(e){console.error(TAG,"callbackCommand 执行失败",e)}final&&delete callbacks[callbackId]}if(data&&typeof data=="object"&&storageId)try{let d={...data};d.__$data=!0,d.__$storageId=String(storageId),localStorage.setItem("XPI_BACK_LISTENER_DATA_STORAGE",JSON.stringify(d))}catch{}simulatedPageHidden?handlePageVisibility(!1):dispatchActiveEvents()}function dispatchGotoEvent(data){if(data!==void 0)try{document.dispatchEvent(new CustomEvent("WV.GotoEvent",{detail:{data}}))}catch{}}function sendUserTrack(params){if(!params||typeof params!="object")return;let p=params,logkey=typeof p.logkey=="string"?p.logkey:"",gmkey=typeof p.gmkey=="string"?p.gmkey:typeof p.event=="string"?p.event:"",gokey=typeof p.gokey=="string"?p.gokey:"";if(!/^\/[0-9A-Za-z._/-]+$/.test(logkey)||!/^[0-9A-Za-z_-]+$/.test(gmkey))return;let pageWindow=w,aplus=pageWindow.goldlog??pageWindow.aplus;if(typeof aplus?.send!="function")return;let configuredHost=aplus.getMetaInfo?.("aplus-rhost-g"),host2=(typeof configuredHost=="string"?configuredHost:"gm.mmstat.com").replace(/^https?:\/\//i,"").replace(/^\/\//,"").split("/")[0];if(!(!host2||!/^[0-9A-Za-z.-]+$/.test(host2)))try{aplus.send(`//${host2}${logkey}`,`gmkey=${encodeURIComponent(gmkey)}&gokey=${gokey}&ts=${Date.now()}`,"GET")}catch{}}function readNetworkState(){let connection=navigator.connection;return navigator.onLine?connection?.type==="wifi"?"wifi":connection?.effectiveType??"unknown":"fail"}function networkTypeNumber(state){return{wifi:2,"slow-2g":3,"2g":3,"3g":4,"4g":5,"5g":6,fail:7}[state]??0}function calendarTimestamp(value){if(typeof value=="number"&&Number.isFinite(value))return value;if(typeof value!="string"||!value.trim())return null;let numeric=Number(value);if(Number.isFinite(numeric)&&numeric>0)return numeric;let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}function calendarEventFromParams(params){let p=params&&typeof params=="object"?params:{},stringValue=(...values)=>values.find(value=>typeof value=="string")??"";return{title:stringValue(p.calendar_title,p.title),startTime:calendarTimestamp(p.calendar_start_ms??p.start_time??p.calendar_start_datetime),endTime:calendarTimestamp(p.calendar_end_ms??p.end_time??p.calendar_end_datetime),url:stringValue(p.calendar_url,p.url),note:stringValue(p.calendar_note,p.note),location:stringValue(p.calendar_location,p.location)}}function readCalendarEvents(){try{let parsed=JSON.parse(localStorage.getItem(CALENDAR_STORAGE_KEY)??"[]");return Array.isArray(parsed)?parsed.filter(event=>event!==null&&typeof event=="object"&&typeof event.title=="string"):[]}catch{return[]}}function writeCalendarEvents(events){try{return localStorage.setItem(CALENDAR_STORAGE_KEY,JSON.stringify(events)),!0}catch{return!1}}function sameCalendarEvent(stored,candidate){return candidate.url?stored.url===candidate.url:!!candidate.title&&stored.title===candidate.title&&(candidate.startTime===null||stored.startTime===candidate.startTime)&&(candidate.endTime===null||stored.endTime===candidate.endTime)}function calendarEventResponse(event){return{title:event.title,start_time:event.startTime,end_time:event.endTime,url:event.url,note:event.note,location:event.location}}function dispatch(api,params,onSuccess,onFailure,callbackCommandFn){let succeed=value=>{onSuccess&&setTimeout(()=>onSuccess(value),0)},failed=reason=>{onFailure&&setTimeout(()=>onFailure(reason),0)},kind=classify(api),silent=config2.actions.silent?.includes(api)===!0;if(silent||log3("桥调用",api,`(${kind})`,params??""),kind==="open"||kind==="navigate"){let p=params&&typeof params=="object"?params:{},navigationData=p.data&&typeof p.data=="object"?p.data:void 0;if(kind==="navigate"&&navigationData?.type==="back"){isTop?requestCloseAll(navigationData.data,!0)||dispatchGotoEvent(navigationData.data):window.top?.postMessage({source:SRC,type:"closeAll",data:navigationData.data,gotoEvent:!0},"*"),succeed({});return}let url2=pickUrl(params);if(!url2){failed("missing url");return}if(matchesImagePickerScheme(url2)){openImagePicker(callbackCommandFn),succeed({});return}if(handleMiniProgramPaymentRoute(url2)){succeed({});return}if(handleMiniProgramNativeRoute(url2)){succeed({});return}let wd=p.useWebdialog===!0||p.useWebdialog==="true"||p.useWebdialog===1||p.useWebdialog==="1";requestOpen(decorateUrlWithFpt(url2),stashCallback(callbackCommandFn),wd,p),succeed({});return}if(kind==="closeAll"){isTop?requestCloseAll(void 0):window.top?.postMessage({source:SRC,type:"closeAll"},"*"),succeed({});return}if(kind==="closeBackData"){let p=params&&typeof params=="object"?params:{};requestClose(Object.prototype.hasOwnProperty.call(p,"backdata")?p.backdata:pickCloseData(p)),succeed({});return}if(kind==="close"){if(api==="navigateBack"&&hasPendingMiniProgramBackData){let data=pendingMiniProgramBackData;pendingMiniProgramBackData=void 0,hasPendingMiniProgramBackData=!1,requestClose(data)}else requestClose(pickCloseData(params));succeed({});return}if(kind==="postMessage"){let p=params&&typeof params=="object"?params:{},data=p.data??p;handleMiniProgramPostMessage(data)||sendAppMessage({kind:"message",data}),succeed({});return}if(kind==="notifySubscribe"){let p=params&&typeof params=="object"?params:{};if(typeof p.name!="string"||!p.name){failed("missing notification name");return}onSuccess&¬ificationListeners.set(p.name,onSuccess);return}if(kind==="notifyUnsubscribe"){let p=params&&typeof params=="object"?params:{};typeof p.name=="string"&¬ificationListeners.delete(p.name),succeed({});return}if(kind==="notifyPost"){let p=params&&typeof params=="object"?params:{};if(typeof p.name!="string"||!p.name){failed("missing notification name");return}sendAppMessage({kind:"notification",name:p.name,data:p.data}),succeed({});return}if(kind==="sharedFileRead"||kind==="sharedFileWrite"||kind==="sharedDataGet"||kind==="sharedDataSet"){requestContainerData(kind,params&&typeof params=="object"?params:{},succeed,failed);return}if(kind==="legacyBroadcastCreate"||kind==="legacyBroadcastPost"||kind==="legacyBroadcastClose"){requestContainerData(kind,params&&typeof params=="object"?params:{},succeed,failed);return}if(kind==="title"){let title=params&&typeof params=="object"?params.title??params.name:void 0;if(typeof title=="string"&&title){systemBars.markStateExplicit();try{document.title=title,syncSimulatedTitleBar()}catch{}isTop||window.top?.postMessage({source:SRC,type:"title",title},"*")}succeed({});return}if(kind==="navigationBar"){applyNavigationBarState(api,params),succeed({});return}if(kind==="statusBar"){applyStatusBarState(params),succeed({});return}if(kind==="systemInfo"){let model=config2.globals.__DEVICE_MODEL__||"iPhone";succeed({language:config2.language,model,systemVersion:config2.systemVersion,statusBarHeight:config2.statusBarHeight,platform:config2.platform,brand:config2.platform==="iOS"?"Apple":"Android",client_version:config2.globals.__APP_VERSION__??"",client_type:config2.clientType});return}if(kind==="mtop"){callMtop(params??{},onSuccess,onFailure);return}if(kind==="mtopStream"){callMtopStream(params??{},succeed,failed);return}if(kind==="kvGet"||kind==="kvSet"||kind==="kvDelete"){let p=params&&typeof params=="object"?params:{},key=typeof p.key=="string"?p.key:"";if(!key){failed("missing key");return}try{let storageKey=`__mearl_app_kv__:${key}`;if(kind==="kvGet"){let stored=localStorage.getItem(storageKey);stored!==null?succeed(stored):failed(JSON.stringify({ret:["HY_FAILED"],msg:"key not found"}))}else if(kind==="kvSet"){let value=typeof p.value=="string"?p.value:p.value===void 0?"":JSON.stringify(p.value);localStorage.setItem(storageKey,value),succeed({})}else localStorage.removeItem(storageKey),succeed({})}catch{failed(JSON.stringify({ret:["HY_FAILED"],msg:"kv storage unavailable"}))}return}if(kind==="pageContext"){succeed({pageContext:void 0});return}if(kind==="memoryGet"||kind==="memorySet"||kind==="memoryDelete"){let p=params&&typeof params=="object"?params:{},key=typeof p.key=="string"?p.key:"";if(!key){failed({error_message:"missing key"});return}try{let storageKey=`__mearl_app_memory__:${key}`;if(kind==="memoryGet"){let value=sessionStorage.getItem(storageKey);succeed(value===null?{}:{value})}else if(kind==="memorySet"){let value=typeof p.value=="string"?p.value:p.value===void 0?"":JSON.stringify(p.value);sessionStorage.setItem(storageKey,value),succeed({key,success:!0})}else sessionStorage.removeItem(storageKey),succeed({key,success:!0})}catch{failed({error_message:"memory cache unavailable"})}return}if(kind==="availabilityMap"){let p=params&&typeof params=="object"?params:{},channels=Array.isArray(p.data)?p.data.filter(value=>typeof value=="string"):[];succeed({res:"success",data:Object.fromEntries(channels.map(channel=>[channel,!1]))});return}if(kind==="userInfo"){let userId=readFirstUserCookie(["unb"]),userName=readFirstUserCookie(["_w_tb_nick","_nk_","snk","tracknick"]);callUserInfo({...userId&&{userId},...userName&&{userName}},succeed);return}if(kind==="networkInfo"){let state=readNetworkState();if(api==="WVNetwork.getNetworkType"){succeed({type:{wifi:"WIFI","slow-2g":"2G","2g":"2G","3g":"3G","4g":"4G"}[state]??"UNKNOWN"});return}if(config2.profile==="alipay"||config2.profile==="koubei"){succeed({networkAvailable:state!=="fail",networkType:{wifi:"WIFI","slow-2g":"2G","2g":"2G","3g":"3G","4g":"4G",fail:"NOTREACHABLE"}[state]??"UNKNOWN"});return}let type=networkTypeNumber(state);succeed({type,state:state==="slow-2g"?"2g":state});return}if(kind==="networkQualityMonitor"){let p=params&&typeof params=="object"?params:{},action=typeof p.action=="string"?p.action:"";if(action==="add_notify_network_quality"){if(!stopNetworkQualityMonitor){let notify=()=>{try{document.dispatchEvent(new CustomEvent("WV.NETWORK_TYPE_CHANGED",{detail:{new_network_type:networkTypeNumber(readNetworkState())}}))}catch{}},connection=navigator.connection;window.addEventListener("online",notify),window.addEventListener("offline",notify),connection?.addEventListener?.("change",notify),stopNetworkQualityMonitor=()=>{window.removeEventListener("online",notify),window.removeEventListener("offline",notify),connection?.removeEventListener?.("change",notify)}}succeed({});return}if(action==="remove_notify_network_quality"){stopNetworkQualityMonitor?.(),stopNetworkQualityMonitor=null,succeed({});return}failed({error_message:"unsupported network quality monitor action"});return}if(kind==="beaconRequest"){let url2=pickUrl(params);if(!url2){failed({error_message:"missing url"});return}try{let resolved=new URL(url2,location.href);if(resolved.protocol!=="http:"&&resolved.protocol!=="https:"){failed({error_message:"unsupported request protocol"});return}let image=new Image;image.referrerPolicy="no-referrer-when-downgrade",image.src=resolved.href,succeed({})}catch{failed({error_message:"invalid url"})}return}if(kind==="calendar"){let p=params&&typeof params=="object"?params:{},events=readCalendarEvents();if(api==="store_calendar_event"){let event=calendarEventFromParams(p);if(!event.title||event.startTime===null){failed({error_message:"calendar title and start time are required"});return}let next=events.filter(stored=>!sameCalendarEvent(stored,event));if(next.push(event),!writeCalendarEvents(next)){failed({error_message:"calendar storage unavailable"});return}succeed({success:!0});return}if(api==="remove_calendar_event"){let candidate=calendarEventFromParams(p),next=events.filter(stored=>!sameCalendarEvent(stored,candidate));if(!writeCalendarEvents(next)){failed({error_message:"calendar storage unavailable"});return}succeed({success:!0,removed:events.length-next.length});return}if(api==="check_batch_calendar"){let batch=Array.isArray(p.batch)?p.batch:[];succeed({batch:batch.map(item=>{let candidate=calendarEventFromParams(item);return{...item&&typeof item=="object"?item:{},success:events.some(stored=>sameCalendarEvent(stored,candidate))}})});return}let urls=Array.isArray(p.urls)?p.urls.filter(value=>typeof value=="string"):typeof p.url=="string"?[p.url]:[],titles=Array.isArray(p.calendar_titles)?p.calendar_titles.filter(value=>typeof value=="string"):typeof p.calendar_title=="string"?[p.calendar_title]:[],matched=events.filter(event=>(urls.length===0||urls.includes(event.url))&&(titles.length===0||titles.includes(event.title)));succeed({events:matched.map(calendarEventResponse)});return}if(kind==="geolocation"){if(!navigator.geolocation){failed({errorCode:2,errorMsg:"geolocation unavailable"});return}let locate=()=>navigator.geolocation.getCurrentPosition(position=>{let{latitude,longitude,accuracy,altitude,altitudeAccuracy,heading,speed}=position.coords;succeed({latitude,longitude,accuracy,altitude,altitudeAccuracy,heading,speed,timestamp:position.timestamp})},error48=>failed({errorCode:error48.code,errorMsg:error48.message}),{enableHighAccuracy:!1,timeout:1e4,maximumAge:3e5});navigator.permissions?.query?navigator.permissions.query({name:"geolocation"}).then(status=>{status.state==="granted"?locate():failed({errorCode:1,errorMsg:"location permission not granted"})}).catch(locate):locate();return}if(kind==="permission"){let p=params&&typeof params=="object"?params:{},action=typeof p.action=="string"?p.action:"",permission=typeof p.permission=="string"?p.permission:"",permissionFailed=message=>failed({error_code:-1,error_message:message});if(permission==="album"||permission==="MODIFY_AUDIO_SETTINGS"){action==="check"||action==="request"?succeed({}):permissionFailed("unsupported permission action");return}let browserPermission=permission==="mic"?"microphone":permission==="camera"?"camera":permission==="lbs"?"geolocation":"";if(!browserPermission){permissionFailed("unsupported permission");return}if(action==="check"&&navigator.permissions?.query){navigator.permissions.query({name:browserPermission}).then(status=>{status.state==="granted"?succeed({}):permissionFailed("permission not granted")}).catch(()=>permissionFailed("permission check failed"));return}if(action==="request"&&(permission==="mic"||permission==="camera")){if(!navigator.mediaDevices?.getUserMedia){permissionFailed("media permission unavailable");return}navigator.mediaDevices.getUserMedia({audio:permission==="mic",video:permission==="camera"}).then(stream=>{for(let track of stream.getTracks())track.stop();succeed({})}).catch(()=>permissionFailed("permission denied"));return}if(action==="request"&&permission==="lbs"&&navigator.geolocation){navigator.geolocation.getCurrentPosition(()=>succeed({}),()=>permissionFailed("permission denied"),{timeout:1e4});return}permissionFailed("unsupported permission action");return}if(kind==="prefetch"){let p=params&&typeof params=="object"?params:{},url2=typeof p.url=="string"?p.url:"";if(!url2){failed({code:-1,errorMsg:"url is empty"});return}let resolvedUrl;try{resolvedUrl=new URL(url2,location.href).href}catch{failed({code:-1,errorMsg:"invalid url"});return}if(!Array.from(document.querySelectorAll('link[rel="prefetch"]')).some(link=>link.href===resolvedUrl)){let link=document.createElement("link");link.rel="prefetch",link.href=url2,(document.head??document.documentElement).appendChild(link)}succeed({});return}if(kind==="fptTrack"){let p=params&&typeof params=="object"?params:{},action=typeof p.action=="string"?p.action:"",actionParams=p.params&&typeof p.params=="object"?p.params:{},key=typeof actionParams.key=="string"?actionParams.key:"";if(action==="setFpt"){let value=typeof actionParams.value=="string"?actionParams.value:"";if(!key||!value||!/^[0-9A-Za-z._-]+$/.test(key)||!/^[0-9A-Za-z._-]+$/.test(value)||`${key}(${value})`.length>100){failed({error_message:"invalid fpt key or value"});return}setFptEntry(fptEntries,key,value),persistFpt()}else action==="deleteFpt"&&key&&(fptEntries.delete(key),persistFpt());succeed({});return}if(kind==="previewFile"){let p=params&&typeof params=="object"?params:{},fileUrl=typeof p.file_url=="string"?p.file_url:"",remoteUrl=typeof p.file_remote_url=="string"?p.file_remote_url:"",url2=(fileUrl.startsWith("http")?fileUrl:remoteUrl)||fileUrl||remoteUrl;url2?(requestOpen(url2,0,!1),succeed({})):failed({code:-1,errorMsg:"file_url is empty"});return}if(kind==="toast"){let error48=showAppToast(params);error48?failed({error_message:error48}):succeed({});return}if(kind==="unsupportedNativeInput"){let containerType="";try{containerType=new URL(location.href).searchParams.get("containerType")??""}catch{}!unsupportedNativeInputNotified&&(containerType==="h5_dx"||containerType==="flutter_h5")&&(unsupportedNativeInputNotified=!0,showAppToast({message:"当前页面使用原生输入框,请移除 URL 中的 containerType 参数以正常操作",milliseconds:4e3})),succeed({});return}if(kind==="payment"){log3("桥调用支付,等待用户确认",api,params),showPaymentDialog(api,params,succeed,failed);return}if(kind==="userTrack"){sendUserTrack(params),succeed({});return}if(kind==="response"){succeed(config2.actions.responses?.[api]);return}if(kind==="noop"){succeed({});return}silent||log3("未覆盖桥方法,回调 failure(页面库将走 H5 兜底):",api),failed(NOT_IMPLEMENTED_PAYLOAD)}let MEGA_SUPPORTED_APIS={stdPop:["showWeex2","showWeex","showH5","changeSize","close"],broadcast:["addEventListener","dispatchEvent","removeEventListener"],kvStorage:["setItem","getItem","removeItem","getAllKeys","clear","getCurrentInfo","getCurrentInfoAndKeys"],LifeCycle:["addPageLifeCycleListener","removePageLifeCycleListener"],Container:["interceptPageClose","disableInterceptPageClose"],navigator:["openURL","close","replace","setSystemBackBlockListener","removeSystemBackBlockListener"],NavBar:["setTitle"],Router:["popPage"]};function isMegaApiSupported(ability,api){return typeof ability=="string"&&typeof api=="string"&&MEGA_SUPPORTED_APIS[ability]?.includes(api)===!0}function megaParams(value){return value&&typeof value=="object"&&!Array.isArray(value)?value:{}}function megaError(callback,statusCode,message){emitMegaCallback(callback,{statusCode,type:"result",data:{errorMessage:typeof message=="string"?message:String(message??"")}})}function cloneMegaDetail(value){if(value===void 0)return{success:!0,value:void 0};try{return{success:!0,value:JSON.parse(JSON.stringify(value))}}catch{return{success:!1}}}function megaSuccess(data={}){return{statusCode:0,type:"result",data}}function megaFailure(message){return{statusCode:500,type:"result",data:{errorMessage:message}}}function megaKVParams(params){return{bizId:typeof params.bizID=="string"?params.bizID:typeof params.bizId=="string"?params.bizId:"",key:typeof params.key=="string"?params.key:"",value:typeof params.value=="string"?params.value:null}}function megaStringByteLength(value){try{return typeof TextEncoder=="function"?new TextEncoder().encode(value).length:value.length}catch{return value.length}}function megaKVUsedSize(entries){let size=0;for(let value of entries.values())size+=megaStringByteLength(value);return size}function reportMegaKVMutation(operation,bizId,key="",value,onSuccess,onFailure){requestContainerData("megaKVMutation",{operation,bizId,key,...value===void 0?{}:{value}},()=>onSuccess?.(),reason=>{log3("KVStorage 容器同步失败:",reason),onFailure?.(reason)})}function completeMegaKVMutation(operation,bizId,key,value,synchronous,callback){let result=megaSuccess();return reportMegaKVMutation(operation,bizId,key,value,synchronous?void 0:()=>emitMegaCallback(callback,result),synchronous?void 0:reason=>emitMegaCallback(callback,megaFailure(String(reason??"container sync failed")))),synchronous?result:null}function executeMegaKVStorage(api,params,synchronous,callback){let{bizId,key,value}=megaKVParams(params);if(!bizId)return megaFailure("missing bizID");let entries=megaKVStorage.get(bizId)??new Map;if(api==="setItem"){if(!key)return megaFailure("missing key");if(value===null||value==="")return megaFailure("missing value");let previousSize=megaStringByteLength(entries.get(key)??"");return megaKVUsedSize(entries)-previousSize+megaStringByteLength(value)>MEGA_KV_TOTAL_SIZE?megaFailure("KVStorage quota exceeded"):(entries.set(key,value),megaKVStorage.set(bizId,entries),megaKVMutationVersion+=1,persistMegaKVStorage(),completeMegaKVMutation("set",bizId,key,value,synchronous,callback))}if(api==="getItem"){if(!key)return megaFailure("missing key");let result=entries.get(key)??"";return megaSuccess(synchronous?{result}:result)}if(api==="removeItem")return key?(entries.delete(key),entries.size===0&&megaKVStorage.delete(bizId),megaKVMutationVersion+=1,persistMegaKVStorage(),completeMegaKVMutation("remove",bizId,key,void 0,synchronous,callback)):megaFailure("missing key");if(api==="getAllKeys"){let result=Array.from(entries.keys());return megaSuccess(synchronous?{result}:result)}if(api==="clear")return megaKVStorage.delete(bizId),megaKVMutationVersion+=1,persistMegaKVStorage(),completeMegaKVMutation("clear",bizId,"",void 0,synchronous,callback);if(api==="getCurrentInfo"||api==="getCurrentInfoAndKeys"){let data={totalSize:MEGA_KV_TOTAL_SIZE,freeSize:Math.max(MEGA_KV_TOTAL_SIZE-megaKVUsedSize(entries),0)};return api==="getCurrentInfoAndKeys"&&(data.keys=Array.from(entries.keys())),megaSuccess(data)}return{statusCode:405,type:"result",data:{}}}function handleMegaLifeCycle(api,callback){if(api==="addPageLifeCycleListener"){callback&&megaLifeCycleListeners.add(callback),emitMegaCallback(callback,megaSuccess());return}if(api==="removePageLifeCycleListener"){let listeners=Array.from(megaLifeCycleListeners);megaLifeCycleListeners.clear(),emitMegaCallback(callback,megaSuccess());for(let listener of listeners)emitMegaCallback(listener,{statusCode:99,type:"finish",data:{}});return}megaError(callback,405,`LifeCycle.${api} is not supported`)}function handleMegaContainer(api,callback){if(api==="interceptPageClose"){callback&&megaPageCloseListeners.add(callback),emitMegaCallback(callback,megaSuccess());return}if(api==="disableInterceptPageClose"){let listeners=Array.from(megaPageCloseListeners);megaPageCloseListeners.clear(),emitMegaCallback(callback,megaSuccess());for(let listener of listeners)emitMegaCallback(listener,{statusCode:99,type:"finish",data:{}});return}megaError(callback,405,`Container.${api} is not supported`)}function megaNavigationUrl(params){let rawUrl=pickUrl(params);if(!rawUrl)return null;if(!params.extQuery||typeof params.extQuery!="object"||Array.isArray(params.extQuery))return rawUrl;try{let target=new URL(rawUrl,location.href);for(let[key,value]of Object.entries(params.extQuery))value!=null&&target.searchParams.set(key,String(value));return target.href}catch{return rawUrl}}function handleMegaNavigator(api,params,callback){if(api==="openURL"||api==="replace"){let url2=megaNavigationUrl(params);if(!url2){megaError(callback,500,"missing url");return}let callbackId=api==="openURL"&&callback?stashCallback(value=>{let backdata=value&&typeof value=="object"?value.backdata:void 0;emitMegaCallback(callback,{statusCode:1,type:"onResult",data:{result:!0,...backdata===void 0?{}:{data:backdata}}}),emitMegaCallback(callback,{statusCode:99,type:"finish",data:{}})}):0;requestOpen(url2,callbackId,!1,{...params,...api==="replace"?{__mearlReplace:!0}:{}}),emitMegaCallback(callback,megaSuccess());return}if(api==="close"){emitMegaCallback(callback,megaSuccess()),requestClose(void 0);return}if(api==="setSystemBackBlockListener"){megaSystemBackListener&&megaSystemBackListener!==callback&&emitMegaCallback(megaSystemBackListener,{statusCode:99,type:"finish",data:{}}),megaSystemBackListener=callback??null,emitMegaCallback(callback,megaSuccess());return}if(api==="removeSystemBackBlockListener"){let listener=megaSystemBackListener;megaSystemBackListener=null,emitMegaCallback(callback,megaSuccess()),listener&&emitMegaCallback(listener,{statusCode:99,type:"finish",data:{}});return}megaError(callback,405,`navigator.${api} is not supported`)}function handleMegaNavBar(api,params,callback){if(api!=="setTitle"){megaError(callback,405,`NavBar.${api} is not supported`);return}applyNavigationBarState(api,params),emitMegaCallback(callback,megaSuccess())}function handleMegaRouter(api,callback){if(api!=="popPage"){megaError(callback,405,`Router.${api} is not supported`);return}emitMegaCallback(callback,megaSuccess()),requestClose(void 0)}function handleMegaStdPop(api,params,callback){if(api==="showH5"||api==="showWeex2"||api==="showWeex"){let url2=pickUrl(params),popId=typeof params.popId=="string"?params.popId.trim():"";if(!url2||!popId){megaError(callback,500,url2?"missing popId":"missing url");return}let callbackId=stashCallback(value=>{let result=value&&typeof value=="object"&&"backdata"in value?value.backdata:void 0;emitMegaCallback(callback,{statusCode:1,type:"onClose",data:result}),emitMegaCallback(callback,{statusCode:99,type:"finish"})});requestOpen(url2,callbackId,!0,{...params,__mearlMegaPopId:popId}),emitMegaCallback(callback,{statusCode:0,type:"result",data:{}});return}if(api==="close"){let popId=typeof params.popId=="string"?params.popId.trim():"";if(!popId){megaError(callback,500,"missing popId");return}let cloned=cloneMegaDetail(params.result);if(!cloned.success){megaError(callback,500,"result is not serializable");return}requestContainerData("megaPopClose",{popId,result:cloned.value},()=>emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),reason=>megaError(callback,500,reason));return}if(api==="changeSize"){let popId=typeof params.popId=="string"?params.popId.trim():"";if(!popId){megaError(callback,500,"missing popId");return}requestContainerData("megaPopResize",{...params,popId},()=>emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),reason=>megaError(callback,500,reason));return}megaError(callback,405,`stdPop.${api} is not supported`)}function handleMegaBroadcast(api,params,callback){let bizId=megaBroadcastBizId(params.bizId),eventName=typeof params.eventName=="string"?params.eventName.trim():"";if(!eventName){megaError(callback,500,"missing eventName");return}if(api==="addEventListener"){if(!callback)return;let id=`mearl-mega-listener-${++megaListenerSeq}`;megaBroadcastListeners.set(id,{id,bizId,eventName,once:params.once===!0,callback}),emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),emitMegaCallback(callback,{statusCode:1,type:"onAdd",data:{listenerId:id}});return}if(api==="dispatchEvent"){let detail=cloneMegaDetail(params.detail);if(!detail.success){megaError(callback,500,"detail is not serializable");return}requestContainerData("megaBroadcast",{message:{kind:"megaBroadcast",bizId,eventName,detail:detail.value}},()=>emitMegaCallback(callback,{statusCode:0,type:"result",data:{}}),reason=>megaError(callback,500,reason));return}if(api==="removeEventListener"){let listenerId=typeof params.listenerId=="string"?params.listenerId:"",removed=[];for(let listener of Array.from(megaBroadcastListeners.values()))listener.bizId!==bizId||listener.eventName!==eventName||listenerId&&listener.id!==listenerId||(megaBroadcastListeners.delete(listener.id),removed.push(listener));emitMegaCallback(callback,{statusCode:0,type:"result",data:{}});for(let listener of removed)emitMegaCallback(listener.callback,{statusCode:99,type:"finish"});return}megaError(callback,405,`broadcast.${api} is not supported`)}function makeMegaBridge(){return{asyncCall:(ability,api,rawParams,callback)=>{let params=megaParams(rawParams);if(ability==="ability"&&api==="available"){emitMegaCallback(callback,{statusCode:0,type:isMegaApiSupported(params.ability,params.api)?"YES":"NO",data:{}});return}if(ability==="ability"&&api==="batchFinishTrace"){emitMegaCallback(callback,{statusCode:0,type:"result",data:{}});return}if(!isMegaApiSupported(ability,api)){megaError(callback,405,`${ability}.${api} is not supported`);return}if(ability==="stdPop")handleMegaStdPop(api,params,callback);else if(ability==="broadcast")handleMegaBroadcast(api,params,callback);else if(ability==="kvStorage"){let result=executeMegaKVStorage(api,params,!1,callback);result&&emitMegaCallback(callback,result)}else ability==="LifeCycle"?handleMegaLifeCycle(api,callback):ability==="Container"?handleMegaContainer(api,callback):ability==="navigator"?handleMegaNavigator(api,params,callback):ability==="NavBar"?handleMegaNavBar(api,params,callback):handleMegaRouter(api,callback)},syncCall:(ability,api,rawParams)=>{let params=megaParams(rawParams);return ability==="ability"&&api==="available"?{statusCode:0,type:isMegaApiSupported(params.ability,params.api)?"YES":"NO",data:{}}:ability==="kvStorage"&&isMegaApiSupported(ability,api)?executeMegaKVStorage(api,params,!0)??megaFailure("container sync pending"):{statusCode:405,type:"result",data:{}}}}}function makeBridge(style){if(style==="mega")return makeMegaBridge();if(style==="easybikeNative"){let callNative=rawPayload=>{let payload;try{payload=typeof rawPayload=="string"?JSON.parse(rawPayload):rawPayload??{}}catch{return}let classMap=typeof payload.classMap=="string"?payload.classMap:"",method=typeof payload.method=="string"?payload.method:"",callbackId=typeof payload.callbackId=="string"||typeof payload.callbackId=="number"?String(payload.callbackId):"",params;try{params=typeof payload.params=="string"?payload.params?JSON.parse(payload.params):{}:payload.params??{}}catch{params={}}let complete=(code,data,msg="")=>{let callback=resolveWindowFunction("callBack");callbackId&&callback&&callback({callbackId,code,data,msg})};dispatch(`${classMap}.${method}`,params,value=>complete(0,value),error48=>complete(1,void 0,typeof error48=="string"?error48:String(error48??"")))};return{postMessage:callNative,callNative}}if(style==="windvane")return{isAvailable:!0,version:"8.7.0",call:(cls,method,params,succ,fail2)=>dispatch(`${cls}.${method}`,params,succ,fail2)};if(style==="fliggy"||style==="alipay"||style==="callback"){let bridge={call:(api,params,succ,fail2)=>{typeof params=="function"&&(fail2=succ,succ=params,params=void 0);let p=params&&typeof params=="object"?params:{},successFn=succ??(typeof p.success_callback=="function"?p.success_callback:void 0)??(typeof p.successCallback=="function"?p.successCallback:void 0),failureFn=fail2??(typeof p.fail_callback=="function"?p.fail_callback:void 0)??(typeof p.failure_callback=="function"?p.failure_callback:void 0)??(typeof p.failCallback=="function"?p.failCallback:void 0)??(typeof p.failureCallback=="function"?p.failureCallback:void 0);dispatch(api,p,res=>successFn?.(res),err=>{failureFn?failureFn(err):successFn?.({error:err})},p.callbackCommand??p.callback_command)},pushBack:(prefixOrApi,apiOrParams,paramsOrSucc,succ)=>{let api=prefixOrApi,params=apiOrParams,success2=paramsOrSucc;typeof apiOrParams=="string"&&(api=apiOrParams,params=paramsOrSucc,success2=succ);let p=params??{},successFn=(typeof success2=="function"?success2:void 0)??(typeof p.successCallback=="function"?p.successCallback:void 0);return dispatch(api,p,res=>successFn?.(res),void 0,p.callbackCommand??p.callback_command),bridge},sendUriScheme:uri=>(handleMaybeScheme(uri),bridge)};if(style==="fliggy"){let normalizedAppName=(config2.globals.__APP_NAME__??"").toUpperCase(),os12=config2.clientType==="iphone"?"ios":"android",isAliApp=name=>normalizedAppName===name.toUpperCase();Object.assign(bridge,{version:"1.0.21",device:{os:os12,OS:config2.platform,type:os12,version:config2.systemVersion,model:config2.globals.__DEVICE_MODEL__??""},platform:os12,isAliApp,isTmall:isAliApp("TM"),isTaobao:isAliApp("TB"),isAlipay:isAliApp("AP"),isAlitrip:isAliApp("LX"),isKoubei:isAliApp("KB"),isElm:isAliApp("ELMC"),isGaode:isAliApp("amap"),isUC:/UCBrowser/i.test(config2.userAgent),isWeibo:/Weibo/i.test(config2.userAgent),isWeixin:/MicroMessenger/i.test(config2.userAgent),isWindVane:config2.bridges.some(item=>item.style==="windvane"),isAlipayClient:/AlipayClient/i.test(config2.userAgent)})}return bridge}if(style==="btrip")return{call:(api,params)=>dispatch(api,params??{},void 0,void 0)};if(style==="invoke")return{invoke:(api,params)=>{let p=params??{};dispatch(api,p,p.success,p.fail)}};if(style==="callHandler")return{callHandler:(api,params)=>dispatch(api,params??{},void 0,void 0)};if(style==="amap")return{ready:cb=>cb?.(),send:(msg,cb)=>{let m=msg??{};dispatch(typeof m.action=="string"?m.action:"",m,res=>cb?.(res),err=>cb?.({error:err}))}};if(style==="didi")return{openPage:params=>dispatch("openPage",params??{},void 0,void 0),closePage:params=>dispatch("closePage",params??{},void 0,void 0)};if(style==="wechatMiniProgram"){let invoke2=(api,params)=>{let p=params&&typeof params=="object"?params:{};dispatch(api,p,value=>{p.success?.(value),p.complete?.(value)},error48=>{p.fail?.(error48),p.complete?.(error48)})};return{navigateTo:params=>invoke2("navigateTo",params),redirectTo:params=>invoke2("redirectTo",params),switchTab:params=>invoke2("switchTab",params),reLaunch:params=>invoke2("reLaunch",params),navigateBack:params=>invoke2("navigateBack",params),postMessage:params=>invoke2("postMessage",params),getEnv:callback=>{callback&&setTimeout(()=>callback({miniprogram:!0}),0)}}}return{}}function setGlobal(path25,value){let parts=path25.split("."),obj=w;for(let i=0;i<parts.length-1;i++){let cur=obj[parts[i]];(!cur||typeof cur!="object")&&(obj[parts[i]]={}),obj=obj[parts[i]]}obj[parts[parts.length-1]]=value}function setPersistentGlobal(path25,value){let parts=path25.split(".").filter(Boolean);if(parts.length<2){setGlobal(path25,value);return}let[rootKey,...nestedParts]=parts,isObjectLike=candidate=>typeof candidate=="object"&&candidate!==null||typeof candidate=="function",attachBridge=candidate=>{let root=isObjectLike(candidate)?candidate:{},obj=root;for(let index=0;index<nestedParts.length-1;index+=1){let key=nestedParts[index],child=obj[key];if(!isObjectLike(child))try{obj[key]={}}catch{return root}obj=obj[key]}let leaf=nestedParts[nestedParts.length-1];try{Object.defineProperty(obj,leaf,{configurable:!1,enumerable:!0,get:()=>value,set:()=>{}})}catch{try{obj[leaf]=value}catch{}}return root},currentRoot=attachBridge(w[rootKey]);try{Object.defineProperty(w,rootKey,{configurable:!1,enumerable:!0,get:()=>currentRoot,set:next=>{currentRoot=attachBridge(next)}})}catch{w[rootKey]=currentRoot}}if(config2.bridges.some(spec=>spec.style==="mega")){let hydrationVersion=megaKVMutationVersion;requestContainerData("megaKVSnapshot",{},value=>{let entries=value&&typeof value=="object"?value.entries:void 0;megaKVMutationVersion===hydrationVersion&&replaceMegaKVStorage(entries)},()=>{})}for(let spec of config2.bridges)try{let bridge=makeBridge(spec.style);spec.persistent?setPersistentGlobal(spec.global,bridge):setGlobal(spec.global,bridge)}catch(e){console.error(TAG,"桥安装失败:",spec.global,e)}return{mapScheme,handleMaybeScheme,handleAppMessage,handleNativeBack,handleResume,handlePageVisibility,applyRuntimeResponses}}function installAppProfileContainerStack(config2,environment,links){let{SRC,TAG,simulateSystemBars,ROOT_FRAME_NAME,LAYER_FRAME_NAME,isTop,isRootFrame,isLayerFrame,isContainerFrame,usesRootContainer,log:log3}=environment,{pageTransport}=links,initialLayerTitleBarState=url2=>links.getSystemBars().initialLayerTitleBarState(url2),resolvedTitleBarState=layer=>links.getSystemBars().resolvedTitleBarState(layer),parseReportedTitleBarState=value=>links.getSystemBars().parseReportedTitleBarState(value),createSimulatedNavigationBarView=(placement,onBack)=>links.getSystemBars().createNavigationBarView(placement,onBack),destroySimulatedNavigationBarView=view=>links.getSystemBars().destroyNavigationBarView(view),syncLayerViewport=(layer,state)=>links.getSystemBars().syncLayerViewport(layer,state),syncActiveSystemBars=()=>links.getSystemBars().syncActiveSystemBars(),syncSimulatedTitleBar=()=>links.getSystemBars().syncSimulatedTitleBar(),rootContainerActive=!1,rootFrame=null,rootBusinessUrl=location.href,webViewEnvironmentRequestSeq=0,simulatedPageHidden=!1,runtimeResponses=null;function syncSimulatorStateToWindow(target){target&&(runtimeResponses&&target.postMessage({source:SRC,type:"runtimeResponses",profile:config2.profile,responses:runtimeResponses},"*"),simulatedPageHidden&&target.postMessage({source:SRC,type:"simulatorVisibility",hidden:!0},"*"))}function startPreparedWebViewNavigation(frame,target,canCommit,registerCleanup){let insets=config2.safeAreaInsets??{top:config2.statusBarHeight,right:0,bottom:0,left:0};if(!usesRootContainer||!Object.values(insets).some(value=>value>0)){canCommit()&&(frame.src=target);return}let requestId=++webViewEnvironmentRequestSeq,settled=!1,fallbackTimer=0,cleanup=()=>{settled||(settled=!0,clearTimeout(fallbackTimer),window.removeEventListener("message",handleResponse),registerCleanup?.(null))},commitNavigation=fallbackReason=>{cleanup(),fallbackReason&&console.warn(TAG,"WebView 环境准备未完成,降级提交导航",{target,requestId,reason:fallbackReason}),canCommit()&&(frame.src=target)},handleResponse=event=>{if(event.source!==window||event.data?.source!=="mearl-content"||event.data?.type!=="APP_BRIDGE_PREPARE_WEBVIEW_RESPONSE"||event.data?.requestId!==requestId)return;let result=event.data.result;result?.success===!0?commitNavigation():commitNavigation(String(result?.error??"unknown preparation failure"))};registerCleanup?.(cleanup),window.addEventListener("message",handleResponse),fallbackTimer=setTimeout(()=>commitNavigation("preparation timed out after 500ms"),500);try{window.postMessage({source:SRC,type:"prepareWebView",requestId},"*")}catch(error48){commitNavigation(error48 instanceof Error?error48.message:String(error48))}}function installRootContainer(){if(!usesRootContainer||!/^https?:$/i.test(location.protocol))return;let shellRoot,frame;try{for(let cookie of config2.rootContainer?.initialCookies??[]){if(!cookie.name)continue;let parts=[`${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`,`Path=${cookie.path??"/"}`];cookie.domain&&parts.push(`Domain=${cookie.domain}`),document.cookie=parts.join("; ")}shellRoot=document.createElement("html");let shellHead=document.createElement("head"),charset=document.createElement("meta"),viewport=document.createElement("meta"),title=document.createElement("title"),shellBody=document.createElement("body");frame=document.createElement("iframe"),shellRoot.setAttribute("data-mearl-app-shell",""),shellBody.setAttribute("data-mearl-app-shell",""),charset.setAttribute("charset","utf-8"),viewport.name="viewport",viewport.content="width=device-width,initial-scale=1,viewport-fit=cover",shellHead.append(charset,viewport,title),shellRoot.append(shellHead,shellBody),shellRoot.style.cssText="width:100%;height:100%;margin:0;overflow:hidden;background:#fff;",shellBody.style.cssText="width:100%;height:100%;margin:0;overflow:hidden;background:#fff;",frame.name=ROOT_FRAME_NAME,frame.setAttribute("data-mearl-root-webview",config2.profile),frame.style.cssText="position:fixed;left:0;right:0;top:0;bottom:0;width:100%;height:100%;border:0;display:block;background:#fff;z-index:0;opacity:1;",frame.addEventListener("load",()=>{let committedSrc=frame.getAttribute("src");!committedSrc||committedSrc==="about:blank"||(syncSimulatorStateToWindow(frame.contentWindow),requestAnimationFrame(()=>{rootFrame!==frame||!frame.isConnected||(frame.setAttribute("data-mearl-webview-ready",""),syncSimulatedTitleBar())}))}),shellBody.appendChild(frame);let currentRoot=document.documentElement;currentRoot?document.replaceChild(shellRoot,currentRoot):document.appendChild(shellRoot)}catch(error48){console.warn(TAG,"根 WebView 容器创建失败,保留当前页面",error48),rootFrame=null;return}rootFrame=frame,rootContainerActive=!0;try{typeof window.stop=="function"&&window.stop()}catch(error48){console.warn(TAG,"停止外层文档加载失败,继续启动根 WebView",error48)}try{startPreparedWebViewNavigation(frame,rootBusinessUrl,()=>rootFrame===frame&&frame.isConnected)}catch(error48){console.warn(TAG,"根 WebView 环境准备启动失败,直接提交业务导航",error48),rootFrame===frame&&frame.isConnected&&(frame.src=rootBusinessUrl)}}installRootContainer();function normalizeProxyPathPrefix(prefix){let withLeadingSlash=prefix.startsWith("/")?prefix:`/${prefix}`;return withLeadingSlash.endsWith("/")?withLeadingSlash:`${withLeadingSlash}/`}function matchesProxyTarget(hostname3,suffixes){return suffixes.some(suffix=>hostname3===suffix||hostname3.endsWith(`.${suffix}`))}function mapLayerFrameUrl(url2){let proxy=config2.layerUrlProxy;if(!proxy||!location.hostname.startsWith(proxy.sourceHostPrefix))return url2;try{let target=new URL(url2,location.href);if(!/^https?:$/.test(target.protocol))return url2;let prefix=normalizeProxyPathPrefix(proxy.pathPrefix);if(target.hostname===location.hostname){if(target.pathname.startsWith(prefix))return url2;let derivedHost=location.pathname.startsWith(prefix)?location.pathname.slice(prefix.length).split("/")[0]:proxy.defaultTargetHost;return!derivedHost||!matchesProxyTarget(derivedHost,proxy.targetHostSuffixes)?url2:`${location.origin}${prefix}${derivedHost}${target.pathname}${target.search}${target.hash}`}return matchesProxyTarget(target.hostname,proxy.targetHostSuffixes)?`${location.origin}${prefix}${target.host}${target.pathname}${target.search}${target.hash}`:url2}catch{return url2}}function restoreLayerBusinessUrl(url2){let proxy=config2.layerUrlProxy;if(!proxy)return url2;try{let current=new URL(url2,location.href),prefix=normalizeProxyPathPrefix(proxy.pathPrefix);if(current.origin!==location.origin||!current.pathname.startsWith(prefix))return url2;let rest=current.pathname.slice(prefix.length),slash=rest.indexOf("/"),host=slash===-1?rest:rest.slice(0,slash);if(!host)return url2;let hostname3=new URL(`${current.protocol}//${host}`).hostname;if(!matchesProxyTarget(hostname3,proxy.targetHostSuffixes))return url2;let pathname=slash===-1?"/":rest.slice(slash);return`${current.protocol}//${host}${pathname}${current.search}${current.hash}`}catch{return url2}}let ANIM_MS=config2.animationMs??300;function boolParam(value,fallback){return value===!0||value===1||value==="1"||value==="true"?!0:value===!1||value===0||value==="0"||value==="false"?!1:value===""?!0:fallback}function numberParam(value,fallback,min,max){let parsed=typeof value=="number"?value:Number(value);return Number.isFinite(parsed)?Math.min(Math.max(parsed,min),max):fallback}function resolveOverlayPresentation(url2,params,explicitWebdialog){let query=null;try{query=new URL(url2,location.href).searchParams}catch{}let records=[],addRecord=value=>{value&&typeof value=="object"&&!Array.isArray(value)&&records.push(value)};addRecord(params?.pageParams),addRecord(params?.page_params),addRecord(params?.popConfig),addRecord(params?.data),addRecord(params?.param),addRecord(params);let read=key=>{for(let record2 of records)if(Object.prototype.hasOwnProperty.call(record2,key))return record2[key];return query?.has(key)?query.get(key):void 0},protocol=config2.overlay;if(!explicitWebdialog&&(!protocol||!boolParam(read(protocol.enabledParam),!1)))return null;let configuredTopRatio=protocol?read(protocol.topRatioParam):void 0,configuredHeightRatio=protocol?.heightRatioParam?read(protocol.heightRatioParam):void 0,configuredMaxHeight=read("maxHeight")??configuredHeightRatio,defaultTopRatio=protocol?.defaultTopRatio??.2;return{topRatio:configuredTopRatio!==void 0?numberParam(configuredTopRatio,defaultTopRatio,0,1):configuredMaxHeight!==void 0?1-numberParam(configuredMaxHeight,1-defaultTopRatio,0,1):defaultTopRatio,widthRatio:numberParam(read("maxWidth"),1,0,1),radius:numberParam((protocol?read(protocol.radiusParam):void 0)??read("cornerRadius"),protocol?.defaultRadius??0,0,50),maskAlpha:numberParam(protocol?read(protocol.maskAlphaParam):void 0,protocol?.defaultMaskAlpha??.3,0,1),tapClose:boolParam((protocol?read(protocol.tapCloseParam):void 0)??read("tapEnable"),protocol?.defaultTapClose??!0)}}function requestsPopBeforeOpen(url2,params){if(params?.__mearlReplace===!0)return!0;let key=config2.popBeforeOpenParam;if(!key)return!1;let records=[params?.pageParams,params?.page_params,params?.data,params?.param,params];for(let value of records){if(!value||typeof value!="object"||Array.isArray(value))continue;let record2=value;if(Object.prototype.hasOwnProperty.call(record2,key))return boolParam(record2[key],!1)}try{let query=new URL(url2,location.href).searchParams;return query.has(key)&&boolParam(query.get(key),!1)}catch{return!1}}let layers=[],forwardStack=[],layerSeq=0,enteringLayerCount=0,closingLayerCount=0,explicitLayerTitleBarStates=new Map,rootScrollStyles=null,pendingClose=null,nativeBackRequestSeq=0,pendingNativeBack=null,containerDataRequestSeq=0,containerDataCallbacks=new Map,sharedFiles=new Map,sharedData=new Map,legacyBroadcastChannels=new Set,MEGA_KV_STORAGE_KEY=`__mearl_mega_kv__:${config2.profile}`;function readMegaKVStorage(){let storage=new Map;try{let parsed=JSON.parse(localStorage.getItem(MEGA_KV_STORAGE_KEY)??"{}");if(!parsed||typeof parsed!="object"||Array.isArray(parsed))return storage;for(let[bizId,rawEntries]of Object.entries(parsed)){if(!rawEntries||typeof rawEntries!="object"||Array.isArray(rawEntries))continue;let entries=new Map;for(let[key,value]of Object.entries(rawEntries))typeof value=="string"&&entries.set(key,value);storage.set(bizId,entries)}}catch{}return storage}let megaKVStorage=readMegaKVStorage();function megaKVSnapshot(){let snapshot={};for(let[bizId,values]of megaKVStorage)snapshot[bizId]=Object.fromEntries(values);return snapshot}function persistMegaKVStorage(){try{localStorage.setItem(MEGA_KV_STORAGE_KEY,JSON.stringify(megaKVSnapshot()))}catch{}}let PENDING_CLOSE_TIMEOUT_MS=400,pendingHistoryDepth=null;function clearPendingClose(){pendingClose&&(clearTimeout(pendingClose.timer),pendingClose=null)}function clearPendingNativeBack(){pendingNativeBack&&(clearTimeout(pendingNativeBack.timer),pendingNativeBack=null)}function clearPendingHistoryDepth(){pendingHistoryDepth&&(clearTimeout(pendingHistoryDepth.timer),pendingHistoryDepth=null)}function syncHistoryAfterDirectClose(){clearPendingHistoryDepth();let depth=layers.length,timer=setTimeout(()=>{pendingHistoryDepth=null,console.warn(TAG,"WebView 已出栈,但浏览器历史未在预期时间内同步",{depth})},PENDING_CLOSE_TIMEOUT_MS);pendingHistoryDepth={depth,timer},history.back()}function armPendingClose(data,retries){clearPendingClose();let timer=setTimeout(()=>{pendingClose=null,log3("close 未等到 popstate,直接关栈顶兜底"),closeToDepth(Math.max(layers.length-1,0),data,!0)},PENDING_CLOSE_TIMEOUT_MS);pendingClose={data,retries,timer},history.back()}function parseStorageId(url2){try{return new URL(url2,location.href).searchParams.get("__storage_id")}catch{return null}}function titleBarStateCacheKey(url2){try{let parsed=new URL(url2,location.href);return parsed.hash="",parsed.href}catch{return url2}}function cacheExplicitTitleBarState(layer,state){explicitLayerTitleBarStates.set(titleBarStateCacheKey(layer.entryUrl),state),explicitLayerTitleBarStates.set(titleBarStateCacheKey(layer.url),state)}function readDepth(state){if(state&&typeof state=="object"){let d=state.__mearl_layer__;if(typeof d=="number")return d}return null}function mapUrlForSync(url2){let suffixes=config2.urlSyncHostSuffixes??[];try{let u=new URL(url2,location.href);if(!/^https?:$/.test(u.protocol)||!(suffixes.length===0||suffixes.some(s=>u.host===s||u.host.endsWith(`.${s}`))))return;if(u.origin===location.origin)return u.pathname+u.search+u.hash;let proxy=config2.layerUrlProxy;return proxy&&location.hostname.startsWith(proxy.sourceHostPrefix)&&matchesProxyTarget(u.hostname,proxy.targetHostSuffixes)?`${normalizeProxyPathPrefix(proxy.pathPrefix)}${u.host}${u.pathname}${u.search}${u.hash}`:u.pathname+u.search+u.hash}catch{return}}function createLayerEl(overlay,id){let el=document.createElement("div");el.setAttribute("data-mearl-layer",String(id)),el.style.cssText=`position:fixed;inset:0;z-index:${2147483e3+id%100*2};`;let frame=document.createElement("iframe");if(frame.name=LAYER_FRAME_NAME,frame.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-modals allow-downloads allow-popups"),frame.style.cssText="position:absolute;inset:0;width:100%;height:100%;border:0;display:block;background:#fff;z-index:0;opacity:1;",overlay){el.style.pointerEvents="none";let mask=document.createElement("div");mask.style.cssText=`position:absolute;inset:0;background:rgba(0,0,0,${overlay.maskAlpha});opacity:0;pointer-events:auto;`;let sheet=document.createElement("div"),width=overlay.widthRatio*100,left=(1-overlay.widthRatio)/2*100;return sheet.style.cssText=`position:absolute;left:${left}%;right:auto;bottom:0;width:${width}%;height:${(1-overlay.topRatio)*100}%;background:#fff;border-radius:${overlay.radius}px ${overlay.radius}px 0 0;overflow:hidden;pointer-events:auto;`,sheet.appendChild(frame),el.appendChild(mask),el.appendChild(sheet),{el,frame,animEl:sheet,mask}}return el.style.background="#fff",el.appendChild(frame),{el,frame,animEl:el,mask:null}}function setLayerInteractive(layer,interactive){layer.frame.style.pointerEvents=interactive?"":"none",layer.titleBarView&&(layer.titleBarView.root.style.pointerEvents=interactive?"":"none"),interactive?(layer.frame.removeAttribute("inert"),layer.frame.removeAttribute("aria-hidden"),layer.frame.removeAttribute("tabindex")):(layer.frame.setAttribute("inert",""),layer.frame.setAttribute("aria-hidden","true"),layer.frame.setAttribute("tabindex","-1"),layer.frame.blur()),layer.overlay?(layer.el.style.pointerEvents="none",layer.animEl.style.pointerEvents=interactive?"auto":"none",layer.mask&&(layer.mask.style.pointerEvents=interactive?"auto":"none")):layer.el.style.pointerEvents=interactive?"":"none"}function setRootFrameInteractive(interactive){rootFrame&&(rootFrame.style.pointerEvents=interactive?"":"none",interactive?(rootFrame.removeAttribute("inert"),rootFrame.removeAttribute("aria-hidden"),rootFrame.removeAttribute("tabindex")):(rootFrame.setAttribute("inert",""),rootFrame.setAttribute("aria-hidden","true"),rootFrame.setAttribute("tabindex","-1"),rootFrame.blur()))}function blockClosingLayerInteractions(layer){setLayerInteractive(layer,!1),layer.el.style.pointerEvents="auto"}function syncRootScrollLock(locked){let body=document.body;if(locked&&!rootScrollStyles){rootScrollStyles={html:document.documentElement.style.overflow,body:body?.style.overflow??null},document.documentElement.style.overflow="hidden",body&&(body.style.overflow="hidden");return}!locked&&rootScrollStyles&&(document.documentElement.style.overflow=rootScrollStyles.html,body&&rootScrollStyles.body!==null&&(body.style.overflow=rootScrollStyles.body),rootScrollStyles=null)}function syncLayerInteractivity(){let activeLayer=closingLayerCount===0&&enteringLayerCount===0?layers[layers.length-1]:void 0;for(let layer of layers)setLayerInteractive(layer,layer===activeLayer),!activeLayer&&layer===layers[layers.length-1]&&(layer.el.style.pointerEvents="auto");setRootFrameInteractive(layers.length===0&&enteringLayerCount===0&&closingLayerCount===0),syncRootScrollLock(layers.length>0||enteringLayerCount>0||closingLayerCount>0)}function finishLayerEntry(layer){layer.entering&&(layer.entering=!1,layer.enterTimer!==null&&clearTimeout(layer.enterTimer),layer.enterTimer=null,layer.enterTransitionEnd&&(layer.animEl.removeEventListener("transitionend",layer.enterTransitionEnd),layer.enterTransitionEnd=null),enteringLayerCount=Math.max(enteringLayerCount-1,0),syncLayerInteractivity())}function animateIn(layer){let t=layer.animEl;if(t.style.transform=layer.overlay?"translateY(100%)":"translateX(100%)",t.offsetWidth,t.style.transition=`transform ${ANIM_MS}ms ease`,t.style.transform="translate(0px, 0px)",layer.mask&&(layer.mask.style.transition=`opacity ${ANIM_MS}ms ease`,layer.mask.style.opacity="1"),ANIM_MS<=0){finishLayerEntry(layer);return}layer.enterTransitionEnd=event=>{event.target===t&&event.propertyName==="transform"&&finishLayerEntry(layer)},t.addEventListener("transitionend",layer.enterTransitionEnd),layer.enterTimer=setTimeout(()=>finishLayerEntry(layer),ANIM_MS+60)}function animateOut(layer,done){let t=layer.animEl;if(ANIM_MS<=0){t.style.transform=layer.overlay?"translateY(100%)":"translateX(100%)",layer.mask&&(layer.mask.style.opacity="0"),setTimeout(done,0);return}let settled=!1,fallbackTimer=0,finish=()=>{settled||(settled=!0,t.removeEventListener("transitionend",onTransitionEnd),clearTimeout(fallbackTimer),done())},onTransitionEnd=event=>{event.target===t&&event.propertyName==="transform"&&finish()};t.addEventListener("transitionend",onTransitionEnd),t.style.transition=`transform ${ANIM_MS}ms ease`,t.style.transform=layer.overlay?"translateY(100%)":"translateX(100%)",layer.mask&&(layer.mask.style.opacity="0"),fallbackTimer=setTimeout(finish,ANIM_MS+60)}function startLayerNavigation(layer,target){startPreparedWebViewNavigation(layer.frame,target,()=>!layer.closing&&layer.el.isConnected,cleanup=>{layer.navigationPreparationCleanup=cleanup})}function setPageVisibility(target,hidden){if(target===window){links.getBridgeProtocol().handlePageVisibility(hidden);return}try{target.postMessage({source:SRC,type:"simulatorVisibility",hidden},"*")}catch{}}function openLayer(url2,callbackId,overlay,openerWin,pushHistory,popId=null){clearPendingClose();let target=url2;if(!/^https?:/i.test(target)){let mapped=links.getBridgeProtocol().mapScheme(target);if(!mapped)return log3("open 失败,scheme 未映射:",url2),null;target=mapped}location.protocol==="https:"&&target.startsWith("http:")&&(target="https:"+target.slice(5));let presentation=overlay??resolveOverlayPresentation(target,void 0,!1);log3("open →",presentation?"(webdialog) ":"",target);let parts=createLayerEl(presentation,++layerSeq),restoredTitleBarState=explicitLayerTitleBarStates.get(titleBarStateCacheKey(target)),layer={id:layerSeq,win:parts.frame.contentWindow,frame:parts.frame,entryUrl:target,url:target,overlay:presentation,openerWin,callbackId,storageId:parseStorageId(target),popId,el:parts.el,animEl:parts.animEl,mask:parts.mask,entering:!0,enterTimer:null,enterTransitionEnd:null,closing:!1,navigationPreparationCleanup:null,titleBarState:restoredTitleBarState??initialLayerTitleBarState(target),titleBarStateExplicit:restoredTitleBarState!==void 0,titleBarStateReady:restoredTitleBarState!==void 0,titleBarView:null};if(popId&&layer.el.setAttribute("data-mearl-pop-id",popId),layer.mask&&presentation?.tapClose&&layer.mask.addEventListener("click",()=>requestOverlayClose(layer)),!presentation&&simulateSystemBars&&config2.titleBar&&(layer.titleBarView=createSimulatedNavigationBarView("layer",()=>requestNativeBack()),layer.titleBarView.root.setAttribute("data-mearl-layer-titlebar",String(layer.id)),parts.el.appendChild(layer.titleBarView.root)),layers.push(layer),setPageVisibility(openerWin,!0),enteringLayerCount+=1,syncLayerViewport(layer,layer.titleBarState),syncLayerInteractivity(),parts.frame.addEventListener("load",()=>{layer.win=parts.frame.contentWindow,parts.frame.name=LAYER_FRAME_NAME;let committedSrc=parts.frame.getAttribute("src");!committedSrc||committedSrc==="about:blank"||(syncSimulatorStateToWindow(parts.frame.contentWindow),requestAnimationFrame(()=>{layer.titleBarStateReady||layer.closing||!layer.el.isConnected||(layer.titleBarStateReady=!0,syncLayerViewport(layer,resolvedTitleBarState(layer)))}))}),(document.body??document.documentElement).appendChild(parts.el),layer.win=parts.frame.contentWindow,startLayerNavigation(layer,mapLayerFrameUrl(target)),animateIn(layer),pushHistory){forwardStack.length=0;try{history.pushState({__mearl_layer__:layers.length},"",mapUrlForSync(target))}catch{}}return layer}function replaceLayer(sourceLayer,url2,callbackId,overlay,popId=null){if(sourceLayer.closing||layers[layers.length-1]!==sourceLayer){openLayer(url2,callbackId,overlay,sourceLayer.win??window,!0,popId);return}let replacement=openLayer(url2,callbackId,overlay,sourceLayer.openerWin,!1,popId);if(!replacement)return;sourceLayer.navigationPreparationCleanup?.(),sourceLayer.navigationPreparationCleanup=null,sourceLayer.entering&&(sourceLayer.entering=!1,enteringLayerCount=Math.max(enteringLayerCount-1,0),sourceLayer.enterTimer!==null&&clearTimeout(sourceLayer.enterTimer),sourceLayer.enterTransitionEnd&&sourceLayer.animEl.removeEventListener("transitionend",sourceLayer.enterTransitionEnd));let sourceIndex=layers.indexOf(sourceLayer);sourceIndex>=0&&layers.splice(sourceIndex,1),destroySimulatedNavigationBarView(sourceLayer.titleBarView),sourceLayer.el.remove(),forwardStack.length=0,syncLayerInteractivity(),syncActiveSystemBars();try{history.replaceState({__mearl_layer__:layers.length},"",mapUrlForSync(replacement.url))}catch{}}function closeLayer(layer,data,final,gotoEvent=!1,resumeOpener=!0,silent=!1){if(layer.closing)return;layer.navigationPreparationCleanup?.(),layer.navigationPreparationCleanup=null,layer.entering&&(layer.entering=!1,enteringLayerCount=Math.max(enteringLayerCount-1,0),layer.enterTimer!==null&&clearTimeout(layer.enterTimer),layer.enterTimer=null,layer.enterTransitionEnd&&(layer.animEl.removeEventListener("transitionend",layer.enterTransitionEnd),layer.enterTransitionEnd=null)),layer.closing=!0;let idx=layers.indexOf(layer);idx>=0&&layers.splice(idx,1),closingLayerCount+=1,blockClosingLayerInteractions(layer),syncLayerInteractivity(),syncActiveSystemBars(),final?forwardStack.length=0:forwardStack.push({url:layer.url,overlay:layer.overlay,openerWin:layer.openerWin,callbackId:layer.callbackId,storageId:layer.storageId,popId:layer.popId}),log3("close ←",layer.url,data===void 0?"":data),animateOut(layer,()=>{if(destroySimulatedNavigationBarView(layer.titleBarView),layer.el.remove(),closingLayerCount=Math.max(closingLayerCount-1,0),syncLayerInteractivity(),syncActiveSystemBars(),!!resumeOpener)if(layer.openerWin===window)links.getBridgeProtocol().handleResume({data,storageId:layer.storageId,callbackId:layer.callbackId,final,gotoEvent,silent});else try{layer.openerWin.postMessage({source:SRC,type:"resume",data,storageId:layer.storageId,callbackId:layer.callbackId,final,gotoEvent,silent},"*")}catch{}})}function closeToDepth(depth,data,final){for(;layers.length>depth;){let revealsTarget=layers.length===depth+1;closeLayer(layers[layers.length-1],revealsTarget?data:void 0,final,!1,revealsTarget)}}function closeAllLayers(data,gotoEvent=!1){let depth=layers.length;for(;layers.length>0;){let isRootmostLayer=layers.length===1;closeLayer(layers[layers.length-1],isRootmostLayer?data:void 0,!0,isRootmostLayer&&gotoEvent,isRootmostLayer)}if(depth>0)try{history.go(-depth)}catch{}return depth>0}function requestOverlayClose(layer){if(!(layer.closing||layers[layers.length-1]!==layer)){if(!config2.overlay?.silentTapClose){for(let selector of config2.overlay?.tapCloseSelectors??[])try{let control=layer.frame.contentDocument?.querySelector(selector);if(typeof control?.click!="function")continue;control.click();return}catch{}requestCloseOnTop(void 0);return}pendingClose||pendingHistoryDepth||(closeLayer(layer,void 0,!0,!1,!0,!0),syncHistoryAfterDirectClose())}}function forwardToDepth(depth){for(;layers.length<depth&&forwardStack.length>0;){let entry=forwardStack.pop();openLayer(entry.url,entry.callbackId,entry.overlay,entry.openerWin,!1,entry.popId)}}function requestCloseOnTop(data){if(layers.length===0){history.back();return}if(rootContainerActive){closeLayer(layers[layers.length-1],data,!0),syncHistoryAfterDirectClose();return}armPendingClose(data,8)}function isActiveBusinessWindow(target){let topLayer=layers[layers.length-1];return topLayer?topLayer.frame.contentWindow===target:rootFrame?rootFrame.contentWindow===target:target===window}function finishNativeBack(requestId,target,handled){pendingNativeBack?.requestId!==requestId||pendingNativeBack.target!==target||(clearPendingNativeBack(),!handled&&isActiveBusinessWindow(target)&&requestCloseOnTop(void 0))}function requestNativeBack(){if(!isTop||pendingNativeBack)return;let target=layers[layers.length-1]?.frame.contentWindow??rootFrame?.contentWindow??window;if(!target||target===window){links.getBridgeProtocol().handleNativeBack()||requestCloseOnTop(void 0);return}let requestId=++nativeBackRequestSeq,timer=setTimeout(()=>finishNativeBack(requestId,target,!1),120);pendingNativeBack={requestId,target,timer};try{target.postMessage({source:SRC,type:"nativeBack",requestId},"*")}catch{finishNativeBack(requestId,target,!1)}}function layerForWindow(source){if(source)for(let layer of layers){if(layer.win===source)return layer;let currentWindow=layer.frame.contentWindow;if(currentWindow&¤tWindow===source)return layer.win=currentWindow,layer}}if(isTop){if(!rootContainerActive){let rawPushState=history.pushState.bind(history),rawReplaceState=history.replaceState.bind(history),withDepth=state=>state==null?{__mearl_layer__:layers.length}:typeof state=="object"&&!Array.isArray(state)?{...state,__mearl_layer__:layers.length}:state;try{history.pushState=function(...args){rawPushState(withDepth(args[0]),args[1],args[2])},history.replaceState=function(...args){rawReplaceState(withDepth(args[0]),args[1],args[2])}}catch{}}try{readDepth(history.state)===null&&history.replaceState({__mearl_layer__:0},"")}catch{}window.addEventListener("popstate",e=>{let depth=readDepth(e.state);if(pendingHistoryDepth){let expectedDepth=pendingHistoryDepth.depth;if(clearPendingHistoryDepth(),depth===expectedDepth)return;console.warn(TAG,"浏览器历史深度与 WebView 出栈事务不一致",{expectedDepth,actualDepth:depth})}if(rootContainerActive){if(depth===null)return;depth<layers.length?closeToDepth(depth,void 0,!1):depth>layers.length&&forwardToDepth(depth);return}if(pendingClose){if(depth!==null&&depth<layers.length){let{data}=pendingClose;clearPendingClose(),closeToDepth(depth,data,!0)}else if(pendingClose.retries>0)armPendingClose(pendingClose.data,pendingClose.retries-1);else{let{data}=pendingClose;clearPendingClose(),closeToDepth(layers.length-1,data,!0)}return}depth!==null&&(depth<layers.length?closeToDepth(depth,void 0,!1):depth>layers.length&&forwardToDepth(depth))})}function broadcastAppMessage(message){links.getBridgeProtocol().handleAppMessage(message);let targets=[rootFrame?.contentWindow??null,...layers.filter(layer=>!layer.closing).map(layer=>layer.frame.contentWindow)];for(let target of targets)if(!(!target||target===window))try{target.postMessage({source:SRC,type:"appMessage",message},"*")}catch{}}function closeMegaPop(popId,data){let index=layers.findIndex(layer=>layer.popId===popId&&!layer.closing);if(index<0)return!1;let closingDepth=layers.length-index;closeToDepth(index,data,!0);try{history.go(-closingDepth)}catch{}return!0}function resizeMegaPop(popId,params){let layer=layers.find(candidate=>candidate.popId===popId&&!candidate.closing);if(!layer?.overlay)return!1;if(params.maxHeight!==void 0){let maxHeight=numberParam(params.maxHeight,1-layer.overlay.topRatio,0,1);layer.overlay.topRatio=1-maxHeight,layer.animEl.style.height=`${maxHeight*100}%`}if(params.maxWidth!==void 0){let maxWidth=numberParam(params.maxWidth,1,0,1);layer.overlay.widthRatio=maxWidth,layer.animEl.style.width=`${maxWidth*100}%`,layer.animEl.style.left=`${(1-maxWidth)/2*100}%`,layer.animEl.style.right="auto"}return params.animated===!0&&(layer.animEl.style.transition="height 200ms ease, width 200ms ease, left 200ms ease"),!0}function executeContainerData(action,params){if(action==="sharedFileRead"||action==="sharedFileWrite"){let fileName=typeof params.fileName=="string"?params.fileName:"";if(!fileName)return{success:!1,value:"missing fileName"};if(action==="sharedFileRead")return{success:!0,value:{data:sharedFiles.get(fileName)??""}};let data=typeof params.data=="string"?params.data:String(params.data??"");return sharedFiles.set(fileName,data),{success:!0,value:{}}}if(action==="sharedDataGet"){let keys=Array.isArray(params.keys)?params.keys.filter(key=>typeof key=="string"):[],data={};for(let key of keys)sharedData.has(key)&&(data[key]=sharedData.get(key));return{success:!0,value:{data}}}if(action==="sharedDataSet"){if(!params.data||typeof params.data!="object"||Array.isArray(params.data))return{success:!1,value:"missing shared data"};for(let[key,value]of Object.entries(params.data))value==null?sharedData.delete(key):sharedData.set(key,value);return{success:!0,value:{}}}if(action==="megaBroadcast")return!params.message||typeof params.message!="object"||Array.isArray(params.message)?{success:!1,value:"missing broadcast message"}:(broadcastAppMessage(params.message),{success:!0,value:{}});if(action==="megaKVSnapshot")return{success:!0,value:{entries:megaKVSnapshot()}};if(action==="megaKVMutation"){let operation=typeof params.operation=="string"?params.operation:"",bizId=typeof params.bizId=="string"?params.bizId:"";if(!bizId)return{success:!1,value:"missing bizID"};let key=typeof params.key=="string"?params.key:"";if((operation==="set"||operation==="remove")&&!key)return{success:!1,value:"missing key"};if(operation==="set"){if(typeof params.value!="string")return{success:!1,value:"missing value"};let entries=megaKVStorage.get(bizId)??new Map;entries.set(key,params.value),megaKVStorage.set(bizId,entries)}else if(operation==="remove"){let entries=megaKVStorage.get(bizId);entries?.delete(key),entries?.size===0&&megaKVStorage.delete(bizId)}else if(operation==="clear")megaKVStorage.delete(bizId);else return{success:!1,value:"unsupported KVStorage operation"};return persistMegaKVStorage(),broadcastAppMessage({kind:"megaKVStorage",operation,bizId,key,value:params.value}),{success:!0,value:{}}}if(action==="legacyBroadcastCreate"){let instanceId=typeof params.instanceId=="string"?params.instanceId:"";return instanceId?(legacyBroadcastChannels.add(instanceId),{success:!0,value:{}}):{success:!1,value:"missing instanceId"}}if(action==="legacyBroadcastPost"){let instanceId=typeof params.instanceId=="string"?params.instanceId:"";return instanceId?legacyBroadcastChannels.has(instanceId)?(broadcastAppMessage({kind:"legacyBroadcast",instanceId,message:params.message}),{success:!0,value:{}}):{success:!1,value:"broadcast channel not found"}:{success:!1,value:"missing instanceId"}}if(action==="legacyBroadcastClose"){let instanceId=typeof params.instanceId=="string"?params.instanceId:"";return instanceId?(legacyBroadcastChannels.delete(instanceId),{success:!0,value:{}}):{success:!1,value:"missing instanceId"}}if(action==="megaPopClose"){let popId=typeof params.popId=="string"?params.popId:"";return popId?closeMegaPop(popId,params.result)?{success:!0,value:{}}:{success:!1,value:"popId not found"}:{success:!1,value:"missing popId"}}if(action==="megaPopResize"){let popId=typeof params.popId=="string"?params.popId:"";return popId?resizeMegaPop(popId,params)?{success:!0,value:{}}:{success:!1,value:"popId not found"}:{success:!1,value:"missing popId"}}return{success:!1,value:"unsupported container data action"}}function requestContainerData(action,params,onSuccess,onFailure){if(isTop){let result=executeContainerData(action,params);setTimeout(()=>result.success?onSuccess(result.value):onFailure(result.value),0);return}let requestId=++containerDataRequestSeq;containerDataCallbacks.set(requestId,{success:onSuccess,failure:onFailure});try{window.top?.postMessage({source:SRC,type:"containerDataRequest",requestId,action,params},"*")}catch(error48){containerDataCallbacks.delete(requestId),onFailure(error48 instanceof Error?error48.message:String(error48))}}function requestOpen(url2,callbackId,webdialog,params){let overlay=resolveOverlayPresentation(url2,params,webdialog),popBeforeOpen=requestsPopBeforeOpen(url2,params),popId=typeof params?.__mearlMegaPopId=="string"?params.__mearlMegaPopId:null;isTop?openLayer(url2,callbackId,overlay,window,!0,popId):window.top?.postMessage({source:SRC,type:"open",url:url2,callbackId,overlay,popBeforeOpen,popId},"*")}function requestClose(data){let payload;try{payload=data===void 0?void 0:JSON.parse(JSON.stringify(data))}catch{payload=void 0}isTop?requestCloseOnTop(payload):window.top?.postMessage({source:SRC,type:"close",data:payload},"*")}if(window.addEventListener("message",event=>{let msg=event.data;if(!(!msg||typeof msg!="object")){if(msg.source==="mearl-content"&&(msg.type==="APP_BRIDGE_SIMULATOR_VISIBILITY"||msg.type==="APP_BRIDGE_RUNTIME_RESPONSES")){if(!isTop||event.source!==window)return;if(msg.type==="APP_BRIDGE_SIMULATOR_VISIBILITY"&&typeof msg.hidden=="boolean"){simulatedPageHidden=msg.hidden,links.getBridgeProtocol().handlePageVisibility(msg.hidden);let lifecycleMessage={source:SRC,type:"simulatorVisibility",hidden:msg.hidden};rootFrame?.contentWindow?.postMessage(lifecycleMessage,"*");for(let layer of layers)layer.closing||layer.frame.contentWindow?.postMessage(lifecycleMessage,"*")}else if(msg.type==="APP_BRIDGE_RUNTIME_RESPONSES"&&msg.profile===config2.profile&&msg.responses&&typeof msg.responses=="object"&&!Array.isArray(msg.responses)){let responses=msg.responses;runtimeResponses={...runtimeResponses??{},...responses},links.getBridgeProtocol().applyRuntimeResponses(responses);let configMessage={source:SRC,type:"runtimeResponses",profile:config2.profile,responses};rootFrame?.contentWindow?.postMessage(configMessage,"*");for(let layer of layers)layer.closing||layer.frame.contentWindow?.postMessage(configMessage,"*")}return}if(msg.source===SRC){if(isTop){let sourceLayer=layerForWindow(event.source),sourceIsRoot=!!(rootFrame?.contentWindow&&rootFrame.contentWindow===event.source);if(!sourceLayer&&!sourceIsRoot)return;if(msg.type==="open"&&typeof msg.url=="string"){let rawOverlay=msg.overlay&&typeof msg.overlay=="object"?msg.overlay:void 0,overlay=rawOverlay?{topRatio:numberParam(rawOverlay.topRatio,.2,0,1),widthRatio:numberParam(rawOverlay.widthRatio,1,0,1),radius:numberParam(rawOverlay.radius,0,0,50),maskAlpha:numberParam(rawOverlay.maskAlpha,.3,0,1),tapClose:boolParam(rawOverlay.tapClose,!0)}:resolveOverlayPresentation(msg.url,void 0,!1),callbackId=typeof msg.callbackId=="number"?msg.callbackId:0,popId=typeof msg.popId=="string"&&msg.popId?msg.popId:null;msg.popBeforeOpen===!0&&sourceLayer?replaceLayer(sourceLayer,msg.url,callbackId,overlay,popId):openLayer(msg.url,callbackId,overlay,event.source??window,!0,popId)}else if(msg.type==="close")requestCloseOnTop(msg.data);else if(msg.type==="closeAll"){let gotoEvent=msg.gotoEvent===!0;if(gotoEvent&&sourceIsRoot&&layers.length===0&&msg.data!==void 0)try{event.source.postMessage({source:SRC,type:"resume",data:msg.data,storageId:null,callbackId:0,final:!0,gotoEvent:!0},"*")}catch{}else closeAllLayers(msg.data,gotoEvent)}else if(msg.type==="appMessageToOpener"&&sourceLayer){let target=sourceLayer.openerWin;if(target===window)links.getBridgeProtocol().handleAppMessage(msg.message);else try{target.postMessage({source:SRC,type:"appMessage",message:msg.message},"*")}catch{}}else if(msg.type==="containerDataRequest"&&typeof msg.requestId=="number"&&typeof msg.action=="string"&&msg.params&&typeof msg.params=="object"&&!Array.isArray(msg.params)&&event.source){let result=executeContainerData(msg.action,msg.params);try{event.source.postMessage({source:SRC,type:"containerDataResponse",requestId:msg.requestId,success:result.success,value:result.value},"*")}catch{}}else if(msg.type==="nativeBackResult"&&typeof msg.requestId=="number"&&typeof msg.handled=="boolean"&&event.source)finishNativeBack(msg.requestId,event.source,msg.handled);else if(msg.type==="urlChanged"&&typeof msg.url=="string"){let topLayer=layers[layers.length-1];if(sourceIsRoot&&!topLayer){rootBusinessUrl=msg.url;let mapped=mapUrlForSync(msg.url);if(mapped)try{history.replaceState({__mearl_layer__:0},"",mapped)}catch{}}else if(topLayer&&!topLayer.closing&&sourceLayer===topLayer){topLayer.url=msg.url,topLayer.titleBarStateExplicit&&topLayer.titleBarState&&cacheExplicitTitleBarState(topLayer,topLayer.titleBarState);let mapped=mapUrlForSync(msg.url);if(mapped)try{history.replaceState({__mearl_layer__:layers.length},"",mapped)}catch{}}}else if(msg.type==="title"&&typeof msg.title=="string"){let topLayer=layers[layers.length-1];if(sourceIsRoot&&!topLayer)try{document.title=msg.title,syncSimulatedTitleBar()}catch{}else if(topLayer&&sourceLayer===topLayer){document.title=msg.title;let state=resolvedTitleBarState(topLayer);topLayer.titleBarState={...state,title:msg.title},syncLayerViewport(topLayer,topLayer.titleBarState)}}else if(msg.type==="titleBarState"){let state=parseReportedTitleBarState(msg.state);if(state&&sourceIsRoot)links.getSystemBars().setPresentedRootTitleBarState(state);else if(state&&sourceLayer){let explicit=msg.explicit===!0;sourceLayer.titleBarStateReady=!0,explicit?(sourceLayer.titleBarState=state,sourceLayer.titleBarStateExplicit=!0,cacheExplicitTitleBarState(sourceLayer,state)):sourceLayer.titleBarStateExplicit||(sourceLayer.titleBarState=state);let resolvedState=sourceLayer.titleBarState??state;syncLayerViewport(sourceLayer,resolvedState)}}}else if(msg.type==="simulatorVisibility"&&typeof msg.hidden=="boolean"){if(event.source!==window.top)return;links.getBridgeProtocol().handlePageVisibility(msg.hidden)}else if(msg.type==="appMessage"){if(event.source!==window.top)return;links.getBridgeProtocol().handleAppMessage(msg.message)}else if(msg.type==="nativeBack"&&typeof msg.requestId=="number"){if(event.source!==window.top)return;let handled=links.getBridgeProtocol().handleNativeBack();window.top?.postMessage({source:SRC,type:"nativeBackResult",requestId:msg.requestId,handled},"*")}else if(msg.type==="containerDataResponse"&&typeof msg.requestId=="number"){if(event.source!==window.top)return;let callback=containerDataCallbacks.get(msg.requestId);if(!callback)return;containerDataCallbacks.delete(msg.requestId),msg.success===!0?callback.success(msg.value):callback.failure(msg.value)}else if(msg.type==="runtimeResponses"&&msg.profile===config2.profile&&msg.responses&&typeof msg.responses=="object"&&!Array.isArray(msg.responses)){if(event.source!==window.top)return;links.getBridgeProtocol().applyRuntimeResponses(msg.responses)}else if(msg.type==="resume"){if(event.source!==window.top)return;links.getBridgeProtocol().handleResume({data:msg.data,storageId:msg.storageId??null,callbackId:typeof msg.callbackId=="number"?msg.callbackId:0,final:msg.final===!0,gotoEvent:msg.gotoEvent===!0,silent:msg.silent===!0})}else event.source!==window.top&&window.top?.postMessage(msg,"*");return}pageTransport.handleMessage(msg)}}),!isTop&&isContainerFrame){let reportUrl=()=>{try{window.top?.postMessage({source:SRC,type:"urlChanged",url:restoreLayerBusinessUrl(location.href)},"*")}catch{}};try{let origPushState=history.pushState.bind(history),origReplaceState=history.replaceState.bind(history);history.pushState=function(...args){origPushState(...args),reportUrl()},history.replaceState=function(...args){origReplaceState(...args),reportUrl()},window.addEventListener("popstate",reportUrl),window.addEventListener("hashchange",reportUrl)}catch{}}if(isContainerFrame){let requestProxyLocationOpen=url2=>{if(links.getBridgeProtocol().handleMaybeScheme(url2))return!0;try{let current=new URL(restoreLayerBusinessUrl(location.href)),target=new URL(url2,current);return!/^https?:$/.test(target.protocol)||target.origin===current.origin&&target.pathname===current.pathname&&target.search===current.search?!1:(requestOpen(target.href,0,!1),!0)}catch{return!1}};Object.defineProperty(window,"__PROXY_LOCATION__",{value:{get href(){return location.href},set href(url2){requestProxyLocationOpen(url2)||(location.href=mapLayerFrameUrl(url2))},replace(url2){links.getBridgeProtocol().handleMaybeScheme(url2)||location.replace(mapLayerFrameUrl(url2))},assign(url2){requestProxyLocationOpen(url2)||location.assign(mapLayerFrameUrl(url2))}},writable:!1,configurable:!0})}if(isContainerFrame){document.addEventListener("click",event=>{let el=event.target;for(;el&&el.tagName!=="A";)el=el.parentElement;if(!el)return;let href=el.getAttribute("href");if(href){if(links.getBridgeProtocol().handleMaybeScheme(href)){event.preventDefault(),event.stopPropagation();return}/^https?:/i.test(href)&&el.getAttribute("target")==="_blank"&&(event.preventDefault(),event.stopPropagation(),requestOpen(href,0,!1))}},!0);let origOpen=window.open;window.open=function(url2,target,features){let urlStr=typeof url2=="string"?url2:url2 instanceof URL?url2.href:"";return links.getBridgeProtocol().handleMaybeScheme(urlStr)?null:/^https?:/i.test(urlStr)?(requestOpen(urlStr,0,!1),null):origOpen?origOpen.call(window,url2,target,features):null};try{let proto=Location.prototype,origAssign=proto.assign,origReplace=proto.replace;origAssign&&(proto.assign=function(url2){if(links.getBridgeProtocol().handleMaybeScheme(url2))return;let upgraded=location.protocol==="https:"&&url2.startsWith("http:")?"https:"+url2.slice(5):url2;origAssign.call(this,upgraded)}),origReplace&&(proto.replace=function(url2){if(links.getBridgeProtocol().handleMaybeScheme(url2))return;let upgraded=location.protocol==="https:"&&url2.startsWith("http:")?"https:"+url2.slice(5):url2;origReplace.call(this,upgraded)})}catch{}}return log3("容器环境已就绪",isTop?"(top)":isRootFrame?"(root)":isLayerFrame?"(layer)":"(iframe,仅桥)"),{getRootFrame:()=>rootFrame,getLayers:()=>layers,getClosingLayerCount:()=>closingLayerCount,requestOpen,requestClose,requestNativeBack,requestContainerData,closeAllLayers}}var APP_PROFILE_RUNTIME_FACTORIES={environment:installAppProfileEnvironment,containerStack:installAppProfileContainerStack,bridgeProtocol:installAppProfileBridgeProtocol,pageTransport:installAppProfilePageTransport,systemBars:installAppProfileSystemBars};function buildAppProfileRuntimeCallSource(configExpression){return`(${installAppProfileRuntime.toString()})(${configExpression},{environment:${installAppProfileEnvironment.toString()},pageTransport:${installAppProfilePageTransport.toString()},containerStack:${installAppProfileContainerStack.toString()},systemBars:${installAppProfileSystemBars.toString()},bridgeProtocol:${installAppProfileBridgeProtocol.toString()}})`}function installAppProfileRuntime(config2,factories=APP_PROFILE_RUNTIME_FACTORIES){let environment=factories.environment(config2);if(!environment)return;let pageTransport=factories.pageTransport(config2,environment),containerStack=factories.containerStack(config2,environment,{pageTransport,getSystemBars:()=>systemBars,getBridgeProtocol:()=>bridgeProtocol}),systemBars=factories.systemBars(config2,environment,{getRootFrame:containerStack.getRootFrame,getLayers:containerStack.getLayers,getClosingLayerCount:containerStack.getClosingLayerCount,requestClose:containerStack.requestClose,requestNativeBack:containerStack.requestNativeBack}),bridgeProtocol=factories.bridgeProtocol(config2,environment,{pageTransport,systemBars,requestOpen:containerStack.requestOpen,requestClose:containerStack.requestClose,requestCloseAll:containerStack.closeAllLayers,requestContainerData:containerStack.requestContainerData})}import https from"node:https";import http3 from"node:http";var TYPE_INTO_ELEMENT_SRC=typeIntoElement.toString(),CLICK_ELEMENT_VIA_JS_SRC=clickElementViaJS.toString(),GET_CLICK_COORDS_FROM_NODE_SRC=getClickCoordsFromNode.toString();function nodeFetch(urlStr,options={}){return new Promise((resolve5,reject)=>{let url2=new URL(urlStr),isHttps=url2.protocol==="https:",lib=isHttps?https:http3,{method="GET",headers={},body,timeoutMs=3e4}=options,req=lib.request({host:url2.hostname,port:url2.port||(isHttps?443:80),path:url2.pathname+url2.search,method,headers},res=>{let responseHeaders={};for(let[key,value]of Object.entries(res.headers))typeof value=="string"?responseHeaders[key]=value:Array.isArray(value)&&(responseHeaders[key]=value.join(", "));let chunks=[];res.on("data",chunk=>chunks.push(Buffer.from(chunk))),res.on("end",()=>{let bodyBuffer=Buffer.concat(chunks);resolve5({status:res.statusCode??0,statusText:res.statusMessage??"",headers:responseHeaders,body:bodyBuffer.toString("utf-8"),bodyBuffer})})});req.on("error",reject),req.setTimeout(timeoutMs,()=>{req.destroy(),reject(new Error(`Request timeout: ${urlStr}`))}),body&&req.write(body),req.end()})}async function getCookiesForUrl(session,targetUrl){let result=await session.client.sendCommand("Network.getCookies",{urls:[targetUrl]}),map2=new Map;for(let cookie of result.cookies??[])map2.set(cookie.name,cookie.value);return map2}function decodeTracknick(raw){if(!raw)return"";try{return decodeURIComponent(raw).replace(/\\u([0-9a-fA-F]{4})/g,(_match,hex3)=>String.fromCharCode(parseInt(hex3,16)))}catch{return raw}}function buildMultipartFormBody(fields){let boundary=`----mearl-${Date.now()}-${Math.random().toString(36).slice(2)}`,body=[...Object.entries(fields).map(([name,value])=>`--${boundary}\r
|
|
1048
1048
|
Content-Disposition: form-data; name="${name}"\r
|
|
1049
1049
|
\r
|
|
1050
1050
|
${value}\r
|
|
@@ -1251,7 +1251,7 @@ ${candidates}`)}let hit=hits[0],dispatchTarget;if(effectiveClickMode==="dom"||po
|
|
|
1251
1251
|
remaining -= 1;
|
|
1252
1252
|
}
|
|
1253
1253
|
return element;
|
|
1254
|
-
}`,arguments:[{value:ancestorDepth}],returnByValue:!1});if(ancestorObjectId=ancestor.result?.objectId,!ancestorObjectId||ancestor.result?.subtype==="null")throw new Error("page_snapshot: cannot resolve an ancestor for rootRef");let ancestorBackendNodeId=(await sendCdpDeviceShellPageCommand(session,"DOM.describeNode",{objectId:ancestorObjectId})).node?.backendNodeId;if(ancestorBackendNodeId===void 0)throw new Error("page_snapshot: cannot resolve an ancestor for rootRef");return ancestorBackendNodeId}finally{ancestorObjectId&&await sendCdpDeviceShellPageCommand(session,"Runtime.releaseObject",{objectId:ancestorObjectId}).catch(()=>{}),await sendCdpDeviceShellPageCommand(session,"Runtime.releaseObject",{objectId}).catch(()=>{})}}async function getViewportBackendNodeIds(session){let[metrics,captured]=await Promise.all([sendCdpDeviceShellPageCommand(session,"Page.getLayoutMetrics",{}),sendCdpDeviceShellPageCommand(session,"DOMSnapshot.captureSnapshot",{computedStyles:[],includeDOMRects:!0,includePaintOrder:!1})]),viewport=resolveDOMSnapshotViewportBounds(metrics);if(!viewport)throw new Error("page_snapshot: viewport metrics are unavailable");let{left,top,width,height}=viewport,right=left+width,bottom=top+height,visible=new Set;for(let document2 of captured.documents??[]){let backendNodeIds=document2.nodes?.backendNodeId??[],nodeIndexes=document2.layout?.nodeIndex??[],bounds=document2.layout?.bounds??[];for(let index=0;index<nodeIndexes.length;index+=1){let box=bounds[index],backendNodeId=backendNodeIds[nodeIndexes[index]];if(!box||backendNodeId===void 0)continue;let[x,y,boxWidth,boxHeight]=box;boxWidth<=0||boxHeight<=0||x<right&&x+boxWidth>left&&y<bottom&&y+boxHeight>top&&visible.add(backendNodeId)}}return visible}async function cdpPageSnapshot(session,data){let mode=data?.mode??"full",rootSelector=data?.rootSelector,rootRef=data?.rootRef,ancestorDepth=data?.ancestorDepth??0,query=resolvePageSnapshotQuery(data?.query);if(!["full","interactive","viewport"].includes(mode))throw new Error("page_snapshot: mode must be one of full, interactive, viewport");if(rootSelector!==void 0&&(typeof rootSelector!="string"||!rootSelector.trim()))throw new Error("page_snapshot: rootSelector must be a non-empty CSS selector");if(rootRef!==void 0&&(typeof rootRef!="string"||!/^@e\d+$/.test(rootRef)))throw new Error('page_snapshot: rootRef must be a snapshot ref like "@e3"');if(rootSelector!==void 0&&rootRef!==void 0)throw new Error("page_snapshot: rootSelector and rootRef are mutually exclusive");if(!Number.isInteger(ancestorDepth)||ancestorDepth<0||ancestorDepth>20)throw new Error("page_snapshot: ancestorDepth must be an integer between 0 and 20");if(ancestorDepth>0&&rootRef===void 0)throw new Error("page_snapshot: ancestorDepth requires rootRef");let rootBackendNodeId;if(rootSelector)rootBackendNodeId=await resolveRootBackendNodeId(session,rootSelector);else if(rootRef){let entry=resolvePageRef(session,rootRef);if(!entry)throw new Error(`Ref ${rootRef} not found. Run page_snapshot first to get fresh refs.`);rootBackendNodeId=await resolveAncestorBackendNodeId(session,entry.backendNodeId,ancestorDepth)}let snapshotRefs=beginPageSnapshotRefs(session),[result,visibleBackendNodeIds]=await Promise.all([sendCdpDeviceShellPageCommand(session,rootBackendNodeId===void 0?"Accessibility.getFullAXTree":"Accessibility.queryAXTree",rootBackendNodeId===void 0?{depth:data?.depth}:{backendNodeId:rootBackendNodeId}),mode==="viewport"||mode==="interactive"?getViewportBackendNodeIds(session):Promise.resolve(void 0)]),nodes=result.nodes??[];await reconcileAXCheckedStates(nodes,backendNodeId=>readDOMCheckedState2(session,backendNodeId));let nodeMap=new Map;for(let node of nodes)nodeMap.set(node.nodeId,node);let rootNode=nodes[0];if(!rootNode)return snapshotRefs.commit(new Set),{snapshot:"(empty page)",refs:{},elementCount:0,outputNodeCount:1,mode,...rootSelector?{rootSelector}:{},...rootRef?{rootRef,ancestorDepth}:{},...query?{query,matches:[],matchCount:0}:{}};let rawTree=buildSnapshotTree(nodeMap,rootNode.nodeId,snapshotRefs),viewportFilteredTree=mode==="interactive"?filterSnapshotTree(rawTree,"viewport",visibleBackendNodeIds):rawTree,effectiveMode=mode;mode==="interactive"&&!hasInteractiveSnapshotNode(viewportFilteredTree)&&(effectiveMode="viewport");let modeFilteredTree=mode==="interactive"?effectiveMode==="interactive"?filterSnapshotTree(viewportFilteredTree,"interactive"):viewportFilteredTree:filterSnapshotTree(rawTree,effectiveMode,visibleBackendNodeIds),queryResult=query?filterSnapshotTreeByQuery(modeFilteredTree,query):{tree:modeFilteredTree,matches:[]},limitedMatches=query?limitPageSnapshotQueryMatches(queryResult.matches):{matches:[],truncated:!1},tree=queryResult.tree,lines=[];tree&&formatSnapshotNode(tree,0,lines);let formatted=formatSnapshotWithLimits(lines.length>0?lines:[query?"(no matches)":"(empty page)"],{maxChars:data?.maxChars,maxNodes:data?.maxNodes}),refs={},outputRefKeys=new Set(Array.from(formatted.snapshot.matchAll(/(?:^|\n)\s*(@e\d+)\s/g),match=>match[1]));for(let match of limitedMatches.matches)match.ref&&outputRefKeys.add(match.ref);snapshotRefs.commit(outputRefKeys);let registry2=getPageRefRegistry(session);for(let ref of outputRefKeys){let entry=registry2.resolve(ref);entry&&(refs[ref.slice(1)]={backendNodeId:entry.backendNodeId})}return{snapshot:formatted.snapshot,refs,elementCount:countSnapshotNodes(tree),outputNodeCount:formatted.outputNodeCount,mode,...rootSelector?{rootSelector}:{},...rootRef?{rootRef,ancestorDepth}:{},...query?{query,matches:limitedMatches.matches,matchCount:queryResult.matches.length,...limitedMatches.truncated?{matchesTruncated:!0}:{}}:{},...effectiveMode!==mode?{fallbackMode:"viewport"}:{},...formatted.truncated?{truncated:!0}:{}}}async function cdpPageFrames(session,_data){let result=await session.client.sendCommand("Page.getFrameTree",{});function flattenFrameTree(tree){if(!tree)return[];let{frame,childFrames=[]}=tree;return[{frameId:frame.id,parentFrameId:frame.parentId??null,url:frame.url,name:frame.name??""},...childFrames.flatMap(flattenFrameTree)]}let frames=flattenFrameTree(result.frameTree);return{frames,count:frames.length}}registerActions([{name:"page_snapshot",session:"page",handler:cdpPageSnapshot},{name:"page_frames",session:"page",handler:cdpPageFrames}]);var MEARL_SERVICE_COOKIE_DOMAINS=["tdbank.alibaba-inc.com","ats2.alibaba-inc.com","g.alibaba-inc.com","login.alibaba-inc.com","token-hub.alibaba-inc.com","alibaba-inc.com"],MEARL_SERVICE_COOKIE_HOSTS=new Set(MEARL_SERVICE_COOKIE_DOMAINS);function normalizeCookieDomain2(input2){let value=input2.trim();if(!value)throw new Error("Cookie domain must be a non-empty string");let hostname3;try{hostname3=new URL(value.includes("://")?value:`https://${value}`).hostname}catch{throw new Error(`Invalid cookie domain: ${input2}`)}if(hostname3=hostname3.toLowerCase().replace(/^\.+/,"").replace(/\.+$/,""),!hostname3)throw new Error(`Invalid cookie domain: ${input2}`);return hostname3}function normalizeCookieDomains(inputs){if(!Array.isArray(inputs))throw new Error("copyCookieDomains must be an array of domains");return[...new Set(inputs.map(value=>normalizeCookieDomain2(String(value))))]}function isMearlServiceCookie(cookie){let domain2=normalizeCookieDomain2(cookie.domain);return MEARL_SERVICE_COOKIE_HOSTS.has(domain2)?!0:domain2.endsWith(".tdbank.alibaba-inc.com")||domain2.endsWith(".ats2.alibaba-inc.com")}function normalizeCookieCopyScope(input2){let presets=input2.presets??[];if(!Array.isArray(presets)||presets.some(preset=>preset!=="mearl-services"))throw new Error("copyCookieDomains.presets contains an unsupported preset");return{includeMearlServices:presets.includes("mearl-services"),domains:normalizeCookieDomains(input2.domains??[])}}function resolveCookieCopyPlan(input2){let includeMearlServices=!1,explicitDomains=[];if(input2==="mearl-services")includeMearlServices=!0;else if(Array.isArray(input2))explicitDomains=normalizeCookieDomains(input2);else if(input2!=null&&typeof input2=="object"){let scope=normalizeCookieCopyScope(input2);includeMearlServices=scope.includeMearlServices,explicitDomains=scope.domains}else if(input2!==void 0)throw new Error('copyCookieDomains must be an array of domains, "mearl-services", or a scope object');return includeMearlServices?{domains:[...new Set([...MEARL_SERVICE_COOKIE_DOMAINS,...explicitDomains])],select:cookies=>cookies.filter(cookie=>isMearlServiceCookie(cookie)||explicitDomains.some(domain2=>cookieMatchesDomain(cookie.domain,domain2)))}:{domains:explicitDomains,select:cookies=>cookies}}function cookieMatchesDomain(cookieDomain,requestedDomain){let cookieHost=cookieDomain.toLowerCase().replace(/^\.+/,"");return cookieHost===requestedDomain||cookieHost.endsWith(`.${requestedDomain}`)||requestedDomain.endsWith(`.${cookieHost}`)}function toTransferableCookie(cookie){let result={name:String(cookie.name),value:String(cookie.value),domain:String(cookie.domain),path:String(cookie.path||"/"),secure:!!cookie.secure,httpOnly:!!cookie.httpOnly};return["Strict","Lax","None"].includes(cookie.sameSite)&&(result.sameSite=cookie.sameSite),typeof cookie.expires=="number"&&cookie.expires>0&&(result.expires=cookie.expires),["Low","Medium","High"].includes(cookie.priority)&&(result.priority=cookie.priority),typeof cookie.sameParty=="boolean"&&(result.sameParty=cookie.sameParty),["Unset","NonSecure","Secure"].includes(cookie.sourceScheme)&&(result.sourceScheme=cookie.sourceScheme),typeof cookie.sourcePort=="number"&&(result.sourcePort=cookie.sourcePort),cookie.partitionKey?.topLevelSite&&(result.partitionKey={topLevelSite:String(cookie.partitionKey.topLevelSite),...typeof cookie.partitionKey.hasCrossSiteAncestor=="boolean"?{hasCrossSiteAncestor:cookie.partitionKey.hasCrossSiteAncestor}:{}}),result}async function cdpExportCookies(session,domains){let requestedDomains=normalizeCookieDomains(domains);return((await(await session.getBrowserClient()).sendCommand("Storage.getCookies",{})).cookies??[]).filter(cookie=>requestedDomains.some(domain2=>cookieMatchesDomain(String(cookie.domain),domain2))).map(toTransferableCookie)}async function cdpImportCookies(session,cookies){if(cookies.length===0)return 0;let browser=await session.getBrowserClient();return cdpImportCookiesWithClient(browser,cookies)}async function cdpImportCookiesWithClient(browser,cookies){return cookies.length===0?0:(await browser.sendCommand("Storage.setCookies",{cookies}),cookies.length)}import{closeSync as closeSync4,existsSync as existsSync5,mkdtempSync,mkdirSync as mkdirSync3,openSync as openSync4,readFileSync as readFileSync4,renameSync as renameSync4,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{spawn as spawn4,spawnSync as spawnSync2}from"node:child_process";import{randomUUID as randomUUID5}from"node:crypto";import{tmpdir}from"node:os";import{join as join5}from"node:path";function stoppedPersistentBrowserRecord(record2,deleteProfile){if(deleteProfile||record2.persistent!==!0)return null;let stopped={...record2,pid:0};return"hostPid"in stopped?{...stopped,hostPid:0}:stopped}var MANAGED_BROWSERS_SUBDIR="managed-browsers",MANAGED_BROWSER_LOCKS_SUBDIR="managed-browser-locks",MANAGED_PROFILES_SUBDIR="managed-profiles",LAUNCH_TIMEOUT_MS=15e3;function validateName(value){let name=typeof value=="string"?value.trim():"";if(!name)throw new Error("name is required");if(name.length>64)throw new Error("name must be at most 64 characters");if(/[/\\\0\r\n]/.test(name))throw new Error("name contains unsupported characters");return name}function managedBrowserId(name){return`managed:${name.toLocaleLowerCase("en-US")}`}function hasTdbankSelector(data){return data.accountId!==void 0||data.havanaId!==void 0||typeof data.query=="string"&&data.query.trim().length>0}function validateTdbankSelector(data){if(data.havanaId!==void 0&&data.site===void 0)throw new Error("site is required when havanaId is provided");if([data.accountId!==void 0,data.havanaId!==void 0,typeof data.query=="string"&&data.query.trim().length>0].filter(Boolean).length>1)throw new Error("Use only one of accountId, havanaId + site, or query")}function chromeExecutableCandidates(platform=process.platform){let envPath=process.env.MEARL_CHROME_PATH,candidates=envPath?[envPath]:[];if(platform==="darwin")return candidates.concat(["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary","/Applications/Chromium.app/Contents/MacOS/Chromium"]);if(platform==="win32"){let local=process.env.LOCALAPPDATA??"",programFiles=process.env.PROGRAMFILES??"",programFilesX86=process.env["PROGRAMFILES(X86)"]??"";return candidates.concat([join5(local,"Google","Chrome","Application","chrome.exe"),join5(programFiles,"Google","Chrome","Application","chrome.exe"),join5(programFilesX86,"Google","Chrome","Application","chrome.exe")])}return candidates.concat(["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium","/usr/bin/chromium-browser"])}function resolveChromeExecutable(explicitPath){if(explicitPath){if(!existsSync5(explicitPath))throw new Error(`Chrome executable not found: ${explicitPath}`);return explicitPath}let found=chromeExecutableCandidates().find(candidate=>candidate&&existsSync5(candidate));if(!found)throw new Error("Chrome executable not found. Set executablePath or MEARL_CHROME_PATH.");return found}function desktopChromeUserAgent(version2,platform=process.platform){if(!/^\d+(?:\.\d+){1,3}$/.test(version2))throw new Error(`Invalid Chrome version: ${version2}`);return`Mozilla/5.0 (${platform==="darwin"?"Macintosh; Intel Mac OS X 10_15_7":platform==="win32"?"Windows NT 10.0; Win64; x64":"X11; Linux x86_64"}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${version2} Safari/537.36`}function resolveChromeVersion(executablePath){let result=spawnSync2(executablePath,["--version"],{encoding:"utf8",windowsHide:!0}),version2=`${result.stdout??""} ${result.stderr??""}`.match(/\b(\d+(?:\.\d+){1,3})\b/)?.[1];if(!version2)throw new Error(`Could not determine Chrome version from: ${executablePath}`);return version2}function resolveUserAgentMode(value){if(value===void 0||value==="default")return"default";if(value==="desktop")return"desktop";throw new Error('userAgentMode must be "default" or "desktop"')}function buildManagedChromeArgs(options){return[`--user-data-dir=${options.userDataDir}`,"--remote-debugging-port=0","--no-first-run","--no-default-browser-check","--disable-background-networking",...options.headless?["--headless=new"]:[],...options.userAgent?[`--user-agent=${options.userAgent}`]:[],"about:blank"]}function browserSummary(record2,running){return{browserId:record2.browserId,name:record2.name,provider:"local",headless:record2.headless,persistent:record2.persistent,cdpPort:record2.cdpPort,createdAt:record2.createdAt,account:record2.account,copiedCookies:record2.copiedCookies,running}}function isManagedProcess(pid,commandMarker,platform=process.platform){if(!isAlive(pid))return!1;try{if(platform==="win32"){let escapedMarker=commandMarker.replace(/'/g,"''");return spawnSync2("powershell.exe",["-NoProfile","-NonInteractive","-Command",`$p = Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}'; if ($p.CommandLine -and $p.CommandLine.Contains('${escapedMarker}')) { exit 0 } else { exit 1 }`],{windowsHide:!0,stdio:"ignore"}).status===0}let result=spawnSync2("ps",["-p",String(pid),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return result.status===0&&result.stdout.includes(commandMarker)}catch{return!1}}function listRecords(){let records=[];for(let file2 of listRecordFiles(keyedDir(MANAGED_BROWSERS_SUBDIR))){let record2=readRecord(file2);if(!record2){removeRecord(file2);continue}let running=isManagedProcess(record2.pid,record2.userDataDir);if(!running&&(signalProcess(record2.hostPid,"SIGTERM",`--browser-id ${record2.browserId}`),removeRecord(keyedConfigFile("browsers",record2.browserId)),!record2.persistent)){removeRecord(file2),rmSync3(record2.userDataDir,{recursive:!0,force:!0});continue}records.push({record:record2,running})}return records}function listManagedBrowsers(){return listRecords().map(({record:record2,running})=>browserSummary(record2,running))}function findManagedRecord(selector){let normalized=selector.trim().toLowerCase();return listRecords().find(({record:record2})=>record2.browserId.toLowerCase()===normalized||record2.name.toLowerCase()===normalized)?.record??null}function hasManagedBrowser(selector){return findManagedRecord(selector)!==null}async function waitForActivePort(userDataDir){let deadline=Date.now()+LAUNCH_TIMEOUT_MS;for(;Date.now()<deadline;){let info=readDevToolsActivePort(userDataDir);if(info)return info.port;await new Promise(resolve5=>setTimeout(resolve5,100))}throw new Error(`Chrome did not expose a CDP port within ${LAUNCH_TIMEOUT_MS}ms`)}async function waitForBrowserRegistration(browserId,expectedPid){let file2=keyedConfigFile("browsers",browserId),deadline=Date.now()+LAUNCH_TIMEOUT_MS;for(;Date.now()<deadline;){if(readRecord(file2)?.pid===expectedPid&&isAlive(expectedPid))return;await new Promise(resolve5=>setTimeout(resolve5,100))}throw new Error(`Managed browser ${browserId} did not register within ${LAUNCH_TIMEOUT_MS}ms`)}function signalProcess(pid,signal,commandMarker){if(isManagedProcess(pid,commandMarker)){if(process.platform==="win32"){spawnSync2("taskkill",["/PID",String(pid),"/T","/F"],{windowsHide:!0,stdio:"ignore"});return}try{process.kill(pid,signal)}catch{}}}async function stopProcess(pid,commandMarker){signalProcess(pid,"SIGTERM",commandMarker);let deadline=Date.now()+3e3;for(;Date.now()<deadline&&isManagedProcess(pid,commandMarker);)await new Promise(resolve5=>setTimeout(resolve5,50));isManagedProcess(pid,commandMarker)&&signalProcess(pid,"SIGKILL",commandMarker)}function profileDirectory(browserId,persistent){if(!persistent)return mkdtempSync(join5(tmpdir(),"mearl-browser-"));let dir=join5(DAEMON_HOME,MANAGED_PROFILES_SUBDIR,hashKey(browserId));return mkdirSync3(dir,{recursive:!0}),dir}async function removeStoppedInstance(browserId){let file2=keyedConfigFile(MANAGED_BROWSERS_SUBDIR,browserId),record2=readRecord(file2);!record2||isManagedProcess(record2.pid,record2.userDataDir)||(await stopProcess(record2.hostPid,`--browser-id ${record2.browserId}`),removeRecord(file2),removeRecord(keyedConfigFile("browsers",record2.browserId)),record2.persistent||rmSync3(record2.userDataDir,{recursive:!0,force:!0}))}function acquireLaunchLock(browserId){let lockDir=keyedDir(MANAGED_BROWSER_LOCKS_SUBDIR),lockFile=keyedConfigFile(MANAGED_BROWSER_LOCKS_SUBDIR,browserId);mkdirSync3(lockDir,{recursive:!0});let token=`${process.pid}:${randomUUID5()}`,tryAcquire=()=>{try{return writeFileSync3(lockFile,token,{flag:"wx"}),!0}catch(error48){if(error48.code!=="EEXIST")throw error48;return!1}};if(!tryAcquire()){let observedToken="";try{observedToken=readFileSync4(lockFile,"utf-8")}catch{}let ownerPid=Number(observedToken.split(":",1)[0]);if(Number.isInteger(ownerPid)&&!isAlive(ownerPid)){let staleFile=`${lockFile}.${process.pid}.${randomUUID5()}.stale`;try{if(readFileSync4(lockFile,"utf-8")!==observedToken)throw new Error("Launch lock owner changed");if(renameSync4(lockFile,staleFile),readFileSync4(staleFile,"utf-8")===observedToken)rmSync3(staleFile,{force:!0});else try{renameSync4(staleFile,lockFile)}catch{}}catch{}}if(!tryAcquire())throw new Error(`Managed browser launch already in progress: ${browserId}`)}return()=>{try{readFileSync4(lockFile,"utf-8")===token&&rmSync3(lockFile,{force:!0})}catch{}}}async function launchManagedBrowser(input2,deps){if(input2.sessionId!==void 0)throw new Error("sessionId is only supported by the AgentBay browser provider");if(input2.reuse!==void 0&&input2.reuse!=="never"&&input2.reuse!=="prefer"&&input2.reuse!=="require")throw new Error('reuse must be "never", "prefer", or "require"');if(input2.reuse==="prefer"||input2.reuse==="require")throw new Error("reuse is currently supported only by the AgentBay browser provider");if(input2.imageId!==void 0)throw new Error("imageId is only supported by the AgentBay browser provider");let name=validateName(input2.name),browserId=managedBrowserId(name);validateTdbankSelector(input2);let cookieCopy=resolveCookieCopyPlan(input2.copyCookieDomains),copyCookieDomains=cookieCopy.domains,headless=input2.headless!==!1,persistent=input2.persistent===!0,executablePath=resolveChromeExecutable(input2.executablePath),userAgent=resolveUserAgentMode(input2.userAgentMode)==="desktop"?desktopChromeUserAgent(resolveChromeVersion(executablePath)):void 0,userDataDir=profileDirectory(browserId,persistent),logDir=keyedDir(MANAGED_BROWSERS_SUBDIR);mkdirSync3(logDir,{recursive:!0});let logPath=join5(logDir,`${hashKey(browserId)}.log`),logFd=openSync4(logPath,"a"),chromePid=0,hostPid=0,session=null,recordWritten=!1,releaseLock=null;try{if(releaseLock=acquireLaunchLock(browserId),await removeStoppedInstance(browserId),findManagedRecord(browserId))throw new Error(`Managed browser already running: ${browserId}`);let[ticket,exportedCookies]=await Promise.all([hasTdbankSelector(input2)?deps.prepareTdbankSso(input2):Promise.resolve(void 0),copyCookieDomains.length>0?deps.exportCookies(copyCookieDomains):Promise.resolve([])]),cookies=cookieCopy.select(exportedCookies),chromeArgs=buildManagedChromeArgs({userDataDir,headless,userAgent});rmSync3(join5(userDataDir,"DevToolsActivePort"),{force:!0});let chrome=spawn4(executablePath,chromeArgs,{detached:!0,stdio:["ignore","ignore",logFd],windowsHide:headless});if(await new Promise((resolve5,reject)=>{chrome.once("error",reject),chrome.once("spawn",resolve5)}),chromePid=chrome.pid??0,!chromePid)throw new Error("Chrome launched without a process id");chrome.unref();let cdpPort=await waitForActivePort(userDataDir);session=new CdpSession({port:cdpPort,userDataDir});let copiedCookieCount=await cdpImportCookies(session,cookies),account;if(ticket){let login=await cdpConsumeTdbankSso(session,ticket.ssoUrl,ticket.account.loginId);account={accountId:ticket.account.accountId,loginId:ticket.account.loginId,nickname:login.nickname}}input2.url&&await(await session.getBrowserClient()).sendCommand("Target.createTarget",{url:input2.url,background:headless}),session.close(),session=null;let host=spawn4(process.execPath,[deps.nativeHostScript,"--daemon","--cdp-port",String(cdpPort),"--cdp-user-data-dir",userDataDir,"--browser-id",browserId,"--browser-name",name,...headless?["--browser-headless"]:[]],{detached:!0,stdio:"ignore",windowsHide:!0});if(await new Promise((resolve5,reject)=>{host.once("error",reject),host.once("spawn",resolve5)}),hostPid=host.pid??0,!hostPid)throw new Error("Native host launched without a process id");host.unref();let record2={pid:chromePid,hostPid,browserId,name,headless,persistent,userDataDir,executablePath,cdpPort,createdAt:new Date().toISOString(),account,...copyCookieDomains.length>0?{copiedCookies:{domains:copyCookieDomains,count:copiedCookieCount}}:{}};return writeRecord(keyedConfigFile(MANAGED_BROWSERS_SUBDIR,browserId),record2),recordWritten=!0,await waitForBrowserRegistration(browserId,hostPid),deps.log(`managed browser launched: ${browserId}, chrome=${chromePid}, host=${hostPid}`),{...browserSummary(record2,!0),created:!0,reused:!1}}catch(error48){throw session?.close(),hostPid&&await stopProcess(hostPid,`--browser-id ${browserId}`),chromePid&&await stopProcess(chromePid,userDataDir),recordWritten&&removeRecord(keyedConfigFile(MANAGED_BROWSERS_SUBDIR,browserId)),persistent||rmSync3(userDataDir,{recursive:!0,force:!0}),error48}finally{releaseLock?.(),closeSync4(logFd)}}async function closeManagedBrowser(selector,options={}){let record2=findManagedRecord(selector);if(!record2)throw new Error(`Managed browser not found: ${selector}`);let recordFile=keyedConfigFile(MANAGED_BROWSERS_SUBDIR,record2.browserId);await stopProcess(record2.pid,record2.userDataDir);let closingOwnHost=record2.hostPid===process.pid;closingOwnHost||await stopProcess(record2.hostPid,`--browser-id ${record2.browserId}`),removeRecord(keyedConfigFile("browsers",record2.browserId));let deleteProfile=options.deleteProfile===!0||!record2.persistent,stoppedRecord=stoppedPersistentBrowserRecord(record2,deleteProfile);return stoppedRecord?writeRecord(recordFile,stoppedRecord):(removeRecord(recordFile),rmSync3(record2.userDataDir,{recursive:!0,force:!0})),closingOwnHost&&setTimeout(()=>process.kill(process.pid,"SIGTERM"),250).unref(),{browserId:record2.browserId,closed:!0,profileDeleted:deleteProfile}}import{existsSync as existsSync11,readFileSync as readFileSync8}from"node:fs";import{spawn as spawn6}from"node:child_process";import{homedir as homedir2}from"node:os";import{dirname as dirname6,join as join8,parse,resolve as resolve3}from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function positiveIntegerMinutes(value,name,fallback){if(value===void 0||!value.trim())return fallback;let minutes=Number(value);if(!Number.isInteger(minutes)||minutes<=0)throw new Error(`${name} must be a positive integer in minutes`);return minutes}function resolveAgentBayLifecycleConfig(env=process.env){let idleReleaseTimeout=positiveIntegerMinutes(env.MEARL_AGENTBAY_IDLE_RELEASE_MINUTES,"MEARL_AGENTBAY_IDLE_RELEASE_MINUTES",30),maxRuntime=positiveIntegerMinutes(env.MEARL_AGENTBAY_MAX_RUNTIME_MINUTES,"MEARL_AGENTBAY_MAX_RUNTIME_MINUTES",120);if(idleReleaseTimeout<3)throw new Error("MEARL_AGENTBAY_IDLE_RELEASE_MINUTES must be at least 3");if(maxRuntime<idleReleaseTimeout)throw new Error("MEARL_AGENTBAY_MAX_RUNTIME_MINUTES must be greater than or equal to MEARL_AGENTBAY_IDLE_RELEASE_MINUTES");return{idleReleaseTimeout,maxRuntime}}var AgentBaySessionWatchdog=class{idleTimeoutMs;checkIntervalMs;now;keepAlive;close;log;activeRequests=0;lastActivityAt;timer=null;checking=!1;closing=!1;stopped=!1;constructor(options){if(!Number.isFinite(options.idleTimeoutMs)||options.idleTimeoutMs<=0)throw new Error("AgentBay idle timeout must be positive");if(this.idleTimeoutMs=options.idleTimeoutMs,this.checkIntervalMs=options.checkIntervalMs??6e4,!Number.isFinite(this.checkIntervalMs)||this.checkIntervalMs<=0)throw new Error("AgentBay lifecycle check interval must be positive");this.now=options.now??Date.now,this.keepAlive=options.keepAlive,this.close=options.close,this.log=options.log,this.lastActivityAt=this.now()}start(){this.timer||this.stopped||(this.timer=setInterval(()=>void this.checkNow(),this.checkIntervalMs),this.timer.unref())}stop(){this.stopped=!0,this.timer&&(clearInterval(this.timer),this.timer=null)}beginActivity(){return this.stopped||this.closing?!1:(this.activeRequests+=1,this.lastActivityAt=this.now(),!0)}endActivity(){this.activeRequests>0&&(this.activeRequests-=1),this.lastActivityAt=this.now()}async checkNow(){if(!(this.stopped||this.checking||this.closing)){this.checking=!0;try{let idleForMs=this.now()-this.lastActivityAt;if(this.activeRequests>0||idleForMs<this.idleTimeoutMs){try{await this.keepAlive()}catch(error48){this.log("AgentBay keepalive failed:",error48 instanceof Error?error48.message:String(error48))}return}this.closing=!0,this.log(`AgentBay browser reached the idle timeout after ${idleForMs}ms; closing`);try{await this.close()}catch(error48){this.closing=!1,this.log("AgentBay idle close failed:",error48 instanceof Error?error48.message:String(error48))}}finally{this.checking=!1}}}};var AGENTBAY_BROWSERS_SUBDIR="agentbay-browsers",DEFAULT_AGENTBAY_IMAGE_ID="imgc-0aae4rgl8kvagdv1j",sdkPromise=null;async function loadSdk(){return sdkPromise??=Promise.resolve().then(()=>(init_agentbay_sdk(),agentbay_sdk_exports)),sdkPromise}async function createClient(apiKey){let{AgentBay:AgentBay2}=await loadSdk();return new AgentBay2({apiKey})}function agentBayBrowserId(name){return`managed:agentbay:${name.toLocaleLowerCase("en-US")}`}function agentBaySessionBrowserId(sessionId){return`managed:agentbay:session:${sessionId}`}function envValue(text,key){for(let line of text.split(/\r?\n/)){let match=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);if(!match||match[1]!==key)continue;let value=(match[2]??"").trim();return value.length>=2&&(value.startsWith('"')&&value.endsWith('"')||value.startsWith("'")&&value.endsWith("'"))?value=value.slice(1,-1):value=value.replace(/\s+#.*$/,"").trim(),value||void 0}}function envFilesUpward(start){let files=[],current=resolve3(start);for(;;){files.push(join8(current,".env"));let parent=dirname6(current);if(parent===current||current===parse(current).root)break;current=parent}return files}function resolveAgentBayApiKey(){let inherited=process.env.AGENTBAY_KEY?.trim()||process.env.AGENTBAY_API_KEY?.trim();if(inherited)return inherited;let moduleDir=dirname6(fileURLToPath2(import.meta.url)),candidates=[...process.env.MEARL_ENV_FILE?[resolve3(process.env.MEARL_ENV_FILE)]:[],...envFilesUpward(process.cwd()),...envFilesUpward(moduleDir),join8(homedir2(),".mearl",".env")];for(let file2 of new Set(candidates))if(existsSync11(file2))try{let text=readFileSync8(file2,"utf8"),value=envValue(text,"AGENTBAY_KEY")??envValue(text,"AGENTBAY_API_KEY");if(value)return value}catch{}throw new Error("AgentBay API key not found. Set AGENTBAY_KEY in the environment, project .env, or ~/.mearl/.env.")}function validateAgentBayInput(input2){if(input2.headless===!0)throw new Error("headless=true is not supported by the AgentBay browser provider");if(input2.executablePath)throw new Error("executablePath is only supported by the local browser provider");if(input2.accountId!==void 0||input2.havanaId!==void 0||input2.site!==void 0||typeof input2.query=="string"&&input2.query.trim())throw new Error("TDBank login parameters are only supported by the local browser provider")}function resolveAgentBaySessionId(value){let sessionId=typeof value=="string"?value.trim():"";if(!sessionId||sessionId.length>256||!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(sessionId))throw new Error("sessionId must be a valid AgentBay session ID");return sessionId}function validateAgentBayAttachmentInput(input2){let unsupported=[["reuse",input2.reuse],["imageId",input2.imageId],["headless",input2.headless],["userAgentMode",input2.userAgentMode],["persistent",input2.persistent],["executablePath",input2.executablePath],["accountId",input2.accountId],["havanaId",input2.havanaId],["site",input2.site],["query",input2.query],["tabId",input2.tabId]].find(([,value])=>value!==void 0);if(unsupported)throw new Error(`${unsupported[0]} cannot be used when attaching by AgentBay sessionId`)}function attachmentName(sessionId,value){if(value!==void 0)return validateName(value);let suffix=sessionId.slice(-12);return validateName(`agentbay-${suffix}`)}function resolveReuseMode(value){if(value===void 0)return"never";if(value==="never"||value==="prefer"||value==="require")return value;throw new Error('reuse must be "never", "prefer", or "require"')}function validateReusableAgentBayConfiguration(input2,record2){if(input2.imageId!==void 0&&resolveAgentBayImageId(input2.imageId)!==record2.imageId)throw new Error(`Cannot change imageId while reusing AgentBay browser: ${record2.browserId}`);if(input2.persistent!==void 0&&input2.persistent!==(record2.persistent===!0))throw new Error(`Cannot change persistent while reusing AgentBay browser: ${record2.browserId}`);if(input2.userAgentMode!==void 0&&record2.userAgentMode!==void 0&&input2.userAgentMode!==record2.userAgentMode)throw new Error(`Cannot change userAgentMode while reusing AgentBay browser: ${record2.browserId}`)}function resolveAgentBayImageId(value){if(value===void 0)return DEFAULT_AGENTBAY_IMAGE_ID;let imageId=typeof value=="string"?value.trim():"";if(!imageId||imageId.length>128||!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(imageId))throw new Error("imageId must be a valid AgentBay image alias or image ID");return imageId}function agentBayContextName(browserId){return`mearl-browser-${hashKey(browserId)}`}function normalizeDesktopUserAgent(value){let userAgent=typeof value=="string"?value.trim():"";if(!userAgent)throw new Error("Could not determine the control browser user agent");return userAgent.replace(/\bHeadlessChrome\//g,"Chrome/")}function normalizeAgentBayAccessUrl(value){let candidate=typeof value=="string"?value.trim():"";if(candidate)try{let url2=new URL(candidate);return url2.protocol==="https:"||url2.protocol==="http:"?url2.toString():void 0}catch{return}}function browserSummary2(record2,running){let sessionMode=record2.sessionMode==="attached"?"attached":"owned";return{browserId:record2.browserId,name:record2.name,provider:"agentbay",headless:!1,persistent:record2.persistent===!0,agentbaySessionId:record2.sessionId,agentbaySessionMode:sessionMode,...record2.imageId?{agentbayImageId:record2.imageId}:{},...record2.contextId?{agentbayContextId:record2.contextId}:{},...record2.contextName?{agentbayContextName:record2.contextName}:{},createdAt:record2.createdAt,...record2.copiedCookies?{copiedCookies:record2.copiedCookies}:{},running}}function listRecords2(){let records=[];for(let file2 of listRecordFiles(keyedDir(AGENTBAY_BROWSERS_SUBDIR))){let stored=readRecord(file2);if(!stored){removeRecord(file2);continue}let{accessUrl:legacyAccessUrl,...record2}=stored;legacyAccessUrl!==void 0&&writeRecord(file2,record2);let running=isManagedProcess(record2.pid,`--browser-id ${record2.browserId}`);running||removeRecord(keyedConfigFile("browsers",record2.browserId)),records.push({record:record2,running})}return records}function findRecordWithStatus(selector){let normalized=selector.trim().toLowerCase(),records=listRecords2();return records.find(({record:record2})=>record2.browserId.toLowerCase()===normalized||record2.sessionId.toLowerCase()===normalized)??records.find(({record:record2})=>record2.name.toLowerCase()===normalized)??null}function findRecord(selector){return findRecordWithStatus(selector)?.record??null}function hasAgentBayBrowser(selector){return findRecord(selector)!==null}function listAgentBayBrowsers(){return listRecords2().map(({record:record2,running})=>browserSummary2(record2,running))}async function requireSession(sessionId,apiKey){let agentBay=await createClient(apiKey);return requireSessionFromClient(agentBay,sessionId)}async function requireSessionFromClient(agentBay,sessionId){let result=await agentBay.get(sessionId);if(!result.success||!result.session)throw new Error(result.errorMessage||`AgentBay session not found: ${sessionId}`);return result.session}async function getAgentBaySession(sessionId,dependencies={}){let apiKey=(dependencies.resolveApiKey??resolveAgentBayApiKey)(),agentBay=dependencies.createAgentBayClient?await dependencies.createAgentBayClient(apiKey):await createClient(apiKey);return requireSessionFromClient(agentBay,sessionId)}async function getAgentBayAccessUrl(sessionId,dependencies={}){let apiKey=(dependencies.resolveApiKey??resolveAgentBayApiKey)(),agentBay=dependencies.createAgentBayClient?await dependencies.createAgentBayClient(apiKey):await createClient(apiKey),session=await requireSessionFromClient(agentBay,sessionId);if(!session.info)throw new Error("The installed AgentBay SDK does not support live session information");let result=await session.info();if(result.success===!1)throw new Error(result.errorMessage||`AgentBay session info failed: ${sessionId}`);let data=result.data&&typeof result.data=="object"?result.data:null,accessUrl=normalizeAgentBayAccessUrl(data&&"resourceUrl"in data?data.resourceUrl:void 0);if(!accessUrl)throw new Error(`AgentBay session did not return a browser access URL: ${sessionId}`);return accessUrl}async function getManagedAgentBayAccessUrl(selector,dependencies={}){let matched=dependencies.findBrowserRecord?dependencies.findBrowserRecord(selector):findRecordWithStatus(selector);if(!matched)throw new Error(`AgentBay browser not found: ${selector}`);if(!matched.running)throw new Error(`AgentBay browser is not running: ${selector}`);return getAgentBayAccessUrl(matched.record.sessionId,dependencies)}async function resolvePersistentContext(agentBay,browserId){if(!agentBay.context)throw new Error("The installed AgentBay SDK does not support persistent browser contexts");let name=agentBayContextName(browserId),result=await agentBay.context.get(name,!0);if(!result.success||!result.context?.id)throw new Error(result.errorMessage||`Failed to create AgentBay browser context: ${name}`);return{id:result.context.id,name:result.context.name||name}}async function resolveAgentBayEndpoint(sessionId){let apiKey=resolveAgentBayApiKey(),{AgentBay:AgentBay2,GetCdpLinkRequest:GetCdpLinkRequest2}=await loadSdk(),response=await new AgentBay2({apiKey}).client.getCdpLink(new GetCdpLinkRequest2({authorization:`Bearer ${apiKey}`,sessionId})),endpoint=response.body?.success?response.body.data?.url:void 0;if(!endpoint)throw new Error(response.body?.message||`Failed to get AgentBay CDP link: ${sessionId}`);let url2=new URL(endpoint);if(url2.protocol!=="ws:"&&url2.protocol!=="wss:")throw new Error(`AgentBay returned an unsupported CDP endpoint: ${url2.protocol}`);return url2.toString()}async function keepAgentBaySessionAlive(sessionId){let result=await(await requireSession(sessionId,resolveAgentBayApiKey())).keepAlive();if(result.success===!1)throw new Error(result.errorMessage||"AgentBay keepalive failed")}async function configureAgentBayBrowserSession(session,input2,cookies,connectCdp=url2=>CdpClient.connect(url2),endpointUrl){let endpoint=endpointUrl??await session.browser.getEndpointUrl(),cdp=await connectCdp(endpoint);try{await cdp.sendCommand("Browser.getVersion",{},1e4);let copiedCookieCount=await cdpImportCookiesWithClient(cdp,cookies);return input2.url&&await cdp.sendCommand("Target.createTarget",{url:input2.url,background:!1}),copiedCookieCount}finally{cdp.close()}}async function initializeAgentBayBrowserSession(session,input2,cookies,options={}){if(!await session.browser.initializeAsync(options.userAgent?{userAgent:options.userAgent}:{}))throw new Error("AgentBay browser initialization failed");return configureAgentBayBrowserSession(session,input2,cookies,options.connectCdp)}async function reuseAgentBayBrowserSession(session,input2,cookies,options={}){return configureAgentBayBrowserSession(session,input2,cookies,options.connectCdp,options.endpointUrl)}function removeAgentBayRecord(record2){removeRecord(keyedConfigFile(AGENTBAY_BROWSERS_SUBDIR,record2.browserId)),removeRecord(keyedConfigFile("browsers",record2.browserId))}async function spawnAgentBayNativeHost(deps,args){if(deps.spawnNativeHost)return deps.spawnNativeHost(args);let host=spawn6(process.execPath,[deps.nativeHostScript,...args],{detached:!0,stdio:"ignore",windowsHide:!0});await new Promise((resolveSpawn,rejectSpawn)=>{host.once("error",rejectSpawn),host.once("spawn",resolveSpawn)});let hostPid=host.pid??0;if(!hostPid)throw new Error("AgentBay native host launched without a process id");return host.unref(),hostPid}function nativeHostArgs(record2,idleReleaseMinutes){return["--daemon","--agentbay-session-id",record2.sessionId,...record2.sessionMode==="attached"?["--agentbay-attachment"]:[],"--browser-id",record2.browserId,"--browser-name",record2.name,...record2.sessionMode==="attached"?[]:["--agentbay-idle-release-minutes",String(idleReleaseMinutes)]]}async function attachAgentBayBrowser(input2,deps){validateAgentBayInput(input2),validateAgentBayAttachmentInput(input2);let sessionId=resolveAgentBaySessionId(input2.sessionId),browserId=agentBaySessionBrowserId(sessionId),requestedName=attachmentName(sessionId,input2.name),cookieCopy=resolveCookieCopyPlan(input2.copyCookieDomains),copyCookieDomains=cookieCopy.domains,apiKey=(deps.resolveApiKey??resolveAgentBayApiKey)(),lifecycle=resolveAgentBayLifecycleConfig(),releaseLock=acquireLaunchLock(browserId),persistBrowserRecord=deps.persistBrowserRecord??(record2=>writeRecord(keyedConfigFile(AGENTBAY_BROWSERS_SUBDIR,record2.browserId),record2)),removeBrowserRecord=deps.removeBrowserRecord??removeAgentBayRecord,findBrowserRecord=deps.findBrowserRecord??findRecordWithStatus,hostPid=0,recordWritten=!1,activeRecord,previousRecord;try{let identityRecord=findBrowserRecord(browserId)??findBrowserRecord(sessionId),namedRecord=findBrowserRecord(requestedName);if(identityRecord&&identityRecord.record.sessionId!==sessionId)throw new Error(`AgentBay browser identity collision: ${browserId}`);if(namedRecord&&namedRecord.record.sessionId!==sessionId)throw new Error(`AgentBay browser name is already used by another session: ${requestedName}. Choose a unique name or omit it.`);let existing=identityRecord??namedRecord,ownedRecord=[identityRecord,namedRecord].find(found=>found&&found.record.sessionMode!=="attached");if(ownedRecord)throw new Error(`AgentBay session ${sessionId} is already lifecycle-owned by this host as ${ownedRecord.record.browserId}. Reuse it by name with reuse=require instead of attaching by sessionId.`);previousRecord=existing?.record;let exportedCookies=copyCookieDomains.length>0?await deps.exportCookies(copyCookieDomains):[],cookies=cookieCopy.select(exportedCookies),agentBay=await(deps.createAgentBayClient??createClient)(apiKey),session=await requireSessionFromClient(agentBay,sessionId),endpointUrl=await(deps.resolveSessionEndpoint??resolveAgentBayEndpoint)(sessionId),copiedCookieCount=await reuseAgentBayBrowserSession(session,input2,cookies,{connectCdp:deps.connectCdp,endpointUrl});if(existing?.running){let record2={...existing.record,...copyCookieDomains.length>0?{copiedCookies:{domains:copyCookieDomains,count:copiedCookieCount}}:{}};return copyCookieDomains.length>0&&persistBrowserRecord(record2),{...browserSummary2(record2,!0),created:!1,reused:!0,attached:record2.sessionMode==="attached"}}return activeRecord=existing?{...existing.record,pid:0}:{pid:0,browserId,name:requestedName,sessionId,sessionMode:"attached",persistent:!1,createdAt:new Date().toISOString()},copyCookieDomains.length>0&&(activeRecord.copiedCookies={domains:copyCookieDomains,count:copiedCookieCount}),hostPid=await spawnAgentBayNativeHost(deps,nativeHostArgs(activeRecord,lifecycle.idleReleaseTimeout)),activeRecord.pid=hostPid,persistBrowserRecord(activeRecord),recordWritten=!0,await(deps.waitForBrowserRegistration??waitForBrowserRegistration)(activeRecord.browserId,hostPid),deps.log(`AgentBay session ${activeRecord.sessionMode==="attached"?"attached":"reconnected"}: ${sessionId}, host=${hostPid}`),{...browserSummary2(activeRecord,!0),created:!1,reused:!0,attached:activeRecord.sessionMode==="attached"}}catch(error48){throw hostPid&&await stopProcess(hostPid,`--browser-id ${activeRecord?.browserId??browserId}`),recordWritten&&activeRecord&&(previousRecord?persistBrowserRecord(previousRecord):removeBrowserRecord(activeRecord)),error48}finally{releaseLock()}}async function launchAgentBayBrowser(input2,deps){if(input2.sessionId!==void 0)return attachAgentBayBrowser(input2,deps);let name=validateName(input2.name),browserId=agentBayBrowserId(name);validateAgentBayInput(input2);let reuseMode=resolveReuseMode(input2.reuse),imageId=resolveAgentBayImageId(input2.imageId),persistent=input2.persistent===!0,userAgentMode=resolveUserAgentMode(input2.userAgentMode),cookieCopy=resolveCookieCopyPlan(input2.copyCookieDomains),copyCookieDomains=cookieCopy.domains,apiKey=(deps.resolveApiKey??resolveAgentBayApiKey)(),lifecycle=resolveAgentBayLifecycleConfig(),releaseLock=acquireLaunchLock(browserId),persistBrowserRecord=deps.persistBrowserRecord??(record2=>writeRecord(keyedConfigFile(AGENTBAY_BROWSERS_SUBDIR,record2.browserId),record2)),removeBrowserRecord=deps.removeBrowserRecord??removeAgentBayRecord,findBrowserRecord=deps.findBrowserRecord??findRecordWithStatus,session=null,context,hostPid=0,recordWritten=!1;try{let existing=findBrowserRecord(browserId);if(existing?.record.sessionMode==="attached"){if(existing.running)throw new Error(`AgentBay browser name ${name} belongs to a sessionId attachment. Reuse session ${existing.record.sessionId} by sessionId, or choose a unique name.`);removeBrowserRecord(existing.record),deps.log(`Stopped AgentBay attachment record cleaned before named launch: ${browserId}`),existing=null}if(existing){if(!existing.running&&reuseMode==="require")throw new Error(`AgentBay browser ${browserId} has status=stopped and reuse=require cannot create a replacement. Retry with reuse=prefer, or run browser_close to clean the stopped record.`);if(existing.running){if(reuseMode==="never")throw new Error(`AgentBay browser already exists with status=running: ${browserId}. Retry with reuse=prefer or reuse=require to reuse it.`);validateReusableAgentBayConfiguration(input2,existing.record);let exportedCookies2=copyCookieDomains.length>0?await deps.exportCookies(copyCookieDomains):[],cookies2=cookieCopy.select(exportedCookies2),agentBay2=await(deps.createAgentBayClient??createClient)(apiKey),existingSession=await requireSessionFromClient(agentBay2,existing.record.sessionId),endpointUrl=await(deps.resolveSessionEndpoint??resolveAgentBayEndpoint)(existing.record.sessionId),copiedCookieCount2=await reuseAgentBayBrowserSession(existingSession,input2,cookies2,{connectCdp:deps.connectCdp,endpointUrl}),record3={...existing.record,...copyCookieDomains.length>0?{copiedCookies:{domains:copyCookieDomains,count:copiedCookieCount2}}:{}};return copyCookieDomains.length>0&&persistBrowserRecord(record3),deps.log(`AgentBay browser reused: ${browserId}, host=${record3.pid}`),{...browserSummary2(record3,!0),created:!1,reused:!0,attached:!1}}else{let agentBay2=await(deps.createAgentBayClient??createClient)(apiKey);try{await releaseAgentBayBrowserResources(existing.record,agentBay2,{persistRecord:persistBrowserRecord})}catch(error48){throw new Error(`Failed to clean stopped AgentBay browser ${browserId} before launch: ${error48 instanceof Error?error48.message:String(error48)}. Run browser_close for ${browserId} and retry.`,{cause:error48})}await stopProcess(existing.record.pid,`--browser-id ${existing.record.browserId}`),removeBrowserRecord(existing.record),deps.log(`AgentBay stopped browser record cleaned before launch: ${browserId}`)}}if(reuseMode==="require")throw new Error(`AgentBay browser is not running and reuse=require: ${browserId}`);let[exportedCookies,userAgent]=await Promise.all([copyCookieDomains.length>0?deps.exportCookies(copyCookieDomains):Promise.resolve([]),userAgentMode==="desktop"?deps.getBrowserUserAgent().then(normalizeDesktopUserAgent):Promise.resolve(void 0)]),cookies=cookieCopy.select(exportedCookies),agentBay=await(deps.createAgentBayClient??createClient)(apiKey);context=persistent?await resolvePersistentContext(agentBay,browserId):void 0;let{LifecyclePolicy:LifecyclePolicy2}=await loadSdk(),created=await agentBay.create({imageId,framework:"mearl",lifecyclePolicy:new LifecyclePolicy2(lifecycle),...context?{browserContext:{contextId:context.id,autoUpload:!0,syncMode:"standard"}}:{}});if(!created.success||!created.session)throw new Error(created.errorMessage||"AgentBay session creation failed");session=created.session;let copiedCookieCount=await initializeAgentBayBrowserSession(session,input2,cookies,{userAgent,connectCdp:deps.connectCdp}),record2={pid:0,browserId,name,sessionId:session.sessionId,sessionMode:"owned",imageId,userAgentMode,persistent,...context?{contextId:context.id,contextName:context.name}:{},createdAt:new Date().toISOString(),...copyCookieDomains.length>0?{copiedCookies:{domains:copyCookieDomains,count:copiedCookieCount}}:{}};return hostPid=await spawnAgentBayNativeHost(deps,nativeHostArgs(record2,lifecycle.idleReleaseTimeout)),record2.pid=hostPid,persistBrowserRecord(record2),recordWritten=!0,await(deps.waitForBrowserRegistration??waitForBrowserRegistration)(browserId,hostPid),deps.log(`AgentBay browser launched: ${browserId}, host=${hostPid}`),{...browserSummary2(record2,!0),created:!0,reused:!1,attached:!1}}catch(error48){if(hostPid&&await stopProcess(hostPid,`--browser-id ${browserId}`),recordWritten&&(removeRecord(keyedConfigFile(AGENTBAY_BROWSERS_SUBDIR,browserId)),removeRecord(keyedConfigFile("browsers",browserId))),session){let cleanupError;try{let deleted=await session.delete(!1);deleted.success||(cleanupError=new Error(deleted.errorMessage||"AgentBay session deletion failed"))}catch(deleteError){cleanupError=deleteError}if(cleanupError){let recoveryRecord={pid:hostPid,browserId,name,sessionId:session.sessionId,sessionMode:"owned",imageId,userAgentMode,persistent,...context?{contextId:context.id,contextName:context.name}:{},createdAt:new Date().toISOString()},recoverySaved=!1,recoveryError;try{persistBrowserRecord(recoveryRecord),recoverySaved=!0}catch(writeError){recoveryError=writeError}throw deps.log(`AgentBay launch cleanup failed for ${session.sessionId}:`,cleanupError instanceof Error?cleanupError.message:String(cleanupError)),recoveryError&&deps.log(`AgentBay recovery metadata could not be saved for ${session.sessionId}:`,recoveryError instanceof Error?recoveryError.message:String(recoveryError)),new AggregateError(recoveryError?[error48,cleanupError,recoveryError]:[error48,cleanupError],`${error48 instanceof Error?error48.message:String(error48)}; `+(recoverySaved?"AgentBay session cleanup failed and recovery metadata was retained for browser_close":`AgentBay session cleanup failed; session ${session.sessionId} may require manual deletion`),{cause:error48})}}throw error48}finally{releaseLock()}}function isMissingSessionError(error48){let message=error48 instanceof Error?error48.message:String(error48);return/not[ -]?found|does not exist|already deleted|invalid session/i.test(message)}async function releaseAgentBayBrowserResources(record2,agentBay,options={}){if(record2.sessionMode==="attached")throw new Error(`AgentBay browser ${record2.browserId} is a local attachment. Use browser_release to detach it without closing session ${record2.sessionId}.`);let deleteContext=record2.persistent===!0&&options.deleteProfile===!0,syncContext=record2.persistent===!0&&!deleteContext,contextSynced=!!record2.contextSyncedAt,session;try{session=await requireSessionFromClient(agentBay,record2.sessionId)}catch(error48){if(!isMissingSessionError(error48))throw error48}if(session){if(syncContext&&!contextSynced){if(!session.callMcpTool)throw new Error("The installed AgentBay SDK cannot stop the browser before context sync");let stopped=await session.callMcpTool("stopChrome",{},!1);if(stopped.success===!1)throw new Error(stopped.errorMessage||"AgentBay browser shutdown failed");if(!session.context)throw new Error("The installed AgentBay SDK cannot synchronize browser context state");let synced=await session.context.sync();if(!synced.success)throw new Error(synced.errorMessage||"AgentBay browser context sync failed");contextSynced=!0,record2.contextSyncedAt=new Date().toISOString(),options.persistRecord?.(record2)}try{let result=await session.delete(!1);if(!result.success)throw new Error(result.errorMessage||"AgentBay session deletion failed")}catch(error48){if(!isMissingSessionError(error48))throw error48}}if(deleteContext){if(!record2.contextId||!record2.contextName||!agentBay.context)throw new Error("AgentBay browser context metadata is unavailable for profile deletion");let result=await agentBay.context.delete({id:record2.contextId,name:record2.contextName});if(!result.success)throw new Error(result.errorMessage||"AgentBay context deletion failed")}return{sessionDeleted:!0,...syncContext?{contextSynced}:{},...deleteContext?{contextDeleted:!0}:{}}}function detachAgentBayBrowser(selector,expectedPid=process.pid){let found=findRecordWithStatus(selector);return!found||found.record.sessionMode!=="attached"||found.record.pid!==expectedPid?{detached:!1}:(removeAgentBayRecord(found.record),{detached:!0,sessionId:found.record.sessionId})}async function closeAgentBayBrowser(selector,options={}){let record2=findRecord(selector);if(!record2)throw new Error(`AgentBay browser not found: ${selector}`);let releaseLock=acquireLaunchLock(record2.browserId);try{if(record2=findRecord(record2.browserId),!record2)throw new Error(`AgentBay browser not found: ${selector}`);if(record2.sessionMode==="attached")throw new Error(`AgentBay browser ${record2.browserId} is attached to session ${record2.sessionId}. Use browser_release to detach this host, or browser_close from the host that created the session.`);let agentBay=await createClient(resolveAgentBayApiKey()),released=await releaseAgentBayBrowserResources(record2,agentBay,{...options,persistRecord:updatedRecord=>writeRecord(keyedConfigFile(AGENTBAY_BROWSERS_SUBDIR,updatedRecord.browserId),updatedRecord)}),closingOwnHost=record2.pid===process.pid;closingOwnHost||await stopProcess(record2.pid,`--browser-id ${record2.browserId}`),removeRecord(keyedConfigFile("browsers",record2.browserId));let stoppedRecord=stoppedPersistentBrowserRecord(record2,options.deleteProfile===!0);return stoppedRecord?writeRecord(keyedConfigFile(AGENTBAY_BROWSERS_SUBDIR,record2.browserId),stoppedRecord):removeRecord(keyedConfigFile(AGENTBAY_BROWSERS_SUBDIR,record2.browserId)),closingOwnHost&&setTimeout(()=>process.kill(process.pid,"SIGTERM"),250).unref(),{browserId:record2.browserId,provider:"agentbay",closed:!0,...released,...record2.persistent===!0?{profileDeleted:options.deleteProfile===!0}:{profileDeleted:!0}}}finally{releaseLock()}}import{randomUUID as randomUUID7}from"node:crypto";import{basename as basename3,posix}from"node:path";var AGENTBAY_FILE_UPLOAD_WAIT_SECONDS=120;function pageUploadTargets(action,data){return action==="page_upload"?[{data}]:action!=="run_actions"||!Array.isArray(data?.actions)?[]:data.actions.flatMap((step,index)=>step?.action==="page_upload"?[{data:step.data,step:index}]:[])}function validateFilePaths(target){let filePaths=target.data?.filePaths;if(!Array.isArray(filePaths)||filePaths.length===0||filePaths.some(filePath=>typeof filePath!="string"||filePath.length===0)){let prefix=target.step===void 0?"":`Step ${target.step}: `;throw new Error(`${prefix}Invalid filePaths: must be a non-empty array of file path strings`)}return filePaths}function uploadError(result){return result.errorMessage??result.error_message??result.error??"unknown error"}async function stageAgentBayPageUploads(sessionId,action,data,dependencies={}){let targets=pageUploadTargets(action,data);if(targets.length===0)return data;let targetFilePaths=targets.map(target=>validateFilePaths(target)),fileSystem=(await(dependencies.getSession??getAgentBaySession)(sessionId)).fileSystem;if(!fileSystem)throw new Error("The installed AgentBay SDK does not support session file transfer");let contextPath=await fileSystem.getFileTransferContextPath();if(!contextPath)throw new Error(`AgentBay file transfer context is unavailable for session ${sessionId}`);let createTransferId=dependencies.createTransferId??randomUUID7,stagedPaths=await Promise.all(targetFilePaths.map(filePaths=>Promise.all(filePaths.map(async localPath=>{let remoteDirectory=posix.join(contextPath,createTransferId()),directoryResult=await fileSystem.createDirectory(remoteDirectory);if(directoryResult?.success===!1)throw new Error(`Failed to prepare AgentBay upload for ${basename3(localPath)}: ${uploadError(directoryResult)}`);let remotePath=posix.join(remoteDirectory,basename3(localPath)),result=await fileSystem.uploadFile(localPath,remotePath,{wait:!0,waitTimeout:AGENTBAY_FILE_UPLOAD_WAIT_SECONDS});if(result?.success!==!0)throw new Error(`Failed to upload ${basename3(localPath)} to AgentBay: ${uploadError(result)}`);return remotePath}))));if(action==="page_upload")return{...data,filePaths:stagedPaths[0]};let runActions=data,targetIndex=0;return{...runActions,actions:runActions.actions.map(step=>{if(step.action!=="page_upload")return step;let filePaths=stagedPaths[targetIndex++];return{...step,data:{...step.data,filePaths}}})}}var BROWSERS_SUBDIR="browsers",STALE_RECORD_TTL_MS=5*6e4,FOCUS_WRITE_THROTTLE_MS=1e3,identity=null,logFn2=()=>{};function initBrowserRegistry(deps){logFn2=deps.log}function recordFileFor2(browserId){return keyedConfigFile(BROWSERS_SUBDIR,browserId)}function ownsRecord(browserId){let existing=readRecord(recordFileFor2(browserId));return!existing||existing.pid===process.pid||!isAlive(existing.pid)}function persist(patch){if(!identity)return;let file2=recordFileFor2(identity.browserId);if(!ownsRecord(identity.browserId))return;let previous=readRecord(file2),record2={pid:process.pid,browserId:identity.browserId,socketPath:identity.socketPath,browserName:identity.browserName,nativeHostVersion:identity.nativeHostVersion,transport:identity.transport,startedAt:identity.startedAt,lastFocusedAt:previous?.lastFocusedAt,extensionVersion:previous?.extensionVersion,...patch,updatedAt:Date.now()};try{writeRecord(file2,record2)}catch(error48){logFn2("browser-registry: failed to write record:",String(error48))}}function registerBrowser(info){let startedAt=identity?.startedAt??new Date().toISOString();identity={browserId:info.browserId,socketPath:info.socketPath,browserName:info.browserName,nativeHostVersion:info.nativeHostVersion,transport:info.transport,startedAt};let previous=readRecord(recordFileFor2(info.browserId));persist({lastFocusedAt:previous?.lastFocusedAt??info.lastFocusedAt??Date.now(),extensionVersion:info.extensionVersion}),logFn2(`browser-registry: registered ${info.browserName} (${info.browserId})`)}var lastFocusWriteAt=0,focusFlushTimer=null;function writeFocusNow(){lastFocusWriteAt=Date.now(),persist({lastFocusedAt:lastFocusWriteAt})}function touchFocus(){if(!identity)return;let elapsed=Date.now()-lastFocusWriteAt;if(elapsed>=FOCUS_WRITE_THROTTLE_MS){writeFocusNow();return}focusFlushTimer||(focusFlushTimer=setTimeout(()=>{focusFlushTimer=null,writeFocusNow()},FOCUS_WRITE_THROTTLE_MS-elapsed),focusFlushTimer.unref())}function unregisterBrowser(){if(focusFlushTimer&&(clearTimeout(focusFlushTimer),focusFlushTimer=null),!identity)return;let file2=recordFileFor2(identity.browserId),existing=readRecord(file2);existing&&existing.pid!==process.pid||removeRecord(file2)}function pruneDeadBrowsers(){let now=Date.now();for(let file2 of listRecordFiles(keyedDir(BROWSERS_SUBDIR))){let rec=readRecord(file2);if(!rec){removeRecord(file2);continue}isAlive(rec.pid)||now-(rec.updatedAt??0)>STALE_RECORD_TTL_MS&&removeRecord(file2)}}function listRegisteredBrowsers(){let records=[];for(let file2 of listRecordFiles(keyedDir(BROWSERS_SUBDIR))){let record2=readRecord(file2);record2&&isAlive(record2.pid)&&records.push(record2)}return records.sort((a,b)=>(b.lastFocusedAt??0)-(a.lastFocusedAt??0)||(b.updatedAt??0)-(a.updatedAt??0))}async function ensureDiscoverableCdpBrowser(discovery){return discovery.isPublished()?!0:await discovery.isAvailable()?(discovery.publish(),discovery.monitor(),!0):!1}function connectionFields(record2){return{extensionVersion:record2.extensionVersion,nativeHostVersion:record2.nativeHostVersion,transport:record2.transport,providerId:record2.providerId,providerName:record2.providerName,providerVersion:record2.providerVersion,providerProtocolVersion:record2.providerProtocolVersion,pairing:record2.pairing}}function mergeBrowserInventory(connected,managed){let managedById=new Map(managed.map(browser=>[browser.browserId,browser])),browsers=connected.map(record2=>{let managedBrowser=managedById.get(record2.browserId);return managedBrowser?(managedById.delete(record2.browserId),{browserId:record2.browserId,name:managedBrowser.name,type:"managed",status:"connected",...connectionFields(record2),headless:managedBrowser.headless,persistent:managedBrowser.persistent,provider:managedBrowser.provider,..."cdpPort"in managedBrowser?{cdpPort:managedBrowser.cdpPort}:{},..."agentbaySessionId"in managedBrowser?{agentbaySessionId:managedBrowser.agentbaySessionId}:{},..."agentbaySessionMode"in managedBrowser?{agentbaySessionMode:managedBrowser.agentbaySessionMode}:{},..."agentbayImageId"in managedBrowser&&managedBrowser.agentbayImageId?{agentbayImageId:managedBrowser.agentbayImageId}:{},..."agentbayContextId"in managedBrowser&&managedBrowser.agentbayContextId?{agentbayContextId:managedBrowser.agentbayContextId}:{},..."agentbayContextName"in managedBrowser&&managedBrowser.agentbayContextName?{agentbayContextName:managedBrowser.agentbayContextName}:{},createdAt:managedBrowser.createdAt,..."account"in managedBrowser?{account:managedBrowser.account}:{},..."copiedCookies"in managedBrowser?{copiedCookies:managedBrowser.copiedCookies}:{}}):{browserId:record2.browserId,name:record2.browserName,type:"regular",status:record2.status==="pairing"?"pairing":"connected",...connectionFields(record2)}}),disconnected=[...managedById.values()].sort((a,b)=>b.createdAt.localeCompare(a.createdAt)).map(browser=>({browserId:browser.browserId,name:browser.name,type:"managed",status:browser.running?"running_disconnected":"stopped",headless:browser.headless,persistent:browser.persistent,provider:browser.provider,..."cdpPort"in browser?{cdpPort:browser.cdpPort}:{},..."agentbaySessionId"in browser?{agentbaySessionId:browser.agentbaySessionId}:{},..."agentbaySessionMode"in browser?{agentbaySessionMode:browser.agentbaySessionMode}:{},..."agentbayImageId"in browser&&browser.agentbayImageId?{agentbayImageId:browser.agentbayImageId}:{},..."agentbayContextId"in browser&&browser.agentbayContextId?{agentbayContextId:browser.agentbayContextId}:{},..."agentbayContextName"in browser&&browser.agentbayContextName?{agentbayContextName:browser.agentbayContextName}:{},createdAt:browser.createdAt,..."account"in browser?{account:browser.account}:{},..."copiedCookies"in browser?{copiedCookies:browser.copiedCookies}:{}}));return browsers.push(...disconnected),{count:browsers.length,connectedCount:browsers.filter(browser=>browser.status==="connected").length,browsers}}function listBrowserInventory(){let managed=[...listManagedBrowsers(),...listAgentBayBrowsers()];return mergeBrowserInventory(listRegisteredBrowsers(),managed)}import fs5 from"node:fs";import path6 from"node:path";import os2 from"node:os";import{randomUUID as randomUUID8}from"node:crypto";var NATIVE_HOST_VERSION="2.13.0";var MEASUREMENT_ID="G-W84LJDZ6PH",API_SECRET="X233siI5RrGYLhlD0kBKEQ",ENDPOINT=`https://www.google-analytics.com/mp/collect?measurement_id=${MEASUREMENT_ID}&api_secret=${API_SECRET}`,CLIENT_ID_PATTERN=/^\d+\.\d+$/,BUILD_CHANNEL=NATIVE_HOST_VERSION==="unknown"?"development":"production",CONFIG_DIR=path6.join(os2.homedir(),".mearl"),CONFIG_FILE=path6.join(CONFIG_DIR,"config.json");function readConfig(){try{return JSON.parse(fs5.readFileSync(CONFIG_FILE,"utf-8"))}catch{return{}}}function writeConfig(config2){try{fs5.mkdirSync(CONFIG_DIR,{recursive:!0}),fs5.writeFileSync(CONFIG_FILE,JSON.stringify(config2,null,2))}catch{}}var clientId=null;function createClientId(seed=randomUUID8()){let first=2166136261,second=2246822519;for(let index=0;index<seed.length;index++){let code=seed.charCodeAt(index);first=Math.imul(first^code,16777619)>>>0,second=Math.imul(second^code,3266489917)>>>0}return`${first||1}.${second||1}`}function getClientId(){if(clientId)return clientId;let config2=readConfig();return config2.clientId&&CLIENT_ID_PATTERN.test(config2.clientId)?(clientId=config2.clientId,clientId):(clientId=createClientId(config2.clientId),writeConfig({...config2,clientId}),clientId)}function setAnalyticsClientId(value){return typeof value!="string"||!CLIENT_ID_PATTERN.test(value)?!1:(clientId=value,!0)}function classifyAnalyticsError(error48){let message=error48 instanceof Error?error48.message:String(error48);return/timed?\s*out|timeout/i.test(message)?"timeout":/permission|not authorized|access denied|forbidden/i.test(message)?"permission_denied":/not found|no matching|does not exist/i.test(message)?"not_found":/not connected|disconnected|unavailable|connection (?:failed|closed)/i.test(message)?"unavailable":/invalid|required|must be|unsupported/i.test(message)?"invalid_request":"execution_error"}function trackAction(action,params){let payload={client_id:getClientId(),events:[{name:"agent_action",params:{action,...params,mearl_version:NATIVE_HOST_VERSION,runtime:"native_host",build_channel:BUILD_CHANNEL}}]};fetch(ENDPOINT,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(payload),keepalive:!0}).catch(()=>{})}import{open}from"node:fs/promises";import path8 from"node:path";var TRUNCATED_MARKER=`
|
|
1254
|
+
}`,arguments:[{value:ancestorDepth}],returnByValue:!1});if(ancestorObjectId=ancestor.result?.objectId,!ancestorObjectId||ancestor.result?.subtype==="null")throw new Error("page_snapshot: cannot resolve an ancestor for rootRef");let ancestorBackendNodeId=(await sendCdpDeviceShellPageCommand(session,"DOM.describeNode",{objectId:ancestorObjectId})).node?.backendNodeId;if(ancestorBackendNodeId===void 0)throw new Error("page_snapshot: cannot resolve an ancestor for rootRef");return ancestorBackendNodeId}finally{ancestorObjectId&&await sendCdpDeviceShellPageCommand(session,"Runtime.releaseObject",{objectId:ancestorObjectId}).catch(()=>{}),await sendCdpDeviceShellPageCommand(session,"Runtime.releaseObject",{objectId}).catch(()=>{})}}async function getViewportBackendNodeIds(session){let[metrics,captured]=await Promise.all([sendCdpDeviceShellPageCommand(session,"Page.getLayoutMetrics",{}),sendCdpDeviceShellPageCommand(session,"DOMSnapshot.captureSnapshot",{computedStyles:[],includeDOMRects:!0,includePaintOrder:!1})]),viewport=resolveDOMSnapshotViewportBounds(metrics);if(!viewport)throw new Error("page_snapshot: viewport metrics are unavailable");let{left,top,width,height}=viewport,right=left+width,bottom=top+height,visible=new Set;for(let document2 of captured.documents??[]){let backendNodeIds=document2.nodes?.backendNodeId??[],nodeIndexes=document2.layout?.nodeIndex??[],bounds=document2.layout?.bounds??[];for(let index=0;index<nodeIndexes.length;index+=1){let box=bounds[index],backendNodeId=backendNodeIds[nodeIndexes[index]];if(!box||backendNodeId===void 0)continue;let[x,y,boxWidth,boxHeight]=box;boxWidth<=0||boxHeight<=0||x<right&&x+boxWidth>left&&y<bottom&&y+boxHeight>top&&visible.add(backendNodeId)}}return visible}async function cdpPageSnapshot(session,data){let mode=data?.mode??"full",rootSelector=data?.rootSelector,rootRef=data?.rootRef,ancestorDepth=data?.ancestorDepth??0,query=resolvePageSnapshotQuery(data?.query);if(!["full","interactive","viewport"].includes(mode))throw new Error("page_snapshot: mode must be one of full, interactive, viewport");if(rootSelector!==void 0&&(typeof rootSelector!="string"||!rootSelector.trim()))throw new Error("page_snapshot: rootSelector must be a non-empty CSS selector");if(rootRef!==void 0&&(typeof rootRef!="string"||!/^@e\d+$/.test(rootRef)))throw new Error('page_snapshot: rootRef must be a snapshot ref like "@e3"');if(rootSelector!==void 0&&rootRef!==void 0)throw new Error("page_snapshot: rootSelector and rootRef are mutually exclusive");if(!Number.isInteger(ancestorDepth)||ancestorDepth<0||ancestorDepth>20)throw new Error("page_snapshot: ancestorDepth must be an integer between 0 and 20");if(ancestorDepth>0&&rootRef===void 0)throw new Error("page_snapshot: ancestorDepth requires rootRef");let rootBackendNodeId;if(rootSelector)rootBackendNodeId=await resolveRootBackendNodeId(session,rootSelector);else if(rootRef){let entry=resolvePageRef(session,rootRef);if(!entry)throw new Error(`Ref ${rootRef} not found. Run page_snapshot first to get fresh refs.`);rootBackendNodeId=await resolveAncestorBackendNodeId(session,entry.backendNodeId,ancestorDepth)}let snapshotRefs=beginPageSnapshotRefs(session),[result,visibleBackendNodeIds]=await Promise.all([sendCdpDeviceShellPageCommand(session,rootBackendNodeId===void 0?"Accessibility.getFullAXTree":"Accessibility.queryAXTree",rootBackendNodeId===void 0?{depth:data?.depth}:{backendNodeId:rootBackendNodeId}),mode==="viewport"||mode==="interactive"?getViewportBackendNodeIds(session):Promise.resolve(void 0)]),nodes=result.nodes??[];await reconcileAXCheckedStates(nodes,backendNodeId=>readDOMCheckedState2(session,backendNodeId));let nodeMap=new Map;for(let node of nodes)nodeMap.set(node.nodeId,node);let rootNode=nodes[0];if(!rootNode)return snapshotRefs.commit(new Set),{snapshot:"(empty page)",refs:{},elementCount:0,outputNodeCount:1,mode,...rootSelector?{rootSelector}:{},...rootRef?{rootRef,ancestorDepth}:{},...query?{query,matches:[],matchCount:0}:{}};let rawTree=buildSnapshotTree(nodeMap,rootNode.nodeId,snapshotRefs),viewportFilteredTree=mode==="interactive"?filterSnapshotTree(rawTree,"viewport",visibleBackendNodeIds):rawTree,effectiveMode=mode;mode==="interactive"&&!hasInteractiveSnapshotNode(viewportFilteredTree)&&(effectiveMode="viewport");let modeFilteredTree=mode==="interactive"?effectiveMode==="interactive"?filterSnapshotTree(viewportFilteredTree,"interactive"):viewportFilteredTree:filterSnapshotTree(rawTree,effectiveMode,visibleBackendNodeIds),queryResult=query?filterSnapshotTreeByQuery(modeFilteredTree,query):{tree:modeFilteredTree,matches:[]},limitedMatches=query?limitPageSnapshotQueryMatches(queryResult.matches):{matches:[],truncated:!1},tree=queryResult.tree,lines=[];tree&&formatSnapshotNode(tree,0,lines);let formatted=formatSnapshotWithLimits(lines.length>0?lines:[query?"(no matches)":"(empty page)"],{maxChars:data?.maxChars,maxNodes:data?.maxNodes}),refs={},outputRefKeys=new Set(Array.from(formatted.snapshot.matchAll(/(?:^|\n)\s*(@e\d+)\s/g),match=>match[1]));for(let match of limitedMatches.matches)match.ref&&outputRefKeys.add(match.ref);snapshotRefs.commit(outputRefKeys);let registry2=getPageRefRegistry(session);for(let ref of outputRefKeys){let entry=registry2.resolve(ref);entry&&(refs[ref.slice(1)]={backendNodeId:entry.backendNodeId})}return{snapshot:formatted.snapshot,refs,elementCount:countSnapshotNodes(tree),outputNodeCount:formatted.outputNodeCount,mode,...rootSelector?{rootSelector}:{},...rootRef?{rootRef,ancestorDepth}:{},...query?{query,matches:limitedMatches.matches,matchCount:queryResult.matches.length,...limitedMatches.truncated?{matchesTruncated:!0}:{}}:{},...effectiveMode!==mode?{fallbackMode:"viewport"}:{},...formatted.truncated?{truncated:!0}:{}}}async function cdpPageFrames(session,_data){let result=await session.client.sendCommand("Page.getFrameTree",{});function flattenFrameTree(tree){if(!tree)return[];let{frame,childFrames=[]}=tree;return[{frameId:frame.id,parentFrameId:frame.parentId??null,url:frame.url,name:frame.name??""},...childFrames.flatMap(flattenFrameTree)]}let frames=flattenFrameTree(result.frameTree);return{frames,count:frames.length}}registerActions([{name:"page_snapshot",session:"page",handler:cdpPageSnapshot},{name:"page_frames",session:"page",handler:cdpPageFrames}]);var MEARL_SERVICE_COOKIE_DOMAINS=["tdbank.alibaba-inc.com","ats2.alibaba-inc.com","g.alibaba-inc.com","login.alibaba-inc.com","token-hub.alibaba-inc.com","alibaba-inc.com"],MEARL_SERVICE_COOKIE_HOSTS=new Set(MEARL_SERVICE_COOKIE_DOMAINS);function normalizeCookieDomain2(input2){let value=input2.trim();if(!value)throw new Error("Cookie domain must be a non-empty string");let hostname3;try{hostname3=new URL(value.includes("://")?value:`https://${value}`).hostname}catch{throw new Error(`Invalid cookie domain: ${input2}`)}if(hostname3=hostname3.toLowerCase().replace(/^\.+/,"").replace(/\.+$/,""),!hostname3)throw new Error(`Invalid cookie domain: ${input2}`);return hostname3}function normalizeCookieDomains(inputs){if(!Array.isArray(inputs))throw new Error("copyCookieDomains must be an array of domains");return[...new Set(inputs.map(value=>normalizeCookieDomain2(String(value))))]}function isMearlServiceCookie(cookie){let domain2=normalizeCookieDomain2(cookie.domain);return MEARL_SERVICE_COOKIE_HOSTS.has(domain2)?!0:domain2.endsWith(".tdbank.alibaba-inc.com")||domain2.endsWith(".ats2.alibaba-inc.com")}function normalizeCookieCopyScope(input2){let presets=input2.presets??[];if(!Array.isArray(presets)||presets.some(preset=>preset!=="mearl-services"))throw new Error("copyCookieDomains.presets contains an unsupported preset");return{includeMearlServices:presets.includes("mearl-services"),domains:normalizeCookieDomains(input2.domains??[])}}function resolveCookieCopyPlan(input2){let includeMearlServices=!1,explicitDomains=[];if(input2==="mearl-services")includeMearlServices=!0;else if(Array.isArray(input2))explicitDomains=normalizeCookieDomains(input2);else if(input2!=null&&typeof input2=="object"){let scope=normalizeCookieCopyScope(input2);includeMearlServices=scope.includeMearlServices,explicitDomains=scope.domains}else if(input2!==void 0)throw new Error('copyCookieDomains must be an array of domains, "mearl-services", or a scope object');return includeMearlServices?{domains:[...new Set([...MEARL_SERVICE_COOKIE_DOMAINS,...explicitDomains])],select:cookies=>cookies.filter(cookie=>isMearlServiceCookie(cookie)||explicitDomains.some(domain2=>cookieMatchesDomain(cookie.domain,domain2)))}:{domains:explicitDomains,select:cookies=>cookies}}function cookieMatchesDomain(cookieDomain,requestedDomain){let cookieHost=cookieDomain.toLowerCase().replace(/^\.+/,"");return cookieHost===requestedDomain||cookieHost.endsWith(`.${requestedDomain}`)||requestedDomain.endsWith(`.${cookieHost}`)}function toTransferableCookie(cookie){let result={name:String(cookie.name),value:String(cookie.value),domain:String(cookie.domain),path:String(cookie.path||"/"),secure:!!cookie.secure,httpOnly:!!cookie.httpOnly};return["Strict","Lax","None"].includes(cookie.sameSite)&&(result.sameSite=cookie.sameSite),typeof cookie.expires=="number"&&cookie.expires>0&&(result.expires=cookie.expires),["Low","Medium","High"].includes(cookie.priority)&&(result.priority=cookie.priority),typeof cookie.sameParty=="boolean"&&(result.sameParty=cookie.sameParty),["Unset","NonSecure","Secure"].includes(cookie.sourceScheme)&&(result.sourceScheme=cookie.sourceScheme),typeof cookie.sourcePort=="number"&&(result.sourcePort=cookie.sourcePort),cookie.partitionKey?.topLevelSite&&(result.partitionKey={topLevelSite:String(cookie.partitionKey.topLevelSite),...typeof cookie.partitionKey.hasCrossSiteAncestor=="boolean"?{hasCrossSiteAncestor:cookie.partitionKey.hasCrossSiteAncestor}:{}}),result}async function cdpExportCookies(session,domains){let requestedDomains=normalizeCookieDomains(domains);return((await(await session.getBrowserClient()).sendCommand("Storage.getCookies",{})).cookies??[]).filter(cookie=>requestedDomains.some(domain2=>cookieMatchesDomain(String(cookie.domain),domain2))).map(toTransferableCookie)}async function cdpImportCookies(session,cookies){if(cookies.length===0)return 0;let browser=await session.getBrowserClient();return cdpImportCookiesWithClient(browser,cookies)}async function cdpImportCookiesWithClient(browser,cookies){return cookies.length===0?0:(await browser.sendCommand("Storage.setCookies",{cookies}),cookies.length)}import{existsSync as existsSync11,readFileSync as readFileSync8}from"node:fs";import{spawn as spawn6}from"node:child_process";import{homedir as homedir2}from"node:os";import{dirname as dirname6,join as join8,parse,resolve as resolve3}from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";import{closeSync as closeSync4,existsSync as existsSync5,mkdtempSync,mkdirSync as mkdirSync3,openSync as openSync4,readFileSync as readFileSync4,renameSync as renameSync4,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{spawn as spawn4,spawnSync as spawnSync2}from"node:child_process";import{randomUUID as randomUUID5}from"node:crypto";import{tmpdir}from"node:os";import{join as join5}from"node:path";function stoppedPersistentBrowserRecord(record2,deleteProfile){if(deleteProfile||record2.persistent!==!0)return null;let stopped={...record2,pid:0};return"hostPid"in stopped?{...stopped,hostPid:0}:stopped}var MANAGED_BROWSERS_SUBDIR="managed-browsers",MANAGED_BROWSER_LOCKS_SUBDIR="managed-browser-locks",MANAGED_PROFILES_SUBDIR="managed-profiles",LAUNCH_TIMEOUT_MS=15e3;function validateName(value){let name=typeof value=="string"?value.trim():"";if(!name)throw new Error("name is required");if(name.length>64)throw new Error("name must be at most 64 characters");if(/[/\\\0\r\n]/.test(name))throw new Error("name contains unsupported characters");return name}function managedBrowserId(name){return`managed:${name.toLocaleLowerCase("en-US")}`}function hasTdbankSelector(data){return data.accountId!==void 0||data.havanaId!==void 0||typeof data.query=="string"&&data.query.trim().length>0}function validateTdbankSelector(data){if(data.havanaId!==void 0&&data.site===void 0)throw new Error("site is required when havanaId is provided");if([data.accountId!==void 0,data.havanaId!==void 0,typeof data.query=="string"&&data.query.trim().length>0].filter(Boolean).length>1)throw new Error("Use only one of accountId, havanaId + site, or query")}function chromeExecutableCandidates(platform=process.platform){let envPath=process.env.MEARL_CHROME_PATH,candidates=envPath?[envPath]:[];if(platform==="darwin")return candidates.concat(["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary","/Applications/Chromium.app/Contents/MacOS/Chromium"]);if(platform==="win32"){let local=process.env.LOCALAPPDATA??"",programFiles=process.env.PROGRAMFILES??"",programFilesX86=process.env["PROGRAMFILES(X86)"]??"";return candidates.concat([join5(local,"Google","Chrome","Application","chrome.exe"),join5(programFiles,"Google","Chrome","Application","chrome.exe"),join5(programFilesX86,"Google","Chrome","Application","chrome.exe")])}return candidates.concat(["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium","/usr/bin/chromium-browser"])}function resolveChromeExecutable(explicitPath){if(explicitPath){if(!existsSync5(explicitPath))throw new Error(`Chrome executable not found: ${explicitPath}`);return explicitPath}let found=chromeExecutableCandidates().find(candidate=>candidate&&existsSync5(candidate));if(!found)throw new Error("Chrome executable not found. Set executablePath or MEARL_CHROME_PATH.");return found}function desktopChromeUserAgent(version2,platform=process.platform){if(!/^\d+(?:\.\d+){1,3}$/.test(version2))throw new Error(`Invalid Chrome version: ${version2}`);return`Mozilla/5.0 (${platform==="darwin"?"Macintosh; Intel Mac OS X 10_15_7":platform==="win32"?"Windows NT 10.0; Win64; x64":"X11; Linux x86_64"}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${version2} Safari/537.36`}function resolveChromeVersion(executablePath){let result=spawnSync2(executablePath,["--version"],{encoding:"utf8",windowsHide:!0}),version2=`${result.stdout??""} ${result.stderr??""}`.match(/\b(\d+(?:\.\d+){1,3})\b/)?.[1];if(!version2)throw new Error(`Could not determine Chrome version from: ${executablePath}`);return version2}function resolveUserAgentMode(value){if(value===void 0||value==="default")return"default";if(value==="desktop")return"desktop";throw new Error('userAgentMode must be "default" or "desktop"')}function buildManagedChromeArgs(options){return[`--user-data-dir=${options.userDataDir}`,"--remote-debugging-port=0","--no-first-run","--no-default-browser-check","--disable-background-networking",...options.headless?["--headless=new"]:[],...options.userAgent?[`--user-agent=${options.userAgent}`]:[],"about:blank"]}function browserSummary(record2,running){return{browserId:record2.browserId,name:record2.name,provider:"local",headless:record2.headless,persistent:record2.persistent,cdpPort:record2.cdpPort,createdAt:record2.createdAt,account:record2.account,copiedCookies:record2.copiedCookies,running}}function isManagedProcess(pid,commandMarker,platform=process.platform){if(!isAlive(pid))return!1;try{if(platform==="win32"){let escapedMarker=commandMarker.replace(/'/g,"''");return spawnSync2("powershell.exe",["-NoProfile","-NonInteractive","-Command",`$p = Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}'; if ($p.CommandLine -and $p.CommandLine.Contains('${escapedMarker}')) { exit 0 } else { exit 1 }`],{windowsHide:!0,stdio:"ignore"}).status===0}let result=spawnSync2("ps",["-p",String(pid),"-o","command="],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return result.status===0&&result.stdout.includes(commandMarker)}catch{return!1}}function listRecords(){let records=[];for(let file2 of listRecordFiles(keyedDir(MANAGED_BROWSERS_SUBDIR))){let record2=readRecord(file2);if(!record2){removeRecord(file2);continue}let running=isManagedProcess(record2.pid,record2.userDataDir);if(!running&&(signalProcess(record2.hostPid,"SIGTERM",`--browser-id ${record2.browserId}`),removeRecord(keyedConfigFile("browsers",record2.browserId)),!record2.persistent)){removeRecord(file2),rmSync3(record2.userDataDir,{recursive:!0,force:!0});continue}records.push({record:record2,running})}return records}function listManagedBrowsers(){return listRecords().map(({record:record2,running})=>browserSummary(record2,running))}function findManagedRecord(selector){let normalized=selector.trim().toLowerCase();return listRecords().find(({record:record2})=>record2.browserId.toLowerCase()===normalized||record2.name.toLowerCase()===normalized)?.record??null}async function waitForActivePort(userDataDir){let deadline=Date.now()+LAUNCH_TIMEOUT_MS;for(;Date.now()<deadline;){let info=readDevToolsActivePort(userDataDir);if(info)return info.port;await new Promise(resolve5=>setTimeout(resolve5,100))}throw new Error(`Chrome did not expose a CDP port within ${LAUNCH_TIMEOUT_MS}ms`)}async function waitForBrowserRegistration(browserId,expectedPid){let file2=keyedConfigFile("browsers",browserId),deadline=Date.now()+LAUNCH_TIMEOUT_MS;for(;Date.now()<deadline;){if(readRecord(file2)?.pid===expectedPid&&isAlive(expectedPid))return;await new Promise(resolve5=>setTimeout(resolve5,100))}throw new Error(`Managed browser ${browserId} did not register within ${LAUNCH_TIMEOUT_MS}ms`)}function signalProcess(pid,signal,commandMarker){if(isManagedProcess(pid,commandMarker)){if(process.platform==="win32"){spawnSync2("taskkill",["/PID",String(pid),"/T","/F"],{windowsHide:!0,stdio:"ignore"});return}try{process.kill(pid,signal)}catch{}}}async function stopProcess(pid,commandMarker){signalProcess(pid,"SIGTERM",commandMarker);let deadline=Date.now()+3e3;for(;Date.now()<deadline&&isManagedProcess(pid,commandMarker);)await new Promise(resolve5=>setTimeout(resolve5,50));isManagedProcess(pid,commandMarker)&&signalProcess(pid,"SIGKILL",commandMarker)}function profileDirectory(browserId,persistent){if(!persistent)return mkdtempSync(join5(tmpdir(),"mearl-browser-"));let dir=join5(DAEMON_HOME,MANAGED_PROFILES_SUBDIR,hashKey(browserId));return mkdirSync3(dir,{recursive:!0}),dir}async function removeStoppedInstance(browserId){let file2=keyedConfigFile(MANAGED_BROWSERS_SUBDIR,browserId),record2=readRecord(file2);!record2||isManagedProcess(record2.pid,record2.userDataDir)||(await stopProcess(record2.hostPid,`--browser-id ${record2.browserId}`),removeRecord(file2),removeRecord(keyedConfigFile("browsers",record2.browserId)),record2.persistent||rmSync3(record2.userDataDir,{recursive:!0,force:!0}))}function acquireLaunchLock(browserId){let lockDir=keyedDir(MANAGED_BROWSER_LOCKS_SUBDIR),lockFile=keyedConfigFile(MANAGED_BROWSER_LOCKS_SUBDIR,browserId);mkdirSync3(lockDir,{recursive:!0});let token=`${process.pid}:${randomUUID5()}`,tryAcquire=()=>{try{return writeFileSync3(lockFile,token,{flag:"wx"}),!0}catch(error48){if(error48.code!=="EEXIST")throw error48;return!1}};if(!tryAcquire()){let observedToken="";try{observedToken=readFileSync4(lockFile,"utf-8")}catch{}let ownerPid=Number(observedToken.split(":",1)[0]);if(Number.isInteger(ownerPid)&&!isAlive(ownerPid)){let staleFile=`${lockFile}.${process.pid}.${randomUUID5()}.stale`;try{if(readFileSync4(lockFile,"utf-8")!==observedToken)throw new Error("Launch lock owner changed");if(renameSync4(lockFile,staleFile),readFileSync4(staleFile,"utf-8")===observedToken)rmSync3(staleFile,{force:!0});else try{renameSync4(staleFile,lockFile)}catch{}}catch{}}if(!tryAcquire())throw new Error(`Managed browser launch already in progress: ${browserId}`)}return()=>{try{readFileSync4(lockFile,"utf-8")===token&&rmSync3(lockFile,{force:!0})}catch{}}}async function launchManagedBrowser(input2,deps){if(input2.sessionId!==void 0)throw new Error("sessionId is only supported by the AgentBay browser provider");if(input2.reuse!==void 0&&input2.reuse!=="never"&&input2.reuse!=="prefer"&&input2.reuse!=="require")throw new Error('reuse must be "never", "prefer", or "require"');if(input2.reuse==="prefer"||input2.reuse==="require")throw new Error("reuse is currently supported only by the AgentBay browser provider");if(input2.imageId!==void 0)throw new Error("imageId is only supported by the AgentBay browser provider");let name=validateName(input2.name),browserId=managedBrowserId(name);validateTdbankSelector(input2);let cookieCopy=resolveCookieCopyPlan(input2.copyCookieDomains),copyCookieDomains=cookieCopy.domains,headless=input2.headless!==!1,persistent=input2.persistent===!0,executablePath=resolveChromeExecutable(input2.executablePath),userAgent=resolveUserAgentMode(input2.userAgentMode)==="desktop"?desktopChromeUserAgent(resolveChromeVersion(executablePath)):void 0,userDataDir=profileDirectory(browserId,persistent),logDir=keyedDir(MANAGED_BROWSERS_SUBDIR);mkdirSync3(logDir,{recursive:!0});let logPath=join5(logDir,`${hashKey(browserId)}.log`),logFd=openSync4(logPath,"a"),chromePid=0,hostPid=0,session=null,recordWritten=!1,releaseLock=null;try{if(releaseLock=acquireLaunchLock(browserId),await removeStoppedInstance(browserId),findManagedRecord(browserId))throw new Error(`Managed browser already running: ${browserId}`);let[ticket,exportedCookies]=await Promise.all([hasTdbankSelector(input2)?deps.prepareTdbankSso(input2):Promise.resolve(void 0),copyCookieDomains.length>0?deps.exportCookies(copyCookieDomains):Promise.resolve([])]),cookies=cookieCopy.select(exportedCookies),chromeArgs=buildManagedChromeArgs({userDataDir,headless,userAgent});rmSync3(join5(userDataDir,"DevToolsActivePort"),{force:!0});let chrome=spawn4(executablePath,chromeArgs,{detached:!0,stdio:["ignore","ignore",logFd],windowsHide:headless});if(await new Promise((resolve5,reject)=>{chrome.once("error",reject),chrome.once("spawn",resolve5)}),chromePid=chrome.pid??0,!chromePid)throw new Error("Chrome launched without a process id");chrome.unref();let cdpPort=await waitForActivePort(userDataDir);session=new CdpSession({port:cdpPort,userDataDir});let copiedCookieCount=await cdpImportCookies(session,cookies),account;if(ticket){let login=await cdpConsumeTdbankSso(session,ticket.ssoUrl,ticket.account.loginId);account={accountId:ticket.account.accountId,loginId:ticket.account.loginId,nickname:login.nickname}}input2.url&&await(await session.getBrowserClient()).sendCommand("Target.createTarget",{url:input2.url,background:headless}),session.close(),session=null;let host=spawn4(process.execPath,[deps.nativeHostScript,"--daemon","--cdp-port",String(cdpPort),"--cdp-user-data-dir",userDataDir,"--browser-id",browserId,"--browser-name",name,...headless?["--browser-headless"]:[]],{detached:!0,stdio:"ignore",windowsHide:!0});if(await new Promise((resolve5,reject)=>{host.once("error",reject),host.once("spawn",resolve5)}),hostPid=host.pid??0,!hostPid)throw new Error("Native host launched without a process id");host.unref();let record2={pid:chromePid,hostPid,browserId,name,headless,persistent,userDataDir,executablePath,cdpPort,createdAt:new Date().toISOString(),account,...copyCookieDomains.length>0?{copiedCookies:{domains:copyCookieDomains,count:copiedCookieCount}}:{}};return writeRecord(keyedConfigFile(MANAGED_BROWSERS_SUBDIR,browserId),record2),recordWritten=!0,await waitForBrowserRegistration(browserId,hostPid),deps.log(`managed browser launched: ${browserId}, chrome=${chromePid}, host=${hostPid}`),{...browserSummary(record2,!0),created:!0,reused:!1}}catch(error48){throw session?.close(),hostPid&&await stopProcess(hostPid,`--browser-id ${browserId}`),chromePid&&await stopProcess(chromePid,userDataDir),recordWritten&&removeRecord(keyedConfigFile(MANAGED_BROWSERS_SUBDIR,browserId)),persistent||rmSync3(userDataDir,{recursive:!0,force:!0}),error48}finally{releaseLock?.(),closeSync4(logFd)}}async function closeManagedBrowser(selector,options={}){let record2=findManagedRecord(selector);if(!record2)throw new Error(`Managed browser not found: ${selector}`);let recordFile=keyedConfigFile(MANAGED_BROWSERS_SUBDIR,record2.browserId);await stopProcess(record2.pid,record2.userDataDir);let closingOwnHost=record2.hostPid===process.pid;closingOwnHost||await stopProcess(record2.hostPid,`--browser-id ${record2.browserId}`),removeRecord(keyedConfigFile("browsers",record2.browserId));let deleteProfile=options.deleteProfile===!0||!record2.persistent,stoppedRecord=stoppedPersistentBrowserRecord(record2,deleteProfile);return stoppedRecord?writeRecord(recordFile,stoppedRecord):(removeRecord(recordFile),rmSync3(record2.userDataDir,{recursive:!0,force:!0})),closingOwnHost&&setTimeout(()=>process.kill(process.pid,"SIGTERM"),250).unref(),{browserId:record2.browserId,closed:!0,profileDeleted:deleteProfile}}function positiveIntegerMinutes(value,name,fallback){if(value===void 0||!value.trim())return fallback;let minutes=Number(value);if(!Number.isInteger(minutes)||minutes<=0)throw new Error(`${name} must be a positive integer in minutes`);return minutes}function resolveAgentBayLifecycleConfig(env=process.env){let idleReleaseTimeout=positiveIntegerMinutes(env.MEARL_AGENTBAY_IDLE_RELEASE_MINUTES,"MEARL_AGENTBAY_IDLE_RELEASE_MINUTES",30),maxRuntime=positiveIntegerMinutes(env.MEARL_AGENTBAY_MAX_RUNTIME_MINUTES,"MEARL_AGENTBAY_MAX_RUNTIME_MINUTES",120);if(idleReleaseTimeout<3)throw new Error("MEARL_AGENTBAY_IDLE_RELEASE_MINUTES must be at least 3");if(maxRuntime<idleReleaseTimeout)throw new Error("MEARL_AGENTBAY_MAX_RUNTIME_MINUTES must be greater than or equal to MEARL_AGENTBAY_IDLE_RELEASE_MINUTES");return{idleReleaseTimeout,maxRuntime}}var AgentBaySessionWatchdog=class{idleTimeoutMs;checkIntervalMs;now;keepAlive;close;log;activeRequests=0;lastActivityAt;timer=null;checking=!1;closing=!1;stopped=!1;constructor(options){if(!Number.isFinite(options.idleTimeoutMs)||options.idleTimeoutMs<=0)throw new Error("AgentBay idle timeout must be positive");if(this.idleTimeoutMs=options.idleTimeoutMs,this.checkIntervalMs=options.checkIntervalMs??6e4,!Number.isFinite(this.checkIntervalMs)||this.checkIntervalMs<=0)throw new Error("AgentBay lifecycle check interval must be positive");this.now=options.now??Date.now,this.keepAlive=options.keepAlive,this.close=options.close,this.log=options.log,this.lastActivityAt=this.now()}start(){this.timer||this.stopped||(this.timer=setInterval(()=>void this.checkNow(),this.checkIntervalMs),this.timer.unref())}stop(){this.stopped=!0,this.timer&&(clearInterval(this.timer),this.timer=null)}beginActivity(){return this.stopped||this.closing?!1:(this.activeRequests+=1,this.lastActivityAt=this.now(),!0)}endActivity(){this.activeRequests>0&&(this.activeRequests-=1),this.lastActivityAt=this.now()}async checkNow(){if(!(this.stopped||this.checking||this.closing)){this.checking=!0;try{let idleForMs=this.now()-this.lastActivityAt;if(this.activeRequests>0||idleForMs<this.idleTimeoutMs){try{await this.keepAlive()}catch(error48){this.log("AgentBay keepalive failed:",error48 instanceof Error?error48.message:String(error48))}return}this.closing=!0,this.log(`AgentBay browser reached the idle timeout after ${idleForMs}ms; closing`);try{await this.close()}catch(error48){this.closing=!1,this.log("AgentBay idle close failed:",error48 instanceof Error?error48.message:String(error48))}}finally{this.checking=!1}}}};var AGENTBAY_BROWSERS_SUBDIR="agentbay-browsers",DEFAULT_AGENTBAY_IMAGE_ID="imgc-0aae4rgl8kvagdv1j",sdkPromise=null;async function loadSdk(){return sdkPromise??=Promise.resolve().then(()=>(init_agentbay_sdk(),agentbay_sdk_exports)),sdkPromise}async function createClient(apiKey){let{AgentBay:AgentBay2}=await loadSdk();return new AgentBay2({apiKey})}function agentBayBrowserId(name){return`managed:agentbay:${name.toLocaleLowerCase("en-US")}`}function agentBaySessionBrowserId(sessionId){return`managed:agentbay:session:${sessionId}`}function envValue(text,key){for(let line of text.split(/\r?\n/)){let match=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);if(!match||match[1]!==key)continue;let value=(match[2]??"").trim();return value.length>=2&&(value.startsWith('"')&&value.endsWith('"')||value.startsWith("'")&&value.endsWith("'"))?value=value.slice(1,-1):value=value.replace(/\s+#.*$/,"").trim(),value||void 0}}function envFilesUpward(start){let files=[],current=resolve3(start);for(;;){files.push(join8(current,".env"));let parent=dirname6(current);if(parent===current||current===parse(current).root)break;current=parent}return files}function resolveAgentBayApiKey(){let inherited=process.env.AGENTBAY_KEY?.trim()||process.env.AGENTBAY_API_KEY?.trim();if(inherited)return inherited;let moduleDir=dirname6(fileURLToPath2(import.meta.url)),candidates=[...process.env.MEARL_ENV_FILE?[resolve3(process.env.MEARL_ENV_FILE)]:[],...envFilesUpward(process.cwd()),...envFilesUpward(moduleDir),join8(homedir2(),".mearl",".env")];for(let file2 of new Set(candidates))if(existsSync11(file2))try{let text=readFileSync8(file2,"utf8"),value=envValue(text,"AGENTBAY_KEY")??envValue(text,"AGENTBAY_API_KEY");if(value)return value}catch{}throw new Error("AgentBay API key not found. Set AGENTBAY_KEY in the environment, project .env, or ~/.mearl/.env.")}function validateAgentBayInput(input2){if(input2.headless===!0)throw new Error("headless=true is not supported by the AgentBay browser provider");if(input2.executablePath)throw new Error("executablePath is only supported by the local browser provider");if(input2.accountId!==void 0||input2.havanaId!==void 0||input2.site!==void 0||typeof input2.query=="string"&&input2.query.trim())throw new Error("TDBank login parameters are only supported by the local browser provider")}function resolveAgentBaySessionId(value){let sessionId=typeof value=="string"?value.trim():"";if(!sessionId||sessionId.length>256||!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(sessionId))throw new Error("sessionId must be a valid AgentBay session ID");return sessionId}function validateAgentBayAttachmentInput(input2){let unsupported=[["reuse",input2.reuse],["imageId",input2.imageId],["headless",input2.headless],["userAgentMode",input2.userAgentMode],["persistent",input2.persistent],["executablePath",input2.executablePath],["accountId",input2.accountId],["havanaId",input2.havanaId],["site",input2.site],["query",input2.query],["tabId",input2.tabId]].find(([,value])=>value!==void 0);if(unsupported)throw new Error(`${unsupported[0]} cannot be used when attaching by AgentBay sessionId`)}function attachmentName(sessionId,value){if(value!==void 0)return validateName(value);let suffix=sessionId.slice(-12);return validateName(`agentbay-${suffix}`)}function resolveReuseMode(value){if(value===void 0)return"never";if(value==="never"||value==="prefer"||value==="require")return value;throw new Error('reuse must be "never", "prefer", or "require"')}function validateReusableAgentBayConfiguration(input2,record2){if(input2.imageId!==void 0&&resolveAgentBayImageId(input2.imageId)!==record2.imageId)throw new Error(`Cannot change imageId while reusing AgentBay browser: ${record2.browserId}`);if(input2.persistent!==void 0&&input2.persistent!==(record2.persistent===!0))throw new Error(`Cannot change persistent while reusing AgentBay browser: ${record2.browserId}`);if(input2.userAgentMode!==void 0&&record2.userAgentMode!==void 0&&input2.userAgentMode!==record2.userAgentMode)throw new Error(`Cannot change userAgentMode while reusing AgentBay browser: ${record2.browserId}`)}function resolveAgentBayImageId(value){if(value===void 0)return DEFAULT_AGENTBAY_IMAGE_ID;let imageId=typeof value=="string"?value.trim():"";if(!imageId||imageId.length>128||!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(imageId))throw new Error("imageId must be a valid AgentBay image alias or image ID");return imageId}function agentBayContextName(browserId){return`mearl-browser-${hashKey(browserId)}`}function normalizeDesktopUserAgent(value){let userAgent=typeof value=="string"?value.trim():"";if(!userAgent)throw new Error("Could not determine the control browser user agent");return userAgent.replace(/\bHeadlessChrome\//g,"Chrome/")}function normalizeAgentBayAccessUrl(value){let candidate=typeof value=="string"?value.trim():"";if(candidate)try{let url2=new URL(candidate);return url2.protocol==="https:"||url2.protocol==="http:"?url2.toString():void 0}catch{return}}function browserSummary2(record2,running){let sessionMode=record2.sessionMode==="attached"?"attached":"owned";return{browserId:record2.browserId,name:record2.name,provider:"agentbay",headless:!1,persistent:record2.persistent===!0,agentbaySessionId:record2.sessionId,agentbaySessionMode:sessionMode,...record2.imageId?{agentbayImageId:record2.imageId}:{},...record2.contextId?{agentbayContextId:record2.contextId}:{},...record2.contextName?{agentbayContextName:record2.contextName}:{},createdAt:record2.createdAt,...record2.copiedCookies?{copiedCookies:record2.copiedCookies}:{},running}}function listRecords2(){let records=[];for(let file2 of listRecordFiles(keyedDir(AGENTBAY_BROWSERS_SUBDIR))){let stored=readRecord(file2);if(!stored){removeRecord(file2);continue}let{accessUrl:legacyAccessUrl,...record2}=stored;legacyAccessUrl!==void 0&&writeRecord(file2,record2);let running=isManagedProcess(record2.pid,`--browser-id ${record2.browserId}`);running||removeRecord(keyedConfigFile("browsers",record2.browserId)),records.push({record:record2,running})}return records}function findRecordWithStatus(selector){let normalized=selector.trim().toLowerCase(),records=listRecords2();return records.find(({record:record2})=>record2.browserId.toLowerCase()===normalized||record2.sessionId.toLowerCase()===normalized)??records.find(({record:record2})=>record2.name.toLowerCase()===normalized)??null}function findRecord(selector){return findRecordWithStatus(selector)?.record??null}function listAgentBayBrowsers(){return listRecords2().map(({record:record2,running})=>browserSummary2(record2,running))}async function requireSession(sessionId,apiKey){let agentBay=await createClient(apiKey);return requireSessionFromClient(agentBay,sessionId)}async function requireSessionFromClient(agentBay,sessionId){let result=await agentBay.get(sessionId);if(!result.success||!result.session)throw new Error(result.errorMessage||`AgentBay session not found: ${sessionId}`);return result.session}async function getAgentBaySession(sessionId,dependencies={}){let apiKey=(dependencies.resolveApiKey??resolveAgentBayApiKey)(),agentBay=dependencies.createAgentBayClient?await dependencies.createAgentBayClient(apiKey):await createClient(apiKey);return requireSessionFromClient(agentBay,sessionId)}async function getAgentBayAccessUrl(sessionId,dependencies={}){let apiKey=(dependencies.resolveApiKey??resolveAgentBayApiKey)(),agentBay=dependencies.createAgentBayClient?await dependencies.createAgentBayClient(apiKey):await createClient(apiKey),session=await requireSessionFromClient(agentBay,sessionId);if(!session.info)throw new Error("The installed AgentBay SDK does not support live session information");let result=await session.info();if(result.success===!1)throw new Error(result.errorMessage||`AgentBay session info failed: ${sessionId}`);let data=result.data&&typeof result.data=="object"?result.data:null,accessUrl=normalizeAgentBayAccessUrl(data&&"resourceUrl"in data?data.resourceUrl:void 0);if(!accessUrl)throw new Error(`AgentBay session did not return a browser access URL: ${sessionId}`);return accessUrl}async function getManagedAgentBayAccessUrl(selector,dependencies={}){let matched=dependencies.findBrowserRecord?dependencies.findBrowserRecord(selector):findRecordWithStatus(selector);if(!matched)throw new Error(`AgentBay browser not found: ${selector}`);if(!matched.running)throw new Error(`AgentBay browser is not running: ${selector}`);return getAgentBayAccessUrl(matched.record.sessionId,dependencies)}async function resolvePersistentContext(agentBay,browserId){if(!agentBay.context)throw new Error("The installed AgentBay SDK does not support persistent browser contexts");let name=agentBayContextName(browserId),result=await agentBay.context.get(name,!0);if(!result.success||!result.context?.id)throw new Error(result.errorMessage||`Failed to create AgentBay browser context: ${name}`);return{id:result.context.id,name:result.context.name||name}}async function resolveAgentBayEndpoint(sessionId){let apiKey=resolveAgentBayApiKey(),{AgentBay:AgentBay2,GetCdpLinkRequest:GetCdpLinkRequest2}=await loadSdk(),response=await new AgentBay2({apiKey}).client.getCdpLink(new GetCdpLinkRequest2({authorization:`Bearer ${apiKey}`,sessionId})),endpoint=response.body?.success?response.body.data?.url:void 0;if(!endpoint)throw new Error(response.body?.message||`Failed to get AgentBay CDP link: ${sessionId}`);let url2=new URL(endpoint);if(url2.protocol!=="ws:"&&url2.protocol!=="wss:")throw new Error(`AgentBay returned an unsupported CDP endpoint: ${url2.protocol}`);return url2.toString()}async function keepAgentBaySessionAlive(sessionId){let result=await(await requireSession(sessionId,resolveAgentBayApiKey())).keepAlive();if(result.success===!1)throw new Error(result.errorMessage||"AgentBay keepalive failed")}async function configureAgentBayBrowserSession(session,input2,cookies,connectCdp=url2=>CdpClient.connect(url2),endpointUrl){let endpoint=endpointUrl??await session.browser.getEndpointUrl(),cdp=await connectCdp(endpoint);try{await cdp.sendCommand("Browser.getVersion",{},1e4);let copiedCookieCount=await cdpImportCookiesWithClient(cdp,cookies);return input2.url&&await cdp.sendCommand("Target.createTarget",{url:input2.url,background:!1}),copiedCookieCount}finally{cdp.close()}}async function initializeAgentBayBrowserSession(session,input2,cookies,options={}){if(!await session.browser.initializeAsync(options.userAgent?{userAgent:options.userAgent}:{}))throw new Error("AgentBay browser initialization failed");return configureAgentBayBrowserSession(session,input2,cookies,options.connectCdp)}async function reuseAgentBayBrowserSession(session,input2,cookies,options={}){return configureAgentBayBrowserSession(session,input2,cookies,options.connectCdp,options.endpointUrl)}function removeAgentBayRecord(record2){removeRecord(keyedConfigFile(AGENTBAY_BROWSERS_SUBDIR,record2.browserId)),removeRecord(keyedConfigFile("browsers",record2.browserId))}async function spawnAgentBayNativeHost(deps,args){if(deps.spawnNativeHost)return deps.spawnNativeHost(args);let host=spawn6(process.execPath,[deps.nativeHostScript,...args],{detached:!0,stdio:"ignore",windowsHide:!0});await new Promise((resolveSpawn,rejectSpawn)=>{host.once("error",rejectSpawn),host.once("spawn",resolveSpawn)});let hostPid=host.pid??0;if(!hostPid)throw new Error("AgentBay native host launched without a process id");return host.unref(),hostPid}function nativeHostArgs(record2,idleReleaseMinutes){return["--daemon","--agentbay-session-id",record2.sessionId,...record2.sessionMode==="attached"?["--agentbay-attachment"]:[],"--browser-id",record2.browserId,"--browser-name",record2.name,...record2.sessionMode==="attached"?[]:["--agentbay-idle-release-minutes",String(idleReleaseMinutes)]]}async function attachAgentBayBrowser(input2,deps){validateAgentBayInput(input2),validateAgentBayAttachmentInput(input2);let sessionId=resolveAgentBaySessionId(input2.sessionId),browserId=agentBaySessionBrowserId(sessionId),requestedName=attachmentName(sessionId,input2.name),cookieCopy=resolveCookieCopyPlan(input2.copyCookieDomains),copyCookieDomains=cookieCopy.domains,apiKey=(deps.resolveApiKey??resolveAgentBayApiKey)(),lifecycle=resolveAgentBayLifecycleConfig(),releaseLock=acquireLaunchLock(browserId),persistBrowserRecord=deps.persistBrowserRecord??(record2=>writeRecord(keyedConfigFile(AGENTBAY_BROWSERS_SUBDIR,record2.browserId),record2)),removeBrowserRecord=deps.removeBrowserRecord??removeAgentBayRecord,findBrowserRecord=deps.findBrowserRecord??findRecordWithStatus,hostPid=0,recordWritten=!1,activeRecord,previousRecord;try{let identityRecord=findBrowserRecord(browserId)??findBrowserRecord(sessionId),namedRecord=findBrowserRecord(requestedName);if(identityRecord&&identityRecord.record.sessionId!==sessionId)throw new Error(`AgentBay browser identity collision: ${browserId}`);if(namedRecord&&namedRecord.record.sessionId!==sessionId)throw new Error(`AgentBay browser name is already used by another session: ${requestedName}. Choose a unique name or omit it.`);let existing=identityRecord??namedRecord,ownedRecord=[identityRecord,namedRecord].find(found=>found&&found.record.sessionMode!=="attached");if(ownedRecord)throw new Error(`AgentBay session ${sessionId} is already lifecycle-owned by this host as ${ownedRecord.record.browserId}. Reuse it by name with reuse=require instead of attaching by sessionId.`);previousRecord=existing?.record;let exportedCookies=copyCookieDomains.length>0?await deps.exportCookies(copyCookieDomains):[],cookies=cookieCopy.select(exportedCookies),agentBay=await(deps.createAgentBayClient??createClient)(apiKey),session=await requireSessionFromClient(agentBay,sessionId),endpointUrl=await(deps.resolveSessionEndpoint??resolveAgentBayEndpoint)(sessionId),copiedCookieCount=await reuseAgentBayBrowserSession(session,input2,cookies,{connectCdp:deps.connectCdp,endpointUrl});if(existing?.running){let record2={...existing.record,...copyCookieDomains.length>0?{copiedCookies:{domains:copyCookieDomains,count:copiedCookieCount}}:{}};return copyCookieDomains.length>0&&persistBrowserRecord(record2),{...browserSummary2(record2,!0),created:!1,reused:!0,attached:record2.sessionMode==="attached"}}return activeRecord=existing?{...existing.record,pid:0}:{pid:0,browserId,name:requestedName,sessionId,sessionMode:"attached",persistent:!1,createdAt:new Date().toISOString()},copyCookieDomains.length>0&&(activeRecord.copiedCookies={domains:copyCookieDomains,count:copiedCookieCount}),hostPid=await spawnAgentBayNativeHost(deps,nativeHostArgs(activeRecord,lifecycle.idleReleaseTimeout)),activeRecord.pid=hostPid,persistBrowserRecord(activeRecord),recordWritten=!0,await(deps.waitForBrowserRegistration??waitForBrowserRegistration)(activeRecord.browserId,hostPid),deps.log(`AgentBay session ${activeRecord.sessionMode==="attached"?"attached":"reconnected"}: ${sessionId}, host=${hostPid}`),{...browserSummary2(activeRecord,!0),created:!1,reused:!0,attached:activeRecord.sessionMode==="attached"}}catch(error48){throw hostPid&&await stopProcess(hostPid,`--browser-id ${activeRecord?.browserId??browserId}`),recordWritten&&activeRecord&&(previousRecord?persistBrowserRecord(previousRecord):removeBrowserRecord(activeRecord)),error48}finally{releaseLock()}}async function launchAgentBayBrowser(input2,deps){if(input2.sessionId!==void 0)return attachAgentBayBrowser(input2,deps);let name=validateName(input2.name),browserId=agentBayBrowserId(name);validateAgentBayInput(input2);let reuseMode=resolveReuseMode(input2.reuse),imageId=resolveAgentBayImageId(input2.imageId),persistent=input2.persistent===!0,userAgentMode=resolveUserAgentMode(input2.userAgentMode),cookieCopy=resolveCookieCopyPlan(input2.copyCookieDomains),copyCookieDomains=cookieCopy.domains,apiKey=(deps.resolveApiKey??resolveAgentBayApiKey)(),lifecycle=resolveAgentBayLifecycleConfig(),releaseLock=acquireLaunchLock(browserId),persistBrowserRecord=deps.persistBrowserRecord??(record2=>writeRecord(keyedConfigFile(AGENTBAY_BROWSERS_SUBDIR,record2.browserId),record2)),removeBrowserRecord=deps.removeBrowserRecord??removeAgentBayRecord,findBrowserRecord=deps.findBrowserRecord??findRecordWithStatus,session=null,context,hostPid=0,recordWritten=!1;try{let existing=findBrowserRecord(browserId);if(existing?.record.sessionMode==="attached"){if(existing.running)throw new Error(`AgentBay browser name ${name} belongs to a sessionId attachment. Reuse session ${existing.record.sessionId} by sessionId, or choose a unique name.`);removeBrowserRecord(existing.record),deps.log(`Stopped AgentBay attachment record cleaned before named launch: ${browserId}`),existing=null}if(existing){if(!existing.running&&reuseMode==="require")throw new Error(`AgentBay browser ${browserId} has status=stopped and reuse=require cannot create a replacement. Retry with reuse=prefer, or run browser_close to clean the stopped record.`);if(existing.running){if(reuseMode==="never")throw new Error(`AgentBay browser already exists with status=running: ${browserId}. Retry with reuse=prefer or reuse=require to reuse it.`);validateReusableAgentBayConfiguration(input2,existing.record);let exportedCookies2=copyCookieDomains.length>0?await deps.exportCookies(copyCookieDomains):[],cookies2=cookieCopy.select(exportedCookies2),agentBay2=await(deps.createAgentBayClient??createClient)(apiKey),existingSession=await requireSessionFromClient(agentBay2,existing.record.sessionId),endpointUrl=await(deps.resolveSessionEndpoint??resolveAgentBayEndpoint)(existing.record.sessionId),copiedCookieCount2=await reuseAgentBayBrowserSession(existingSession,input2,cookies2,{connectCdp:deps.connectCdp,endpointUrl}),record3={...existing.record,...copyCookieDomains.length>0?{copiedCookies:{domains:copyCookieDomains,count:copiedCookieCount2}}:{}};return copyCookieDomains.length>0&&persistBrowserRecord(record3),deps.log(`AgentBay browser reused: ${browserId}, host=${record3.pid}`),{...browserSummary2(record3,!0),created:!1,reused:!0,attached:!1}}else{let agentBay2=await(deps.createAgentBayClient??createClient)(apiKey);try{await releaseAgentBayBrowserResources(existing.record,agentBay2,{persistRecord:persistBrowserRecord})}catch(error48){throw new Error(`Failed to clean stopped AgentBay browser ${browserId} before launch: ${error48 instanceof Error?error48.message:String(error48)}. Run browser_close for ${browserId} and retry.`,{cause:error48})}await stopProcess(existing.record.pid,`--browser-id ${existing.record.browserId}`),removeBrowserRecord(existing.record),deps.log(`AgentBay stopped browser record cleaned before launch: ${browserId}`)}}if(reuseMode==="require")throw new Error(`AgentBay browser is not running and reuse=require: ${browserId}`);let[exportedCookies,userAgent]=await Promise.all([copyCookieDomains.length>0?deps.exportCookies(copyCookieDomains):Promise.resolve([]),userAgentMode==="desktop"?deps.getBrowserUserAgent().then(normalizeDesktopUserAgent):Promise.resolve(void 0)]),cookies=cookieCopy.select(exportedCookies),agentBay=await(deps.createAgentBayClient??createClient)(apiKey);context=persistent?await resolvePersistentContext(agentBay,browserId):void 0;let{LifecyclePolicy:LifecyclePolicy2}=await loadSdk(),created=await agentBay.create({imageId,framework:"mearl",lifecyclePolicy:new LifecyclePolicy2(lifecycle),...context?{browserContext:{contextId:context.id,autoUpload:!0,syncMode:"standard"}}:{}});if(!created.success||!created.session)throw new Error(created.errorMessage||"AgentBay session creation failed");session=created.session;let copiedCookieCount=await initializeAgentBayBrowserSession(session,input2,cookies,{userAgent,connectCdp:deps.connectCdp}),record2={pid:0,browserId,name,sessionId:session.sessionId,sessionMode:"owned",imageId,userAgentMode,persistent,...context?{contextId:context.id,contextName:context.name}:{},createdAt:new Date().toISOString(),...copyCookieDomains.length>0?{copiedCookies:{domains:copyCookieDomains,count:copiedCookieCount}}:{}};return hostPid=await spawnAgentBayNativeHost(deps,nativeHostArgs(record2,lifecycle.idleReleaseTimeout)),record2.pid=hostPid,persistBrowserRecord(record2),recordWritten=!0,await(deps.waitForBrowserRegistration??waitForBrowserRegistration)(browserId,hostPid),deps.log(`AgentBay browser launched: ${browserId}, host=${hostPid}`),{...browserSummary2(record2,!0),created:!0,reused:!1,attached:!1}}catch(error48){if(hostPid&&await stopProcess(hostPid,`--browser-id ${browserId}`),recordWritten&&(removeRecord(keyedConfigFile(AGENTBAY_BROWSERS_SUBDIR,browserId)),removeRecord(keyedConfigFile("browsers",browserId))),session){let cleanupError;try{let deleted=await session.delete(!1);deleted.success||(cleanupError=new Error(deleted.errorMessage||"AgentBay session deletion failed"))}catch(deleteError){cleanupError=deleteError}if(cleanupError){let recoveryRecord={pid:hostPid,browserId,name,sessionId:session.sessionId,sessionMode:"owned",imageId,userAgentMode,persistent,...context?{contextId:context.id,contextName:context.name}:{},createdAt:new Date().toISOString()},recoverySaved=!1,recoveryError;try{persistBrowserRecord(recoveryRecord),recoverySaved=!0}catch(writeError){recoveryError=writeError}throw deps.log(`AgentBay launch cleanup failed for ${session.sessionId}:`,cleanupError instanceof Error?cleanupError.message:String(cleanupError)),recoveryError&&deps.log(`AgentBay recovery metadata could not be saved for ${session.sessionId}:`,recoveryError instanceof Error?recoveryError.message:String(recoveryError)),new AggregateError(recoveryError?[error48,cleanupError,recoveryError]:[error48,cleanupError],`${error48 instanceof Error?error48.message:String(error48)}; `+(recoverySaved?"AgentBay session cleanup failed and recovery metadata was retained for browser_close":`AgentBay session cleanup failed; session ${session.sessionId} may require manual deletion`),{cause:error48})}}throw error48}finally{releaseLock()}}function isMissingSessionError(error48){let message=error48 instanceof Error?error48.message:String(error48);return/not[ -]?found|does not exist|already deleted|invalid session/i.test(message)}async function releaseAgentBayBrowserResources(record2,agentBay,options={}){if(record2.sessionMode==="attached")throw new Error(`AgentBay browser ${record2.browserId} is a local attachment. Use browser_release to detach it without closing session ${record2.sessionId}.`);let deleteContext=record2.persistent===!0&&options.deleteProfile===!0,syncContext=record2.persistent===!0&&!deleteContext,contextSynced=!!record2.contextSyncedAt,session;try{session=await requireSessionFromClient(agentBay,record2.sessionId)}catch(error48){if(!isMissingSessionError(error48))throw error48}if(session){if(syncContext&&!contextSynced){if(!session.callMcpTool)throw new Error("The installed AgentBay SDK cannot stop the browser before context sync");let stopped=await session.callMcpTool("stopChrome",{},!1);if(stopped.success===!1)throw new Error(stopped.errorMessage||"AgentBay browser shutdown failed");if(!session.context)throw new Error("The installed AgentBay SDK cannot synchronize browser context state");let synced=await session.context.sync();if(!synced.success)throw new Error(synced.errorMessage||"AgentBay browser context sync failed");contextSynced=!0,record2.contextSyncedAt=new Date().toISOString(),options.persistRecord?.(record2)}try{let result=await session.delete(!1);if(!result.success)throw new Error(result.errorMessage||"AgentBay session deletion failed")}catch(error48){if(!isMissingSessionError(error48))throw error48}}if(deleteContext){if(!record2.contextId||!record2.contextName||!agentBay.context)throw new Error("AgentBay browser context metadata is unavailable for profile deletion");let result=await agentBay.context.delete({id:record2.contextId,name:record2.contextName});if(!result.success)throw new Error(result.errorMessage||"AgentBay context deletion failed")}return{sessionDeleted:!0,...syncContext?{contextSynced}:{},...deleteContext?{contextDeleted:!0}:{}}}function detachAgentBayBrowser(selector,expectedPid=process.pid){let found=findRecordWithStatus(selector);return!found||found.record.sessionMode!=="attached"||found.record.pid!==expectedPid?{detached:!1}:(removeAgentBayRecord(found.record),{detached:!0,sessionId:found.record.sessionId})}async function closeAgentBayBrowser(selector,options={}){let record2=findRecord(selector);if(!record2)throw new Error(`AgentBay browser not found: ${selector}`);let releaseLock=acquireLaunchLock(record2.browserId);try{if(record2=findRecord(record2.browserId),!record2)throw new Error(`AgentBay browser not found: ${selector}`);if(record2.sessionMode==="attached")throw new Error(`AgentBay browser ${record2.browserId} is attached to session ${record2.sessionId}. Use browser_release to detach this host, or browser_close from the host that created the session.`);let agentBay=await createClient(resolveAgentBayApiKey()),released=await releaseAgentBayBrowserResources(record2,agentBay,{...options,persistRecord:updatedRecord=>writeRecord(keyedConfigFile(AGENTBAY_BROWSERS_SUBDIR,updatedRecord.browserId),updatedRecord)}),closingOwnHost=record2.pid===process.pid;closingOwnHost||await stopProcess(record2.pid,`--browser-id ${record2.browserId}`),removeRecord(keyedConfigFile("browsers",record2.browserId));let stoppedRecord=stoppedPersistentBrowserRecord(record2,options.deleteProfile===!0);return stoppedRecord?writeRecord(keyedConfigFile(AGENTBAY_BROWSERS_SUBDIR,record2.browserId),stoppedRecord):removeRecord(keyedConfigFile(AGENTBAY_BROWSERS_SUBDIR,record2.browserId)),closingOwnHost&&setTimeout(()=>process.kill(process.pid,"SIGTERM"),250).unref(),{browserId:record2.browserId,provider:"agentbay",closed:!0,...released,...record2.persistent===!0?{profileDeleted:options.deleteProfile===!0}:{profileDeleted:!0}}}finally{releaseLock()}}import{randomUUID as randomUUID7}from"node:crypto";import{basename as basename3,posix}from"node:path";var AGENTBAY_FILE_UPLOAD_WAIT_SECONDS=120;function pageUploadTargets(action,data){return action==="page_upload"?[{data}]:action!=="run_actions"||!Array.isArray(data?.actions)?[]:data.actions.flatMap((step,index)=>step?.action==="page_upload"?[{data:step.data,step:index}]:[])}function validateFilePaths(target){let filePaths=target.data?.filePaths;if(!Array.isArray(filePaths)||filePaths.length===0||filePaths.some(filePath=>typeof filePath!="string"||filePath.length===0)){let prefix=target.step===void 0?"":`Step ${target.step}: `;throw new Error(`${prefix}Invalid filePaths: must be a non-empty array of file path strings`)}return filePaths}function uploadError(result){return result.errorMessage??result.error_message??result.error??"unknown error"}async function stageAgentBayPageUploads(sessionId,action,data,dependencies={}){let targets=pageUploadTargets(action,data);if(targets.length===0)return data;let targetFilePaths=targets.map(target=>validateFilePaths(target)),fileSystem=(await(dependencies.getSession??getAgentBaySession)(sessionId)).fileSystem;if(!fileSystem)throw new Error("The installed AgentBay SDK does not support session file transfer");let contextPath=await fileSystem.getFileTransferContextPath();if(!contextPath)throw new Error(`AgentBay file transfer context is unavailable for session ${sessionId}`);let createTransferId=dependencies.createTransferId??randomUUID7,stagedPaths=await Promise.all(targetFilePaths.map(filePaths=>Promise.all(filePaths.map(async localPath=>{let remoteDirectory=posix.join(contextPath,createTransferId()),directoryResult=await fileSystem.createDirectory(remoteDirectory);if(directoryResult?.success===!1)throw new Error(`Failed to prepare AgentBay upload for ${basename3(localPath)}: ${uploadError(directoryResult)}`);let remotePath=posix.join(remoteDirectory,basename3(localPath)),result=await fileSystem.uploadFile(localPath,remotePath,{wait:!0,waitTimeout:AGENTBAY_FILE_UPLOAD_WAIT_SECONDS});if(result?.success!==!0)throw new Error(`Failed to upload ${basename3(localPath)} to AgentBay: ${uploadError(result)}`);return remotePath}))));if(action==="page_upload")return{...data,filePaths:stagedPaths[0]};let runActions=data,targetIndex=0;return{...runActions,actions:runActions.actions.map(step=>{if(step.action!=="page_upload")return step;let filePaths=stagedPaths[targetIndex++];return{...step,data:{...step.data,filePaths}}})}}var BROWSERS_SUBDIR="browsers",STALE_RECORD_TTL_MS=5*6e4,FOCUS_WRITE_THROTTLE_MS=1e3,identity=null,logFn2=()=>{};function initBrowserRegistry(deps){logFn2=deps.log}function recordFileFor2(browserId){return keyedConfigFile(BROWSERS_SUBDIR,browserId)}function ownsRecord(browserId){let existing=readRecord(recordFileFor2(browserId));return!existing||existing.pid===process.pid||!isAlive(existing.pid)}function persist(patch){if(!identity)return;let file2=recordFileFor2(identity.browserId);if(!ownsRecord(identity.browserId))return;let previous=readRecord(file2),record2={pid:process.pid,browserId:identity.browserId,socketPath:identity.socketPath,browserName:identity.browserName,nativeHostVersion:identity.nativeHostVersion,transport:identity.transport,startedAt:identity.startedAt,lastFocusedAt:previous?.lastFocusedAt,extensionVersion:previous?.extensionVersion,...patch,updatedAt:Date.now()};try{writeRecord(file2,record2)}catch(error48){logFn2("browser-registry: failed to write record:",String(error48))}}function registerBrowser(info){let startedAt=identity?.startedAt??new Date().toISOString();identity={browserId:info.browserId,socketPath:info.socketPath,browserName:info.browserName,nativeHostVersion:info.nativeHostVersion,transport:info.transport,startedAt};let previous=readRecord(recordFileFor2(info.browserId));persist({lastFocusedAt:previous?.lastFocusedAt??info.lastFocusedAt??Date.now(),extensionVersion:info.extensionVersion}),logFn2(`browser-registry: registered ${info.browserName} (${info.browserId})`)}var lastFocusWriteAt=0,focusFlushTimer=null;function writeFocusNow(){lastFocusWriteAt=Date.now(),persist({lastFocusedAt:lastFocusWriteAt})}function touchFocus(){if(!identity)return;let elapsed=Date.now()-lastFocusWriteAt;if(elapsed>=FOCUS_WRITE_THROTTLE_MS){writeFocusNow();return}focusFlushTimer||(focusFlushTimer=setTimeout(()=>{focusFlushTimer=null,writeFocusNow()},FOCUS_WRITE_THROTTLE_MS-elapsed),focusFlushTimer.unref())}function unregisterBrowser(){if(focusFlushTimer&&(clearTimeout(focusFlushTimer),focusFlushTimer=null),!identity)return;let file2=recordFileFor2(identity.browserId),existing=readRecord(file2);existing&&existing.pid!==process.pid||removeRecord(file2)}function pruneDeadBrowsers(){let now=Date.now();for(let file2 of listRecordFiles(keyedDir(BROWSERS_SUBDIR))){let rec=readRecord(file2);if(!rec){removeRecord(file2);continue}isAlive(rec.pid)||now-(rec.updatedAt??0)>STALE_RECORD_TTL_MS&&removeRecord(file2)}}function listRegisteredBrowsers(){let records=[];for(let file2 of listRecordFiles(keyedDir(BROWSERS_SUBDIR))){let record2=readRecord(file2);record2&&isAlive(record2.pid)&&records.push(record2)}return records.sort((a,b)=>(b.lastFocusedAt??0)-(a.lastFocusedAt??0)||(b.updatedAt??0)-(a.updatedAt??0))}function providerIdentity(descriptor){return{id:descriptor.providerId,name:descriptor.name,builtin:descriptor.builtin===!0,version:descriptor.version,protocolVersion:descriptor.protocolVersion}}async function ensureDiscoverableCdpBrowser(discovery){return discovery.isPublished()?!0:await discovery.isAvailable()?(discovery.publish(),discovery.monitor(),!0):!1}function ordinaryBrowser(record2){return{browserId:record2.browserId,name:record2.browserName,type:"regular",status:record2.status==="pairing"?"pairing":"connected",extensionVersion:record2.extensionVersion,nativeHostVersion:record2.nativeHostVersion,transport:record2.transport,pairing:record2.pairing}}function externalProviderBrowser(record2){if(!record2.provider||!record2.persistence||!record2.operations)throw new Error(`Provider browser record is incomplete: ${record2.browserId}`);let status=record2.status??"connected";return{browserId:record2.browserId,name:record2.browserName,type:"managed",status,extensionVersion:record2.extensionVersion,nativeHostVersion:record2.nativeHostVersion,transport:record2.transport,provider:record2.provider,ownership:record2.ownership,persistence:record2.persistence,operations:record2.operations,pairing:record2.pairing,references:record2.references,details:record2.details}}function providerBrowserInfo(entry,route){let{browser,provider}=entry,status=route&&(route.status===void 0||route.status==="connected")?"connected":browser.status;return{browserId:browser.browserId,name:browser.name,type:"managed",status,transport:route?.transport??(browser.control.kind==="host"?browser.control.transport:provider.builtin?void 0:"provider"),extensionVersion:route?.extensionVersion,nativeHostVersion:route?.nativeHostVersion,provider,ownership:browser.ownership,persistence:browser.persistence,operations:browser.operations,pairing:browser.pairing,references:browser.references,details:browser.details}}function mergeBrowserInventory(routes,providerBrowsers){let providerById=new Map(providerBrowsers.map(entry=>[entry.browser.browserId,entry])),browsers=[];for(let route of routes){let providerEntry=providerById.get(route.browserId);providerEntry?(providerById.delete(route.browserId),browsers.push(providerBrowserInfo(providerEntry,route))):route.provider||route.transport==="provider"?browsers.push(externalProviderBrowser(route)):browsers.push(ordinaryBrowser(route))}let inactive=[...providerById.values()].sort((a,b)=>{let aCreated=String(a.browser.details?.createdAt??"");return String(b.browser.details?.createdAt??"").localeCompare(aCreated)}).map(entry=>providerBrowserInfo(entry));return browsers.push(...inactive),{count:browsers.length,connectedCount:browsers.filter(browser=>browser.status==="connected").length,browsers}}async function providerInventory(runtimes){return(await Promise.all(runtimes.map(async runtime=>{let provider=providerIdentity(runtime.definition.descriptor);return(await runtime.listBrowsers()).map(browser=>({provider,browser}))}))).flat()}async function listBrowserInventory(runtimes){return mergeBrowserInventory(listRegisteredBrowsers(),await providerInventory(runtimes))}import fs5 from"node:fs";import path6 from"node:path";import os2 from"node:os";import{randomUUID as randomUUID8}from"node:crypto";var NATIVE_HOST_VERSION="2.14.0";var MEASUREMENT_ID="G-W84LJDZ6PH",API_SECRET="X233siI5RrGYLhlD0kBKEQ",ENDPOINT=`https://www.google-analytics.com/mp/collect?measurement_id=${MEASUREMENT_ID}&api_secret=${API_SECRET}`,CLIENT_ID_PATTERN=/^\d+\.\d+$/,BUILD_CHANNEL=NATIVE_HOST_VERSION==="unknown"?"development":"production",CONFIG_DIR=path6.join(os2.homedir(),".mearl"),CONFIG_FILE=path6.join(CONFIG_DIR,"config.json");function readConfig(){try{return JSON.parse(fs5.readFileSync(CONFIG_FILE,"utf-8"))}catch{return{}}}function writeConfig(config2){try{fs5.mkdirSync(CONFIG_DIR,{recursive:!0}),fs5.writeFileSync(CONFIG_FILE,JSON.stringify(config2,null,2))}catch{}}var clientId=null;function createClientId(seed=randomUUID8()){let first=2166136261,second=2246822519;for(let index=0;index<seed.length;index++){let code=seed.charCodeAt(index);first=Math.imul(first^code,16777619)>>>0,second=Math.imul(second^code,3266489917)>>>0}return`${first||1}.${second||1}`}function getClientId(){if(clientId)return clientId;let config2=readConfig();return config2.clientId&&CLIENT_ID_PATTERN.test(config2.clientId)?(clientId=config2.clientId,clientId):(clientId=createClientId(config2.clientId),writeConfig({...config2,clientId}),clientId)}function setAnalyticsClientId(value){return typeof value!="string"||!CLIENT_ID_PATTERN.test(value)?!1:(clientId=value,!0)}function classifyAnalyticsError(error48){let message=error48 instanceof Error?error48.message:String(error48);return/timed?\s*out|timeout/i.test(message)?"timeout":/permission|not authorized|access denied|forbidden/i.test(message)?"permission_denied":/not found|no matching|does not exist/i.test(message)?"not_found":/not connected|disconnected|unavailable|connection (?:failed|closed)/i.test(message)?"unavailable":/invalid|required|must be|unsupported/i.test(message)?"invalid_request":"execution_error"}function trackAction(action,params){let payload={client_id:getClientId(),events:[{name:"agent_action",params:{action,...params,mearl_version:NATIVE_HOST_VERSION,runtime:"native_host",build_channel:BUILD_CHANNEL}}]};fetch(ENDPOINT,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(payload),keepalive:!0}).catch(()=>{})}import{open}from"node:fs/promises";import path8 from"node:path";var TRUNCATED_MARKER=`
|
|
1255
1255
|
… [middle truncated for Native Messaging] …
|
|
1256
1256
|
`;function truncateUtf82(value,maxBytes){if(Buffer.byteLength(value,"utf8")<=maxBytes)return value;let markerBytes=Buffer.byteLength(TRUNCATED_MARKER,"utf8");if(maxBytes<=markerBytes)return"";let source=Buffer.from(value,"utf8"),contentBytes=maxBytes-markerBytes,headBytes=Math.ceil(contentBytes/2),tailBytes=Math.floor(contentBytes/2);do{let truncated=`${source.subarray(0,headBytes).toString("utf8")}${TRUNCATED_MARKER}${source.subarray(source.length-tailBytes).toString("utf8")}`;if(Buffer.byteLength(truncated,"utf8")<=maxBytes)return truncated;headBytes>=tailBytes?headBytes-=1:tailBytes-=1}while(headBytes>0&&tailBytes>0);return""}function sanitizeValue(value,budget,depth){if(value===null||typeof value=="boolean"||typeof value=="number")return value;if(typeof value=="string"){let available=Math.max(0,budget.remaining),next2=truncateUtf82(value,available),bytes=Buffer.byteLength(next2,"utf8");return budget.remaining=Math.max(0,budget.remaining-bytes),next2!==value&&(budget.truncated=!0),next2}if(typeof value>"u")return null;if(typeof value!="object")return String(value);if(depth>=12||budget.remaining<=0)return budget.truncated=!0,{__transportTruncated:!0};if(budget.seen.has(value))return budget.truncated=!0,"[Circular]";if(budget.seen.add(value),Array.isArray(value)){let next2=value.slice(0,160).map(entry=>sanitizeValue(entry,budget,depth+1));return value.length>160&&(budget.truncated=!0,next2.push({__transportTruncated:!0,originalLength:value.length})),next2}let entries=Object.entries(value),next={};for(let[index,[key,entry]]of entries.entries()){if(index>=160||budget.remaining<=0){budget.truncated=!0;break}budget.remaining=Math.max(0,budget.remaining-Buffer.byteLength(key,"utf8")),next[key]=sanitizeValue(entry,budget,depth+1)}return budget.truncated&&(next.__transportTruncated=!0),next}function sanitizeAgentChatEvent(event){let budget={remaining:409600,truncated:!1,seen:new WeakSet},next={...event,params:sanitizeValue(event.params,budget,0)},bytes=Buffer.byteLength(JSON.stringify(next),"utf8");return bytes<=524288?next:{...event,params:{__transportTruncated:!0,originalBytes:bytes,message:"Agent event exceeded the Native Messaging transport limit."}}}import fs6 from"node:fs";import path7 from"node:path";import{execFile}from"node:child_process";function selectedPath(stdout){return stdout.replace(/[\r\n]+$/,"")||null}var runDirectoryPickerCommand=(command,args)=>new Promise((resolve5,reject)=>{execFile(command,args,{encoding:"utf8",windowsHide:!0},(error48,stdout)=>{if(!error48){resolve5(selectedPath(stdout));return}if(error48.code===1){resolve5(null);return}reject(error48)})});function isMissingCommand(error48){return error48 instanceof Error&&error48.code==="ENOENT"}async function pickWorkspaceDirectory(platform=process.platform,run=runDirectoryPickerCommand){let directory;if(platform==="darwin")directory=await run("osascript",["-e",'POSIX path of (choose folder with prompt "Select a workspace for Agent Chat")']);else if(platform==="win32"){let script=["Add-Type -AssemblyName System.Windows.Forms;","$dialog = New-Object System.Windows.Forms.FolderBrowserDialog;","$dialog.Description = 'Select a workspace for Agent Chat';","if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {","[Console]::OutputEncoding = [System.Text.Encoding]::UTF8;","Write-Output $dialog.SelectedPath;","}"].join(" ");directory=await run("powershell.exe",["-NoProfile","-STA","-Command",script])}else if(platform==="linux")try{directory=await run("zenity",["--file-selection","--directory","--title=Select a workspace for Agent Chat"])}catch(error48){if(!isMissingCommand(error48))throw error48;try{directory=await run("kdialog",["--getexistingdirectory",".","--title","Select a workspace for Agent Chat"])}catch(fallbackError){throw isMissingCommand(fallbackError)?new Error("Install zenity or kdialog to select an Agent Chat workspace",{cause:fallbackError}):fallbackError}}else throw new Error(`Directory selection is not supported on ${platform}`);return directory?resolveWorkspaceDirectory(directory):null}function resolveWorkspaceDirectory(directory){if(typeof directory!="string"||!directory)throw new Error("Workspace directory is required");if(!path7.isAbsolute(directory))throw new Error("Workspace directory must be an absolute path");let resolved;try{resolved=fs6.realpathSync.native(directory)}catch(error48){throw new Error(`Workspace directory does not exist: ${directory}`,{cause:error48})}if(!fs6.statSync(resolved).isDirectory())throw new Error(`Workspace path is not a directory: ${directory}`);return resolved}var MAX_REPLAY_EVENTS=1e3,MAX_REPLAY_BYTES=2048*1024,MAX_REPLAY_PAGE_BYTES=524288,MAX_SKILL_FILE_BYTES=1024*1024,SUPPORTED_IMAGE_MIME_TYPES=new Set(AGENT_CHAT_SUPPORTED_IMAGE_MIME_TYPES),REPLAY_SNAPSHOT_METHODS=new Set(["thread/settings/updated"]);function createAgentDeveloperInstructions({cwd,tabId,initialPageUrl,initialPageTitle}){return[...cwd?[createAgentDirectoryContextInstructions(cwd)]:[],...tabId!==void 0?[createBrowserAgentDeveloperInstructions(tabId,{...initialPageUrl?{url:initialPageUrl}:{},...initialPageTitle?{title:initialPageTitle}:{}})]:[]].join(`
|
|
1257
1257
|
|
|
@@ -1303,14 +1303,14 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
1303
1303
|
User request:
|
|
1304
1304
|
${message}`:message,promptContent=[...prompt?[{type:"text",text:prompt}]:[],...images.map(image=>({type:"image",data:image.data,mimeType:image.mimeType}))];return session.instructionsSent=!0,this.emit({providerSessionId,kind:"notification",method:"turn/started",params:{turn:{id:turnId,status:"inProgress"}}}),this.runPrompt(providerSessionId,session,turn,promptContent),{turnId}}async interrupt(providerSessionId,_turnId){await this.ensureStarted(),await this.getContext().notify(methods.agent.session.cancel,{sessionId:providerSessionId}),this.cancelPermissions(providerSessionId)}async closeSession(providerSessionId){this.sessions.get(providerSessionId)?.activeTurn&&this.context&&await this.context.notify(methods.agent.session.cancel,{sessionId:providerSessionId}).catch(()=>{}),this.cancelPermissions(providerSessionId),this.sessions.delete(providerSessionId)}respondToRequest(requestId,result){let pending=this.pendingPermissions.get(requestId);if(!pending)throw new Error(`Unknown Qoder permission request: ${String(requestId)}`);if(!isPermissionResponse(result))throw new Error("Invalid Qoder permission response");this.pendingPermissions.delete(requestId),pending.resolve(result),this.emit({providerSessionId:pending.providerSessionId,kind:"notification",method:"serverRequest/resolved",params:{requestId}})}dispose(){for(let pending of this.pendingPermissions.values())pending.resolve({outcome:{outcome:"cancelled"}});this.pendingPermissions.clear(),this.historyCaptures.clear(),this.sessions.clear();let connection=this.connection,child=this.process;this.process=null,this.connection=null,this.context=null,this.initializeResponse=null,this.startPromise=null,this.executableResolver.reset(),connection?.close(new Error("Qoder provider disposed")),child&&!child.killed&&child.kill("SIGTERM")}async ensureStarted(){if(!(this.process&&!this.process.killed&&this.context)){if(this.startPromise)return this.startPromise;this.startPromise=this.start();try{await this.startPromise}catch(error48){throw this.startPromise=null,error48}}}async start(){let resolution=await this.resolveExecutable();if(resolution.executable===null)throw new Error(resolution.error);let{executable}=resolution,launch=resolveSpawnCommand(executable,["--acp"]),child=spawn10(launch.command,launch.args,{stdio:["pipe","pipe","pipe"],windowsHide:!0,env:prependNodePath()});this.process=child,child.stderr.on("data",chunk=>{let message=chunk.toString("utf8").trim();message&&this.log("[Qoder]",message)}),child.once("error",error48=>this.handleExit(child,error48)),child.once("exit",(code,signal)=>{this.handleExit(child,new Error(`Qoder ACP exited (code=${String(code)}, signal=${String(signal)})`))});let stream=ndJsonStream(Writable.toWeb(child.stdin),Readable.toWeb(child.stdout)),connection=client({name:"mearl"}).onRequest(methods.client.session.requestPermission,context=>this.handlePermissionRequest(context.requestId,context.params)).onNotification(methods.client.session.update,context=>{this.handleSessionUpdate(context.params)}).connect(stream);this.connection=connection,this.context=connection.agent;try{this.initializeResponse=await this.withTimeout(connection.agent.request(methods.agent.initialize,{protocolVersion:PROTOCOL_VERSION,clientCapabilities:{},clientInfo:{name:"mearl",title:"Mearl",version:this.clientVersion}}),"Qoder ACP initialization")}catch(error48){throw this.process=null,this.connection=null,this.context=null,this.executableResolver.reset(),connection.close(error48),child.killed||child.kill("SIGTERM"),new Error(`Qoder ACP failed to initialize. Start "qodercli", enter "/login", and try again: ${errorMessage(error48)}`,{cause:error48})}}async runPrompt(providerSessionId,session,turn,prompt){try{let response=await this.getContext().request(methods.agent.session.prompt,{sessionId:providerSessionId,prompt});turn.reasoningStarted&&this.emit({providerSessionId,kind:"notification",method:"item/completed",params:{turnId:turn.id,item:{id:turn.reasoningItemId,type:"reasoning",summary:turn.reasoningText?[turn.reasoningText]:[]}}}),turn.assistantText&&this.emit({providerSessionId,kind:"notification",method:"item/completed",params:{turnId:turn.id,item:{id:turn.assistantItemId,type:"agentMessage",text:turn.assistantText}}}),response.usage&&this.emit({providerSessionId,kind:"notification",method:"thread/tokenUsage/updated",params:{turnId:turn.id,usage:response.usage}}),this.emit({providerSessionId,kind:"notification",method:"turn/completed",params:{turn:{id:turn.id,status:response.stopReason==="cancelled"?"cancelled":"completed",stopReason:response.stopReason}}})}catch(error48){this.emit({providerSessionId,kind:"error",method:"chat/error",params:{turnId:turn.id,message:errorMessage(error48)}}),this.emit({providerSessionId,kind:"notification",method:"turn/completed",params:{turn:{id:turn.id,status:"failed"}}})}finally{session.activeTurn===turn&&delete session.activeTurn}}handleSessionUpdate(notification){let historyCapture=this.historyCaptures.get(notification.sessionId);if(historyCapture){captureHistoryUpdate(historyCapture,notification.update);return}let session=this.sessions.get(notification.sessionId),update=notification.update;if(update.sessionUpdate==="config_option_update"){let model=qoderModelInfo(update.configOptions);session&&(model?session.model=model:delete session.model),this.emit({providerSessionId:notification.sessionId,kind:"notification",method:"session/model/updated",params:{model:model??null}}),this.emit({providerSessionId:notification.sessionId,kind:"notification",method:"qoder/sessionUpdate",params:notification});return}let turn=session?.activeTurn;if(!turn){this.emit({providerSessionId:notification.sessionId,kind:"notification",method:"qoder/sessionUpdate",params:notification});return}switch(update.sessionUpdate){case"agent_message_chunk":{let delta=contentText(update.content);if(!delta)return;turn.assistantText+=delta,this.emit({providerSessionId:notification.sessionId,kind:"notification",method:"item/agentMessage/delta",params:{turnId:turn.id,itemId:turn.assistantItemId,delta}});return}case"agent_thought_chunk":{let delta=contentText(update.content);if(!delta)return;turn.reasoningStarted||(turn.reasoningStarted=!0,this.emit({providerSessionId:notification.sessionId,kind:"notification",method:"item/started",params:{turnId:turn.id,item:{id:turn.reasoningItemId,type:"reasoning",summary:[]}}})),turn.reasoningText+=delta,this.emit({providerSessionId:notification.sessionId,kind:"notification",method:"item/reasoning/summaryTextDelta",params:{turnId:turn.id,itemId:turn.reasoningItemId,delta}});return}case"tool_call":turn.toolTitles.set(update.toolCallId,update.title),this.emitToolUpdate(notification.sessionId,turn,update,update.title);return;case"tool_call_update":{let title=update.title||turn.toolTitles.get(update.toolCallId)||update.toolCallId;turn.toolTitles.set(update.toolCallId,title),this.emitToolUpdate(notification.sessionId,turn,update,title);return}case"plan":{let text=planText(update.entries);this.emit({providerSessionId:notification.sessionId,kind:"notification",method:"item/completed",params:{turnId:turn.id,item:{id:turn.planItemId,type:"plan",text}}});return}case"usage_update":this.emit({providerSessionId:notification.sessionId,kind:"notification",method:"thread/tokenUsage/updated",params:{turnId:turn.id,usage:update}});return;default:this.emit({providerSessionId:notification.sessionId,kind:"notification",method:"qoder/sessionUpdate",params:{turnId:turn.id,update}})}}emitToolUpdate(providerSessionId,turn,update,title){let completed=update.status==="completed"||update.status==="failed";this.emit({providerSessionId,kind:"notification",method:completed?"item/completed":"item/started",params:{turnId:turn.id,item:{id:update.toolCallId,type:"dynamicToolCall",namespace:"qoder",tool:title,status:update.status||(completed?"completed":"inProgress"),kind:update.kind,rawInput:update.rawInput,rawOutput:update.rawOutput,content:update.content,locations:update.locations}}})}handlePermissionRequest(requestId,request){return requestId===null?Promise.resolve({outcome:{outcome:"cancelled"}}):new Promise(resolve5=>{this.pendingPermissions.set(requestId,{providerSessionId:request.sessionId,resolve:resolve5}),this.emit({providerSessionId:request.sessionId,kind:"request",method:"qoder/requestPermission",params:request,requestId})})}cancelPermissions(providerSessionId){for(let[requestId,pending]of this.pendingPermissions)pending.providerSessionId===providerSessionId&&(this.pendingPermissions.delete(requestId),pending.resolve({outcome:{outcome:"cancelled"}}))}handleExit(child,error48){if(this.process===child){this.process=null,this.connection?.close(error48),this.connection=null,this.context=null,this.initializeResponse=null,this.startPromise=null,this.executableResolver.reset();for(let providerSessionId of this.sessions.keys())this.cancelPermissions(providerSessionId),this.emit({providerSessionId,kind:"error",method:"provider/exited",params:{message:error48.message}})}}getContext(){if(!this.context)throw new Error("Qoder ACP is not running");return this.context}assertImageInputSupported(){if(!this.initializeResponse?.agentCapabilities?.promptCapabilities?.image)throw new Error("This Qoder CLI version does not support image prompts")}withTimeout(promise2,operation){return new Promise((resolve5,reject)=>{let timer=setTimeout(()=>reject(new Error(`${operation} timed out`)),REQUEST_TIMEOUT_MS2);promise2.then(result=>{clearTimeout(timer),resolve5(result)},error48=>{clearTimeout(timer),reject(error48)})})}probeExecutable(executable){return probeAgentExecutable(executable,{args:["--version"],timeoutMs:PROBE_TIMEOUT_MS2,timeoutError:"Timed out while checking Qoder CLI availability.",startError:error48=>`Failed to start Qoder CLI: ${error48.message}`,exitError:code=>`Qoder CLI check exited with code ${String(code)}`})}runSkillsList(executable,cwd){return new Promise((resolve5,reject)=>{let launch=resolveSpawnCommand(executable,["skill","list","--all"]),child=spawn10(launch.command,launch.args,{cwd,stdio:["ignore","pipe","pipe"],windowsHide:!0,env:prependNodePath()}),stdout="",stderr="",settled=!1,finish=error48=>{settled||(settled=!0,clearTimeout(timer),error48?reject(error48):resolve5(stdout))},timer=setTimeout(()=>{child.kill("SIGTERM"),finish(new Error("Timed out while listing Qoder skills."))},REQUEST_TIMEOUT_MS2);child.stdout.on("data",chunk=>{stdout.length<1e6&&(stdout+=chunk.toString("utf8"))}),child.stderr.on("data",chunk=>{stderr.length<1e4&&(stderr+=chunk.toString("utf8"))}),child.once("error",error48=>finish(error48)),child.once("exit",code=>{code===0?finish():finish(new Error(stderr.trim()||`Qoder skill list exited with code ${String(code)}`))})})}resolveExecutable(){return this.executableResolver.resolve()}resolveExecutableCandidates(){return executableFileCandidates(qoderExecutableCandidatePaths())}emit(event){for(let listener of this.listeners)listener(event)}};import fs10 from"node:fs";import os5 from"node:os";import path12 from"node:path";import{spawn as spawn11}from"node:child_process";var COMMAND_TIMEOUT_MS=12e4,MAX_OUTPUT_LENGTH=1e6,ANSI_ESCAPE_PATTERN=new RegExp(String.raw`\u001B\[[0-?]*[ -/]*[@-~]`,"g");function existingExecutable(candidates,existsSync14){return candidates.find(candidate=>candidate&&existsSync14(candidate))??null}function stripAnsi(value){return value.replace(ANSI_ESCAPE_PATTERN,"")}function resolveAliSkillsExecutable(options={}){let env=options.env??process.env,home=(options.homedir??os5.homedir)(),platform=options.platform??process.platform,existsSync14=options.existsSync??(candidate=>isExecutable(candidate,platform)),processExecPath=options.processExecPath??process.execPath,readdirSync2=options.readdirSync??fs10.readdirSync,names=executableNames("ali-skills",platform),pathKey=Object.keys(env).find(key=>key.toLowerCase()==="path")||"PATH",pathCandidates=(env[pathKey]||"").split(path12.delimiter).filter(Boolean).flatMap(directory=>names.map(name=>path12.join(directory,name))),candidates=[env.MEARL_ALI_SKILLS_PATH,...names.map(name=>path12.join(path12.dirname(processExecPath),name)),...names.map(name=>path12.join(home,".local","bin",name)),...names.map(name=>path12.join(home,".npm-global","bin",name)),...names.map(name=>path12.join(home,".volta","bin",name)),...names.map(name=>path12.join(home,".local","share","pnpm",name)),...names.map(name=>path12.join(home,"Library","pnpm",name)),...versionManagerExecutableCandidates(home,names,{env,platform,readdirSync:readdirSync2}),...platform==="win32"?[]:["/opt/homebrew/bin/ali-skills","/usr/local/bin/ali-skills","/usr/bin/ali-skills"],...pathCandidates];return existingExecutable(candidates,existsSync14)}var runAliSkillsCli=(executable,args,cwd)=>new Promise((resolve5,reject)=>{let launch=resolveSpawnCommand(executable,args),child=spawn11(launch.command,launch.args,{cwd,env:prependNodePath(prependCommandPath(executable)),stdio:["ignore","pipe","pipe"],windowsHide:!0}),stdout="",stderr="",settled=!1,append=(current,chunk)=>current.length>=MAX_OUTPUT_LENGTH?current:(current+chunk.toString("utf8")).slice(0,MAX_OUTPUT_LENGTH),finish=error48=>{settled||(settled=!0,clearTimeout(timer),error48?reject(error48):resolve5({stdout,stderr}))},timer=setTimeout(()=>{child.kill("SIGTERM"),finish(new Error(`Ali Skills command timed out after ${COMMAND_TIMEOUT_MS/1e3}s`))},COMMAND_TIMEOUT_MS);child.stdout.on("data",chunk=>stdout=append(stdout,chunk)),child.stderr.on("data",chunk=>stderr=append(stderr,chunk)),child.once("error",error48=>finish(error48)),child.once("exit",code=>{if(code===0){finish();return}let detail=stripAnsi(stderr||stdout).trim();finish(new Error(detail||`Ali Skills command exited with code ${String(code)}`))})});var SETUP_COMMAND="npm install -g ali-skills";var runSkillCli=runAliSkillsCli;function validateProvider(value){if(value!=="codex"&&value!=="qoder")throw new Error("Skill provider must be codex or qoder");return value}function validateScope(value){if(value!=="project"&&value!=="global")throw new Error("Skill scope must be project or global");return value}function validateArgument(value,label){if(typeof value!="string"||!value.trim()||/[\0\r\n]/.test(value))throw new Error(`${label} is invalid`);return value.trim()}function scopeCwd(scope,cwd){if(scope!=="global")return resolveWorkspaceDirectory(cwd)}function parseSkillUpdates(stdout,scope){let clean=stripAnsi(stdout),updates=[],pattern=/^\s*↑\s+([^\s(]+)(?:\s+\(([^)]+)\))?/gm;for(let match of clean.matchAll(pattern))match[1]&&updates.push({name:match[1],...match[2]?{source:match[2]}:{},scope});return updates}var AgentSkillManager=class{executableResolver;run;constructor(options={}){this.executableResolver=options.resolveExecutable??resolveAliSkillsExecutable,this.run=options.run??runSkillCli}async getStatus(){let executable=this.executableResolver();if(!executable)return{available:!1,error:"Ali Skills CLI is not installed",setupCommand:SETUP_COMMAND};try{let{stdout,stderr}=await this.run(executable,["--version"]),version2=stripAnsi(stdout||stderr).trim().split(/\s+/)[0];return{available:!0,executable,...version2?{version:version2}:{},setupCommand:SETUP_COMMAND}}catch(error48){return{available:!1,executable,error:error48 instanceof Error?error48.message:String(error48),setupCommand:SETUP_COMMAND}}}async install(data){let{executable,providerId,scope,cwd}=await this.mutationContext(data),source=validateArgument(data.source,"Skill source"),name=validateArgument(data.name,"Skill name"),args=["add",source,"--skill",name,"--agent",providerId,scope==="global"?"--global":"--project","--full-depth","--yes"],output2=await this.run(executable,args,cwd);return{ok:!0,output:stripAnsi(output2.stdout||output2.stderr).trim()}}async checkUpdates(data){validateProvider(data.providerId);let cli=await this.getStatus();if(!cli.available||!cli.executable)return{cli,updates:[]};let commands=[this.run(cli.executable,["check","--global"]).then(output2=>parseSkillUpdates(`${output2.stdout}
|
|
1305
1305
|
${output2.stderr}`,"global"))];if(data.cwd!==void 0&&data.cwd!==null&&data.cwd!==""){let cwd=resolveWorkspaceDirectory(data.cwd);commands.push(this.run(cli.executable,["check"],cwd).then(output2=>parseSkillUpdates(`${output2.stdout}
|
|
1306
|
-
${output2.stderr}`,"project")))}return{cli,updates:(await Promise.all(commands)).flat()}}async update(data){let{executable,scope,cwd}=await this.mutationContext(data),args=["update",validateArgument(data.name,"Skill name"),...scope==="global"?["--global"]:[],"--yes"],output2=await this.run(executable,args,cwd);return{ok:!0,output:stripAnsi(output2.stdout||output2.stderr).trim()}}async uninstall(data){let{executable,providerId,scope,cwd}=await this.mutationContext(data),args=["remove",validateArgument(data.name,"Skill name"),"--agent",providerId,...scope==="global"?["--global"]:[],"--yes"],output2=await this.run(executable,args,cwd);return{ok:!0,output:stripAnsi(output2.stdout||output2.stderr).trim()}}async mutationContext(data){let providerId=validateProvider(data.providerId),scope=validateScope(data.scope),cwd=scopeCwd(scope,data.cwd),cli=await this.getStatus();if(!cli.available||!cli.executable)throw new Error(`${cli.error||"Ali Skills CLI is unavailable"}. Run: ${cli.setupCommand}`);return{executable:cli.executable,providerId,scope,...cwd?{cwd}:{}}}};var INTERNAL_EXTENSION_ACTIONS=new Set(["__tdbank_prepare_sso","__export_cookies","__send_request_file_start","__send_request_file_chunk","__send_request_file_abort","__send_request_with_files","browser_provider_list"]);function isInternalExtensionAction(action){return typeof action=="string"&&INTERNAL_EXTENSION_ACTIONS.has(action)}function createExtensionRequestMessage(id,action,data,trustedInternal=!1,controlSource="local"){return{id,action,data,controlSource:toControlSourceWireValue(controlSource),...trustedInternal?{trustedInternal:!0}:{}}}import fs12 from"node:fs";import path14 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";import fs11 from"node:fs";import path13 from"node:path";function normalizePath(filePath){return filePath.replaceAll("\\","/").replace(/\/+$/,"")}function firstExisting(candidates,existsSync14){return candidates.find(candidate=>existsSync14(candidate))}function fallbackCommand(name,platform){return platform!=="win32"?name:name==="bun"||name==="volta"?`${name}.exe`:`${name}.cmd`}function resolvePackageManagerInstallation(packageRoot,packageName,options={}){let env=options.env??process.env,platform=options.platform??process.platform,existsSync14=options.existsSync??(candidate=>isExecutable(candidate,platform)),processExecPath=options.processExecPath??process.execPath,normalizedRoot=normalizePath(path13.resolve(packageRoot)),lowerRoot=normalizedRoot.toLowerCase(),lowerPackageName=packageName.toLowerCase(),pnpmGlobalRoot=/\/global\/\d+\/(?:\.pnpm\/.*\/)?node_modules\//.exec(lowerRoot);if(pnpmGlobalRoot&&lowerRoot.endsWith(`/node_modules/${lowerPackageName}`)){let pnpmHome=normalizedRoot.slice(0,pnpmGlobalRoot.index);return{manager:"pnpm",command:firstExisting([...executableNames("pnpm",platform).map(name=>path13.join(pnpmHome,name)),...executableNames("pnpm",platform).map(name=>path13.join(path13.dirname(processExecPath),name))],existsSync14)??fallbackCommand("pnpm",platform),binDirectory:pnpmHome}}let bunMarker=`/.bun/install/global/node_modules/${lowerPackageName}`;if(lowerRoot.endsWith(bunMarker)){let bunHome=normalizedRoot.slice(0,lowerRoot.indexOf("/.bun/"));return{manager:"bun",command:firstExisting(executableNames("bun",platform).map(name=>path13.join(bunHome,".bun","bin",name)),existsSync14)??fallbackCommand("bun",platform),binDirectory:path13.join(bunHome,".bun","bin")}}if((lowerRoot.includes("/.config/yarn/global/node_modules/")||lowerRoot.includes("/.yarn/global/node_modules/")||lowerRoot.includes("/yarn/global/node_modules/")||lowerRoot.includes("/yarn/data/global/node_modules/"))&&lowerRoot.endsWith(`/node_modules/${lowerPackageName}`)){let layout=[{marker:"/.config/yarn/global/",binSegments:[".yarn","bin"]},{marker:"/.yarn/global/",binSegments:[".yarn","bin"]},{marker:"/yarn/data/global/",binSegments:["yarn","bin"]},{marker:"/yarn/global/",binSegments:["yarn","bin"]}].find(candidate=>lowerRoot.includes(candidate.marker)),prefix=normalizedRoot.slice(0,lowerRoot.indexOf(layout.marker)),binDirectory=path13.join(prefix,...layout.binSegments);return{manager:"yarn",command:firstExisting([...executableNames("yarn",platform).map(name=>path13.join(binDirectory,name)),...executableNames("yarn",platform).map(name=>path13.join(path13.dirname(processExecPath),name))],existsSync14)??findExecutable("yarn",{env,existsSync:existsSync14,platform})??fallbackCommand("yarn",platform),binDirectory}}if(lowerRoot.includes("/.volta/tools/image/packages/")&&lowerRoot.endsWith(`/lib/node_modules/${lowerPackageName}`)){let voltaHome=normalizedRoot.slice(0,lowerRoot.indexOf("/.volta/"));return{manager:"volta",command:firstExisting(executableNames("volta",platform).map(name=>path13.join(voltaHome,".volta","bin",name)),existsSync14)??fallbackCommand("volta",platform),binDirectory:path13.join(voltaHome,".volta","bin")}}let npmMarker=`/lib/node_modules/${lowerPackageName}`;if(lowerRoot.endsWith(npmMarker)){let prefix=normalizedRoot.slice(0,lowerRoot.length-npmMarker.length);return{manager:"npm",command:firstExisting([...executableNames("npm",platform).map(name=>path13.join(prefix,"bin",name)),...executableNames("npm",platform).map(name=>path13.join(path13.dirname(processExecPath),name))],existsSync14)??fallbackCommand("npm",platform),binDirectory:path13.join(prefix,"bin")}}if(platform==="win32"&&env.APPDATA){let npmRoot=normalizePath(path13.join(env.APPDATA,"npm","node_modules",packageName));if(lowerRoot===npmRoot.toLowerCase()){let binDirectory=path13.join(env.APPDATA,"npm");return{manager:"npm",command:firstExisting([...executableNames("npm",platform).map(name=>path13.join(binDirectory,name)),...executableNames("npm",platform).map(name=>path13.join(path13.dirname(processExecPath),name))],existsSync14)??fallbackCommand("npm",platform),binDirectory}}}return null}var RELEASE_VERSION_PATTERN=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-beta\.(0|[1-9]\d*))?$/,RELEASE_LINE_PATTERN=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.x$/;function parseComponent(value){let component=Number(value);return Number.isSafeInteger(component)&&component<=65535?component:null}function parseMearlReleaseVersion(value){if(typeof value!="string"||value.length>64)return null;let match=RELEASE_VERSION_PATTERN.exec(value);if(!match)return null;let major=parseComponent(match[1]),minor=parseComponent(match[2]),patch=parseComponent(match[3]),beta=match[4]===void 0?void 0:parseComponent(match[4]);return major===null||minor===null||patch===null||beta===null?null:{raw:value,major,minor,patch,channel:beta===void 0?"stable":"beta",...beta===void 0?{}:{beta}}}function isMearlReleaseVersion(value){return parseMearlReleaseVersion(value)!==null}function parseMearlReleaseLine(value){if(typeof value!="string"||value.length>64)return null;let match=RELEASE_LINE_PATTERN.exec(value);if(!match)return null;let major=parseComponent(match[1]),minor=parseComponent(match[2]);return major===null||minor===null?null:{raw:value,major,minor}}function mearlReleaseLineForVersion(version2){let parsed=parseMearlReleaseVersion(version2);if(!parsed)throw new Error("A valid Mearl release version is required");return`${parsed.major}.${parsed.minor}.x`}function isMearlReleaseVersionInLine(version2,releaseLine){let parsedVersion=parseMearlReleaseVersion(version2),parsedLine=parseMearlReleaseLine(releaseLine);return parsedVersion!==null&&parsedLine!==null&&parsedVersion.major===parsedLine.major&&parsedVersion.minor===parsedLine.minor}function compareMearlReleaseLines(leftVersion,rightVersion){let left=parseMearlReleaseVersion(leftVersion),right=parseMearlReleaseVersion(rightVersion);if(!left||!right)throw new Error("Mearl release-line comparison requires valid release versions");for(let key of["major","minor"]){if(left[key]<right[key])return-1;if(left[key]>right[key])return 1}return 0}function compareMearlReleaseVersions(leftVersion,rightVersion){let left=parseMearlReleaseVersion(leftVersion),right=parseMearlReleaseVersion(rightVersion);if(!left||!right)throw new Error("Mearl release comparison requires valid release versions");for(let key of["major","minor","patch"]){if(left[key]<right[key])return-1;if(left[key]>right[key])return 1}if(left.channel!==right.channel)return left.channel==="stable"?1:-1;let leftBeta=left.beta??0,rightBeta=right.beta??0;return leftBeta<rightBeta?-1:leftBeta>rightBeta?1:0}var NATIVE_HOST_UPDATE_TIMEOUT_MS=5*6e4,UPDATE_LOCK_PATH=path14.join(DAEMON_HOME,"native-host-update.lock"),UPDATE_LOCK_POLL_MS=500,INVALID_UPDATE_LOCK_GRACE_MS=1e4,NativeHostUpdateFailure=class extends Error{constructor(updateError,message){super(message);this.updateError=updateError;this.name="NativeHostUpdateFailure"}};function wait(delayMs){return new Promise(resolve5=>setTimeout(resolve5,delayMs))}function readLockState(lockPath){try{let stat2=fs12.lstatSync(lockPath);if(!stat2.isFile()||stat2.isSymbolicLink()||stat2.size>4096)return{modifiedAt:stat2.mtimeMs,owner:null};try{let value=JSON.parse(fs12.readFileSync(lockPath,"utf8")),owner=Number.isInteger(value.pid)&&value.pid>0&&typeof value.startedAt=="number"&&Number.isFinite(value.startedAt)&&value.startedAt>0?{pid:value.pid,startedAt:value.startedAt}:null;return{modifiedAt:stat2.mtimeMs,owner}}catch{return{modifiedAt:stat2.mtimeMs,owner:null}}}catch{return null}}async function withNativeHostUpdateLock(lockPath,targetVersion,operation){fs12.mkdirSync(path14.dirname(lockPath),{recursive:!0,mode:448});let startedAt=Date.now(),owner=`${JSON.stringify({pid:process.pid,startedAt,targetVersion})}
|
|
1306
|
+
${output2.stderr}`,"project")))}return{cli,updates:(await Promise.all(commands)).flat()}}async update(data){let{executable,scope,cwd}=await this.mutationContext(data),args=["update",validateArgument(data.name,"Skill name"),...scope==="global"?["--global"]:[],"--yes"],output2=await this.run(executable,args,cwd);return{ok:!0,output:stripAnsi(output2.stdout||output2.stderr).trim()}}async uninstall(data){let{executable,providerId,scope,cwd}=await this.mutationContext(data),args=["remove",validateArgument(data.name,"Skill name"),"--agent",providerId,...scope==="global"?["--global"]:[],"--yes"],output2=await this.run(executable,args,cwd);return{ok:!0,output:stripAnsi(output2.stdout||output2.stderr).trim()}}async mutationContext(data){let providerId=validateProvider(data.providerId),scope=validateScope(data.scope),cwd=scopeCwd(scope,data.cwd),cli=await this.getStatus();if(!cli.available||!cli.executable)throw new Error(`${cli.error||"Ali Skills CLI is unavailable"}. Run: ${cli.setupCommand}`);return{executable:cli.executable,providerId,scope,...cwd?{cwd}:{}}}};var INTERNAL_EXTENSION_ACTIONS=new Set(["__tdbank_prepare_sso","__export_cookies","__send_request_file_start","__send_request_file_chunk","__send_request_file_abort","__send_request_with_files","browser_provider_list","browser_provider_configure","browser_manager_start","browser_manager_sync_cookies"]);function isInternalExtensionAction(action){return typeof action=="string"&&INTERNAL_EXTENSION_ACTIONS.has(action)}function createExtensionRequestMessage(id,action,data,trustedInternal=!1,controlSource="local"){return{id,action,data,controlSource:toControlSourceWireValue(controlSource),...trustedInternal?{trustedInternal:!0}:{}}}import fs12 from"node:fs";import path14 from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";import fs11 from"node:fs";import path13 from"node:path";function normalizePath(filePath){return filePath.replaceAll("\\","/").replace(/\/+$/,"")}function firstExisting(candidates,existsSync14){return candidates.find(candidate=>existsSync14(candidate))}function fallbackCommand(name,platform){return platform!=="win32"?name:name==="bun"||name==="volta"?`${name}.exe`:`${name}.cmd`}function resolvePackageManagerInstallation(packageRoot,packageName,options={}){let env=options.env??process.env,platform=options.platform??process.platform,existsSync14=options.existsSync??(candidate=>isExecutable(candidate,platform)),processExecPath=options.processExecPath??process.execPath,normalizedRoot=normalizePath(path13.resolve(packageRoot)),lowerRoot=normalizedRoot.toLowerCase(),lowerPackageName=packageName.toLowerCase(),pnpmGlobalRoot=/\/global\/\d+\/(?:\.pnpm\/.*\/)?node_modules\//.exec(lowerRoot);if(pnpmGlobalRoot&&lowerRoot.endsWith(`/node_modules/${lowerPackageName}`)){let pnpmHome=normalizedRoot.slice(0,pnpmGlobalRoot.index);return{manager:"pnpm",command:firstExisting([...executableNames("pnpm",platform).map(name=>path13.join(pnpmHome,name)),...executableNames("pnpm",platform).map(name=>path13.join(path13.dirname(processExecPath),name))],existsSync14)??fallbackCommand("pnpm",platform),binDirectory:pnpmHome}}let bunMarker=`/.bun/install/global/node_modules/${lowerPackageName}`;if(lowerRoot.endsWith(bunMarker)){let bunHome=normalizedRoot.slice(0,lowerRoot.indexOf("/.bun/"));return{manager:"bun",command:firstExisting(executableNames("bun",platform).map(name=>path13.join(bunHome,".bun","bin",name)),existsSync14)??fallbackCommand("bun",platform),binDirectory:path13.join(bunHome,".bun","bin")}}if((lowerRoot.includes("/.config/yarn/global/node_modules/")||lowerRoot.includes("/.yarn/global/node_modules/")||lowerRoot.includes("/yarn/global/node_modules/")||lowerRoot.includes("/yarn/data/global/node_modules/"))&&lowerRoot.endsWith(`/node_modules/${lowerPackageName}`)){let layout=[{marker:"/.config/yarn/global/",binSegments:[".yarn","bin"]},{marker:"/.yarn/global/",binSegments:[".yarn","bin"]},{marker:"/yarn/data/global/",binSegments:["yarn","bin"]},{marker:"/yarn/global/",binSegments:["yarn","bin"]}].find(candidate=>lowerRoot.includes(candidate.marker)),prefix=normalizedRoot.slice(0,lowerRoot.indexOf(layout.marker)),binDirectory=path13.join(prefix,...layout.binSegments);return{manager:"yarn",command:firstExisting([...executableNames("yarn",platform).map(name=>path13.join(binDirectory,name)),...executableNames("yarn",platform).map(name=>path13.join(path13.dirname(processExecPath),name))],existsSync14)??findExecutable("yarn",{env,existsSync:existsSync14,platform})??fallbackCommand("yarn",platform),binDirectory}}if(lowerRoot.includes("/.volta/tools/image/packages/")&&lowerRoot.endsWith(`/lib/node_modules/${lowerPackageName}`)){let voltaHome=normalizedRoot.slice(0,lowerRoot.indexOf("/.volta/"));return{manager:"volta",command:firstExisting(executableNames("volta",platform).map(name=>path13.join(voltaHome,".volta","bin",name)),existsSync14)??fallbackCommand("volta",platform),binDirectory:path13.join(voltaHome,".volta","bin")}}let npmMarker=`/lib/node_modules/${lowerPackageName}`;if(lowerRoot.endsWith(npmMarker)){let prefix=normalizedRoot.slice(0,lowerRoot.length-npmMarker.length);return{manager:"npm",command:firstExisting([...executableNames("npm",platform).map(name=>path13.join(prefix,"bin",name)),...executableNames("npm",platform).map(name=>path13.join(path13.dirname(processExecPath),name))],existsSync14)??fallbackCommand("npm",platform),binDirectory:path13.join(prefix,"bin")}}if(platform==="win32"&&env.APPDATA){let npmRoot=normalizePath(path13.join(env.APPDATA,"npm","node_modules",packageName));if(lowerRoot===npmRoot.toLowerCase()){let binDirectory=path13.join(env.APPDATA,"npm");return{manager:"npm",command:firstExisting([...executableNames("npm",platform).map(name=>path13.join(binDirectory,name)),...executableNames("npm",platform).map(name=>path13.join(path13.dirname(processExecPath),name))],existsSync14)??fallbackCommand("npm",platform),binDirectory}}}return null}var RELEASE_VERSION_PATTERN=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-beta\.(0|[1-9]\d*))?$/,RELEASE_LINE_PATTERN=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.x$/;function parseComponent(value){let component=Number(value);return Number.isSafeInteger(component)&&component<=65535?component:null}function parseMearlReleaseVersion(value){if(typeof value!="string"||value.length>64)return null;let match=RELEASE_VERSION_PATTERN.exec(value);if(!match)return null;let major=parseComponent(match[1]),minor=parseComponent(match[2]),patch=parseComponent(match[3]),beta=match[4]===void 0?void 0:parseComponent(match[4]);return major===null||minor===null||patch===null||beta===null?null:{raw:value,major,minor,patch,channel:beta===void 0?"stable":"beta",...beta===void 0?{}:{beta}}}function isMearlReleaseVersion(value){return parseMearlReleaseVersion(value)!==null}function parseMearlReleaseLine(value){if(typeof value!="string"||value.length>64)return null;let match=RELEASE_LINE_PATTERN.exec(value);if(!match)return null;let major=parseComponent(match[1]),minor=parseComponent(match[2]);return major===null||minor===null?null:{raw:value,major,minor}}function mearlReleaseLineForVersion(version2){let parsed=parseMearlReleaseVersion(version2);if(!parsed)throw new Error("A valid Mearl release version is required");return`${parsed.major}.${parsed.minor}.x`}function isMearlReleaseVersionInLine(version2,releaseLine){let parsedVersion=parseMearlReleaseVersion(version2),parsedLine=parseMearlReleaseLine(releaseLine);return parsedVersion!==null&&parsedLine!==null&&parsedVersion.major===parsedLine.major&&parsedVersion.minor===parsedLine.minor}function compareMearlReleaseLines(leftVersion,rightVersion){let left=parseMearlReleaseVersion(leftVersion),right=parseMearlReleaseVersion(rightVersion);if(!left||!right)throw new Error("Mearl release-line comparison requires valid release versions");for(let key of["major","minor"]){if(left[key]<right[key])return-1;if(left[key]>right[key])return 1}return 0}function compareMearlReleaseVersions(leftVersion,rightVersion){let left=parseMearlReleaseVersion(leftVersion),right=parseMearlReleaseVersion(rightVersion);if(!left||!right)throw new Error("Mearl release comparison requires valid release versions");for(let key of["major","minor","patch"]){if(left[key]<right[key])return-1;if(left[key]>right[key])return 1}if(left.channel!==right.channel)return left.channel==="stable"?1:-1;let leftBeta=left.beta??0,rightBeta=right.beta??0;return leftBeta<rightBeta?-1:leftBeta>rightBeta?1:0}var NATIVE_HOST_UPDATE_TIMEOUT_MS=5*6e4,UPDATE_LOCK_PATH=path14.join(DAEMON_HOME,"native-host-update.lock"),UPDATE_LOCK_POLL_MS=500,INVALID_UPDATE_LOCK_GRACE_MS=1e4,NativeHostUpdateFailure=class extends Error{constructor(updateError,message){super(message);this.updateError=updateError;this.name="NativeHostUpdateFailure"}};function wait(delayMs){return new Promise(resolve5=>setTimeout(resolve5,delayMs))}function readLockState(lockPath){try{let stat2=fs12.lstatSync(lockPath);if(!stat2.isFile()||stat2.isSymbolicLink()||stat2.size>4096)return{modifiedAt:stat2.mtimeMs,owner:null};try{let value=JSON.parse(fs12.readFileSync(lockPath,"utf8")),owner=Number.isInteger(value.pid)&&value.pid>0&&typeof value.startedAt=="number"&&Number.isFinite(value.startedAt)&&value.startedAt>0?{pid:value.pid,startedAt:value.startedAt}:null;return{modifiedAt:stat2.mtimeMs,owner}}catch{return{modifiedAt:stat2.mtimeMs,owner:null}}}catch{return null}}async function withNativeHostUpdateLock(lockPath,targetVersion,operation){fs12.mkdirSync(path14.dirname(lockPath),{recursive:!0,mode:448});let startedAt=Date.now(),owner=`${JSON.stringify({pid:process.pid,startedAt,targetVersion})}
|
|
1307
1307
|
`;for(;;)try{let handle=fs12.openSync(lockPath,"wx",384);try{fs12.writeFileSync(handle,owner,"utf8")}finally{fs12.closeSync(handle)}break}catch(error48){if(!(error48 instanceof Error)||!("code"in error48)||error48.code!=="EEXIST")throw error48;let existing=readLockState(lockPath),staleAfter=existing?.owner?NATIVE_HOST_UPDATE_TIMEOUT_MS:INVALID_UPDATE_LOCK_GRACE_MS,referenceTime=existing?.owner?.startedAt??existing?.modifiedAt,expired=referenceTime!==void 0&&Date.now()-referenceTime>staleAfter,ownerAlive=existing?.owner?isAlive(existing.owner.pid):!1;if(expired&&!ownerAlive)try{fs12.unlinkSync(lockPath);continue}catch{}if(Date.now()-startedAt>NATIVE_HOST_UPDATE_TIMEOUT_MS+1e4)throw new NativeHostUpdateFailure("lock-timeout","Another Mearl Native Host update did not finish in time");await wait(UPDATE_LOCK_POLL_MS)}try{return await operation()}finally{try{fs12.readFileSync(lockPath,"utf8")===owner&&fs12.unlinkSync(lockPath)}catch{}}}function classifyUpdateFailure(output2){return/\b(?:E404|ETARGET)\b|no matching version found|404\s+not found|package.+not found/i.test(output2)?"package-unavailable":/\b(?:EAI_AGAIN|ECONNREFUSED|ECONNRESET|ENETUNREACH|ENOTFOUND|ERR_SOCKET_TIMEOUT)\b|fetch failed|network request/i.test(output2)?"network":"setup-failed"}function nativeHostUpdateCommand(targetVersion){if(!isMearlReleaseVersion(targetVersion))throw new Error("The Native Host update target must be a valid Mearl release");let releaseLine=mearlReleaseLineForVersion(targetVersion);return{args:["--yes",`@mearl/setup@${releaseLine}`,"update","--local","--yes","--target-line",releaseLine,"--skip-skill"]}}function currentNativeHostPackageRoot(entryPath){let current=path14.dirname(entryPath);for(let depth=0;depth<12;depth+=1){try{if(JSON.parse(fs12.readFileSync(path14.join(current,"package.json"),"utf8")).name==="@mearl/native-host")return current}catch{}let parent=path14.dirname(current);if(parent===current)break;current=parent}return null}function currentPackageManagerInstallation(environment,nodePath,platform){let packageRoot=currentNativeHostPackageRoot(fileURLToPath3(import.meta.url));return packageRoot?resolvePackageManagerInstallation(packageRoot,"@mearl/native-host",{env:environment,platform,processExecPath:nodePath}):null}async function installedLocalPackagesMatch(targetReleaseLine,environment,runner){let installedVersions=[];for(let executableName of["mearl-native-host","mearl"]){let executable=findExecutable(executableName,{env:environment});if(!executable)return!1;try{let result=await runner(executable,["--version"],{capture:!0,env:environment,timeoutMs:5e3}),installedVersion=result.stdout.trim();if(result.code!==0||!isMearlReleaseVersionInLine(installedVersion,targetReleaseLine))return!1;installedVersions.push(installedVersion)}catch{return!1}}return new Set(installedVersions).size===1}async function runNativeHostUpdate(targetVersion,options={}){let command=nativeHostUpdateCommand(targetVersion),targetReleaseLine=mearlReleaseLineForVersion(targetVersion),environment=options.environment??process.env,platform=options.platform??process.platform,nodePath=options.nodePath??process.execPath,currentInstallation=currentPackageManagerInstallation(environment,nodePath,platform),managerCommand=options.packageManagerCommand===void 0?currentInstallation?.command??null:options.packageManagerCommand,packageBinDirectory=options.packageBinDirectory===void 0?currentInstallation?.binDirectory??null:options.packageBinDirectory,childEnvironment=prependNodePath(environment,nodePath);managerCommand&&(childEnvironment=prependCommandPath(managerCommand,childEnvironment)),packageBinDirectory&&(childEnvironment=prependPathDirectory(packageBinDirectory,childEnvironment));let packageRunner=options.packageRunner??findExecutable("npx",{env:childEnvironment,extraDirectories:[path14.dirname(nodePath)],platform});if(!packageRunner)throw new NativeHostUpdateFailure("package-unavailable","The package runner is unavailable");let runner=options.runner??runCommand,areTargetsInstalled=options.areTargetsInstalled??((version2,env)=>installedLocalPackagesMatch(version2,env,runner));await(options.withUpdateLock??((version2,operation)=>withNativeHostUpdateLock(options.updateLockPath??UPDATE_LOCK_PATH,version2,operation)))(targetVersion,async()=>{let result;try{result=await runner(packageRunner,command.args,{capture:!0,env:childEnvironment,timeoutMs:options.timeoutMs??NATIVE_HOST_UPDATE_TIMEOUT_MS})}catch(error48){let message=error48 instanceof Error?error48.message:String(error48),classified=classifyUpdateFailure(message);throw new NativeHostUpdateFailure(/timed out/i.test(message)?"timeout":classified==="setup-failed"?"unknown":classified,"The Native Host update process did not complete")}if(result.code!==0)throw new NativeHostUpdateFailure(classifyUpdateFailure(`${result.stderr.slice(0,8192)}
|
|
1308
1308
|
${result.stdout.slice(0,8192)}`),"The Mearl setup release line did not complete successfully");if(!await areTargetsInstalled(targetReleaseLine,childEnvironment))throw new NativeHostUpdateFailure("verification-failed","The installed Native Host and client do not match the Extension release line")})}var NativeHostUpdateCoordinator=class{constructor(options){this.options=options}#automaticAttempted=!1;#operation=null;evaluate(extensionVersion2,checkForUpdates){if(checkForUpdates!==!0||this.#automaticAttempted||this.#operation)return;if(!isMearlReleaseVersion(extensionVersion2)||!isMearlReleaseVersion(this.options.hostVersion)){this.options.log("Skipped Native Host update check because a release version was invalid");return}let targetVersion=extensionVersion2;if(compareMearlReleaseLines(this.options.hostVersion,targetVersion)>=0)return;this.#automaticAttempted=!0;let operation=this.options.runUpdate(targetVersion).then(()=>this.options.requestRestart()).catch(error48=>{let category=error48 instanceof NativeHostUpdateFailure?error48.updateError:"unknown";this.options.log(`Native Host automatic update failed (${category})`)}).finally(()=>{this.#operation===operation&&(this.#operation=null)});this.#operation=operation}};import fs17 from"node:fs";import path18 from"node:path";import{randomUUID as randomUUID10}from"node:crypto";import fs16 from"node:fs";import os8 from"node:os";import path17 from"node:path";import{createHash as createHash2,randomUUID as randomUUID9}from"node:crypto";import WebSocket2 from"ws";var PAGE_ACT_ACTIONS2=["page_click","page_drag","page_type","page_hover","page_scroll","page_press","page_upload","page_eval"];var OBSERVED_PAGE_ACTIONS=new Set(PAGE_ACT_ACTIONS2);import net2 from"node:net";import fs15 from"node:fs";import os7 from"node:os";import path16 from"node:path";import{createRequire as createRequire8}from"node:module";import fs13 from"node:fs";import fs14 from"node:fs";import os6 from"node:os";import path15 from"node:path";var BROWSERS_DIR=path15.join(os6.homedir(),".mearl","browsers");var require9=createRequire8(import.meta.url),CLIENT_VERSION=require9("../package.json").version,MAX_SOCKET_BUFFER_SIZE=64*1024*1024,SOCKET_PATH=process.platform==="win32"?"\\\\.\\pipe\\mearl-agent":path16.join(os7.tmpdir(),"mearl-agent.sock");import{existsSync as existsSync12,readFileSync as readFileSync9}from"node:fs";import{homedir as homedir3}from"node:os";import{join as join9}from"node:path";var MEARL_CONFIG_DIR=join9(homedir3(),".mearl");var import_extract_zip=__toESM(require_extract_zip(),1);import WebSocket3 from"ws";var MEARL_EXTENSION_DOWNLOAD_PAGE="https://mearl.alibaba-inc.com/",MEARL_EXTENSION_REMOTE_CONFIG_URL=`${MEARL_EXTENSION_DOWNLOAD_PAGE}config.json`;var MEARL_EXTENSION_ID="aoehhjnofngknnjefamjbplchbolghkm",MEARL_EXTENSION_SETUP_MARKER=".mearl-setup.json";var MAX_ARCHIVE_BYTES=64*1024*1024,SHA256_PATTERN=/^[a-f\d]{64}$/i;function extensionArchiveUrl(version2){if(!isMearlReleaseVersion(version2))throw new Error(`Invalid Mearl browser extension version: ${version2}`);return new URL(`mearl-chrome-v${version2}.zip`,MEARL_EXTENSION_DOWNLOAD_PAGE).toString()}function validateExtensionRelease(release){if(!isMearlReleaseVersion(release.version))throw new Error("Remote extension config has an invalid latestVersion");let expectedArchiveUrl=extensionArchiveUrl(release.version),archiveUrl;try{archiveUrl=new URL(release.archiveUrl).toString()}catch{throw new Error("Remote extension config has an invalid downloadUrl")}if(archiveUrl!==expectedArchiveUrl)throw new Error("Remote extension downloadUrl does not match latestVersion");if(release.sha256!==void 0&&!SHA256_PATTERN.test(release.sha256))throw new Error("Remote extension config has an invalid downloadSha256");return{archiveUrl,...release.sha256?{sha256:release.sha256.toLowerCase()}:{},version:release.version}}async function fetchBrowserExtensionRelease(fetchImpl=fetch){let response=await fetchImpl(MEARL_EXTENSION_REMOTE_CONFIG_URL,{cache:"no-store"});if(!response.ok)throw new Error(`Extension config returned HTTP ${response.status}`);let config2=await response.json();return validateExtensionRelease({archiveUrl:typeof config2.downloadUrl=="string"?config2.downloadUrl:"",...typeof config2.downloadSha256=="string"?{sha256:config2.downloadSha256}:{},version:typeof config2.latestVersion=="string"?config2.latestVersion:""})}function sameExtensionPath(left,right){let normalizedLeft=path17.normalize(path17.resolve(left)),normalizedRight=path17.normalize(path17.resolve(right));return process.platform==="win32"?normalizedLeft.toLowerCase()===normalizedRight.toLowerCase():normalizedLeft===normalizedRight}function setupMarkerPath(directory){return path17.join(directory,MEARL_EXTENSION_SETUP_MARKER)}function hasSetupMarker(targetDirectory){try{let marker=JSON.parse(fs16.readFileSync(setupMarkerPath(targetDirectory),"utf8"));return marker.schemaVersion===1&&marker.extensionId===MEARL_EXTENSION_ID&&typeof marker.path=="string"&&sameExtensionPath(marker.path,targetDirectory)}catch{return!1}}async function writeSetupMarker(directory,targetDirectory){let marker={extensionId:MEARL_EXTENSION_ID,path:path17.resolve(targetDirectory),schemaVersion:1};await fs16.promises.writeFile(setupMarkerPath(directory),`${JSON.stringify(marker,null,2)}
|
|
1309
1309
|
`,{mode:384})}async function replaceDirectory(stagingDirectory,targetDirectory){let backupDirectory=`${targetDirectory}.backup-${randomUUID9()}`,targetExists=fs16.existsSync(targetDirectory);try{targetExists&&await fs16.promises.rename(targetDirectory,backupDirectory),await fs16.promises.rename(stagingDirectory,targetDirectory)}catch(error48){throw!fs16.existsSync(targetDirectory)&&fs16.existsSync(backupDirectory)&&await fs16.promises.rename(backupDirectory,targetDirectory),error48}targetExists&&await fs16.promises.rm(backupDirectory,{force:!0,recursive:!0})}function readExtensionManifest(directory){let manifestPath=path17.join(directory,"manifest.json"),parsed;try{parsed=JSON.parse(fs16.readFileSync(manifestPath,"utf8"))}catch(error48){throw new Error(`Downloaded extension has no valid manifest.json: ${error48 instanceof Error?error48.message:error48}`,{cause:error48})}if(parsed.manifest_version!==3||typeof parsed.name!="string"||typeof parsed.key!="string"||parsed.key.length===0)throw new Error("Downloaded archive is not a valid Manifest V3 extension");if(!isMearlReleaseVersion(parsed.version))throw new Error("Downloaded extension manifest has an invalid version");return parsed}async function downloadAndReplaceExtension(releaseInput,targetDirectory,fetchImpl,extractArchive){let release=validateExtensionRelease(releaseInput),parentDirectory=path17.dirname(targetDirectory),stagingDirectory=`${targetDirectory}.staging-${randomUUID9()}`,archivePath=path17.join(parentDirectory,`.mearl-extension-${randomUUID9()}.zip`);await fs16.promises.mkdir(parentDirectory,{recursive:!0});try{let response=await fetchImpl(release.archiveUrl,{redirect:"follow"});if(!response.ok)throw new Error(`Extension archive returned HTTP ${response.status}: ${release.archiveUrl}`);if(Number(response.headers.get("content-length")??0)>MAX_ARCHIVE_BYTES)throw new Error(`Extension archive exceeds ${MAX_ARCHIVE_BYTES} bytes`);let archive=Buffer.from(await response.arrayBuffer());if(archive.length===0||archive.length>MAX_ARCHIVE_BYTES)throw new Error("Extension archive is empty or too large");if(release.sha256&&createHash2("sha256").update(archive).digest("hex")!==release.sha256)throw new Error("Extension archive SHA256 does not match remote config");await fs16.promises.writeFile(archivePath,archive,{mode:384}),await fs16.promises.mkdir(stagingDirectory,{recursive:!0}),await extractArchive(archivePath,stagingDirectory);let manifest=readExtensionManifest(stagingDirectory);if(manifest.version!==release.version)throw new Error(`Extension archive version ${String(manifest.version)} does not match ${release.version}`);return await writeSetupMarker(stagingDirectory,targetDirectory),await replaceDirectory(stagingDirectory,targetDirectory),release}finally{await fs16.promises.rm(archivePath,{force:!0}),await fs16.promises.rm(stagingDirectory,{force:!0,recursive:!0})}}async function updateSetupManagedBrowserExtensionFiles(options,dependencies={}){let targetDirectory=path17.resolve(options.targetDirectory);if(!hasSetupMarker(targetDirectory))throw new Error("The running extension is not managed by Mearl setup");let fetchImpl=dependencies.fetch??fetch,extractArchive=dependencies.extractArchive??((archivePath,destination)=>(0,import_extract_zip.default)(archivePath,{dir:destination}));return{...await downloadAndReplaceExtension(options.release,targetDirectory,fetchImpl,extractArchive),path:targetDirectory}}var EXTENSION_UPDATE_LOCK_PATH=path18.join(DAEMON_HOME,"extension-update.lock"),EXTENSION_UPDATE_LOCK_STALE_MS=10*6e4,INVALID_UPDATE_LOCK_GRACE_MS2=1e4;function readUpdateLock(lockPath){try{let stat2=fs17.lstatSync(lockPath);if(!stat2.isFile()||stat2.isSymbolicLink()||stat2.size>4096)return{modifiedAt:stat2.mtimeMs,owner:null};try{let value=JSON.parse(fs17.readFileSync(lockPath,"utf8")),owner=typeof value.id=="string"&&Number.isInteger(value.pid)&&(value.pid??0)>0&&typeof value.startedAt=="number"?value:null;return{modifiedAt:stat2.mtimeMs,owner}}catch{return{modifiedAt:stat2.mtimeMs,owner:null}}}catch{return null}}async function withExtensionUpdateLock(operation,dependencies){let lockPath=dependencies.lockPath??EXTENSION_UPDATE_LOCK_PATH,now=dependencies.now??Date.now,isProcessAlive=dependencies.isProcessAlive??isAlive;fs17.mkdirSync(path18.dirname(lockPath),{recursive:!0,mode:448});let owner={id:randomUUID10(),pid:process.pid,startedAt:now()},serializedOwner=`${JSON.stringify(owner)}
|
|
1310
1310
|
`;for(let attempt=0;attempt<2;attempt+=1)try{fs17.writeFileSync(lockPath,serializedOwner,{encoding:"utf8",flag:"wx",mode:384});break}catch(error48){if(!(error48 instanceof Error)||!("code"in error48)||error48.code!=="EEXIST")throw error48;let state=readUpdateLock(lockPath);if(!(state===null||(state.owner?now()-state.owner.startedAt>EXTENSION_UPDATE_LOCK_STALE_MS&&!isProcessAlive(state.owner.pid):now()-state.modifiedAt>INVALID_UPDATE_LOCK_GRACE_MS2))||attempt>0)throw new Error("Another extension update is already running",{cause:error48});try{fs17.unlinkSync(lockPath)}catch(unlinkError){throw new Error("Another extension update is already running",{cause:unlinkError})}}try{return await operation()}finally{try{fs17.readFileSync(lockPath,"utf8")===serializedOwner&&fs17.unlinkSync(lockPath)}catch{}}}async function updateSetupManagedExtension(request,dependencies={}){if(!isMearlReleaseVersion(request.currentVersion))throw new Error("The running extension reported an invalid version");if(!request.setupManagedPath||!path18.isAbsolute(request.setupManagedPath))throw new Error("A setup-managed extension path is required");let release=await(dependencies.fetchRelease??fetchBrowserExtensionRelease)(),changelogUrl=`https://mearl.alibaba-inc.com/changelog.html#v${release.version}`;return compareMearlReleaseVersions(release.version,request.currentVersion)<=0?{changelogUrl,updated:!1,version:request.currentVersion}:withExtensionUpdateLock(async()=>(await(dependencies.updateFiles??updateSetupManagedBrowserExtensionFiles)({release,targetDirectory:request.setupManagedPath}),{changelogUrl,updated:!0,version:release.version}),dependencies)}init_runtimeArgs();var OPEN_SANDBOX_PORT_PLACEHOLDER="{port}",AONE_PORT_MAPPING_URL="http://127.0.0.1:58596/api/port-mapping";function normalizeBrowserAccessUrl(value){if(typeof value!="string"||!value.trim())return null;let input2=/^[a-z][a-z\d+.-]*:\/\//i.test(value.trim())?value.trim():`https://${value.trim()}`;try{let parsed=new URL(input2);return parsed.protocol==="ws:"&&(parsed.protocol="http:"),parsed.protocol==="wss:"&&(parsed.protocol="https:"),!["http:","https:"].includes(parsed.protocol)||!parsed.hostname?null:parsed.toString()}catch{return null}}function resolveSandboxBrowserAccessCapability(env=process.env){return env.OPENSANDBOX_ID?.trim()?{kind:"sandbox-novnc",environment:"opensandbox",port:6080}:env.AONE_SANDBOX_ID?.trim()?{kind:"sandbox-novnc",environment:"aone",port:6080}:null}function resolveOpenSandboxBrowserAccessUrl(port,env=process.env){if(!env.OPENSANDBOX_ID?.trim())return null;let template=env.AONE_SANDBOX_ENDPOINT_TEMPLATE?.trim();return template?.includes(OPEN_SANDBOX_PORT_PLACEHOLDER)?normalizeBrowserAccessUrl(template.replaceAll(OPEN_SANDBOX_PORT_PLACEHOLDER,String(port))):null}async function resolveAoneBrowserAccessUrl(port,dependencies){let response=await(dependencies.fetch??globalThis.fetch)(`${AONE_PORT_MAPPING_URL}?port=${port}`,{signal:AbortSignal.timeout(5e3)});if(!response.ok)throw new Error(`AONE Sandbox port mapping failed with HTTP ${response.status}`);let payload=await response.json(),url2=payload.success?normalizeBrowserAccessUrl(payload.url):null;if(!url2)throw new Error(`AONE Sandbox did not return a browser access URL for port ${port}`);return url2}async function resolveSandboxBrowserAccess(dependencies={}){let env=dependencies.env??process.env,capability=resolveSandboxBrowserAccessCapability(env);if(!capability)throw new Error("The selected browser is not running in a supported sandbox");if(capability.environment==="opensandbox"){let url3=resolveOpenSandboxBrowserAccessUrl(capability.port,env);if(url3)return{...capability,url:url3};if(!env.AONE_SANDBOX_ID?.trim())throw new Error("OpenSandbox browser access is unavailable because AONE_SANDBOX_ENDPOINT_TEMPLATE is missing or invalid")}let url2=await resolveAoneBrowserAccessUrl(capability.port,dependencies);return{...capability,environment:"aone",url:url2}}import fs18 from"node:fs";import os9 from"node:os";import path19 from"node:path";var AGENTBAY_ENV_KEY="AGENTBAY_KEY",AGENTBAY_ENV_LINE=/^\s*(?:export\s+)?AGENTBAY_KEY\s*=/;function normalizeApiKey(apiKey){let value=apiKey.trim();if(!value)throw new Error("AgentBay API key is required.");if(/[\r\n\0]/.test(value))throw new Error("AgentBay API key must be a single-line value.");return value}function updateEnvContent(content,apiKey){let newline=content.includes(`\r
|
|
1311
1311
|
`)?`\r
|
|
1312
1312
|
`:`
|
|
1313
|
-
`,lines=content?content.split(/\r?\n/):[];lines.at(-1)===""&&lines.pop();let entry=`${AGENTBAY_ENV_KEY}=${apiKey}`,output2=[],updated=!1;for(let line of lines){if(!AGENTBAY_ENV_LINE.test(line)){output2.push(line);continue}updated||output2.push(entry),updated=!0}return updated||output2.push(entry),{content:`${output2.join(newline)}${newline}`,updated}}function configureAgentBayApiKey(apiKey,options={}){let value=normalizeApiKey(apiKey),envFile=options.envFile??path19.join(os9.homedir(),".mearl",".env"),current="";try{current=fs18.readFileSync(envFile,"utf8")}catch(error48){if(!(error48 instanceof Error&&"code"in error48&&error48.code==="ENOENT"))throw error48}let next=updateEnvContent(current,value);return fs18.mkdirSync(path19.dirname(envFile),{recursive:!0,mode:448}),fs18.writeFileSync(envFile,next.content,{encoding:"utf8",mode:384}),fs18.chmodSync(envFile,384),{envFile,updated:next.updated}}import fs20 from"node:fs";import path21 from"node:path";import{createInterface}from"node:readline/promises";import{stdin as input,stdout as output}from"node:process";init_nativeHost();init_nativeHost();import{existsSync as existsSync13}from"node:fs";import{dirname as dirname7,join as join10,resolve as resolve4}from"node:path";function configureAgentBayKey(data,configure=configureAgentBayApiKey){if(typeof data?.apiKey!="string"||!data.apiKey.trim())throw new Error("AgentBay API key is required.");return{configured:!0,updated:configure(data.apiKey).updated}}function listBrowserProviders(){return{providers:listInstalledProviders().map(provider=>({providerId:provider.providerId,providerName:provider.name,browserType:provider.browserType}))}}function launchParameters(browserType,value){let inputValue=value??{};if(!inputValue||typeof inputValue!="object"||Array.isArray(inputValue))throw new Error("providerOptions must be an object");let input2=inputValue,definitions=new Map(browserType.parameters.map(parameter=>[parameter.key,parameter]));for(let key of Object.keys(input2))if(!definitions.has(key))throw new Error(`Unknown Provider parameter: ${key}`);let parameters={};for(let parameter of browserType.parameters){let raw=input2[parameter.key];if(raw!==void 0&&typeof raw!="string")throw new Error(`Provider parameter ${parameter.key} must be a string`);let parameterValue=raw?.trim()??"";if(parameter.required&&!parameterValue)throw new Error(`Provider parameter ${parameter.key} is required`);parameterValue&&(parameters[parameter.key]=parameterValue)}return parameters}function isValidPairing(value){if(!value||typeof value!="object"||Array.isArray(value))return!1;let pairing=value;return pairing.kind==="qr"&&typeof pairing.url=="string"&&pairing.url.trim().length>0&&(pairing.code===void 0||typeof pairing.code=="string")&&(pairing.label===void 0||typeof pairing.label=="string")}async function launchProviderBrowser(data){let providerId=typeof data.provider=="string"?data.provider.trim():"",provider=listInstalledProviders().find(item=>item.providerId===providerId);if(!provider)throw new Error(`Provider is not registered: ${providerId}`);let unsupported=Object.keys(data).filter(key=>key!=="provider"&&key!=="providerOptions");if(unsupported.length>0)throw new Error(`External Provider does not accept: ${unsupported.join(", ")}`);let parameters=launchParameters(provider.browserType,data.providerOptions),warnings=await ensureInstalledProvidersRunning(),live=readLiveProvider(providerId);if(!live){let warning=warnings.find(item=>item.startsWith(`provider ${providerId}:`));throw new Error(warning??`Provider did not start: ${providerId}`)}let result=await requestBrowserSocket(live.socketPath,"browser_launch",parameters,NATIVE_HOST_VERSION),resultRecord=result,status=resultRecord?.status,pairing=resultRecord?.pairing;if(!result||typeof result!="object"||Array.isArray(result)||typeof resultRecord?.browserId!="string"||!resultRecord.browserId.trim()||typeof resultRecord.name!="string"||!resultRecord.name.trim()||!["connected","pairing"].includes(String(status))||status==="pairing"&&!isValidPairing(pairing)||status!=="pairing"&&pairing!==void 0)throw new Error(`Provider ${providerId} returned an invalid browser creation result`);let created=resultRecord;return{...created,browserId:providerBrowserKey(providerId,created.browserId)}}function findProviderBrowser(selector){let normalized=selector.toLowerCase(),exact=listRegisteredBrowsers().filter(browser=>browser.transport==="provider").filter(browser=>browser.browserId.toLowerCase()===normalized||browser.providerBrowserId?.toLowerCase()===normalized||browser.browserName.toLowerCase()===normalized);if(exact.length>1)throw new Error(`Provider browser selector is ambiguous: ${selector}`);return exact[0]??null}function deleteProviderBrowser(browser){if(browser.transport!=="provider"||!browser.providerBrowserId)throw new Error(`Browser is not managed by an external Provider: ${browser.browserId}`);return requestBrowserSocket(browser.socketPath,"browser_close",{},NATIVE_HOST_VERSION,6e4,browser.providerBrowserId)}var cliArgs=process.argv.slice(2),cliArg=cliArgs[0];if(cliArg==="--init"||cliArg==="--uninstall"||cliArg==="init"||cliArg==="uninstall"){let{runCli:runCli2}=await Promise.resolve().then(()=>(init_install(),install_exports));process.exit(await runCli2(cliArgs))}function printCliHelp(){console.error(`mearl-native-host v${NATIVE_HOST_VERSION}
|
|
1313
|
+
`,lines=content?content.split(/\r?\n/):[];lines.at(-1)===""&&lines.pop();let entry=`${AGENTBAY_ENV_KEY}=${apiKey}`,output2=[],updated=!1;for(let line of lines){if(!AGENTBAY_ENV_LINE.test(line)){output2.push(line);continue}updated||output2.push(entry),updated=!0}return updated||output2.push(entry),{content:`${output2.join(newline)}${newline}`,updated}}function configureAgentBayApiKey(apiKey,options={}){let value=normalizeApiKey(apiKey),envFile=options.envFile??path19.join(os9.homedir(),".mearl",".env"),current="";try{current=fs18.readFileSync(envFile,"utf8")}catch(error48){if(!(error48 instanceof Error&&"code"in error48&&error48.code==="ENOENT"))throw error48}let next=updateEnvContent(current,value);return fs18.mkdirSync(path19.dirname(envFile),{recursive:!0,mode:448}),fs18.writeFileSync(envFile,next.content,{encoding:"utf8",mode:384}),fs18.chmodSync(envFile,384),{envFile,updated:next.updated}}import fs20 from"node:fs";import path21 from"node:path";import{createInterface}from"node:readline/promises";import{stdin as input,stdout as output}from"node:process";init_nativeHost();init_nativeHost();import{existsSync as existsSync13}from"node:fs";import{dirname as dirname7,join as join10,resolve as resolve4}from"node:path";function configureAgentBayKey(data,configure=configureAgentBayApiKey){if(typeof data?.apiKey!="string"||!data.apiKey.trim())throw new Error("AgentBay API key is required.");return{configured:!0,updated:configure(data.apiKey).updated}}import net3 from"node:net";import{chmodSync,rmSync as rmSync4}from"node:fs";import{dirname as dirname8}from"node:path";var MAX_REQUEST_BYTES=16*1024*1024;var commonLaunchProperties={name:{type:"string",minLength:1},persistent:{type:"boolean",default:!0},copyCookieDomains:{type:"object",properties:{presets:{type:"array",items:{type:"string",enum:["mearl-services"]}},domains:{type:"array",items:{type:"string",minLength:1}}}}};function connectedBrowserIds(){return new Set(listRegisteredBrowsers().filter(browser=>browser.status===void 0||browser.status==="connected").map(browser=>browser.browserId))}function commonDetails(browser){return{headless:browser.headless,createdAt:browser.createdAt,...browser.copiedCookies?{copiedCookies:{domains:browser.copiedCookies.domains,count:browser.copiedCookies.count}}:{},..."account"in browser&&browser.account?{account:{nickname:browser.account.nickname,...browser.account.accountId?{accountId:browser.account.accountId}:{},...browser.account.loginId?{loginId:browser.account.loginId}:{}}}:{}}}function localBrowser(browser,connected){let stopped=!browser.running;return{browserId:browser.browserId,name:browser.name,status:stopped?"stopped":connected.has(browser.browserId)?"connected":"running_disconnected",control:stopped?{kind:"none"}:{kind:"host",transport:"cdp",browserId:browser.browserId},ownership:"owned",persistence:browser.persistent?"persistent":"ephemeral",operations:stopped?["start","deleteData"]:["close","deleteData"],references:[{kind:"profile",id:browser.browserId,label:"Profile"}],details:{...commonDetails(browser),cdpPort:browser.cdpPort}}}function agentBayBrowser(browser,connected){let stopped=!browser.running,attached=browser.agentbaySessionMode==="attached",operations=stopped?["start",...attached?[]:["deleteData"]]:attached?["detach","access","syncCookies"]:["close","deleteData","access","syncCookies"];return{browserId:browser.browserId,name:browser.name,status:stopped?"stopped":connected.has(browser.browserId)?"connected":"running_disconnected",control:stopped?{kind:"none"}:{kind:"host",transport:"cdp",browserId:browser.browserId},ownership:attached?"attached":"owned",persistence:browser.persistent?"persistent":"ephemeral",operations,references:[{kind:"session",id:browser.agentbaySessionId,label:"Session ID"},...browser.agentbayImageId?[{kind:"image",id:browser.agentbayImageId,label:"Image ID"}]:[],...browser.agentbayContextId?[{kind:"context",id:browser.agentbayContextId,label:"Context ID"}]:[],...browser.agentbayContextName?[{kind:"context-name",id:browser.agentbayContextName,label:"Context Name"}]:[]],details:commonDetails(browser)}}function localDefinition(deps){return{descriptor:{providerId:"local",name:"Local Chrome",version:NATIVE_HOST_VERSION,protocolVersion:2,builtin:!0},browserType:{name:"本地浏览器",inputSchema:{type:"object",required:["name"],additionalProperties:!0,properties:{...commonLaunchProperties,headless:{type:"boolean",default:!0}}}},listBrowsers:()=>{let connected=connectedBrowserIds();return listManagedBrowsers().map(browser=>localBrowser(browser,connected))},launch:async options=>{let summary=await launchManagedBrowser(options,{nativeHostScript:deps.nativeHostScript,prepareTdbankSso:deps.prepareTdbankSso,exportCookies:deps.exportCookies,log:deps.log});return localBrowser(summary,connectedBrowserIds())},start:async({browserId})=>{let summary=listManagedBrowsers().find(browser=>browser.browserId===browserId);if(!summary)throw new Error(`Local browser not found: ${browserId}`);let launched=await launchManagedBrowser({name:summary.name,persistent:summary.persistent,headless:summary.headless},{nativeHostScript:deps.nativeHostScript,prepareTdbankSso:deps.prepareTdbankSso,exportCookies:deps.exportCookies,log:deps.log});return localBrowser(launched,connectedBrowserIds())},close:({browserId,deleteData})=>closeManagedBrowser(browserId,{deleteProfile:deleteData})}}function agentBayDefinition(deps){let managerDeps={nativeHostScript:deps.nativeHostScript,exportCookies:deps.exportCookies,getBrowserUserAgent:deps.getBrowserUserAgent,log:deps.log};return{descriptor:{providerId:"agentbay",name:"AgentBay",version:NATIVE_HOST_VERSION,protocolVersion:2,builtin:!0},browserType:{name:"AgentBay",documentationUrl:"https://alidocs.dingtalk.com/i/nodes/93NwLYZXWyxXroNzCkyONLoN8kyEqBQm",inputSchema:{type:"object",properties:{},additionalProperties:!0,oneOf:[{type:"object",title:"Create session",required:["name"],additionalProperties:!0,not:{type:"object",properties:{sessionId:{type:"string"}},required:["sessionId"],additionalProperties:!0},properties:commonLaunchProperties},{type:"object",title:"Attach session",required:["sessionId"],properties:{name:commonLaunchProperties.name,sessionId:{type:"string",minLength:1},copyCookieDomains:commonLaunchProperties.copyCookieDomains,url:{type:"string"}}}]},configuration:{inputSchema:{type:"object",required:["apiKey"],properties:{apiKey:{type:"string",title:"AgentBay API Key",secret:!0,minLength:1}}}}},listBrowsers:()=>{let connected=connectedBrowserIds();return listAgentBayBrowsers().map(browser=>agentBayBrowser(browser,connected))},launch:async options=>{let summary=await launchAgentBayBrowser(options,managerDeps);return agentBayBrowser(summary,connectedBrowserIds())},start:async({browserId})=>{let summary=listAgentBayBrowsers().find(browser=>browser.browserId===browserId);if(!summary)throw new Error(`AgentBay browser not found: ${browserId}`);let options=summary.agentbaySessionMode==="attached"?{sessionId:summary.agentbaySessionId,name:summary.name}:{name:summary.name,reuse:"prefer",persistent:summary.persistent,imageId:summary.agentbayImageId},launched=await launchAgentBayBrowser(options,managerDeps);return agentBayBrowser(launched,connectedBrowserIds())},close:({browserId,deleteData})=>closeAgentBayBrowser(browserId,{deleteProfile:deleteData}),detach:({browserId})=>deps.detachAgentBay(browserId),syncCookies:async({browserId,scope})=>{let summary=listAgentBayBrowsers().find(browser=>browser.browserId===browserId);if(!summary)throw new Error(`AgentBay browser not found: ${browserId}`);let options=summary.agentbaySessionMode==="attached"?{sessionId:summary.agentbaySessionId,name:summary.name,copyCookieDomains:scope}:{name:summary.name,reuse:"require",persistent:summary.persistent,imageId:summary.agentbayImageId,copyCookieDomains:scope},synced=await launchAgentBayBrowser(options,managerDeps);return agentBayBrowser(synced,connectedBrowserIds())},getAccess:async({browserId})=>({kind:"agentbay",url:await getManagedAgentBayAccessUrl(browserId),sensitive:!0}),configure:async options=>deps.configureAgentBay(String(options.apiKey??""))}}function createBuiltinBrowserProviders(deps){return[createProviderRuntime(localDefinition(deps)),createProviderRuntime(agentBayDefinition(deps))]}function listExternalBrowserProviders(){return listInstalledProviders().map(provider=>({provider:{id:provider.providerId,name:provider.name,builtin:!1,version:provider.version,protocolVersion:provider.protocolVersion},browserType:provider.browserType}))}async function requireLiveProvider(providerId){let warnings=await ensureInstalledProvidersRunning(),live=readLiveProvider(providerId);if(!live){let warning=warnings.find(item=>item.startsWith(`provider ${providerId}:`));throw new Error(warning??`Provider did not start: ${providerId}`)}return{socketPath:live.socketPath}}async function launchProviderBrowser(input2){let providerId=input2.provider.trim();if(!listInstalledProviders().find(item=>item.providerId===providerId))throw new Error(`Provider is not registered: ${providerId}`);let live=await requireLiveProvider(providerId),result=await requestBrowserSocket(live.socketPath,"browser_launch",input2.providerOptions,NATIVE_HOST_VERSION);return validateProviderBrowser(result),{...result,browserId:providerBrowserKey(providerId,result.browserId)}}function findProviderBrowser(selector){let normalized=selector.toLowerCase(),exact=listRegisteredBrowsers().filter(browser=>browser.transport==="provider").filter(browser=>browser.browserId.toLowerCase()===normalized||browser.providerBrowserId?.toLowerCase()===normalized||browser.browserName.toLowerCase()===normalized);if(exact.length>1)throw new Error(`Provider browser selector is ambiguous: ${selector}`);return exact[0]??null}function requireProviderBrowser(browser){if(browser.transport!=="provider"||!browser.providerBrowserId)throw new Error(`Browser is not managed by an external Provider: ${browser.browserId}`);return browser.providerBrowserId}function closeProviderBrowser(browser,options={}){return requestBrowserSocket(browser.socketPath,"browser_close",{deleteProfile:options.deleteProfile===!0},NATIVE_HOST_VERSION,6e4,requireProviderBrowser(browser))}function detachProviderBrowser(browser){return requestBrowserSocket(browser.socketPath,"browser_release",{},NATIVE_HOST_VERSION,6e4,requireProviderBrowser(browser))}async function accessProviderBrowser(browser){return(await requestBrowserSocket(browser.socketPath,"get_browser_access_url",{},NATIVE_HOST_VERSION,6e4,requireProviderBrowser(browser))).browserAccess}async function startProviderBrowser(browser){let result=await requestBrowserSocket(browser.socketPath,"browser_manager_start",{},NATIVE_HOST_VERSION,12e4,requireProviderBrowser(browser));return validateProviderBrowser(result),{...result,browserId:browser.browserId}}function syncProviderBrowserCookies(browser,scope){return requestBrowserSocket(browser.socketPath,"browser_manager_sync_cookies",{scope},NATIVE_HOST_VERSION,12e4,requireProviderBrowser(browser))}async function configureProvider(providerId,options){if(!listInstalledProviders().find(item=>item.providerId===providerId)?.browserType.configuration)throw new Error(`Provider does not support configuration: ${providerId}`);let live=await requireLiveProvider(providerId);return requestBrowserSocket(live.socketPath,"browser_provider_configure",options,NATIVE_HOST_VERSION)}var BrowserProviderCoordinator=class{constructor(runtimes){this.runtimes=runtimes}definitions(){return{providers:[...this.runtimes.map(runtime=>{let descriptor=runtime.definition.descriptor;return{provider:providerIdentity(descriptor),browserType:runtime.definition.browserType}}),...listExternalBrowserProviders()]}}get providerRuntimes(){return this.runtimes}async launch(input2){if(input2.sessionId!==void 0&&input2.provider!==void 0&&input2.provider!=="agentbay")throw new Error('sessionId requires provider="agentbay" when provider is specified');let providerId=input2.sessionId!==void 0?"agentbay":input2.provider?.trim()||"local",runtime=this.runtimes.find(item=>item.definition.descriptor.providerId===providerId),builtinOptions={...input2};if(delete builtinOptions.provider,delete builtinOptions.providerOptions,input2.providerOptions&&Object.keys(builtinOptions).length>0)throw new Error("Use either providerOptions or flat launch options, not both");if(runtime){let descriptor=runtime.definition.descriptor,options={...input2.providerOptions??builtinOptions};return Array.isArray(options.copyCookieDomains)&&(options.copyCookieDomains={domains:options.copyCookieDomains}),options.copyCookieDomains==="mearl-services"&&(options.copyCookieDomains={presets:["mearl-services"]}),providerBrowserInfo({provider:providerIdentity(descriptor),browser:await runtime.launch(options)})}let external=listExternalBrowserProviders().find(provider=>provider.provider.id===providerId);if(!external)throw new Error(`Provider is not registered: ${providerId}`);if(Object.keys(builtinOptions).length>0)throw new Error("External Provider launch options must be supplied in providerOptions");return providerBrowserInfo({provider:external.provider,browser:await launchProviderBrowser({provider:providerId,providerOptions:input2.providerOptions??{}})})}async close(selector,deleteProfile=!1){let match=await this.requireOne(selector);return"external"in match?closeProviderBrowser(match.external,{deleteProfile}):match.runtime.close({browserId:match.browser.browserId,deleteData:deleteProfile})}async start(selector){let match=await this.requireOne(selector);if("external"in match){if(!match.external.provider)throw new Error("Provider identity is missing");return providerBrowserInfo({provider:match.external.provider,browser:await startProviderBrowser(match.external)})}let descriptor=match.runtime.definition.descriptor;return providerBrowserInfo({provider:providerIdentity(descriptor),browser:await match.runtime.start({browserId:match.browser.browserId})})}async syncCookies(selector,scope){let match=await this.requireOne(selector);return"external"in match?syncProviderBrowserCookies(match.external,scope):match.runtime.syncCookies({browserId:match.browser.browserId,scope})}async access(selector){let match=await this.requireOne(selector);return{browserAccess:"runtime"in match?await match.runtime.getAccess({browserId:match.browser.browserId}):await accessProviderBrowser(match.external)}}async detach(selector){let match=await this.requireOne(selector);return"runtime"in match?match.runtime.detach({browserId:match.browser.browserId}):detachProviderBrowser(match.external)}async configure(providerId,options){let runtime=this.runtimes.find(item=>item.definition.descriptor.providerId===providerId);return runtime?runtime.configure(options):configureProvider(providerId,options)}async findRuntimeBrowsers(selector){let normalized=selector.trim().toLowerCase();return(await Promise.all(this.runtimes.map(async runtime=>(await runtime.listBrowsers()).map(browser=>({runtime,browser}))))).flat().filter(entry=>entry.browser.browserId.toLowerCase()===normalized||entry.browser.name.toLowerCase()===normalized)}async requireOne(selector){let matches=await this.findRuntimeBrowsers(selector),external=findProviderBrowser(selector);if(matches.length+ +!!external>1)throw new Error(`Browser name is ambiguous: ${selector}. Use the full browserId from browser_list.`);if(matches[0])return matches[0];if(external)return{external};throw new Error(`Provider browser not found: ${selector}`)}};var cliArgs=process.argv.slice(2),cliArg=cliArgs[0];if(cliArg==="--init"||cliArg==="--uninstall"||cliArg==="init"||cliArg==="uninstall"){let{runCli:runCli2}=await Promise.resolve().then(()=>(init_install(),install_exports));process.exit(await runCli2(cliArgs))}function printCliHelp(){console.error(`mearl-native-host v${NATIVE_HOST_VERSION}
|
|
1314
1314
|
|
|
1315
1315
|
Usage:
|
|
1316
1316
|
mearl-native-host [runtime-options]
|
|
@@ -1355,8 +1355,8 @@ Examples:
|
|
|
1355
1355
|
mearl-native-host --daemon
|
|
1356
1356
|
mearl-native-host --version`)}!cliArg&&process.stdin.isTTY&&(printCliHelp(),process.exit(0));var runtimeArgs={agentBayAttachment:!1,browserId:"cdp",browserHeadless:!1,browserName:"CDP",cdpPort:9222,daemon:!1,discoverCdp:!1,help:!1,skipBrowserRegistration:!1,version:!1};if(cliArgs.length>0)try{let{parseNativeHostRuntimeArgs:parseNativeHostRuntimeArgs2}=await Promise.resolve().then(()=>(init_runtimeArgs(),runtimeArgs_exports));runtimeArgs=await parseNativeHostRuntimeArgs2(cliArgs,3)}catch(error48){console.error(`Error: ${error48 instanceof Error?error48.message:String(error48)}`),printCliHelp(),process.exit(2)}runtimeArgs.version&&(console.log(NATIVE_HOST_VERSION),process.exit(0));runtimeArgs.help&&(printCliHelp(),process.exit(0));var isDaemonMode=runtimeArgs.daemon,discoverCdp=runtimeArgs.discoverCdp,skipBrowserRegistration=runtimeArgs.skipBrowserRegistration,CDP_PORT=runtimeArgs.cdpPort,CDP_USER_DATA_DIR=runtimeArgs.cdpUserDataDir,AGENTBAY_SESSION_ID=runtimeArgs.agentBaySessionId,AGENTBAY_ATTACHMENT=runtimeArgs.agentBayAttachment,AGENTBAY_IDLE_RELEASE_MINUTES=runtimeArgs.agentBayIdleReleaseMinutes,BROWSER_HEADLESS=runtimeArgs.browserHeadless,CDP_BROWSER_ID=runtimeArgs.browserId,CDP_BROWSER_NAME=runtimeArgs.browserName;function socketPathFor(suffix){return process.platform==="win32"?`\\\\.\\pipe\\mearl-agent${suffix}`:path24.join(os11.tmpdir(),`mearl-agent${suffix}.sock`)}var LEGACY_SOCKET_PATH=socketPathFor(""),INSTANCE_SOCKET_PATH=socketPathFor(`-${process.pid}`),LOG_FILE=path24.join(os11.tmpdir(),"mearl-native-host.log"),DEFAULT_TIMEOUT_MS=15e3,INVENTORY_IDLE_EXIT_MS=1e3,DISCOVERY_REQUEST_IDLE_EXIT_MS=5e3,MAX_SOCKET_BUFFER_SIZE2=64*1024*1024,extensionVersion=null,versionWarningEmitted=!1,cdpPermissionNoticeLogged=!1,EXTENSION_INSTALL_URL="https://chromewebstore.google.com/detail/mearl/aoehhjnofngknnjefamjbplchbolghkm";function majorMinor(version2){let parts=version2.split(".");return parts.length>=2?`${parts[0]}.${parts[1]}`:version2}function extractChromeVersion(input2){let match=/Chrome\/([\d.]+)/.exec(input2);return match?match[1].split(".").slice(0,3).join("."):null}async function fetchCdpBrowserVersion(){if(AGENTBAY_SESSION_ID)try{return(await(await getCdpSession().getBrowserClient()).sendCommand("Browser.getVersion",{},5e3)).product??null}catch{return null}let port=readDevToolsActivePort(CDP_USER_DATA_DIR)?.port??CDP_PORT;return new Promise(resolve5=>{let req=http4.get(`http://localhost:${port}/json/version`,res=>{let data="";res.on("data",chunk=>data+=chunk),res.on("end",()=>{try{let info=JSON.parse(data);resolve5(info.Browser??null)}catch{resolve5(null)}})});req.on("error",()=>resolve5(null)),req.setTimeout(2e3,()=>{req.destroy(),resolve5(null)})})}async function getCurrentBrowserUserAgent(){if(extensionVersion!==null)try{let result=await sendRequestToExtension("get_browser_info",{},3e3,!0);if(result.userAgent?.trim())return result.userAgent}catch{}try{let result=await(await getCdpSession().getBrowserClient()).sendCommand("Browser.getVersion",{},5e3);if(result.userAgent?.trim())return result.userAgent}catch{}throw new Error("Could not determine the control browser user agent for userAgentMode=desktop")}function currentBrowserSupportsSandboxAccess(){return!BROWSER_HEADLESS}function resolveBrowserAccessCapability(){return AGENTBAY_SESSION_ID?{kind:"agentbay"}:currentBrowserSupportsSandboxAccess()?resolveSandboxBrowserAccessCapability():null}async function resolveBrowserAccess(){let capability=resolveBrowserAccessCapability();if(!capability)throw new Error("The selected browser does not expose a browser access URL");if(capability.kind==="agentbay"){if(!AGENTBAY_SESSION_ID)throw new Error("The selected browser is not an AgentBay browser");return{kind:"agentbay",url:await getAgentBayAccessUrl(AGENTBAY_SESSION_ID)}}return resolveSandboxBrowserAccess()}async function collectVersions(includeInstallationInfo=!1){let browserAccess=resolveBrowserAccessCapability(),info={nativeHost:NATIVE_HOST_VERSION,extension:extensionVersion,browser:null,...browserAccess?{browserAccess}:{}};if(extensionVersion!==null)try{let browserInfo=await sendRequestToExtension("get_browser_info",{},3e3,!0);browserInfo?.userAgent&&(info.browser=extractChromeVersion(browserInfo.userAgent)),browserInfo?.extensionVersion&&(info.extension=browserInfo.extensionVersion),includeInstallationInfo&&(browserInfo?.extensionId&&(info.extensionId=browserInfo.extensionId),(typeof browserInfo?.setupManagedPath=="string"||browserInfo?.setupManagedPath===null)&&(info.setupManagedPath=browserInfo.setupManagedPath))}catch{}if(!info.browser){let cdpBrowser=await fetchCdpBrowserVersion();cdpBrowser&&(info.browser=extractChromeVersion(cdpBrowser))}return info}function buildVersionWarning(clientVersion){let versions=[clientVersion?{name:"client",version:clientVersion}:null,{name:"native-host",version:NATIVE_HOST_VERSION},extensionVersion?{name:"extension",version:extensionVersion}:null].filter(Boolean);return new Set(versions.map(v=>majorMinor(v.version))).size<=1?null:["⚠️ Mearl version mismatch detected:",versions.map(v=>` - ${v.name}: ${v.version}`).join(`
|
|
1357
1357
|
`),"","This may cause unexpected behavior. To update:"," npx @mearl/setup update --local",` Browser extension: ${EXTENSION_INSTALL_URL}`].join(`
|
|
1358
|
-
`)}var pendingRequests=new Map,nativeMessageBuffer=Buffer.alloc(0),socketServer=null,legacyServer=null,inventoryExitTimer=null,cdpRegistrationTimer=null,cdpBrowserPublished=!1,agentBaySessionWatchdog=null;function cancelInventoryExit(){inventoryExitTimer&&(clearTimeout(inventoryExitTimer),inventoryExitTimer=null)}function scheduleInventoryExit(delayMs=INVENTORY_IDLE_EXIT_MS){cancelInventoryExit(),inventoryExitTimer=setTimeout(()=>cleanupAndExit(0),delayMs),inventoryExitTimer.unref()}var cdpSession=null;function getCdpSession(){return cdpSession||(cdpSession=AGENTBAY_SESSION_ID?new CdpSession({endpointResolver:()=>resolveAgentBayEndpoint(AGENTBAY_SESSION_ID)}):new CdpSession({port:CDP_PORT,userDataDir:CDP_USER_DATA_DIR})),cdpSession}function log2(...args){let msg=`[${new Date().toISOString()}] [NativeHost] ${args.join(" ")}
|
|
1359
|
-
`;try{fs23.appendFileSync(LOG_FILE,msg)}catch{}}function sendToExtension(message){let json2=JSON.stringify(message),length=Buffer.byteLength(json2,"utf-8"),header=Buffer.alloc(4);header.writeUInt32LE(length,0),process.stdout.write(header),process.stdout.write(json2)}var nativeHostUpdateCoordinator=new NativeHostUpdateCoordinator({hostVersion:NATIVE_HOST_VERSION,log:log2,runUpdate:targetVersion=>runNativeHostUpdate(targetVersion),requestRestart:()=>{restartAfterUpdate()}}),agentChatManager=null,agentSkillManager=new AgentSkillManager;function getAgentChatManager(){return agentChatManager||(agentChatManager=new AgentChatManager([new CodexAgentProvider(log2,NATIVE_HOST_VERSION,INSTANCE_SOCKET_PATH),new QoderAgentProvider(log2,NATIVE_HOST_VERSION)],event=>{sendToExtension({type:"agent_chat_event",data:event})})),agentChatManager}var agentServiceHandlers={agent_chat_pick_directory:async()=>({path:await pickWorkspaceDirectory()}),agent_chat_status:()=>getAgentChatManager().getStatus(),agent_chat_prepare:async data=>(await getAgentChatManager().prepare(data),{ok:!0}),agent_chat_list_sessions:data=>getAgentChatManager().listSessions(data),agent_chat_start:data=>getAgentChatManager().startSession(data),agent_chat_send:data=>getAgentChatManager().sendMessage(data),agent_chat_interrupt:async data=>(await getAgentChatManager().interrupt(data),{ok:!0}),agent_chat_close:async data=>(await getAgentChatManager().closeSession(data),{ok:!0}),agent_chat_events:data=>getAgentChatManager().getEvents(data),agent_chat_refresh:data=>getAgentChatManager().refreshSession(data),agent_chat_open_app:async data=>(await getAgentChatManager().openSession(data),{ok:!0}),agent_chat_respond:data=>(getAgentChatManager().respondToRequest(data),{ok:!0}),agent_skills_installed:async data=>{let[cli,skills]=await Promise.all([agentSkillManager.getStatus(),getAgentChatManager().listSkills(data)]);return{cli,skills}},agent_skills_read:data=>getAgentChatManager().readSkill(data),agent_skills_install:data=>agentSkillManager.install(data),agent_skills_check_updates:data=>agentSkillManager.checkUpdates(data),agent_skills_update:data=>agentSkillManager.update(data),agent_skills_uninstall:data=>agentSkillManager.uninstall(data)};function dispatchAgentServiceAction(action,request){let handler=agentServiceHandlers[action];return Promise.resolve(handler(request))}async function launchBrowser(data){let provider=typeof data?.provider=="string"?data.provider.trim():void 0;if(provider&&provider!=="local"&&provider!=="agentbay")return launchProviderBrowser(data);let exportCookies=extensionVersion!==null?async domains=>(await sendRequestToExtension("__export_cookies",{domains},2e4,!0)).cookies??[]:domains=>cdpExportCookies(getCdpSession(),domains);if(data?.sessionId!==void 0&&data?.provider!==void 0&&data.provider!=="agentbay")throw new Error('sessionId requires provider="agentbay" when provider is specified');if(data?.provider==="agentbay"||data?.sessionId!==void 0){let name2=typeof data?.name=="string"?data.name.trim():"";if(name2&&hasManagedBrowser(name2))throw new Error(`Managed browser name is already used by the local provider: ${name2}. Choose a unique name.`);return launchAgentBayBrowser(data,{nativeHostScript:fileURLToPath5(import.meta.url),exportCookies,getBrowserUserAgent:getCurrentBrowserUserAgent,log:log2})}if(data?.provider!==void 0&&data.provider!=="local")throw new Error('provider must be "local" or "agentbay"');let name=typeof data?.name=="string"?data.name.trim():"";if(name&&hasAgentBayBrowser(name))throw new Error(`Managed browser name is already used by the AgentBay provider: ${name}. Choose a unique name.`);let prepareTdbankSso=extensionVersion!==null?payload=>sendRequestToExtension("__tdbank_prepare_sso",payload,2e4,!0):payload=>cdpPrepareTdbankSso(getCdpSession(),payload);return launchManagedBrowser(data,{nativeHostScript:fileURLToPath5(import.meta.url),prepareTdbankSso,exportCookies,log:log2})}async function closeBrowser(data){let selector=String(data?.browser??data?.browserId??data?.name??"").trim();if(!selector)throw new Error("browser is required");let localExists=hasManagedBrowser(selector),agentBayExists=hasAgentBayBrowser(selector),providerBrowser=findProviderBrowser(selector);if([localExists,agentBayExists,!!providerBrowser].filter(Boolean).length>1)throw new Error(`Browser name is ambiguous: ${selector}. Use the full browserId from browser_list.`);return providerBrowser?deleteProviderBrowser(providerBrowser):agentBayExists?closeAgentBayBrowser(selector,{deleteProfile:data?.deleteProfile}):closeManagedBrowser(selector,{deleteProfile:data?.deleteProfile})}async function releaseManagedBrowserAttachment(data){let selector=String(data?.browser??data?.browserId??"").trim();if(!selector)throw new Error("browser is required");let record2=listRegisteredBrowsers().find(browser=>browser.browserId===selector);if(!record2)throw new Error(`Browser is not connected: ${selector}`);if(!record2.browserId.startsWith("managed:agentbay:session:"))throw new Error("Only an attached AgentBay Session can be released from Browser Manager");return requestBrowserSocket(record2.socketPath,"browser_release",{},NATIVE_HOST_VERSION,6e4)}async function getManagedBrowserAccess(data){let selector=String(data?.browser??data?.browserId??"").trim();if(!selector)throw new Error("browser is required");return{kind:"agentbay",url:await getManagedAgentBayAccessUrl(selector)}}function appendWarnings(result,warnings){let merged=[...new Set([...result.warnings??[],...warnings])];return{...result,...merged.length>0?{warnings:merged}:{}}}async function handleExtensionControlMessage(message){let{id,action,data={}}=message;if(isAgentServiceAction(action)){let result=await dispatchAgentServiceAction(action,data);sendToExtension({id,success:!0,data:result});return}if(action==="browser_list"){let providerWarnings=await ensureInstalledProvidersRunning(),inventory=listBrowserInventory();sendToExtension({id,success:!0,data:appendWarnings(inventory,providerWarnings)});return}if(action==="browser_provider_list"){sendToExtension({id,success:!0,data:listBrowserProviders()});return}if(action==="browser_launch"){let result=await launchBrowser(data);sendToExtension({id,success:!0,data:result});return}if(action==="browser_close"){let result=await closeBrowser(data);sendToExtension({id,success:!0,data:result});return}if(action==="browser_manager_release"){let result=await releaseManagedBrowserAttachment(data);sendToExtension({id,success:!0,data:result});return}if(action==="get_browser_access_url"){let browserAccess=await getManagedBrowserAccess(data);sendToExtension({id,success:!0,data:{browserAccess}});return}if(action==="configure_agentbay_key"){sendToExtension({id,success:!0,data:configureAgentBayKey(data)});return}if(action==="start_cloud_connector"){let serverUrl=data?.serverUrl;if(!serverUrl||typeof serverUrl!="string"){sendToExtension({id,success:!1,error:"serverUrl is required"});return}let result=await startCloudConnector(serverUrl);sendToExtension({id,success:result.success,data:result,error:result.error});return}if(action==="stop_cloud_connector"){let serverUrl=data?.serverUrl;if(!serverUrl||typeof serverUrl!="string"){sendToExtension({id,success:!1,error:"serverUrl is required"});return}let result=stopCloudConnector(serverUrl);sendToExtension({id,success:result.success,data:result,error:result.error});return}if(action==="list_cloud_connectors"){sendToExtension({id,success:!0,data:listCloudConnectors()});return}if(action==="update_setup_extension"){let result=await updateSetupManagedExtension({currentVersion:data?.currentVersion,setupManagedPath:data?.setupManagedPath});sendToExtension({id,success:!0,data:result});return}sendToExtension({id,success:!1,error:`Unknown extension action: ${action}`})}function handleExtensionMessage(message){if(message&&message.type==="ping"){message.version&&(extensionVersion=message.version,log2(`Extension version: ${extensionVersion}, Native Host version: ${NATIVE_HOST_VERSION}`)),setAnalyticsClientId(message.analyticsClientId),registerBrowser({browserId:typeof message.browserId=="string"?message.browserId:"default",socketPath:INSTANCE_SOCKET_PATH,browserName:typeof message.browserName=="string"?message.browserName:"Browser",nativeHostVersion:NATIVE_HOST_VERSION,transport:"extension",extensionVersion:extensionVersion??void 0}),sendToExtension({type:"pong",timestamp:Date.now(),version:NATIVE_HOST_VERSION}),nativeHostUpdateCoordinator.evaluate(message.version,message.checkForUpdates);return}if(message&&message.type==="browser_focus"){touchFocus();return}if(!message||typeof message!="object"||!message.id)return;let pending=pendingRequests.get(message.id);if(!pending){message.action&&handleExtensionControlMessage(message).catch(error48=>{sendToExtension({id:message.id,success:!1,error:error48 instanceof Error?error48.message:String(error48)})});return}clearTimeout(pending.timer),pendingRequests.delete(message.id),message.success?pending.resolve(message.data):pending.reject(new Error(message.error||"Unknown error from extension"))}function processNativeMessages(){for(;nativeMessageBuffer.length>=4;){let length=nativeMessageBuffer.readUInt32LE(0);if(nativeMessageBuffer.length<4+length)return;let jsonBytes=nativeMessageBuffer.subarray(4,4+length);nativeMessageBuffer=nativeMessageBuffer.subarray(4+length);try{let message=JSON.parse(jsonBytes.toString("utf-8"));handleExtensionMessage(message)}catch(error48){log2("Failed to parse extension message:",String(error48))}}}function setupNativeMessageInput(){process.stdin.on("readable",()=>{let chunk;for(;(chunk=process.stdin.read())!==null;)nativeMessageBuffer=Buffer.concat([nativeMessageBuffer,chunk]),processNativeMessages()}),process.stdin.on("end",()=>{log2("Extension disconnected (stdin end)"),cleanupAndExit(0)}),process.stdin.on("error",error48=>{log2("stdin error:",String(error48)),cleanupAndExit(1)})}function sendRequestToExtension(action,data,timeoutMs,trustedInternal=!1,controlSource="local"){let id=`${Date.now()}_${Math.random().toString(36).slice(2,10)}`;return new Promise((resolve5,reject)=>{let timer=setTimeout(()=>{pendingRequests.delete(id),reject(new Error(`Request timeout after ${timeoutMs}ms`))},timeoutMs);pendingRequests.set(id,{resolve:resolve5,reject,timer}),sendToExtension(createExtensionRequestMessage(id,action,data,trustedInternal,controlSource))})}function toTimeoutMs(action,data){if(action==="send_request"||action==="__send_request_with_files")return Number(data&&data.timeout?data.timeout:3e4)+5e3;if(action==="send_mtop_request")return Number(data&&data.timeout?data.timeout:1e4)+5e3;if(action==="page_wait")return Number(data?.time??data?.timeout??1e4)+5e3;if(action==="tab_open")return 4e4;if(action==="run_actions"){let timeoutMs=(Array.isArray(data?.actions)?data.actions:[{}]).reduce((total,step)=>{let stepAction=String(step?.action??"");return!stepAction||stepAction==="run_actions"?total+DEFAULT_TIMEOUT_MS:total+toTimeoutMs(stepAction,step?.data??{})},0);return Math.max(DEFAULT_TIMEOUT_MS,timeoutMs)}if(shouldObservePageAction(action,data)){let observationMs=Math.min(Math.max(Number(data?.observe?.timeoutMs??3e3),500),3e4),navigationGraceMs=Math.min(Math.max(Number(data?.observe?.navigationGraceMs??1e3),0),5e3),navigationTimeoutMs=Math.min(Math.max(Number(data?.observe?.navigationTimeoutMs??15e3),1e3),3e4);return Math.max(DEFAULT_TIMEOUT_MS,observationMs+navigationGraceMs+4e3+navigationTimeoutMs+5e3)}return DEFAULT_TIMEOUT_MS}async function handleSocketRequest(socket,line){let request;try{request=JSON.parse(line)}catch{socket.write(JSON.stringify({id:"",success:!1,error:`Invalid JSON request: ${line}`})+`
|
|
1358
|
+
`)}var pendingRequests=new Map,nativeMessageBuffer=Buffer.alloc(0),socketServer=null,legacyServer=null,inventoryExitTimer=null,cdpRegistrationTimer=null,cdpBrowserPublished=!1,agentBaySessionWatchdog=null;function cancelInventoryExit(){inventoryExitTimer&&(clearTimeout(inventoryExitTimer),inventoryExitTimer=null)}function scheduleInventoryExit(delayMs=INVENTORY_IDLE_EXIT_MS){cancelInventoryExit(),inventoryExitTimer=setTimeout(()=>cleanupAndExit(0),delayMs),inventoryExitTimer.unref()}var cdpSession=null,cdpAutoReconnectEnabled=!0;function getCdpSession(){return cdpAutoReconnectEnabled=!0,cdpSession||(cdpSession=AGENTBAY_SESSION_ID?new CdpSession({endpointResolver:()=>resolveAgentBayEndpoint(AGENTBAY_SESSION_ID)}):new CdpSession({port:CDP_PORT,userDataDir:CDP_USER_DATA_DIR})),cdpSession}function log2(...args){let msg=`[${new Date().toISOString()}] [NativeHost] ${args.join(" ")}
|
|
1359
|
+
`;try{fs23.appendFileSync(LOG_FILE,msg)}catch{}}function sendToExtension(message){let json2=JSON.stringify(message),length=Buffer.byteLength(json2,"utf-8"),header=Buffer.alloc(4);header.writeUInt32LE(length,0),process.stdout.write(header),process.stdout.write(json2)}var nativeHostUpdateCoordinator=new NativeHostUpdateCoordinator({hostVersion:NATIVE_HOST_VERSION,log:log2,runUpdate:targetVersion=>runNativeHostUpdate(targetVersion),requestRestart:()=>{restartAfterUpdate()}}),agentChatManager=null,agentSkillManager=new AgentSkillManager;function getAgentChatManager(){return agentChatManager||(agentChatManager=new AgentChatManager([new CodexAgentProvider(log2,NATIVE_HOST_VERSION,INSTANCE_SOCKET_PATH),new QoderAgentProvider(log2,NATIVE_HOST_VERSION)],event=>{sendToExtension({type:"agent_chat_event",data:event})})),agentChatManager}var agentServiceHandlers={agent_chat_pick_directory:async()=>({path:await pickWorkspaceDirectory()}),agent_chat_status:()=>getAgentChatManager().getStatus(),agent_chat_prepare:async data=>(await getAgentChatManager().prepare(data),{ok:!0}),agent_chat_list_sessions:data=>getAgentChatManager().listSessions(data),agent_chat_start:data=>getAgentChatManager().startSession(data),agent_chat_send:data=>getAgentChatManager().sendMessage(data),agent_chat_interrupt:async data=>(await getAgentChatManager().interrupt(data),{ok:!0}),agent_chat_close:async data=>(await getAgentChatManager().closeSession(data),{ok:!0}),agent_chat_events:data=>getAgentChatManager().getEvents(data),agent_chat_refresh:data=>getAgentChatManager().refreshSession(data),agent_chat_open_app:async data=>(await getAgentChatManager().openSession(data),{ok:!0}),agent_chat_respond:data=>(getAgentChatManager().respondToRequest(data),{ok:!0}),agent_skills_installed:async data=>{let[cli,skills]=await Promise.all([agentSkillManager.getStatus(),getAgentChatManager().listSkills(data)]);return{cli,skills}},agent_skills_read:data=>getAgentChatManager().readSkill(data),agent_skills_install:data=>agentSkillManager.install(data),agent_skills_check_updates:data=>agentSkillManager.checkUpdates(data),agent_skills_update:data=>agentSkillManager.update(data),agent_skills_uninstall:data=>agentSkillManager.uninstall(data)};function dispatchAgentServiceAction(action,request){let handler=agentServiceHandlers[action];return Promise.resolve(handler(request))}var browserProviderCoordinator=null;function getBrowserProviderCoordinator(){if(browserProviderCoordinator)return browserProviderCoordinator;let runtimes=createBuiltinBrowserProviders({nativeHostScript:fileURLToPath5(import.meta.url),prepareTdbankSso:payload=>extensionVersion!==null?sendRequestToExtension("__tdbank_prepare_sso",payload,2e4,!0):cdpPrepareTdbankSso(getCdpSession(),payload),exportCookies:async domains=>extensionVersion!==null?(await sendRequestToExtension("__export_cookies",{domains},2e4,!0)).cookies??[]:cdpExportCookies(getCdpSession(),domains),getBrowserUserAgent:getCurrentBrowserUserAgent,detachAgentBay:releaseManagedBrowserAttachment,configureAgentBay:apiKey=>configureAgentBayKey({apiKey}),log:log2});return browserProviderCoordinator=new BrowserProviderCoordinator(runtimes),browserProviderCoordinator}async function launchBrowser(data){return getBrowserProviderCoordinator().launch(data)}async function closeBrowser(data){let selector=String(data?.browser??data?.browserId??data?.name??"").trim();if(!selector)throw new Error("browser is required");return getBrowserProviderCoordinator().close(selector,data?.deleteProfile===!0)}async function releaseManagedBrowserAttachment(selectorValue){let selector=String(selectorValue).trim();if(!selector)throw new Error("browser is required");let record2=listRegisteredBrowsers().find(browser=>browser.browserId===selector);if(!record2)throw new Error(`Browser is not connected: ${selector}`);if(!record2.browserId.startsWith("managed:agentbay:session:"))throw new Error("Only an attached AgentBay Session can be detached from Browser Manager");return requestBrowserSocket(record2.socketPath,"browser_release",{},NATIVE_HOST_VERSION,6e4)}async function getManagedBrowserAccess(data){let selector=String(data?.browser??data?.browserId??"").trim();if(!selector)throw new Error("browser is required");return(await getBrowserProviderCoordinator().access(selector)).browserAccess}function appendWarnings(result,warnings){let merged=[...new Set([...result.warnings??[],...warnings])];return{...result,...merged.length>0?{warnings:merged}:{}}}async function handleExtensionControlMessage(message){let{id,action,data={}}=message;if(isAgentServiceAction(action)){let result=await dispatchAgentServiceAction(action,data);sendToExtension({id,success:!0,data:result});return}if(action==="browser_list"){let providerWarnings=await ensureInstalledProvidersRunning(),inventory=await listBrowserInventory(getBrowserProviderCoordinator().providerRuntimes);sendToExtension({id,success:!0,data:appendWarnings(inventory,providerWarnings)});return}if(action==="browser_provider_list"){sendToExtension({id,success:!0,data:getBrowserProviderCoordinator().definitions()});return}if(action==="browser_launch"){let result=await launchBrowser(data);sendToExtension({id,success:!0,data:result});return}if(action==="browser_close"){let result=await closeBrowser(data);sendToExtension({id,success:!0,data:result});return}if(action==="browser_manager_release"){let selector=String(data?.browser??data?.browserId??"").trim();if(!selector)throw new Error("browser is required");let result=await getBrowserProviderCoordinator().detach(selector);sendToExtension({id,success:!0,data:result});return}if(action==="browser_manager_start"||action==="browser_manager_sync_cookies"){let selector=String(data?.browser??"").trim();if(!selector)throw new Error("browser is required");let coordinator=getBrowserProviderCoordinator(),result=action==="browser_manager_start"?await coordinator.start(selector):await coordinator.syncCookies(selector,data?.scope);sendToExtension({id,success:!0,data:result});return}if(action==="get_browser_access_url"){let browserAccess=await getManagedBrowserAccess(data);sendToExtension({id,success:!0,data:{browserAccess}});return}if(action==="browser_provider_configure"){if(typeof data?.provider!="string"||!data.provider.trim())throw new Error("provider is required");let result=await getBrowserProviderCoordinator().configure(data.provider,data.options);sendToExtension({id,success:!0,data:result});return}if(action==="configure_agentbay_key"){let result=await getBrowserProviderCoordinator().configure("agentbay",data);sendToExtension({id,success:!0,data:result});return}if(action==="start_cloud_connector"){let serverUrl=data?.serverUrl;if(!serverUrl||typeof serverUrl!="string"){sendToExtension({id,success:!1,error:"serverUrl is required"});return}let result=await startCloudConnector(serverUrl);sendToExtension({id,success:result.success,data:result,error:result.error});return}if(action==="stop_cloud_connector"){let serverUrl=data?.serverUrl;if(!serverUrl||typeof serverUrl!="string"){sendToExtension({id,success:!1,error:"serverUrl is required"});return}let result=stopCloudConnector(serverUrl);sendToExtension({id,success:result.success,data:result,error:result.error});return}if(action==="list_cloud_connectors"){sendToExtension({id,success:!0,data:listCloudConnectors()});return}if(action==="update_setup_extension"){let result=await updateSetupManagedExtension({currentVersion:data?.currentVersion,setupManagedPath:data?.setupManagedPath});sendToExtension({id,success:!0,data:result});return}sendToExtension({id,success:!1,error:`Unknown extension action: ${action}`})}function handleExtensionMessage(message){if(message&&message.type==="ping"){message.version&&(extensionVersion=message.version,log2(`Extension version: ${extensionVersion}, Native Host version: ${NATIVE_HOST_VERSION}`)),setAnalyticsClientId(message.analyticsClientId),registerBrowser({browserId:typeof message.browserId=="string"?message.browserId:"default",socketPath:INSTANCE_SOCKET_PATH,browserName:typeof message.browserName=="string"?message.browserName:"Browser",nativeHostVersion:NATIVE_HOST_VERSION,transport:"extension",extensionVersion:extensionVersion??void 0}),sendToExtension({type:"pong",timestamp:Date.now(),version:NATIVE_HOST_VERSION}),nativeHostUpdateCoordinator.evaluate(message.version,message.checkForUpdates);return}if(message&&message.type==="browser_focus"){touchFocus();return}if(!message||typeof message!="object"||!message.id)return;let pending=pendingRequests.get(message.id);if(!pending){message.action&&handleExtensionControlMessage(message).catch(error48=>{sendToExtension({id:message.id,success:!1,error:error48 instanceof Error?error48.message:String(error48)})});return}clearTimeout(pending.timer),pendingRequests.delete(message.id),message.success?pending.resolve(message.data):pending.reject(new Error(message.error||"Unknown error from extension"))}function processNativeMessages(){for(;nativeMessageBuffer.length>=4;){let length=nativeMessageBuffer.readUInt32LE(0);if(nativeMessageBuffer.length<4+length)return;let jsonBytes=nativeMessageBuffer.subarray(4,4+length);nativeMessageBuffer=nativeMessageBuffer.subarray(4+length);try{let message=JSON.parse(jsonBytes.toString("utf-8"));handleExtensionMessage(message)}catch(error48){log2("Failed to parse extension message:",String(error48))}}}function setupNativeMessageInput(){process.stdin.on("readable",()=>{let chunk;for(;(chunk=process.stdin.read())!==null;)nativeMessageBuffer=Buffer.concat([nativeMessageBuffer,chunk]),processNativeMessages()}),process.stdin.on("end",()=>{log2("Extension disconnected (stdin end)"),cleanupAndExit(0)}),process.stdin.on("error",error48=>{log2("stdin error:",String(error48)),cleanupAndExit(1)})}function sendRequestToExtension(action,data,timeoutMs,trustedInternal=!1,controlSource="local"){let id=`${Date.now()}_${Math.random().toString(36).slice(2,10)}`;return new Promise((resolve5,reject)=>{let timer=setTimeout(()=>{pendingRequests.delete(id),reject(new Error(`Request timeout after ${timeoutMs}ms`))},timeoutMs);pendingRequests.set(id,{resolve:resolve5,reject,timer}),sendToExtension(createExtensionRequestMessage(id,action,data,trustedInternal,controlSource))})}function toTimeoutMs(action,data){if(action==="send_request"||action==="__send_request_with_files")return Number(data&&data.timeout?data.timeout:3e4)+5e3;if(action==="send_mtop_request")return Number(data&&data.timeout?data.timeout:1e4)+5e3;if(action==="page_wait")return Number(data?.time??data?.timeout??1e4)+5e3;if(action==="tab_open")return 4e4;if(action==="run_actions"){let timeoutMs=(Array.isArray(data?.actions)?data.actions:[{}]).reduce((total,step)=>{let stepAction=String(step?.action??"");return!stepAction||stepAction==="run_actions"?total+DEFAULT_TIMEOUT_MS:total+toTimeoutMs(stepAction,step?.data??{})},0);return Math.max(DEFAULT_TIMEOUT_MS,timeoutMs)}if(shouldObservePageAction(action,data)){let observationMs=Math.min(Math.max(Number(data?.observe?.timeoutMs??3e3),500),3e4),navigationGraceMs=Math.min(Math.max(Number(data?.observe?.navigationGraceMs??1e3),0),5e3),navigationTimeoutMs=Math.min(Math.max(Number(data?.observe?.navigationTimeoutMs??15e3),1e3),3e4);return Math.max(DEFAULT_TIMEOUT_MS,observationMs+navigationGraceMs+4e3+navigationTimeoutMs+5e3)}return DEFAULT_TIMEOUT_MS}async function handleSocketRequest(socket,line){let request;try{request=JSON.parse(line)}catch{socket.write(JSON.stringify({id:"",success:!1,error:`Invalid JSON request: ${line}`})+`
|
|
1360
1360
|
`);return}let{id="",action,data={},version:clientVersion}=request,controlSource=normalizeControlSource(request.controlSource);if(action==="start_cloud_connector"){let serverUrl=data?.serverUrl;if(!serverUrl||typeof serverUrl!="string"){socket.write(JSON.stringify({id,success:!1,error:"serverUrl is required"})+`
|
|
1361
1361
|
`);return}let result=await startCloudConnector(serverUrl);socket.write(JSON.stringify({id,success:result.success,data:result})+`
|
|
1362
1362
|
`);return}if(action==="stop_cloud_connector"){let serverUrl=data?.serverUrl;if(!serverUrl||typeof serverUrl!="string"){socket.write(JSON.stringify({id,success:!1,error:"serverUrl is required"})+`
|
|
@@ -1366,10 +1366,10 @@ Examples:
|
|
|
1366
1366
|
`);return}if(action==="get_browser_access_url"){try{let browserAccess=data?.browser?await getManagedBrowserAccess(data):await resolveBrowserAccess();socket.write(JSON.stringify({id,success:!0,data:{browserAccess}})+`
|
|
1367
1367
|
`)}catch(error48){socket.write(JSON.stringify({id,success:!1,error:error48 instanceof Error?error48.message:String(error48)})+`
|
|
1368
1368
|
`)}return}if(isInternalExtensionAction(action)){socket.write(JSON.stringify({id,success:!1,error:"Internal action is not available to clients"})+`
|
|
1369
|
-
`);return}if(action==="browser_list"){let providerWarnings=await ensureInstalledProvidersRunning();discoverCdp&&cancelInventoryExit();let discovered=isDaemonMode&&!skipBrowserRegistration?await ensureDiscoverableCdpBrowser({isPublished:()=>cdpBrowserPublished,isAvailable:()=>getCdpSession().isAvailable(),publish:publishDaemonBrowser,monitor:monitorConnectedDaemonBrowser}):!1,inventory=listBrowserInventory(),data2=appendWarnings(inventory,providerWarnings),response=JSON.stringify({id,success:!0,data:data2})+`
|
|
1369
|
+
`);return}if(action==="browser_list"){let providerWarnings=await ensureInstalledProvidersRunning();discoverCdp&&cancelInventoryExit();let discovered=isDaemonMode&&!skipBrowserRegistration?await ensureDiscoverableCdpBrowser({isPublished:()=>cdpBrowserPublished,isAvailable:()=>getCdpSession().isAvailable(),publish:publishDaemonBrowser,monitor:monitorConnectedDaemonBrowser}):!1,inventory=await listBrowserInventory(getBrowserProviderCoordinator().providerRuntimes),data2=appendWarnings(inventory,providerWarnings),response=JSON.stringify({id,success:!0,data:data2})+`
|
|
1370
1370
|
`;skipBrowserRegistration||discoverCdp&&!discovered?(socket.end(response),scheduleInventoryExit()):socket.write(response);return}if(action==="browser_close"){try{let result=await closeBrowser(data);socket.write(JSON.stringify({id,success:!0,data:result})+`
|
|
1371
1371
|
`)}catch(error48){socket.write(JSON.stringify({id,success:!1,error:error48 instanceof Error?error48.message:String(error48)})+`
|
|
1372
|
-
`)}return}if(action==="browser_release"){let startedAt2=Date.now(),affectedTabIds=new Set,transports=[],failures=[],released=!0,hadActiveControl=!1;try{let releaseErrors=[];if(extensionVersion!==null)try{let result=await sendRequestToExtension(action,data,toTimeoutMs(action,data));released=released&&result?.released!==!1,hadActiveControl=hadActiveControl||result?.hadActiveControl===!0,result?.hadActiveControl&&transports.push("extension");for(let tabId of result?.affectedTabIds??[])affectedTabIds.add(tabId);Array.isArray(result?.failures)&&failures.push(...result.failures)}catch(error48){releaseErrors.push(`extension: ${error48 instanceof Error?error48.message:String(error48)}`)}if(cdpSession){let session=cdpSession;cdpSession=null;try{let result=await releaseCdpControl(session);released=released&&result.released,hadActiveControl=hadActiveControl||result.hadActiveControl,result.hadActiveControl&&transports.push("cdp");for(let tabId of result.affectedTabIds)affectedTabIds.add(tabId)}catch(error48){session.close(),releaseErrors.push(`cdp: ${error48 instanceof Error?error48.message:String(error48)}`)}}if(releaseErrors.length>0)throw new Error(`Failed to fully release browser control (${releaseErrors.join("; ")})`);trackAction(action,{success:released,transport:transports.join("+")||"none",duration_ms:Date.now()-startedAt2,extension_version:extensionVersion??"not_connected"});let attachment=AGENTBAY_ATTACHMENT?detachAgentBayBrowser(CDP_BROWSER_ID,process.pid):{detached:!1},response=JSON.stringify({id,success:!0,data:{released,hadActiveControl,transports,affectedTabIds:Array.from(affectedTabIds).sort((a,b)=>a-b),...failures.length>0&&{failures},...AGENTBAY_ATTACHMENT?{detached:attachment.detached,sessionClosed:!1,...attachment.sessionId?{agentbaySessionId:attachment.sessionId}:{}}:{}}})+`
|
|
1372
|
+
`)}return}if(action==="browser_release"){let startedAt2=Date.now(),affectedTabIds=new Set,transports=[],failures=[],released=!0,hadActiveControl=!1;try{let releaseErrors=[];if(extensionVersion!==null)try{let result=await sendRequestToExtension(action,data,toTimeoutMs(action,data));released=released&&result?.released!==!1,hadActiveControl=hadActiveControl||result?.hadActiveControl===!0,result?.hadActiveControl&&transports.push("extension");for(let tabId of result?.affectedTabIds??[])affectedTabIds.add(tabId);Array.isArray(result?.failures)&&failures.push(...result.failures)}catch(error48){releaseErrors.push(`extension: ${error48 instanceof Error?error48.message:String(error48)}`)}if(cdpSession){let session=cdpSession;cdpSession=null;try{let result=await releaseCdpControl(session);released=released&&result.released,hadActiveControl=hadActiveControl||result.hadActiveControl,result.hadActiveControl&&transports.push("cdp");for(let tabId of result.affectedTabIds)affectedTabIds.add(tabId)}catch(error48){session.close(),releaseErrors.push(`cdp: ${error48 instanceof Error?error48.message:String(error48)}`)}}if(cdpAutoReconnectEnabled=!1,releaseErrors.length>0)throw new Error(`Failed to fully release browser control (${releaseErrors.join("; ")})`);trackAction(action,{success:released,transport:transports.join("+")||"none",duration_ms:Date.now()-startedAt2,extension_version:extensionVersion??"not_connected"});let attachment=AGENTBAY_ATTACHMENT?detachAgentBayBrowser(CDP_BROWSER_ID,process.pid):{detached:!1},response=JSON.stringify({id,success:!0,data:{released,hadActiveControl,transports,affectedTabIds:Array.from(affectedTabIds).sort((a,b)=>a-b),...failures.length>0&&{failures},...AGENTBAY_ATTACHMENT?{detached:attachment.detached,sessionClosed:!1,...attachment.sessionId?{agentbaySessionId:attachment.sessionId}:{}}:{}}})+`
|
|
1373
1373
|
`;AGENTBAY_ATTACHMENT?socket.end(response,()=>cleanupAndExit(0)):socket.write(response)}catch(error48){trackAction(action,{success:!1,transport:transports.join("+")||(extensionVersion!==null?"extension":"cdp"),duration_ms:Date.now()-startedAt2,error_code:classifyAnalyticsError(error48),extension_version:extensionVersion??"not_connected"}),socket.write(JSON.stringify({id,success:!1,error:error48 instanceof Error?error48.message:String(error48)})+`
|
|
1374
1374
|
`)}return}if(action==="browser_launch"){try{let result=await launchBrowser(data);socket.write(JSON.stringify({id,success:!0,data:result})+`
|
|
1375
1375
|
`)}catch(error48){socket.write(JSON.stringify({id,success:!1,error:error48 instanceof Error?error48.message:String(error48)})+`
|
|
@@ -1377,7 +1377,7 @@ Examples:
|
|
|
1377
1377
|
`);return}let useExtension=!(request.transport==="cdp")&&extensionVersion!==null,transport=useExtension?"extension":"cdp",startedAt=Date.now();try{let result;useExtension?action==="send_request"&&hasSendRequestFiles(data)?result=await sendRequestWithTransferredFiles(data,(internalAction,payload,timeoutMs)=>sendRequestToExtension(internalAction,payload,timeoutMs,!0,controlSource)):action==="run_actions"&&hasRunActionsSendRequestFiles(data)?result=await sendRunActionsWithTransferredFiles(data,(internalAction,payload,timeoutMs)=>sendRequestToExtension(internalAction,payload,timeoutMs,!0,controlSource),transformed=>toTimeoutMs("run_actions",transformed)):result=await sendRequestToExtension(action,data,toTimeoutMs(action,data),!1,controlSource):(cdpPermissionNoticeLogged||(cdpPermissionNoticeLogged=!0,log2("CDP mode: domain permission checks are not enforced — all actions run without domain authorization")),result=await handleViaCdp(action,data,toTimeoutMs(action,data),controlSource)),trackAction(action,{success:!0,transport,duration_ms:Date.now()-startedAt,extension_version:extensionVersion??"not_connected"});let response={id,success:!0,data:result};if(!versionWarningEmitted){let versionWarning=buildVersionWarning(clientVersion);versionWarning&&(versionWarningEmitted=!0,response.versionWarning=versionWarning)}socket.write(JSON.stringify(response)+`
|
|
1378
1378
|
`)}catch(error48){let message=error48 instanceof Error?error48.message:String(error48);trackAction(action,{success:!1,transport,duration_ms:Date.now()-startedAt,error_code:classifyAnalyticsError(error48),extension_version:extensionVersion??"not_connected"}),socket.write(JSON.stringify({id,success:!1,error:message})+`
|
|
1379
1379
|
`)}}async function handleSocketLine(socket,line){let watchdog=agentBaySessionWatchdog;if(!watchdog){await handleSocketRequest(socket,line);return}if(!watchdog.beginActivity()){let id="";try{id=JSON.parse(line)?.id??""}catch{}socket.write(JSON.stringify({id,success:!1,error:"AgentBay browser is closing after reaching its idle timeout"})+`
|
|
1380
|
-
`);return}try{await handleSocketRequest(socket,line)}finally{watchdog.endActivity()}}async function handleViaCdp(action,data,_timeoutMs,controlSource){if(action==="set_rule"||action==="get_rules")throw new Error(`${action} requires the Mearl browser extension. Install it from https://chromewebstore.google.com/detail/mearl/aoehhjnofngknnjefamjbplchbolghkm`);if(!getRegisteredActionNames().includes(action))throw new Error(`Action "${action}" is not supported in CDP mode`);if(!await getCdpSession().isAvailable())throw AGENTBAY_SESSION_ID?new Error(`AgentBay CDP endpoint is not available for session ${AGENTBAY_SESSION_ID}. Check the session status and AgentBay plan permissions.`):new Error(`Chrome DevTools remote debugging is not available on port ${CDP_PORT}. Enable it via chrome://inspect/#remote-debugging (Chrome 145+) or install the Mearl extension.`);isDaemonMode&&!skipBrowserRegistration&&(publishDaemonBrowser(),shouldReconnectDaemonBrowser()||monitorConnectedDaemonBrowser());let actionData=AGENTBAY_SESSION_ID?await stageAgentBayPageUploads(AGENTBAY_SESSION_ID,action,data):data;return shouldObservePageAction(action,actionData)?cdpObservedPageAction(getCdpSession(),action,actionData,controlSource):dispatchCdpAction(getCdpSession(),action,actionData,controlSource)}function onSocketConnection(socket){let lineBuffer=new Utf8LineBuffer(MAX_SOCKET_BUFFER_SIZE2);socket.on("data",chunk=>{let result=lineBuffer.push(chunk);if(result.overflow){log2(`socket request exceeded ${MAX_SOCKET_BUFFER_SIZE2} bytes; closing connection`),socket.destroy();return}for(let line of result.lines)line.trim()&&handleSocketLine(socket,line)}),socket.on("error",error48=>{log2("socket error:",String(error48))})}function isPathAlive(socketPath){return new Promise(resolve5=>{if(process.platform!=="win32"&&!fs23.existsSync(socketPath)){resolve5(!1);return}let client2=
|
|
1380
|
+
`);return}try{await handleSocketRequest(socket,line)}finally{watchdog.endActivity()}}async function handleViaCdp(action,data,_timeoutMs,controlSource){if(action==="set_rule"||action==="get_rules")throw new Error(`${action} requires the Mearl browser extension. Install it from https://chromewebstore.google.com/detail/mearl/aoehhjnofngknnjefamjbplchbolghkm`);if(!getRegisteredActionNames().includes(action))throw new Error(`Action "${action}" is not supported in CDP mode`);if(!await getCdpSession().isAvailable())throw AGENTBAY_SESSION_ID?new Error(`AgentBay CDP endpoint is not available for session ${AGENTBAY_SESSION_ID}. Check the session status and AgentBay plan permissions.`):new Error(`Chrome DevTools remote debugging is not available on port ${CDP_PORT}. Enable it via chrome://inspect/#remote-debugging (Chrome 145+) or install the Mearl extension.`);isDaemonMode&&!skipBrowserRegistration&&(publishDaemonBrowser(),shouldReconnectDaemonBrowser()||monitorConnectedDaemonBrowser());let actionData=AGENTBAY_SESSION_ID?await stageAgentBayPageUploads(AGENTBAY_SESSION_ID,action,data):data;return shouldObservePageAction(action,actionData)?cdpObservedPageAction(getCdpSession(),action,actionData,controlSource):dispatchCdpAction(getCdpSession(),action,actionData,controlSource)}function onSocketConnection(socket){let lineBuffer=new Utf8LineBuffer(MAX_SOCKET_BUFFER_SIZE2);socket.on("data",chunk=>{let result=lineBuffer.push(chunk);if(result.overflow){log2(`socket request exceeded ${MAX_SOCKET_BUFFER_SIZE2} bytes; closing connection`),socket.destroy();return}for(let line of result.lines)line.trim()&&handleSocketLine(socket,line)}),socket.on("error",error48=>{log2("socket error:",String(error48))})}function isPathAlive(socketPath){return new Promise(resolve5=>{if(process.platform!=="win32"&&!fs23.existsSync(socketPath)){resolve5(!1);return}let client2=net4.createConnection(socketPath),done=alive=>{client2.removeAllListeners(),client2.destroy(),resolve5(alive)},timer=setTimeout(()=>done(!1),500);client2.on("connect",()=>{clearTimeout(timer),done(!0)}),client2.on("error",()=>{clearTimeout(timer),done(!1)})})}function listenOn(socketPath){return new Promise((resolve5,reject)=>{if(process.platform!=="win32"&&fs23.existsSync(socketPath))try{fs23.unlinkSync(socketPath)}catch{}let server=net4.createServer(onSocketConnection);server.once("error",reject),server.listen(socketPath,()=>{if(process.platform!=="win32")try{fs23.chmodSync(socketPath,384)}catch(error48){server.close();try{fs23.unlinkSync(socketPath)}catch{}reject(error48);return}server.removeListener("error",reject),server.on("error",error48=>log2("socket server error:",String(error48))),log2(`listening on ${socketPath}`),resolve5(server)})})}async function tryBindLegacySocket(){if(await isPathAlive(LEGACY_SOCKET_PATH)){log2("legacy socket already owned by a live host, skipping");return}try{legacyServer=await listenOn(LEGACY_SOCKET_PATH)}catch(error48){log2("legacy socket bind failed (raced):",String(error48)),legacyServer=null}}function releaseLegacySocket(){if(!legacyServer)return;let server=legacyServer;legacyServer=null;try{server.close()}catch{}if(process.platform!=="win32")try{fs23.existsSync(LEGACY_SOCKET_PATH)&&fs23.unlinkSync(LEGACY_SOCKET_PATH)}catch{}}async function startSocketServer(){socketServer=await listenOn(INSTANCE_SOCKET_PATH),await tryBindLegacySocket()}function cleanupInstanceSocketFile(){if(process.platform!=="win32")try{fs23.existsSync(INSTANCE_SOCKET_PATH)&&fs23.unlinkSync(INSTANCE_SOCKET_PATH)}catch(error48){log2("cleanup socket file failed:",String(error48))}}function cleanupAndExit(code){cancelInventoryExit(),cdpRegistrationTimer&&(clearInterval(cdpRegistrationTimer),cdpRegistrationTimer=null),agentBaySessionWatchdog?.stop(),agentBaySessionWatchdog=null,cdpSession?.close(),agentChatManager?.dispose(),agentChatManager=null,AGENTBAY_ATTACHMENT&&detachAgentBayBrowser(CDP_BROWSER_ID,process.pid),unregisterBrowser(),cdpBrowserPublished=!1,releaseLegacySocket();let finish=()=>{cleanupInstanceSocketFile(),process.exit(code)};if(socketServer){socketServer.close(finish),socketServer=null;return}finish()}function restartAfterUpdate(){setTimeout(()=>process.exit(0),2e3).unref(),cleanupAndExit(0)}function publishDaemonBrowser(){cancelInventoryExit(),!cdpBrowserPublished&&(registerBrowser({browserId:CDP_BROWSER_ID,socketPath:INSTANCE_SOCKET_PATH,browserName:CDP_BROWSER_NAME,nativeHostVersion:NATIVE_HOST_VERSION,transport:"cdp",lastFocusedAt:CDP_BROWSER_ID.startsWith("managed:")?0:void 0}),cdpBrowserPublished=!0)}function unpublishDaemonBrowser(){cdpBrowserPublished&&(unregisterBrowser(),cdpBrowserPublished=!1)}function shouldReconnectDaemonBrowser(){return!!AGENTBAY_SESSION_ID||CDP_BROWSER_ID.startsWith("managed:")}function monitorConnectedDaemonBrowser(){cdpRegistrationTimer||(cdpRegistrationTimer=setInterval(()=>{getCdpSession().hasActiveConnections()||(unpublishDaemonBrowser(),cdpRegistrationTimer&&clearInterval(cdpRegistrationTimer),cdpRegistrationTimer=null)},2e3),cdpRegistrationTimer.unref())}async function monitorReconnectableDaemonBrowser(){let checking=!1,refresh=async()=>{if(!checking&&cdpAutoReconnectEnabled){checking=!0;try{await getCdpSession().isAvailable()?publishDaemonBrowser():unpublishDaemonBrowser()}finally{checking=!1}}};await refresh(),cdpRegistrationTimer=setInterval(()=>{refresh()},2e3),cdpRegistrationTimer.unref()}async function main(){if(initBrowserRegistry({log:log2}),pruneDeadBrowsers(),initCloudConnector({log:log2,isDaemonMode,sendToExtension,version:NATIVE_HOST_VERSION}),isDaemonMode?log2(`running in ${skipBrowserRegistration?"browser inventory":discoverCdp?"CDP discovery":"CDP"} daemon mode, pid=${process.pid}, version=${NATIVE_HOST_VERSION}`):setupNativeMessageInput(),await startSocketServer(),shouldExitWithoutLegacySocket(runtimeArgs,!!legacyServer)){cleanupAndExit(0);return}if(discoverCdp&&scheduleInventoryExit(DISCOVERY_REQUEST_IDLE_EXIT_MS),isDaemonMode&&!skipBrowserRegistration&&shouldReconnectDaemonBrowser()&&await monitorReconnectableDaemonBrowser(),AGENTBAY_SESSION_ID&&!AGENTBAY_ATTACHMENT){let idleReleaseMinutes=AGENTBAY_IDLE_RELEASE_MINUTES??resolveAgentBayLifecycleConfig().idleReleaseTimeout;agentBaySessionWatchdog=new AgentBaySessionWatchdog({idleTimeoutMs:idleReleaseMinutes*6e4,keepAlive:()=>keepAgentBaySessionAlive(AGENTBAY_SESSION_ID),close:async()=>{await closeAgentBayBrowser(CDP_BROWSER_ID)},log:log2}),agentBaySessionWatchdog.start(),log2(`AgentBay idle close enabled for ${AGENTBAY_SESSION_ID}: ${idleReleaseMinutes} minutes`)}process.on("SIGINT",()=>cleanupAndExit(0)),process.on("SIGTERM",()=>cleanupAndExit(0)),process.on("uncaughtException",error48=>{log2("uncaughtException:",String(error48)),cleanupAndExit(1)}),process.on("unhandledRejection",error48=>{log2("unhandledRejection:",String(error48)),cleanupAndExit(1)})}main().catch(error48=>{log2("main() failed:",String(error48)),process.exit(1)});
|
|
1381
1381
|
/*! Bundled license information:
|
|
1382
1382
|
|
|
1383
1383
|
moment/moment.js:
|