MCPcopy Index your code
hub / github.com/ChinaSiro/claude-code-sourcemap / register

Method register

package/cli.js:2092–2092  ·  view source on GitHub ↗
(Y,$,A,O,w)

Source from the content-addressed store, hash-verified

2090`;this.trace(`Received server trailers:
2091`+K);let _;try{_=No.Metadata.fromHttp2Headers(q)}catch($){_=new No.Metadata}let z=_.getMap(),Y;if(typeof z["grpc-status"]==="string"){let $=Number(z["grpc-status"]);this.trace("received status code "+$+" from server"),_.remove("grpc-status");let A="";if(typeof z["grpc-message"]==="string"){try{A=decodeURI(z["grpc-message"])}catch(O){A=z["grpc-message"]}_.remove("grpc-message"),this.trace('received status details string "'+A+'" from server')}Y={code:$,details:A,metadata:_}}else if(this.httpStatusCode)Y=Wc1(this.httpStatusCode),Y.metadata=_;else Y={code:UO.Status.UNKNOWN,details:"No status information received",metadata:_};this.endCall(Y)}destroyHttp2Stream(){var q;if(this.http2Stream.destroyed)return;if(this.serverEndedCall)this.http2Stream.end();else{let K;if(((q=this.finalStatus)===null||q===void 0?void 0:q.code)===UO.Status.OK)K=Vo.constants.NGHTTP2_NO_ERROR;else K=Vo.constants.NGHTTP2_CANCEL;this.trace("close http2 stream with code "+K),this.http2Stream.close(K)}}cancelWithStatus(q,K){this.trace("cancelWithStatus code: "+q+' details: "'+K+'"'),this.endCall({code:q,details:K,metadata:new No.Metadata})}getStatus(){return this.finalStatus}getPeer(){return this.transport.getPeerName()}getCallNumber(){return this.callId}getAuthContext(){return this.transport.getAuthContext()}startRead(){if(this.finalStatus!==null&&this.finalStatus.code!==UO.Status.OK){this.readsClosed=!0,this.maybeOutputStatus();return}if(this.canPush=!0,this.unpushedReadMessages.length>0){let q=this.unpushedReadMessages.shift();this.push(q);return}this.http2Stream.resume()}sendMessageWithContext(q,K){this.trace("write() called with message of length "+K.length);let _=(z)=>{process.nextTick(()=>{var Y;let $=UO.Status.UNAVAILABLE;if((z===null||z===void 0?void 0:z.code)==="ERR_STREAM_WRITE_AFTER_END")$=UO.Status.INTERNAL;if(z)this.cancelWithStatus($,`Write error: ${z.message}`);(Y=q.callback)===null||Y===void 0||Y.call(q)})};this.trace("sending data chunk of length "+K.length),this.callEventTracker.addMessageSent();try{this.http2Stream.write(K,_)}catch(z){this.endCall({code:UO.Status.UNAVAILABLE,details:`Write failed with error ${z.message}`,metadata:new No.Metadata})}}halfClose(){this.trace("end() called"),this.trace("calling end() on HTTP/2 stream"),this.http2Stream.end()}}Xr4.Http2SubchannelCall=Mr4});var Tr4=m((Zr4)=>{Object.defineProperty(Zr4,"__esModule",{value:!0});Zr4.Http2SubchannelConnector=void 0;var Z26=U6("http2"),RLz=U6("tls"),mh8=V46(),At6=c_(),hLz=Xc1(),Iy6=Gw(),SLz=Tm(),ph8=FN(),Dc1=tv(),CLz=U6("net"),bLz=Wr4(),xLz=Sh8(),fc1="transport",ILz="transport_flowctrl",uLz=CQ1().version,{HTTP2_HEADER_AUTHORITY:mLz,HTTP2_HEADER_CONTENT_TYPE:pLz,HTTP2_HEADER_METHOD:BLz,HTTP2_HEADER_PATH:gLz,HTTP2_HEADER_TE:FLz,HTTP2_HEADER_USER_AGENT:ULz}=Z26.constants,QLz=20000,dLz=Buffer.from("too_many_pings","ascii");class Dr4{constructor(q,K,_,z){if(this.session=q,this.options=_,this.remoteName=z,this.keepaliveTimer=null,this.pendingSendKeepalivePing=!1,this.activeCalls=new Set,this.disconnectListeners=[],this.disconnectHandled=!1,this.channelzEnabled=!0,this.keepalivesSent=0,this.messagesSent=0,this.messagesReceived=0,this.lastMessageSentTimestamp=null,this.lastMessageReceivedTimestamp=null,this.subchannelAddressString=(0,ph8.subchannelAddressToString)(K),_["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.streamTracker=new mh8.ChannelzCallTrackerStub;else this.streamTracker=new mh8.ChannelzCallTracker;if(this.channelzRef=(0,mh8.registerChannelzSocket)(this.subchannelAddressString,()=>this.getChannelzInfo(),this.channelzEnabled),this.userAgent=[_["grpc.primary_user_agent"],`grpc-node-js/${uLz}`,_["grpc.secondary_user_agent"]].filter((Y)=>Y).join(" "),"grpc.keepalive_time_ms"in _)this.keepaliveTimeMs=_["grpc.keepalive_time_ms"];else this.keepaliveTimeMs=-1;if("grpc.keepalive_timeout_ms"in _)this.keepaliveTimeoutMs=_["grpc.keepalive_timeout_ms"];else this.keepaliveTimeoutMs=QLz;if("grpc.keepalive_permit_without_calls"in _)this.keepaliveWithoutCalls=_["grpc.keepalive_permit_without_calls"]===1;else this.keepaliveWithoutCalls=!1;if(q.once("close",()=>{this.trace("session closed"),this.handleDisconnect()}),q.once("goaway",(Y,$,A)=>{let O=!1;if(Y===Z26.constants.NGHTTP2_ENHANCE_YOUR_CALM&&A&&A.equals(dLz))O=!0;this.trace("connection closed by GOAWAY with code "+Y+" and data "+(A===null||A===void 0?void 0:A.toString())),this.reportDisconnectToOwner(O)}),q.once("error",(Y)=>{this.trace("connection closed with error "+Y.message),this.handleDisconnect()}),q.socket.once("close",(Y)=>{this.trace("connection closed. hadError="+Y),this.handleDisconnect()}),Iy6.isTracerEnabled(fc1))q.on("remoteSettings",(Y)=>{this.trace("new settings received"+(this.session!==q?" on the old connection":"")+": "+JSON.stringify(Y))}),q.on("localSettings",(Y)=>{this.trace("local settings acknowledged by remote"+(this.session!==q?" on the old connection":"")+": "+JSON.stringify(Y))});if(this.keepaliveWithoutCalls)this.maybeStartKeepalivePingTimer();if(q.socket instanceof RLz.TLSSocket)this.authContext={transportSecurityType:"ssl",sslPeerCertificate:q.socket.getPeerCertificate()};else this.authContext={}}getChannelzInfo(){var q,K,_;let z=this.session.socket,Y=z.remoteAddress?(0,ph8.stringToSubchannelAddress)(z.remoteAddress,z.remotePort):null,$=z.localAddress?(0,ph8.stringToSubchannelAddress)(z.localAddress,z.localPort):null,A;if(this.session.encrypted){let w=z,j=w.getCipher(),H=w.getCertificate(),J=w.getPeerCertificate();A={cipherSuiteStandardName:(q=j.standardName)!==null&&q!==void 0?q:null,cipherSuiteOtherName:j.standardName?null:j.name,localCertificate:H&&"raw"in H?H.raw:null,remoteCertificate:J&&"raw"in J?J.raw:null}}else A=null;return{remoteAddress:Y,localAddress:$,security:A,remoteName:this.remoteName,streamsStarted:this.streamTracker.callsStarted,streamsSucceeded:this.streamTracker.callsSucceeded,streamsFailed:this.streamTracker.callsFailed,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived,keepAlivesSent:this.keepalivesSent,lastLocalStreamCreatedTimestamp:this.streamTracker.lastCallStartedTimestamp,lastRemoteStreamCreatedTimestamp:null,lastMessageSentTimestamp:this.lastMessageSentTimestamp,lastMessageReceivedTimestamp:this.lastMessageReceivedTimestamp,localFlowControlWindow:(K=this.session.state.localWindowSize)!==null&&K!==void 0?K:null,remoteFlowControlWindow:(_=this.session.state.remoteWindowSize)!==null&&_!==void 0?_:null}}trace(q){Iy6.trace(At6.LogVerbosity.DEBUG,fc1,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+q)}keepaliveTrace(q){Iy6.trace(At6.LogVerbosity.DEBUG,"keepalive","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+q)}flowControlTrace(q){Iy6.trace(At6.LogVerbosity.DEBUG,ILz,"("+this.channelzRef.id+") "+this.subchannelAddressString+" "+q)}internalsTrace(q){Iy6.trace(At6.LogVerbosity.DEBUG,"transport_internals","("+this.channelzRef.id+") "+this.subchannelAddressString+" "+q)}reportDisconnectToOwner(q){if(this.disconnectHandled)return;this.disconnectHandled=!0,this.disconnectListeners.forEach((K)=>K(q))}handleDisconnect(){this.clearKeepaliveTimeout(),this.reportDisconnectToOwner(!1);for(let q of this.activeCalls)q.onDisconnect();setImmediate(()=>{this.session.destroy()})}addDisconnectListener(q){this.disconnectListeners.push(q)}canSendPing(){return!this.session.destroyed&&this.keepaliveTimeMs>0&&(this.keepaliveWithoutCalls||this.activeCalls.size>0)}maybeSendPing(){var q,K;if(!this.canSendPing()){this.pendingSendKeepalivePing=!0;return}if(this.keepaliveTimer){console.error("keepaliveTimeout is not null");return}if(this.channelzEnabled)this.keepalivesSent+=1;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms"),this.keepaliveTimer=setTimeout(()=>{this.keepaliveTimer=null,this.keepaliveTrace("Ping timeout passed without response"),this.handleDisconnect()},this.keepaliveTimeoutMs),(K=(q=this.keepaliveTimer).unref)===null||K===void 0||K.call(q);let _="";try{if(!this.session.ping((Y,$,A)=>{if(this.clearKeepaliveTimeout(),Y)this.keepaliveTrace("Ping failed with error "+Y.message),this.handleDisconnect();else this.keepaliveTrace("Received ping response"),this.maybeStartKeepalivePingTimer()}))_="Ping returned false"}catch(z){_=(z instanceof Error?z.message:"")||"Unknown error"}if(_)this.keepaliveTrace("Ping send failed: "+_),this.handleDisconnect()}maybeStartKeepalivePingTimer(){var q,K;if(!this.canSendPing())return;if(this.pendingSendKeepalivePing)this.pendingSendKeepalivePing=!1,this.maybeSendPing();else if(!this.keepaliveTimer)this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),this.keepaliveTimer=setTimeout(()=>{this.keepaliveTimer=null,this.maybeSendPing()},this.keepaliveTimeMs),(K=(q=this.keepaliveTimer).unref)===null||K===void 0||K.call(q)}clearKeepaliveTimeout(){if(this.keepaliveTimer)clearTimeout(this.keepaliveTimer),this.keepaliveTimer=null}removeActiveCall(q){if(this.activeCalls.delete(q),this.activeCalls.size===0)this.session.unref()}addActiveCall(q){if(this.activeCalls.add(q),this.activeCalls.size===1){if(this.session.ref(),!this.keepaliveWithoutCalls)this.maybeStartKeepalivePingTimer()}}createCall(q,K,_,z,Y){let $=q.toHttp2Headers();$[mLz]=K,$[ULz]=this.userAgent,$[pLz]="application/grpc",$[BLz]="POST",$[gLz]=_,$[FLz]="trailers";let A;try{A=this.session.request($)}catch(j){throw this.handleDisconnect(),j}this.flowControlTrace("local window size: "+this.session.state.localWindowSize+" remote window size: "+this.session.state.remoteWindowSize),this.internalsTrace("session.closed="+this.session.closed+" session.destroyed="+this.session.destroyed+" session.socket.destroyed="+this.session.socket.destroyed);let O,w;if(this.channelzEnabled)this.streamTracker.addCallStarted(),O={addMessageSent:()=>{var j;this.messagesSent+=1,this.lastMessageSentTimestamp=new Date,(j=Y.addMessageSent)===null||j===void 0||j.call(Y)},addMessageReceived:()=>{var j;this.messagesReceived+=1,this.lastMessageReceivedTimestamp=new Date,(j=Y.addMessageReceived)===null||j===void 0||j.call(Y)},onCallEnd:(j)=>{var H;(H=Y.onCallEnd)===null||H===void 0||H.call(Y,j),this.removeActiveCall(w)},onStreamEnd:(j)=>{var H;if(j)this.streamTracker.addCallSucceeded();else this.streamTracker.addCallFailed();(H=Y.onStreamEnd)===null||H===void 0||H.call(Y,j)}};else O={addMessageSent:()=>{var j;(j=Y.addMessageSent)===null||j===void 0||j.call(Y)},addMessageReceived:()=>{var j;(j=Y.addMessageReceived)===null||j===void 0||j.call(Y)},onCallEnd:(j)=>{var H;(H=Y.onCallEnd)===null||H===void 0||H.call(Y,j),this.removeActiveCall(w)},onStreamEnd:(j)=>{var H;(H=Y.onStreamEnd)===null||H===void 0||H.call(Y,j)}};return w=new bLz.Http2SubchannelCall(A,O,z,this,(0,xLz.getNextCallNumber)()),this.addActiveCall(w),w}getChannelzRef(){return this.channelzRef}getPeerName(){return this.subchannelAddressString}getOptions(){return this.options}getAuthContext(){return this.authContext}shutdown(){this.session.close(),(0,mh8.unregisterChannelzRef)(this.channelzRef)}}class fr4{constructor(q){this.channelTarget=q,this.session=null,this.isShutdown=!1}trace(q){Iy6.trace(At6.LogVerbosity.DEBUG,fc1,(0,Dc1.uriToString)(this.channelTarget)+" "+q)}createSession(q,K,_){if(this.isShutdown)return Promise.reject();if(q.socket.closed)return Promise.reject("Connection closed before starting HTTP/2 handshake");return new Promise((z,Y)=>{var $,A,O,w,j,H,J;let M=null,X=this.channelTarget;if("grpc.http_connect_target"in _){let S=(0,Dc1.parseUri)(_["grpc.http_connect_target"]);if(S)X=S,M=(0,Dc1.uriToString)(S)}let P=q.secure?"https":"http",W=(0,SLz.getDefaultAuthority)(X),D=()=>{var S;(S=this.session)===null||S===void 0||S.destroy(),this.session=null,setImmediate(()=>{if(!E)E=!0,Y(`${V.trim()} (${new Date().toISOString()})`)})},f=(S)=>{var R;if((R=this.session)===null||R===void 0||R.destroy(),V=S.message,this.trace("connection failed with error "+V),!E)E=!0,Y(`${V} (${new Date().toISOString()})`)},G={createConnection:(S,R)=>{return q.socket},settings:{initialWindowSize:(w=($=_["grpc-node.flow_control_window"])!==null&&$!==void 0?$:(O=(A=Z26.getDefaultSettings)===null||A===void 0?void 0:A.call(Z26))===null||O===void 0?void 0:O.initialWindowSize)!==null&&w!==void 0?w:65535}},Z=Z26.connect(`${P}://${W}`,G),T=(J=(H=(j=Z26.getDefaultSettings)===null||j===void 0?void 0:j.call(Z26))===null||H===void 0?void 0:H.initialWindowSize)!==null&&J!==void 0?J:65535,v=_["grpc-node.flow_control_window"];this.session=Z;let V="Failed to connect",E=!1;Z.unref(),Z.once("remoteSettings",()=>{var S;if(v&&v>T)try{Z.setLocalWindowSize(v)}catch(R){let x=v-((S=Z.state.localWindowSize)!==null&&S!==void 0?S:T);if(x>0)Z.incrementWindowSize(x)}Z.removeAllListeners(),q.socket.removeListener("close",D),q.socket.removeListener("error",f),z(new Dr4(Z,K,_,M)),this.session=null}),Z.once("close",D),Z.once("error",f),q.socket.once("close",D),q.socket.once("error",f)})}tcpConnect(q,K){return(0,hLz.getProxiedConnection)(q,K).then((_)=>{if(_)return _;else return new Promise((z,Y)=>{let $=()=>{Y(Error("Socket closed"))},A=(w)=>{Y(w)},O=CLz.connect(q,()=>{O.removeListener("close",$),O.removeListener("error",A),z(O)});O.once("close",$),O.once("error",A)})})}async connect(q,K,_){if(this.isShutdown)return Promise.reject();let z=null,Y=null,$=(0,ph8.subchannelAddressToString)(q);try{return this.trace($+" Waiting for secureConnector to be ready"),await K.waitForReady(),this.trace($+" secureConnector is ready"),z=await this.tcpConnect(q,_),z.setNoDelay(),this.trace($+" Established TCP connection"),Y=await K.connect(z),this.trace($+" Established secure connection"),this.createSession(Y,q,_)}catch(A){throw z===null||z===void 0||z.destroy(),Y===null||Y===void 0||Y.socket.destroy(),A}}shutdown(){var q;this.isShutdown=!0,(q=this.session)===null||q===void 0||q.close(),this.session=null}}Zr4.Http2SubchannelConnector=fr4});var Vr4=m((vr4)=>{Object.defineProperty(vr4,"__esModule",{value:!0});vr4.SubchannelPool=void 0;vr4.getSubchannelPool=sLz;var cLz=Vc4(),lLz=oi4(),nLz=FN(),iLz=tv(),rLz=Tr4(),oLz=1e4;class Bh8{constructor(){this.pool=Object.create(null),this.cleanupTimer=null}unrefUnusedSubchannels(){let q=!0;for(let K in this.pool){let z=this.pool[K].filter((Y)=>!Y.subchannel.unrefIfOneRef());if(z.length>0)q=!1;this.pool[K]=z}if(q&&this.cleanupTimer!==null)clearInterval(this.cleanupTimer),this.cleanupTimer=null}ensureCleanupTask(){var q,K;if(this.cleanupTimer===null)this.cleanupTimer=setInterval(()=>{this.unrefUnusedSubchannels()},oLz),(K=(q=this.cleanupTimer).unref)===null||K===void 0||K.call(q)}getOrCreateSubchannel(q,K,_,z){this.ensureCleanupTask();let Y=(0,iLz.uriToString)(q);if(Y in this.pool){let A=this.pool[Y];for(let O of A)if((0,nLz.subchannelAddressEqual)(K,O.subchannelAddress)&&(0,cLz.channelOptionsEqual)(_,O.channelArguments)&&z._equals(O.channelCredentials))return O.subchannel}let $=new lLz.Subchannel(q,K,_,z,new rLz.Http2SubchannelConnector(q));if(!(Y in this.pool))this.pool[Y]=[];return this.pool[Y].push({subchannelAddress:K,channelArguments:_,channelCredentials:z,subchannel:$}),$.ref(),$}}vr4.SubchannelPool=Bh8;var aLz=new Bh8;function sLz(q){if(q)return aLz;else return new Bh8}});var hr4=m((Lr4)=>{Object.defineProperty(Lr4,"__esModule",{value:!0});Lr4.LoadBalancingCall=void 0;var Nr4=ev(),gh8=c_(),yr4=Sy6(),Fh8=vD(),Ot6=Wo(),eLz=tv(),qRz=Gw(),Zc1=Kt6(),KRz=U6("http2"),_Rz="load_balancing_call";class Er4{constructor(q,K,_,z,Y,$,A){var O,w;this.channel=q,this.callConfig=K,this.methodName=_,this.host=z,this.credentials=Y,this.deadline=$,this.callNumber=A,this.child=null,this.readPending=!1,this.pendingMessage=null,this.pendingHalfClose=!1,this.ended=!1,this.metadata=null,this.listener=null,this.onCallEnded=null,this.childStartTime=null;let j=this.methodName.split("/"),H="";if(j.length>=2)H=j[1];let J=(w=(O=(0,eLz.splitHostPort)(this.host))===null||O===void 0?void 0:O.host)!==null&&w!==void 0?w:"localhost";this.serviceUrl=`https://${J}/${H}`,this.startTime=new Date}getDeadlineInfo(){var q,K;let _=[];if(this.childStartTime){if(this.childStartTime>this.startTime){if((q=this.metadata)===null||q===void 0?void 0:q.getOptions().waitForReady)_.push("wait_for_ready");_.push(`LB pick: ${(0,yr4.formatDateDifference)(this.startTime,this.childStartTime)}`)}return _.push(...this.child.getDeadlineInfo()),_}else{if((K=this.metadata)===null||K===void 0?void 0:K.getOptions().waitForReady)_.push("wait_for_ready");_.push("Waiting for LB pick")}return _}trace(q){qRz.trace(gh8.LogVerbosity.DEBUG,_Rz,"["+this.callNumber+"] "+q)}outputStatus(q,K){var _,z;if(!this.ended){this.ended=!0,this.trace("ended with status: code="+q.code+' details="'+q.details+'" start time='+this.startTime.toISOString());let Y=Object.assign(Object.assign({},q),{progress:K});(_=this.listener)===null||_===void 0||_.onReceiveStatus(Y),(z=this.onCallEnded)===null||z===void 0||z.call(this,Y.code,Y.details,Y.metadata)}}doPick(){var q,K;if(this.ended)return;if(!this.metadata)throw Error("doPick called before start");this.trace("Pick called");let _=this.metadata.clone(),z=this.channel.doPick(_,this.callConfig.pickInformation),Y=z.subchannel?"("+z.subchannel.getChannelzRef().id+") "+z.subchannel.getAddress():""+z.subchannel;switch(this.trace("Pick result: "+Ot6.PickResultType[z.pickResultType]+" subchannel: "+Y+" status: "+((q=z.status)===null||q===void 0?void 0:q.code)+" "+((K=z.status)===null||K===void 0?void 0:K.details)),z.pickResultType){case Ot6.PickResultType.COMPLETE:this.credentials.compose(z.subchannel.getCallCredentials()).generateMetadata({method_name:this.methodName,service_url:this.serviceUrl}).then((w)=>{var j;if(this.ended){this.trace("Credentials metadata generation finished after call ended");return}if(_.merge(w),_.get("authorization").length>1)this.outputStatus({code:gh8.Status.INTERNAL,details:'"authorization" metadata cannot have multiple values',metadata:new Fh8.Metadata},"PROCESSED");if(z.subchannel.getConnectivityState()!==Nr4.ConnectivityState.READY){this.trace("Picked subchannel "+Y+" has state "+Nr4.ConnectivityState[z.subchannel.getConnectivityState()]+" after getting credentials metadata. Retrying pick"),this.doPick();return}if(this.deadline!==1/0)_.set("grpc-timeout",(0,yr4.getDeadlineTimeoutString)(this.deadline));try{this.child=z.subchannel.getRealSubchannel().createCall(_,this.host,this.methodName,{onReceiveMetadata:(H)=>{this.trace("Received metadata"),this.listener.onReceiveMetadata(H)},onReceiveMessage:(H)=>{this.trace("Received message"),this.listener.onReceiveMessage(H)},onReceiveStatus:(H)=>{if(this.trace("Received status"),H.rstCode===KRz.constants.NGHTTP2_REFUSED_STREAM)this.outputStatus(H,"REFUSED");else this.outputStatus(H,"PROCESSED")}}),this.childStartTime=new Date}catch(H){this.trace("Failed to start call on picked subchannel "+Y+" with error "+H.message),this.outputStatus({code:gh8.Status.INTERNAL,details:"Failed to start HTTP/2 stream with error "+H.message,metadata:new Fh8.Metadata},"NOT_STARTED");return}if((j=z.onCallStarted)===null||j===void 0||j.call(z),this.onCallEnded=z.onCallEnded,this.trace("Created child call ["+this.child.getCallNumber()+"]"),this.readPending)this.child.startRead();if(this.pendingMessage)this.child.sendMessageWithContext(this.pendingMessage.context,this.pendingMessage.message);if(this.pendingHalfClose)this.child.halfClose()},(w)=>{let{code:j,details:H}=(0,Zc1.restrictControlPlaneStatusCode)(typeof w.code==="number"?w.code:gh8.Status.UNKNOWN,`Getting metadata from plugin failed with error: ${w.message}`);this.outputStatus({code:j,details:H,metadata:new Fh8.Metadata},"PROCESSED")});break;case Ot6.PickResultType.DROP:let{code:A,details:O}=(0,Zc1.restrictControlPlaneStatusCode)(z.status.code,z.status.details);setImmediate(()=>{this.outputStatus({code:A,details:O,metadata:z.status.metadata},"DROP")});break;case Ot6.PickResultType.TRANSIENT_FAILURE:if(this.metadata.getOptions().waitForReady)this.channel.queueCallForPick(this);else{let{code:w,details:j}=(0,Zc1.restrictControlPlaneStatusCode)(z.status.code,z.status.details);setImmediate(()=>{this.outputStatus({code:w,details:j,metadata:z.status.metadata},"PROCESSED")})}break;case Ot6.PickResultType.QUEUE:this.channel.queueCallForPick(this)}}cancelWithStatus(q,K){var _;this.trace("cancelWithStatus code: "+q+' details: "'+K+'"'),(_=this.child)===null||_===void 0||_.cancelWithStatus(q,K),this.outputStatus({code:q,details:K,metadata:new Fh8.Metadata},"PROCESSED")}getPeer(){var q,K;return(K=(q=this.child)===null||q===void 0?void 0:q.getPeer())!==null&&K!==void 0?K:this.channel.getTarget()}start(q,K){this.trace("start called"),this.listener=K,this.metadata=q,this.doPick()}sendMessageWithContext(q,K){if(this.trace("write() called with message of length "+K.length),this.child)this.child.sendMessageWithContext(q,K);else this.pendingMessage={context:q,message:K}}startRead(){if(this.trace("startRead called"),this.child)this.child.startRead();else this.readPending=!0}halfClose(){if(this.trace("halfClose called"),this.child)this.child.halfClose();else this.pendingHalfClose=!0}setCredentials(q){throw Error("Method not implemented.")}getCallNumber(){return this.callNumber}getAuthContext(){if(this.child)return this.child.getAuthContext();else return null}}Lr4.LoadBalancingCall=Er4});var Ir4=m((br4)=>{Object.defineProperty(br4,"__esModule",{value:!0});br4.ResolvingCall=void 0;var zRz=dR8(),G26=c_(),T26=Sy6(),Sr4=vD(),YRz=Gw(),$Rz=Kt6(),ARz="resolving_call";class Cr4{constructor(q,K,_,z,Y){if(this.channel=q,this.method=K,this.filterStackFactory=z,this.callNumber=Y,this.child=null,this.readPending=!1,this.pendingMessage=null,this.pendingHalfClose=!1,this.ended=!1,this.readFilterPending=!1,this.writeFilterPending=!1,this.pendingChildStatus=null,this.metadata=null,this.listener=null,this.statusWatchers=[],this.deadlineTimer=setTimeout(()=>{},0),this.filterStack=null,this.deadlineStartTime=null,this.configReceivedTime=null,this.childStartTime=null,this.credentials=zRz.CallCredentials.createEmpty(),this.deadline=_.deadline,this.host=_.host,_.parentCall){if(_.flags&G26.Propagate.CANCELLATION)_.parentCall.on("cancelled",()=>{this.cancelWithStatus(G26.Status.CANCELLED,"Cancelled by parent call")});if(_.flags&G26.Propagate.DEADLINE)this.trace("Propagating deadline from parent: "+_.parentCall.getDeadline()),this.deadline=(0,T26.minDeadline)(this.deadline,_.parentCall.getDeadline())}this.trace("Created"),this.runDeadlineTimer()}trace(q){YRz.trace(G26.LogVerbosity.DEBUG,ARz,"["+this.callNumber+"] "+q)}runDeadlineTimer(){clearTimeout(this.deadlineTimer),this.deadlineStartTime=new Date,this.trace("Deadline: "+(0,T26.deadlineToString)(this.deadline));let q=(0,T26.getRelativeTimeout)(this.deadline);if(q!==1/0){this.trace("Deadline will be reached in "+q+"ms");let K=()=>{if(!this.deadlineStartTime){this.cancelWithStatus(G26.Status.DEADLINE_EXCEEDED,"Deadline exceeded");return}let _=[],z=new Date;if(_.push(`Deadline exceeded after ${(0,T26.formatDateDifference)(this.deadlineStartTime,z)}`),this.configReceivedTime){if(this.configReceivedTime>this.deadlineStartTime)_.push(`name resolution: ${(0,T26.formatDateDifference)(this.deadlineStartTime,this.configReceivedTime)}`);if(this.childStartTime){if(this.childStartTime>this.configReceivedTime)_.push(`metadata filters: ${(0,T26.formatDateDifference)(this.configReceivedTime,this.childStartTime)}`)}else _.push("waiting for metadata filters")}else _.push("waiting for name resolution");if(this.child)_.push(...this.child.getDeadlineInfo());this.cancelWithStatus(G26.Status.DEADLINE_EXCEEDED,_.join(","))};if(q<=0)process.nextTick(K);else this.deadlineTimer=setTimeout(K,q)}}outputStatus(q){if(!this.ended){if(this.ended=!0,!this.filterStack)this.filterStack=this.filterStackFactory.createFilter();clearTimeout(this.deadlineTimer);let K=this.filterStack.receiveTrailers(q);this.trace("ended with status: code="+K.code+' details="'+K.details+'"'),this.statusWatchers.forEach((_)=>_(K)),process.nextTick(()=>{var _;(_=this.listener)===null||_===void 0||_.onReceiveStatus(K)})}}sendMessageOnChild(q,K){if(!this.child)throw Error("sendMessageonChild called with child not populated");let _=this.child;this.writeFilterPending=!0,this.filterStack.sendMessage(Promise.resolve({message:K,flags:q.flags})).then((z)=>{if(this.writeFilterPending=!1,_.sendMessageWithContext(q,z.message),this.pendingHalfClose)_.halfClose()},(z)=>{this.cancelWithStatus(z.code,z.details)})}getConfig(){if(this.ended)return;if(!this.metadata||!this.listener)throw Error("getConfig called before start");let q=this.channel.getConfig(this.method,this.metadata);if(q.type==="NONE"){this.channel.queueCallForConfig(this);return}else if(q.type==="ERROR"){if(this.metadata.getOptions().waitForReady)this.channel.queueCallForConfig(this);else this.outputStatus(q.error);return}this.configReceivedTime=new Date;let K=q.config;if(K.status!==G26.Status.OK){let{code:_,details:z}=(0,$Rz.restrictControlPlaneStatusCode)(K.status,"Failed to route call to method "+this.method);this.outputStatus({code:_,details:z,metadata:new Sr4.Metadata});return}if(K.methodConfig.timeout){let _=new Date;_.setSeconds(_.getSeconds()+K.methodConfig.timeout.seconds),_.setMilliseconds(_.getMilliseconds()+K.methodConfig.timeout.nanos/1e6),this.deadline=(0,T26.minDeadline)(this.deadline,_),this.runDeadlineTimer()}this.filterStackFactory.push(K.dynamicFilterFactories),this.filterStack=this.filterStackFactory.createFilter(),this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then((_)=>{if(this.child=this.channel.createRetryingCall(K,this.method,this.host,this.credentials,this.deadline),this.trace("Created child ["+this.child.getCallNumber()+"]"),this.childStartTime=new Date,this.child.start(_,{onReceiveMetadata:(z)=>{this.trace("Received metadata"),this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(z))},onReceiveMessage:(z)=>{this.trace("Received message"),this.readFilterPending=!0,this.filterStack.receiveMessage(z).then((Y)=>{if(this.trace("Finished filtering received message"),this.readFilterPending=!1,this.listener.onReceiveMessage(Y),this.pendingChildStatus)this.outputStatus(this.pendingChildStatus)},(Y)=>{this.cancelWithStatus(Y.code,Y.details)})},onReceiveStatus:(z)=>{if(this.trace("Received status"),this.readFilterPending)this.pendingChildStatus=z;else this.outputStatus(z)}}),this.readPending)this.child.startRead();if(this.pendingMessage)this.sendMessageOnChild(this.pendingMessage.context,this.pendingMessage.message);else if(this.pendingHalfClose)this.child.halfClose()},(_)=>{this.outputStatus(_)})}reportResolverError(q){var K;if((K=this.metadata)===null||K===void 0?void 0:K.getOptions().waitForReady)this.channel.queueCallForConfig(this);else this.outputStatus(q)}cancelWithStatus(q,K){var _;this.trace("cancelWithStatus code: "+q+' details: "'+K+'"'),(_=this.child)===null||_===void 0||_.cancelWithStatus(q,K),this.outputStatus({code:q,details:K,metadata:new Sr4.Metadata})}getPeer(){var q,K;return(K=(q=this.child)===null||q===void 0?void 0:q.getPeer())!==null&&K!==void 0?K:this.channel.getTarget()}start(q,K){this.trace("start called"),this.metadata=q.clone(),this.listener=K,this.getConfig()}sendMessageWithContext(q,K){if(this.trace("write() called with message of length "+K.length),this.child)this.sendMessageOnChild(q,K);else this.pendingMessage={context:q,message:K}}startRead(){if(this.trace("startRead called"),this.child)this.child.startRead();else this.readPending=!0}halfClose(){if(this.trace("halfClose called"),this.child&&!this.writeFilterPending)this.child.halfClose();else this.pendingHalfClose=!0}setCredentials(q){this.credentials=q}addStatusWatcher(q){this.statusWatchers.push(q)}getCallNumber(){return this.callNumber}getAuthContext(){if(this.child)return this.child.getAuthContext();else return null}}br4.ResolvingCall=Cr4});var Fr4=m((Br4)=>{Object.defineProperty(Br4,"__esModule",{value:!0});Br4.RetryingCall=Br4.MessageBufferTracker=Br4.RetryThrottler=void 0;var Uh8=c_(),ORz=Sy6(),wRz=vD(),jRz=Gw(),HRz="retrying_call";class ur4{constructor(q,K,_){if(this.maxTokens=q,this.tokenRatio=K,_)this.tokens=_.tokens*(q/_.maxTokens);else this.tokens=q}addCallSucceeded(){this.tokens=Math.min(this.tokens+this.tokenRatio,this.maxTokens)}addCallFailed(){this.tokens=Math.max(this.tokens-1,0)}canRetryCall(){return this.tokens>this.maxTokens/2}}Br4.RetryThrottler=ur4;class mr4{constructor(q,K){this.totalLimit=q,this.limitPerCall=K,this.totalAllocated=0,this.allocatedPerCall=new Map}allocate(q,K){var _;let z=(_=this.allocatedPerCall.get(K))!==null&&_!==void 0?_:0;if(this.limitPerCall-z<q||this.totalLimit-this.totalAllocated<q)return!1;return this.allocatedPerCall.set(K,z+q),this.totalAllocated+=q,!0}free(q,K){var _;if(this.totalAllocated<q)throw Error(`Invalid buffer allocation state: call ${K} freed ${q} > total allocated ${this.totalAllocated}`);this.totalAllocated-=q;let z=(_=this.allocatedPerCall.get(K))!==null&&_!==void 0?_:0;if(z<q)throw Error(`Invalid buffer allocation state: call ${K} freed ${q} > allocated for call ${z}`);this.allocatedPerCall.set(K,z-q)}freeAll(q){var K;let _=(K=this.allocatedPerCall.get(q))!==null&&K!==void 0?K:0;if(this.totalAllocated<_)throw Error(`Invalid buffer allocation state: call ${q} allocated ${_} > total allocated ${this.totalAllocated}`);this.totalAllocated-=_,this.allocatedPerCall.delete(q)}}Br4.MessageBufferTracker=mr4;var Gc1="grpc-previous-rpc-attempts",JRz=5;class pr4{constructor(q,K,_,z,Y,$,A,O,w){var j;this.channel=q,this.callConfig=K,this.methodName=_,this.host=z,this.credentials=Y,this.deadline=$,this.callNumber=A,this.bufferTracker=O,this.retryThrottler=w,this.listener=null,this.initialMetadata=null,this.underlyingCalls=[],this.writeBuffer=[],this.writeBufferOffset=0,this.readStarted=!1,this.transparentRetryUsed=!1,this.attempts=0,this.hedgingTimer=null,this.committedCallIndex=null,this.initialRetryBackoffSec=0,this.nextRetryBackoffSec=0;let H=(j=q.getOptions()["grpc-node.retry_max_attempts_limit"])!==null&&j!==void 0?j:JRz;if(q.getOptions()["grpc.enable_retries"]===0)this.state="NO_RETRY",this.maxAttempts=1;else if(K.methodConfig.retryPolicy){this.state="RETRY";let J=K.methodConfig.retryPolicy;this.nextRetryBackoffSec=this.initialRetryBackoffSec=Number(J.initialBackoff.substring(0,J.initialBackoff.length-1)),this.maxAttempts=Math.min(J.maxAttempts,H)}else if(K.methodConfig.hedgingPolicy)this.state="HEDGING",this.maxAttempts=Math.min(K.methodConfig.hedgingPolicy.maxAttempts,H);else this.state="TRANSPARENT_ONLY",this.maxAttempts=1;this.startTime=new Date}getDeadlineInfo(){if(this.underlyingCalls.length===0)return[];let q=[],K=this.underlyingCalls[this.underlyingCalls.length-1];if(this.underlyingCalls.length>1)q.push(`previous attempts: ${this.underlyingCalls.length-1}`);if(K.startTime>this.startTime)q.push(`time to current attempt start: ${(0,ORz.formatDateDifference)(this.startTime,K.startTime)}`);return q.push(...K.call.getDeadlineInfo()),q}getCallNumber(){return this.callNumber}trace(q){jRz.trace(Uh8.LogVerbosity.DEBUG,HRz,"["+this.callNumber+"] "+q)}reportStatus(q){this.trace("ended with status: code="+q.code+' details="'+q.details+'" start time='+this.startTime.toISOString()),this.bufferTracker.freeAll(this.callNumber),this.writeBufferOffset=this.writeBufferOffset+this.writeBuffer.length,this.writeBuffer=[],process.nextTick(()=>{var K;(K=this.listener)===null||K===void 0||K.onReceiveStatus({code:q.code,details:q.details,metadata:q.metadata})})}cancelWithStatus(q,K){this.trace("cancelWithStatus code: "+q+' details: "'+K+'"'),this.reportStatus({code:q,details:K,metadata:new wRz.Metadata});for(let{call:_}of this.underlyingCalls)_.cancelWithStatus(q,K)}getPeer(){if(this.committedCallIndex!==null)return this.underlyingCalls[this.committedCallIndex].call.getPeer();else return"unknown"}getBufferEntry(q){var K;return(K=this.writeBuffer[q-this.writeBufferOffset])!==null&&K!==void 0?K:{entryType:"FREED",allocated:!1}}getNextBufferIndex(){return this.writeBufferOffset+this.writeBuffer.length}clearSentMessages(){if(this.state!=="COMMITTED")return;let q;if(this.underlyingCalls[this.committedCallIndex].state==="COMPLETED")q=this.getNextBufferIndex();else q=this.underlyingCalls[this.committedCallIndex].nextMessageToSend;for(let K=this.writeBufferOffset;K<q;K++){let _=this.getBufferEntry(K);if(_.allocated)this.bufferTracker.free(_.message.message.length,this.callNumber)}this.writeBuffer=this.writeBuffer.slice(q-this.writeBufferOffset),this.writeBufferOffset=q}commitCall(q){var K,_;if(this.state==="COMMITTED")return;this.trace("Committing call ["+this.underlyingCalls[q].call.getCallNumber()+"] at index "+q),this.state="COMMITTED",(_=(K=this.callConfig).onCommitted)===null||_===void 0||_.call(K),this.committedCallIndex=q;for(let z=0;z<this.underlyingCalls.length;z++){if(z===q)continue;if(this.underlyingCalls[z].state==="COMPLETED")continue;this.underlyingCalls[z].state="COMPLETED",this.underlyingCalls[z].call.cancelWithStatus(Uh8.Status.CANCELLED,"Discarded in favor of other hedged attempt")}this.clearSentMessages()}commitCallWithMostMessages(){if(this.state==="COMMITTED")return;let q=-1,K=-1;for(let[_,z]of this.underlyingCalls.entries())if(z.state==="ACTIVE"&&z.nextMessageToSend>q)q=z.nextMessageToSend,K=_;if(K===-1)this.state="TRANSPARENT_ONLY";else this.commitCall(K)}isStatusCodeInList(q,K){return q.some((_)=>{var z;return _===K||_.toString().toLowerCase()===((z=Uh8.Status[K])===null||z===void 0?void 0:z.toLowerCase())})}getNextRetryJitter(){return Math.random()*0.3999999999999999+0.8}getNextRetryBackoffMs(){var q;let K=(q=this.callConfig)===null||q===void 0?void 0:q.methodConfig.retryPolicy;if(!K)return 0;let z=this.getNextRetryJitter()*this.nextRetryBackoffSec*1000,Y=Number(K.maxBackoff.substring(0,K.maxBackoff.length-1));return this.nextRetryBackoffSec=Math.min(this.nextRetryBackoffSec*K.backoffMultiplier,Y),z}maybeRetryCall(q,K){if(this.state!=="RETRY"){K(!1);return}if(this.attempts>=this.maxAttempts){K(!1);return}let _;if(q===null)_=this.getNextRetryBackoffMs();else if(q<0){this.state="TRANSPARENT_ONLY",K(!1);return}else _=q,this.nextRetryBackoffSec=this.initialRetryBackoffSec;setTimeout(()=>{var z,Y;if(this.state!=="RETRY"){K(!1);return}if((Y=(z=this.retryThrottler)===null||z===void 0?void 0:z.canRetryCall())!==null&&Y!==void 0?Y:!0)K(!0),this.attempts+=1,this.startNewAttempt();else this.trace("Retry attempt denied by throttling policy"),K(!1)},_)}countActiveCalls(){let q=0;for(let K of this.underlyingCalls)if((K===null||K===void 0?void 0:K.state)==="ACTIVE")q+=1;return q}handleProcessedStatus(q,K,_){var z,Y,$;switch(this.state){case"COMMITTED":case"NO_RETRY":case"TRANSPARENT_ONLY":this.commitCall(K),this.reportStatus(q);break;case"HEDGING":if(this.isStatusCodeInList((z=this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes)!==null&&z!==void 0?z:[],q.code)){(Y=this.retryThrottler)===null||Y===void 0||Y.addCallFailed();let A;if(_===null)A=0;else if(_<0){this.state="TRANSPARENT_ONLY",this.commitCall(K),this.reportStatus(q);return}else A=_;setTimeout(()=>{if(this.maybeStartHedgingAttempt(),this.countActiveCalls()===0)this.commitCall(K),this.reportStatus(q)},A)}else this.commitCall(K),this.reportStatus(q);break;case"RETRY":if(this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes,q.code))($=this.retryThrottler)===null||$===void 0||$.addCallFailed(),this.maybeRetryCall(_,(A)=>{if(!A)this.commitCall(K),this.reportStatus(q)});else this.commitCall(K),this.reportStatus(q);break}}getPushback(q){let K=q.get("grpc-retry-pushback-ms");if(K.length===0)return null;try{return parseInt(K[0])}catch(_){return-1}}handleChildStatus(q,K){var _;if(this.underlyingCalls[K].state==="COMPLETED")return;if(this.trace("state="+this.state+" handling status with progress "+q.progress+" from child ["+this.underlyingCalls[K].call.getCallNumber()+"] in state "+this.underlyingCalls[K].state),this.underlyingCalls[K].state="COMPLETED",q.code===Uh8.Status.OK){(_=this.retryThrottler)===null||_===void 0||_.addCallSucceeded(),this.commitCall(K),this.reportStatus(q);return}if(this.state==="NO_RETRY"){this.commitCall(K),this.reportStatus(q);return}if(this.state==="COMMITTED"){this.reportStatus(q);return}let z=this.getPushback(q.metadata);switch(q.progress){case"NOT_STARTED":this.startNewAttempt();break;case"REFUSED":if(this.transparentRetryUsed)this.handleProcessedStatus(q,K,z);else this.transparentRetryUsed=!0,this.startNewAttempt();break;case"DROP":this.commitCall(K),this.reportStatus(q);break;case"PROCESSED":this.handleProcessedStatus(q,K,z);break}}maybeStartHedgingAttempt(){if(this.state!=="HEDGING")return;if(!this.callConfig.methodConfig.hedgingPolicy)return;if(this.attempts>=this.maxAttempts)return;this.attempts+=1,this.startNewAttempt(),this.maybeStartHedgingTimer()}maybeStartHedgingTimer(){var q,K,_;if(this.hedgingTimer)clearTimeout(this.hedgingTimer);if(this.state!=="HEDGING")return;if(!this.callConfig.methodConfig.hedgingPolicy)return;let z=this.callConfig.methodConfig.hedgingPolicy;if(this.attempts>=this.maxAttempts)return;let Y=(q=z.hedgingDelay)!==null&&q!==void 0?q:"0s",$=Number(Y.substring(0,Y.length-1));this.hedgingTimer=setTimeout(()=>{this.maybeStartHedgingAttempt()},$*1000),(_=(K=this.hedgingTimer).unref)===null||_===void 0||_.call(K)}startNewAttempt(){let q=this.channel.createLoadBalancingCall(this.callConfig,this.methodName,this.host,this.credentials,this.deadline);this.trace("Created child call ["+q.getCallNumber()+"] for attempt "+this.attempts);let K=this.underlyingCalls.length;this.underlyingCalls.push({state:"ACTIVE",call:q,nextMessageToSend:0,startTime:new Date});let _=this.attempts-1,z=this.initialMetadata.clone();if(_>0)z.set(Gc1,`${_}`);let Y=!1;if(q.start(z,{onReceiveMetadata:($)=>{if(this.trace("Received metadata from child ["+q.getCallNumber()+"]"),this.commitCall(K),Y=!0,_>0)$.set(Gc1,`${_}`);if(this.underlyingCalls[K].state==="ACTIVE")this.listener.onReceiveMetadata($)},onReceiveMessage:($)=>{if(this.trace("Received message from child ["+q.getCallNumber()+"]"),this.commitCall(K),this.underlyingCalls[K].state==="ACTIVE")this.listener.onReceiveMessage($)},onReceiveStatus:($)=>{if(this.trace("Received status from child ["+q.getCallNumber()+"]"),!Y&&_>0)$.metadata.set(Gc1,`${_}`);this.handleChildStatus($,K)}}),this.sendNextChildMessage(K),this.readStarted)q.startRead()}start(q,K){this.trace("start called"),this.listener=K,this.initialMetadata=q,this.attempts+=1,this.startNewAttempt(),this.maybeStartHedgingTimer()}handleChildWriteCompleted(q){var K,_;let z=this.underlyingCalls[q],Y=z.nextMessageToSend;(_=(K=this.getBufferEntry(Y)).callback)===null||_===void 0||_.call(K),this.clearSentMessages(),z.nextMessageToSend+=1,this.sendNextChildMessage(q)}sendNextChildMessage(q){let K=this.underlyingCalls[q];if(K.state==="COMPLETED")return;if(this.getBufferEntry(K.nextMessageToSend)){let _=this.getBufferEntry(K.nextMessageToSend);switch(_.entryType){case"MESSAGE":K.call.sendMessageWithContext({callback:(z)=>{this.handleChildWriteCompleted(q)}},_.message.message);break;case"HALF_CLOSE":K.nextMessageToSend+=1,K.call.halfClose();break;case"FREED":break}}}sendMessageWithContext(q,K){var _;this.trace("write() called with message of length "+K.length);let z={message:K,flags:q.flags},Y=this.getNextBufferIndex(),$={entryType:"MESSAGE",message:z,allocated:this.bufferTracker.allocate(K.length,this.callNumber)};if(this.writeBuffer.push($),$.allocated){(_=q.callback)===null||_===void 0||_.call(q);for(let[A,O]of this.underlyingCalls.entries())if(O.state==="ACTIVE"&&O.nextMessageToSend===Y)O.call.sendMessageWithContext({callback:(w)=>{this.handleChildWriteCompleted(A)}},K)}else{if(this.commitCallWithMostMessages(),this.committedCallIndex===null)return;let A=this.underlyingCalls[this.committedCallIndex];if($.callback=q.callback,A.state==="ACTIVE"&&A.nextMessageToSend===Y)A.call.sendMessageWithContext({callback:(O)=>{this.handleChildWriteCompleted(this.committedCallIndex)}},K)}}startRead(){this.trace("startRead called"),this.readStarted=!0;for(let q of this.underlyingCalls)if((q===null||q===void 0?void 0:q.state)==="ACTIVE")q.call.startRead()}halfClose(){this.trace("halfClose called");let q=this.getNextBufferIndex();this.writeBuffer.push({entryType:"HALF_CLOSE",allocated:!1});for(let K of this.underlyingCalls)if((K===null||K===void 0?void 0:K.state)==="ACTIVE"&&K.nextMessageToSend===q)K.nextMessageToSend+=1,K.call.halfClose()}setCredentials(q){throw Error("Method not implemented.")}getMethod(){return this.methodName}getHost(){return this.host}getAuthContext(){if(this.committedCallIndex!==null)return this.underlyingCalls[this.committedCallIndex].call.getAuthContext();else return null}}Br4.RetryingCall=pr4});var wt6=m((Qr4)=>{Object.defineProperty(Qr4,"__esModule",{value:!0});Qr4.BaseSubchannelWrapper=void 0;class Ur4{constructor(q){this.child=q,this.healthy=!0,this.healthListeners=new Set,this.refcount=0,this.dataWatchers=new Set,q.addHealthStateWatcher((K)=>{if(this.healthy)this.updateHealthListeners()})}updateHealthListeners(){for(let q of this.healthListeners)q(this.isHealthy())}getConnectivityState(){return this.child.getConnectivityState()}addConnectivityStateListener(q){this.child.addConnectivityStateListener(q)}removeConnectivityStateListener(q){this.child.removeConnectivityStateListener(q)}startConnecting(){this.child.startConnecting()}getAddress(){return this.child.getAddress()}throttleKeepalive(q){this.child.throttleKeepalive(q)}ref(){this.child.ref(),this.refcount+=1}unref(){if(this.child.unref(),this.refcount-=1,this.refcount===0)this.destroy()}destroy(){for(let q of this.dataWatchers)q.destroy()}getChannelzRef(){return this.child.getChannelzRef()}isHealthy(){return this.healthy&&this.child.isHealthy()}addHealthStateWatcher(q){this.healthListeners.add(q)}removeHealthStateWatcher(q){this.healthListeners.delete(q)}addDataWatcher(q){q.setSubchannel(this.getRealSubchannel()),this.dataWatchers.add(q)}setHealthy(q){if(q!==this.healthy){if(this.healthy=q,this.child.isHealthy())this.updateHealthListeners()}}getRealSubchannel(){return this.child.getRealSubchannel()}realSubchannelEquals(q){return this.getRealSubchannel()===q.getRealSubchannel()}getCallCredentials(){return this.child.getCallCredentials()}getChannel(){return this.child.getChannel()}}Qr4.BaseSubchannelWrapper=Ur4});var Vc1=m((or4)=>{Object.defineProperty(or4,"__esModule",{value:!0});or4.InternalChannel=or4.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX=void 0;var PRz=Wy6(),WRz=Tc4(),DRz=Vr4(),kc1=Wo(),fRz=vD(),y46=c_(),ZRz=bh8(),GRz=Yc1(),cr4=Tm(),Qh8=Gw(),TRz=Xc1(),dh8=tv(),Ab=ev(),jt6=V46(),vRz=hr4(),kRz=Sy6(),VRz=Ir4(),Tc1=Sh8(),NRz=Kt6(),vc1=Fr4(),yRz=wt6(),ERz=2147483647,LRz=1000,RRz=1800000,ch8=new Map,hRz=16777216,SRz=1048576;class lr4 extends yRz.BaseSubchannelWrapper{constructor(q,K){super(q);this.channel=K,this.refCount=0,this.subchannelStateListener=(_,z,Y,$)=>{K.throttleKeepalive($)}}ref(){if(this.refCount===0)this.child.addConnectivityStateListener(this.subchannelStateListener),this.channel.addWrappedSubchannel(this);this.child.ref(),this.refCount+=1}unref(){if(this.child.unref(),this.refCount-=1,this.refCount<=0)this.child.removeConnectivityStateListener(this.subchannelStateListener),this.channel.removeWrappedSubchannel(this)}}class nr4{pick(q){return{pickResultType:kc1.PickResultType.DROP,status:{code:y46.Status.UNAVAILABLE,details:"Channel closed before call started",metadata:new fRz.Metadata},subchannel:null,onCallStarted:null,onCallEnded:null}}}or4.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX="grpc.internal.no_subchannel";class ir4{constructor(q){this.target=q,this.trace=new jt6.ChannelzTrace,this.callTracker=new jt6.ChannelzCallTracker,this.childrenTracker=new jt6.ChannelzChildrenTracker,this.state=Ab.ConnectivityState.IDLE}getChannelzInfoCallback(){return()=>{return{target:this.target,state:this.state,trace:this.trace,callTracker:this.callTracker,children:this.childrenTracker.getChildLists()}}}}class rr4{constructor(q,K,_){var z,Y,$,A,O,w;if(this.credentials=K,this.options=_,this.connectivityState=Ab.ConnectivityState.IDLE,this.currentPicker=new kc1.UnavailablePicker,this.configSelectionQueue=[],this.pickQueue=[],this.connectivityStateWatchers=[],this.callRefTimer=null,this.configSelector=null,this.currentResolutionError=null,this.wrappedSubchannels=new Set,this.callCount=0,this.idleTimer=null,this.channelzEnabled=!0,this.randomChannelId=Math.floor(Math.random()*Number.MAX_SAFE_INTEGER),typeof q!=="string")throw TypeError("Channel target must be a string");if(!(K instanceof PRz.ChannelCredentials))throw TypeError("Channel credentials must be a ChannelCredentials object");if(_){if(typeof _!=="object")throw TypeError("Channel options must be an object")}this.channelzInfoTracker=new ir4(q);let j=(0,dh8.parseUri)(q);if(j===null)throw Error(`Could not parse target name "${q}"`);let H=(0,cr4.mapUriDefaultScheme)(j);if(H===null)throw Error(`Could not find a default scheme for target name "${q}"`);if(this.options["grpc.enable_channelz"]===0)this.channelzEnabled=!1;if(this.channelzRef=(0,jt6.registerChannelzChannel)(q,this.channelzInfoTracker.getChannelzInfoCallback(),this.channelzEnabled),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Channel created");if(this.options["grpc.default_authority"])this.defaultAuthority=this.options["grpc.default_authority"];else this.defaultAuthority=(0,cr4.getDefaultAuthority)(H);let J=(0,TRz.mapProxyName)(H,_);this.target=J.target,this.options=Object.assign({},this.options,J.extraOptions),this.subchannelPool=(0,DRz.getSubchannelPool)(((z=this.options["grpc.use_local_subchannel_pool"])!==null&&z!==void 0?z:0)===0),this.retryBufferTracker=new vc1.MessageBufferTracker((Y=this.options["grpc.retry_buffer_size"])!==null&&Y!==void 0?Y:hRz,($=this.options["grpc.per_rpc_retry_buffer_size"])!==null&&$!==void 0?$:SRz),this.keepaliveTime=(A=this.options["grpc.keepalive_time_ms"])!==null&&A!==void 0?A:-1,this.idleTimeoutMs=Math.max((O=this.options["grpc.client_idle_timeout_ms"])!==null&&O!==void 0?O:RRz,LRz);let M={createSubchannel:(P,W)=>{let D={};for(let[Z,T]of Object.entries(W))if(!Z.startsWith(or4.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX))D[Z]=T;let f=this.subchannelPool.getOrCreateSubchannel(this.target,P,D,this.credentials);if(f.throttleKeepalive(this.keepaliveTime),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Created subchannel or used existing subchannel",f.getChannelzRef());return new lr4(f,this)},updateState:(P,W)=>{this.currentPicker=W;let D=this.pickQueue.slice();if(this.pickQueue=[],D.length>0)this.callRefTimerUnref();for(let f of D)f.doPick();this.updateState(P)},requestReresolution:()=>{throw Error("Resolving load balancer should never call requestReresolution")},addChannelzChild:(P)=>{if(this.channelzEnabled)this.channelzInfoTracker.childrenTracker.refChild(P)},removeChannelzChild:(P)=>{if(this.channelzEnabled)this.channelzInfoTracker.childrenTracker.unrefChild(P)}};this.resolvingLoadBalancer=new WRz.ResolvingLoadBalancer(this.target,M,this.options,(P,W)=>{var D;if(P.retryThrottling)ch8.set(this.getTarget(),new vc1.RetryThrottler(P.retryThrottling.maxTokens,P.retryThrottling.tokenRatio,ch8.get(this.getTarget())));else ch8.delete(this.getTarget());if(this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Address resolution succeeded");(D=this.configSelector)===null||D===void 0||D.unref(),this.configSelector=W,this.currentResolutionError=null,process.nextTick(()=>{let f=this.configSelectionQueue;if(this.configSelectionQueue=[],f.length>0)this.callRefTimerUnref();for(let G of f)G.getConfig()})},(P)=>{if(this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_WARNING","Address resolution failed with code "+P.code+' and details "'+P.details+'"');if(this.configSelectionQueue.length>0)this.trace("Name resolution failed with calls queued for config selection");if(this.configSelector===null)this.currentResolutionError=Object.assign(Object.assign({},(0,NRz.restrictControlPlaneStatusCode)(P.code,P.details)),{metadata:P.metadata});let W=this.configSelectionQueue;if(this.configSelectionQueue=[],W.length>0)this.callRefTimerUnref();for(let D of W)D.reportResolverError(P)}),this.filterStackFactory=new ZRz.FilterStackFactory([new GRz.CompressionFilterFactory(this,this.options)]),this.trace("Channel constructed with options "+JSON.stringify(_,void 0,2));let X=Error();if((0,Qh8.isTracerEnabled)("channel_stacktrace"))(0,Qh8.trace)(y46.LogVerbosity.DEBUG,"channel_stacktrace","("+this.channelzRef.id+`) Channel constructed
2092`+((w=X.stack)===null||w===void 0?void 0:w.substring(X.stack.indexOf(`
2093`)+1)));this.lastActivityTimestamp=new Date}trace(q,K){(0,Qh8.trace)(K!==null&&K!==void 0?K:y46.LogVerbosity.DEBUG,"channel","("+this.channelzRef.id+") "+(0,dh8.uriToString)(this.target)+" "+q)}callRefTimerRef(){var q,K,_,z;if(!this.callRefTimer)this.callRefTimer=setInterval(()=>{},ERz);if(!((K=(q=this.callRefTimer).hasRef)===null||K===void 0?void 0:K.call(q)))this.trace("callRefTimer.ref | configSelectionQueue.length="+this.configSelectionQueue.length+" pickQueue.length="+this.pickQueue.length),(z=(_=this.callRefTimer).ref)===null||z===void 0||z.call(_)}callRefTimerUnref(){var q,K,_;if(!((q=this.callRefTimer)===null||q===void 0?void 0:q.hasRef)||this.callRefTimer.hasRef())this.trace("callRefTimer.unref | configSelectionQueue.length="+this.configSelectionQueue.length+" pickQueue.length="+this.pickQueue.length),(_=(K=this.callRefTimer)===null||K===void 0?void 0:K.unref)===null||_===void 0||_.call(K)}removeConnectivityStateWatcher(q){let K=this.connectivityStateWatchers.findIndex((_)=>_===q);if(K>=0)this.connectivityStateWatchers.splice(K,1)}updateState(q){if((0,Qh8.trace)(y46.LogVerbosity.DEBUG,"connectivity_state","("+this.channelzRef.id+") "+(0,dh8.uriToString)(this.target)+" "+Ab.ConnectivityState[this.connectivityState]+" -> "+Ab.ConnectivityState[q]),this.channelzEnabled)this.channelzInfoTracker.trace.addTrace("CT_INFO","Connectivity state change to "+Ab.ConnectivityState[q]);this.connectivityState=q,this.channelzInfoTracker.state=q;let K=this.connectivityStateWatchers.slice();for(let _ of K)if(q!==_.currentState){if(_.timer)clearTimeout(_.timer);this.removeConnectivityStateWatcher(_),_.callback()}if(q!==Ab.ConnectivityState.TRANSIENT_FAILURE)this.currentResolutionError=null}throttleKeepalive(q){if(q>this.keepaliveTime){this.keepaliveTime=q;for(let K of this.wrappedSubchannels)K.throttleKeepalive(q)}}addWrappedSubchannel(q){this.wrappedSubchannels.add(q)}removeWrappedSubchannel(q){this.wrappedSubchannels.delete(q)}doPick(q,K){return this.currentPicker.pick({metadata:q,extraPickInfo:K})}queueCallForPick(q){this.pickQueue.push(q),this.callRefTimerRef()}getConfig(q,K){if(this.connectivityState!==Ab.ConnectivityState.SHUTDOWN)this.resolvingLoadBalancer.exitIdle();if(this.configSelector)return{type:"SUCCESS",config:this.configSelector.invoke(q,K,this.randomChannelId)};else if(this.currentResolutionError)return{type:"ERROR",error:this.currentResolutionError};else return{type:"NONE"}}queueCallForConfig(q){this.configSelectionQueue.push(q),this.callRefTimerRef()}enterIdle(){if(this.resolvingLoadBalancer.destroy(),this.updateState(Ab.ConnectivityState.IDLE),this.currentPicker=new kc1.QueuePicker(this.resolvingLoadBalancer),this.idleTimer)clearTimeout(this.idleTimer),this.idleTimer=null;if(this.callRefTimer)clearInterval(this.callRefTimer),this.callRefTimer=null}startIdleTimeout(q){var K,_;this.idleTimer=setTimeout(()=>{if(this.callCount>0){this.startIdleTimeout(this.idleTimeoutMs);return}let Y=new Date().valueOf()-this.lastActivityTimestamp.valueOf();if(Y>=this.idleTimeoutMs)this.trace("Idle timer triggered after "+this.idleTimeoutMs+"ms of inactivity"),this.enterIdle();else this.startIdleTimeout(this.idleTimeoutMs-Y)},q),(_=(K=this.idleTimer).unref)===null||_===void 0||_.call(K)}maybeStartIdleTimer(){if(this.connectivityState!==Ab.ConnectivityState.SHUTDOWN&&!this.idleTimer)this.startIdleTimeout(this.idleTimeoutMs)}onCallStart(){if(this.channelzEnabled)this.channelzInfoTracker.callTracker.addCallStarted();this.callCount+=1}onCallEnd(q){if(this.channelzEnabled)if(q.code===y46.Status.OK)this.channelzInfoTracker.callTracker.addCallSucceeded();else this.channelzInfoTracker.callTracker.addCallFailed();this.callCount-=1,this.lastActivityTimestamp=new Date,this.maybeStartIdleTimer()}createLoadBalancingCall(q,K,_,z,Y){let $=(0,Tc1.getNextCallNumber)();return this.trace("createLoadBalancingCall ["+$+'] method="'+K+'"'),new vRz.LoadBalancingCall(this,q,K,_,z,Y,$)}createRetryingCall(q,K,_,z,Y){let $=(0,Tc1.getNextCallNumber)();return this.trace("createRetryingCall ["+$+'] method="'+K+'"'),new vc1.RetryingCall(this,q,K,_,z,Y,$,this.retryBufferTracker,ch8.get(this.getTarget()))}createResolvingCall(q,K,_,z,Y){let $=(0,Tc1.getNextCallNumber)();this.trace("createResolvingCall ["+$+'] method="'+q+'", deadline='+(0,kRz.deadlineToString)(K));let A={deadline:K,flags:Y!==null&&Y!==void 0?Y:y46.Propagate.DEFAULTS,host:_!==null&&_!==void 0?_:this.defaultAuthority,parentCall:z},O=new VRz.ResolvingCall(this,q,A,this.filterStackFactory.clone(),$);return this.onCallStart(),O.addStatusWatcher((w)=>{this.onCallEnd(w)}),O}close(){var q;this.resolvingLoadBalancer.destroy(),this.updateState(Ab.ConnectivityState.SHUTDOWN),this.currentPicker=new nr4;for(let K of this.configSelectionQueue)K.cancelWithStatus(y46.Status.UNAVAILABLE,"Channel closed before call started");this.configSelectionQueue=[];for(let K of this.pickQueue)K.cancelWithStatus(y46.Status.UNAVAILABLE,"Channel closed before call started");if(this.pickQueue=[],this.callRefTimer)clearInterval(this.callRefTimer);if(this.idleTimer)clearTimeout(this.idleTimer);if(this.channelzEnabled)(0,jt6.unregisterChannelzRef)(this.channelzRef);this.subchannelPool.unrefUnusedSubchannels(),(q=this.configSelector)===null||q===void 0||q.unref(),this.configSelector=null}getTarget(){return(0,dh8.uriToString)(this.target)}getConnectivityState(q){let K=this.connectivityState;if(q)this.resolvingLoadBalancer.exitIdle(),this.lastActivityTimestamp=new Date,this.maybeStartIdleTimer();return K}watchConnectivityState(q,K,_){if(this.connectivityState===Ab.ConnectivityState.SHUTDOWN)throw Error("Channel has been shut down");let z=null;if(K!==1/0){let $=K instanceof Date?K:new Date(K),A=new Date;if(K===-1/0||$<=A){process.nextTick(_,Error("Deadline passed without connectivity state change"));return}z=setTimeout(()=>{this.removeConnectivityStateWatcher(Y),_(Error("Deadline passed without connectivity state change"))},$.getTime()-A.getTime())}let Y={currentState:q,callback:_,timer:z};this.connectivityStateWatchers.push(Y)}getChannelzRef(){return this.channelzRef}createCall(q,K,_,z,Y){if(typeof q!=="string")throw TypeError("Channel#createCall: method must be a string");if(!(typeof K==="number"||K instanceof Date))throw TypeError("Channel#createCall: deadline must be a number or Date");if(this.connectivityState===Ab.ConnectivityState.SHUTDOWN)throw Error("Channel has been shut down");return this.createResolvingCall(q,K,_,z,Y)}getOptions(){return this.options}}or4.InternalChannel=rr4});var zd1=m((er4)=>{Object.defineProperty(er4,"__esModule",{value:!0});er4.ChannelImplementation=void 0;var CRz=Wy6(),bRz=Vc1();class tr4{constructor(q,K,_){if(typeof q!=="string")throw TypeError("Channel target must be a string");if(!(K instanceof CRz.ChannelCredentials))throw TypeError("Channel credentials must be a ChannelCredentials object");if(_){if(typeof _!=="object")throw TypeError("Channel options must be an object")}this.internalChannel=new bRz.InternalChannel(q,K,_)}close(){this.internalChannel.close()}getTarget(){return this.internalChannel.getTarget()}getConnectivityState(q){return this.internalChannel.getConnectivityState(q)}watchConnectivityState(q,K,_){this.internalChannel.watchConnectivityState(q,K,_)}getChannelzRef(){return this.internalChannel.getChannelzRef()}createCall(q,K,_,z,Y){if(typeof q!=="string")throw TypeError("Channel#createCall: method must be a string");if(!(typeof K==="number"||K instanceof Date))throw TypeError("Channel#createCall: deadline must be a number or Date");return this.internalChannel.createCall(q,K,_,z,Y)}}er4.ChannelImplementation=tr4});var wo4=m((Ao4)=>{Object.defineProperty(Ao4,"__esModule",{value:!0});Ao4.ServerDuplexStreamImpl=Ao4.ServerWritableStreamImpl=Ao4.ServerReadableStreamImpl=Ao4.ServerUnaryCallImpl=void 0;Ao4.serverErrorToStatus=Ec1;var xRz=U6("events"),Nc1=U6("stream"),yc1=c_(),Ko4=vD();function Ec1(q,K){var _;let z={code:yc1.Status.UNKNOWN,details:"message"in q?q.message:"Unknown Error",metadata:(_=K!==null&&K!==void 0?K:q.metadata)!==null&&_!==void 0?_:null};if("code"in q&&typeof q.code==="number"&&Number.isInteger(q.code)){if(z.code=q.code,"details"in q&&typeof q.details==="string")z.details=q.details}return z}class _o4 extends xRz.EventEmitter{constructor(q,K,_,z){super();this.path=q,this.call=K,this.metadata=_,this.request=z,this.cancelled=!1}getPeer(){return this.call.getPeer()}sendMetadata(q){this.call.sendMetadata(q)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}}Ao4.ServerUnaryCallImpl=_o4;class zo4 extends Nc1.Readable{constructor(q,K,_){super({objectMode:!0});this.path=q,this.call=K,this.metadata=_,this.cancelled=!1}_read(q){this.call.startRead()}getPeer(){return this.call.getPeer()}sendMetadata(q){this.call.sendMetadata(q)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}}Ao4.ServerReadableStreamImpl=zo4;class Yo4 extends Nc1.Writable{constructor(q,K,_,z){super({objectMode:!0});this.path=q,this.call=K,this.metadata=_,this.request=z,this.pendingStatus={code:yc1.Status.OK,details:"OK"},this.cancelled=!1,this.trailingMetadata=new Ko4.Metadata,this.on("error",(Y)=>{this.pendingStatus=Ec1(Y),this.end()})}getPeer(){return this.call.getPeer()}sendMetadata(q){this.call.sendMetadata(q)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}_write(q,K,_){this.call.sendMessage(q,_)}_final(q){var K;q(null),this.call.sendStatus(Object.assign(Object.assign({},this.pendingStatus),{metadata:(K=this.pendingStatus.metadata)!==null&&K!==void 0?K:this.trailingMetadata}))}end(q){if(q)this.trailingMetadata=q;return super.end()}}Ao4.ServerWritableStreamImpl=Yo4;class $o4 extends Nc1.Duplex{constructor(q,K,_){super({objectMode:!0});this.path=q,this.call=K,this.metadata=_,this.pendingStatus={code:yc1.Status.OK,details:"OK"},this.cancelled=!1,this.trailingMetadata=new Ko4.Metadata,this.on("error",(z)=>{this.pendingStatus=Ec1(z),this.end()})}getPeer(){return this.call.getPeer()}sendMetadata(q){this.call.sendMetadata(q)}getDeadline(){return this.call.getDeadline()}getPath(){return this.path}getHost(){return this.call.getHost()}getAuthContext(){return this.call.getAuthContext()}getMetricsRecorder(){return this.call.getMetricsRecorder()}_read(q){this.call.startRead()}_write(q,K,_){this.call.sendMessage(q,_)}_final(q){var K;q(null),this.call.sendStatus(Object.assign(Object.assign({},this.pendingStatus),{metadata:(K=this.pendingStatus.metadata)!==null&&K!==void 0?K:this.trailingMetadata}))}end(q){if(q)this.trailingMetadata=q;return super.end()}}Ao4.ServerDuplexStreamImpl=$o4});var lh8=m((jo4)=>{Object.defineProperty(jo4,"__esModule",{value:!0});jo4.ServerCredentials=void 0;jo4.createCertificateProviderServerCredentials=BRz;jo4.createServerCredentialsWithInterceptors=gRz;var Lc1=QQ1();class uy6{constructor(q,K){this.serverConstructorOptions=q,this.watchers=new Set,this.latestContextOptions=null,this.latestContextOptions=K!==null&&K!==void 0?K:null}_addWatcher(q){this.watchers.add(q)}_removeWatcher(q){this.watchers.delete(q)}getWatcherCount(){return this.watchers.size}updateSecureContextOptions(q){this.latestContextOptions=q;for(let K of this.watchers)K(this.latestContextOptions)}_isSecure(){return this.serverConstructorOptions!==null}_getSecureContextOptions(){return this.latestContextOptions}_getConstructorOptions(){return this.serverConstructorOptions}_getInterceptors(){return[]}static createInsecure(){return new Rc1}static createSsl(q,K,_=!1){var z;if(q!==null&&!Buffer.isBuffer(q))throw TypeError("rootCerts must be null or a Buffer");if(!Array.isArray(K))throw TypeError("keyCertPairs must be an array");if(typeof _!=="boolean")throw TypeError("checkClientCertificate must be a boolean");let Y=[],$=[];for(let A=0;A<K.length;A++){let O=K[A];if(O===null||typeof O!=="object")throw TypeError(`keyCertPair[${A}] must be an object`);if(!Buffer.isBuffer(O.private_key))throw TypeError(`keyCertPair[${A}].private_key must be a Buffer`);if(!Buffer.isBuffer(O.cert_chain))throw TypeError(`keyCertPair[${A}].cert_chain must be a Buffer`);Y.push(O.cert_chain),$.push(O.private_key)}return new hc1({requestCert:_,ciphers:Lc1.CIPHER_SUITES},{ca:(z=q!==null&&q!==void 0?q:(0,Lc1.getDefaultRootsData)())!==null&&z!==void 0?z:void 0,cert:Y,key:$})}}jo4.ServerCredentials=uy6;class Rc1 extends uy6{constructor(){super(null)}_getSettings(){return null}_equals(q){return q instanceof Rc1}}class hc1 extends uy6{constructor(q,K){super(q,K);this.options=Object.assign(Object.assign({},q),K)}_equals(q){if(this===q)return!0;if(!(q instanceof hc1))return!1;if(Buffer.isBuffer(this.options.ca)&&Buffer.isBuffer(q.options.ca)){if(!this.options.ca.equals(q.options.ca))return!1}else if(this.options.ca!==q.options.ca)return!1;if(Array.isArray(this.options.cert)&&Array.isArray(q.options.cert)){if(this.options.cert.length!==q.options.cert.length)return!1;for(let K=0;K<this.options.cert.length;K++){let _=this.options.cert[K],z=q.options.cert[K];if(Buffer.isBuffer(_)&&Buffer.isBuffer(z)){if(!_.equals(z))return!1}else if(_!==z)return!1}}else if(this.options.cert!==q.options.cert)return!1;if(Array.isArray(this.options.key)&&Array.isArray(q.options.key)){if(this.options.key.length!==q.options.key.length)return!1;for(let K=0;K<this.options.key.length;K++){let _=this.options.key[K],z=q.options.key[K];if(Buffer.isBuffer(_)&&Buffer.isBuffer(z)){if(!_.equals(z))return!1}else if(_!==z)return!1}}else if(this.options.key!==q.options.key)return!1;if(this.options.requestCert!==q.options.requestCert)return!1;return!0}}class Sc1 extends uy6{constructor(q,K,_){super({requestCert:K!==null,rejectUnauthorized:_,ciphers:Lc1.CIPHER_SUITES});this.identityCertificateProvider=q,this.caCertificateProvider=K,this.requireClientCertificate=_,this.latestCaUpdate=null,this.latestIdentityUpdate=null,this.caCertificateUpdateListener=this.handleCaCertificateUpdate.bind(this),this.identityCertificateUpdateListener=this.handleIdentityCertitificateUpdate.bind(this)}_addWatcher(q){var K;if(this.getWatcherCount()===0)(K=this.caCertificateProvider)===null||K===void 0||K.addCaCertificateListener(this.caCertificateUpdateListener),this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener);super._addWatcher(q)}_removeWatcher(q){var K;if(super._removeWatcher(q),this.getWatcherCount()===0)(K=this.caCertificateProvider)===null||K===void 0||K.removeCaCertificateListener(this.caCertificateUpdateListener),this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener)}_equals(q){if(this===q)return!0;if(!(q instanceof Sc1))return!1;return this.caCertificateProvider===q.caCertificateProvider&&this.identityCertificateProvider===q.identityCertificateProvider&&this.requireClientCertificate===q.requireClientCertificate}calculateSecureContextOptions(){var q;if(this.latestIdentityUpdate===null)return null;if(this.caCertificateProvider!==null&&this.latestCaUpdate===null)return null;return{ca:(q=this.latestCaUpdate)===null||q===void 0?void 0:q.caCertificate,cert:[this.latestIdentityUpdate.certificate],key:[this.latestIdentityUpdate.privateKey]}}finalizeUpdate(){let q=this.calculateSecureContextOptions();this.updateSecureContextOptions(q)}handleCaCertificateUpdate(q){this.latestCaUpdate=q,this.finalizeUpdate()}handleIdentityCertitificateUpdate(q){this.latestIdentityUpdate=q,this.finalizeUpdate()}}function BRz(q,K,_){return new Sc1(q,K,_)}class Cc1 extends uy6{constructor(q,K){super({});this.childCredentials=q,this.interceptors=K}_isSecure(){return this.childCredentials._isSecure()}_equals(q){if(!(q instanceof Cc1))return!1;if(!this.childCredentials._equals(q.childCredentials))return!1;if(this.interceptors.length!==q.interceptors.length)return!1;for(let K=0;K<this.interceptors.length;K++)if(this.interceptors[K]!==q.interceptors[K])return!1;return!0}_getInterceptors(){return this.interceptors}_addWatcher(q){this.childCredentials._addWatcher(q)}_removeWatcher(q){this.childCredentials._removeWatcher(q)}_getConstructorOptions(){return this.childCredentials._getConstructorOptions()}_getSecureContextOptions(){return this.childCredentials._getSecureContextOptions()}}function gRz(q,K){return new Cc1(q,K)}});var Ht6=m((Jo4)=>{Object.defineProperty(Jo4,"__esModule",{value:!0});Jo4.durationMessageToDuration=QRz;Jo4.msToDuration=dRz;Jo4.durationToMs=cRz;Jo4.isDuration=lRz;Jo4.isDurationMessage=nRz;Jo4.parseDuration=rRz;Jo4.durationToString=oRz;function QRz(q){return{seconds:Number.parseInt(q.seconds),nanos:q.nanos}}function dRz(q){return{seconds:q/1000|0,nanos:q%1000*1e6|0}}function cRz(q){return q.seconds*1000+q.nanos/1e6|0}function lRz(q){return typeof q.seconds==="number"&&typeof q.nanos==="number"}function nRz(q){return typeof q.seconds==="string"&&typeof q.nanos==="number"}var iRz=/^(\d+)(?:\.(\d+))?s$/;function rRz(q){let K=q.match(iRz);if(!K)return null;return{seconds:Number.parseInt(K[1],10),nanos:K[2]?Number.parseInt(K[2].padEnd(9,"0"),10):0}}function oRz(q){if(q.nanos===0)return`${q.seconds}s`;let K;if(q.nanos%1e6===0)K=1e6;else if(q.nanos%1000===0)K=1000;else K=1;return`${q.seconds}.${q.nanos/K}s`}});var ih8=m((ko4)=>{var __dirname="/home/runner/code/tmp/claude-cli-external-build-2195/node_modules/@grpc/grpc-js/build/src";Object.defineProperty(ko4,"__esModule",{value:!0});ko4.OrcaOobMetricsSubchannelWrapper=ko4.GRPC_METRICS_HEADER=ko4.ServerMetricRecorder=ko4.PerRequestMetricRecorder=void 0;ko4.createOrcaClient=fo4;ko4.createMetricsReader=jhz;var zhz=Kh8(),bc1=Ht6(),Yhz=Wy6(),$hz=wt6(),Mo4=c_(),Ahz=Dy6(),Ohz=ev(),Xo4=null;function nh8(){if(Xo4)return Xo4;let q=od1().loadSync,K=q("xds/service/orca/v3/orca.proto",{keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0,includeDirs:[`${__dirname}/../../proto/xds`,`${__dirname}/../../proto/protoc-gen-validate`]});return(0,zhz.loadPackageDefinition)(K)}class Wo4{constructor(){this.message={}}recordRequestCostMetric(q,K){if(!this.message.request_cost)this.message.request_cost={};this.message.request_cost[q]=K}recordUtilizationMetric(q,K){if(!this.message.utilization)this.message.utilization={};this.message.utilization[q]=K}recordNamedMetric(q,K){if(!this.message.named_metrics)this.message.named_metrics={};this.message.named_metrics[q]=K}recordCPUUtilizationMetric(q){this.message.cpu_utilization=q}recordMemoryUtilizationMetric(q){this.message.mem_utilization=q}recordApplicationUtilizationMetric(q){this.message.application_utilization=q}recordQpsMetric(q){this.message.rps_fractional=q}recordEpsMetric(q){this.message.eps=q}serialize(){return nh8().xds.data.orca.v3.OrcaLoadReport.serialize(this.message)}}ko4.PerRequestMetricRecorder=Wo4;var whz=30000;class Do4{constructor(){this.message={},this.serviceImplementation={StreamCoreMetrics:(q)=>{let K=q.request.report_interval?(0,bc1.durationToMs)((0,bc1.durationMessageToDuration)(q.request.report_interval)):whz,_=setInterval(()=>{q.write(this.message)},K);q.on("cancelled",()=>{clearInterval(_)})}}}putUtilizationMetric(q,K){if(!this.message.utilization)this.message.utilization={};this.message.utilization[q]=K}setAllUtilizationMetrics(q){this.message.utilization=Object.assign({},q)}deleteUtilizationMetric(q){var K;(K=this.message.utilization)===null||K===void 0||delete K[q]}setCpuUtilizationMetric(q){this.message.cpu_utilization=q}deleteCpuUtilizationMetric(){delete this.message.cpu_utilization}setApplicationUtilizationMetric(q){this.message.application_utilization=q}deleteApplicationUtilizationMetric(){delete this.message.application_utilization}setQpsMetric(q){this.message.rps_fractional=q}deleteQpsMetric(){delete this.message.rps_fractional}setEpsMetric(q){this.message.eps=q}deleteEpsMetric(){delete this.message.eps}addToServer(q){let K=nh8().xds.service.orca.v3.OpenRcaService.service;q.addService(K,this.serviceImplementation)}}ko4.ServerMetricRecorder=Do4;function fo4(q){return new(nh8()).xds.service.orca.v3.OpenRcaService("unused",Yhz.ChannelCredentials.createInsecure(),{channelOverride:q})}ko4.GRPC_METRICS_HEADER="endpoint-load-metrics-bin";var Po4="grpc_orca_load_report";function jhz(q,K){return(_,z,Y)=>{let $=Y.getOpaque(Po4);if($)q($);else{let A=Y.get(ko4.GRPC_METRICS_HEADER);if(A.length>0)$=nh8().xds.data.orca.v3.OrcaLoadReport.deserialize(A[0]),q($),Y.setOpaque(Po4,$)}if(K)K(_,z,Y)}}var Zo4="orca_oob_metrics";class Go4{constructor(q,K){this.metricsListener=q,this.intervalMs=K,this.dataProducer=null}setSubchannel(q){let K=q.getOrCreateDataProducer(Zo4,Hhz);this.dataProducer=K,K.addDataWatcher(this)}destroy(){var q;(q=this.dataProducer)===null||q===void 0||q.removeDataWatcher(this)}getInterval(){return this.intervalMs}onMetricsUpdate(q){this.metricsListener(q)}}class To4{constructor(q){this.subchannel=q,this.dataWatchers=new Set,this.orcaSupported=!0,this.metricsCall=null,this.currentInterval=1/0,this.backoffTimer=new Ahz.BackoffTimeout(()=>this.updateMetricsSubscription()),this.subchannelStateListener=()=>this.updateMetricsSubscription();let K=q.getChannel();this.client=fo4(K),q.addConnectivityStateListener(this.subchannelStateListener)}addDataWatcher(q){this.dataWatchers.add(q),this.updateMetricsSubscription()}removeDataWatcher(q){var K;if(this.dataWatchers.delete(q),this.dataWatchers.size===0)this.subchannel.removeDataProducer(Zo4),(K=this.metricsCall)===null||K===void 0||K.cancel(),this.metricsCall=null,this.client.close(),this.subchannel.removeConnectivityStateListener(this.subchannelStateListener);else this.updateMetricsSubscription()}updateMetricsSubscription(){var q;if(this.dataWatchers.size===0||!this.orcaSupported||this.subchannel.getConnectivityState()!==Ohz.ConnectivityState.READY)return;let K=Math.min(...Array.from(this.dataWatchers).map((_)=>_.getInterval()));if(!this.metricsCall||K!==this.currentInterval){(q=this.metricsCall)===null||q===void 0||q.cancel(),this.currentInterval=K;let _=this.client.streamCoreMetrics({report_interval:(0,bc1.msToDuration)(K)});this.metricsCall=_,_.on("data",(z)=>{this.dataWatchers.forEach((Y)=>{Y.onMetricsUpdate(z)})}),_.on("error",(z)=>{if(this.metricsCall=null,z.code===Mo4.Status.UNIMPLEMENTED){this.orcaSupported=!1;return}if(z.code===Mo4.Status.CANCELLED)return;this.backoffTimer.runOnce()})}}}class vo4 extends $hz.BaseSubchannelWrapper{constructor(q,K,_){super(q);this.addDataWatcher(new Go4(K,_))}getWrappedSubchannel(){return this.child}}ko4.OrcaOobMetricsSubchannelWrapper=vo4;function Hhz(q){return new To4(q)}});var mc1=m((Bo4)=>{Object.defineProperty(Bo4,"__esModule",{value:!0});Bo4.BaseServerInterceptingCall=Bo4.ServerInterceptingCall=Bo4.ResponderBuilder=Bo4.ServerListenerBuilder=void 0;Bo4.isInterceptingServerListener=fhz;Bo4.getServerInterceptingCall=khz;var ah8=vD(),UN=c_(),my6=U6("http2"),yo4=gR8(),Eo4=U6("zlib"),Whz=Pc1(),Co4=Gw(),Dhz=U6("tls"),Lo4=ih8(),bo4="server_call";function v26(q){Co4.trace(UN.LogVerbosity.DEBUG,bo4,q)}class xo4{constructor(){this.metadata=void 0,this.message=void 0,this.halfClose=void 0,this.cancel=void 0}withOnReceiveMetadata(q){return this.metadata=q,this}withOnReceiveMessage(q){return this.message=q,this}withOnReceiveHalfClose(q){return this.halfClose=q,this}withOnCancel(q){return this.cancel=q,this}build(){return{onReceiveMetadata:this.metadata,onReceiveMessage:this.message,onReceiveHalfClose:this.halfClose,onCancel:this.cancel}}}Bo4.ServerListenerBuilder=xo4;function fhz(q){return q.onReceiveMetadata!==void 0&&q.onReceiveMetadata.length===1}class Io4{constructor(q,K){this.listener=q,this.nextListener=K,this.cancelled=!1,this.processingMetadata=!1,this.hasPendingMessage=!1,this.pendingMessage=null,this.processingMessage=!1,this.hasPendingHalfClose=!1}processPendingMessage(){if(this.hasPendingMessage)this.nextListener.onReceiveMessage(this.pendingMessage),this.pendingMessage=null,this.hasPendingMessage=!1}processPendingHalfClose(){if(this.hasPendingHalfClose)this.nextListener.onReceiveHalfClose(),this.hasPendingHalfClose=!1}onReceiveMetadata(q){if(this.cancelled)return;this.processingMetadata=!0,this.listener.onReceiveMetadata(q,(K)=>{if(this.processingMetadata=!1,this.cancelled)return;this.nextListener.onReceiveMetadata(K),this.processPendingMessage(),this.processPendingHalfClose()})}onReceiveMessage(q){if(this.cancelled)return;this.processingMessage=!0,this.listener.onReceiveMessage(q,(K)=>{if(this.processingMessage=!1,this.cancelled)return;if(this.processingMetadata)this.pendingMessage=K,this.hasPendingMessage=!0;else this.nextListener.onReceiveMessage(K),this.processPendingHalfClose()})}onReceiveHalfClose(){if(this.cancelled)return;this.listener.onReceiveHalfClose(()=>{if(this.cancelled)return;if(this.processingMetadata||this.processingMessage)this.hasPendingHalfClose=!0;else this.nextListener.onReceiveHalfClose()})}onCancel(){this.cancelled=!0,this.listener.onCancel(),this.nextListener.onCancel()}}class uo4{constructor(){this.start=void 0,this.metadata=void 0,this.message=void 0,this.status=void 0}withStart(q){return this.start=q,this}withSendMetadata(q){return this.metadata=q,this}withSendMessage(q){return this.message=q,this}withSendStatus(q){return this.status=q,this}build(){return{start:this.start,sendMetadata:this.metadata,sendMessage:this.message,sendStatus:this.status}}}Bo4.ResponderBuilder=uo4;var rh8={onReceiveMetadata:(q,K)=>{K(q)},onReceiveMessage:(q,K)=>{K(q)},onReceiveHalfClose:(q)=>{q()},onCancel:()=>{}},oh8={start:(q)=>{q()},sendMetadata:(q,K)=>{K(q)},sendMessage:(q,K)=>{K(q)},sendStatus:(q,K)=>{K(q)}};class mo4{constructor(q,K){var _,z,Y,$;this.nextCall=q,this.processingMetadata=!1,this.sentMetadata=!1,this.processingMessage=!1,this.pendingMessage=null,this.pendingMessageCallback=null,this.pendingStatus=null,this.responder={start:(_=K===null||K===void 0?void 0:K.start)!==null&&_!==void 0?_:oh8.start,sendMetadata:(z=K===null||K===void 0?void 0:K.sendMetadata)!==null&&z!==void 0?z:oh8.sendMetadata,sendMessage:(Y=K===null||K===void 0?void 0:K.sendMessage)!==null&&Y!==void 0?Y:oh8.sendMessage,sendStatus:($=K===null||K===void 0?void 0:K.sendStatus)!==null&&$!==void 0?$:oh8.sendStatus}}processPendingMessage(){if(this.pendingMessageCallback)this.nextCall.sendMessage(this.pendingMessage,this.pendingMessageCallback),this.pendingMessage=null,this.pendingMessageCallback=null}processPendingStatus(){if(this.pendingStatus)this.nextCall.sendStatus(this.pendingStatus),this.pendingStatus=null}start(q){this.responder.start((K)=>{var _,z,Y,$;let A={onReceiveMetadata:(_=K===null||K===void 0?void 0:K.onReceiveMetadata)!==null&&_!==void 0?_:rh8.onReceiveMetadata,onReceiveMessage:(z=K===null||K===void 0?void 0:K.onReceiveMessage)!==null&&z!==void 0?z:rh8.onReceiveMessage,onReceiveHalfClose:(Y=K===null||K===void 0?void 0:K.onReceiveHalfClose)!==null&&Y!==void 0?Y:rh8.onReceiveHalfClose,onCancel:($=K===null||K===void 0?void 0:K.onCancel)!==null&&$!==void 0?$:rh8.onCancel},O=new Io4(A,q);this.nextCall.start(O)})}sendMetadata(q){this.processingMetadata=!0,this.sentMetadata=!0,this.responder.sendMetadata(q,(K)=>{this.processingMetadata=!1,this.nextCall.sendMetadata(K),this.processPendingMessage(),this.processPendingStatus()})}sendMessage(q,K){if(this.processingMessage=!0,!this.sentMetadata)this.sendMetadata(new ah8.Metadata);this.responder.sendMessage(q,(_)=>{if(this.processingMessage=!1,this.processingMetadata)this.pendingMessage=_,this.pendingMessageCallback=K;else this.nextCall.sendMessage(_,K)})}sendStatus(q){this.responder.sendStatus(q,(K)=>{if(this.processingMetadata||this.processingMessage)this.pendingStatus=K;else this.nextCall.sendStatus(K)})}startRead(){this.nextCall.startRead()}getPeer(){return this.nextCall.getPeer()}getDeadline(){return this.nextCall.getDeadline()}getHost(){return this.nextCall.getHost()}getAuthContext(){return this.nextCall.getAuthContext()}getConnectionInfo(){return this.nextCall.getConnectionInfo()}getMetricsRecorder(){return this.nextCall.getMetricsRecorder()}}Bo4.ServerInterceptingCall=mo4;var po4="grpc-accept-encoding",Ic1="grpc-encoding",Ro4="grpc-message",ho4="grpc-status",xc1="grpc-timeout",Zhz=/(\d{1,8})\s*([HMSmun])/,Ghz={H:3600000,M:60000,S:1000,m:1,u:0.001,n:0.000001},Thz={[po4]:"identity,deflate,gzip",[Ic1]:"identity"},So4={[my6.constants.HTTP2_HEADER_STATUS]:my6.constants.HTTP_STATUS_OK,[my6.constants.HTTP2_HEADER_CONTENT_TYPE]:"application/grpc+proto"},vhz={waitForTrailers:!0};class uc1{constructor(q,K,_,z,Y){var $,A;if(this.stream=q,this.callEventTracker=_,this.handler=z,this.listener=null,this.deadlineTimer=null,this.deadline=1/0,this.maxSendMessageSize=UN.DEFAULT_MAX_SEND_MESSAGE_LENGTH,this.maxReceiveMessageSize=UN.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH,this.cancelled=!1,this.metadataSent=!1,this.wantTrailers=!1,this.cancelNotified=!1,this.incomingEncoding="identity",this.readQueue=[],this.isReadPending=!1,this.receivedHalfClose=!1,this.streamEnded=!1,this.metricsRecorder=new Lo4.PerRequestMetricRecorder,this.stream.once("error",(J)=>{}),this.stream.once("close",()=>{var J;if(v26("Request to method "+((J=this.handler)===null||J===void 0?void 0:J.path)+" stream closed with rstCode "+this.stream.rstCode),this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!1),this.callEventTracker.onCallEnd({code:UN.Status.CANCELLED,details:"Stream closed before sending status",metadata:null});this.notifyOnCancel()}),this.stream.on("data",(J)=>{this.handleDataFrame(J)}),this.stream.pause(),this.stream.on("end",()=>{this.handleEndEvent()}),"grpc.max_send_message_length"in Y)this.maxSendMessageSize=Y["grpc.max_send_message_length"];if("grpc.max_receive_message_length"in Y)this.maxReceiveMessageSize=Y["grpc.max_receive_message_length"];this.host=($=K[":authority"])!==null&&$!==void 0?$:K.host,this.decoder=new Whz.StreamDecoder(this.maxReceiveMessageSize);let O=ah8.Metadata.fromHttp2Headers(K);if(Co4.isTracerEnabled(bo4))v26("Request to "+this.handler.path+" received headers "+JSON.stringify(O.toJSON()));let w=O.get(xc1);if(w.length>0)this.handleTimeoutHeader(w[0]);let j=O.get(Ic1);if(j.length>0)this.incomingEncoding=j[0];O.remove(xc1),O.remove(Ic1),O.remove(po4),O.remove(my6.constants.HTTP2_HEADER_ACCEPT_ENCODING),O.remove(my6.constants.HTTP2_HEADER_TE),O.remove(my6.constants.HTTP2_HEADER_CONTENT_TYPE),this.metadata=O;let H=(A=q.session)===null||A===void 0?void 0:A.socket;this.connectionInfo={localAddress:H===null||H===void 0?void 0:H.localAddress,localPort:H===null||H===void 0?void 0:H.localPort,remoteAddress:H===null||H===void 0?void 0:H.remoteAddress,remotePort:H===null||H===void 0?void 0:H.remotePort},this.shouldSendMetrics=!!Y["grpc.server_call_metric_recording"]}handleTimeoutHeader(q){let K=q.toString().match(Zhz);if(K===null){let Y={code:UN.Status.INTERNAL,details:`Invalid ${xc1} value "${q}"`,metadata:null};process.nextTick(()=>{this.sendStatus(Y)});return}let _=+K[1]*Ghz[K[2]]|0,z=new Date;this.deadline=z.setMilliseconds(z.getMilliseconds()+_),this.deadlineTimer=setTimeout(()=>{let Y={code:UN.Status.DEADLINE_EXCEEDED,details:"Deadline exceeded",metadata:null};this.sendStatus(Y)},_)}checkCancelled(){if(!this.cancelled&&(this.stream.destroyed||this.stream.closed))this.notifyOnCancel(),this.cancelled=!0;return this.cancelled}notifyOnCancel(){if(this.cancelNotified)return;if(this.cancelNotified=!0,this.cancelled=!0,process.nextTick(()=>{var q;(q=this.listener)===null||q===void 0||q.onCancel()}),this.deadlineTimer)clearTimeout(this.deadlineTimer);this.stream.resume()}maybeSendMetadata(){if(!this.metadataSent)this.sendMetadata(new ah8.Metadata)}serializeMessage(q){let K=this.handler.serialize(q),_=K.byteLength,z=Buffer.allocUnsafe(_+5);return z.writeUInt8(0,0),z.writeUInt32BE(_,1),K.copy(z,5),z}decompressMessage(q,K){let _=q.subarray(5);if(K==="identity")return _;else if(K==="deflate"||K==="gzip"){let z;if(K==="deflate")z=Eo4.createInflate();else z=Eo4.createGunzip();return new Promise((Y,$)=>{let A=0,O=[];z.on("data",(w)=>{if(O.push(w),A+=w.byteLength,this.maxReceiveMessageSize!==-1&&A>this.maxReceiveMessageSize)z.destroy(),$({code:UN.Status.RESOURCE_EXHAUSTED,details:`Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}`})}),z.on("end",()=>{Y(Buffer.concat(O))}),z.write(_),z.end()})}else return Promise.reject({code:UN.Status.UNIMPLEMENTED,details:`Received message compressed with unsupported encoding "${K}"`})}async decompressAndMaybePush(q){if(q.type!=="COMPRESSED")throw Error(`Invalid queue entry type: ${q.type}`);let _=q.compressedMessage.readUInt8(0)===1?this.incomingEncoding:"identity",z;try{z=await this.decompressMessage(q.compressedMessage,_)}catch(Y){this.sendStatus(Y);return}try{q.parsedMessage=this.handler.deserialize(z)}catch(Y){this.sendStatus({code:UN.Status.INTERNAL,details:`Error deserializing request: ${Y.message}`});return}q.type="READABLE",this.maybePushNextMessage()}maybePushNextMessage(){if(this.listener&&this.isReadPending&&this.readQueue.length>0&&this.readQueue[0].type!=="COMPRESSED"){this.isReadPending=!1;let q=this.readQueue.shift();if(q.type==="READABLE")this.listener.onReceiveMessage(q.parsedMessage);else this.listener.onReceiveHalfClose()}}handleDataFrame(q){var K;if(this.checkCancelled())return;v26("Request to "+this.handler.path+" received data frame of size "+q.length);let _;try{_=this.decoder.write(q)}catch(z){this.sendStatus({code:UN.Status.RESOURCE_EXHAUSTED,details:z.message});return}for(let z of _){this.stream.pause();let Y={type:"COMPRESSED",compressedMessage:z,parsedMessage:null};this.readQueue.push(Y),this.decompressAndMaybePush(Y),(K=this.callEventTracker)===null||K===void 0||K.addMessageReceived()}}handleEndEvent(){this.readQueue.push({type:"HALF_CLOSE",compressedMessage:null,parsedMessage:null}),this.receivedHalfClose=!0,this.maybePushNextMessage()}start(q){if(v26("Request to "+this.handler.path+" start called"),this.checkCancelled())return;this.listener=q,q.onReceiveMetadata(this.metadata)}sendMetadata(q){if(this.checkCancelled())return;if(this.metadataSent)return;this.metadataSent=!0;let K=q?q.toHttp2Headers():null,_=Object.assign(Object.assign(Object.assign({},So4),Thz),K);this.stream.respond(_,vhz)}sendMessage(q,K){if(this.checkCancelled())return;let _;try{_=this.serializeMessage(q)}catch(z){this.sendStatus({code:UN.Status.INTERNAL,details:`Error serializing response: ${(0,yo4.getErrorMessage)(z)}`,metadata:null});return}if(this.maxSendMessageSize!==-1&&_.length-5>this.maxSendMessageSize){this.sendStatus({code:UN.Status.RESOURCE_EXHAUSTED,details:`Sent message larger than max (${_.length} vs. ${this.maxSendMessageSize})`,metadata:null});return}this.maybeSendMetadata(),v26("Request to "+this.handler.path+" sent data frame of size "+_.length),this.stream.write(_,(z)=>{var Y;if(z){this.sendStatus({code:UN.Status.INTERNAL,details:`Error writing message: ${(0,yo4.getErrorMessage)(z)}`,metadata:null});return}(Y=this.callEventTracker)===null||Y===void 0||Y.addMessageSent(),K()})}sendStatus(q){var K,_,z;if(this.checkCancelled())return;v26("Request to method "+((K=this.handler)===null||K===void 0?void 0:K.path)+" ended with status code: "+UN.Status[q.code]+" details: "+q.details);let Y=(z=(_=q.metadata)===null||_===void 0?void 0:_.clone())!==null&&z!==void 0?z:new ah8.Metadata;if(this.shouldSendMetrics)Y.set(Lo4.GRPC_METRICS_HEADER,this.metricsRecorder.serialize());if(this.metadataSent)if(!this.wantTrailers)this.wantTrailers=!0,this.stream.once("wantTrailers",()=>{if(this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!0),this.callEventTracker.onCallEnd(q);let $=Object.assign({[ho4]:q.code,[Ro4]:encodeURI(q.details)},Y.toHttp2Headers());this.stream.sendTrailers($),this.notifyOnCancel()}),this.stream.end();else this.notifyOnCancel();else{if(this.callEventTracker&&!this.streamEnded)this.streamEnded=!0,this.callEventTracker.onStreamEnd(!0),this.callEventTracker.onCallEnd(q);let $=Object.assign(Object.assign({[ho4]:q.code,[Ro4]:encodeURI(q.details)},So4),Y.toHttp2Headers());this.stream.respond($,{endStream:!0}),this.notifyOnCancel()}}startRead(){if(v26("Request to "+this.handler.path+" startRead called"),this.checkCancelled())return;if(this.isReadPending=!0,this.readQueue.length===0){if(!this.receivedHalfClose)this.stream.resume()}else this.maybePushNextMessage()}getPeer(){var q;let K=(q=this.stream.session)===null||q===void 0?void 0:q.socket;if(K===null||K===void 0?void 0:K.remoteAddress)if(K.remotePort)return`${K.remoteAddress}:${K.remotePort}`;else return K.remoteAddress;else return"unknown"}getDeadline(){return this.deadline}getHost(){return this.host}getAuthContext(){var q;if(((q=this.stream.session)===null||q===void 0?void 0:q.socket)instanceof Dhz.TLSSocket){let K=this.stream.session.socket.getPeerCertificate();return{transportSecurityType:"ssl",sslPeerCertificate:K.raw?K:void 0}}else return{}}getConnectionInfo(){return this.connectionInfo}getMetricsRecorder(){return this.metricsRecorder}}Bo4.BaseServerInterceptingCall=uc1;function khz(q,K,_,z,Y,$){let A={path:Y.path,requestStream:Y.type==="clientStream"||Y.type==="bidi",responseStream:Y.type==="serverStream"||Y.type==="bidi",requestDeserialize:Y.deserialize,responseSerialize:Y.serialize},O=new uc1(K,_,z,Y,$);return q.reduce((w,j)=>{return j(A,w)},O)}});var no4=m((L46)=>{var Rhz=L46&&L46.__runInitializers||function(q,K,_){var z=arguments.length>2;for(var Y=0;Y<K.length;Y++)_=z?K[Y].call(q,_):K[Y].call(q);return z?_:void 0},hhz=L46&&L46.__esDecorate||function(q,K,_,z,Y,$){function A(f){if(f!==void 0&&typeof f!=="function")throw TypeError("Function expected");return f}var O=z.kind,w=O==="getter"?"get":O==="setter"?"set":"value",j=!K&&q?z.static?q:q.prototype:null,H=K||(j?Object.getOwnPropertyDescriptor(j,z.name):{}),J,M=!1;for(var X=_.length-1;X>=0;X--){var P={};for(var W in z)P[W]=W==="access"?{}:z[W];for(var W in z.access)P.access[W]=z.access[W];P.addInitializer=function(f){if(M)throw TypeError("Cannot add initializers after decoration has completed");$.push(A(f||null))};var D=(0,_[X])(O==="accessor"?{get:H.get,set:H.set}:H[w],P);if(O==="accessor"){if(D===void 0)continue;if(D===null||typeof D!=="object")throw TypeError("Object expected");if(J=A(D.get))H.get=J;if(J=A(D.set))H.set=J;if(J=A(D.init))Y.unshift(J)}else if(J=A(D))if(O==="field")Y.unshift(J);else H[w]=J}if(j)Object.defineProperty(j,z.name,H);M=!0};Object.defineProperty(L46,"__esModule",{value:!0});L46.Server=void 0;var QN=U6("http2"),Shz=U6("util"),GM=c_(),gy6=wo4(),pc1=lh8(),Fo4=Tm(),By6=Gw(),E46=FN(),Em=tv(),UP=V46(),Uo4=mc1(),py6=2147483647,Bc1=2147483647,Chz=20000,Qo4=2147483647,{HTTP2_HEADER_PATH:do4}=QN.constants,bhz="server",co4=Buffer.from("max_age");function lo4(q){By6.trace(GM.LogVerbosity.DEBUG,"server_call",q)}function xhz(){}function Ihz(q){return function(K,_){return Shz.deprecate(K,q)}}function gc1(q){return{code:GM.Status.UNIMPLEMENTED,details:`The server does not implement the method ${q}`}}function uhz(q,K){let _=gc1(K);switch(q){case"unary":return(z,Y)=>{Y(_,null)};case"clientStream":return(z,Y)=>{Y(_,null)};case"serverStream":return(z)=>{z.emit("error",_)};case"bidi":return(z)=>{z.emit("error",_)};default:throw Error(`Invalid handlerType ${q}`)}}var mhz=(()=>{var q;let K=[],_;return q=class{constructor(Y){var $,A,O,w,j,H;if(this.boundPorts=(Rhz(this,K),new Map),this.http2Servers=new Map,this.sessionIdleTimeouts=new Map,this.handlers=new Map,this.sessions=new Map,this.started=!1,this.shutdown=!1,this.serverAddressString="null",this.channelzEnabled=!0,this.options=Y!==null&&Y!==void 0?Y:{},this.options["grpc.enable_channelz"]===0)this.channelzEnabled=!1,this.channelzTrace=new UP.ChannelzTraceStub,this.callTracker=new UP.ChannelzCallTrackerStub,this.listenerChildrenTracker=new UP.ChannelzChildrenTrackerStub,this.sessionChildrenTracker=new UP.ChannelzChildrenTrackerStub;else this.channelzTrace=new UP.ChannelzTrace,this.callTracker=new UP.ChannelzCallTracker,this.listenerChildrenTracker=new UP.ChannelzChildrenTracker,this.sessionChildrenTracker=new UP.ChannelzChildrenTracker;if(this.channelzRef=(0,UP.registerChannelzServer)("server",()=>this.getChannelzInfo(),this.channelzEnabled),this.channelzTrace.addTrace("CT_INFO","Server created"),this.maxConnectionAgeMs=($=this.options["grpc.max_connection_age_ms"])!==null&&$!==void 0?$:py6,this.maxConnectionAgeGraceMs=(A=this.options["grpc.max_connection_age_grace_ms"])!==null&&A!==void 0?A:py6,this.keepaliveTimeMs=(O=this.options["grpc.keepalive_time_ms"])!==null&&O!==void 0?O:Bc1,this.keepaliveTimeoutMs=(w=this.options["grpc.keepalive_timeout_ms"])!==null&&w!==void 0?w:Chz,this.sessionIdleTimeout=(j=this.options["grpc.max_connection_idle_ms"])!==null&&j!==void 0?j:Qo4,this.commonServerOptions={maxSendHeaderBlockLength:Number.MAX_SAFE_INTEGER},"grpc-node.max_session_memory"in this.options)this.commonServerOptions.maxSessionMemory=this.options["grpc-node.max_session_memory"];else this.commonServerOptions.maxSessionMemory=Number.MAX_SAFE_INTEGER;if("grpc.max_concurrent_streams"in this.options)this.commonServerOptions.settings={maxConcurrentStreams:this.options["grpc.max_concurrent_streams"]};this.interceptors=(H=this.options.interceptors)!==null&&H!==void 0?H:[],this.trace("Server constructed")}getChannelzInfo(){return{trace:this.channelzTrace,callTracker:this.callTracker,listenerChildren:this.listenerChildrenTracker.getChildLists(),sessionChildren:this.sessionChildrenTracker.getChildLists()}}getChannelzSessionInfo(Y){var $,A,O;let w=this.sessions.get(Y),j=Y.socket,H=j.remoteAddress?(0,E46.stringToSubchannelAddress)(j.remoteAddress,j.remotePort):null,J=j.localAddress?(0,E46.stringToSubchannelAddress)(j.localAddress,j.localPort):null,M;if(Y.encrypted){let P=j,W=P.getCipher(),D=P.getCertificate(),f=P.getPeerCertificate();M={cipherSuiteStandardName:($=W.standardName)!==null&&$!==void 0?$:null,cipherSuiteOtherName:W.standardName?null:W.name,localCertificate:D&&"raw"in D?D.raw:null,remoteCertificate:f&&"raw"in f?f.raw:null}}else M=null;return{remoteAddress:H,localAddress:J,security:M,remoteName:null,streamsStarted:w.streamTracker.callsStarted,streamsSucceeded:w.streamTracker.callsSucceeded,streamsFailed:w.streamTracker.callsFailed,messagesSent:w.messagesSent,messagesReceived:w.messagesReceived,keepAlivesSent:w.keepAlivesSent,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:w.streamTracker.lastCallStartedTimestamp,lastMessageSentTimestamp:w.lastMessageSentTimestamp,lastMessageReceivedTimestamp:w.lastMessageReceivedTimestamp,localFlowControlWindow:(A=Y.state.localWindowSize)!==null&&A!==void 0?A:null,remoteFlowControlWindow:(O=Y.state.remoteWindowSize)!==null&&O!==void 0?O:null}}trace(Y){By6.trace(GM.LogVerbosity.DEBUG,bhz,"("+this.channelzRef.id+") "+Y)}keepaliveTrace(Y){By6.trace(GM.LogVerbosity.DEBUG,"keepalive","("+this.channelzRef.id+") "+Y)}addProtoService(){throw Error("Not implemented. Use addService() instead")}addService(Y,$){if(Y===null||typeof Y!=="object"||$===null||typeof $!=="object")throw Error("addService() requires two objects as arguments");let A=Object.keys(Y);if(A.length===0)throw Error("Cannot add an empty service to a server");A.forEach((O)=>{let w=Y[O],j;if(w.requestStream)if(w.responseStream)j="bidi";else j="clientStream";else if(w.responseStream)j="serverStream";else j="unary";let H=$[O],J;if(H===void 0&&typeof w.originalName==="string")H=$[w.originalName];if(H!==void 0)J=H.bind($);else J=uhz(j,O);if(this.register(w.path,J,w.responseSerialize,w.requestDeserialize,j)===!1)throw Error(`Method handler for ${w.path} already provided.`)})}removeService(Y){if(Y===null||typeof Y!=="object")throw Error("removeService() requires object as argument");Object.keys(Y).forEach((A)=>{let O=Y[A];this.unregister(O.path)})}bind(Y,$){throw Error("Not implemented. Use bindAsync() instead")}experimentalRegisterListenerToChannelz(Y){return(0,UP.registerChannelzSocket)((0,E46.subchannelAddressToString)(Y),()=>{return{localAddress:Y,remoteAddress:null,security:null,remoteName:null,streamsStarted:0,streamsSucceeded:0,streamsFailed:0,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:null,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null,localFlowControlWindow:null,remoteFlowControlWindow:null}},this.channelzEnabled)}experimentalUnregisterListenerFromChannelz(Y){(0,UP.unregisterChannelzRef)(Y)}createHttp2Server(Y){let $;if(Y._isSecure()){let A=Y._getConstructorOptions(),O=Y._getSecureContextOptions(),w=Object.assign(Object.assign(Object.assign(Object.assign({},this.commonServerOptions),A),O),{enableTrace:this.options["grpc-node.tls_enable_trace"]===1}),j=O!==null;this.trace("Initial credentials valid: "+j),$=QN.createSecureServer(w),$.prependListener("connection",(J)=>{if(!j)this.trace("Dropped connection from "+JSON.stringify(J.address())+" due to unloaded credentials"),J.destroy()}),$.on("secureConnection",(J)=>{J.on("error",(M)=>{this.trace("An incoming TLS connection closed with error: "+M.message)})});let H=(J)=>{if(J){let M=$;try{M.setSecureContext(J)}catch(X){By6.log(GM.LogVerbosity.ERROR,"Failed to set secure context with error "+X.message),J=null}}j=J!==null,this.trace("Post-update credentials valid: "+j)};Y._addWatcher(H),$.on("close",()=>{Y._removeWatcher(H)})}else $=QN.createServer(this.commonServerOptions);return $.setTimeout(0,xhz),this._setupHandlers($,Y._getInterceptors()),$}bindOneAddress(Y,$){this.trace("Attempting to bind "+(0,E46.subchannelAddressToString)(Y));let A=this.createHttp2Server($.credentials);return new Promise((O,w)=>{let j=(H)=>{this.trace("Failed to bind "+(0,E46.subchannelAddressToString)(Y)+" with error "+H.message),O({port:"port"in Y?Y.port:1,error:H.message})};A.once("error",j),A.listen(Y,()=>{let H=A.address(),J;if(typeof H==="string")J={path:H};else J={host:H.address,port:H.port};let M=this.experimentalRegisterListenerToChannelz(J);this.listenerChildrenTracker.refChild(M),this.http2Servers.set(A,{channelzRef:M,sessions:new Set,ownsChannelzRef:!0}),$.listeningServers.add(A),this.trace("Successfully bound "+(0,E46.subchannelAddressToString)(J)),O({port:"port"in J?J.port:1}),A.removeListener("error",j)})})}async bindManyPorts(Y,$){if(Y.length===0)return{count:0,port:0,errors:[]};if((0,E46.isTcpSubchannelAddress)(Y[0])&&Y[0].port===0){let A=await this.bindOneAddress(Y[0],$);if(A.error){let O=await this.bindManyPorts(Y.slice(1),$);return Object.assign(Object.assign({},O),{errors:[A.error,...O.errors]})}else{let O=Y.slice(1).map((H)=>(0,E46.isTcpSubchannelAddress)(H)?{host:H.host,port:A.port}:H),w=await Promise.all(O.map((H)=>this.bindOneAddress(H,$))),j=[A,...w];return{count:j.filter((H)=>H.error===void 0).length,port:A.port,errors:j.filter((H)=>H.error).map((H)=>H.error)}}}else{let A=await Promise.all(Y.map((O)=>this.bindOneAddress(O,$)));return{count:A.filter((O)=>O.error===void 0).length,port:A[0].port,errors:A.filter((O)=>O.error).map((O)=>O.error)}}}async bindAddressList(Y,$){let A=await this.bindManyPorts(Y,$);if(A.count>0){if(A.count<Y.length)By6.log(GM.LogVerbosity.INFO,`WARNING Only ${A.count} addresses added out of total ${Y.length} resolved`);return A.port}else{let O=`No address added out of total ${Y.length} resolved`;throw By6.log(GM.LogVerbosity.ERROR,O),Error(`${O} errors: [${A.errors.join(",")}]`)}}resolvePort(Y){return new Promise(($,A)=>{let O=!1,w=(H,J,M,X)=>{if(O)return!0;if(O=!0,!H.ok)return A(Error(H.error.details)),!0;let P=[].concat(...H.value.map((W)=>W.addresses));if(P.length===0)return A(Error(`No addresses resolved for port ${Y}`)),!0;return $(P),!0};(0,Fo4.createResolver)(Y,w,this.options).updateResolution()})}async bindPort(Y,$){let A=await this.resolvePort(Y);if($.cancelled)throw this.completeUnbind($),Error("bindAsync operation cancelled by unbind call");let O=await this.bindAddressList(A,$);if($.cancelled)throw this.completeUnbind($),Error("bindAsync operation cancelled by unbind call");return O}normalizePort(Y){let $=(0,Em.parseUri)(Y);if($===null)throw Error(`Could not parse port "${Y}"`);let A=(0,Fo4.mapUriDefaultScheme)($);if(A===null)throw Error(`Could not get a default scheme for port "${Y}"`);return A}bindAsync(Y,$,A){if(this.shutdown)throw Error("bindAsync called after shutdown");if(typeof Y!=="string")throw TypeError("port must be a string");if($===null||!($ instanceof pc1.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");if(typeof A!=="function")throw TypeError("callback must be a function");this.trace("bindAsync port="+Y);let O=this.normalizePort(Y),w=(M,X)=>{process.nextTick(()=>A(M,X))},j=this.boundPorts.get((0,Em.uriToString)(O));if(j){if(!$._equals(j.credentials)){w(Error(`${Y} already bound with incompatible credentials`),0);return}if(j.cancelled=!1,j.completionPromise)j.completionPromise.then((M)=>A(null,M),(M)=>A(M,0));else w(null,j.portNumber);return}j={mapKey:(0,Em.uriToString)(O),originalUri:O,completionPromise:null,cancelled:!1,portNumber:0,credentials:$,listeningServers:new Set};let H=(0,Em.splitHostPort)(O.path),J=this.bindPort(O,j);if(j.completionPromise=J,(H===null||H===void 0?void 0:H.port)===0)J.then((M)=>{let X={scheme:O.scheme,authority:O.authority,path:(0,Em.combineHostPort)({host:H.host,port:M})};j.mapKey=(0,Em.uriToString)(X),j.completionPromise=null,j.portNumber=M,this.boundPorts.set(j.mapKey,j),A(null,M)},(M)=>{A(M,0)});else this.boundPorts.set(j.mapKey,j),J.then((M)=>{j.completionPromise=null,j.portNumber=M,A(null,M)},(M)=>{A(M,0)})}registerInjectorToChannelz(){return(0,UP.registerChannelzSocket)("injector",()=>{return{localAddress:null,remoteAddress:null,security:null,remoteName:null,streamsStarted:0,streamsSucceeded:0,streamsFailed:0,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastLocalStreamCreatedTimestamp:null,lastRemoteStreamCreatedTimestamp:null,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null,localFlowControlWindow:null,remoteFlowControlWindow:null}},this.channelzEnabled)}experimentalCreateConnectionInjectorWithChannelzRef(Y,$,A=!1){if(Y===null||!(Y instanceof pc1.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");if(this.channelzEnabled)this.listenerChildrenTracker.refChild($);let O=this.createHttp2Server(Y),w=new Set;return this.http2Servers.set(O,{channelzRef:$,sessions:w,ownsChannelzRef:A}),{injectConnection:(j)=>{O.emit("connection",j)},drain:(j)=>{var H,J;for(let M of w)this.closeSession(M);(J=(H=setTimeout(()=>{for(let M of w)M.destroy(QN.constants.NGHTTP2_CANCEL)},j)).unref)===null||J===void 0||J.call(H)},destroy:()=>{this.closeServer(O);for(let j of w)this.closeSession(j)}}}createConnectionInjector(Y){if(Y===null||!(Y instanceof pc1.ServerCredentials))throw TypeError("creds must be a ServerCredentials object");let $=this.registerInjectorToChannelz();return this.experimentalCreateConnectionInjectorWithChannelzRef(Y,$,!0)}closeServer(Y,$){this.trace("Closing server with address "+JSON.stringify(Y.address()));let A=this.http2Servers.get(Y);Y.close(()=>{if(A&&A.ownsChannelzRef)this.listenerChildrenTracker.unrefChild(A.channelzRef),(0,UP.unregisterChannelzRef)(A.channelzRef);this.http2Servers.delete(Y),$===null||$===void 0||$()})}closeSession(Y,$){var A;this.trace("Closing session initiated by "+((A=Y.socket)===null||A===void 0?void 0:A.remoteAddress));let O=this.sessions.get(Y),w=()=>{if(O)this.sessionChildrenTracker.unrefChild(O.ref),(0,UP.unregisterChannelzRef)(O.ref);$===null||$===void 0||$()};if(Y.closed)queueMicrotask(w);else Y.close(w)}completeUnbind(Y){for(let $ of Y.listeningServers){let A=this.http2Servers.get($);if(this.closeServer($,()=>{Y.listeningServers.delete($)}),A)for(let O of A.sessions)this.closeSession(O)}this.boundPorts.delete(Y.mapKey)}unbind(Y){this.trace("unbind port="+Y);let $=this.normalizePort(Y),A=(0,Em.splitHostPort)($.path);if((A===null||A===void 0?void 0:A.port)===0)throw Error("Cannot unbind port 0");let O=this.boundPorts.get((0,Em.uriToString)($));if(O)if(this.trace("unbinding "+O.mapKey+" originally bound as "+(0,Em.uriToString)(O.originalUri)),O.completionPromise)O.cancelled=!0;else this.completeUnbind(O)}drain(Y,$){var A,O;this.trace("drain port="+Y+" graceTimeMs="+$);let w=this.normalizePort(Y),j=(0,Em.splitHostPort)(w.path);if((j===null||j===void 0?void 0:j.port)===0)throw Error("Cannot drain port 0");let H=this.boundPorts.get((0,Em.uriToString)(w));if(!H)return;let J=new Set;for(let M of H.listeningServers){let X=this.http2Servers.get(M);if(X)for(let P of X.sessions)J.add(P),this.closeSession(P,()=>{J.delete(P)})}(O=(A=setTimeout(()=>{for(let M of J)M.destroy(QN.constants.NGHTTP2_CANCEL)},$)).unref)===null||O===void 0||O.call(A)}forceShutdown(){for(let Y of this.boundPorts.values())Y.cancelled=!0;this.boundPorts.clear();for(let Y of this.http2Servers.keys())this.closeServer(Y);this.sessions.forEach((Y,$)=>{this.closeSession($),$.destroy(QN.constants.NGHTTP2_CANCEL)}),this.sessions.clear(),(0,UP.unregisterChannelzRef)(this.channelzRef),this.shutdown=!0}register(Y,$,A,O,w){if(this.handlers.has(Y))return!1;return this.handlers.set(Y,{func:$,serialize:A,deserialize:O,type:w,path:Y}),!0}unregister(Y){return this.handlers.delete(Y)}start(){if(this.http2Servers.size===0||[...this.http2Servers.keys()].every((Y)=>!Y.listening))throw Error("server must be bound in order to start");if(this.started===!0)throw Error("server is already started");this.started=!0}tryShutdown(Y){var $;let A=(j)=>{(0,UP.unregisterChannelzRef)(this.channelzRef),Y(j)},O=0;function w(){if(O--,O===0)A()}this.shutdown=!0;for(let[j,H]of this.http2Servers.entries()){O++;let J=H.channelzRef.name;this.trace("Waiting for server "+J+" to close"),this.closeServer(j,()=>{this.trace("Server "+J+" finished closing"),w()});for(let M of H.sessions.keys()){O++;let X=($=M.socket)===null||$===void 0?void 0:$.remoteAddress;this.trace("Waiting for session "+X+" to close"),this.closeSession(M,()=>{this.trace("Session "+X+" finished closing"),w()})}}if(O===0)A()}addHttp2Port(){throw Error("Not yet implemented")}getChannelzRef(){return this.channelzRef}_verifyContentType(Y,$){let A=$[QN.constants.HTTP2_HEADER_CONTENT_TYPE];if(typeof A!=="string"||!A.startsWith("application/grpc"))return Y.respond({[QN.constants.HTTP2_HEADER_STATUS]:QN.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE},{endStream:!0}),!1;return!0}_retrieveHandler(Y){lo4("Received call to method "+Y+" at address "+this.serverAddressString);let $=this.handlers.get(Y);if($===void 0)return lo4("No handler registered for method "+Y+". Sending UNIMPLEMENTED status."),null;return $}_respondWithError(Y,$,A=null){var O,w;let j=Object.assign({"grpc-status":(O=Y.code)!==null&&O!==void 0?O:GM.Status.INTERNAL,"grpc-message":Y.details,[QN.constants.HTTP2_HEADER_STATUS]:QN.constants.HTTP_STATUS_OK,[QN.constants.HTTP2_HEADER_CONTENT_TYPE]:"application/grpc+proto"},(w=Y.metadata)===null||w===void 0?void 0:w.toHttp2Headers());$.respond(j,{endStream:!0}),this.callTracker.addCallFailed(),A===null||A===void 0||A.streamTracker.addCallFailed()}_channelzHandler(Y,$,A){this.onStreamOpened($);let O=this.sessions.get($.session);if(this.callTracker.addCallStarted(),O===null||O===void 0||O.streamTracker.addCallStarted(),!this._verifyContentType($,A)){this.callTracker.addCallFailed(),O===null||O===void 0||O.streamTracker.addCallFailed();return}let w=A[do4],j=this._retrieveHandler(w);if(!j){this._respondWithError(gc1(w),$,O);return}let H={addMessageSent:()=>{if(O)O.messagesSent+=1,O.lastMessageSentTimestamp=new Date},addMessageReceived:()=>{if(O)O.messagesReceived+=1,O.lastMessageReceivedTimestamp=new Date},onCallEnd:(M)=>{if(M.code===GM.Status.OK)this.callTracker.addCallSucceeded();else this.callTracker.addCallFailed()},onStreamEnd:(M)=>{if(O)if(M)O.streamTracker.addCallSucceeded();else O.streamTracker.addCallFailed()}},J=(0,Uo4.getServerInterceptingCall)([...Y,...this.interceptors],$,A,H,j,this.options);if(!this._runHandlerForCall(J,j))this.callTracker.addCallFailed(),O===null||O===void 0||O.streamTracker.addCallFailed(),J.sendStatus({code:GM.Status.INTERNAL,details:`Unknown handler type: ${j.type}`})}_streamHandler(Y,$,A){if(this.onStreamOpened($),this._verifyContentType($,A)!==!0)return;let O=A[do4],w=this._retrieveHandler(O);if(!w){this._respondWithError(gc1(O),$,null);return}let j=(0,Uo4.getServerInterceptingCall)([...Y,...this.interceptors],$,A,null,w,this.options);if(!this._runHandlerForCall(j,w))j.sendStatus({code:GM.Status.INTERNAL,details:`Unknown handler type: ${w.type}`})}_runHandlerForCall(Y,$){let{type:A}=$;if(A==="unary")phz(Y,$);else if(A==="clientStream")Bhz(Y,$);else if(A==="serverStream")ghz(Y,$);else if(A==="bidi")Fhz(Y,$);else return!1;return!0}_setupHandlers(Y,$){if(Y===null)return;let A=Y.address(),O="null";if(A)if(typeof A==="string")O=A;else O=A.address+":"+A.port;this.serverAddressString=O;let w=this.channelzEnabled?this._channelzHandler:this._streamHandler,j=this.channelzEnabled?this._channelzSessionHandler(Y):this._sessionHandler(Y);Y.on("stream",w.bind(this,$)),Y.on("session",j)}_sessionHandler(Y){return($)=>{var A,O;(A=this.http2Servers.get(Y))===null||A===void 0||A.sessions.add($);let w=null,j=null,H=null,J=!1,M=this.enableIdleTimeout($);if(this.maxConnectionAgeMs!==py6){let f=this.maxConnectionAgeMs/10,G=Math.random()*f*2-f;w=setTimeout(()=>{var Z,T;J=!0,this.trace("Connection dropped by max connection age: "+((Z=$.socket)===null||Z===void 0?void 0:Z.remoteAddress));try{$.goaway(QN.constants.NGHTTP2_NO_ERROR,2147483647,co4)}catch(v){$.destroy();return}if($.close(),this.maxConnectionAgeGraceMs!==py6)j=setTimeout(()=>{$.destroy()},this.maxConnectionAgeGraceMs),(T=j.unref)===null||T===void 0||T.call(j)},this.maxConnectionAgeMs+G),(O=w.unref)===null||O===void 0||O.call(w)}let X=()=>{if(H)clearTimeout(H),H=null},P=()=>{return!$.destroyed&&this.keepaliveTimeMs<Bc1&&this.keepaliveTimeMs>0},W,D=()=>{var f;if(!P())return;this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),H=setTimeout(()=>{X(),W()},this.keepaliveTimeMs),(f=H.unref)===null||f===void 0||f.call(H)};W=()=>{var f;if(!P())return;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms");let G="";try{if(!$.ping((T,v,V)=>{if(X(),T)this.keepaliveTrace("Ping failed with error: "+T.message),J=!0,$.close();else this.keepaliveTrace("Received ping response"),D()}))G="Ping returned false"}catch(Z){G=(Z instanceof Error?Z.message:"")||"Unknown error"}if(G){this.keepaliveTrace("Ping send failed: "+G),this.trace("Connection dropped due to ping send error: "+G),J=!0,$.close();return}H=setTimeout(()=>{X(),this.keepaliveTrace("Ping timeout passed without response"),this.trace("Connection dropped by keepalive timeout"),J=!0,$.close()},this.keepaliveTimeoutMs),(f=H.unref)===null||f===void 0||f.call(H)},D(),$.on("close",()=>{var f,G;if(!J)this.trace(`Connection dropped by client ${(f=$.socket)===null||f===void 0?void 0:f.remoteAddress}`);if(w)clearTimeout(w);if(j)clearTimeout(j);if(X(),M!==null)clearTimeout(M.timeout),this.sessionIdleTimeouts.delete($);(G=this.http2Servers.get(Y))===null||G===void 0||G.sessions.delete($)})}}_channelzSessionHandler(Y){return($)=>{var A,O,w,j;let H=(0,UP.registerChannelzSocket)((O=(A=$.socket)===null||A===void 0?void 0:A.remoteAddress)!==null&&O!==void 0?O:"unknown",this.getChannelzSessionInfo.bind(this,$),this.channelzEnabled),J={ref:H,streamTracker:new UP.ChannelzCallTracker,messagesSent:0,messagesReceived:0,keepAlivesSent:0,lastMessageSentTimestamp:null,lastMessageReceivedTimestamp:null};(w=this.http2Servers.get(Y))===null||w===void 0||w.sessions.add($),this.sessions.set($,J);let M=`${$.socket.remoteAddress}:${$.socket.remotePort}`;this.channelzTrace.addTrace("CT_INFO","Connection established by client "+M),this.trace("Connection established by client "+M),this.sessionChildrenTracker.refChild(H);let X=null,P=null,W=null,D=!1,f=this.enableIdleTimeout($);if(this.maxConnectionAgeMs!==py6){let V=this.maxConnectionAgeMs/10,E=Math.random()*V*2-V;X=setTimeout(()=>{var S;D=!0,this.channelzTrace.addTrace("CT_INFO","Connection dropped by max connection age from "+M);try{$.goaway(QN.constants.NGHTTP2_NO_ERROR,2147483647,co4)}catch(R){$.destroy();return}if($.close(),this.maxConnectionAgeGraceMs!==py6)P=setTimeout(()=>{$.destroy()},this.maxConnectionAgeGraceMs),(S=P.unref)===null||S===void 0||S.call(P)},this.maxConnectionAgeMs+E),(j=X.unref)===null||j===void 0||j.call(X)}let G=()=>{if(W)clearTimeout(W),W=null},Z=()=>{return!$.destroyed&&this.keepaliveTimeMs<Bc1&&this.keepaliveTimeMs>0},T,v=()=>{var V;if(!Z())return;this.keepaliveTrace("Starting keepalive timer for "+this.keepaliveTimeMs+"ms"),W=setTimeout(()=>{G(),T()},this.keepaliveTimeMs),(V=W.unref)===null||V===void 0||V.call(W)};T=()=>{var V;if(!Z())return;this.keepaliveTrace("Sending ping with timeout "+this.keepaliveTimeoutMs+"ms");let E="";try{if(!$.ping((R,x,I)=>{if(G(),R)this.keepaliveTrace("Ping failed with error: "+R.message),this.channelzTrace.addTrace("CT_INFO","Connection dropped due to error of a ping frame "+R.message+" return in "+x),D=!0,$.close();else this.keepaliveTrace("Received ping response"),v()}))E="Ping returned false"}catch(S){E=(S instanceof Error?S.message:"")||"Unknown error"}if(E){this.keepaliveTrace("Ping send failed: "+E),this.channelzTrace.addTrace("CT_INFO","Connection dropped due to ping send error: "+E),D=!0,$.close();return}J.keepAlivesSent+=1,W=setTimeout(()=>{G(),this.keepaliveTrace("Ping timeout passed without response"),this.channelzTrace.addTrace("CT_INFO","Connection dropped by keepalive timeout from "+M),D=!0,$.close()},this.keepaliveTimeoutMs),(V=W.unref)===null||V===void 0||V.call(W)},v(),$.on("close",()=>{var V;if(!D)this.channelzTrace.addTrace("CT_INFO","Connection dropped by client "+M);if(this.sessionChildrenTracker.unrefChild(H),(0,UP.unregisterChannelzRef)(H),X)clearTimeout(X);if(P)clearTimeout(P);if(G(),f!==null)clearTimeout(f.timeout),this.sessionIdleTimeouts.delete($);(V=this.http2Servers.get(Y))===null||V===void 0||V.sessions.delete($),this.sessions.delete($)})}}enableIdleTimeout(Y){var $,A;if(this.sessionIdleTimeout>=Qo4)return null;let O={activeStreams:0,lastIdle:Date.now(),onClose:this.onStreamClose.bind(this,Y),timeout:setTimeout(this.onIdleTimeout,this.sessionIdleTimeout,this,Y)};(A=($=O.timeout).unref)===null||A===void 0||A.call($),this.sessionIdleTimeouts.set(Y,O);let{socket:w}=Y;return this.trace("Enable idle timeout for "+w.remoteAddress+":"+w.remotePort),O}onIdleTimeout(Y,$){let{socket:A}=$,O=Y.sessionIdleTimeouts.get($);if(O!==void 0&&O.activeStreams===0)if(Date.now()-O.lastIdle>=Y.sessionIdleTimeout)Y.trace("Session idle timeout triggered for "+(A===null||A===void 0?void 0:A.remoteAddress)+":"+(A===null||A===void 0?void 0:A.remotePort)+" last idle at "+O.lastIdle),Y.closeSession($);else O.timeout.refresh()}onStreamOpened(Y){let $=Y.session,A=this.sessionIdleTimeouts.get($);if(A)A.activeStreams+=1,Y.once("close",A.onClose)}onStreamClose(Y){var $,A;let O=this.sessionIdleTimeouts.get(Y);if(O){if(O.activeStreams-=1,O.activeStreams===0)O.lastIdle=Date.now(),O.timeout.refresh(),this.trace("Session onStreamClose"+(($=Y.socket)===null||$===void 0?void 0:$.remoteAddress)+":"+((A=Y.socket)===null||A===void 0?void 0:A.remotePort)+" at "+O.lastIdle)}}},(()=>{let z=typeof Symbol==="function"&&Symbol.metadata?Object.create(null):void 0;if(_=[Ihz("Calling start() is no longer necessary. It can be safely omitted.")],hhz(q,null,_,{kind:"method",name:"start",static:!1,private:!1,access:{has:(Y)=>("start"in Y),get:(Y)=>Y.start},metadata:z},null,K),z)Object.defineProperty(q,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:z})})(),q})();L46.Server=mhz;async function phz(q,K){let _;function z(A,O,w,j){if(A){q.sendStatus((0,gy6.serverErrorToStatus)(A,w));return}q.sendMessage(O,()=>{q.sendStatus({code:GM.Status.OK,details:"OK",metadata:w!==null&&w!==void 0?w:null})})}let Y,$=null;q.start({onReceiveMetadata(A){Y=A,q.startRead()},onReceiveMessage(A){if($){q.sendStatus({code:GM.Status.UNIMPLEMENTED,details:`Received a second request message for server streaming method ${K.path}`,metadata:null});return}$=A,q.startRead()},onReceiveHalfClose(){if(!$){q.sendStatus({code:GM.Status.UNIMPLEMENTED,details:`Received no request message for server streaming method ${K.path}`,metadata:null});return}_=new gy6.ServerWritableStreamImpl(K.path,q,Y,$);try{K.func(_,z)}catch(A){q.sendStatus({code:GM.Status.UNKNOWN,details:`Server method handler threw error ${A.message}`,metadata:null})}},onCancel(){if(_)_.cancelled=!0,_.emit("cancelled","cancelled")}})}function Bhz(q,K){let _;function z(Y,$,A,O){if(Y){q.sendStatus((0,gy6.serverErrorToStatus)(Y,A));return}q.sendMessage($,()=>{q.sendStatus({code:GM.Status.OK,details:"OK",metadata:A!==null&&A!==void 0?A:null})})}q.start({onReceiveMetadata(Y){_=new gy6.ServerDuplexStreamImpl(K.path,q,Y);try{K.func(_,z)}catch($){q.sendStatus({code:GM.Status.UNKNOWN,details:`Server method handler threw error ${$.message}`,metadata:null})}},onReceiveMessage(Y){_.push(Y)},onReceiveHalfClose(){_.push(null)},onCancel(){if(_)_.cancelled=!0,_.emit("cancelled","cancelled"),_.destroy()}})}function ghz(q,K){let _,z,Y=null;q.start({onReceiveMetadata($){z=$,q.startRead()},onReceiveMessage($){if(Y){q.sendStatus({code:GM.Status.UNIMPLEMENTED,details:`Received a second request message for server streaming method ${K.path}`,metadata:null});return}Y=$,q.startRead()},onReceiveHalfClose(){if(!Y){q.sendStatus({code:GM.Status.UNIMPLEMENTED,details:`Received no request message for server streaming method ${K.path}`,metadata:null});return}_=new gy6.ServerWritableStreamImpl(K.path,q,z,Y);try{K.func(_)}catch($){q.sendStatus({code:GM.Status.UNKNOWN,details:`Server method handler threw error ${$.message}`,metadata:null})}},onCancel(){if(_)_.cancelled=!0,_.emit("cancelled","cancelled"),_.destroy()}})}function Fhz(q,K){let _;q.start({onReceiveMetadata(z){_=new gy6.ServerDuplexStreamImpl(K.path,q,z);try{K.func(_)}catch(Y){q.sendStatus({code:GM.Status.UNKNOWN,details:`Server method handler threw error ${Y.message}`,metadata:null})}},onReceiveMessage(z){_.push(z)},onReceiveHalfClose(){_.push(null)},onCancel(){if(_)_.cancelled=!0,_.emit("cancelled","cancelled"),_.destroy()}})}});var ao4=m((ro4)=>{Object.defineProperty(ro4,"__esModule",{value:!0});ro4.StatusBuilder=void 0;class io4{constructor(){this.code=null,this.details=null,this.metadata=null}withCode(q){return this.code=q,this}withDetails(q){return this.details=q,this}withMetadata(q){return this.metadata=q,this}build(){let q={};if(this.code!==null)q.code=this.code;if(this.details!==null)q.details=this.details;if(this.metadata!==null)q.metadata=this.metadata;return q}}ro4.StatusBuilder=io4});var Xt6=m((Ya4)=>{Object.defineProperty(Ya4,"__esModule",{value:!0});Ya4.LeafLoadBalancer=Ya4.PickFirstLoadBalancer=Ya4.PickFirstLoadBalancingConfig=void 0;Ya4.shuffled=Ka4;Ya4.setup=rhz;var Fc1=D46(),TM=ev(),R46=Wo(),so4=FN(),Uhz=Gw(),Qhz=c_(),to4=FN(),eo4=U6("net"),dhz=J26(),chz="pick_first";function Jt6(q){Uhz.trace(Qhz.LogVerbosity.DEBUG,chz,q)}var Mt6="pick_first",lhz=250;class Fy6{constructor(q){this.shuffleAddressList=q}getLoadBalancerName(){return Mt6}toJsonObject(){return{[Mt6]:{shuffleAddressList:this.shuffleAddressList}}}getShuffleAddressList(){return this.shuffleAddressList}static createFromJson(q){if("shuffleAddressList"in q&&typeof q.shuffleAddressList!=="boolean")throw Error("pick_first config field shuffleAddressList must be a boolean if provided");return new Fy6(q.shuffleAddressList===!0)}}Ya4.PickFirstLoadBalancingConfig=Fy6;class qa4{constructor(q){this.subchannel=q}pick(q){return{pickResultType:R46.PickResultType.COMPLETE,subchannel:this.subchannel,status:null,onCallStarted:null,onCallEnded:null}}}function Ka4(q){let K=q.slice();for(let _=K.length-1;_>1;_--){let z=Math.floor(Math.random()*(_+1)),Y=K[_];K[_]=K[z],K[z]=Y}return K}function nhz(q){if(q.length===0)return[];let K=[],_=[],z=[],Y=(0,to4.isTcpSubchannelAddress)(q[0])&&(0,eo4.isIPv6)(q[0].host);for(let O of q)if((0,to4.isTcpSubchannelAddress)(O)&&(0,eo4.isIPv6)(O.host))_.push(O);else z.push(O);let $=Y?_:z,A=Y?z:_;for(let O=0;O<Math.max($.length,A.length);O++){if(O<$.length)K.push($[O]);if(O<A.length)K.push(A[O])}return K}var _a4="grpc-node.internal.pick-first.report_health_status";class sh8{constructor(q){this.channelControlHelper=q,this.children=[],this.currentState=TM.ConnectivityState.IDLE,this.currentSubchannelIndex=0,this.currentPick=null,this.subchannelStateListener=(K,_,z,Y,$)=>{this.onSubchannelStateUpdate(K,_,z,$)},this.pickedSubchannelHealthListener=()=>this.calculateAndReportNewState(),this.stickyTransientFailureMode=!1,this.reportHealthStatus=!1,this.lastError=null,this.latestAddressList=null,this.latestOptions={},this.latestResolutionNote="",this.connectionDelayTimeout=setTimeout(()=>{},0),clearTimeout(this.connectionDelayTimeout)}allChildrenHaveReportedTF(){return this.children.every((q)=>q.hasReportedTransientFailure)}resetChildrenReportedTF(){this.children.every((q)=>q.hasReportedTransientFailure=!1)}calculateAndReportNewState(){var q;if(this.currentPick)if(this.reportHealthStatus&&!this.currentPick.isHealthy()){let K=`Picked subchannel ${this.currentPick.getAddress()} is unhealthy`;this.updateState(TM.ConnectivityState.TRANSIENT_FAILURE,new R46.UnavailablePicker({details:K}),K)}else this.updateState(TM.ConnectivityState.READY,new qa4(this.currentPick),null);else if(((q=this.latestAddressList)===null||q===void 0?void 0:q.length)===0){let K=`No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`;this.updateState(TM.ConnectivityState.TRANSIENT_FAILURE,new R46.UnavailablePicker({details:K}),K)}else if(this.children.length===0)this.updateState(TM.ConnectivityState.IDLE,new R46.QueuePicker(this),null);else if(this.stickyTransientFailureMode){let K=`No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`;this.updateState(TM.ConnectivityState.TRANSIENT_FAILURE,new R46.UnavailablePicker({details:K}),K)}else this.updateState(TM.ConnectivityState.CONNECTING,new R46.QueuePicker(this),null)}requestReresolution(){this.channelControlHelper.requestReresolution()}maybeEnterStickyTransientFailureMode(){if(!this.allChildrenHaveReportedTF())return;if(this.requestReresolution(),this.resetChildrenReportedTF(),this.stickyTransientFailureMode){this.calculateAndReportNewState();return}this.stickyTransientFailureMode=!0;for(let{subchannel:q}of this.children)q.startConnecting();this.calculateAndReportNewState()}removeCurrentPick(){if(this.currentPick!==null)this.currentPick.removeConnectivityStateListener(this.subchannelStateListener),this.channelControlHelper.removeChannelzChild(this.currentPick.getChannelzRef()),this.currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener),this.currentPick.unref(),this.currentPick=null}onSubchannelStateUpdate(q,K,_,z){var Y;if((Y=this.currentPick)===null||Y===void 0?void 0:Y.realSubchannelEquals(q)){if(_!==TM.ConnectivityState.READY)this.removeCurrentPick(),this.calculateAndReportNewState();return}for(let[$,A]of this.children.entries())if(q.realSubchannelEquals(A.subchannel)){if(_===TM.ConnectivityState.READY)this.pickSubchannel(A.subchannel);if(_===TM.ConnectivityState.TRANSIENT_FAILURE){if(A.hasReportedTransientFailure=!0,z)this.lastError=z;if(this.maybeEnterStickyTransientFailureMode(),$===this.currentSubchannelIndex)this.startNextSubchannelConnecting($+1)}A.subchannel.startConnecting();return}}startNextSubchannelConnecting(q){clearTimeout(this.connectionDelayTimeout);for(let[K,_]of this.children.entries())if(K>=q){let z=_.subchannel.getConnectivityState();if(z===TM.ConnectivityState.IDLE||z===TM.ConnectivityState.CONNECTING){this.startConnecting(K);return}}this.maybeEnterStickyTransientFailureMode()}startConnecting(q){var K,_;if(clearTimeout(this.connectionDelayTimeout),this.currentSubchannelIndex=q,this.children[q].subchannel.getConnectivityState()===TM.ConnectivityState.IDLE)Jt6("Start connecting to subchannel with address "+this.children[q].subchannel.getAddress()),process.nextTick(()=>{var z;(z=this.children[q])===null||z===void 0||z.subchannel.startConnecting()});this.connectionDelayTimeout=setTimeout(()=>{this.startNextSubchannelConnecting(q+1)},lhz),(_=(K=this.connectionDelayTimeout).unref)===null||_===void 0||_.call(K)}pickSubchannel(q){Jt6("Pick subchannel with address "+q.getAddress()),this.stickyTransientFailureMode=!1,q.ref(),this.channelControlHelper.addChannelzChild(q.getChannelzRef()),this.removeCurrentPick(),this.resetSubchannelList(),q.addConnectivityStateListener(this.subchannelStateListener),q.addHealthStateWatcher(this.pickedSubchannelHealthListener),this.currentPick=q,clearTimeout(this.connectionDelayTimeout),this.calculateAndReportNewState()}updateState(q,K,_){Jt6(TM.ConnectivityState[this.currentState]+" -> "+TM.ConnectivityState[q]),this.currentState=q,this.channelControlHelper.updateState(q,K,_)}resetSubchannelList(){for(let q of this.children)q.subchannel.removeConnectivityStateListener(this.subchannelStateListener),q.subchannel.unref(),this.channelControlHelper.removeChannelzChild(q.subchannel.getChannelzRef());this.currentSubchannelIndex=0,this.children=[]}connectToAddressList(q,K){Jt6("connectToAddressList(["+q.map((z)=>(0,so4.subchannelAddressToString)(z))+"])");let _=q.map((z)=>({subchannel:this.channelControlHelper.createSubchannel(z,K),hasReportedTransientFailure:!1}));for(let{subchannel:z}of _)if(z.getConnectivityState()===TM.ConnectivityState.READY){this.pickSubchannel(z);return}for(let{subchannel:z}of _)z.ref(),this.channelControlHelper.addChannelzChild(z.getChannelzRef());this.resetSubchannelList(),this.children=_;for(let{subchannel:z}of this.children)z.addConnectivityStateListener(this.subchannelStateListener);for(let z of this.children)if(z.subchannel.getConnectivityState()===TM.ConnectivityState.TRANSIENT_FAILURE)z.hasReportedTransientFailure=!0;this.startNextSubchannelConnecting(0),this.calculateAndReportNewState()}updateAddressList(q,K,_,z){if(!(K instanceof Fy6))return!1;if(!q.ok){if(this.children.length===0&&this.currentPick===null)this.channelControlHelper.updateState(TM.ConnectivityState.TRANSIENT_FAILURE,new R46.UnavailablePicker(q.error),q.error.details);return!0}let Y=q.value;if(this.reportHealthStatus=_[_a4],K.getShuffleAddressList())Y=Ka4(Y);let $=[].concat(...Y.map((O)=>O.addresses));Jt6("updateAddressList(["+$.map((O)=>(0,so4.subchannelAddressToString)(O))+"])");let A=nhz($);if(this.latestAddressList=A,this.latestOptions=_,this.connectToAddressList(A,_),this.latestResolutionNote=z,$.length>0)return!0;else return this.lastError="No addresses resolved",!1}exitIdle(){if(this.currentState===TM.ConnectivityState.IDLE&&this.latestAddressList)this.connectToAddressList(this.latestAddressList,this.latestOptions)}resetBackoff(){}destroy(){this.resetSubchannelList(),this.removeCurrentPick()}getTypeName(){return Mt6}}Ya4.PickFirstLoadBalancer=sh8;var ihz=new Fy6(!1);class za4{constructor(q,K,_,z){this.endpoint=q,this.options=_,this.resolutionNote=z,this.latestState=TM.ConnectivityState.IDLE;let Y=(0,Fc1.createChildChannelControlHelper)(K,{updateState:($,A,O)=>{this.latestState=$,this.latestPicker=A,K.updateState($,A,O)}});this.pickFirstBalancer=new sh8(Y),this.latestPicker=new R46.QueuePicker(this.pickFirstBalancer)}startConnecting(){this.pickFirstBalancer.updateAddressList((0,dhz.statusOrFromValue)([this.endpoint]),ihz,Object.assign(Object.assign({},this.options),{[_a4]:!0}),this.resolutionNote)}updateEndpoint(q,K){if(this.options=K,this.endpoint=q,this.latestState!==TM.ConnectivityState.IDLE)this.startConnecting()}getConnectivityState(){return this.latestState}getPicker(){return this.latestPicker}getEndpoint(){return this.endpoint}exitIdle(){this.pickFirstBalancer.exitIdle()}destroy(){this.pickFirstBalancer.destroy()}}Ya4.LeafLoadBalancer=za4;function rhz(){(0,Fc1.registerLoadBalancerType)(Mt6,sh8,Fy6),(0,Fc1.registerDefaultLoadBalancerType)(Mt6)}});var ja4=m((Oa4)=>{Object.defineProperty(Oa4,"__esModule",{value:!0});Oa4.FileWatcherCertificateProvider=void 0;var ehz=U6("fs"),qSz=Gw(),KSz=c_(),_Sz=U6("util"),zSz="certificate_provider";function th8(q){qSz.trace(KSz.LogVerbosity.DEBUG,zSz,q)}var Uc1=(0,_Sz.promisify)(ehz.readFile);class Aa4{constructor(q){if(this.config=q,this.refreshTimer=null,this.fileResultPromise=null,this.latestCaUpdate=void 0,this.caListeners=new Set,this.latestIdentityUpdate=void 0,this.identityListeners=new Set,this.lastUpdateTime=null,q.certificateFile===void 0!==(q.privateKeyFile===void 0))throw Error("certificateFile and privateKeyFile must be set or unset together");if(q.certificateFile===void 0&&q.caCertificateFile===void 0)throw Error("At least one of certificateFile and caCertificateFile must be set");th8("File watcher constructed with config "+JSON.stringify(q))}updateCertificates(){if(this.fileResultPromise)return;this.fileResultPromise=Promise.allSettled([this.config.certificateFile?Uc1(this.config.certificateFile):Promise.reject(),this.config.privateKeyFile?Uc1(this.config.privateKeyFile):Promise.reject(),this.config.caCertificateFile?Uc1(this.config.caCertificateFile):Promise.reject()]),this.fileResultPromise.then(([q,K,_])=>{if(!this.refreshTimer)return;if(th8("File watcher read certificates certificate "+q.status+", privateKey "+K.status+", CA certificate "+_.status),this.lastUpdateTime=new Date,this.fileResultPromise=null,q.status==="fulfilled"&&K.status==="fulfilled")this.latestIdentityUpdate={certificate:q.value,privateKey:K.value};else this.latestIdentityUpdate=null;if(_.status==="fulfilled")this.latestCaUpdate={caCertificate:_.value};else this.latestCaUpdate=null;for(let z of this.identityListeners)z(this.latestIdentityUpdate);for(let z of this.caListeners)z(this.latestCaUpdate)}),th8("File watcher initiated certificate update")}maybeStartWatchingFiles(){if(!this.refreshTimer){let q=this.lastUpdateTime?new Date().getTime()-this.lastUpdateTime.getTime():1/0;if(q>this.config.refreshIntervalMs)this.updateCertificates();if(q>this.config.refreshIntervalMs*2)this.latestCaUpdate=void 0,this.latestIdentityUpdate=void 0;this.refreshTimer=setInterval(()=>this.updateCertificates(),this.config.refreshIntervalMs),th8("File watcher started watching")}}maybeStopWatchingFiles(){if(this.caListeners.size===0&&this.identityListeners.size===0){if(this.fileResultPromise=null,this.refreshTimer)clearInterval(this.refreshTimer),this.refreshTimer=null}}addCaCertificateListener(q){if(this.caListeners.add(q),this.maybeStartWatchingFiles(),this.latestCaUpdate!==void 0)process.nextTick(q,this.latestCaUpdate)}removeCaCertificateListener(q){this.caListeners.delete(q),this.maybeStopWatchingFiles()}addIdentityCertificateListener(q){if(this.identityListeners.add(q),this.maybeStartWatchingFiles(),this.latestIdentityUpdate!==void 0)process.nextTick(q,this.latestIdentityUpdate)}removeIdentityCertificateListener(q){this.identityListeners.delete(q),this.maybeStopWatchingFiles()}}Oa4.FileWatcherCertificateProvider=Aa4});var cc1=m((Lz)=>{Object.defineProperty(Lz,"__esModule",{value:!0});Lz.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX=Lz.createCertificateProviderChannelCredentials=Lz.FileWatcherCertificateProvider=Lz.createCertificateProviderServerCredentials=Lz.createServerCredentialsWithInterceptors=Lz.BaseSubchannelWrapper=Lz.registerAdminService=Lz.FilterStackFactory=Lz.BaseFilter=Lz.statusOrFromError=Lz.statusOrFromValue=Lz.PickResultType=Lz.QueuePicker=Lz.UnavailablePicker=Lz.ChildLoadBalancerHandler=Lz.EndpointMap=Lz.endpointHasAddress=Lz.endpointToString=Lz.subchannelAddressToString=Lz.LeafLoadBalancer=Lz.isLoadBalancerNameRegistered=Lz.parseLoadBalancingConfig=Lz.selectLbConfigFromList=Lz.registerLoadBalancerType=Lz.createChildChannelControlHelper=Lz.BackoffTimeout=Lz.parseDuration=Lz.durationToMs=Lz.splitHostPort=Lz.uriToString=Lz.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=Lz.createResolver=Lz.registerResolver=Lz.log=Lz.trace=void 0;var Ha4=Gw();Object.defineProperty(Lz,"trace",{enumerable:!0,get:function(){return Ha4.trace}});Object.defineProperty(Lz,"log",{enumerable:!0,get:function(){return Ha4.log}});var Qc1=Tm();Object.defineProperty(Lz,"registerResolver",{enumerable:!0,get:function(){return Qc1.registerResolver}});Object.defineProperty(Lz,"createResolver",{enumerable:!0,get:function(){return Qc1.createResolver}});Object.defineProperty(Lz,"CHANNEL_ARGS_CONFIG_SELECTOR_KEY",{enumerable:!0,get:function(){return Qc1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY}});var Ja4=tv();Object.defineProperty(Lz,"uriToString",{enumerable:!0,get:function(){return Ja4.uriToString}});Object.defineProperty(Lz,"splitHostPort",{enumerable:!0,get:function(){return Ja4.splitHostPort}});var Ma4=Ht6();Object.defineProperty(Lz,"durationToMs",{enumerable:!0,get:function(){return Ma4.durationToMs}});Object.defineProperty(Lz,"parseDuration",{enumerable:!0,get:function(){return Ma4.parseDuration}});var YSz=Dy6();Object.defineProperty(Lz,"BackoffTimeout",{enumerable:!0,get:function(){return YSz.BackoffTimeout}});var Pt6=D46();Object.defineProperty(Lz,"createChildChannelControlHelper",{enumerable:!0,get:function(){return Pt6.createChildChannelControlHelper}});Object.defineProperty(Lz,"registerLoadBalancerType",{enumerable:!0,get:function(){return Pt6.registerLoadBalancerType}});Object.defineProperty(Lz,"selectLbConfigFromList",{enumerable:!0,get:function(){return Pt6.selectLbConfigFromList}});Object.defineProperty(Lz,"parseLoadBalancingConfig",{enumerable:!0,get:function(){return Pt6.parseLoadBalancingConfig}});Object.defineProperty(Lz,"isLoadBalancerNameRegistered",{enumerable:!0,get:function(){return Pt6.isLoadBalancerNameRegistered}});var $Sz=Xt6();Object.defineProperty(Lz,"LeafLoadBalancer",{enumerable:!0,get:function(){return $Sz.LeafLoadBalancer}});var eh8=FN();Object.defineProperty(Lz,"subchannelAddressToString",{enumerable:!0,get:function(){return eh8.subchannelAddressToString}});Object.defineProperty(Lz,"endpointToString",{enumerable:!0,get:function(){return eh8.endpointToString}});Object.defineProperty(Lz,"endpointHasAddress",{enumerable:!0,get:function(){return eh8.endpointHasAddress}});Object.defineProperty(Lz,"EndpointMap",{enumerable:!0,get:function(){return eh8.EndpointMap}});var ASz=sR8();Object.defineProperty(Lz,"ChildLoadBalancerHandler",{enumerable:!0,get:function(){return ASz.ChildLoadBalancerHandler}});var dc1=Wo();Object.defineProperty(Lz,"UnavailablePicker",{enumerable:!0,get:function(){return dc1.UnavailablePicker}});Object.defineProperty(Lz,"QueuePicker",{enumerable:!0,get:function(){return dc1.QueuePicker}});Object.defineProperty(Lz,"PickResultType",{enumerable:!0,get:function(){return dc1.PickResultType}});var Xa4=J26();Object.defineProperty(Lz,"statusOrFromValue",{enumerable:!0,get:function(){return Xa4.statusOrFromValue}});Object.defineProperty(Lz,"statusOrFromError",{enumerable:!0,get:function(){return Xa4.statusOrFromError}});var OSz=_c1();Object.defineProperty(Lz,"BaseFilter",{enumerable:!0,get:function(){return OSz.BaseFilter}});var wSz=bh8();Object.defineProperty(Lz,"FilterStackFactory",{enumerable:!0,get:function(){return wSz.FilterStackFactory}});var jSz=eR8();Object.defineProperty(Lz,"registerAdminService",{enumerable:!0,get:function(){return jSz.registerAdminService}});var HSz=wt6();Object.defineProperty(Lz,"BaseSubchannelWrapper",{enumerable:!0,get:function(){return HSz.BaseSubchannelWrapper}});var Pa4=lh8();Object.defineProperty(Lz,"createServerCredentialsWithInterceptors",{enumerable:!0,get:function(){return Pa4.createServerCredentialsWithInterceptors}});Object.defineProperty(Lz,"createCertificateProviderServerCredentials",{enumerable:!0,get:function(){return Pa4.createCertificateProviderServerCredentials}});var JSz=ja4();Object.defineProperty(Lz,"FileWatcherCertificateProvider",{enumerable:!0,get:function(){return JSz.FileWatcherCertificateProvider}});var MSz=Wy6();Object.defineProperty(Lz,"createCertificateProviderChannelCredentials",{enumerable:!0,get:function(){return MSz.createCertificateProviderChannelCredentials}});var XSz=Vc1();Object.defineProperty(Lz,"SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX",{enumerable:!0,get:function(){return XSz.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX}})});var fa4=m((Da4)=>{Object.defineProperty(Da4,"__esModule",{value:!0});Da4.setup=fSz;var WSz=Tm(),DSz=J26();class Wa4{constructor(q,K,_){this.listener=K,this.hasReturnedResult=!1,this.endpoints=[];let z;if(q.authority==="")z="/"+q.path;else z=q.path;this.endpoints=[{addresses:[{path:z}]}]}updateResolution(){if(!this.hasReturnedResult)this.hasReturnedResult=!0,process.nextTick(this.listener,(0,DSz.statusOrFromValue)(this.endpoints),{},null,"")}destroy(){this.hasReturnedResult=!1}static getDefaultAuthority(q){return"localhost"}}function fSz(){(0,WSz.registerResolver)("unix",Wa4)}});var Na4=m((Va4)=>{Object.defineProperty(Va4,"__esModule",{value:!0});Va4.setup=VSz;var Za4=U6("net"),Ga4=J26(),qS8=c_(),lc1=vD(),Ta4=Tm(),GSz=FN(),va4=tv(),TSz=Gw(),vSz="ip_resolver";function ka4(q){TSz.trace(qS8.LogVerbosity.DEBUG,vSz,q)}var nc1="ipv4",ic1="ipv6",kSz=443;class rc1{constructor(q,K,_){var z;this.listener=K,this.endpoints=[],this.error=null,this.hasReturnedResult=!1,ka4("Resolver constructed for target "+(0,va4.uriToString)(q));let Y=[];if(!(q.scheme===nc1||q.scheme===ic1)){this.error={code:qS8.Status.UNAVAILABLE,details:`Unrecognized scheme ${q.scheme} in IP resolver`,metadata:new lc1.Metadata};return}let $=q.path.split(",");for(let A of $){let O=(0,va4.splitHostPort)(A);if(O===null){this.error={code:qS8.Status.UNAVAILABLE,details:`Failed to parse ${q.scheme} address ${A}`,metadata:new lc1.Metadata};return}if(q.scheme===nc1&&!(0,Za4.isIPv4)(O.host)||q.scheme===ic1&&!(0,Za4.isIPv6)(O.host)){this.error={code:qS8.Status.UNAVAILABLE,details:`Failed to parse ${q.scheme} address ${A}`,metadata:new lc1.Metadata};return}Y.push({host:O.host,port:(z=O.port)!==null&&z!==void 0?z:kSz})}this.endpoints=Y.map((A)=>({addresses:[A]})),ka4("Parsed "+q.scheme+" address list "+Y.map(GSz.subchannelAddressToString))}updateResolution(){if(!this.hasReturnedResult)this.hasReturnedResult=!0,process.nextTick(()=>{if(this.error)this.listener((0,Ga4.statusOrFromError)(this.error),{},null,"");else this.listener((0,Ga4.statusOrFromValue)(this.endpoints),{},null,"")})}destroy(){this.hasReturnedResult=!1}static getDefaultAuthority(q){return q.path.split(",")[0]}}function VSz(){(0,Ta4.registerResolver)(nc1,rc1),(0,Ta4.registerResolver)(ic1,rc1)}});var Ca4=m((ha4)=>{Object.defineProperty(ha4,"__esModule",{value:!0});ha4.RoundRobinLoadBalancer=void 0;ha4.setup=SSz;var La4=D46(),E0=ev(),Wt6=Wo(),ySz=Gw(),ESz=c_(),ya4=FN(),LSz=Xt6(),RSz="round_robin";function Ea4(q){ySz.trace(ESz.LogVerbosity.DEBUG,RSz,q)}var KS8="round_robin";class _S8{getLoadBalancerName(){return KS8}constructor(){}toJsonObject(){return{[KS8]:{}}}static createFromJson(q){return new _S8}}class Ra4{constructor(q,K=0){this.children=q,this.nextIndex=K}pick(q){let K=this.children[this.nextIndex].picker;return this.nextIndex=(this.nextIndex+1)%this.children.length,K.pick(q)}peekNextEndpoint(){return this.children[this.nextIndex].endpoint}}function hSz(q,K){return[...q.slice(K),...q.slice(0,K)]}class oc1{constructor(q){this.channelControlHelper=q,this.children=[],this.currentState=E0.ConnectivityState.IDLE,this.currentReadyPicker=null,this.updatesPaused=!1,this.lastError=null,this.childChannelControlHelper=(0,La4.createChildChannelControlHelper)(q,{updateState:(K,_,z)=>{if(this.currentState===E0.ConnectivityState.READY&&K!==E0.ConnectivityState.READY)this.channelControlHelper.requestReresolution();if(z)this.lastError=z;this.calculateAndUpdateState()}})}countChildrenWithState(q){return this.children.filter((K)=>K.getConnectivityState()===q).length}calculateAndUpdateState(){if(this.updatesPaused)return;if(this.countChildrenWithState(E0.ConnectivityState.READY)>0){let q=this.children.filter((_)=>_.getConnectivityState()===E0.ConnectivityState.READY),K=0;if(this.currentReadyPicker!==null){let _=this.currentReadyPicker.peekNextEndpoint();if(K=q.findIndex((z)=>(0,ya4.endpointEqual)(z.getEndpoint(),_)),K<0)K=0}this.updateState(E0.ConnectivityState.READY,new Ra4(q.map((_)=>({endpoint:_.getEndpoint(),picker:_.getPicker()})),K),null)}else if(this.countChildrenWithState(E0.ConnectivityState.CONNECTING)>0)this.updateState(E0.ConnectivityState.CONNECTING,new Wt6.QueuePicker(this),null);else if(this.countChildrenWithState(E0.ConnectivityState.TRANSIENT_FAILURE)>0){let q=`round_robin: No connection established. Last error: ${this.lastError}`;this.updateState(E0.ConnectivityState.TRANSIENT_FAILURE,new Wt6.UnavailablePicker({details:q}),q)}else this.updateState(E0.ConnectivityState.IDLE,new Wt6.QueuePicker(this),null);for(let q of this.children)if(q.getConnectivityState()===E0.ConnectivityState.IDLE)q.exitIdle()}updateState(q,K,_){if(Ea4(E0.ConnectivityState[this.currentState]+" -> "+E0.ConnectivityState[q]),q===E0.ConnectivityState.READY)this.currentReadyPicker=K;else this.currentReadyPicker=null;this.currentState=q,this.channelControlHelper.updateState(q,K,_)}resetSubchannelList(){for(let q of this.children)q.destroy();this.children=[]}updateAddressList(q,K,_,z){if(!(K instanceof _S8))return!1;if(!q.ok){if(this.children.length===0)this.updateState(E0.ConnectivityState.TRANSIENT_FAILURE,new Wt6.UnavailablePicker(q.error),q.error.details);return!0}let Y=Math.random()*q.value.length|0,$=hSz(q.value,Y);if(this.resetSubchannelList(),$.length===0){let A=`No addresses resolved. Resolution note: ${z}`;this.updateState(E0.ConnectivityState.TRANSIENT_FAILURE,new Wt6.UnavailablePicker({details:A}),A)}Ea4("Connect to endpoint list "+$.map(ya4.endpointToString)),this.updatesPaused=!0,this.children=$.map((A)=>new LSz.LeafLoadBalancer(A,this.childChannelControlHelper,_,z));for(let A of this.children)A.startConnecting();return this.updatesPaused=!1,this.calculateAndUpdateState(),!0}exitIdle(){}resetBackoff(){}destroy(){this.resetSubchannelList()}getTypeName(){return KS8}}ha4.RoundRobinLoadBalancer=oc1;function SSz(){(0,La4.registerLoadBalancerType)(KS8,oc1,_S8)}});var ga4=m((pa4)=>{var ac1;Object.defineProperty(pa4,"__esModule",{value:!0});pa4.OutlierDetectionLoadBalancer=pa4.OutlierDetectionLoadBalancingConfig=void 0;pa4.setup=QSz;var bSz=ev(),ba4=c_(),k26=Ht6(),xa4=cc1(),xSz=D46(),ISz=sR8(),uSz=Wo(),sc1=FN(),mSz=wt6(),pSz=Gw(),BSz="outlier_detection";function ND(q){pSz.trace(ba4.LogVerbosity.DEBUG,BSz,q)}var ql1="outlier_detection",gSz=((ac1=process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION)!==null&&ac1!==void 0?ac1:"true")==="true",FSz={stdev_factor:1900,enforcement_percentage:100,minimum_hosts:5,request_volume:100},USz={threshold:85,enforcement_percentage:100,minimum_hosts:5,request_volume:50};function Uy6(q,K,_,z){if(K in q&&q[K]!==void 0&&typeof q[K]!==_){let Y=z?`${z}.${K}`:K;throw Error(`outlier detection config ${Y} parse error: expected ${_}, got ${typeof q[K]}`)}}function tc1(q,K,_){let z=_?`${_}.${K}`:K;if(K in q&&q[K]!==void 0){if(!(0,k26.isDuration)(q[K]))throw Error(`outlier detection config ${z} parse error: expected Duration, got ${typeof q[K]}`);if(!(q[K].seconds>=0&&q[K].seconds<=315576000000&&q[K].nanos>=0&&q[K].nanos<=999999999))throw Error(`outlier detection config ${z} parse error: values out of range for non-negative Duaration`)}}function zS8(q,K,_){let z=_?`${_}.${K}`:K;if(Uy6(q,K,"number",_),K in q&&q[K]!==void 0&&!(q[K]>=0&&q[K]<=100))throw Error(`outlier detection config ${z} parse error: value out of range for percentage (0-100)`)}class Dt6{constructor(q,K,_,z,Y,$,A){if(this.childPolicy=A,A.getLoadBalancerName()==="pick_first")throw Error("outlier_detection LB policy cannot have a pick_first child policy");this.intervalMs=q!==null&&q!==void 0?q:1e4,this.baseEjectionTimeMs=K!==null&&K!==void 0?K:30000,this.maxEjectionTimeMs=_!==null&&_!==void 0?_:300000,this.maxEjectionPercent=z!==null&&z!==void 0?z:10,this.successRateEjection=Y?Object.assign(Object.assign({},FSz),Y):null,this.failurePercentageEjection=$?Object.assign(Object.assign({},USz),$):null}getLoadBalancerName(){return ql1}toJsonObject(){var q,K;return{outlier_detection:{interval:(0,k26.msToDuration)(this.intervalMs),base_ejection_time:(0,k26.msToDuration)(this.baseEjectionTimeMs),max_ejection_time:(0,k26.msToDuration)(this.maxEjectionTimeMs),max_ejection_percent:this.maxEjectionPercent,success_rate_ejection:(q=this.successRateEjection)!==null&&q!==void 0?q:void 0,failure_percentage_ejection:(K=this.failurePercentageEjection)!==null&&K!==void 0?K:void 0,child_policy:[this.childPolicy.toJsonObject()]}}}getIntervalMs(){return this.intervalMs}getBaseEjectionTimeMs(){return this.baseEjectionTimeMs}getMaxEjectionTimeMs(){return this.maxEjectionTimeMs}getMaxEjectionPercent(){return this.maxEjectionPercent}getSuccessRateEjectionConfig(){return this.successRateEjection}getFailurePercentageEjectionConfig(){return this.failurePercentageEjection}getChildPolicy(){return this.childPolicy}static createFromJson(q){var K;if(tc1(q,"interval"),tc1(q,"base_ejection_time"),tc1(q,"max_ejection_time"),zS8(q,"max_ejection_percent"),"success_rate_ejection"in q&&q.success_rate_ejection!==void 0){if(typeof q.success_rate_ejection!=="object")throw Error("outlier detection config success_rate_ejection must be an object");Uy6(q.success_rate_ejection,"stdev_factor","number","success_rate_ejection"),zS8(q.success_rate_ejection,"enforcement_percentage","success_rate_ejection"),Uy6(q.success_rate_ejection,"minimum_hosts","number","success_rate_ejection"),Uy6(q.success_rate_ejection,"request_volume","number","success_rate_ejection")}if("failure_percentage_ejection"in q&&q.failure_percentage_ejection!==void 0){if(typeof q.failure_percentage_ejection!=="object")throw Error("outlier detection config failure_percentage_ejection must be an object");zS8(q.failure_percentage_ejection,"threshold","failure_percentage_ejection"),zS8(q.failure_percentage_ejection,"enforcement_percentage","failure_percentage_ejection"),Uy6(q.failure_percentage_ejection,"minimum_hosts","number","failure_percentage_ejection"),Uy6(q.failure_percentage_ejection,"request_volume","number","failure_percentage_ejection")}if(!("child_policy"in q)||!Array.isArray(q.child_policy))throw Error("outlier detection config child_policy must be an array");let _=(0,xSz.selectLbConfigFromList)(q.child_policy);if(!_)throw Error("outlier detection config child_policy: no valid recognized policy found");return new Dt6(q.interval?(0,k26.durationToMs)(q.interval):null,q.base_ejection_time?(0,k26.durationToMs)(q.base_ejection_time):null,q.max_ejection_time?(0,k26.durationToMs)(q.max_ejection_time):null,(K=q.max_ejection_percent)!==null&&K!==void 0?K:null,q.success_rate_ejection,q.failure_percentage_ejection,_)}}pa4.OutlierDetectionLoadBalancingConfig=Dt6;class Ia4 extends mSz.BaseSubchannelWrapper{constructor(q,K){super(q);this.mapEntry=K,this.refCount=0}ref(){this.child.ref(),this.refCount+=1}unref(){if(this.child.unref(),this.refCount-=1,this.refCount<=0){if(this.mapEntry){let q=this.mapEntry.subchannelWrappers.indexOf(this);if(q>=0)this.mapEntry.subchannelWrappers.splice(q,1)}}}eject(){this.setHealthy(!1)}uneject(){this.setHealthy(!0)}getMapEntry(){return this.mapEntry}getWrappedSubchannel(){return this.child}}function ec1(){return{success:0,failure:0}}class ua4{constructor(){this.activeBucket=ec1(),this.inactiveBucket=ec1()}addSuccess(){this.activeBucket.success+=1}addFailure(){this.activeBucket.failure+=1}switchBuckets(){this.inactiveBucket=this.activeBucket,this.activeBucket=ec1()}getLastSuccesses(){return this.inactiveBucket.success}getLastFailures(){return this.inactiveBucket.failure}}class ma4{constructor(q,K){this.wrappedPicker=q,this.countCalls=K}pick(q){let K=this.wrappedPicker.pick(q);if(K.pickResultType===uSz.PickResultType.COMPLETE){let _=K.subchannel,z=_.getMapEntry();if(z){let Y=K.onCallEnded;if(this.countCalls)Y=($,A,O)=>{var w;if($===ba4.Status.OK)z.counter.addSuccess();else z.counter.addFailure();(w=K.onCallEnded)===null||w===void 0||w.call(K,$,A,O)};return Object.assign(Object.assign({},K),{subchannel:_.getWrappedSubchannel(),onCallEnded:Y})}else return Object.assign(Object.assign({},K),{subchannel:_.getWrappedSubchannel()})}else return K}}class Kl1{constructor(q){this.entryMap=new sc1.EndpointMap,this.latestConfig=null,this.timerStartTime=null,this.childBalancer=new ISz.ChildLoadBalancerHandler((0,xa4.createChildChannelControlHelper)(q,{createSubchannel:(K,_)=>{let z=q.createSubchannel(K,_),Y=this.entryMap.getForSubchannelAddress(K),$=new Ia4(z,Y);if((Y===null||Y===void 0?void 0:Y.currentEjectionTimestamp)!==null)$.eject();return Y===null||Y===void 0||Y.subchannelWrappers.push($),$},updateState:(K,_,z)=>{if(K===bSz.ConnectivityState.READY)q.updateState(K,new ma4(_,this.isCountingEnabled()),z);else q.updateState(K,_,z)}})),this.ejectionTimer=setInterval(()=>{},0),clearInterval(this.ejectionTimer)}isCountingEnabled(){return this.latestConfig!==null&&(this.latestConfig.getSuccessRateEjectionConfig()!==null||this.latestConfig.getFailurePercentageEjectionConfig()!==null)}getCurrentEjectionPercent(){let q=0;for(let K of this.entryMap.values())if(K.currentEjectionTimestamp!==null)q+=1;return q*100/this.entryMap.size}runSuccessRateCheck(q){if(!this.latestConfig)return;let K=this.latestConfig.getSuccessRateEjectionConfig();if(!K)return;ND("Running success rate check");let _=K.request_volume,z=0,Y=[];for(let[H,J]of this.entryMap.entries()){let M=J.counter.getLastSuccesses(),X=J.counter.getLastFailures();if(ND("Stats for "+(0,sc1.endpointToString)(H)+": successes="+M+" failures="+X+" targetRequestVolume="+_),M+X>=_)z+=1,Y.push(M/(M+X))}if(ND("Found "+z+" success rate candidates; currentEjectionPercent="+this.getCurrentEjectionPercent()+" successRates=["+Y+"]"),z<K.minimum_hosts)return;let $=Y.reduce((H,J)=>H+J)/Y.length,A=0;for(let H of Y){let J=H-$;A+=J*J}let O=A/Y.length,w=Math.sqrt(O),j=$-w*(K.stdev_factor/1000);ND("stdev="+w+" ejectionThreshold="+j);for(let[H,J]of this.entryMap.entries()){if(this.getCurrentEjectionPercent()>=this.latestConfig.getMaxEjectionPercent())break;let M=J.counter.getLastSuccesses(),X=J.counter.getLastFailures();if(M+X<_)continue;let P=M/(M+X);if(ND("Checking candidate "+H+" successRate="+P),P<j){let W=Math.random()*100;if(ND("Candidate "+H+" randomNumber="+W+" enforcement_percentage="+K.enforcement_percentage),W<K.enforcement_percentage)ND("Ejecting candidate "+H),this.eject(J,q)}}}runFailurePercentageCheck(q){if(!this.latestConfig)return;let K=this.latestConfig.getFailurePercentageEjectionConfig();if(!K)return;ND("Running failure percentage check. threshold="+K.threshold+" request volume threshold="+K.request_volume);let _=0;for(let z of this.entryMap.values()){let Y=z.counter.getLastSuccesses(),$=z.counter.getLastFailures();if(Y+$>=K.request_volume)_+=1}if(_<K.minimum_hosts)return;for(let[z,Y]of this.entryMap.entries()){if(this.getCurrentEjectionPercent()>=this.latestConfig.getMaxEjectionPercent())break;let $=Y.counter.getLastSuccesses(),A=Y.counter.getLastFailures();if(ND("Candidate successes="+$+" failures="+A),$+A<K.request_volume)continue;if(A*100/(A+$)>K.threshold){let w=Math.random()*100;if(ND("Candidate "+z+" randomNumber="+w+" enforcement_percentage="+K.enforcement_percentage),w<K.enforcement_percentage)ND("Ejecting candidate "+z),this.eject(Y,q)}}}eject(q,K){q.currentEjectionTimestamp=new Date,q.ejectionTimeMultiplier+=1;for(let _ of q.subchannelWrappers)_.eject()}uneject(q){q.currentEjectionTimestamp=null;for(let K of q.subchannelWrappers)K.uneject()}switchAllBuckets(){for(let q of this.entryMap.values())q.counter.switchBuckets()}startTimer(q){var K,_;this.ejectionTimer=setTimeout(()=>this.runChecks(),q),(_=(K=this.ejectionTimer).unref)===null||_===void 0||_.call(K)}runChecks(){let q=new Date;if(ND("Ejection timer running"),this.switchAllBuckets(),!this.latestConfig)return;this.timerStartTime=q,this.startTimer(this.latestConfig.getIntervalMs()),this.runSuccessRateCheck(q),this.runFailurePercentageCheck(q);for(let[K,_]of this.entryMap.entries())if(_.currentEjectionTimestamp===null){if(_.ejectionTimeMultiplier>0)_.ejectionTimeMultiplier-=1}else{let z=this.latestConfig.getBaseEjectionTimeMs(),Y=this.latestConfig.getMaxEjectionTimeMs(),$=new Date(_.currentEjectionTimestamp.getTime());if($.setMilliseconds($.getMilliseconds()+Math.min(z*_.ejectionTimeMultiplier,Math.max(z,Y))),$<new Date)ND("Unejecting "+K),this.uneject(_)}}updateAddressList(q,K,_,z){if(!(K instanceof Dt6))return!1;if(ND("Received update with config: "+JSON.stringify(K.toJsonObject(),void 0,2)),q.ok){for(let $ of q.value)if(!this.entryMap.has($))ND("Adding map entry for "+(0,sc1.endpointToString)($)),this.entryMap.set($,{counter:new ua4,currentEjectionTimestamp:null,ejectionTimeMultiplier:0,subchannelWrappers:[]});this.entryMap.deleteMissing(q.value)}let Y=K.getChildPolicy();if(this.childBalancer.updateAddressList(q,Y,_,z),K.getSuccessRateEjectionConfig()||K.getFailurePercentageEjectionConfig())if(this.timerStartTime){ND("Previous timer existed. Replacing timer"),clearTimeout(this.ejectionTimer);let $=K.getIntervalMs()-(new Date().getTime()-this.timerStartTime.getTime());this.startTimer($)}else ND("Starting new timer"),this.timerStartTime=new Date,this.startTimer(K.getIntervalMs()),this.switchAllBuckets();else{ND("Counting disabled. Cancelling timer."),this.timerStartTime=null,clearTimeout(this.ejectionTimer);for(let $ of this.entryMap.values())this.uneject($),$.ejectionTimeMultiplier=0}return this.latestConfig=K,!0}exitIdle(){this.childBalancer.exitIdle()}resetBackoff(){this.childBalancer.resetBackoff()}destroy(){clearTimeout(this.ejectionTimer),this.childBalancer.destroy()}getTypeName(){return ql1}}pa4.OutlierDetectionLoadBalancer=Kl1;function QSz(){if(gSz)(0,xa4.registerLoadBalancerType)(ql1,Kl1,Dt6)}});var da4=m((Ua4)=>{Object.defineProperty(Ua4,"__esModule",{value:!0});Ua4.PriorityQueue=void 0;var Qy6=0,_l1=(q)=>Math.floor(q/2),YS8=(q)=>q*2+1,ft6=(q)=>q*2+2;class Fa4{constructor(q=(K,_)=>K>_){this.comparator=q,this.heap=[]}size(){return this.heap.length}isEmpty(){return this.size()==0}peek(){return this.heap[Qy6]}push(...q){return q.forEach((K)=>{this.heap.push(K),this.siftUp()}),this.size()}pop(){let q=this.peek(),K=this.size()-1;if(K>Qy6)this.swap(Qy6,K);return this.heap.pop(),this.siftDown(),q}replace(q){let K=this.peek();return this.heap[Qy6]=q,this.siftDown(),K}greater(q,K){return this.comparator(this.heap[q],this.heap[K])}swap(q,K){[this.heap[q],this.heap[K]]=[this.heap[K],this.heap[q]]}siftUp(){let q=this.size()-1;while(q>Qy6&&this.greater(q,_l1(q)))this.swap(q,_l1(q)),q=_l1(q)}siftDown(){let q=Qy6;while(YS8(q)<this.size()&&this.greater(YS8(q),q)||ft6(q)<this.size()&&this.greater(ft6(q),q)){let K=ft6(q)<this.size()&&this.greater(ft6(q),YS8(q))?ft6(q):YS8(q);this.swap(q,K),q=K}}}Ua4.PriorityQueue=Fa4});var ta4=m((aa4)=>{Object.defineProperty(aa4,"__esModule",{value:!0});aa4.WeightedRoundRobinLoadBalancingConfig=void 0;aa4.setup=KCz;var yD=ev(),lSz=c_(),cL=Ht6(),na4=D46(),nSz=Xt6(),iSz=Gw(),ia4=ih8(),dy6=Wo(),rSz=da4(),ca4=FN(),oSz="weighted_round_robin";function zl1(q){iSz.trace(lSz.LogVerbosity.DEBUG,oSz,q)}var Yl1="weighted_round_robin",aSz=1e4,sSz=1e4,tSz=180000,eSz=1000,qCz=1;function la4(q,K,_){if(K in q&&q[K]!==void 0&&typeof q[K]!==_)throw Error(`weighted round robin config ${K} parse error: expected ${_}, got ${typeof q[K]}`)}function $S8(q,K){if(K in q&&q[K]!==void 0&&q[K]!==null){let _;if((0,cL.isDuration)(q[K]))_=q[K];else if((0,cL.isDurationMessage)(q[K]))_=(0,cL.durationMessageToDuration)(q[K]);else if(typeof q[K]==="string"){let z=(0,cL.parseDuration)(q[K]);if(!z)throw Error(`weighted round robin config ${K}: failed to parse duration string ${q[K]}`);_=z}else throw Error(`weighted round robin config ${K}: expected duration, got ${typeof q[K]}`);return(0,cL.durationToMs)(_)}return null}class Zt6{constructor(q,K,_,z,Y,$){this.enableOobLoadReport=q!==null&&q!==void 0?q:!1,this.oobLoadReportingPeriodMs=K!==null&&K!==void 0?K:aSz,this.blackoutPeriodMs=_!==null&&_!==void 0?_:sSz,this.weightExpirationPeriodMs=z!==null&&z!==void 0?z:tSz,this.weightUpdatePeriodMs=Math.max(Y!==null&&Y!==void 0?Y:eSz,100),this.errorUtilizationPenalty=$!==null&&$!==void 0?$:qCz}getLoadBalancerName(){return Yl1}toJsonObject(){return{enable_oob_load_report:this.enableOobLoadReport,oob_load_reporting_period:(0,cL.durationToString)((0,cL.msToDuration)(this.oobLoadReportingPeriodMs)),blackout_period:(0,cL.durationToString)((0,cL.msToDuration)(this.blackoutPeriodMs)),weight_expiration_period:(0,cL.durationToString)((0,cL.msToDuration)(this.weightExpirationPeriodMs)),weight_update_period:(0,cL.durationToString)((0,cL.msToDuration)(this.weightUpdatePeriodMs)),error_utilization_penalty:this.errorUtilizationPenalty}}static createFromJson(q){if(la4(q,"enable_oob_load_report","boolean"),la4(q,"error_utilization_penalty","number"),q.error_utilization_penalty<0)throw Error("weighted round robin config error_utilization_penalty < 0");return new Zt6(q.enable_oob_load_report,$S8(q,"oob_load_reporting_period"),$S8(q,"blackout_period"),$S8(q,"weight_expiration_period"),$S8(q,"weight_update_period"),q.error_utilization_penalty)}getEnableOobLoadReport(){return this.enableOobLoadReport}getOobLoadReportingPeriodMs(){return this.oobLoadReportingPeriodMs}getBlackoutPeriodMs(){return this.blackoutPeriodMs}getWeightExpirationPeriodMs(){return this.weightExpirationPeriodMs}getWeightUpdatePeriodMs(){return this.weightUpdatePeriodMs}getErrorUtilizationPenalty(){return this.errorUtilizationPenalty}}aa4.WeightedRoundRobinLoadBalancingConfig=Zt6;class ra4{constructor(q,K){this.metricsHandler=K,this.queue=new rSz.PriorityQueue((Y,$)=>Y.deadline<$.deadline);let _=q.filter((Y)=>Y.weight>0),z;if(_.length<2)z=1;else{let Y=0;for(let{weight:$}of _)Y+=$;z=Y/_.length}for(let Y of q){let $=Y.weight>0?1/Y.weight:z;this.queue.push({endpointName:Y.endpointName,picker:Y.picker,period:$,deadline:Math.random()*$})}}pick(q){let K=this.queue.pop();this.queue.push(Object.assign(Object.assign({},K),{deadline:K.deadline+K.period}));let _=K.picker.pick(q);if(_.pickResultType===dy6.PickResultType.COMPLETE)if(this.metricsHandler)return Object.assign(Object.assign({},_),{onCallEnded:(0,ia4.createMetricsReader)((z)=>this.metricsHandler(z,K.endpointName),_.onCallEnded)});else{let z=_.subchannel;return Object.assign(Object.assign({},_),{subchannel:z.getWrappedSubchannel()})}else return _}}class oa4{constructor(q){this.channelControlHelper=q,this.latestConfig=null,this.children=new Map,this.currentState=yD.ConnectivityState.IDLE,this.updatesPaused=!1,this.lastError=null,this.weightUpdateTimer=null}countChildrenWithState(q){let K=0;for(let _ of this.children.values())if(_.child.getConnectivityState()===q)K+=1;return K}updateWeight(q,K){var _,z;let{rps_fractional:Y,application_utilization:$}=K;if($>0&&Y>0)$+=K.eps/Y*((z=(_=this.latestConfig)===null||_===void 0?void 0:_.getErrorUtilizationPenalty())!==null&&z!==void 0?z:0);let A=$===0?0:Y/$;if(A===0)return;let O=new Date;if(q.nonEmptySince===null)q.nonEmptySince=O;q.lastUpdated=O,q.weight=A}getWeight(q){if(!this.latestConfig)return 0;let K=new Date().getTime();if(K-q.lastUpdated.getTime()>=this.latestConfig.getWeightExpirationPeriodMs())return q.nonEmptySince=null,0;let _=this.latestConfig.getBlackoutPeriodMs();if(_>0&&(q.nonEmptySince===null||K-q.nonEmptySince.getTime()<_))return 0;return q.weight}calculateAndUpdateState(){if(this.updatesPaused||!this.latestConfig)return;if(this.countChildrenWithState(yD.ConnectivityState.READY)>0){let q=[];for(let[_,z]of this.children){if(z.child.getConnectivityState()!==yD.ConnectivityState.READY)continue;q.push({endpointName:_,picker:z.child.getPicker(),weight:this.getWeight(z)})}zl1("Created picker with weights: "+q.map((_)=>_.endpointName+":"+_.weight).join(","));let K;if(!this.latestConfig.getEnableOobLoadReport())K=(_,z)=>{let Y=this.children.get(z);if(Y)this.updateWeight(Y,_)};else K=null;this.updateState(yD.ConnectivityState.READY,new ra4(q,K),null)}else if(this.countChildrenWithState(yD.ConnectivityState.CONNECTING)>0)this.updateState(yD.ConnectivityState.CONNECTING,new dy6.QueuePicker(this),null);else if(this.countChildrenWithState(yD.ConnectivityState.TRANSIENT_FAILURE)>0){let q=`weighted_round_robin: No connection established. Last error: ${this.lastError}`;this.updateState(yD.ConnectivityState.TRANSIENT_FAILURE,new dy6.UnavailablePicker({details:q}),q)}else this.updateState(yD.ConnectivityState.IDLE,new dy6.QueuePicker(this),null);for(let{child:q}of this.children.values())if(q.getConnectivityState()===yD.ConnectivityState.IDLE)q.exitIdle()}updateState(q,K,_){zl1(yD.ConnectivityState[this.currentState]+" -> "+yD.ConnectivityState[q]),this.currentState=q,this.channelControlHelper.updateState(q,K,_)}updateAddressList(q,K,_,z){var Y,$;if(!(K instanceof Zt6))return!1;if(!q.ok){if(this.children.size===0)this.updateState(yD.ConnectivityState.TRANSIENT_FAILURE,new dy6.UnavailablePicker(q.error),q.error.details);return!0}if(q.value.length===0){let w=`No addresses resolved. Resolution note: ${z}`;return this.updateState(yD.ConnectivityState.TRANSIENT_FAILURE,new dy6.UnavailablePicker({details:w}),w),!1}zl1("Connect to endpoint list "+q.value.map(ca4.endpointToString));let A=new Date,O=new Set;this.updatesPaused=!0,this.latestConfig=K;for(let w of q.value){let j=(0,ca4.endpointToString)(w);O.add(j);let H=this.children.get(j);if(!H)H={child:new nSz.LeafLoadBalancer(w,(0,na4.createChildChannelControlHelper)(this.channelControlHelper,{updateState:(J,M,X)=>{if(this.currentState===yD.ConnectivityState.READY&&J!==yD.ConnectivityState.READY)this.channelControlHelper.requestReresolution();if(J===yD.ConnectivityState.READY)H.nonEmptySince=null;if(X)this.lastError=X;this.calculateAndUpdateState()},createSubchannel:(J,M)=>{let X=this.channelControlHelper.createSubchannel(J,M);if(H===null||H===void 0?void 0:H.oobMetricsListener)return new ia4.OrcaOobMetricsSubchannelWrapper(X,H.oobMetricsListener,this.latestConfig.getOobLoadReportingPeriodMs());else return X}}),_,z),lastUpdated:A,nonEmptySince:null,weight:0,oobMetricsListener:null},this.children.set(j,H);if(K.getEnableOobLoadReport())H.oobMetricsListener=(J)=>{this.updateWeight(H,J)};else H.oobMetricsListener=null}for(let[w,j]of this.children)if(O.has(w))j.child.startConnecting();else j.child.destroy(),this.children.delete(w);if(this.updatesPaused=!1,this.calculateAndUpdateState(),this.weightUpdateTimer)clearInterval(this.weightUpdateTimer);return this.weightUpdateTimer=($=(Y=setInterval(()=>{if(this.currentState===yD.ConnectivityState.READY)this.calculateAndUpdateState()},K.getWeightUpdatePeriodMs())).unref)===null||$===void 0?void 0:$.call(Y),!0}exitIdle(){}resetBackoff(){}destroy(){for(let q of this.children.values())q.child.destroy();if(this.children.clear(),this.weightUpdateTimer)clearInterval(this.weightUpdateTimer)}getTypeName(){return Yl1}}function KCz(){(0,na4.registerLoadBalancerType)(Yl1,oa4,Zt6)}});var Gt6=m((wO)=>{Object.defineProperty(wO,"__esModule",{value:!0});wO.experimental=wO.ServerMetricRecorder=wO.ServerInterceptingCall=wO.ResponderBuilder=wO.ServerListenerBuilder=wO.addAdminServicesToServer=wO.getChannelzHandlers=wO.getChannelzServiceDefinition=wO.InterceptorConfigurationError=wO.InterceptingCall=wO.RequesterBuilder=wO.ListenerBuilder=wO.StatusBuilder=wO.getClientChannel=wO.ServerCredentials=wO.Server=wO.setLogVerbosity=wO.setLogger=wO.load=wO.loadObject=wO.CallCredentials=wO.ChannelCredentials=wO.waitForClientReady=wO.closeClient=wO.Channel=wO.makeGenericClientConstructor=wO.makeClientConstructor=wO.loadPackageDefinition=wO.Client=wO.compressionAlgorithms=wO.propagate=wO.connectivityState=wO.status=wO.logVerbosity=wO.Metadata=wO.credentials=void 0;var AS8=dR8();Object.defineProperty(wO,"CallCredentials",{enumerable:!0,get:function(){return AS8.CallCredentials}});var zCz=zd1();Object.defineProperty(wO,"Channel",{enumerable:!0,get:function(){return zCz.ChannelImplementation}});var YCz=Kc1();Object.defineProperty(wO,"compressionAlgorithms",{enumerable:!0,get:function(){return YCz.CompressionAlgorithms}});var $Cz=ev();Object.defineProperty(wO,"connectivityState",{enumerable:!0,get:function(){return $Cz.ConnectivityState}});var OS8=Wy6();Object.defineProperty(wO,"ChannelCredentials",{enumerable:!0,get:function(){return OS8.ChannelCredentials}});var ea4=_d1();Object.defineProperty(wO,"Client",{enumerable:!0,get:function(){return ea4.Client}});var $l1=c_();Object.defineProperty(wO,"logVerbosity",{enumerable:!0,get:function(){return $l1.LogVerbosity}});Object.defineProperty(wO,"status",{enumerable:!0,get:function(){return $l1.Status}});Object.defineProperty(wO,"propagate",{enumerable:!0,get:function(){return $l1.Propagate}});var qs4=Gw(),Al1=Kh8();Object.defineProperty(wO,"loadPackageDefinition",{enumerable:!0,get:function(){return Al1.loadPackageDefinition}});Object.defineProperty(wO,"makeClientConstructor",{enumerable:!0,get:function(){return Al1.makeClientConstructor}});Object.defineProperty(wO,"makeGenericClientConstructor",{enumerable:!0,get:function(){return Al1.makeClientConstructor}});var ACz=vD();Object.defineProperty(wO,"Metadata",{enumerable:!0,get:function(){return ACz.Metadata}});var OCz=no4();Object.defineProperty(wO,"Server",{enumerable:!0,get:function(){return OCz.Server}});var wCz=lh8();Object.defineProperty(wO,"ServerCredentials",{enumerable:!0,get:function(){return wCz.ServerCredentials}});var jCz=ao4();Object.defineProperty(wO,"StatusBuilder",{enumerable:!0,get:function(){return jCz.StatusBuilder}});wO.credentials={combineChannelCredentials:(q,...K)=>{return K.reduce((_,z)=>_.compose(z),q)},combineCallCredentials:(q,...K)=>{return K.reduce((_,z)=>_.compose(z),q)},createInsecure:OS8.ChannelCredentials.createInsecure,createSsl:OS8.ChannelCredentials.createSsl,createFromSecureContext:OS8.ChannelCredentials.createFromSecureContext,createFromMetadataGenerator:AS8.CallCredentials.createFromMetadataGenerator,createFromGoogleCredential:AS8.CallCredentials.createFromGoogleCredential,createEmpty:AS8.CallCredentials.createEmpty};var HCz=(q)=>q.close();wO.closeClient=HCz;var JCz=(q,K,_)=>q.waitForReady(K,_);wO.waitForClientReady=JCz;var MCz=(q,K)=>{throw Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead")};wO.loadObject=MCz;var XCz=(q,K,_)=>{throw Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead")};wO.load=XCz;var PCz=(q)=>{qs4.setLogger(q)};wO.setLogger=PCz;var WCz=(q)=>{qs4.setLoggerVerbosity(q)};wO.setLogVerbosity=WCz;var DCz=(q)=>{return ea4.Client.prototype.getChannel.call(q)};wO.getClientChannel=DCz;var wS8=qd1();Object.defineProperty(wO,"ListenerBuilder",{enumerable:!0,get:function(){return wS8.ListenerBuilder}});Object.defineProperty(wO,"RequesterBuilder",{enumerable:!0,get:function(){return wS8.RequesterBuilder}});Object.defineProperty(wO,"InterceptingCall",{enumerable:!0,get:function(){return wS8.InterceptingCall}});Object.defineProperty(wO,"InterceptorConfigurationError",{enumerable:!0,get:function(){return wS8.InterceptorConfigurationError}});var Ks4=V46();Object.defineProperty(wO,"getChannelzServiceDefinition",{enumerable:!0,get:function(){return Ks4.getChannelzServiceDefinition}});Object.defineProperty(wO,"getChannelzHandlers",{enumerable:!0,get:function(){return Ks4.getChannelzHandlers}});var fCz=eR8();Object.defineProperty(wO,"addAdminServicesToServer",{enumerable:!0,get:function(){return fCz.addAdminServicesToServer}});var Ol1=mc1();Object.defineProperty(wO,"ServerListenerBuilder",{enumerable:!0,get:function(){return Ol1.ServerListenerBuilder}});Object.defineProperty(wO,"ResponderBuilder",{enumerable:!0,get:function(){return Ol1.ResponderBuilder}});Object.defineProperty(wO,"ServerInterceptingCall",{enumerable:!0,get:function(){return Ol1.ServerInterceptingCall}});var ZCz=ih8();Object.defineProperty(wO,"ServerMetricRecorder",{enumerable:!0,get:function(){return ZCz.ServerMetricRecorder}});var GCz=cc1();wO.experimental=GCz;var TCz=Mc1(),vCz=fa4(),kCz=Na4(),VCz=Xt6(),NCz=Ca4(),yCz=ga4(),ECz=ta4(),LCz=V46();(()=>{TCz.setup(),vCz.setup(),kCz.setup(),VCz.setup(),NCz.setup(),yCz.setup(),ECz.setup(),LCz.setup()})()});var $s4=m((zs4)=>{Object.defineProperty(zs4,"__esModule",{value:!0});zs4.createServiceClientConstructor=void 0;var mCz=Gt6();function pCz(q,K){let _={export:{path:q,requestStream:!1,responseStream:!1,requestSerialize:(z)=>{return z},requestDeserialize:(z)=>{return z},responseSerialize:(z)=>{return z},responseDeserialize:(z)=>{return z}}};return mCz.makeGenericClientConstructor(_,K)}zs4.createServiceClientConstructor=pCz});var Tt6=m((Os4)=>{Object.defineProperty(Os4,"__esModule",{value:!0});Os4.createOtlpGrpcExporterTransport=Os4.GrpcExporterTransport=Os4.createEmptyMetadata=Os4.createSslCredentials=Os4.createInsecureCredentials=void 0;var BCz=Nd4(),As4=`OTel-OTLP-Exporter-JavaScript/${BCz.VERSION}`;function gCz(q){if(q)return`${q} ${As4}`;return As4}var FCz=0,UCz=2;function QCz(q){return q==="gzip"?UCz:FCz}function dCz(){let{credentials:q}=Gt6();return q.createInsecure()}Os4.createInsecureCredentials=dCz;function cCz(q,K,_){let{credentials:z}=Gt6();return z.createSsl(q,K,_)}Os4.createSslCredentials=cCz;function lCz(){let{Metadata:q}=Gt6();return new q}Os4.createEmptyMetadata=lCz;class wl1{_parameters;_client;_metadata;constructor(q){this._parameters=q}shutdown(){this._client?.close()}send(q,K){let _=Buffer.from(q);if(this._client==null){let{createServiceClientConstructor:z}=$s4();try{this._metadata=this._parameters.metadata()}catch($){return Promise.resolve({status:"failure",error:$})}let Y=z(this._parameters.grpcPath,this._parameters.grpcName);try{this._client=new Y(this._parameters.address,this._parameters.credentials(),{"grpc.default_compression_algorithm":QCz(this._parameters.compression),"grpc.primary_user_agent":gCz(this._parameters.userAgent)})}catch($){return Promise.resolve({status:"failure",error:$})}}return new Promise((z)=>{let Y=Date.now()+K;if(this._metadata==null)return z({error:Error("metadata was null"),status:"failure"});this._client.export(_,this._metadata,{deadline:Y},($,A)=>{if($)z({status:"failure",error:$});else z({data:A,status:"success"})})})}}Os4.GrpcExporterTransport=wl1;function nCz(q){return new wl1(q)}Os4.createOtlpGrpcExporterTransport=nCz});var Ws4=m((Xs4)=>{Object.defineProperty(Xs4,"__esModule",{value:!0});Xs4.getOtlpGrpcDefaultConfiguration=Xs4.mergeOtlpGrpcConfigurationWithDefaults=Xs4.validateAndNormalizeUrl=void 0;var Js4=oU(),vt6=Tt6(),sCz=U6("url"),js4=nK();function Ms4(q){if(q=q.trim(),!q.match(/^([\w]{1,8}):\/\//))q=`https://${q}`;let _=new sCz.URL(q);if(_.protocol==="unix:")return q;if(_.pathname&&_.pathname!=="/")js4.diag.warn("URL path should not be set when using grpc, the path part of the URL will be ignored.");if(_.protocol!==""&&!_.protocol?.match(/^(http)s?:$/))js4.diag.warn("URL protocol should be http(s)://. Using http://.");return _.host}Xs4.validateAndNormalizeUrl=Ms4;function Hs4(q,K){for(let[_,z]of Object.entries(K.getMap()))if(q.get(_).length<1)q.set(_,z)}function tCz(q,K,_){let z=q.url??K.url??_.url;return{...(0,Js4.mergeOtlpSharedConfigurationWithDefaults)(q,K,_),metadata:()=>{let Y=_.metadata();return Hs4(Y,q.metadata?.().clone()??(0,vt6.createEmptyMetadata)()),Hs4(Y,K.metadata?.()??(0,vt6.createEmptyMetadata)()),Y},url:Ms4(z),credentials:q.credentials??K.credentials?.(z)??_.credentials(z),userAgent:q.userAgent}}Xs4.mergeOtlpGrpcConfigurationWithDefaults=tCz;function eCz(){return{...(0,Js4.getSharedConfigurationDefaults)(),metadata:()=>(0,vt6.createEmptyMetadata)(),url:"http://localhost:4317",credentials:(q)=>{if(q.startsWith("http://"))return()=>(0,vt6.createInsecureCredentials)();else return()=>(0,vt6.createSslCredentials)()}}}Xs4.getOtlpGrpcDefaultConfiguration=eCz});var ks4=m((Ts4)=>{Object.defineProperty(Ts4,"__esModule",{value:!0});Ts4.getOtlpGrpcConfigurationFromEnv=void 0;var Ds4=Oz(),kt6=Tt6(),_bz=Po(),zbz=U6("fs"),Ybz=U6("path"),Zs4=nK();function jl1(q,K){if(q!=null&&q!=="")return q;if(K!=null&&K!=="")return K;return}function $bz(q){let K=process.env[`OTEL_EXPORTER_OTLP_${q}_HEADERS`]?.trim(),_=process.env.OTEL_EXPORTER_OTLP_HEADERS?.trim(),z=(0,Ds4.parseKeyPairsIntoRecord)(K),Y=(0,Ds4.parseKeyPairsIntoRecord)(_);if(Object.keys(z).length===0&&Object.keys(Y).length===0)return;let $=Object.assign({},Y,z),A=(0,kt6.createEmptyMetadata)();for(let[O,w]of Object.entries($))A.set(O,w);return A}function Abz(q){let K=$bz(q);if(K==null)return;return()=>K}function Obz(q){let K=process.env[`OTEL_EXPORTER_OTLP_${q}_ENDPOINT`]?.trim(),_=process.env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim();return jl1(K,_)}function wbz(q){let K=process.env[`OTEL_EXPORTER_OTLP_${q}_INSECURE`]?.toLowerCase().trim(),_=process.env.OTEL_EXPORTER_OTLP_INSECURE?.toLowerCase().trim();return jl1(K,_)==="true"}function Hl1(q,K,_){let z=process.env[q]?.trim(),Y=process.env[K]?.trim(),$=jl1(z,Y);if($!=null)try{return zbz.readFileSync(Ybz.resolve(process.cwd(),$))}catch{Zs4.diag.warn(_);return}else return}function jbz(q){return Hl1(`OTEL_EXPORTER_OTLP_${q}_CLIENT_CERTIFICATE`,"OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE","Failed to read client certificate chain file")}function Hbz(q){return Hl1(`OTEL_EXPORTER_OTLP_${q}_CLIENT_KEY`,"OTEL_EXPORTER_OTLP_CLIENT_KEY","Failed to read client certificate private key file")}function fs4(q){return Hl1(`OTEL_EXPORTER_OTLP_${q}_CERTIFICATE`,"OTEL_EXPORTER_OTLP_CERTIFICATE","Failed to read root certificate file")}function Gs4(q){let K=Hbz(q),_=jbz(q),z=fs4(q),Y=K!=null&&_!=null;if(z!=null&&!Y)return Zs4.diag.warn("Client key and certificate must both be provided, but one was missing - attempting to create credentials from just the root certificate"),(0,kt6.createSslCredentials)(fs4(q));return(0,kt6.createSslCredentials)(z,K,_)}function Jbz(q){if(wbz(q))return(0,kt6.createInsecureCredentials)();return Gs4(q)}function Mbz(q){return{...(0,_bz.getSharedConfigurationFromEnvironment)(q),metadata:Abz(q),url:Obz(q),credentials:(K)=>{if(K.startsWith("http://"))return()=>{return(0,kt6.createInsecureCredentials)()};else if(K.startsWith("https://"))return()=>{return Gs4(q)};return()=>{return Jbz(q)}}}}Ts4.getOtlpGrpcConfigurationFromEnv=Mbz});var Es4=m((Ns4)=>{Object.defineProperty(Ns4,"__esModule",{value:!0});Ns4.convertLegacyOtlpGrpcOptions=void 0;var Xbz=nK(),Vs4=Ws4(),Pbz=Tt6(),Wbz=ks4();function Dbz(q,K){if(q.headers)Xbz.diag.warn("Headers cannot be set when using grpc");let _=q.credentials;return(0,Vs4.mergeOtlpGrpcConfigurationWithDefaults)({url:q.url,metadata:()=>{return q.metadata??(0,Pbz.createEmptyMetadata)()},compression:q.compression,timeoutMillis:q.timeoutMillis,concurrencyLimit:q.concurrencyLimit,credentials:_!=null?()=>_:void 0,userAgent:q.userAgent},(0,Wbz.getOtlpGrpcConfigurationFromEnv)(K),(0,Vs4.getOtlpGrpcDefaultConfiguration)())}Ns4.convertLegacyOtlpGrpcOptions=Dbz});var hs4=m((Ls4)=>{Object.defineProperty(Ls4,"__esModule",{value:!0});Ls4.createOtlpGrpcExportDelegate=void 0;var fbz=oU(),Zbz=Tt6();function Gbz(q,K,_,z){return(0,fbz.createOtlpNetworkExportDelegate)(q,K,(0,Zbz.createOtlpGrpcExporterTransport)({address:q.url,compression:q.compression,credentials:q.credentials,metadata:q.metadata,userAgent:q.userAgent,grpcName:_,grpcPath:z}))}Ls4.createOtlpGrpcExportDelegate=Gbz});var HS8=m((jS8)=>{Object.defineProperty(jS8,"__esModule",{value:!0});jS8.createOtlpGrpcExportDelegate=jS8.convertLegacyOtlpGrpcOptions=void 0;var Tbz=Es4();Object.defineProperty(jS8,"convertLegacyOtlpGrpcOptions",{enumerable:!0,get:function(){return Tbz.convertLegacyOtlpGrpcOptions}});var vbz=hs4();Object.defineProperty(jS8,"createOtlpGrpcExportDelegate",{enumerable:!0,get:function(){return vbz.createOtlpGrpcExportDelegate}})});var Is4=m((bs4)=>{Object.defineProperty(bs4,"__esModule",{value:!0});bs4.OTLPMetricExporter=void 0;var Vbz=BR8(),Ss4=HS8(),Nbz=tU();class Cs4 extends Vbz.OTLPMetricExporterBase{constructor(q){super((0,Ss4.createOtlpGrpcExportDelegate)((0,Ss4.convertLegacyOtlpGrpcOptions)(q??{},"METRICS"),Nbz.ProtobufMetricsSerializer,"MetricsExportService","/opentelemetry.proto.collector.metrics.v1.MetricsService/Export"),q)}}bs4.OTLPMetricExporter=Cs4});var us4=m((Jl1)=>{Object.defineProperty(Jl1,"__esModule",{value:!0});Jl1.OTLPMetricExporter=void 0;var ybz=Is4();Object.defineProperty(Jl1,"OTLPMetricExporter",{enumerable:!0,get:function(){return ybz.OTLPMetricExporter}})});var Fs4=m((Bs4)=>{Object.defineProperty(Bs4,"__esModule",{value:!0});Bs4.OTLPMetricExporter=void 0;var Lbz=BR8(),Rbz=tU(),ms4=Po();class ps4 extends Lbz.OTLPMetricExporterBase{constructor(q){super((0,ms4.createOtlpHttpExportDelegate)((0,ms4.convertLegacyHttpOptions)(q??{},"METRICS","v1/metrics",{"Content-Type":"application/x-protobuf"}),Rbz.ProtobufMetricsSerializer),q)}}Bs4.OTLPMetricExporter=ps4});var Us4=m((Ml1)=>{Object.defineProperty(Ml1,"__esModule",{value:!0});Ml1.OTLPMetricExporter=void 0;var hbz=Fs4();Object.defineProperty(Ml1,"OTLPMetricExporter",{enumerable:!0,get:function(){return hbz.OTLPMetricExporter}})});var Qs4=m((Xl1)=>{Object.defineProperty(Xl1,"__esModule",{value:!0});Xl1.OTLPMetricExporter=void 0;var Cbz=Us4();Object.defineProperty(Xl1,"OTLPMetricExporter",{enumerable:!0,get:function(){return Cbz.OTLPMetricExporter}})});var ds4=m((Pl1)=>{Object.defineProperty(Pl1,"__esModule",{value:!0});Pl1.OTLPMetricExporter=void 0;var xbz=Qs4();Object.defineProperty(Pl1,"OTLPMetricExporter",{enumerable:!0,get:function(){return xbz.OTLPMetricExporter}})});var fl1=m((is4)=>{Object.defineProperty(is4,"__esModule",{value:!0});is4.PrometheusSerializer=void 0;var ubz=nK(),V26=z26(),cs4=Oz();function MS8(q){return q.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function ls4(q=""){if(typeof q!=="string")q=JSON.stringify(q);return MS8(q).replace(/"/g,"\\\"")}var mbz=/[^a-z0-9_]/gi,pbz=/_{2,}/g;function Dl1(q){return q.replace(mbz,"_").replace(pbz,"_")}function Wl1(q,K){if(!q.endsWith("_total")&&K.dataPointType===V26.DataPointType.SUM&&K.isMonotonic)q=q+"_total";return q}function Bbz(q){if(q===1/0)return"+Inf";else if(q===-1/0)return"-Inf";else return`${q}`}function gbz(q){switch(q.dataPointType){case V26.DataPointType.SUM:if(q.isMonotonic)return"counter";return"gauge";case V26.DataPointType.GAUGE:return"gauge";case V26.DataPointType.HISTOGRAM:return"histogram";default:return"untyped"}}function JS8(q,K,_,z,Y){let $=!1,A="";for(let[O,w]of Object.entries(K)){let j=Dl1(O);$=!0,A+=`${A.length>0?",":""}${j}="${ls4(w)}"`}if(Y)for(let[O,w]of Object.entries(Y)){let j=Dl1(O);$=!0,A+=`${A.length>0?",":""}${j}="${ls4(w)}"`}if($)q+=`{${A}}`;return`${q} ${Bbz(_)}${z!==void 0?" "+String(z):""}
2094`}var Fbz="# no registered metrics";class ns4{_prefix;_appendTimestamp;_additionalAttributes;_withResourceConstantLabels;_withoutTargetInfo;constructor(q,K=!1,_,z){if(q)this._prefix=q+"_";this._appendTimestamp=K,this._withResourceConstantLabels=_,this._withoutTargetInfo=!!z}serialize(q){let K="";this._additionalAttributes=this._filterResourceConstantLabels(q.resource.attributes,this._withResourceConstantLabels);for(let _ of q.scopeMetrics)K+=this._serializeScopeMetrics(_);if(K==="")K+=Fbz;return this._serializeResource(q.resource)+K}_filterResourceConstantLabels(q,K){if(K){let _={};for(let[z,Y]of Object.entries(q))if(z.match(K))_[z]=Y;return _}return}_serializeScopeMetrics(q){let K="";for(let _ of q.metrics)K+=this._serializeMetricData(_)+`
2095`;return K}_serializeMetricData(q){let K=Dl1(MS8(q.descriptor.name));if(this._prefix)K=`${this._prefix}${K}`;let _=q.dataPointType;K=Wl1(K,q);let z=`# HELP ${K} ${MS8(q.descriptor.description||"description missing")}`,Y=q.descriptor.unit?`

Callers 6

setMethod · 0.45
cloneMethod · 0.45
wB6Function · 0.45
constructorMethod · 0.45
addServiceMethod · 0.45

Calls 2

hasMethod · 0.45
setMethod · 0.45

Tested by

no test coverage detected