9remote 2.0.65 → 2.0.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.cjs CHANGED
@@ -26,7 +26,7 @@ Content-Length: `+i+`\r
26
26
  `+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
27
27
  `)+`\r
28
28
  \r
29
- `+t)}function si(r,e,t,n,i,s){if(r.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,si),r.emit("wsClientError",o,t,e)}else Ro(t,n,i,s)}});var nb=R((f6,rb)=>{"use strict";var cn=Vc();cn.createWebSocketStream=z_();cn.Server=tb();cn.Receiver=vd();cn.Sender=_d();cn.WebSocket=cn;cn.WebSocketServer=cn.Server;rb.exports=cn});var Od=R(cs=>{"use strict";var Rd;Object.defineProperty(cs,"__esModule",{value:!0});cs.SessionAwareAdapter=cs.Adapter=void 0;var jD=require("events"),FD=Xx(),Yc=nb(),UD=typeof((Rd=Yc?.Sender)===null||Rd===void 0?void 0:Rd.frame)=="function",Jc=class extends jD.EventEmitter{constructor(e){super(),this.nsp=e,this.rooms=new Map,this.sids=new Map,this.encoder=e.server.encoder}init(){}close(){}serverCount(){return Promise.resolve(1)}addAll(e,t){this.sids.has(e)||this.sids.set(e,new Set);for(let n of t)this.sids.get(e).add(n),this.rooms.has(n)||(this.rooms.set(n,new Set),this.emit("create-room",n)),this.rooms.get(n).has(e)||(this.rooms.get(n).add(e),this.emit("join-room",n,e))}del(e,t){this.sids.has(e)&&this.sids.get(e).delete(t),this._del(t,e)}_del(e,t){let n=this.rooms.get(e);n!=null&&(n.delete(t)&&this.emit("leave-room",e,t),n.size===0&&this.rooms.delete(e)&&this.emit("delete-room",e))}delAll(e){if(this.sids.has(e)){for(let t of this.sids.get(e))this._del(t,e);this.sids.delete(e)}}broadcast(e,t){let n=t.flags||{},i={preEncoded:!0,volatile:n.volatile,compress:n.compress};e.nsp=this.nsp.name;let s=this._encode(e,i);this.apply(t,o=>{typeof o.notifyOutgoingListeners=="function"&&o.notifyOutgoingListeners(e),o.client.writeToEngine(s,i)})}broadcastWithAck(e,t,n,i){let s=t.flags||{},o={preEncoded:!0,volatile:s.volatile,compress:s.compress};e.nsp=this.nsp.name,e.id=this.nsp._ids++;let a=this._encode(e,o),c=0;this.apply(t,l=>{c++,l.acks.set(e.id,i),typeof l.notifyOutgoingListeners=="function"&&l.notifyOutgoingListeners(e),l.client.writeToEngine(a,o)}),n(c)}_encode(e,t){let n=this.encoder.encode(e);if(UD&&n.length===1&&typeof n[0]=="string"){let i=Buffer.from("4"+n[0]);t.wsPreEncodedFrame=Yc.Sender.frame(i,{readOnly:!1,mask:!1,rsv1:!1,opcode:1,fin:!0})}return n}sockets(e){let t=new Set;return this.apply({rooms:e},n=>{t.add(n.id)}),Promise.resolve(t)}socketRooms(e){return this.sids.get(e)}fetchSockets(e){let t=[];return this.apply(e,n=>{t.push(n)}),Promise.resolve(t)}addSockets(e,t){this.apply(e,n=>{n.join(t)})}delSockets(e,t){this.apply(e,n=>{t.forEach(i=>n.leave(i))})}disconnectSockets(e,t){this.apply(e,n=>{n.disconnect(t)})}apply(e,t){let n=e.rooms,i=this.computeExceptSids(e.except);if(n.size){let s=new Set;for(let o of n)if(this.rooms.has(o))for(let a of this.rooms.get(o)){if(s.has(a)||i.has(a))continue;let c=this.nsp.sockets.get(a);c&&(t(c),s.add(a))}}else for(let[s]of this.sids){if(i.has(s))continue;let o=this.nsp.sockets.get(s);o&&t(o)}}computeExceptSids(e){let t=new Set;if(e&&e.size>0)for(let n of e)this.rooms.has(n)&&this.rooms.get(n).forEach(i=>t.add(i));return t}serverSideEmit(e){console.warn("this adapter does not support the serverSideEmit() functionality")}persistSession(e){}restoreSession(e,t){return null}};cs.Adapter=Jc;var kd=class extends Jc{constructor(e){super(e),this.nsp=e,this.sessions=new Map,this.packets=[],this.maxDisconnectionDuration=e.server.opts.connectionStateRecovery.maxDisconnectionDuration,setInterval(()=>{let n=Date.now()-this.maxDisconnectionDuration;this.sessions.forEach((i,s)=>{i.disconnectedAt<n&&this.sessions.delete(s)});for(let i=this.packets.length-1;i>=0;i--)if(this.packets[i].emittedAt<n){this.packets.splice(0,i+1);break}},60*1e3).unref()}persistSession(e){e.disconnectedAt=Date.now(),this.sessions.set(e.pid,e)}restoreSession(e,t){let n=this.sessions.get(e);if(!n)return null;if(n.disconnectedAt+this.maxDisconnectionDuration<Date.now())return this.sessions.delete(e),null;let s=this.packets.findIndex(a=>a.id===t);if(s===-1)return null;let o=[];for(let a=s+1;a<this.packets.length;a++){let c=this.packets[a];qD(n.rooms,c.opts)&&o.push(c.data)}return Promise.resolve(Object.assign(Object.assign({},n),{missedPackets:o}))}broadcast(e,t){var n;let i=e.type===2,s=e.id===void 0,o=((n=t.flags)===null||n===void 0?void 0:n.volatile)===void 0;if(i&&s&&o){let a=(0,FD.yeast)();e.data.push(a),this.packets.push({id:a,opts:t,data:e.data,emittedAt:Date.now()})}super.broadcast(e,t)}};cs.SessionAwareAdapter=kd;function qD(r,e){let t=e.rooms.size===0||r.some(i=>e.rooms.has(i)),n=r.every(i=>!e.except.has(i));return t&&n}});var ib=R(Dr=>{"use strict";var HD=Dr&&Dr.__rest||function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.ClusterAdapterWithHeartbeat=Dr.ClusterAdapter=Dr.MessageType=void 0;var $D=Od(),WD=Ce(),GD=require("crypto"),we=(0,WD.debug)("socket.io-adapter"),zD="emitter",Xc=5e3;function us(){return(0,GD.randomBytes)(8).toString("hex")}var Q;(function(r){r[r.INITIAL_HEARTBEAT=1]="INITIAL_HEARTBEAT",r[r.HEARTBEAT=2]="HEARTBEAT",r[r.BROADCAST=3]="BROADCAST",r[r.SOCKETS_JOIN=4]="SOCKETS_JOIN",r[r.SOCKETS_LEAVE=5]="SOCKETS_LEAVE",r[r.DISCONNECT_SOCKETS=6]="DISCONNECT_SOCKETS",r[r.FETCH_SOCKETS=7]="FETCH_SOCKETS",r[r.FETCH_SOCKETS_RESPONSE=8]="FETCH_SOCKETS_RESPONSE",r[r.SERVER_SIDE_EMIT=9]="SERVER_SIDE_EMIT",r[r.SERVER_SIDE_EMIT_RESPONSE=10]="SERVER_SIDE_EMIT_RESPONSE",r[r.BROADCAST_CLIENT_COUNT=11]="BROADCAST_CLIENT_COUNT",r[r.BROADCAST_ACK=12]="BROADCAST_ACK",r[r.ADAPTER_CLOSE=13]="ADAPTER_CLOSE"})(Q||(Dr.MessageType=Q={}));function oi(r){return{rooms:[...r.rooms],except:[...r.except],flags:r.flags}}function ls(r){return{rooms:new Set(r.rooms),except:new Set(r.except),flags:r.flags}}var Zc=class extends $D.Adapter{constructor(e){super(e),this.requests=new Map,this.ackRequests=new Map,this.uid=us()}onMessage(e,t){if(e.uid===this.uid)return we("[%s] ignore message from self",this.uid);if(e.nsp!==this.nsp.name)return we("[%s] ignore message from another namespace (%s)",this.uid,e.nsp);switch(we("[%s] new event of type %d from %s",this.uid,e.type,e.uid),e.type){case Q.BROADCAST:{if(e.data.requestId!==void 0)super.broadcastWithAck(e.data.packet,ls(e.data.opts),i=>{we("[%s] waiting for %d client acknowledgements",this.uid,i),this.publishResponse(e.uid,{type:Q.BROADCAST_CLIENT_COUNT,data:{requestId:e.data.requestId,clientCount:i}})},i=>{we("[%s] received acknowledgement with value %j",this.uid,i),this.publishResponse(e.uid,{type:Q.BROADCAST_ACK,data:{requestId:e.data.requestId,packet:i}})});else{let i=e.data.packet,s=ls(e.data.opts);this.addOffsetIfNecessary(i,s,t),super.broadcast(i,s)}break}case Q.SOCKETS_JOIN:super.addSockets(ls(e.data.opts),e.data.rooms);break;case Q.SOCKETS_LEAVE:super.delSockets(ls(e.data.opts),e.data.rooms);break;case Q.DISCONNECT_SOCKETS:super.disconnectSockets(ls(e.data.opts),e.data.close);break;case Q.FETCH_SOCKETS:{we("[%s] calling fetchSockets with opts %j",this.uid,e.data.opts),super.fetchSockets(ls(e.data.opts)).then(n=>{this.publishResponse(e.uid,{type:Q.FETCH_SOCKETS_RESPONSE,data:{requestId:e.data.requestId,sockets:n.map(i=>{let s=i.handshake,{sessionStore:o}=s,a=HD(s,["sessionStore"]);return{id:i.id,handshake:a,rooms:[...i.rooms],data:i.data}})}})});break}case Q.SERVER_SIDE_EMIT:{let n=e.data.packet;if(!(e.data.requestId!==void 0)){this.nsp._onServerSideEmit(n);return}let s=!1,o=a=>{s||(s=!0,we("[%s] calling acknowledgement with %j",this.uid,a),this.publishResponse(e.uid,{type:Q.SERVER_SIDE_EMIT_RESPONSE,data:{requestId:e.data.requestId,packet:a}}))};this.nsp._onServerSideEmit([...n,o]);break}case Q.BROADCAST_CLIENT_COUNT:case Q.BROADCAST_ACK:case Q.FETCH_SOCKETS_RESPONSE:case Q.SERVER_SIDE_EMIT_RESPONSE:this.onResponse(e);break;default:we("[%s] unknown message type: %s",this.uid,e.type)}}onResponse(e){var t,n;let i=e.data.requestId;switch(we("[%s] received response %s to request %s",this.uid,e.type,i),e.type){case Q.BROADCAST_CLIENT_COUNT:{(t=this.ackRequests.get(i))===null||t===void 0||t.clientCountCallback(e.data.clientCount);break}case Q.BROADCAST_ACK:{(n=this.ackRequests.get(i))===null||n===void 0||n.ack(e.data.packet);break}case Q.FETCH_SOCKETS_RESPONSE:{let s=this.requests.get(i);if(!s)return;s.current++,e.data.sockets.forEach(o=>s.responses.push(o)),s.current===s.expected&&(clearTimeout(s.timeout),s.resolve(s.responses),this.requests.delete(i));break}case Q.SERVER_SIDE_EMIT_RESPONSE:{let s=this.requests.get(i);if(!s)return;s.current++,s.responses.push(e.data.packet),s.current===s.expected&&(clearTimeout(s.timeout),s.resolve(null,s.responses),this.requests.delete(i));break}default:we("[%s] unknown response type: %s",this.uid,e.type)}}async broadcast(e,t){var n;if(!((n=t.flags)===null||n===void 0?void 0:n.local))try{let s=await this.publishAndReturnOffset({type:Q.BROADCAST,data:{packet:e,opts:oi(t)}});this.addOffsetIfNecessary(e,t,s)}catch(s){return we("[%s] error while broadcasting message: %s",this.uid,s.message)}super.broadcast(e,t)}addOffsetIfNecessary(e,t,n){var i;if(!this.nsp.server.opts.connectionStateRecovery)return;let s=e.type===2,o=e.id===void 0,a=((i=t.flags)===null||i===void 0?void 0:i.volatile)===void 0;s&&o&&a&&e.data.push(n)}broadcastWithAck(e,t,n,i){var s;if(!((s=t?.flags)===null||s===void 0?void 0:s.local)){let a=us();this.ackRequests.set(a,{clientCountCallback:n,ack:i}),this.publish({type:Q.BROADCAST,data:{packet:e,requestId:a,opts:oi(t)}}),setTimeout(()=>{this.ackRequests.delete(a)},t.flags.timeout)}super.broadcastWithAck(e,t,n,i)}async addSockets(e,t){var n;if(!((n=e.flags)===null||n===void 0?void 0:n.local))try{await this.publishAndReturnOffset({type:Q.SOCKETS_JOIN,data:{opts:oi(e),rooms:t}})}catch(s){we("[%s] error while publishing message: %s",this.uid,s.message)}super.addSockets(e,t)}async delSockets(e,t){var n;if(!((n=e.flags)===null||n===void 0?void 0:n.local))try{await this.publishAndReturnOffset({type:Q.SOCKETS_LEAVE,data:{opts:oi(e),rooms:t}})}catch(s){we("[%s] error while publishing message: %s",this.uid,s.message)}super.delSockets(e,t)}async disconnectSockets(e,t){var n;if(!((n=e.flags)===null||n===void 0?void 0:n.local))try{await this.publishAndReturnOffset({type:Q.DISCONNECT_SOCKETS,data:{opts:oi(e),close:t}})}catch(s){we("[%s] error while publishing message: %s",this.uid,s.message)}super.disconnectSockets(e,t)}async fetchSockets(e){var t;let[n,i]=await Promise.all([super.fetchSockets(e),this.serverCount()]),s=i-1;if(!((t=e.flags)===null||t===void 0)&&t.local||s<=0)return n;let o=us();return new Promise((a,c)=>{let l=setTimeout(()=>{let f=this.requests.get(o);f&&(c(new Error(`timeout reached: only ${f.current} responses received out of ${f.expected}`)),this.requests.delete(o))},e.flags.timeout||Xc),p={type:Q.FETCH_SOCKETS,resolve:a,timeout:l,current:0,expected:s,responses:n};this.requests.set(o,p),this.publish({type:Q.FETCH_SOCKETS,data:{opts:oi(e),requestId:o}})})}async serverSideEmit(e){if(!(typeof e[e.length-1]=="function"))return this.publish({type:Q.SERVER_SIDE_EMIT,data:{packet:e}});let n=e.pop(),i=await this.serverCount()-1;if(we('[%s] waiting for %d responses to "serverSideEmit" request',this.uid,i),i<=0)return n(null,[]);let s=us(),o=setTimeout(()=>{let c=this.requests.get(s);c&&(n(new Error(`timeout reached: only ${c.current} responses received out of ${c.expected}`),c.responses),this.requests.delete(s))},Xc),a={type:Q.SERVER_SIDE_EMIT,resolve:n,timeout:o,current:0,expected:i,responses:[]};this.requests.set(s,a),this.publish({type:Q.SERVER_SIDE_EMIT,data:{requestId:s,packet:e}})}publish(e){we("[%s] sending message %s",this.uid,e.type),this.publishAndReturnOffset(e).catch(t=>{we("[%s] error while publishing message: %s",this.uid,t)})}publishAndReturnOffset(e){return e.uid=this.uid,e.nsp=this.nsp.name,this.doPublish(e)}publishResponse(e,t){t.uid=this.uid,t.nsp=this.nsp.name,we("[%s] sending response %s to %s",this.uid,t.type,e),this.doPublishResponse(e,t).catch(n=>{we("[%s] error while publishing response: %s",this.uid,n)})}};Dr.ClusterAdapter=Zc;var Md=class extends Zc{constructor(e,t){super(e),this.nodesMap=new Map,this.customRequests=new Map,this._opts=Object.assign({heartbeatInterval:5e3,heartbeatTimeout:1e4},t),this.cleanupTimer=setInterval(()=>{let n=Date.now();this.nodesMap.forEach((i,s)=>{n-i>this._opts.heartbeatTimeout&&(we("[%s] node %s seems down",this.uid,s),this.removeNode(s))})},1e3)}init(){this.publish({type:Q.INITIAL_HEARTBEAT})}scheduleHeartbeat(){this.heartbeatTimer?this.heartbeatTimer.refresh():this.heartbeatTimer=setTimeout(()=>{this.publish({type:Q.HEARTBEAT})},this._opts.heartbeatInterval)}close(){this.publish({type:Q.ADAPTER_CLOSE}),clearTimeout(this.heartbeatTimer),this.cleanupTimer&&clearInterval(this.cleanupTimer)}onMessage(e,t){if(e.uid===this.uid)return we("[%s] ignore message from self",this.uid);switch(e.uid&&e.uid!==zD&&this.nodesMap.set(e.uid,Date.now()),e.type){case Q.INITIAL_HEARTBEAT:this.publish({type:Q.HEARTBEAT});break;case Q.HEARTBEAT:break;case Q.ADAPTER_CLOSE:this.removeNode(e.uid);break;default:super.onMessage(e,t)}}serverCount(){return Promise.resolve(1+this.nodesMap.size)}publish(e){return this.scheduleHeartbeat(),super.publish(e)}async serverSideEmit(e){if(!(typeof e[e.length-1]=="function"))return this.publish({type:Q.SERVER_SIDE_EMIT,data:{packet:e}});let n=e.pop(),i=this.nodesMap.size;if(we('[%s] waiting for %d responses to "serverSideEmit" request',this.uid,i),i<=0)return n(null,[]);let s=us(),o=setTimeout(()=>{let c=this.customRequests.get(s);c&&(n(new Error(`timeout reached: missing ${c.missingUids.size} responses`),c.responses),this.customRequests.delete(s))},Xc),a={type:Q.SERVER_SIDE_EMIT,resolve:n,timeout:o,missingUids:new Set([...this.nodesMap.keys()]),responses:[]};this.customRequests.set(s,a),this.publish({type:Q.SERVER_SIDE_EMIT,data:{requestId:s,packet:e}})}async fetchSockets(e){var t;let[n,i]=await Promise.all([super.fetchSockets({rooms:e.rooms,except:e.except,flags:{local:!0}}),this.serverCount()]),s=i-1;if(!((t=e.flags)===null||t===void 0)&&t.local||s<=0)return n;let o=us();return new Promise((a,c)=>{let l=setTimeout(()=>{let f=this.customRequests.get(o);f&&(c(new Error(`timeout reached: missing ${f.missingUids.size} responses`)),this.customRequests.delete(o))},e.flags.timeout||Xc),p={type:Q.FETCH_SOCKETS,resolve:a,timeout:l,missingUids:new Set([...this.nodesMap.keys()]),responses:n};this.customRequests.set(o,p),this.publish({type:Q.FETCH_SOCKETS,data:{opts:oi(e),requestId:o}})})}onResponse(e){let t=e.data.requestId;switch(we("[%s] received response %s to request %s",this.uid,e.type,t),e.type){case Q.FETCH_SOCKETS_RESPONSE:{let n=this.customRequests.get(t);if(!n)return;e.data.sockets.forEach(i=>n.responses.push(i)),n.missingUids.delete(e.uid),n.missingUids.size===0&&(clearTimeout(n.timeout),n.resolve(n.responses),this.customRequests.delete(t));break}case Q.SERVER_SIDE_EMIT_RESPONSE:{let n=this.customRequests.get(t);if(!n)return;n.responses.push(e.data.packet),n.missingUids.delete(e.uid),n.missingUids.size===0&&(clearTimeout(n.timeout),n.resolve(null,n.responses),this.customRequests.delete(t));break}default:super.onResponse(e)}}removeNode(e){this.customRequests.forEach((t,n)=>{t.missingUids.delete(e),t.missingUids.size===0&&(clearTimeout(t.timeout),t.type===Q.FETCH_SOCKETS?t.resolve(t.responses):t.type===Q.SERVER_SIDE_EMIT&&t.resolve(null,t.responses),this.customRequests.delete(n))}),this.nodesMap.delete(e)}};Dr.ClusterAdapterWithHeartbeat=Md});var Qc=R(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.MessageType=ar.ClusterAdapterWithHeartbeat=ar.ClusterAdapter=ar.SessionAwareAdapter=ar.Adapter=void 0;var sb=Od();Object.defineProperty(ar,"Adapter",{enumerable:!0,get:function(){return sb.Adapter}});Object.defineProperty(ar,"SessionAwareAdapter",{enumerable:!0,get:function(){return sb.SessionAwareAdapter}});var Pd=ib();Object.defineProperty(ar,"ClusterAdapter",{enumerable:!0,get:function(){return Pd.ClusterAdapter}});Object.defineProperty(ar,"ClusterAdapterWithHeartbeat",{enumerable:!0,get:function(){return Pd.ClusterAdapterWithHeartbeat}});Object.defineProperty(ar,"MessageType",{enumerable:!0,get:function(){return Pd.MessageType}})});var cb=R(ps=>{"use strict";var VD=ps&&ps.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ps,"__esModule",{value:!0});ps.ParentNamespace=void 0;var ob=sd(),KD=Qc(),YD=VD(Ce()),ab=(0,YD.default)("socket.io:parent-namespace"),el=class r extends ob.Namespace{constructor(e){super(e,"/_"+r.count++),this.children=new Set}_initAdapter(){this.adapter=new Id(this)}emit(e,...t){return this.children.forEach(n=>{n.emit(e,...t)}),!0}createChild(e){ab("creating child namespace %s",e);let t=new ob.Namespace(this.server,e);if(this._fns.forEach(n=>t.use(n)),this.listeners("connect").forEach(n=>t.on("connect",n)),this.listeners("connection").forEach(n=>t.on("connection",n)),this.children.add(t),this.server._opts.cleanupEmptyChildNamespaces){let n=t._remove;t._remove=i=>{n.call(t,i),t.sockets.size===0&&(ab("closing child namespace %s",e),t.adapter.close(),this.server._nsps.delete(t.name),this.children.delete(t))}}return this.server._nsps.set(e,t),this.server.sockets.emitReserved("new_namespace",t),t}fetchSockets(){throw new Error("fetchSockets() is not supported on parent namespaces")}};ps.ParentNamespace=el;el.count=0;var Id=class extends KD.Adapter{broadcast(e,t){this.nsp.children.forEach(n=>{n.adapter.broadcast(e,t)})}}});var hb=R(ci=>{"use strict";var JD=ci&&ci.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ci,"__esModule",{value:!0});ci.patchAdapter=ZD;ci.restoreAdapter=QD;ci.serveFile=t2;var ai=Qc(),lb=require("fs"),XD=JD(Ce()),tl=(0,XD.default)("socket.io:adapter-uws"),Nd="",{addAll:pb,del:fb,broadcast:db}=ai.Adapter.prototype;function ZD(r){ai.Adapter.prototype.addAll=function(e,t){let n=!this.sids.has(e);pb.call(this,e,t);let i=this.nsp.sockets.get(e)||this.nsp._preConnectSockets.get(e);if(i){if(i.conn.transport.name==="websocket"){ub(this.nsp.name,i,n,t);return}n&&i.conn.on("upgrade",()=>{let s=this.sids.get(e);s&&ub(this.nsp.name,i,n,s)})}},ai.Adapter.prototype.del=function(e,t){fb.call(this,e,t);let n=this.nsp.sockets.get(e)||this.nsp._preConnectSockets.get(e);if(n&&n.conn.transport.name==="websocket"){let i=n.conn.id,s=n.conn.transport.socket,o=`${this.nsp.name}${Nd}${t}`;tl("unsubscribe connection %s from topic %s",i,o),s.unsubscribe(o)}},ai.Adapter.prototype.broadcast=function(e,t){if(!(t.rooms.size<=1&&t.except.size===0)){db.call(this,e,t);return}let i=t.flags||{},s={preEncoded:!0,volatile:i.volatile,compress:i.compress};e.nsp=this.nsp.name;let o=this.encoder.encode(e),a=t.rooms.size===0?this.nsp.name:`${this.nsp.name}${Nd}${t.rooms.keys().next().value}`;tl("fast publish to %s",a),o.forEach(c=>{let l=typeof c!="string";r.publish(a,l?c:"4"+c,l)}),this.apply(t,c=>{c.conn.transport.name!=="websocket"&&c.client.writeToEngine(o,s)})}}function ub(r,e,t,n){let i=e.conn.id,s=e.conn.transport.socket;t&&(tl("subscribe connection %s to topic %s",i,r),s.subscribe(r)),n.forEach(o=>{let a=`${r}${Nd}${o}`;tl("subscribe connection %s to topic %s",i,a),s.subscribe(a)})}function QD(){ai.Adapter.prototype.addAll=pb,ai.Adapter.prototype.del=fb,ai.Adapter.prototype.broadcast=db}var e2=r=>{let{buffer:e,byteOffset:t,byteLength:n}=r;return e.slice(t,t+n)};function t2(r,e){let{size:t}=(0,lb.statSync)(e),n=(0,lb.createReadStream)(e),i=()=>!n.destroyed&&n.destroy(),s=a=>{throw i(),a},o=a=>{let c=e2(a);r.cork(()=>{let l=r.getWriteOffset(),[p,f]=r.tryEnd(c,t);!f&&!p&&(n.pause(),r.onWritable(h=>{let[v,x]=r.tryEnd(c.slice(h-l),t);return!x&&v&&n.resume(),v}))})};r.onAborted(i),n.on("data",o).on("error",s).on("end",i)}});var mb=R((y6,r2)=>{r2.exports={name:"socket.io",version:"4.8.3",description:"node.js realtime framework server",keywords:["realtime","framework","websocket","tcp","events","socket","io"],files:["dist/","client-dist/","wrapper.mjs","!**/*.tsbuildinfo"],directories:{doc:"docs/",example:"example/",lib:"lib/",test:"test/"},type:"commonjs",main:"./dist/index.js",exports:{".":{types:"./dist/index.d.ts",import:"./wrapper.mjs",require:"./dist/index.js"},"./package.json":"./package.json"},types:"./dist/index.d.ts",license:"MIT",homepage:"https://github.com/socketio/socket.io/tree/main/packages/socket.io#readme",repository:{type:"git",url:"git+https://github.com/socketio/socket.io.git"},bugs:{url:"https://github.com/socketio/socket.io/issues"},scripts:{compile:"rimraf ./dist && tsc",test:"npm run format:check && npm run compile && npm run test:types && npm run test:unit","test:types":"tsd","test:unit":"nyc mocha --import=tsx --reporter spec --slow 200 --bail --timeout 10000 test/index.ts","format:check":'prettier --check "lib/**/*.ts" "test/**/*.ts"',"format:fix":'prettier --write "lib/**/*.ts" "test/**/*.ts"',prepack:"npm run compile"},dependencies:{accepts:"~1.3.4",base64id:"~2.0.0",cors:"~2.8.5",debug:"~4.4.1","engine.io":"~6.6.0","socket.io-adapter":"~2.5.2","socket.io-parser":"~4.2.4"},contributors:[{name:"Guillermo Rauch",email:"rauchg@gmail.com"},{name:"Arnout Kazemier",email:"info@3rd-eden.com"},{name:"Vladimir Dronnikov",email:"dronnikov@gmail.com"},{name:"Einar Otto Stangvik",email:"einaros@gmail.com"}],engines:{node:">=10.2.0"},tsd:{directory:"test"}}});var Sb=R((xt,ko)=>{"use strict";var n2=xt&&xt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),i2=xt&&xt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),s2=xt&&xt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&n2(e,r,t);return i2(e,r),e},Bd=xt&&xt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(xt,"__esModule",{value:!0});xt.Namespace=xt.Socket=xt.Server=void 0;var o2=Bd(require("http")),a2=require("fs"),Ld=require("zlib"),c2=$a(),rl=require("stream"),gb=require("path"),vb=Px(),l2=Hx(),yb=require("events"),jd=sd();Object.defineProperty(xt,"Namespace",{enumerable:!0,get:function(){return jd.Namespace}});var u2=cb(),xb=Qc(),p2=s2(xo()),f2=Bd(Ce()),wb=nd();Object.defineProperty(xt,"Socket",{enumerable:!0,get:function(){return wb.Socket}});var d2=Mc(),Dd=hb(),h2=Bd(Bf()),At=(0,f2.default)("socket.io:server"),_b=mb().version,bb=/\.map/,fs=class r extends d2.StrictEventEmitter{constructor(e,t={}){super(),this._nsps=new Map,this.parentNsps=new Map,this.parentNamespacesFromRegExp=new Map,typeof e=="object"&&e instanceof Object&&!e.listen&&(t=e,e=void 0),this.path(t.path||"/socket.io"),this.connectTimeout(t.connectTimeout||45e3),this.serveClient(t.serveClient!==!1),this._parser=t.parser||p2,this.encoder=new this._parser.Encoder,this.opts=t,t.connectionStateRecovery?(t.connectionStateRecovery=Object.assign({maxDisconnectionDuration:120*1e3,skipMiddlewares:!0},t.connectionStateRecovery),this.adapter(t.adapter||xb.SessionAwareAdapter)):this.adapter(t.adapter||xb.Adapter),t.cleanupEmptyChildNamespaces=!!t.cleanupEmptyChildNamespaces,this.sockets=this.of("/"),(e||typeof e=="number")&&this.attach(e),this.opts.cors&&(this._corsMiddleware=(0,h2.default)(this.opts.cors))}get _opts(){return this.opts}serveClient(e){return arguments.length?(this._serveClient=e,this):this._serveClient}_checkNamespace(e,t,n){if(this.parentNsps.size===0)return n(!1);let i=this.parentNsps.keys(),s=()=>{let o=i.next();if(o.done)return n(!1);o.value(e,t,(a,c)=>{if(a||!c)return s();if(this._nsps.has(e))return At("dynamic namespace %s already exists",e),n(this._nsps.get(e));let l=this.parentNsps.get(o.value).createChild(e);At("dynamic namespace %s was created",e),n(l)})};s()}path(e){if(!arguments.length)return this._path;this._path=e.replace(/\/$/,"");let t=this._path.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");return this.clientPathRegex=new RegExp("^"+t+"/socket\\.io(\\.msgpack|\\.esm)?(\\.min)?\\.js(\\.map)?(?:\\?|$)"),this}connectTimeout(e){return e===void 0?this._connectTimeout:(this._connectTimeout=e,this)}adapter(e){if(!arguments.length)return this._adapter;this._adapter=e;for(let t of this._nsps.values())t._initAdapter();return this}listen(e,t={}){return this.attach(e,t)}attach(e,t={}){if(typeof e=="function"){let n="You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.";throw new Error(n)}if(Number(e)==e&&(e=Number(e)),typeof e=="number"){At("creating http server and binding to %d",e);let n=e;e=o2.default.createServer((i,s)=>{s.writeHead(404),s.end()}),e.listen(n)}return Object.assign(t,this.opts),t.path=t.path||this._path,this.initEngine(e,t),this}attachApp(e,t={}){Object.assign(t,this.opts),t.path=t.path||this._path,At("creating uWebSockets.js-based engine with opts %j",t);let n=new vb.uServer(t);n.attach(e,t),this.bind(n),this._serveClient&&e.get(`${this._path}/*`,(i,s)=>{if(!this.clientPathRegex.test(s.getUrl())){s.setYield(!0);return}let o=s.getUrl().replace(this._path,"").replace(/\?.*$/,"").replace(/^\//,""),a=bb.test(o),c=a?"map":"source",l='"'+_b+'"',p="W/"+l,f=s.getHeader("if-none-match");if(f&&(l===f||p===f)){At("serve client %s 304",c),i.writeStatus("304 Not Modified"),i.end();return}At("serve client %s",c),i.writeHeader("cache-control","public, max-age=0"),i.writeHeader("content-type","application/"+(a?"json":"javascript")+"; charset=utf-8"),i.writeHeader("etag",l);let h=gb.join(__dirname,"../client-dist/",o);(0,Dd.serveFile)(i,h)}),(0,Dd.patchAdapter)(e)}initEngine(e,t){At("creating engine.io instance with opts %j",t),this.eio=(0,vb.attach)(e,t),this._serveClient&&this.attachServe(e),this.httpServer=e,this.bind(this.eio)}attachServe(e){At("attaching client serving req handler");let t=e.listeners("request").slice(0);e.removeAllListeners("request"),e.on("request",(n,i)=>{if(this.clientPathRegex.test(n.url))this._corsMiddleware?this._corsMiddleware(n,i,()=>{this.serve(n,i)}):this.serve(n,i);else for(let s=0;s<t.length;s++)t[s].call(e,n,i)})}serve(e,t){let n=e.url.replace(this._path,"").replace(/\?.*$/,""),i=bb.test(n),s=i?"map":"source",o='"'+_b+'"',a="W/"+o,c=e.headers["if-none-match"];if(c&&(o===c||a===c)){At("serve client %s 304",s),t.writeHead(304),t.end();return}At("serve client %s",s),t.setHeader("Cache-Control","public, max-age=0"),t.setHeader("Content-Type","application/"+(i?"json":"javascript")+"; charset=utf-8"),t.setHeader("ETag",o),r.sendFile(n,e,t)}static sendFile(e,t,n){let i=(0,a2.createReadStream)(gb.join(__dirname,"../client-dist/",e)),s=c2(t).encodings(["br","gzip","deflate"]),o=a=>{a&&n.end()};switch(s){case"br":n.writeHead(200,{"content-encoding":"br"}),(0,rl.pipeline)(i,(0,Ld.createBrotliCompress)(),n,o);break;case"gzip":n.writeHead(200,{"content-encoding":"gzip"}),(0,rl.pipeline)(i,(0,Ld.createGzip)(),n,o);break;case"deflate":n.writeHead(200,{"content-encoding":"deflate"}),(0,rl.pipeline)(i,(0,Ld.createDeflate)(),n,o);break;default:n.writeHead(200),(0,rl.pipeline)(i,n,o)}}bind(e){return this.engine=e,this.engine.on("connection",this.onconnection.bind(this)),this}onconnection(e){At("incoming connection with id %s",e.id);let t=new l2.Client(this,e);return e.protocol===3&&t.connect("/"),this}of(e,t){if(typeof e=="function"||e instanceof RegExp){let i=new u2.ParentNamespace(this);return At("initializing parent namespace %s",i.name),typeof e=="function"?this.parentNsps.set(e,i):(this.parentNsps.set((s,o,a)=>a(null,e.test(s)),i),this.parentNamespacesFromRegExp.set(e,i)),t&&i.on("connect",t),i}String(e)[0]!=="/"&&(e="/"+e);let n=this._nsps.get(e);if(!n){for(let[i,s]of this.parentNamespacesFromRegExp)if(i.test(e))return At("attaching namespace %s to parent namespace %s",e,i),s.createChild(e);At("initializing namespace %s",e),n=new jd.Namespace(this,e),this._nsps.set(e,n),e!=="/"&&this.sockets.emitReserved("new_namespace",n)}return t&&n.on("connect",t),n}async close(e){if(await Promise.allSettled([...this._nsps.values()].map(async t=>{t.sockets.forEach(n=>{n._onclose("server shutting down")}),await t.adapter.close()})),this.engine.close(),(0,Dd.restoreAdapter)(),this.httpServer)return new Promise(t=>{this.httpServer.close(n=>{e&&e(n),n&&At("server was not running"),t()})});e&&e()}use(e){return this.sockets.use(e),this}to(e){return this.sockets.to(e)}in(e){return this.sockets.in(e)}except(e){return this.sockets.except(e)}send(...e){return this.sockets.emit("message",...e),this}write(...e){return this.sockets.emit("message",...e),this}serverSideEmit(e,...t){return this.sockets.serverSideEmit(e,...t)}serverSideEmitWithAck(e,...t){return this.sockets.serverSideEmitWithAck(e,...t)}allSockets(){return this.sockets.allSockets()}compress(e){return this.sockets.compress(e)}get volatile(){return this.sockets.volatile}get local(){return this.sockets.local}timeout(e){return this.sockets.timeout(e)}fetchSockets(){return this.sockets.fetchSockets()}socketsJoin(e){return this.sockets.socketsJoin(e)}socketsLeave(e){return this.sockets.socketsLeave(e)}disconnectSockets(e=!1){return this.sockets.disconnectSockets(e)}};xt.Server=fs;var m2=Object.keys(yb.EventEmitter.prototype).filter(function(r){return typeof yb.EventEmitter.prototype[r]=="function"});m2.forEach(function(r){fs.prototype[r]=function(){return this.sockets[r].apply(this.sockets,arguments)}});ko.exports=(r,e)=>new fs(r,e);ko.exports.Server=fs;ko.exports.Namespace=jd.Namespace;ko.exports.Socket=wb.Socket});function Fd(){return Oo=(0,Cb.randomBytes)(32).toString("hex"),Oo}function Ab(){return Oo||Fd(),Oo}function Rb(r){return!!r&&typeof r=="string"&&r===Oo}var Cb,Oo,nl=Ee(()=>{Cb=require("crypto"),Oo=null});var Ob,il,$,ot=Ee(()=>{Ob={darwin:{capture:"robotjs",encoder:"sharp",tileSize:128,inputFormat:"bgra"},win32:{capture:"nodeScreenshots",encoder:"sharp",tileSize:256,inputFormat:"rgba"},linux:{capture:"nodeScreenshots",encoder:"sharp",tileSize:256,inputFormat:"rgba"}},il=Ob[process.platform]||Ob.linux,$={pipeline:{captureLib:il.capture,encoder:il.encoder,inputFormat:il.inputFormat,tileSize:il.tileSize,tileFormat:"webp",webpEffort:0,jpegQuality:50,tileConcurrency:6,outputScale:1,adaptiveTiers:[{minEffective:1,outputScale:1,jpegQuality:72},{minEffective:.7,outputScale:.95,jpegQuality:62},{minEffective:.4,outputScale:.8,jpegQuality:52},{minEffective:0,outputScale:.65,jpegQuality:45}],tierHysteresis:.05,checksumSampling:{rowStep:3,colStep:8}},webrtc:{enableWebRTC:!0,enableTurn:!1,turnApiUrl:"https://9remote.cc/api/webrtc/turn-credentials",turnRefreshInterval:1380*60*1e3,dcMaxMessageSize:65536,dcBufferThreshold:65536,iceDisconnectGraceMs:6e3,dcChunkSize:8,dcMaxTilesPerFrame:32,dcReliable:!0,dcOrdered:!1,answerTimeout:1e4,maxControlBuffer:500},robotSettings:{mouseDelay:2,keyboardDelay:2},throttling:{mouseThrottle:8,keyThrottle:25,typeTextThrottle:100,maxTextLength:1e3},resourceManagement:{inactiveTimeout:120*1e3,memoryCheckInterval:6e4,memoryWarningThreshold:1e3,maxTimersPerClient:100,maxChunkTimersPerClient:50,disconnectGraceMs:3e4},streaming:{activeInterval:60,idleInterval:400,idleThreshold:3,actionCaptureDelay:50,chunkSize:32,chunkDelay:5,wsVolatileTiles:!0},focus:{paddingTiles:4},displayWake:{enabled:!0,throttleMs:3e4,macDurationSec:5},sleepInhibit:{defaultMode:"never",presets:{"30m":1800*1e3,"1h":3600*1e3,"2h":7200*1e3,"4h":14400*1e3,"24h":1440*60*1e3,never:null}},desktopSwitch:{darwin:{prev:{keyCode:123,mods:"control down"},next:{keyCode:124,mods:"control down"},new:{type:"missionControl"}},win32:{prev:["left",["control","command"]],next:["right",["control","command"]],new:["d",["control","command"]]},linux:{prev:null,next:null,new:null}},logging:{lifecycle:!1,errors:!0,dpiDetection:!1,focus:!1,focusEveryFrames:60,metrics:!1,metricsEveryFrames:30,webrtc:!1}}});var Mo,Po,me,qd=Ee(()=>{ot();Ii();Mo=()=>$.logging,Po=Tn("remote"),me={lifecycle:r=>{Mo().lifecycle&&Po.info(r)},focus:r=>{Mo().focus&&Po.info(r)},dpi:r=>{Mo().dpiDetection&&Po.info(r)},error:(r,e)=>{Mo().errors&&Po.error(`${r} ${e?.message||e||""}`)},warn:r=>{Mo().errors&&Po.warn(r)}}});function No(){for(let r of[ie.ROOT,ie.STATE])Br.default.existsSync(r)||Br.default.mkdirSync(r,{recursive:!0})}function Wd(){try{return No(),Br.default.existsSync($d)?JSON.parse(Br.default.readFileSync($d,"utf8"))||{}:{}}catch{return{}}}function Fb(r){try{No();let e={...Wd(),...r};return Br.default.writeFileSync($d,JSON.stringify(e,null,2),{mode:384}),e}catch(e){return console.error("Error saving settings:",e),null}}function Ub(){try{return No(),Br.default.existsSync(Hd)?JSON.parse(Br.default.readFileSync(Hd,"utf8")):{machineId:null,key:null,name:"Default",createdAt:null}}catch{return{machineId:null,key:null,name:"Default",createdAt:null}}}function Dn(r){try{No(),Br.default.writeFileSync(E2,JSON.stringify({cmd:r,ts:Date.now()}))}catch{}}function qb(r,e,t="Default"){try{No();let n={machineId:r,key:e,name:t,createdAt:new Date().toISOString()};return Br.default.writeFileSync(Hd,JSON.stringify(n,null,2),{mode:384}),n}catch(n){return console.error("Error saving key:",n),null}}var Br,Io,W6,G6,Hd,E2,$d,hs=Ee(()=>{Br=K(require("fs"),1),Io=K(require("path"),1);vt();W6=ie.STATE,G6=Io.default.join(ie.STATE,"state.json"),Hd=Io.default.join(ie.ROOT,"keys.json"),E2=Io.default.join(ie.STATE,"cmd.json"),$d=Io.default.join(ie.STATE,"settings.json")});function Hb(){return new Promise(r=>{if(process.platform!=="darwin"){r({screenRecording:!0,accessibility:!0});return}let e=!1,t=!1,n=0,i=()=>{++n===2&&r({screenRecording:e,accessibility:t})};(0,Lo.execFile)("osascript",["-e",'use framework "ApplicationServices"',"-e",`set checkOptions to current application's NSDictionary's dictionaryWithObject:(false) forKey:("AXTrustedCheckOptionPrompt" as string)`,"-e","return current application's AXIsProcessTrustedWithOptions(checkOptions) as boolean"],{timeout:3e3},(s,o)=>{t=!s&&o.trim()==="true",i()}),(0,Lo.exec)(`osascript -e 'use framework "CoreGraphics"' -e "return (current application's CGPreflightScreenCaptureAccess()) as boolean"`,{timeout:3e3},(s,o)=>{e=!s&&o.trim()==="true",i()})})}function $b(r){let e=T2[r];e&&process.platform==="darwin"&&(0,Lo.exec)(`open "${e}"`,()=>{})}var Lo,T2,Wb=Ee(()=>{Lo=require("child_process"),T2={screenRecording:"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",accessibility:"x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"}});function C2(){return!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY}function Fo(){for(let r=Gb,e=null;r!==e;e=r,r=jr.default.dirname(r)){let t=jr.default.join(r,"package.json");if((0,Se.existsSync)(t)){try{let n=JSON.parse((0,Se.readFileSync)(t,"utf8"));if(n.name!==Pi)continue;let i=typeof n.bin=="string"?n.bin:n.bin?.[Pi];if(i){let s=jr.default.resolve(r,i);if((0,Se.existsSync)(s))return s}}catch{}break}}return process.argv[1]||jr.default.resolve(Gb,"..","index.js")}function vs(){return process.execPath}function Kb(){let r=jr.default.dirname(vs()),e=["/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin","/opt/homebrew/bin"];return e.includes(r)||e.unshift(r),e.join(":")}function Gd(r){return String(r).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function A2(r,e){let t=[r,e,...ll].map(n=>` <string>${Gd(n)}</string>`).join(`
29
+ `+t)}function si(r,e,t,n,i,s){if(r.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,si),r.emit("wsClientError",o,t,e)}else Ro(t,n,i,s)}});var nb=R((f6,rb)=>{"use strict";var cn=Vc();cn.createWebSocketStream=z_();cn.Server=tb();cn.Receiver=vd();cn.Sender=_d();cn.WebSocket=cn;cn.WebSocketServer=cn.Server;rb.exports=cn});var Od=R(cs=>{"use strict";var Rd;Object.defineProperty(cs,"__esModule",{value:!0});cs.SessionAwareAdapter=cs.Adapter=void 0;var jD=require("events"),FD=Xx(),Yc=nb(),UD=typeof((Rd=Yc?.Sender)===null||Rd===void 0?void 0:Rd.frame)=="function",Jc=class extends jD.EventEmitter{constructor(e){super(),this.nsp=e,this.rooms=new Map,this.sids=new Map,this.encoder=e.server.encoder}init(){}close(){}serverCount(){return Promise.resolve(1)}addAll(e,t){this.sids.has(e)||this.sids.set(e,new Set);for(let n of t)this.sids.get(e).add(n),this.rooms.has(n)||(this.rooms.set(n,new Set),this.emit("create-room",n)),this.rooms.get(n).has(e)||(this.rooms.get(n).add(e),this.emit("join-room",n,e))}del(e,t){this.sids.has(e)&&this.sids.get(e).delete(t),this._del(t,e)}_del(e,t){let n=this.rooms.get(e);n!=null&&(n.delete(t)&&this.emit("leave-room",e,t),n.size===0&&this.rooms.delete(e)&&this.emit("delete-room",e))}delAll(e){if(this.sids.has(e)){for(let t of this.sids.get(e))this._del(t,e);this.sids.delete(e)}}broadcast(e,t){let n=t.flags||{},i={preEncoded:!0,volatile:n.volatile,compress:n.compress};e.nsp=this.nsp.name;let s=this._encode(e,i);this.apply(t,o=>{typeof o.notifyOutgoingListeners=="function"&&o.notifyOutgoingListeners(e),o.client.writeToEngine(s,i)})}broadcastWithAck(e,t,n,i){let s=t.flags||{},o={preEncoded:!0,volatile:s.volatile,compress:s.compress};e.nsp=this.nsp.name,e.id=this.nsp._ids++;let a=this._encode(e,o),c=0;this.apply(t,l=>{c++,l.acks.set(e.id,i),typeof l.notifyOutgoingListeners=="function"&&l.notifyOutgoingListeners(e),l.client.writeToEngine(a,o)}),n(c)}_encode(e,t){let n=this.encoder.encode(e);if(UD&&n.length===1&&typeof n[0]=="string"){let i=Buffer.from("4"+n[0]);t.wsPreEncodedFrame=Yc.Sender.frame(i,{readOnly:!1,mask:!1,rsv1:!1,opcode:1,fin:!0})}return n}sockets(e){let t=new Set;return this.apply({rooms:e},n=>{t.add(n.id)}),Promise.resolve(t)}socketRooms(e){return this.sids.get(e)}fetchSockets(e){let t=[];return this.apply(e,n=>{t.push(n)}),Promise.resolve(t)}addSockets(e,t){this.apply(e,n=>{n.join(t)})}delSockets(e,t){this.apply(e,n=>{t.forEach(i=>n.leave(i))})}disconnectSockets(e,t){this.apply(e,n=>{n.disconnect(t)})}apply(e,t){let n=e.rooms,i=this.computeExceptSids(e.except);if(n.size){let s=new Set;for(let o of n)if(this.rooms.has(o))for(let a of this.rooms.get(o)){if(s.has(a)||i.has(a))continue;let c=this.nsp.sockets.get(a);c&&(t(c),s.add(a))}}else for(let[s]of this.sids){if(i.has(s))continue;let o=this.nsp.sockets.get(s);o&&t(o)}}computeExceptSids(e){let t=new Set;if(e&&e.size>0)for(let n of e)this.rooms.has(n)&&this.rooms.get(n).forEach(i=>t.add(i));return t}serverSideEmit(e){console.warn("this adapter does not support the serverSideEmit() functionality")}persistSession(e){}restoreSession(e,t){return null}};cs.Adapter=Jc;var kd=class extends Jc{constructor(e){super(e),this.nsp=e,this.sessions=new Map,this.packets=[],this.maxDisconnectionDuration=e.server.opts.connectionStateRecovery.maxDisconnectionDuration,setInterval(()=>{let n=Date.now()-this.maxDisconnectionDuration;this.sessions.forEach((i,s)=>{i.disconnectedAt<n&&this.sessions.delete(s)});for(let i=this.packets.length-1;i>=0;i--)if(this.packets[i].emittedAt<n){this.packets.splice(0,i+1);break}},60*1e3).unref()}persistSession(e){e.disconnectedAt=Date.now(),this.sessions.set(e.pid,e)}restoreSession(e,t){let n=this.sessions.get(e);if(!n)return null;if(n.disconnectedAt+this.maxDisconnectionDuration<Date.now())return this.sessions.delete(e),null;let s=this.packets.findIndex(a=>a.id===t);if(s===-1)return null;let o=[];for(let a=s+1;a<this.packets.length;a++){let c=this.packets[a];qD(n.rooms,c.opts)&&o.push(c.data)}return Promise.resolve(Object.assign(Object.assign({},n),{missedPackets:o}))}broadcast(e,t){var n;let i=e.type===2,s=e.id===void 0,o=((n=t.flags)===null||n===void 0?void 0:n.volatile)===void 0;if(i&&s&&o){let a=(0,FD.yeast)();e.data.push(a),this.packets.push({id:a,opts:t,data:e.data,emittedAt:Date.now()})}super.broadcast(e,t)}};cs.SessionAwareAdapter=kd;function qD(r,e){let t=e.rooms.size===0||r.some(i=>e.rooms.has(i)),n=r.every(i=>!e.except.has(i));return t&&n}});var ib=R(Dr=>{"use strict";var HD=Dr&&Dr.__rest||function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t};Object.defineProperty(Dr,"__esModule",{value:!0});Dr.ClusterAdapterWithHeartbeat=Dr.ClusterAdapter=Dr.MessageType=void 0;var $D=Od(),WD=Ce(),GD=require("crypto"),we=(0,WD.debug)("socket.io-adapter"),zD="emitter",Xc=5e3;function us(){return(0,GD.randomBytes)(8).toString("hex")}var Q;(function(r){r[r.INITIAL_HEARTBEAT=1]="INITIAL_HEARTBEAT",r[r.HEARTBEAT=2]="HEARTBEAT",r[r.BROADCAST=3]="BROADCAST",r[r.SOCKETS_JOIN=4]="SOCKETS_JOIN",r[r.SOCKETS_LEAVE=5]="SOCKETS_LEAVE",r[r.DISCONNECT_SOCKETS=6]="DISCONNECT_SOCKETS",r[r.FETCH_SOCKETS=7]="FETCH_SOCKETS",r[r.FETCH_SOCKETS_RESPONSE=8]="FETCH_SOCKETS_RESPONSE",r[r.SERVER_SIDE_EMIT=9]="SERVER_SIDE_EMIT",r[r.SERVER_SIDE_EMIT_RESPONSE=10]="SERVER_SIDE_EMIT_RESPONSE",r[r.BROADCAST_CLIENT_COUNT=11]="BROADCAST_CLIENT_COUNT",r[r.BROADCAST_ACK=12]="BROADCAST_ACK",r[r.ADAPTER_CLOSE=13]="ADAPTER_CLOSE"})(Q||(Dr.MessageType=Q={}));function oi(r){return{rooms:[...r.rooms],except:[...r.except],flags:r.flags}}function ls(r){return{rooms:new Set(r.rooms),except:new Set(r.except),flags:r.flags}}var Zc=class extends $D.Adapter{constructor(e){super(e),this.requests=new Map,this.ackRequests=new Map,this.uid=us()}onMessage(e,t){if(e.uid===this.uid)return we("[%s] ignore message from self",this.uid);if(e.nsp!==this.nsp.name)return we("[%s] ignore message from another namespace (%s)",this.uid,e.nsp);switch(we("[%s] new event of type %d from %s",this.uid,e.type,e.uid),e.type){case Q.BROADCAST:{if(e.data.requestId!==void 0)super.broadcastWithAck(e.data.packet,ls(e.data.opts),i=>{we("[%s] waiting for %d client acknowledgements",this.uid,i),this.publishResponse(e.uid,{type:Q.BROADCAST_CLIENT_COUNT,data:{requestId:e.data.requestId,clientCount:i}})},i=>{we("[%s] received acknowledgement with value %j",this.uid,i),this.publishResponse(e.uid,{type:Q.BROADCAST_ACK,data:{requestId:e.data.requestId,packet:i}})});else{let i=e.data.packet,s=ls(e.data.opts);this.addOffsetIfNecessary(i,s,t),super.broadcast(i,s)}break}case Q.SOCKETS_JOIN:super.addSockets(ls(e.data.opts),e.data.rooms);break;case Q.SOCKETS_LEAVE:super.delSockets(ls(e.data.opts),e.data.rooms);break;case Q.DISCONNECT_SOCKETS:super.disconnectSockets(ls(e.data.opts),e.data.close);break;case Q.FETCH_SOCKETS:{we("[%s] calling fetchSockets with opts %j",this.uid,e.data.opts),super.fetchSockets(ls(e.data.opts)).then(n=>{this.publishResponse(e.uid,{type:Q.FETCH_SOCKETS_RESPONSE,data:{requestId:e.data.requestId,sockets:n.map(i=>{let s=i.handshake,{sessionStore:o}=s,a=HD(s,["sessionStore"]);return{id:i.id,handshake:a,rooms:[...i.rooms],data:i.data}})}})});break}case Q.SERVER_SIDE_EMIT:{let n=e.data.packet;if(!(e.data.requestId!==void 0)){this.nsp._onServerSideEmit(n);return}let s=!1,o=a=>{s||(s=!0,we("[%s] calling acknowledgement with %j",this.uid,a),this.publishResponse(e.uid,{type:Q.SERVER_SIDE_EMIT_RESPONSE,data:{requestId:e.data.requestId,packet:a}}))};this.nsp._onServerSideEmit([...n,o]);break}case Q.BROADCAST_CLIENT_COUNT:case Q.BROADCAST_ACK:case Q.FETCH_SOCKETS_RESPONSE:case Q.SERVER_SIDE_EMIT_RESPONSE:this.onResponse(e);break;default:we("[%s] unknown message type: %s",this.uid,e.type)}}onResponse(e){var t,n;let i=e.data.requestId;switch(we("[%s] received response %s to request %s",this.uid,e.type,i),e.type){case Q.BROADCAST_CLIENT_COUNT:{(t=this.ackRequests.get(i))===null||t===void 0||t.clientCountCallback(e.data.clientCount);break}case Q.BROADCAST_ACK:{(n=this.ackRequests.get(i))===null||n===void 0||n.ack(e.data.packet);break}case Q.FETCH_SOCKETS_RESPONSE:{let s=this.requests.get(i);if(!s)return;s.current++,e.data.sockets.forEach(o=>s.responses.push(o)),s.current===s.expected&&(clearTimeout(s.timeout),s.resolve(s.responses),this.requests.delete(i));break}case Q.SERVER_SIDE_EMIT_RESPONSE:{let s=this.requests.get(i);if(!s)return;s.current++,s.responses.push(e.data.packet),s.current===s.expected&&(clearTimeout(s.timeout),s.resolve(null,s.responses),this.requests.delete(i));break}default:we("[%s] unknown response type: %s",this.uid,e.type)}}async broadcast(e,t){var n;if(!((n=t.flags)===null||n===void 0?void 0:n.local))try{let s=await this.publishAndReturnOffset({type:Q.BROADCAST,data:{packet:e,opts:oi(t)}});this.addOffsetIfNecessary(e,t,s)}catch(s){return we("[%s] error while broadcasting message: %s",this.uid,s.message)}super.broadcast(e,t)}addOffsetIfNecessary(e,t,n){var i;if(!this.nsp.server.opts.connectionStateRecovery)return;let s=e.type===2,o=e.id===void 0,a=((i=t.flags)===null||i===void 0?void 0:i.volatile)===void 0;s&&o&&a&&e.data.push(n)}broadcastWithAck(e,t,n,i){var s;if(!((s=t?.flags)===null||s===void 0?void 0:s.local)){let a=us();this.ackRequests.set(a,{clientCountCallback:n,ack:i}),this.publish({type:Q.BROADCAST,data:{packet:e,requestId:a,opts:oi(t)}}),setTimeout(()=>{this.ackRequests.delete(a)},t.flags.timeout)}super.broadcastWithAck(e,t,n,i)}async addSockets(e,t){var n;if(!((n=e.flags)===null||n===void 0?void 0:n.local))try{await this.publishAndReturnOffset({type:Q.SOCKETS_JOIN,data:{opts:oi(e),rooms:t}})}catch(s){we("[%s] error while publishing message: %s",this.uid,s.message)}super.addSockets(e,t)}async delSockets(e,t){var n;if(!((n=e.flags)===null||n===void 0?void 0:n.local))try{await this.publishAndReturnOffset({type:Q.SOCKETS_LEAVE,data:{opts:oi(e),rooms:t}})}catch(s){we("[%s] error while publishing message: %s",this.uid,s.message)}super.delSockets(e,t)}async disconnectSockets(e,t){var n;if(!((n=e.flags)===null||n===void 0?void 0:n.local))try{await this.publishAndReturnOffset({type:Q.DISCONNECT_SOCKETS,data:{opts:oi(e),close:t}})}catch(s){we("[%s] error while publishing message: %s",this.uid,s.message)}super.disconnectSockets(e,t)}async fetchSockets(e){var t;let[n,i]=await Promise.all([super.fetchSockets(e),this.serverCount()]),s=i-1;if(!((t=e.flags)===null||t===void 0)&&t.local||s<=0)return n;let o=us();return new Promise((a,c)=>{let l=setTimeout(()=>{let f=this.requests.get(o);f&&(c(new Error(`timeout reached: only ${f.current} responses received out of ${f.expected}`)),this.requests.delete(o))},e.flags.timeout||Xc),p={type:Q.FETCH_SOCKETS,resolve:a,timeout:l,current:0,expected:s,responses:n};this.requests.set(o,p),this.publish({type:Q.FETCH_SOCKETS,data:{opts:oi(e),requestId:o}})})}async serverSideEmit(e){if(!(typeof e[e.length-1]=="function"))return this.publish({type:Q.SERVER_SIDE_EMIT,data:{packet:e}});let n=e.pop(),i=await this.serverCount()-1;if(we('[%s] waiting for %d responses to "serverSideEmit" request',this.uid,i),i<=0)return n(null,[]);let s=us(),o=setTimeout(()=>{let c=this.requests.get(s);c&&(n(new Error(`timeout reached: only ${c.current} responses received out of ${c.expected}`),c.responses),this.requests.delete(s))},Xc),a={type:Q.SERVER_SIDE_EMIT,resolve:n,timeout:o,current:0,expected:i,responses:[]};this.requests.set(s,a),this.publish({type:Q.SERVER_SIDE_EMIT,data:{requestId:s,packet:e}})}publish(e){we("[%s] sending message %s",this.uid,e.type),this.publishAndReturnOffset(e).catch(t=>{we("[%s] error while publishing message: %s",this.uid,t)})}publishAndReturnOffset(e){return e.uid=this.uid,e.nsp=this.nsp.name,this.doPublish(e)}publishResponse(e,t){t.uid=this.uid,t.nsp=this.nsp.name,we("[%s] sending response %s to %s",this.uid,t.type,e),this.doPublishResponse(e,t).catch(n=>{we("[%s] error while publishing response: %s",this.uid,n)})}};Dr.ClusterAdapter=Zc;var Md=class extends Zc{constructor(e,t){super(e),this.nodesMap=new Map,this.customRequests=new Map,this._opts=Object.assign({heartbeatInterval:5e3,heartbeatTimeout:1e4},t),this.cleanupTimer=setInterval(()=>{let n=Date.now();this.nodesMap.forEach((i,s)=>{n-i>this._opts.heartbeatTimeout&&(we("[%s] node %s seems down",this.uid,s),this.removeNode(s))})},1e3)}init(){this.publish({type:Q.INITIAL_HEARTBEAT})}scheduleHeartbeat(){this.heartbeatTimer?this.heartbeatTimer.refresh():this.heartbeatTimer=setTimeout(()=>{this.publish({type:Q.HEARTBEAT})},this._opts.heartbeatInterval)}close(){this.publish({type:Q.ADAPTER_CLOSE}),clearTimeout(this.heartbeatTimer),this.cleanupTimer&&clearInterval(this.cleanupTimer)}onMessage(e,t){if(e.uid===this.uid)return we("[%s] ignore message from self",this.uid);switch(e.uid&&e.uid!==zD&&this.nodesMap.set(e.uid,Date.now()),e.type){case Q.INITIAL_HEARTBEAT:this.publish({type:Q.HEARTBEAT});break;case Q.HEARTBEAT:break;case Q.ADAPTER_CLOSE:this.removeNode(e.uid);break;default:super.onMessage(e,t)}}serverCount(){return Promise.resolve(1+this.nodesMap.size)}publish(e){return this.scheduleHeartbeat(),super.publish(e)}async serverSideEmit(e){if(!(typeof e[e.length-1]=="function"))return this.publish({type:Q.SERVER_SIDE_EMIT,data:{packet:e}});let n=e.pop(),i=this.nodesMap.size;if(we('[%s] waiting for %d responses to "serverSideEmit" request',this.uid,i),i<=0)return n(null,[]);let s=us(),o=setTimeout(()=>{let c=this.customRequests.get(s);c&&(n(new Error(`timeout reached: missing ${c.missingUids.size} responses`),c.responses),this.customRequests.delete(s))},Xc),a={type:Q.SERVER_SIDE_EMIT,resolve:n,timeout:o,missingUids:new Set([...this.nodesMap.keys()]),responses:[]};this.customRequests.set(s,a),this.publish({type:Q.SERVER_SIDE_EMIT,data:{requestId:s,packet:e}})}async fetchSockets(e){var t;let[n,i]=await Promise.all([super.fetchSockets({rooms:e.rooms,except:e.except,flags:{local:!0}}),this.serverCount()]),s=i-1;if(!((t=e.flags)===null||t===void 0)&&t.local||s<=0)return n;let o=us();return new Promise((a,c)=>{let l=setTimeout(()=>{let f=this.customRequests.get(o);f&&(c(new Error(`timeout reached: missing ${f.missingUids.size} responses`)),this.customRequests.delete(o))},e.flags.timeout||Xc),p={type:Q.FETCH_SOCKETS,resolve:a,timeout:l,missingUids:new Set([...this.nodesMap.keys()]),responses:n};this.customRequests.set(o,p),this.publish({type:Q.FETCH_SOCKETS,data:{opts:oi(e),requestId:o}})})}onResponse(e){let t=e.data.requestId;switch(we("[%s] received response %s to request %s",this.uid,e.type,t),e.type){case Q.FETCH_SOCKETS_RESPONSE:{let n=this.customRequests.get(t);if(!n)return;e.data.sockets.forEach(i=>n.responses.push(i)),n.missingUids.delete(e.uid),n.missingUids.size===0&&(clearTimeout(n.timeout),n.resolve(n.responses),this.customRequests.delete(t));break}case Q.SERVER_SIDE_EMIT_RESPONSE:{let n=this.customRequests.get(t);if(!n)return;n.responses.push(e.data.packet),n.missingUids.delete(e.uid),n.missingUids.size===0&&(clearTimeout(n.timeout),n.resolve(null,n.responses),this.customRequests.delete(t));break}default:super.onResponse(e)}}removeNode(e){this.customRequests.forEach((t,n)=>{t.missingUids.delete(e),t.missingUids.size===0&&(clearTimeout(t.timeout),t.type===Q.FETCH_SOCKETS?t.resolve(t.responses):t.type===Q.SERVER_SIDE_EMIT&&t.resolve(null,t.responses),this.customRequests.delete(n))}),this.nodesMap.delete(e)}};Dr.ClusterAdapterWithHeartbeat=Md});var Qc=R(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.MessageType=ar.ClusterAdapterWithHeartbeat=ar.ClusterAdapter=ar.SessionAwareAdapter=ar.Adapter=void 0;var sb=Od();Object.defineProperty(ar,"Adapter",{enumerable:!0,get:function(){return sb.Adapter}});Object.defineProperty(ar,"SessionAwareAdapter",{enumerable:!0,get:function(){return sb.SessionAwareAdapter}});var Pd=ib();Object.defineProperty(ar,"ClusterAdapter",{enumerable:!0,get:function(){return Pd.ClusterAdapter}});Object.defineProperty(ar,"ClusterAdapterWithHeartbeat",{enumerable:!0,get:function(){return Pd.ClusterAdapterWithHeartbeat}});Object.defineProperty(ar,"MessageType",{enumerable:!0,get:function(){return Pd.MessageType}})});var cb=R(ps=>{"use strict";var VD=ps&&ps.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ps,"__esModule",{value:!0});ps.ParentNamespace=void 0;var ob=sd(),KD=Qc(),YD=VD(Ce()),ab=(0,YD.default)("socket.io:parent-namespace"),el=class r extends ob.Namespace{constructor(e){super(e,"/_"+r.count++),this.children=new Set}_initAdapter(){this.adapter=new Id(this)}emit(e,...t){return this.children.forEach(n=>{n.emit(e,...t)}),!0}createChild(e){ab("creating child namespace %s",e);let t=new ob.Namespace(this.server,e);if(this._fns.forEach(n=>t.use(n)),this.listeners("connect").forEach(n=>t.on("connect",n)),this.listeners("connection").forEach(n=>t.on("connection",n)),this.children.add(t),this.server._opts.cleanupEmptyChildNamespaces){let n=t._remove;t._remove=i=>{n.call(t,i),t.sockets.size===0&&(ab("closing child namespace %s",e),t.adapter.close(),this.server._nsps.delete(t.name),this.children.delete(t))}}return this.server._nsps.set(e,t),this.server.sockets.emitReserved("new_namespace",t),t}fetchSockets(){throw new Error("fetchSockets() is not supported on parent namespaces")}};ps.ParentNamespace=el;el.count=0;var Id=class extends KD.Adapter{broadcast(e,t){this.nsp.children.forEach(n=>{n.adapter.broadcast(e,t)})}}});var hb=R(ci=>{"use strict";var JD=ci&&ci.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(ci,"__esModule",{value:!0});ci.patchAdapter=ZD;ci.restoreAdapter=QD;ci.serveFile=t2;var ai=Qc(),lb=require("fs"),XD=JD(Ce()),tl=(0,XD.default)("socket.io:adapter-uws"),Nd="",{addAll:pb,del:fb,broadcast:db}=ai.Adapter.prototype;function ZD(r){ai.Adapter.prototype.addAll=function(e,t){let n=!this.sids.has(e);pb.call(this,e,t);let i=this.nsp.sockets.get(e)||this.nsp._preConnectSockets.get(e);if(i){if(i.conn.transport.name==="websocket"){ub(this.nsp.name,i,n,t);return}n&&i.conn.on("upgrade",()=>{let s=this.sids.get(e);s&&ub(this.nsp.name,i,n,s)})}},ai.Adapter.prototype.del=function(e,t){fb.call(this,e,t);let n=this.nsp.sockets.get(e)||this.nsp._preConnectSockets.get(e);if(n&&n.conn.transport.name==="websocket"){let i=n.conn.id,s=n.conn.transport.socket,o=`${this.nsp.name}${Nd}${t}`;tl("unsubscribe connection %s from topic %s",i,o),s.unsubscribe(o)}},ai.Adapter.prototype.broadcast=function(e,t){if(!(t.rooms.size<=1&&t.except.size===0)){db.call(this,e,t);return}let i=t.flags||{},s={preEncoded:!0,volatile:i.volatile,compress:i.compress};e.nsp=this.nsp.name;let o=this.encoder.encode(e),a=t.rooms.size===0?this.nsp.name:`${this.nsp.name}${Nd}${t.rooms.keys().next().value}`;tl("fast publish to %s",a),o.forEach(c=>{let l=typeof c!="string";r.publish(a,l?c:"4"+c,l)}),this.apply(t,c=>{c.conn.transport.name!=="websocket"&&c.client.writeToEngine(o,s)})}}function ub(r,e,t,n){let i=e.conn.id,s=e.conn.transport.socket;t&&(tl("subscribe connection %s to topic %s",i,r),s.subscribe(r)),n.forEach(o=>{let a=`${r}${Nd}${o}`;tl("subscribe connection %s to topic %s",i,a),s.subscribe(a)})}function QD(){ai.Adapter.prototype.addAll=pb,ai.Adapter.prototype.del=fb,ai.Adapter.prototype.broadcast=db}var e2=r=>{let{buffer:e,byteOffset:t,byteLength:n}=r;return e.slice(t,t+n)};function t2(r,e){let{size:t}=(0,lb.statSync)(e),n=(0,lb.createReadStream)(e),i=()=>!n.destroyed&&n.destroy(),s=a=>{throw i(),a},o=a=>{let c=e2(a);r.cork(()=>{let l=r.getWriteOffset(),[p,f]=r.tryEnd(c,t);!f&&!p&&(n.pause(),r.onWritable(h=>{let[v,x]=r.tryEnd(c.slice(h-l),t);return!x&&v&&n.resume(),v}))})};r.onAborted(i),n.on("data",o).on("error",s).on("end",i)}});var mb=R((y6,r2)=>{r2.exports={name:"socket.io",version:"4.8.3",description:"node.js realtime framework server",keywords:["realtime","framework","websocket","tcp","events","socket","io"],files:["dist/","client-dist/","wrapper.mjs","!**/*.tsbuildinfo"],directories:{doc:"docs/",example:"example/",lib:"lib/",test:"test/"},type:"commonjs",main:"./dist/index.js",exports:{".":{types:"./dist/index.d.ts",import:"./wrapper.mjs",require:"./dist/index.js"},"./package.json":"./package.json"},types:"./dist/index.d.ts",license:"MIT",homepage:"https://github.com/socketio/socket.io/tree/main/packages/socket.io#readme",repository:{type:"git",url:"git+https://github.com/socketio/socket.io.git"},bugs:{url:"https://github.com/socketio/socket.io/issues"},scripts:{compile:"rimraf ./dist && tsc",test:"npm run format:check && npm run compile && npm run test:types && npm run test:unit","test:types":"tsd","test:unit":"nyc mocha --import=tsx --reporter spec --slow 200 --bail --timeout 10000 test/index.ts","format:check":'prettier --check "lib/**/*.ts" "test/**/*.ts"',"format:fix":'prettier --write "lib/**/*.ts" "test/**/*.ts"',prepack:"npm run compile"},dependencies:{accepts:"~1.3.4",base64id:"~2.0.0",cors:"~2.8.5",debug:"~4.4.1","engine.io":"~6.6.0","socket.io-adapter":"~2.5.2","socket.io-parser":"~4.2.4"},contributors:[{name:"Guillermo Rauch",email:"rauchg@gmail.com"},{name:"Arnout Kazemier",email:"info@3rd-eden.com"},{name:"Vladimir Dronnikov",email:"dronnikov@gmail.com"},{name:"Einar Otto Stangvik",email:"einaros@gmail.com"}],engines:{node:">=10.2.0"},tsd:{directory:"test"}}});var Sb=R((xt,ko)=>{"use strict";var n2=xt&&xt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),i2=xt&&xt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),s2=xt&&xt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&n2(e,r,t);return i2(e,r),e},Bd=xt&&xt.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(xt,"__esModule",{value:!0});xt.Namespace=xt.Socket=xt.Server=void 0;var o2=Bd(require("http")),a2=require("fs"),Ld=require("zlib"),c2=$a(),rl=require("stream"),gb=require("path"),vb=Px(),l2=Hx(),yb=require("events"),jd=sd();Object.defineProperty(xt,"Namespace",{enumerable:!0,get:function(){return jd.Namespace}});var u2=cb(),xb=Qc(),p2=s2(xo()),f2=Bd(Ce()),wb=nd();Object.defineProperty(xt,"Socket",{enumerable:!0,get:function(){return wb.Socket}});var d2=Mc(),Dd=hb(),h2=Bd(Bf()),At=(0,f2.default)("socket.io:server"),_b=mb().version,bb=/\.map/,fs=class r extends d2.StrictEventEmitter{constructor(e,t={}){super(),this._nsps=new Map,this.parentNsps=new Map,this.parentNamespacesFromRegExp=new Map,typeof e=="object"&&e instanceof Object&&!e.listen&&(t=e,e=void 0),this.path(t.path||"/socket.io"),this.connectTimeout(t.connectTimeout||45e3),this.serveClient(t.serveClient!==!1),this._parser=t.parser||p2,this.encoder=new this._parser.Encoder,this.opts=t,t.connectionStateRecovery?(t.connectionStateRecovery=Object.assign({maxDisconnectionDuration:120*1e3,skipMiddlewares:!0},t.connectionStateRecovery),this.adapter(t.adapter||xb.SessionAwareAdapter)):this.adapter(t.adapter||xb.Adapter),t.cleanupEmptyChildNamespaces=!!t.cleanupEmptyChildNamespaces,this.sockets=this.of("/"),(e||typeof e=="number")&&this.attach(e),this.opts.cors&&(this._corsMiddleware=(0,h2.default)(this.opts.cors))}get _opts(){return this.opts}serveClient(e){return arguments.length?(this._serveClient=e,this):this._serveClient}_checkNamespace(e,t,n){if(this.parentNsps.size===0)return n(!1);let i=this.parentNsps.keys(),s=()=>{let o=i.next();if(o.done)return n(!1);o.value(e,t,(a,c)=>{if(a||!c)return s();if(this._nsps.has(e))return At("dynamic namespace %s already exists",e),n(this._nsps.get(e));let l=this.parentNsps.get(o.value).createChild(e);At("dynamic namespace %s was created",e),n(l)})};s()}path(e){if(!arguments.length)return this._path;this._path=e.replace(/\/$/,"");let t=this._path.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");return this.clientPathRegex=new RegExp("^"+t+"/socket\\.io(\\.msgpack|\\.esm)?(\\.min)?\\.js(\\.map)?(?:\\?|$)"),this}connectTimeout(e){return e===void 0?this._connectTimeout:(this._connectTimeout=e,this)}adapter(e){if(!arguments.length)return this._adapter;this._adapter=e;for(let t of this._nsps.values())t._initAdapter();return this}listen(e,t={}){return this.attach(e,t)}attach(e,t={}){if(typeof e=="function"){let n="You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.";throw new Error(n)}if(Number(e)==e&&(e=Number(e)),typeof e=="number"){At("creating http server and binding to %d",e);let n=e;e=o2.default.createServer((i,s)=>{s.writeHead(404),s.end()}),e.listen(n)}return Object.assign(t,this.opts),t.path=t.path||this._path,this.initEngine(e,t),this}attachApp(e,t={}){Object.assign(t,this.opts),t.path=t.path||this._path,At("creating uWebSockets.js-based engine with opts %j",t);let n=new vb.uServer(t);n.attach(e,t),this.bind(n),this._serveClient&&e.get(`${this._path}/*`,(i,s)=>{if(!this.clientPathRegex.test(s.getUrl())){s.setYield(!0);return}let o=s.getUrl().replace(this._path,"").replace(/\?.*$/,"").replace(/^\//,""),a=bb.test(o),c=a?"map":"source",l='"'+_b+'"',p="W/"+l,f=s.getHeader("if-none-match");if(f&&(l===f||p===f)){At("serve client %s 304",c),i.writeStatus("304 Not Modified"),i.end();return}At("serve client %s",c),i.writeHeader("cache-control","public, max-age=0"),i.writeHeader("content-type","application/"+(a?"json":"javascript")+"; charset=utf-8"),i.writeHeader("etag",l);let h=gb.join(__dirname,"../client-dist/",o);(0,Dd.serveFile)(i,h)}),(0,Dd.patchAdapter)(e)}initEngine(e,t){At("creating engine.io instance with opts %j",t),this.eio=(0,vb.attach)(e,t),this._serveClient&&this.attachServe(e),this.httpServer=e,this.bind(this.eio)}attachServe(e){At("attaching client serving req handler");let t=e.listeners("request").slice(0);e.removeAllListeners("request"),e.on("request",(n,i)=>{if(this.clientPathRegex.test(n.url))this._corsMiddleware?this._corsMiddleware(n,i,()=>{this.serve(n,i)}):this.serve(n,i);else for(let s=0;s<t.length;s++)t[s].call(e,n,i)})}serve(e,t){let n=e.url.replace(this._path,"").replace(/\?.*$/,""),i=bb.test(n),s=i?"map":"source",o='"'+_b+'"',a="W/"+o,c=e.headers["if-none-match"];if(c&&(o===c||a===c)){At("serve client %s 304",s),t.writeHead(304),t.end();return}At("serve client %s",s),t.setHeader("Cache-Control","public, max-age=0"),t.setHeader("Content-Type","application/"+(i?"json":"javascript")+"; charset=utf-8"),t.setHeader("ETag",o),r.sendFile(n,e,t)}static sendFile(e,t,n){let i=(0,a2.createReadStream)(gb.join(__dirname,"../client-dist/",e)),s=c2(t).encodings(["br","gzip","deflate"]),o=a=>{a&&n.end()};switch(s){case"br":n.writeHead(200,{"content-encoding":"br"}),(0,rl.pipeline)(i,(0,Ld.createBrotliCompress)(),n,o);break;case"gzip":n.writeHead(200,{"content-encoding":"gzip"}),(0,rl.pipeline)(i,(0,Ld.createGzip)(),n,o);break;case"deflate":n.writeHead(200,{"content-encoding":"deflate"}),(0,rl.pipeline)(i,(0,Ld.createDeflate)(),n,o);break;default:n.writeHead(200),(0,rl.pipeline)(i,n,o)}}bind(e){return this.engine=e,this.engine.on("connection",this.onconnection.bind(this)),this}onconnection(e){At("incoming connection with id %s",e.id);let t=new l2.Client(this,e);return e.protocol===3&&t.connect("/"),this}of(e,t){if(typeof e=="function"||e instanceof RegExp){let i=new u2.ParentNamespace(this);return At("initializing parent namespace %s",i.name),typeof e=="function"?this.parentNsps.set(e,i):(this.parentNsps.set((s,o,a)=>a(null,e.test(s)),i),this.parentNamespacesFromRegExp.set(e,i)),t&&i.on("connect",t),i}String(e)[0]!=="/"&&(e="/"+e);let n=this._nsps.get(e);if(!n){for(let[i,s]of this.parentNamespacesFromRegExp)if(i.test(e))return At("attaching namespace %s to parent namespace %s",e,i),s.createChild(e);At("initializing namespace %s",e),n=new jd.Namespace(this,e),this._nsps.set(e,n),e!=="/"&&this.sockets.emitReserved("new_namespace",n)}return t&&n.on("connect",t),n}async close(e){if(await Promise.allSettled([...this._nsps.values()].map(async t=>{t.sockets.forEach(n=>{n._onclose("server shutting down")}),await t.adapter.close()})),this.engine.close(),(0,Dd.restoreAdapter)(),this.httpServer)return new Promise(t=>{this.httpServer.close(n=>{e&&e(n),n&&At("server was not running"),t()})});e&&e()}use(e){return this.sockets.use(e),this}to(e){return this.sockets.to(e)}in(e){return this.sockets.in(e)}except(e){return this.sockets.except(e)}send(...e){return this.sockets.emit("message",...e),this}write(...e){return this.sockets.emit("message",...e),this}serverSideEmit(e,...t){return this.sockets.serverSideEmit(e,...t)}serverSideEmitWithAck(e,...t){return this.sockets.serverSideEmitWithAck(e,...t)}allSockets(){return this.sockets.allSockets()}compress(e){return this.sockets.compress(e)}get volatile(){return this.sockets.volatile}get local(){return this.sockets.local}timeout(e){return this.sockets.timeout(e)}fetchSockets(){return this.sockets.fetchSockets()}socketsJoin(e){return this.sockets.socketsJoin(e)}socketsLeave(e){return this.sockets.socketsLeave(e)}disconnectSockets(e=!1){return this.sockets.disconnectSockets(e)}};xt.Server=fs;var m2=Object.keys(yb.EventEmitter.prototype).filter(function(r){return typeof yb.EventEmitter.prototype[r]=="function"});m2.forEach(function(r){fs.prototype[r]=function(){return this.sockets[r].apply(this.sockets,arguments)}});ko.exports=(r,e)=>new fs(r,e);ko.exports.Server=fs;ko.exports.Namespace=jd.Namespace;ko.exports.Socket=wb.Socket});function Fd(){return Oo=(0,Cb.randomBytes)(32).toString("hex"),Oo}function Ab(){return Oo||Fd(),Oo}function Rb(r){return!!r&&typeof r=="string"&&r===Oo}var Cb,Oo,nl=Ee(()=>{Cb=require("crypto"),Oo=null});var Pb,sl,$,at=Ee(()=>{Pb={darwin:{capture:"robotjs",encoder:"sharp",tileSize:128,inputFormat:"bgra"},win32:{capture:"nodeScreenshots",encoder:"sharp",tileSize:256,inputFormat:"rgba"},linux:{capture:"nodeScreenshots",encoder:"sharp",tileSize:256,inputFormat:"rgba"}},sl=Pb[process.platform]||Pb.linux,$={pipeline:{captureLib:sl.capture,encoder:sl.encoder,inputFormat:sl.inputFormat,tileSize:sl.tileSize,tileFormat:"webp",webpEffort:0,jpegQuality:50,tileConcurrency:6,outputScale:1,adaptiveTiers:[{minEffective:1,outputScale:1,jpegQuality:72},{minEffective:.7,outputScale:.95,jpegQuality:62},{minEffective:.4,outputScale:.8,jpegQuality:52},{minEffective:0,outputScale:.65,jpegQuality:45}],tierHysteresis:.05,checksumSampling:{rowStep:3,colStep:8}},webrtc:{enableWebRTC:!0,enableTurn:!1,turnApiUrl:"https://9remote.cc/api/webrtc/turn-credentials",turnRefreshInterval:1380*60*1e3,dcMaxMessageSize:65536,dcBufferThreshold:65536,iceDisconnectGraceMs:6e3,dcChunkSize:8,dcMaxTilesPerFrame:32,dcReliable:!0,dcOrdered:!1,answerTimeout:1e4,maxControlBuffer:500},robotSettings:{mouseDelay:2,keyboardDelay:2},throttling:{mouseThrottle:8,keyThrottle:25,typeTextThrottle:100,maxTextLength:1e3},resourceManagement:{inactiveTimeout:120*1e3,memoryCheckInterval:6e4,memoryWarningThreshold:1e3,maxTimersPerClient:100,maxChunkTimersPerClient:50,disconnectGraceMs:3e4},streaming:{activeInterval:60,idleInterval:400,idleThreshold:3,actionCaptureDelay:50,chunkSize:32,chunkDelay:5},focus:{paddingTiles:4},displayWake:{enabled:!0,throttleMs:3e4,macDurationSec:5},sleepInhibit:{defaultMode:"never",presets:{"30m":1800*1e3,"1h":3600*1e3,"2h":7200*1e3,"4h":14400*1e3,"24h":1440*60*1e3,never:null}},desktopSwitch:{darwin:{prev:{keyCode:123,mods:"control down"},next:{keyCode:124,mods:"control down"},new:{type:"missionControl"}},win32:{prev:["left",["control","command"]],next:["right",["control","command"]],new:["d",["control","command"]]},linux:{prev:null,next:null,new:null}},logging:{lifecycle:!1,errors:!0,dpiDetection:!1,focus:!1,focusEveryFrames:60,metrics:!1,metricsEveryFrames:30,webrtc:!1}}});var Mo,Po,me,qd=Ee(()=>{at();Ii();Mo=()=>$.logging,Po=Tn("remote"),me={lifecycle:r=>{Mo().lifecycle&&Po.info(r)},focus:r=>{Mo().focus&&Po.info(r)},dpi:r=>{Mo().dpiDetection&&Po.info(r)},error:(r,e)=>{Mo().errors&&Po.error(`${r} ${e?.message||e||""}`)},warn:r=>{Mo().errors&&Po.warn(r)}}});function No(){for(let r of[ie.ROOT,ie.STATE])Br.default.existsSync(r)||Br.default.mkdirSync(r,{recursive:!0})}function Wd(){try{return No(),Br.default.existsSync($d)?JSON.parse(Br.default.readFileSync($d,"utf8"))||{}:{}}catch{return{}}}function Fb(r){try{No();let e={...Wd(),...r};return Br.default.writeFileSync($d,JSON.stringify(e,null,2),{mode:384}),e}catch(e){return console.error("Error saving settings:",e),null}}function Ub(){try{return No(),Br.default.existsSync(Hd)?JSON.parse(Br.default.readFileSync(Hd,"utf8")):{machineId:null,key:null,name:"Default",createdAt:null}}catch{return{machineId:null,key:null,name:"Default",createdAt:null}}}function Dn(r){try{No(),Br.default.writeFileSync(E2,JSON.stringify({cmd:r,ts:Date.now()}))}catch{}}function qb(r,e,t="Default"){try{No();let n={machineId:r,key:e,name:t,createdAt:new Date().toISOString()};return Br.default.writeFileSync(Hd,JSON.stringify(n,null,2),{mode:384}),n}catch(n){return console.error("Error saving key:",n),null}}var Br,Io,$6,W6,Hd,E2,$d,hs=Ee(()=>{Br=K(require("fs"),1),Io=K(require("path"),1);vt();$6=ie.STATE,W6=Io.default.join(ie.STATE,"state.json"),Hd=Io.default.join(ie.ROOT,"keys.json"),E2=Io.default.join(ie.STATE,"cmd.json"),$d=Io.default.join(ie.STATE,"settings.json")});function Hb(){return new Promise(r=>{if(process.platform!=="darwin"){r({screenRecording:!0,accessibility:!0});return}let e=!1,t=!1,n=0,i=()=>{++n===2&&r({screenRecording:e,accessibility:t})};(0,Lo.execFile)("osascript",["-e",'use framework "ApplicationServices"',"-e",`set checkOptions to current application's NSDictionary's dictionaryWithObject:(false) forKey:("AXTrustedCheckOptionPrompt" as string)`,"-e","return current application's AXIsProcessTrustedWithOptions(checkOptions) as boolean"],{timeout:3e3},(s,o)=>{t=!s&&o.trim()==="true",i()}),(0,Lo.exec)(`osascript -e 'use framework "CoreGraphics"' -e "return (current application's CGPreflightScreenCaptureAccess()) as boolean"`,{timeout:3e3},(s,o)=>{e=!s&&o.trim()==="true",i()})})}function $b(r){let e=T2[r];e&&process.platform==="darwin"&&(0,Lo.exec)(`open "${e}"`,()=>{})}var Lo,T2,Wb=Ee(()=>{Lo=require("child_process"),T2={screenRecording:"x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",accessibility:"x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"}});function C2(){return!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY}function Fo(){for(let r=Gb,e=null;r!==e;e=r,r=jr.default.dirname(r)){let t=jr.default.join(r,"package.json");if((0,Se.existsSync)(t)){try{let n=JSON.parse((0,Se.readFileSync)(t,"utf8"));if(n.name!==Pi)continue;let i=typeof n.bin=="string"?n.bin:n.bin?.[Pi];if(i){let s=jr.default.resolve(r,i);if((0,Se.existsSync)(s))return s}}catch{}break}}return process.argv[1]||jr.default.resolve(Gb,"..","index.js")}function vs(){return process.execPath}function Kb(){let r=jr.default.dirname(vs()),e=["/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin","/opt/homebrew/bin"];return e.includes(r)||e.unshift(r),e.join(":")}function Gd(r){return String(r).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function A2(r,e){let t=[r,e,...ll].map(n=>` <string>${Gd(n)}</string>`).join(`
30
30
  `);return`<?xml version="1.0" encoding="UTF-8"?>
31
31
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
32
32
  <plist version="1.0">
@@ -78,7 +78,7 @@ StandardError=append:${al}
78
78
 
79
79
  [Install]
80
80
  WantedBy=default.target
81
- `}function cl(r){try{return(0,jo.execFileSync)("systemctl",["--user",...r],{stdio:"ignore"}),!0}catch{return!1}}function B2(){return C2()?((0,Se.mkdirSync)(jr.default.dirname(Rt.linuxSystemd),{recursive:!0}),(0,Se.writeFileSync)(Rt.linuxSystemd,D2()),cl(["daemon-reload"]),cl(["enable",`${ms}.service`]),!0):((0,Se.mkdirSync)(jr.default.dirname(Rt.linux),{recursive:!0}),(0,Se.writeFileSync)(Rt.linux,L2()),!0)}function j2(){if((0,Se.existsSync)(Rt.linuxSystemd)){cl(["disable",`${ms}.service`]);try{(0,Se.unlinkSync)(Rt.linuxSystemd)}catch{}cl(["daemon-reload"])}if((0,Se.existsSync)(Rt.linux))try{(0,Se.unlinkSync)(Rt.linux)}catch{}return!0}function F2(){return(0,Se.existsSync)(Rt.linux)||(0,Se.existsSync)(Rt.linuxSystemd)}async function Vd(){try{if(process.platform==="darwin")return O2();if(process.platform==="win32")return await N2();if(process.platform==="linux")return F2()}catch{}return!1}async function Yb(r){try{if(process.platform==="darwin")return r?R2():k2();if(process.platform==="win32")return r?await P2():await I2();if(process.platform==="linux")return r?B2():j2()}catch{}return!1}var jo,Se,Do,zb,jr,Vb,al,ms,gs,ll,Bo,Gb,Rt,Kd=Ee(()=>{jo=require("child_process"),Se=require("fs"),Do=require("path"),zb=K(require("os"),1),jr=K(require("path"),1),Vb=require("url");vt();al=(0,Do.join)(ie.LOGS,"autostart.log"),ms="cc.9remote.agent",gs="9Remote",ll=["--tray","--skip-update","--start"],Bo=zb.default.homedir(),Gb=jr.default.dirname((0,Vb.fileURLToPath)(__importMetaUrl)),Rt={darwin:(0,Do.join)(Bo,"Library","LaunchAgents",`${ms}.plist`),linux:(0,Do.join)(Bo,".config","autostart",`${ms}.desktop`),linuxSystemd:(0,Do.join)(Bo,".config","systemd","user",`${ms}.service`)}});function U2(){Uo.default.existsSync(ie.CONFIG)||Uo.default.mkdirSync(ie.CONFIG,{recursive:!0})}function qo(){try{return JSON.parse(Uo.default.readFileSync(Xb,"utf8"))||{}}catch{return{}}}function ul(r){try{U2();let e={...qo(),...r};return Uo.default.writeFileSync(Xb,JSON.stringify(e,null,2)),e}catch{return null}}var Uo,Jb,Xb,Yd=Ee(()=>{Uo=K(require("fs"),1),Jb=K(require("path"),1);vt();Xb=Jb.default.join(ie.CONFIG,"settings.json")});var dl={};Vr(dl,{getMode:()=>eh,isActive:()=>Qd,onConnectionChange:()=>z2,setMode:()=>$o,start:()=>G2,stop:()=>Zd});function H2(){Zb||(Zb=!0,process.on("exit",()=>{if(Dt){try{Dt.kill()}catch{}Dt=null}}))}function pl(){if(Dt)return;let r=q2[process.platform];if(r)try{Dt=(0,Qb.spawn)(r.cmd,r.args,{stdio:"ignore",windowsHide:!0}),Dt.on("error",e=>{fl.warn(`inhibitor error: ${e.message}`),Dt=null}),Dt.on("exit",()=>{Dt=null}),H2(),fl.info(`\u{1F4A4} Sleep inhibitor started (${r.cmd})`)}catch(e){fl.warn(`Failed to start sleep inhibitor: ${e.message}`),Dt=null}}function ew(){if(Dt){try{Dt.kill()}catch{}Dt=null,fl.info("\u{1F4A4} Sleep inhibitor stopped")}}function tw(){Ho&&(clearTimeout(Ho),Ho=null)}function $2(r){return($.sleepInhibit?.presets||{})[r]??null}function W2(r){let e=$.sleepInhibit?.presets||{};return Object.prototype.hasOwnProperty.call(e,r)}function Xd(){if(tw(),ys==="never"){pl();return}let r=$2(ys);if(r==null){pl();return}if(Jd>0){pl();return}pl(),Ho=setTimeout(()=>{Ho=null,Jd===0&&ew()},r)}function G2(){Xd()}function Zd(){tw(),ew()}function Qd(){return Dt!==null}function eh(){return ys}function $o(r){return W2(r)&&(ys=r,Xd()),ys}function z2(r){Jd=r,Xd()}var Qb,fl,q2,Dt,ys,Ho,Jd,Zb,hl=Ee(()=>{Qb=require("child_process");ot();Ii();fl=Tn("sleep"),q2={darwin:{cmd:"caffeinate",args:["-imsd"]},linux:{cmd:"systemd-inhibit",args:["--what=idle:sleep:handle-lid-switch","--who=9remote","--why=remote-active","sleep","infinity"]},win32:{cmd:"powershell.exe",args:["-NonInteractive","-NoProfile","-WindowStyle","Hidden","-Command",`Add-Type -Name K -Namespace W -MemberDefinition '[System.Runtime.InteropServices.DllImport("kernel32")]public static extern uint SetThreadExecutionState(uint e);'; [void][W.K]::SetThreadExecutionState(0x80000041); while($true){Start-Sleep 3600}`]}},Dt=null,ys=$.sleepInhibit?.defaultMode||"never",Ho=null,Jd=0,Zb=!1});function V2(){(0,Bn.mkdirSync)(ie.STATE,{recursive:!0})}function nw(){try{if((0,Bn.existsSync)(th)){let r=JSON.parse((0,Bn.readFileSync)(th,"utf8"));r.step===zn.READY&&r.permanentKey&&(ln={...ln,...r})}}catch{}}function K2(){try{V2(),(0,Bn.writeFileSync)(th,JSON.stringify(ln),{mode:384})}catch{}}function iw(){Bt=!!qo().desktopEnabled}function rh(){ul({desktopEnabled:Bt})}function _t(r,e){let t=`data: ${JSON.stringify({type:r,...e})}
81
+ `}function cl(r){try{return(0,jo.execFileSync)("systemctl",["--user",...r],{stdio:"ignore"}),!0}catch{return!1}}function B2(){return C2()?((0,Se.mkdirSync)(jr.default.dirname(Rt.linuxSystemd),{recursive:!0}),(0,Se.writeFileSync)(Rt.linuxSystemd,D2()),cl(["daemon-reload"]),cl(["enable",`${ms}.service`]),!0):((0,Se.mkdirSync)(jr.default.dirname(Rt.linux),{recursive:!0}),(0,Se.writeFileSync)(Rt.linux,L2()),!0)}function j2(){if((0,Se.existsSync)(Rt.linuxSystemd)){cl(["disable",`${ms}.service`]);try{(0,Se.unlinkSync)(Rt.linuxSystemd)}catch{}cl(["daemon-reload"])}if((0,Se.existsSync)(Rt.linux))try{(0,Se.unlinkSync)(Rt.linux)}catch{}return!0}function F2(){return(0,Se.existsSync)(Rt.linux)||(0,Se.existsSync)(Rt.linuxSystemd)}async function Vd(){try{if(process.platform==="darwin")return O2();if(process.platform==="win32")return await N2();if(process.platform==="linux")return F2()}catch{}return!1}async function Yb(r){try{if(process.platform==="darwin")return r?R2():k2();if(process.platform==="win32")return r?await P2():await I2();if(process.platform==="linux")return r?B2():j2()}catch{}return!1}var jo,Se,Do,zb,jr,Vb,al,ms,gs,ll,Bo,Gb,Rt,Kd=Ee(()=>{jo=require("child_process"),Se=require("fs"),Do=require("path"),zb=K(require("os"),1),jr=K(require("path"),1),Vb=require("url");vt();al=(0,Do.join)(ie.LOGS,"autostart.log"),ms="cc.9remote.agent",gs="9Remote",ll=["--tray","--skip-update","--start"],Bo=zb.default.homedir(),Gb=jr.default.dirname((0,Vb.fileURLToPath)(__importMetaUrl)),Rt={darwin:(0,Do.join)(Bo,"Library","LaunchAgents",`${ms}.plist`),linux:(0,Do.join)(Bo,".config","autostart",`${ms}.desktop`),linuxSystemd:(0,Do.join)(Bo,".config","systemd","user",`${ms}.service`)}});function U2(){Uo.default.existsSync(ie.CONFIG)||Uo.default.mkdirSync(ie.CONFIG,{recursive:!0})}function qo(){try{return JSON.parse(Uo.default.readFileSync(Xb,"utf8"))||{}}catch{return{}}}function ul(r){try{U2();let e={...qo(),...r};return Uo.default.writeFileSync(Xb,JSON.stringify(e,null,2)),e}catch{return null}}var Uo,Jb,Xb,Yd=Ee(()=>{Uo=K(require("fs"),1),Jb=K(require("path"),1);vt();Xb=Jb.default.join(ie.CONFIG,"settings.json")});var dl={};Vr(dl,{getMode:()=>eh,isActive:()=>Qd,onConnectionChange:()=>z2,setMode:()=>$o,start:()=>G2,stop:()=>Zd});function H2(){Zb||(Zb=!0,process.on("exit",()=>{if(Dt){try{Dt.kill()}catch{}Dt=null}}))}function pl(){if(Dt)return;let r=q2[process.platform];if(r)try{Dt=(0,Qb.spawn)(r.cmd,r.args,{stdio:"ignore",windowsHide:!0}),Dt.on("error",e=>{fl.warn(`inhibitor error: ${e.message}`),Dt=null}),Dt.on("exit",()=>{Dt=null}),H2(),fl.info(`\u{1F4A4} Sleep inhibitor started (${r.cmd})`)}catch(e){fl.warn(`Failed to start sleep inhibitor: ${e.message}`),Dt=null}}function ew(){if(Dt){try{Dt.kill()}catch{}Dt=null,fl.info("\u{1F4A4} Sleep inhibitor stopped")}}function tw(){Ho&&(clearTimeout(Ho),Ho=null)}function $2(r){return($.sleepInhibit?.presets||{})[r]??null}function W2(r){let e=$.sleepInhibit?.presets||{};return Object.prototype.hasOwnProperty.call(e,r)}function Xd(){if(tw(),ys==="never"){pl();return}let r=$2(ys);if(r==null){pl();return}if(Jd>0){pl();return}pl(),Ho=setTimeout(()=>{Ho=null,Jd===0&&ew()},r)}function G2(){Xd()}function Zd(){tw(),ew()}function Qd(){return Dt!==null}function eh(){return ys}function $o(r){return W2(r)&&(ys=r,Xd()),ys}function z2(r){Jd=r,Xd()}var Qb,fl,q2,Dt,ys,Ho,Jd,Zb,hl=Ee(()=>{Qb=require("child_process");at();Ii();fl=Tn("sleep"),q2={darwin:{cmd:"caffeinate",args:["-imsd"]},linux:{cmd:"systemd-inhibit",args:["--what=idle:sleep:handle-lid-switch","--who=9remote","--why=remote-active","sleep","infinity"]},win32:{cmd:"powershell.exe",args:["-NonInteractive","-NoProfile","-WindowStyle","Hidden","-Command",`Add-Type -Name K -Namespace W -MemberDefinition '[System.Runtime.InteropServices.DllImport("kernel32")]public static extern uint SetThreadExecutionState(uint e);'; [void][W.K]::SetThreadExecutionState(0x80000041); while($true){Start-Sleep 3600}`]}},Dt=null,ys=$.sleepInhibit?.defaultMode||"never",Ho=null,Jd=0,Zb=!1});function V2(){(0,Bn.mkdirSync)(ie.STATE,{recursive:!0})}function nw(){try{if((0,Bn.existsSync)(th)){let r=JSON.parse((0,Bn.readFileSync)(th,"utf8"));r.step===zn.READY&&r.permanentKey&&(ln={...ln,...r})}}catch{}}function K2(){try{V2(),(0,Bn.writeFileSync)(th,JSON.stringify(ln),{mode:384})}catch{}}function iw(){Bt=!!qo().desktopEnabled}function rh(){ul({desktopEnabled:Bt})}function _t(r,e){let t=`data: ${JSON.stringify({type:r,...e})}
82
82
 
83
83
  `;for(let n of ml)try{n.write(t)}catch{ml.delete(n)}}function ve(r){_t("log",{message:`[${new Date().toLocaleTimeString()}] ${r}`})}function sw(){return ln}function un(r){ln={...ln,...r},_t("state",ln),K2()}function ow(){un({oneTimeKey:"",oneTimeKeyExpiresAt:null,qrUrl:""})}function aw(){return gl}function cw(r){gl=r||null}function lw(r){nh=!!r}function xs(){return!!nh&&!!Bt&&!!Er.screenRecording&&!!Er.accessibility}function uw(r){ih=r}async function vl(){let r=await Hb(),e=Er,t=xs();Er=r,Bt&&(!r.screenRecording||!r.accessibility)&&(Bt=!1,rh());let n=e.screenRecording&&e.accessibility,i=r.screenRecording&&r.accessibility;return!Bt&&!n&&i&&(Bt=!0,rh()),(e.screenRecording!==r.screenRecording||e.accessibility!==r.accessibility)&&_t("permissions",{...Er,desktopEnabled:Bt}),xs()!==t&&ih?.(),r}function pw(r,e){let t=r.headers.origin;if(t&&!ja.includes(t))return ce(e,403,"Forbidden origin");X(e,{localToken:Ab()})}function fw(r,e,t=null,n="ws"){li.set(r,{socketId:r,ip:e,deviceId:t,type:n,connectedAt:Date.now()}),_t("connections",{connections:[...li.values()]}),hw()}function dw(r){li.delete(r),_t("connections",{connections:[...li.values()]}),hw()}async function hw(){try{(await Promise.resolve().then(()=>(hl(),dl))).onConnectionChange(li.size)}catch{}}function mw(r,e){e.setHeader("Content-Type","text/event-stream"),e.setHeader("Cache-Control","no-cache"),e.setHeader("Connection","keep-alive"),e.writeHead(200),e.write(`data: ${JSON.stringify({type:"state",...ln})}
84
84
 
@@ -88,32 +88,32 @@ WantedBy=default.target
88
88
 
89
89
  `),gl&&e.write(`data: ${JSON.stringify({type:"updateAvailable",...gl})}
90
90
 
91
- `),ml.add(e),r.on("close",()=>ml.delete(e))}function gw(r,e){X(e,{...ln,...Er,desktopEnabled:Bt,remoteAvailable:nh})}async function vw(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Pt(),Mi)),n=await t(r,e);n&&(un(n),X(e))}function yw(r,e){X(e),un({step:zn.PREPARING,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null}),Dn("restart-tunnel")}function xw(r,e){X(e),un({step:zn.PREPARING,stepDesc:""}),Dn("start-tunnel")}function _w(r,e){X(e),un({step:zn.STOPPED,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null}),Dn("stop-tunnel")}function bw(r,e){X(e),un({step:zn.STOPPED,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null}),Dn("shutdown")}function ww(r,e){X(e),Dn("update")}function Sw(r,e){X(e,{connections:[...li.values()]})}function Ew(r,e){let t=new URL(r.url,"http://localhost"),n=parseInt(t.searchParams.get("lines")||bp,10);X(e,{logs:Sv(Number.isFinite(n)?n:bp)})}async function Tw(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Pt(),Mi)),n=await t(r,e);if(!n)return;let i=!!n.enabled;if(i&&(!Er.screenRecording||!Er.accessibility)){X(e,{ok:!1,enabled:Bt,reason:"permissions_required"});return}let s=xs();Bt=i,rh(),_t("permissions",{...Er,desktopEnabled:Bt}),xs()!==s&&ih?.(),X(e,{ok:!0,enabled:Bt})}function Cw(r,e){X(e,Er)}async function Aw(r,e){let t=await Vd();X(e,{enabled:t})}async function Rw(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Pt(),Mi)),n=await t(r,e);if(!n)return;let i=await Yb(!!n.enabled),s=await Vd();_t("autostart",{enabled:s}),X(e,{ok:i,enabled:s})}async function kw(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Pt(),Mi)),n=await t(r,e);if(!n)return;let{type:i}=n;if(process.platform==="darwin"){$b(i);let s=Date.now(),o=setInterval(async()=>{((await vl())[i]||Date.now()-s>gv)&&clearInterval(o)},mv)}X(e)}var Bn,rw,th,ln,Bt,nh,Er,ml,li,gl,ih,pn=Ee(()=>{vt();Ii();vt();hs();Wb();Kd();Pt();nl();vt();Bn=require("fs"),rw=require("path");vt();Yd();th=(0,rw.join)(ie.STATE,"ui-state.json");ln={step:zn.STOPPED,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null,permanentKey:"",qrUrl:"",latency:null,uptime:null,healthCheck:{running:!1,timeoutMs:0,startedAt:null,logs:[]},tunnelHealth:{status:"unknown",checkedAt:null}},Bt=!1,nh=!1,Er={screenRecording:!1,accessibility:!1},ml=new Set,li=new Map;wv(ve);gl=null;ih=null});var Ow={};Vr(Ow,{ScreenHandler:()=>sh,encodeTilesBatch:()=>_s});function Y2(r){let e=Buffer.alloc(28);return e.writeUInt32LE(r.tileIndex,0),e.writeUInt32LE(r.x,4),e.writeUInt32LE(r.y,8),e.writeUInt32LE(r.width,12),e.writeUInt32LE(r.height,16),e.writeUInt32LE(r.imageBuffer.length,20),e.writeUInt32LE(r.hash>>>0,24),Buffer.concat([e,r.imageBuffer])}function _s(r,e){let t=Buffer.alloc(12);return t.writeUInt32LE(r.length,0),t.writeDoubleBE(e,4),Buffer.concat([t,...r.map(Y2)])}var sh,oh=Ee(()=>{qd();ot();pn();sh=class{constructor(e,t){this.resourceManager=e,this.screenUpdateHelper=t}setupScreenHandlers(e,t,n){e.on("request-screen",t(async()=>{let i=this.resourceManager.getClient(e.id);if(i)try{let s=await i.tileManager.detectChangedTiles();s.length>0&&n.sendTiles({tiles:s,timestamp:Date.now()},_s),this.resourceManager.updateClientActivity(e.id)}catch(s){me.error("Tile capture error:",s),n.emit("screen-error",{error:s.message})}})),e.on("request-screen-with-hashes",t(async i=>{let s=this.resourceManager.getClient(e.id);if(s)try{let o=i.tileHashes||[],a=await s.tileManager.compareClientTileHashes(o);a?.tiles?.length>0&&n.sendTiles({tiles:a.tiles,timestamp:Date.now()},_s),this.resourceManager.updateClientActivity(e.id)}catch(o){me.error("Tile capture with hashes error:",o),n.emit("screen-error",{error:o.message})}})),e.on("start-streaming",t(async()=>{let i=this.resourceManager.getClient(e.id);if(!i)return;i.streamingTimeout&&(clearTimeout(i.streamingTimeout),i.streamingTimeout=null),me.lifecycle("\u{1F680} Remote streaming started");let{tileFormat:s,webpEffort:o,jpegQuality:a}=$.pipeline;ve(`\u{1F5BC}\uFE0F Remote stream codec: ${s.toUpperCase()}${s==="webp"?` (effort=${o})`:""} q=${a}`),i.idleFrameCount=0,i.isStreaming=!0,i.streamGen=(i.streamGen||0)+1;let c=i.streamGen;i.tileManager.lastTileChecksums.clear();try{let p=await i.tileManager.getScreenDimensions();n.emit("screen-dimensions",p)}catch(p){me.error("Get dimensions error:",p)}let l=async()=>{if(!e.connected||!i.isStreaming||i.streamGen!==c){i.streamingTimeout=null;return}try{let p=performance.now(),f=await i.tileManager.detectChangedTilesWithHashes();f.tiles.length>0&&e.connected?(n.sendTiles({tiles:f.tiles,timestamp:Date.now(),currentHashes:f.currentHashes},_s),i.idleFrameCount=0):i.idleFrameCount++;let{activeInterval:h,idleInterval:v,idleThreshold:x}=this.resourceManager.getStreamingConfig(),S=i.idleFrameCount>=x?v:h,A=Math.max(0,S-(performance.now()-p));i.streamingTimeout=setTimeout(l,A)}catch(p){me.error("Auto streaming error:",p),i.streamingTimeout=setTimeout(l,200)}};l()})),e.on("stop-streaming",()=>{let i=this.resourceManager.getClient(e.id);i&&(i.isStreaming=!1,i.streamingTimeout&&(clearTimeout(i.streamingTimeout),i.streamingTimeout=null),i.tileManager?.clearMemory?.(),me.lifecycle("\u23F9\uFE0F Remote streaming stopped"))}),e.on("get-screen-dimensions",t(async()=>{let i=this.resourceManager.getClient(e.id);if(i)try{let s=await i.tileManager.getScreenDimensions();n.emit("screen-dimensions",s)}catch(s){me.error("Get dimensions error:",s),n.emit("screen-error",{error:s.message})}})),e.on("boost-stream",t(()=>{let i=this.resourceManager.getClient(e.id);i&&(i.idleFrameCount=0)})),e.on("set-focus",t(i=>{let s=this.resourceManager.getClient(e.id);if(!s)return;let o=i?.rect||null,a=typeof i?.zoom=="number"?i.zoom:1,c=typeof i?.viewerWidth=="number"?i.viewerWidth:0,l=typeof i?.dpr=="number"?i.dpr:1,p=s.tileManager.pickProfile({zoom:a,viewerWidth:c,dpr:l});if(s.tileManager.setProfile(p),s.tileManager.setFocusRect(o),o){let f=s.tileManager.activeTileSet?.size||0,h=s.tileManager.totalTiles,v=h?(f/h*100).toFixed(0):0;me.focus(`\u{1F3AF} [Focus] rect=${o.x},${o.y} ${o.w}x${o.h} | tiles ${f}/${h} (${v}%)`)}else me.focus("\u{1F3AF} [Focus] cleared \u2192 full screen")}))}}});function Mw(r){ah.add(r)}function bs(r){ah.delete(r)}function bt(r,e,t){for(let n of ah)if(n.hasReadyAdapter?.())try{n.emit(e,t)}catch{}}var ah,ui=Ee(()=>{ah=new Set});async function Vw(){if(Go)return Go;let r=await import("node-screenshots");if(Go=(r.Monitor||r.default?.Monitor).all()[0],!Go)throw new Error("No monitor found via node-screenshots");return Go}async function Kw(r){hh=r,$.pipeline.captureLib==="nodeScreenshots"&&await Vw()}async function Yw(){let{captureLib:r,inputFormat:e}=$.pipeline;if(r==="robotjs"){let{width:s,height:o}=hh.getScreenSize(),a=hh.screen.capture(0,0,s,o),c=a.byteWidth/a.bytesPerPixel;return{buffer:Buffer.from(a.image),width:c,height:a.height,channels:a.bytesPerPixel,format:e}}let n=(await Vw()).captureImageSync();return{buffer:n.toRawSync?n.toRawSync():n.rawSync(),width:n.width,height:n.height,channels:4,format:e}}var hh,Go,Jw=Ee(()=>{ot();hh=null,Go=null});function lB(r){return r==="bgra"?gh.FORMAT_BGRA:gh.FORMAT_RGBA}function vh(r){let e=new Uint32Array(r.buffer,r.byteOffset,r.length>>2);for(let t=0;t<e.length;t++){let n=e[t];e[t]=n&4278255360|(n&16711680)>>16|(n&255)<<16}}async function Xw(r,e,t,n=4,i,s){let{encoder:o,inputFormat:a,jpegQuality:c,tileFormat:l,webpEffort:p}=$.pipeline,f=i??c,h=s??a;if(o==="jpegTurbo"&&l!=="webp")return gh.compressSync(r,{width:e,height:t,format:lB(h),quality:f});let v=r;h==="bgra"&&(v=Buffer.from(r),vh(v));let x=(0,kl.default)(v,{raw:{width:e,height:t,channels:n}});return l==="webp"?x.webp({quality:f,effort:p}).toBuffer():x.jpeg({quality:f}).toBuffer()}var kl,mh,gh,Zw=Ee(()=>{kl=K(require("sharp"),1),mh=K(require("@julusian/jpeg-turbo"),1);ot();gh=mh.default.default||mh.default;kl.default.cache(!1);kl.default.concurrency(1)});var Ol,Qw=Ee(()=>{ot();pn();Ol=class{constructor(){this.cfg=$.logging,this.samples=[],this.lastLogTime=Date.now()}now(){return this.cfg.metrics?performance.now():0}record({capture:e,checksum:t,encode:n,total:i,changedTiles:s,totalTiles:o,tileBytes:a,rawBytes:c}){this.cfg.metrics&&(this.samples.push({capture:e,checksum:t,encode:n,total:i,changedTiles:s,totalTiles:o,tileBytes:a,rawBytes:c}),this.samples.length>=this.cfg.metricsEveryFrames&&this._flush())}_flush(){let e=this.samples.length,t=I=>(this.samples.reduce((B,V)=>B+V[I],0)/e).toFixed(1),n=(Date.now()-this.lastLogTime)/1e3,i=(e/n).toFixed(1),s=[],o=0;for(let I of this.samples){for(let B of I.tileBytes)s.push(B);o+=I.tileBytes.reduce((B,V)=>B+V,0)}let a=(o/e/1024).toFixed(1),c=s.length?(s.reduce((I,B)=>I+B,0)/s.length/1024).toFixed(2):"0",l=s.length?(Math.min(...s)/1024).toFixed(2):"0",p=s.length?(Math.max(...s)/1024).toFixed(2):"0",f=this.samples.reduce((I,B)=>I+B.rawBytes,0)/e,h=o/e,v=h>0?(f/h).toFixed(0):"0",x=(this.samples.reduce((I,B)=>I+B.changedTiles,0)/e).toFixed(0),S=this.samples[0]?.totalTiles||0,A=S?(x/S*100).toFixed(1):"0",k=$.pipeline,P=`[Metrics] ${k.captureLib}+${k.encoder} tile=${k.tileSize} q${k.jpegQuality} scale=${k.outputScale} | fps=${i} | capture=${t("capture")}ms enc=${t("encode")}ms total=${t("total")}ms | tiles=${x}/${S} (${A}%) | data=${a}KB/frame | tileAvg=${c}KB (min ${l}, max ${p}) | compress=${v}x`;ve(P),console.log(P),this.samples=[],this.lastLogTime=Date.now()}}});var rS={};Vr(rS,{TileManager:()=>yh,mapLimit:()=>fi});async function fi(r,e,t){let n=new Array(r.length),i=0,s=Array.from({length:Math.min(e,r.length)},async()=>{for(;i<r.length;){let o=i++;n[o]=await t(r[o],o)}});return await Promise.all(s),n}var Es,Pl,eS,Ml,tS,uB,pB,yh,nS=Ee(()=>{Es=K(require("fs"),1),Pl=K(require("path"),1),eS=K(require("sharp"),1),Ml=require("child_process"),tS=require("url");ot();Jw();Zw();Qw();qd();uB=(0,tS.fileURLToPath)(__importMetaUrl),pB=Pl.default.dirname(uB);yh=class{constructor(e){this.robot=e,this.metrics=new Ol,this.tileSize=$.pipeline.tileSize,this.lastTileChecksums=new Map,this.screenWidth=0,this.screenHeight=0,this.tilesPerRow=0,this.tilesPerColumn=0,this.totalTiles=0,this.frameCount=0,this.tempDir=Pl.default.join(pB,"../../temp"),this.changeThreshold=1,this.scaledWidth=0,this.scaledHeight=0,this.isProcessing=!1,this.sharedScreenCache=null,this.lastCaptureTime=0,this.CACHE_TTL=100,this.dpiScale=1,this.captureWidth=0,this.captureHeight=0,this.scaleFactor=$.pipeline.outputScale||1,this.compressionQuality=$.pipeline.jpegQuality,this.activeTileSet=null,this.focusStats={frames:0,scanned:0,changed:0,bytes:0},Es.default.existsSync(this.tempDir)||Es.default.mkdirSync(this.tempDir,{recursive:!0}),Kw(e),this.initializeScreenDimensions()}initializeScreenDimensions(){try{let{width:e,height:t}=this.robot.getScreenSize();this.screenWidth=e,this.screenHeight=t,this.detectDpiScale(),this.scaledWidth=this.captureWidth,this.scaledHeight=this.captureHeight,this.tilesPerRow=Math.ceil(this.scaledWidth/this.tileSize),this.tilesPerColumn=Math.ceil(this.scaledHeight/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn;let n=100;if(this.totalTiles>n){let i=Math.ceil(Math.sqrt(this.scaledWidth*this.scaledHeight/n));this.tileSize=Math.max(i,120),this.tilesPerRow=Math.ceil(this.scaledWidth/this.tileSize),this.tilesPerColumn=Math.ceil(this.scaledHeight/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn}}catch(e){me.error("Screen dimensions error:",e),this.screenWidth=1920,this.screenHeight=1080,this.dpiScale=1,this.captureWidth=1920,this.captureHeight=1080,this.scaledWidth=1728,this.scaledHeight=972,this.tileSize=120,this.tilesPerRow=Math.ceil(this.scaledWidth/this.tileSize),this.tilesPerColumn=Math.ceil(this.scaledHeight/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn}}detectDpiScale(){if(process.platform==="darwin"){let e=this.robot.screen.capture(0,0,this.screenWidth,this.screenHeight),n=e.byteWidth/e.bytesPerPixel/this.screenWidth;n>=1.9&&n<=2.1?this.dpiScale=2:this.dpiScale=1}else process.platform==="win32"?this.dpiScale=this._detectDpiScaleWin32():this.dpiScale=1;this.captureWidth=Math.floor(this.screenWidth*this.dpiScale),this.captureHeight=Math.floor(this.screenHeight*this.dpiScale)}_detectDpiScaleWin32(){me.dpi(`\u{1F50D} [DPI Detection] screenWidth from robot: ${this.screenWidth}x${this.screenHeight}`);try{let e=(0,Ml.execSync)(`powershell -NonInteractive -NoProfile -WindowStyle Hidden -command "try{Get-ItemPropertyValue 'HKCU:\\Control Panel\\Desktop\\WindowMetrics' -Name AppliedDPI}catch{0}"`,{encoding:"utf8",windowsHide:!0}).trim(),t=Number(e);if(me.dpi(`\u{1F50D} [DPI Detection] Strategy 1 (Registry AppliedDPI): ${t} DPI`),t>=96){let n=t/96;return me.dpi(`\u2705 [DPI Detection] Using registry scale: ${n}x (${t}/96)`),n}}catch(e){me.dpi(`\u274C [DPI Detection] Strategy 1 failed: ${e.message}`)}try{let e=(0,Ml.execSync)('powershell -NonInteractive -NoProfile -WindowStyle Hidden -command "(Get-WmiObject -Class Win32_VideoController | Select-Object -First 1).CurrentHorizontalResolution"',{encoding:"utf8",windowsHide:!0}).trim(),t=Number(e);if(me.dpi(`\u{1F50D} [DPI Detection] Strategy 2 (WMI): physical width = ${t}px`),t>0&&t>this.screenWidth){let n=t/this.screenWidth;return me.dpi(`\u2705 [DPI Detection] Using WMI scale: ${n}x (${t}/${this.screenWidth})`),n}}catch(e){me.dpi(`\u274C [DPI Detection] Strategy 2 failed: ${e.message}`)}try{let e=(0,Ml.execSync)(`powershell -NonInteractive -NoProfile -WindowStyle Hidden -command "Add-Type -TypeDefinition 'using System;using System.Runtime.InteropServices;public class Disp{[DllImport(\\"user32\\")]public static extern bool EnumDisplaySettings(string d,int m,ref DEVMODE dm);[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]public struct DEVMODE{[MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)]public string dmDeviceName;public short dmSpecVersion,dmDriverVersion,dmSize,dmDriverExtra;public int dmFields;public int dmPositionX,dmPositionY,dmDisplayOrientation,dmDisplayFixedOutput;public short dmColor,dmDuplex,dmYResolution,dmTTOption,dmCollate;[MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)]public string dmFormName;public short dmLogPixels;public int dmBitsPerPel,dmPelsWidth,dmPelsHeight,dmDisplayFlags,dmDisplayFrequency;}}'; $dm=New-Object Disp+DEVMODE; $dm.dmSize=[System.Runtime.InteropServices.Marshal]::SizeOf($dm); [Disp]::EnumDisplaySettings($null,-1,[ref]$dm) | Out-Null; Write-Output $dm.dmPelsWidth"`,{encoding:"utf8",windowsHide:!0}).trim(),t=Number(e);if(me.dpi(`\u{1F50D} [DPI Detection] Strategy 3 (EnumDisplaySettings): physical width = ${t}px`),t>0&&t>this.screenWidth){let n=t/this.screenWidth;return me.dpi(`\u2705 [DPI Detection] Using EnumDisplaySettings scale: ${n}x (${t}/${this.screenWidth})`),n}}catch(e){me.dpi(`\u274C [DPI Detection] Strategy 3 failed: ${e.message}`)}return me.dpi("\u26A0\uFE0F [DPI Detection] All strategies failed, fallback to 1x"),1}async captureFullScreen(){let e=await Yw();return{buffer:e.buffer,width:e.width,height:e.height,channels:e.channels}}async getSharedScreenCapture(){let e=Date.now();return this.sharedScreenCache&&e-this.lastCaptureTime<this.CACHE_TTL?this.sharedScreenCache:(this.sharedScreenCache=await this.captureFullScreen(),this.lastCaptureTime=e,this.sharedScreenCache)}clearScreenCache(){}async detectChangedTiles(){return(await this.detectChangedTilesWithHashes()).tiles}async detectChangedTilesWithHashes(){if(this.isProcessing)return{tiles:[],currentHashes:Array.from(this.lastTileChecksums.values())};this.isProcessing=!0;let e=this.metrics.now(),t=e,n=e;try{let i=await this.getSharedScreenCapture();t=this.metrics.now();let s=[],o=[],a=new Map;this.frameCount++;let c=this.activeTileSet;for(let f=0;f<this.totalTiles;f++){if(c&&!c.has(f))continue;let h=this.calculateTileChecksumDirect(i,f);a.set(f,h)}n=this.metrics.now();let l=Array.from(a.values());if(this.lastTileChecksums.size===0){let f=[];for(let v=0;v<this.totalTiles;v++)c&&!c.has(v)||(this.lastTileChecksums.set(v,a.get(v)),f.push(v));let h=await fi(f,$.pipeline.tileConcurrency,v=>this.processTileAsync(i,v));return s.push(...h),this._recordFrame(e,t,n,s,i),{tiles:s,currentHashes:l}}for(let f=0;f<this.totalTiles;f++){if(c&&!c.has(f))continue;let h=a.get(f),v=this.lastTileChecksums.get(f);h!==v&&(o.push(f),this.lastTileChecksums.set(f,h))}if(o.length/this.totalTiles>this.changeThreshold){let f=[];for(let v=0;v<this.totalTiles;v++)c&&!c.has(v)||f.push(v);let h=await fi(f,$.pipeline.tileConcurrency,v=>this.processTileAsync(i,v));s.push(...h.map(v=>({...v,fullRefresh:!0})))}else if(o.length>0){let f=await fi(o,$.pipeline.tileConcurrency,h=>this.processTileAsync(i,h));s.push(...f)}return this._recordFrame(e,t,n,s,i),{tiles:s,currentHashes:l}}finally{this.isProcessing=!1}}async processTileAsync(e,t,n=null){let i=n||this.extractTile(e,t),s=await this.compressTileImage(i.buffer,i.width,i.height),{row:o,col:a}=this.getTilePosition(t);return{type:"tile-update",tileIndex:t,x:a*this.tileSize,y:o*this.tileSize,width:i.width,height:i.height,imageBuffer:s,hash:this.lastTileChecksums.get(t)??0,timestamp:Date.now(),frameCount:this.frameCount}}calculateTileChecksumDirect(e,t){let{row:n,col:i}=this.getTilePosition(t),s=i*this.tileSize,o=n*this.tileSize,a=Math.min(s+this.tileSize,e.width),c=Math.min(o+this.tileSize,e.height),l=a-s,p=c-o,f=e.channels,h=e.width*f,v=0,{rowStep:x,colStep:S}=$.pipeline.checksumSampling;for(let A=0;A<p;A+=x){let k=(o+A)*h+s*f;for(let P=0;P<l;P+=S){let I=k+P*f,B=P+1;v=v+e.buffer[I]*B>>>0,v^=e.buffer[I+1]<<1,v=v+e.buffer[I+2]*B>>>0,v^=e.buffer[I+3]<<2}}return v>>>0}setFocusRect(e){if(!e){this.activeTileSet=null;return}let t=$.focus.paddingTiles,n=Math.max(0,Math.floor(e.x/this.tileSize)-t),i=Math.max(0,Math.floor(e.y/this.tileSize)-t),s=Math.min(this.tilesPerRow-1,Math.floor((e.x+e.w)/this.tileSize)+t),o=Math.min(this.tilesPerColumn-1,Math.floor((e.y+e.h)/this.tileSize)+t),a=new Set;for(let l=i;l<=o;l++)for(let p=n;p<=s;p++)a.add(l*this.tilesPerRow+p);let c=this.activeTileSet;if(c)for(let l of a)c.has(l)||this.lastTileChecksums.delete(l);this.activeTileSet=a}getTilePosition(e){return{row:Math.floor(e/this.tilesPerRow),col:e%this.tilesPerRow}}extractTile(e,t){let{row:n,col:i}=this.getTilePosition(t),s=i*this.tileSize,o=n*this.tileSize,a=Math.min(s+this.tileSize,e.width),c=Math.min(o+this.tileSize,e.height),l=a-s,p=c-o,f=e.channels,h=l*f,v=Buffer.alloc(l*p*f);for(let x=0;x<p;x++){let S=((o+x)*e.width+s)*f,A=x*h;e.buffer.copy(v,A,S,S+h)}return{buffer:v,width:l,height:p,channels:f,tileIndex:t,x:s,y:o}}async compressTileImage(e,t,n){let i=this.scaleFactor;if(i&&i>0&&i<1){let s=Math.max(1,Math.floor(t*i)),o=Math.max(1,Math.floor(n*i)),{inputFormat:a}=$.pipeline,c=e,l=4;a==="bgra"&&(c=Buffer.from(e),vh(c));let{tileFormat:p,webpEffort:f}=$.pipeline,h=(0,eS.default)(c,{raw:{width:t,height:n,channels:l}}).resize(s,o,{kernel:"lanczos3",fastShrinkOnLoad:!1});return p==="webp"?h.webp({quality:this.compressionQuality,effort:f}).toBuffer():h.jpeg({quality:this.compressionQuality}).toBuffer()}return Xw(e,t,n,4,this.compressionQuality)}pickProfile({zoom:e=1,viewerWidth:t=0,dpr:n=1}={}){let i=$.pipeline.adaptiveTiers||[];if(!i.length)return null;let s=this.captureWidth||this.screenWidth||1,o=t>0?t:s,a=e>0?e:1,c=n>0?n:1,l=o*a*c/s,p=$.pipeline.tierHysteresis||0,f=this._currentTier;for(let v of i){let x=f&&v===f?v.minEffective-p:v.minEffective;if(l>=x)return this._currentTier=v,v}let h=i[i.length-1];return this._currentTier=h,h}setProfile(e){if(!e)return;let t=e.outputScale??this.scaleFactor,n=e.jpegQuality??this.compressionQuality;t===this.scaleFactor&&n===this.compressionQuality||(this.scaleFactor=t,this.compressionQuality=n,this.lastTileChecksums.clear())}_recordFrame(e,t,n,i,s){if(this._recordFocusFrame(i),!this.metrics.cfg.metrics)return;let o=this.metrics.now(),a=i.map(l=>l.imageBuffer?.length||0),c=s?s.width*s.height*s.channels:0;this.metrics.record({capture:t-e,checksum:n-t,encode:o-n,total:o-e,changedTiles:i.length,totalTiles:this.totalTiles,tileBytes:a,rawBytes:c})}_recordFocusFrame(e){let t=this.focusStats;t.frames++,t.scanned+=this.activeTileSet?this.activeTileSet.size:this.totalTiles,t.changed+=e.length;for(let c of e)t.bytes+=c.imageBuffer?.length||0;if(t.frames<$.logging.focusEveryFrames)return;let n=(t.scanned/t.frames).toFixed(0),i=(t.changed/t.frames).toFixed(1),s=(t.bytes/t.frames/1024).toFixed(1),o=this.totalTiles?((1-n/this.totalTiles)*100).toFixed(0):0,a=this.activeTileSet?"focus":"full";me.focus(`\u{1F3AF} [Focus/${a}] ${t.frames}f | scan ${n}/${this.totalTiles} tiles (saved ${o}%) | changed ${i}/f | data ${s}KB/f`),this.focusStats={frames:0,scanned:0,changed:0,bytes:0}}async getScreenDimensions(){try{let e=await this.captureFullScreen();this.scaledWidth=e.width,this.scaledHeight=e.height,this.tilesPerRow=Math.ceil(e.width/this.tileSize),this.tilesPerColumn=Math.ceil(e.height/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn}catch(e){me.error("Error getting dimensions:",e)}return{width:this.scaledWidth,height:this.scaledHeight,tileWidth:this.tileSize,tileHeight:this.tileSize,tileCount:this.totalTiles,scaleFactor:this.scaleFactor,originalWidth:this.screenWidth,originalHeight:this.screenHeight}}async compareClientTileHashes(e){if(this.isProcessing)return{tiles:[],currentHashes:[],changedIndices:[]};this.isProcessing=!0;try{let t=await this.getSharedScreenCapture(),n=[],i=[];this.frameCount++;let s=this.activeTileSet,o=new Map;for(let c=0;c<this.totalTiles;c++){if(s&&!s.has(c))continue;let l=this.calculateTileChecksumDirect(t,c);o.set(c,l),this.lastTileChecksums.set(c,l)}if(!e||e.length===0){let c=[];for(let p=0;p<this.totalTiles;p++)s&&!s.has(p)||c.push(p);let l=await fi(c,$.pipeline.tileConcurrency,p=>this.processTileAsync(t,p));return n.push(...l),{tiles:n,currentHashes:Array.from(o.values())}}for(let c=0;c<this.totalTiles;c++)s&&!s.has(c)||e[c]!==o.get(c)&&i.push(c);if(i.length/this.totalTiles>this.changeThreshold){let c=[];for(let p=0;p<this.totalTiles;p++)s&&!s.has(p)||c.push(p);let l=await fi(c,$.pipeline.tileConcurrency,p=>this.processTileAsync(t,p));n.push(...l.map(p=>({...p,fullRefresh:!0})))}else if(i.length>0){let c=await fi(i,$.pipeline.tileConcurrency,l=>this.processTileAsync(t,l));n.push(...c)}return this._recordFocusFrame(n),{tiles:n,currentHashes:Array.from(o.values()),changedIndices:i}}finally{this.isProcessing=!1}}clearMemory(){this.sharedScreenCache=null,this.lastCaptureTime=0,this.lastTileChecksums.clear()}reset(){this.lastTileChecksums.clear(),this.frameCount=0}cleanup(){try{Es.default.existsSync(this.tempDir)&&Es.default.readdirSync(this.tempDir).forEach(t=>Es.default.unlinkSync(Pl.default.join(this.tempDir,t)))}catch(e){me.warn(`Cleanup error: ${e.message}`)}}}});var iS={};Vr(iS,{ResourceManager:()=>xh});var xh,sS=Ee(()=>{ot();ui();xh=class{constructor(){this.activeClients=new Map,this.activeTimers=new Map,this.chunkTimers=new Map,this.memoryCheckInterval=null}startResourceMonitoring(){this.memoryCheckInterval=setInterval(()=>{let e=process.memoryUsage(),t=Math.round(e.heapUsed/1024/1024);t>$.resourceManagement.memoryWarningThreshold&&(console.warn(`\u26A0\uFE0F High memory: ${t}MB`),this.cleanupInactiveClients())},$.resourceManagement.memoryCheckInterval)}stopResourceMonitoring(){this.memoryCheckInterval&&(clearInterval(this.memoryCheckInterval),this.memoryCheckInterval=null)}addClient(e,t){this.activeClients.set(e,{...t,lastActivity:Date.now()})}getClient(e){return this.activeClients.get(e)}updateClientActivity(e){let t=this.activeClients.get(e);t&&(t.lastActivity=Date.now())}cleanupInactiveClients(){let e=Date.now(),t=$.resourceManagement.inactiveTimeout;for(let[n,i]of this.activeClients.entries())e-i.lastActivity>t&&(console.log(`\u{1F9F9} Cleaning inactive client: ${n}`),this.cleanupClientResources(n,i),this.activeClients.delete(n))}cleanupClientResources(e,t){try{t.isStreaming=!1,t?.streamingTimeout&&(clearTimeout(t.streamingTimeout),t.streamingTimeout=null),t?.screenInterval&&(clearInterval(t.screenInterval),t.screenInterval=null);let n=this.activeTimers.get(e);n&&(n.forEach(s=>clearTimeout(s)),this.activeTimers.delete(e));let i=this.chunkTimers.get(e);i&&(i.forEach(s=>clearTimeout(s)),this.chunkTimers.delete(e)),t?.tileManager&&(t.tileManager.clearMemory(),t.tileManager.cleanup(),t.tileManager.reset()),t?.protocol&&(t.protocol.close(),bs(t.protocol))}catch(n){console.error(`Error cleaning up ${e}:`,n.message)}}getStreamingConfig(){return $.streaming}getWebRTCConfig(){return $.webrtc}removeClient(e){let t=this.activeClients.get(e);t&&(this.cleanupClientResources(e,t),this.activeClients.delete(e))}getChunkTimers(e){return this.chunkTimers.has(e)||this.chunkTimers.set(e,new Set),this.chunkTimers.get(e)}cleanupAll(){this.stopResourceMonitoring();for(let[e,t]of this.activeClients.entries())this.cleanupClientResources(e,t);this.activeClients.clear(),this.activeTimers.clear(),this.chunkTimers.clear()}}});var oS={};Vr(oS,{ScreenUpdateHelper:()=>_h});var _h,aS=Ee(()=>{ot();_h=class{constructor(e){this.resourceManager=e}async sendTilesInChunks(e,t,n,i=!1){if(!t||t.length===0)return;let s=$.streaming.chunkSize,o=[];for(let c=0;c<t.length;c+=s)o.push(t.slice(c,c+s));let a=this.resourceManager.getChunkTimers(e.id);for(let c=0;c<o.length;c++){let l=o[c],p=c===o.length-1,f=setTimeout(()=>{a.delete(f),e.connected&&e.emit("tiles-data",{tiles:l,timestamp:n,forceRefresh:!1,userAction:i,chunkInfo:{chunkIndex:c,totalChunks:o.length,isLastChunk:p}})},c*$.streaming.chunkDelay);a.add(f)}}}});var cS={};Vr(cS,{MouseHandler:()=>bh});var bh,lS=Ee(()=>{ot();bh=class{constructor(e,t){this.robot=e,this.resourceManager=t,this.lastMouseMove=0}setupMouseHandlers(e,t){let n=this.robot;e.on("mouse-move",t(i=>{let s=Date.now();if(!(s-this.lastMouseMove<$.throttling.mouseThrottle)){this.lastMouseMove=s;try{let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),l=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(l,p),this.resourceManager.updateClientActivity(e.id)}catch(o){console.error("Mouse move error:",o.message)}}})),e.on("mouse-click",t(async i=>{try{let s=this.resourceManager.getClient(e.id);if(!s)return;let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),l=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(l,p),n.mouseClick(i.button||"left",i.double||!1),s.idleFrameCount=0,this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Mouse click error:",s.message)}})),e.on("mouse-press",t(async i=>{try{if(!this.resourceManager.getClient(e.id))return;let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),l=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(l,p),n.mouseToggle("down",i.button||"left"),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Mouse press error:",s.message)}})),e.on("mouse-release",t(async i=>{try{if(!this.resourceManager.getClient(e.id))return;let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),l=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(l,p),n.mouseToggle("up",i.button||"left"),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Mouse release error:",s.message)}})),e.on("scroll",t(async i=>{try{let{direction:s,amount:o=60,horizontal:a=!1}=i,c=this.resourceManager.getClient(e.id);if(!c)return;let l=0,p=0;a||s==="left"||s==="right"?l=s==="right"?o:-o:p=s==="down"?-o:o,n.scrollMouse(l,p),c.idleFrameCount=0,this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Scroll error:",s.message)}})),e.on("mouse-drag-select",t(i=>{try{let{startX:s,startY:o,endX:a,endY:c}=i,l=n.getScreenSize(),p=Math.round(s/100*l.width),f=Math.round(o/100*l.height),h=Math.round(a/100*l.width),v=Math.round(c/100*l.height),x=Math.max(0,Math.min(l.width-1,p)),S=Math.max(0,Math.min(l.height-1,f)),A=Math.max(0,Math.min(l.width-1,h)),k=Math.max(0,Math.min(l.height-1,v));n.moveMouse(x,S),n.mouseToggle("down","left"),n.dragMouse(A,k),n.mouseToggle("up","left"),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Drag selection error:",s.message)}}))}}});var pS={};Vr(pS,{KeyboardHandler:()=>wh});function fB(r){let e;r.type==="missionControl"?e='tell application "System Events" to key code 160':e=`tell application "System Events" to key code ${r.keyCode} using ${r.mods}`,(0,uS.execFile)("osascript",["-e",e],t=>{t&&console.error("osascript error:",t.message)})}var uS,wh,fS=Ee(()=>{uS=require("child_process");ot();wh=class{constructor(e,t){this.robot=e,this.resourceManager=t,this.lastKeyPress=0,this.lastTypeText=0}setupKeyboardHandlers(e,t){let n=this.robot;e.on("key-press",t(i=>{let s=Date.now();if(!(s-this.lastKeyPress<$.throttling.keyThrottle)){this.lastKeyPress=s;try{if(!i.key||typeof i.key!="string")return;let o=this.resourceManager.getClient(e.id),a=i.key,c=i.modifier||[];if(a.length===1)if(c.filter(p=>p!=="shift").length>0){n.keyTap(a.toLowerCase(),c);for(let p of c)n.keyToggle(p,"up")}else n.typeString(a);else{let p={return:"enter"}[a.toLowerCase()]??a.toLowerCase();n.keyTap(p,c)}o&&(o.idleFrameCount=0),this.resourceManager.updateClientActivity(e.id)}catch(o){console.error("Key press error:",o.message)}}})),e.on("desktop-switch",t(i=>{try{let s=i?.direction,o=$.desktopSwitch[process.platform]?.[s];if(!o)return;process.platform==="darwin"?fB(o):n.keyTap(o[0],o[1]);let a=this.resourceManager.getClient(e.id);a&&(a.idleFrameCount=0),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Desktop switch error:",s.message)}})),e.on("type-text",t(i=>{let s=Date.now();if(!(s-this.lastTypeText<$.throttling.typeTextThrottle)){this.lastTypeText=s;try{if(!i.text||typeof i.text!="string")return;let o=i.text;o.length>$.throttling.maxTextLength&&(o=o.substring(0,$.throttling.maxTextLength));let a=o.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),c=this.resourceManager.getClient(e.id);setTimeout(()=>{try{n.typeString(a),this.resourceManager.updateClientActivity(e.id),c&&(c.idleFrameCount=0,c.tileManager&&c.tileManager.clearScreenCache())}catch(l){console.error("Robot typeString error:",l.message)}},10)}catch(o){console.error("Type text error:",o.message)}}}))}}});var Mh=R((WS,Oh)=>{(function(r,e){"use strict";function t(T,u){if(!T)throw new Error(u||"Assertion failed")}function n(T,u){T.super_=u;var m=function(){};m.prototype=u.prototype,T.prototype=new m,T.prototype.constructor=T}function i(T,u,m){if(i.isBN(T))return T;this.negative=0,this.words=null,this.length=0,this.red=null,T!==null&&((u==="le"||u==="be")&&(m=u,u=10),this._init(T||0,u||10,m||"be"))}typeof r=="object"?r.exports=i:e.BN=i,i.BN=i,i.wordSize=26;var s;try{typeof window<"u"&&typeof window.Buffer<"u"?s=window.Buffer:s=require("buffer").Buffer}catch{}i.isBN=function(u){return u instanceof i?!0:u!==null&&typeof u=="object"&&u.constructor.wordSize===i.wordSize&&Array.isArray(u.words)},i.max=function(u,m){return u.cmp(m)>0?u:m},i.min=function(u,m){return u.cmp(m)<0?u:m},i.prototype._init=function(u,m,y){if(typeof u=="number")return this._initNumber(u,m,y);if(typeof u=="object")return this._initArray(u,m,y);m==="hex"&&(m=16),t(m===(m|0)&&m>=2&&m<=36),u=u.toString().replace(/\s+/g,"");var w=0;u[0]==="-"&&(w++,this.negative=1),w<u.length&&(m===16?this._parseHex(u,w,y):(this._parseBase(u,m,w),y==="le"&&this._initArray(this.toArray(),m,y)))},i.prototype._initNumber=function(u,m,y){u<0&&(this.negative=1,u=-u),u<67108864?(this.words=[u&67108863],this.length=1):u<4503599627370496?(this.words=[u&67108863,u/67108864&67108863],this.length=2):(t(u<9007199254740992),this.words=[u&67108863,u/67108864&67108863,1],this.length=3),y==="le"&&this._initArray(this.toArray(),m,y)},i.prototype._initArray=function(u,m,y){if(t(typeof u.length=="number"),u.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(u.length/3),this.words=new Array(this.length);for(var w=0;w<this.length;w++)this.words[w]=0;var g,_,C=0;if(y==="be")for(w=u.length-1,g=0;w>=0;w-=3)_=u[w]|u[w-1]<<8|u[w-2]<<16,this.words[g]|=_<<C&67108863,this.words[g+1]=_>>>26-C&67108863,C+=24,C>=26&&(C-=26,g++);else if(y==="le")for(w=0,g=0;w<u.length;w+=3)_=u[w]|u[w+1]<<8|u[w+2]<<16,this.words[g]|=_<<C&67108863,this.words[g+1]=_>>>26-C&67108863,C+=24,C>=26&&(C-=26,g++);return this.strip()};function o(T,u){var m=T.charCodeAt(u);return m>=65&&m<=70?m-55:m>=97&&m<=102?m-87:m-48&15}function a(T,u,m){var y=o(T,m);return m-1>=u&&(y|=o(T,m-1)<<4),y}i.prototype._parseHex=function(u,m,y){this.length=Math.ceil((u.length-m)/6),this.words=new Array(this.length);for(var w=0;w<this.length;w++)this.words[w]=0;var g=0,_=0,C;if(y==="be")for(w=u.length-1;w>=m;w-=2)C=a(u,m,w)<<g,this.words[_]|=C&67108863,g>=18?(g-=18,_+=1,this.words[_]|=C>>>26):g+=8;else{var b=u.length-m;for(w=b%2===0?m+1:m;w<u.length;w+=2)C=a(u,m,w)<<g,this.words[_]|=C&67108863,g>=18?(g-=18,_+=1,this.words[_]|=C>>>26):g+=8}this.strip()};function c(T,u,m,y){for(var w=0,g=Math.min(T.length,m),_=u;_<g;_++){var C=T.charCodeAt(_)-48;w*=y,C>=49?w+=C-49+10:C>=17?w+=C-17+10:w+=C}return w}i.prototype._parseBase=function(u,m,y){this.words=[0],this.length=1;for(var w=0,g=1;g<=67108863;g*=m)w++;w--,g=g/m|0;for(var _=u.length-y,C=_%w,b=Math.min(_,_-C)+y,d=0,E=y;E<b;E+=w)d=c(u,E,E+w,m),this.imuln(g),this.words[0]+d<67108864?this.words[0]+=d:this._iaddn(d);if(C!==0){var q=1;for(d=c(u,E,u.length,m),E=0;E<C;E++)q*=m;this.imuln(q),this.words[0]+d<67108864?this.words[0]+=d:this._iaddn(d)}this.strip()},i.prototype.copy=function(u){u.words=new Array(this.length);for(var m=0;m<this.length;m++)u.words[m]=this.words[m];u.length=this.length,u.negative=this.negative,u.red=this.red},i.prototype.clone=function(){var u=new i(null);return this.copy(u),u},i.prototype._expand=function(u){for(;this.length<u;)this.words[this.length++]=0;return this},i.prototype.strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},i.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var l=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],p=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],f=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];i.prototype.toString=function(u,m){u=u||10,m=m|0||1;var y;if(u===16||u==="hex"){y="";for(var w=0,g=0,_=0;_<this.length;_++){var C=this.words[_],b=((C<<w|g)&16777215).toString(16);g=C>>>24-w&16777215,w+=2,w>=26&&(w-=26,_--),g!==0||_!==this.length-1?y=l[6-b.length]+b+y:y=b+y}for(g!==0&&(y=g.toString(16)+y);y.length%m!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}if(u===(u|0)&&u>=2&&u<=36){var d=p[u],E=f[u];y="";var q=this.clone();for(q.negative=0;!q.isZero();){var O=q.modn(E).toString(u);q=q.idivn(E),q.isZero()?y=O+y:y=l[d-O.length]+O+y}for(this.isZero()&&(y="0"+y);y.length%m!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}t(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var u=this.words[0];return this.length===2?u+=this.words[1]*67108864:this.length===3&&this.words[2]===1?u+=4503599627370496+this.words[1]*67108864:this.length>2&&t(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-u:u},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(u,m){return t(typeof s<"u"),this.toArrayLike(s,u,m)},i.prototype.toArray=function(u,m){return this.toArrayLike(Array,u,m)},i.prototype.toArrayLike=function(u,m,y){var w=this.byteLength(),g=y||Math.max(1,w);t(w<=g,"byte array longer than desired length"),t(g>0,"Requested array length <= 0"),this.strip();var _=m==="le",C=new u(g),b,d,E=this.clone();if(_){for(d=0;!E.isZero();d++)b=E.andln(255),E.iushrn(8),C[d]=b;for(;d<g;d++)C[d]=0}else{for(d=0;d<g-w;d++)C[d]=0;for(d=0;!E.isZero();d++)b=E.andln(255),E.iushrn(8),C[g-d-1]=b}return C},Math.clz32?i.prototype._countBits=function(u){return 32-Math.clz32(u)}:i.prototype._countBits=function(u){var m=u,y=0;return m>=4096&&(y+=13,m>>>=13),m>=64&&(y+=7,m>>>=7),m>=8&&(y+=4,m>>>=4),m>=2&&(y+=2,m>>>=2),y+m},i.prototype._zeroBits=function(u){if(u===0)return 26;var m=u,y=0;return(m&8191)===0&&(y+=13,m>>>=13),(m&127)===0&&(y+=7,m>>>=7),(m&15)===0&&(y+=4,m>>>=4),(m&3)===0&&(y+=2,m>>>=2),(m&1)===0&&y++,y},i.prototype.bitLength=function(){var u=this.words[this.length-1],m=this._countBits(u);return(this.length-1)*26+m};function h(T){for(var u=new Array(T.bitLength()),m=0;m<u.length;m++){var y=m/26|0,w=m%26;u[m]=(T.words[y]&1<<w)>>>w}return u}i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var u=0,m=0;m<this.length;m++){var y=this._zeroBits(this.words[m]);if(u+=y,y!==26)break}return u},i.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},i.prototype.toTwos=function(u){return this.negative!==0?this.abs().inotn(u).iaddn(1):this.clone()},i.prototype.fromTwos=function(u){return this.testn(u-1)?this.notn(u).iaddn(1).ineg():this.clone()},i.prototype.isNeg=function(){return this.negative!==0},i.prototype.neg=function(){return this.clone().ineg()},i.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},i.prototype.iuor=function(u){for(;this.length<u.length;)this.words[this.length++]=0;for(var m=0;m<u.length;m++)this.words[m]=this.words[m]|u.words[m];return this.strip()},i.prototype.ior=function(u){return t((this.negative|u.negative)===0),this.iuor(u)},i.prototype.or=function(u){return this.length>u.length?this.clone().ior(u):u.clone().ior(this)},i.prototype.uor=function(u){return this.length>u.length?this.clone().iuor(u):u.clone().iuor(this)},i.prototype.iuand=function(u){var m;this.length>u.length?m=u:m=this;for(var y=0;y<m.length;y++)this.words[y]=this.words[y]&u.words[y];return this.length=m.length,this.strip()},i.prototype.iand=function(u){return t((this.negative|u.negative)===0),this.iuand(u)},i.prototype.and=function(u){return this.length>u.length?this.clone().iand(u):u.clone().iand(this)},i.prototype.uand=function(u){return this.length>u.length?this.clone().iuand(u):u.clone().iuand(this)},i.prototype.iuxor=function(u){var m,y;this.length>u.length?(m=this,y=u):(m=u,y=this);for(var w=0;w<y.length;w++)this.words[w]=m.words[w]^y.words[w];if(this!==m)for(;w<m.length;w++)this.words[w]=m.words[w];return this.length=m.length,this.strip()},i.prototype.ixor=function(u){return t((this.negative|u.negative)===0),this.iuxor(u)},i.prototype.xor=function(u){return this.length>u.length?this.clone().ixor(u):u.clone().ixor(this)},i.prototype.uxor=function(u){return this.length>u.length?this.clone().iuxor(u):u.clone().iuxor(this)},i.prototype.inotn=function(u){t(typeof u=="number"&&u>=0);var m=Math.ceil(u/26)|0,y=u%26;this._expand(m),y>0&&m--;for(var w=0;w<m;w++)this.words[w]=~this.words[w]&67108863;return y>0&&(this.words[w]=~this.words[w]&67108863>>26-y),this.strip()},i.prototype.notn=function(u){return this.clone().inotn(u)},i.prototype.setn=function(u,m){t(typeof u=="number"&&u>=0);var y=u/26|0,w=u%26;return this._expand(y+1),m?this.words[y]=this.words[y]|1<<w:this.words[y]=this.words[y]&~(1<<w),this.strip()},i.prototype.iadd=function(u){var m;if(this.negative!==0&&u.negative===0)return this.negative=0,m=this.isub(u),this.negative^=1,this._normSign();if(this.negative===0&&u.negative!==0)return u.negative=0,m=this.isub(u),u.negative=1,m._normSign();var y,w;this.length>u.length?(y=this,w=u):(y=u,w=this);for(var g=0,_=0;_<w.length;_++)m=(y.words[_]|0)+(w.words[_]|0)+g,this.words[_]=m&67108863,g=m>>>26;for(;g!==0&&_<y.length;_++)m=(y.words[_]|0)+g,this.words[_]=m&67108863,g=m>>>26;if(this.length=y.length,g!==0)this.words[this.length]=g,this.length++;else if(y!==this)for(;_<y.length;_++)this.words[_]=y.words[_];return this},i.prototype.add=function(u){var m;return u.negative!==0&&this.negative===0?(u.negative=0,m=this.sub(u),u.negative^=1,m):u.negative===0&&this.negative!==0?(this.negative=0,m=u.sub(this),this.negative=1,m):this.length>u.length?this.clone().iadd(u):u.clone().iadd(this)},i.prototype.isub=function(u){if(u.negative!==0){u.negative=0;var m=this.iadd(u);return u.negative=1,m._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(u),this.negative=1,this._normSign();var y=this.cmp(u);if(y===0)return this.negative=0,this.length=1,this.words[0]=0,this;var w,g;y>0?(w=this,g=u):(w=u,g=this);for(var _=0,C=0;C<g.length;C++)m=(w.words[C]|0)-(g.words[C]|0)+_,_=m>>26,this.words[C]=m&67108863;for(;_!==0&&C<w.length;C++)m=(w.words[C]|0)+_,_=m>>26,this.words[C]=m&67108863;if(_===0&&C<w.length&&w!==this)for(;C<w.length;C++)this.words[C]=w.words[C];return this.length=Math.max(this.length,C),w!==this&&(this.negative=1),this.strip()},i.prototype.sub=function(u){return this.clone().isub(u)};function v(T,u,m){m.negative=u.negative^T.negative;var y=T.length+u.length|0;m.length=y,y=y-1|0;var w=T.words[0]|0,g=u.words[0]|0,_=w*g,C=_&67108863,b=_/67108864|0;m.words[0]=C;for(var d=1;d<y;d++){for(var E=b>>>26,q=b&67108863,O=Math.min(d,u.length-1),M=Math.max(0,d-T.length+1);M<=O;M++){var j=d-M|0;w=T.words[j]|0,g=u.words[M]|0,_=w*g+q,E+=_/67108864|0,q=_&67108863}m.words[d]=q|0,b=E|0}return b!==0?m.words[d]=b|0:m.length--,m.strip()}var x=function(u,m,y){var w=u.words,g=m.words,_=y.words,C=0,b,d,E,q=w[0]|0,O=q&8191,M=q>>>13,j=w[1]|0,z=j&8191,U=j>>>13,Te=w[2]|0,ne=Te&8191,N=Te>>>13,te=w[3]|0,D=te&8191,W=te>>>13,se=w[4]|0,Z=se&8191,J=se>>>13,Tt=w[5]|0,oe=Tt&8191,Oe=Tt>>>13,jg=w[6]|0,Me=jg&8191,Pe=jg>>>13,Fg=w[7]|0,Ie=Fg&8191,Ne=Fg>>>13,Ug=w[8]|0,Le=Ug&8191,De=Ug>>>13,qg=w[9]|0,Be=qg&8191,je=qg>>>13,Hg=g[0]|0,Fe=Hg&8191,Ue=Hg>>>13,$g=g[1]|0,qe=$g&8191,He=$g>>>13,Wg=g[2]|0,$e=Wg&8191,We=Wg>>>13,Gg=g[3]|0,Ge=Gg&8191,ze=Gg>>>13,zg=g[4]|0,Ve=zg&8191,Ke=zg>>>13,Vg=g[5]|0,Ye=Vg&8191,Je=Vg>>>13,Kg=g[6]|0,Xe=Kg&8191,Ze=Kg>>>13,Yg=g[7]|0,Qe=Yg&8191,et=Yg>>>13,Jg=g[8]|0,tt=Jg&8191,rt=Jg>>>13,Xg=g[9]|0,nt=Xg&8191,it=Xg>>>13;y.negative=u.negative^m.negative,y.length=19,b=Math.imul(O,Fe),d=Math.imul(O,Ue),d=d+Math.imul(M,Fe)|0,E=Math.imul(M,Ue);var Yu=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(Yu>>>26)|0,Yu&=67108863,b=Math.imul(z,Fe),d=Math.imul(z,Ue),d=d+Math.imul(U,Fe)|0,E=Math.imul(U,Ue),b=b+Math.imul(O,qe)|0,d=d+Math.imul(O,He)|0,d=d+Math.imul(M,qe)|0,E=E+Math.imul(M,He)|0;var Ju=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(Ju>>>26)|0,Ju&=67108863,b=Math.imul(ne,Fe),d=Math.imul(ne,Ue),d=d+Math.imul(N,Fe)|0,E=Math.imul(N,Ue),b=b+Math.imul(z,qe)|0,d=d+Math.imul(z,He)|0,d=d+Math.imul(U,qe)|0,E=E+Math.imul(U,He)|0,b=b+Math.imul(O,$e)|0,d=d+Math.imul(O,We)|0,d=d+Math.imul(M,$e)|0,E=E+Math.imul(M,We)|0;var Xu=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(Xu>>>26)|0,Xu&=67108863,b=Math.imul(D,Fe),d=Math.imul(D,Ue),d=d+Math.imul(W,Fe)|0,E=Math.imul(W,Ue),b=b+Math.imul(ne,qe)|0,d=d+Math.imul(ne,He)|0,d=d+Math.imul(N,qe)|0,E=E+Math.imul(N,He)|0,b=b+Math.imul(z,$e)|0,d=d+Math.imul(z,We)|0,d=d+Math.imul(U,$e)|0,E=E+Math.imul(U,We)|0,b=b+Math.imul(O,Ge)|0,d=d+Math.imul(O,ze)|0,d=d+Math.imul(M,Ge)|0,E=E+Math.imul(M,ze)|0;var Zu=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(Zu>>>26)|0,Zu&=67108863,b=Math.imul(Z,Fe),d=Math.imul(Z,Ue),d=d+Math.imul(J,Fe)|0,E=Math.imul(J,Ue),b=b+Math.imul(D,qe)|0,d=d+Math.imul(D,He)|0,d=d+Math.imul(W,qe)|0,E=E+Math.imul(W,He)|0,b=b+Math.imul(ne,$e)|0,d=d+Math.imul(ne,We)|0,d=d+Math.imul(N,$e)|0,E=E+Math.imul(N,We)|0,b=b+Math.imul(z,Ge)|0,d=d+Math.imul(z,ze)|0,d=d+Math.imul(U,Ge)|0,E=E+Math.imul(U,ze)|0,b=b+Math.imul(O,Ve)|0,d=d+Math.imul(O,Ke)|0,d=d+Math.imul(M,Ve)|0,E=E+Math.imul(M,Ke)|0;var Qu=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(Qu>>>26)|0,Qu&=67108863,b=Math.imul(oe,Fe),d=Math.imul(oe,Ue),d=d+Math.imul(Oe,Fe)|0,E=Math.imul(Oe,Ue),b=b+Math.imul(Z,qe)|0,d=d+Math.imul(Z,He)|0,d=d+Math.imul(J,qe)|0,E=E+Math.imul(J,He)|0,b=b+Math.imul(D,$e)|0,d=d+Math.imul(D,We)|0,d=d+Math.imul(W,$e)|0,E=E+Math.imul(W,We)|0,b=b+Math.imul(ne,Ge)|0,d=d+Math.imul(ne,ze)|0,d=d+Math.imul(N,Ge)|0,E=E+Math.imul(N,ze)|0,b=b+Math.imul(z,Ve)|0,d=d+Math.imul(z,Ke)|0,d=d+Math.imul(U,Ve)|0,E=E+Math.imul(U,Ke)|0,b=b+Math.imul(O,Ye)|0,d=d+Math.imul(O,Je)|0,d=d+Math.imul(M,Ye)|0,E=E+Math.imul(M,Je)|0;var ep=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(ep>>>26)|0,ep&=67108863,b=Math.imul(Me,Fe),d=Math.imul(Me,Ue),d=d+Math.imul(Pe,Fe)|0,E=Math.imul(Pe,Ue),b=b+Math.imul(oe,qe)|0,d=d+Math.imul(oe,He)|0,d=d+Math.imul(Oe,qe)|0,E=E+Math.imul(Oe,He)|0,b=b+Math.imul(Z,$e)|0,d=d+Math.imul(Z,We)|0,d=d+Math.imul(J,$e)|0,E=E+Math.imul(J,We)|0,b=b+Math.imul(D,Ge)|0,d=d+Math.imul(D,ze)|0,d=d+Math.imul(W,Ge)|0,E=E+Math.imul(W,ze)|0,b=b+Math.imul(ne,Ve)|0,d=d+Math.imul(ne,Ke)|0,d=d+Math.imul(N,Ve)|0,E=E+Math.imul(N,Ke)|0,b=b+Math.imul(z,Ye)|0,d=d+Math.imul(z,Je)|0,d=d+Math.imul(U,Ye)|0,E=E+Math.imul(U,Je)|0,b=b+Math.imul(O,Xe)|0,d=d+Math.imul(O,Ze)|0,d=d+Math.imul(M,Xe)|0,E=E+Math.imul(M,Ze)|0;var tp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(tp>>>26)|0,tp&=67108863,b=Math.imul(Ie,Fe),d=Math.imul(Ie,Ue),d=d+Math.imul(Ne,Fe)|0,E=Math.imul(Ne,Ue),b=b+Math.imul(Me,qe)|0,d=d+Math.imul(Me,He)|0,d=d+Math.imul(Pe,qe)|0,E=E+Math.imul(Pe,He)|0,b=b+Math.imul(oe,$e)|0,d=d+Math.imul(oe,We)|0,d=d+Math.imul(Oe,$e)|0,E=E+Math.imul(Oe,We)|0,b=b+Math.imul(Z,Ge)|0,d=d+Math.imul(Z,ze)|0,d=d+Math.imul(J,Ge)|0,E=E+Math.imul(J,ze)|0,b=b+Math.imul(D,Ve)|0,d=d+Math.imul(D,Ke)|0,d=d+Math.imul(W,Ve)|0,E=E+Math.imul(W,Ke)|0,b=b+Math.imul(ne,Ye)|0,d=d+Math.imul(ne,Je)|0,d=d+Math.imul(N,Ye)|0,E=E+Math.imul(N,Je)|0,b=b+Math.imul(z,Xe)|0,d=d+Math.imul(z,Ze)|0,d=d+Math.imul(U,Xe)|0,E=E+Math.imul(U,Ze)|0,b=b+Math.imul(O,Qe)|0,d=d+Math.imul(O,et)|0,d=d+Math.imul(M,Qe)|0,E=E+Math.imul(M,et)|0;var rp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(rp>>>26)|0,rp&=67108863,b=Math.imul(Le,Fe),d=Math.imul(Le,Ue),d=d+Math.imul(De,Fe)|0,E=Math.imul(De,Ue),b=b+Math.imul(Ie,qe)|0,d=d+Math.imul(Ie,He)|0,d=d+Math.imul(Ne,qe)|0,E=E+Math.imul(Ne,He)|0,b=b+Math.imul(Me,$e)|0,d=d+Math.imul(Me,We)|0,d=d+Math.imul(Pe,$e)|0,E=E+Math.imul(Pe,We)|0,b=b+Math.imul(oe,Ge)|0,d=d+Math.imul(oe,ze)|0,d=d+Math.imul(Oe,Ge)|0,E=E+Math.imul(Oe,ze)|0,b=b+Math.imul(Z,Ve)|0,d=d+Math.imul(Z,Ke)|0,d=d+Math.imul(J,Ve)|0,E=E+Math.imul(J,Ke)|0,b=b+Math.imul(D,Ye)|0,d=d+Math.imul(D,Je)|0,d=d+Math.imul(W,Ye)|0,E=E+Math.imul(W,Je)|0,b=b+Math.imul(ne,Xe)|0,d=d+Math.imul(ne,Ze)|0,d=d+Math.imul(N,Xe)|0,E=E+Math.imul(N,Ze)|0,b=b+Math.imul(z,Qe)|0,d=d+Math.imul(z,et)|0,d=d+Math.imul(U,Qe)|0,E=E+Math.imul(U,et)|0,b=b+Math.imul(O,tt)|0,d=d+Math.imul(O,rt)|0,d=d+Math.imul(M,tt)|0,E=E+Math.imul(M,rt)|0;var np=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(np>>>26)|0,np&=67108863,b=Math.imul(Be,Fe),d=Math.imul(Be,Ue),d=d+Math.imul(je,Fe)|0,E=Math.imul(je,Ue),b=b+Math.imul(Le,qe)|0,d=d+Math.imul(Le,He)|0,d=d+Math.imul(De,qe)|0,E=E+Math.imul(De,He)|0,b=b+Math.imul(Ie,$e)|0,d=d+Math.imul(Ie,We)|0,d=d+Math.imul(Ne,$e)|0,E=E+Math.imul(Ne,We)|0,b=b+Math.imul(Me,Ge)|0,d=d+Math.imul(Me,ze)|0,d=d+Math.imul(Pe,Ge)|0,E=E+Math.imul(Pe,ze)|0,b=b+Math.imul(oe,Ve)|0,d=d+Math.imul(oe,Ke)|0,d=d+Math.imul(Oe,Ve)|0,E=E+Math.imul(Oe,Ke)|0,b=b+Math.imul(Z,Ye)|0,d=d+Math.imul(Z,Je)|0,d=d+Math.imul(J,Ye)|0,E=E+Math.imul(J,Je)|0,b=b+Math.imul(D,Xe)|0,d=d+Math.imul(D,Ze)|0,d=d+Math.imul(W,Xe)|0,E=E+Math.imul(W,Ze)|0,b=b+Math.imul(ne,Qe)|0,d=d+Math.imul(ne,et)|0,d=d+Math.imul(N,Qe)|0,E=E+Math.imul(N,et)|0,b=b+Math.imul(z,tt)|0,d=d+Math.imul(z,rt)|0,d=d+Math.imul(U,tt)|0,E=E+Math.imul(U,rt)|0,b=b+Math.imul(O,nt)|0,d=d+Math.imul(O,it)|0,d=d+Math.imul(M,nt)|0,E=E+Math.imul(M,it)|0;var ip=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(ip>>>26)|0,ip&=67108863,b=Math.imul(Be,qe),d=Math.imul(Be,He),d=d+Math.imul(je,qe)|0,E=Math.imul(je,He),b=b+Math.imul(Le,$e)|0,d=d+Math.imul(Le,We)|0,d=d+Math.imul(De,$e)|0,E=E+Math.imul(De,We)|0,b=b+Math.imul(Ie,Ge)|0,d=d+Math.imul(Ie,ze)|0,d=d+Math.imul(Ne,Ge)|0,E=E+Math.imul(Ne,ze)|0,b=b+Math.imul(Me,Ve)|0,d=d+Math.imul(Me,Ke)|0,d=d+Math.imul(Pe,Ve)|0,E=E+Math.imul(Pe,Ke)|0,b=b+Math.imul(oe,Ye)|0,d=d+Math.imul(oe,Je)|0,d=d+Math.imul(Oe,Ye)|0,E=E+Math.imul(Oe,Je)|0,b=b+Math.imul(Z,Xe)|0,d=d+Math.imul(Z,Ze)|0,d=d+Math.imul(J,Xe)|0,E=E+Math.imul(J,Ze)|0,b=b+Math.imul(D,Qe)|0,d=d+Math.imul(D,et)|0,d=d+Math.imul(W,Qe)|0,E=E+Math.imul(W,et)|0,b=b+Math.imul(ne,tt)|0,d=d+Math.imul(ne,rt)|0,d=d+Math.imul(N,tt)|0,E=E+Math.imul(N,rt)|0,b=b+Math.imul(z,nt)|0,d=d+Math.imul(z,it)|0,d=d+Math.imul(U,nt)|0,E=E+Math.imul(U,it)|0;var sp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(sp>>>26)|0,sp&=67108863,b=Math.imul(Be,$e),d=Math.imul(Be,We),d=d+Math.imul(je,$e)|0,E=Math.imul(je,We),b=b+Math.imul(Le,Ge)|0,d=d+Math.imul(Le,ze)|0,d=d+Math.imul(De,Ge)|0,E=E+Math.imul(De,ze)|0,b=b+Math.imul(Ie,Ve)|0,d=d+Math.imul(Ie,Ke)|0,d=d+Math.imul(Ne,Ve)|0,E=E+Math.imul(Ne,Ke)|0,b=b+Math.imul(Me,Ye)|0,d=d+Math.imul(Me,Je)|0,d=d+Math.imul(Pe,Ye)|0,E=E+Math.imul(Pe,Je)|0,b=b+Math.imul(oe,Xe)|0,d=d+Math.imul(oe,Ze)|0,d=d+Math.imul(Oe,Xe)|0,E=E+Math.imul(Oe,Ze)|0,b=b+Math.imul(Z,Qe)|0,d=d+Math.imul(Z,et)|0,d=d+Math.imul(J,Qe)|0,E=E+Math.imul(J,et)|0,b=b+Math.imul(D,tt)|0,d=d+Math.imul(D,rt)|0,d=d+Math.imul(W,tt)|0,E=E+Math.imul(W,rt)|0,b=b+Math.imul(ne,nt)|0,d=d+Math.imul(ne,it)|0,d=d+Math.imul(N,nt)|0,E=E+Math.imul(N,it)|0;var op=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(op>>>26)|0,op&=67108863,b=Math.imul(Be,Ge),d=Math.imul(Be,ze),d=d+Math.imul(je,Ge)|0,E=Math.imul(je,ze),b=b+Math.imul(Le,Ve)|0,d=d+Math.imul(Le,Ke)|0,d=d+Math.imul(De,Ve)|0,E=E+Math.imul(De,Ke)|0,b=b+Math.imul(Ie,Ye)|0,d=d+Math.imul(Ie,Je)|0,d=d+Math.imul(Ne,Ye)|0,E=E+Math.imul(Ne,Je)|0,b=b+Math.imul(Me,Xe)|0,d=d+Math.imul(Me,Ze)|0,d=d+Math.imul(Pe,Xe)|0,E=E+Math.imul(Pe,Ze)|0,b=b+Math.imul(oe,Qe)|0,d=d+Math.imul(oe,et)|0,d=d+Math.imul(Oe,Qe)|0,E=E+Math.imul(Oe,et)|0,b=b+Math.imul(Z,tt)|0,d=d+Math.imul(Z,rt)|0,d=d+Math.imul(J,tt)|0,E=E+Math.imul(J,rt)|0,b=b+Math.imul(D,nt)|0,d=d+Math.imul(D,it)|0,d=d+Math.imul(W,nt)|0,E=E+Math.imul(W,it)|0;var ap=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(ap>>>26)|0,ap&=67108863,b=Math.imul(Be,Ve),d=Math.imul(Be,Ke),d=d+Math.imul(je,Ve)|0,E=Math.imul(je,Ke),b=b+Math.imul(Le,Ye)|0,d=d+Math.imul(Le,Je)|0,d=d+Math.imul(De,Ye)|0,E=E+Math.imul(De,Je)|0,b=b+Math.imul(Ie,Xe)|0,d=d+Math.imul(Ie,Ze)|0,d=d+Math.imul(Ne,Xe)|0,E=E+Math.imul(Ne,Ze)|0,b=b+Math.imul(Me,Qe)|0,d=d+Math.imul(Me,et)|0,d=d+Math.imul(Pe,Qe)|0,E=E+Math.imul(Pe,et)|0,b=b+Math.imul(oe,tt)|0,d=d+Math.imul(oe,rt)|0,d=d+Math.imul(Oe,tt)|0,E=E+Math.imul(Oe,rt)|0,b=b+Math.imul(Z,nt)|0,d=d+Math.imul(Z,it)|0,d=d+Math.imul(J,nt)|0,E=E+Math.imul(J,it)|0;var cp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(cp>>>26)|0,cp&=67108863,b=Math.imul(Be,Ye),d=Math.imul(Be,Je),d=d+Math.imul(je,Ye)|0,E=Math.imul(je,Je),b=b+Math.imul(Le,Xe)|0,d=d+Math.imul(Le,Ze)|0,d=d+Math.imul(De,Xe)|0,E=E+Math.imul(De,Ze)|0,b=b+Math.imul(Ie,Qe)|0,d=d+Math.imul(Ie,et)|0,d=d+Math.imul(Ne,Qe)|0,E=E+Math.imul(Ne,et)|0,b=b+Math.imul(Me,tt)|0,d=d+Math.imul(Me,rt)|0,d=d+Math.imul(Pe,tt)|0,E=E+Math.imul(Pe,rt)|0,b=b+Math.imul(oe,nt)|0,d=d+Math.imul(oe,it)|0,d=d+Math.imul(Oe,nt)|0,E=E+Math.imul(Oe,it)|0;var lp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(lp>>>26)|0,lp&=67108863,b=Math.imul(Be,Xe),d=Math.imul(Be,Ze),d=d+Math.imul(je,Xe)|0,E=Math.imul(je,Ze),b=b+Math.imul(Le,Qe)|0,d=d+Math.imul(Le,et)|0,d=d+Math.imul(De,Qe)|0,E=E+Math.imul(De,et)|0,b=b+Math.imul(Ie,tt)|0,d=d+Math.imul(Ie,rt)|0,d=d+Math.imul(Ne,tt)|0,E=E+Math.imul(Ne,rt)|0,b=b+Math.imul(Me,nt)|0,d=d+Math.imul(Me,it)|0,d=d+Math.imul(Pe,nt)|0,E=E+Math.imul(Pe,it)|0;var up=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(up>>>26)|0,up&=67108863,b=Math.imul(Be,Qe),d=Math.imul(Be,et),d=d+Math.imul(je,Qe)|0,E=Math.imul(je,et),b=b+Math.imul(Le,tt)|0,d=d+Math.imul(Le,rt)|0,d=d+Math.imul(De,tt)|0,E=E+Math.imul(De,rt)|0,b=b+Math.imul(Ie,nt)|0,d=d+Math.imul(Ie,it)|0,d=d+Math.imul(Ne,nt)|0,E=E+Math.imul(Ne,it)|0;var pp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(pp>>>26)|0,pp&=67108863,b=Math.imul(Be,tt),d=Math.imul(Be,rt),d=d+Math.imul(je,tt)|0,E=Math.imul(je,rt),b=b+Math.imul(Le,nt)|0,d=d+Math.imul(Le,it)|0,d=d+Math.imul(De,nt)|0,E=E+Math.imul(De,it)|0;var fp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(fp>>>26)|0,fp&=67108863,b=Math.imul(Be,nt),d=Math.imul(Be,it),d=d+Math.imul(je,nt)|0,E=Math.imul(je,it);var dp=(C+b|0)+((d&8191)<<13)|0;return C=(E+(d>>>13)|0)+(dp>>>26)|0,dp&=67108863,_[0]=Yu,_[1]=Ju,_[2]=Xu,_[3]=Zu,_[4]=Qu,_[5]=ep,_[6]=tp,_[7]=rp,_[8]=np,_[9]=ip,_[10]=sp,_[11]=op,_[12]=ap,_[13]=cp,_[14]=lp,_[15]=up,_[16]=pp,_[17]=fp,_[18]=dp,C!==0&&(_[19]=C,y.length++),y};Math.imul||(x=v);function S(T,u,m){m.negative=u.negative^T.negative,m.length=T.length+u.length;for(var y=0,w=0,g=0;g<m.length-1;g++){var _=w;w=0;for(var C=y&67108863,b=Math.min(g,u.length-1),d=Math.max(0,g-T.length+1);d<=b;d++){var E=g-d,q=T.words[E]|0,O=u.words[d]|0,M=q*O,j=M&67108863;_=_+(M/67108864|0)|0,j=j+C|0,C=j&67108863,_=_+(j>>>26)|0,w+=_>>>26,_&=67108863}m.words[g]=C,y=_,_=w}return y!==0?m.words[g]=y:m.length--,m.strip()}function A(T,u,m){var y=new k;return y.mulp(T,u,m)}i.prototype.mulTo=function(u,m){var y,w=this.length+u.length;return this.length===10&&u.length===10?y=x(this,u,m):w<63?y=v(this,u,m):w<1024?y=S(this,u,m):y=A(this,u,m),y};function k(T,u){this.x=T,this.y=u}k.prototype.makeRBT=function(u){for(var m=new Array(u),y=i.prototype._countBits(u)-1,w=0;w<u;w++)m[w]=this.revBin(w,y,u);return m},k.prototype.revBin=function(u,m,y){if(u===0||u===y-1)return u;for(var w=0,g=0;g<m;g++)w|=(u&1)<<m-g-1,u>>=1;return w},k.prototype.permute=function(u,m,y,w,g,_){for(var C=0;C<_;C++)w[C]=m[u[C]],g[C]=y[u[C]]},k.prototype.transform=function(u,m,y,w,g,_){this.permute(_,u,m,y,w,g);for(var C=1;C<g;C<<=1)for(var b=C<<1,d=Math.cos(2*Math.PI/b),E=Math.sin(2*Math.PI/b),q=0;q<g;q+=b)for(var O=d,M=E,j=0;j<C;j++){var z=y[q+j],U=w[q+j],Te=y[q+j+C],ne=w[q+j+C],N=O*Te-M*ne;ne=O*ne+M*Te,Te=N,y[q+j]=z+Te,w[q+j]=U+ne,y[q+j+C]=z-Te,w[q+j+C]=U-ne,j!==b&&(N=d*O-E*M,M=d*M+E*O,O=N)}},k.prototype.guessLen13b=function(u,m){var y=Math.max(m,u)|1,w=y&1,g=0;for(y=y/2|0;y;y=y>>>1)g++;return 1<<g+1+w},k.prototype.conjugate=function(u,m,y){if(!(y<=1))for(var w=0;w<y/2;w++){var g=u[w];u[w]=u[y-w-1],u[y-w-1]=g,g=m[w],m[w]=-m[y-w-1],m[y-w-1]=-g}},k.prototype.normalize13b=function(u,m){for(var y=0,w=0;w<m/2;w++){var g=Math.round(u[2*w+1]/m)*8192+Math.round(u[2*w]/m)+y;u[w]=g&67108863,g<67108864?y=0:y=g/67108864|0}return u},k.prototype.convert13b=function(u,m,y,w){for(var g=0,_=0;_<m;_++)g=g+(u[_]|0),y[2*_]=g&8191,g=g>>>13,y[2*_+1]=g&8191,g=g>>>13;for(_=2*m;_<w;++_)y[_]=0;t(g===0),t((g&-8192)===0)},k.prototype.stub=function(u){for(var m=new Array(u),y=0;y<u;y++)m[y]=0;return m},k.prototype.mulp=function(u,m,y){var w=2*this.guessLen13b(u.length,m.length),g=this.makeRBT(w),_=this.stub(w),C=new Array(w),b=new Array(w),d=new Array(w),E=new Array(w),q=new Array(w),O=new Array(w),M=y.words;M.length=w,this.convert13b(u.words,u.length,C,w),this.convert13b(m.words,m.length,E,w),this.transform(C,_,b,d,w,g),this.transform(E,_,q,O,w,g);for(var j=0;j<w;j++){var z=b[j]*q[j]-d[j]*O[j];d[j]=b[j]*O[j]+d[j]*q[j],b[j]=z}return this.conjugate(b,d,w),this.transform(b,d,M,_,w,g),this.conjugate(M,_,w),this.normalize13b(M,w),y.negative=u.negative^m.negative,y.length=u.length+m.length,y.strip()},i.prototype.mul=function(u){var m=new i(null);return m.words=new Array(this.length+u.length),this.mulTo(u,m)},i.prototype.mulf=function(u){var m=new i(null);return m.words=new Array(this.length+u.length),A(this,u,m)},i.prototype.imul=function(u){return this.clone().mulTo(u,this)},i.prototype.imuln=function(u){t(typeof u=="number"),t(u<67108864);for(var m=0,y=0;y<this.length;y++){var w=(this.words[y]|0)*u,g=(w&67108863)+(m&67108863);m>>=26,m+=w/67108864|0,m+=g>>>26,this.words[y]=g&67108863}return m!==0&&(this.words[y]=m,this.length++),this.length=u===0?1:this.length,this},i.prototype.muln=function(u){return this.clone().imuln(u)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(u){var m=h(u);if(m.length===0)return new i(1);for(var y=this,w=0;w<m.length&&m[w]===0;w++,y=y.sqr());if(++w<m.length)for(var g=y.sqr();w<m.length;w++,g=g.sqr())m[w]!==0&&(y=y.mul(g));return y},i.prototype.iushln=function(u){t(typeof u=="number"&&u>=0);var m=u%26,y=(u-m)/26,w=67108863>>>26-m<<26-m,g;if(m!==0){var _=0;for(g=0;g<this.length;g++){var C=this.words[g]&w,b=(this.words[g]|0)-C<<m;this.words[g]=b|_,_=C>>>26-m}_&&(this.words[g]=_,this.length++)}if(y!==0){for(g=this.length-1;g>=0;g--)this.words[g+y]=this.words[g];for(g=0;g<y;g++)this.words[g]=0;this.length+=y}return this.strip()},i.prototype.ishln=function(u){return t(this.negative===0),this.iushln(u)},i.prototype.iushrn=function(u,m,y){t(typeof u=="number"&&u>=0);var w;m?w=(m-m%26)/26:w=0;var g=u%26,_=Math.min((u-g)/26,this.length),C=67108863^67108863>>>g<<g,b=y;if(w-=_,w=Math.max(0,w),b){for(var d=0;d<_;d++)b.words[d]=this.words[d];b.length=_}if(_!==0)if(this.length>_)for(this.length-=_,d=0;d<this.length;d++)this.words[d]=this.words[d+_];else this.words[0]=0,this.length=1;var E=0;for(d=this.length-1;d>=0&&(E!==0||d>=w);d--){var q=this.words[d]|0;this.words[d]=E<<26-g|q>>>g,E=q&C}return b&&E!==0&&(b.words[b.length++]=E),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(u,m,y){return t(this.negative===0),this.iushrn(u,m,y)},i.prototype.shln=function(u){return this.clone().ishln(u)},i.prototype.ushln=function(u){return this.clone().iushln(u)},i.prototype.shrn=function(u){return this.clone().ishrn(u)},i.prototype.ushrn=function(u){return this.clone().iushrn(u)},i.prototype.testn=function(u){t(typeof u=="number"&&u>=0);var m=u%26,y=(u-m)/26,w=1<<m;if(this.length<=y)return!1;var g=this.words[y];return!!(g&w)},i.prototype.imaskn=function(u){t(typeof u=="number"&&u>=0);var m=u%26,y=(u-m)/26;if(t(this.negative===0,"imaskn works only with positive numbers"),this.length<=y)return this;if(m!==0&&y++,this.length=Math.min(y,this.length),m!==0){var w=67108863^67108863>>>m<<m;this.words[this.length-1]&=w}return this.length===0&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.maskn=function(u){return this.clone().imaskn(u)},i.prototype.iaddn=function(u){return t(typeof u=="number"),t(u<67108864),u<0?this.isubn(-u):this.negative!==0?this.length===1&&(this.words[0]|0)<u?(this.words[0]=u-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(u),this.negative=1,this):this._iaddn(u)},i.prototype._iaddn=function(u){this.words[0]+=u;for(var m=0;m<this.length&&this.words[m]>=67108864;m++)this.words[m]-=67108864,m===this.length-1?this.words[m+1]=1:this.words[m+1]++;return this.length=Math.max(this.length,m+1),this},i.prototype.isubn=function(u){if(t(typeof u=="number"),t(u<67108864),u<0)return this.iaddn(-u);if(this.negative!==0)return this.negative=0,this.iaddn(u),this.negative=1,this;if(this.words[0]-=u,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var m=0;m<this.length&&this.words[m]<0;m++)this.words[m]+=67108864,this.words[m+1]-=1;return this.strip()},i.prototype.addn=function(u){return this.clone().iaddn(u)},i.prototype.subn=function(u){return this.clone().isubn(u)},i.prototype.iabs=function(){return this.negative=0,this},i.prototype.abs=function(){return this.clone().iabs()},i.prototype._ishlnsubmul=function(u,m,y){var w=u.length+y,g;this._expand(w);var _,C=0;for(g=0;g<u.length;g++){_=(this.words[g+y]|0)+C;var b=(u.words[g]|0)*m;_-=b&67108863,C=(_>>26)-(b/67108864|0),this.words[g+y]=_&67108863}for(;g<this.length-y;g++)_=(this.words[g+y]|0)+C,C=_>>26,this.words[g+y]=_&67108863;if(C===0)return this.strip();for(t(C===-1),C=0,g=0;g<this.length;g++)_=-(this.words[g]|0)+C,C=_>>26,this.words[g]=_&67108863;return this.negative=1,this.strip()},i.prototype._wordDiv=function(u,m){var y=this.length-u.length,w=this.clone(),g=u,_=g.words[g.length-1]|0,C=this._countBits(_);y=26-C,y!==0&&(g=g.ushln(y),w.iushln(y),_=g.words[g.length-1]|0);var b=w.length-g.length,d;if(m!=="mod"){d=new i(null),d.length=b+1,d.words=new Array(d.length);for(var E=0;E<d.length;E++)d.words[E]=0}var q=w.clone()._ishlnsubmul(g,1,b);q.negative===0&&(w=q,d&&(d.words[b]=1));for(var O=b-1;O>=0;O--){var M=(w.words[g.length+O]|0)*67108864+(w.words[g.length+O-1]|0);for(M=Math.min(M/_|0,67108863),w._ishlnsubmul(g,M,O);w.negative!==0;)M--,w.negative=0,w._ishlnsubmul(g,1,O),w.isZero()||(w.negative^=1);d&&(d.words[O]=M)}return d&&d.strip(),w.strip(),m!=="div"&&y!==0&&w.iushrn(y),{div:d||null,mod:w}},i.prototype.divmod=function(u,m,y){if(t(!u.isZero()),this.isZero())return{div:new i(0),mod:new i(0)};var w,g,_;return this.negative!==0&&u.negative===0?(_=this.neg().divmod(u,m),m!=="mod"&&(w=_.div.neg()),m!=="div"&&(g=_.mod.neg(),y&&g.negative!==0&&g.iadd(u)),{div:w,mod:g}):this.negative===0&&u.negative!==0?(_=this.divmod(u.neg(),m),m!=="mod"&&(w=_.div.neg()),{div:w,mod:_.mod}):(this.negative&u.negative)!==0?(_=this.neg().divmod(u.neg(),m),m!=="div"&&(g=_.mod.neg(),y&&g.negative!==0&&g.isub(u)),{div:_.div,mod:g}):u.length>this.length||this.cmp(u)<0?{div:new i(0),mod:this}:u.length===1?m==="div"?{div:this.divn(u.words[0]),mod:null}:m==="mod"?{div:null,mod:new i(this.modn(u.words[0]))}:{div:this.divn(u.words[0]),mod:new i(this.modn(u.words[0]))}:this._wordDiv(u,m)},i.prototype.div=function(u){return this.divmod(u,"div",!1).div},i.prototype.mod=function(u){return this.divmod(u,"mod",!1).mod},i.prototype.umod=function(u){return this.divmod(u,"mod",!0).mod},i.prototype.divRound=function(u){var m=this.divmod(u);if(m.mod.isZero())return m.div;var y=m.div.negative!==0?m.mod.isub(u):m.mod,w=u.ushrn(1),g=u.andln(1),_=y.cmp(w);return _<0||g===1&&_===0?m.div:m.div.negative!==0?m.div.isubn(1):m.div.iaddn(1)},i.prototype.modn=function(u){t(u<=67108863);for(var m=(1<<26)%u,y=0,w=this.length-1;w>=0;w--)y=(m*y+(this.words[w]|0))%u;return y},i.prototype.idivn=function(u){t(u<=67108863);for(var m=0,y=this.length-1;y>=0;y--){var w=(this.words[y]|0)+m*67108864;this.words[y]=w/u|0,m=w%u}return this.strip()},i.prototype.divn=function(u){return this.clone().idivn(u)},i.prototype.egcd=function(u){t(u.negative===0),t(!u.isZero());var m=this,y=u.clone();m.negative!==0?m=m.umod(u):m=m.clone();for(var w=new i(1),g=new i(0),_=new i(0),C=new i(1),b=0;m.isEven()&&y.isEven();)m.iushrn(1),y.iushrn(1),++b;for(var d=y.clone(),E=m.clone();!m.isZero();){for(var q=0,O=1;(m.words[0]&O)===0&&q<26;++q,O<<=1);if(q>0)for(m.iushrn(q);q-- >0;)(w.isOdd()||g.isOdd())&&(w.iadd(d),g.isub(E)),w.iushrn(1),g.iushrn(1);for(var M=0,j=1;(y.words[0]&j)===0&&M<26;++M,j<<=1);if(M>0)for(y.iushrn(M);M-- >0;)(_.isOdd()||C.isOdd())&&(_.iadd(d),C.isub(E)),_.iushrn(1),C.iushrn(1);m.cmp(y)>=0?(m.isub(y),w.isub(_),g.isub(C)):(y.isub(m),_.isub(w),C.isub(g))}return{a:_,b:C,gcd:y.iushln(b)}},i.prototype._invmp=function(u){t(u.negative===0),t(!u.isZero());var m=this,y=u.clone();m.negative!==0?m=m.umod(u):m=m.clone();for(var w=new i(1),g=new i(0),_=y.clone();m.cmpn(1)>0&&y.cmpn(1)>0;){for(var C=0,b=1;(m.words[0]&b)===0&&C<26;++C,b<<=1);if(C>0)for(m.iushrn(C);C-- >0;)w.isOdd()&&w.iadd(_),w.iushrn(1);for(var d=0,E=1;(y.words[0]&E)===0&&d<26;++d,E<<=1);if(d>0)for(y.iushrn(d);d-- >0;)g.isOdd()&&g.iadd(_),g.iushrn(1);m.cmp(y)>=0?(m.isub(y),w.isub(g)):(y.isub(m),g.isub(w))}var q;return m.cmpn(1)===0?q=w:q=g,q.cmpn(0)<0&&q.iadd(u),q},i.prototype.gcd=function(u){if(this.isZero())return u.abs();if(u.isZero())return this.abs();var m=this.clone(),y=u.clone();m.negative=0,y.negative=0;for(var w=0;m.isEven()&&y.isEven();w++)m.iushrn(1),y.iushrn(1);do{for(;m.isEven();)m.iushrn(1);for(;y.isEven();)y.iushrn(1);var g=m.cmp(y);if(g<0){var _=m;m=y,y=_}else if(g===0||y.cmpn(1)===0)break;m.isub(y)}while(!0);return y.iushln(w)},i.prototype.invm=function(u){return this.egcd(u).a.umod(u)},i.prototype.isEven=function(){return(this.words[0]&1)===0},i.prototype.isOdd=function(){return(this.words[0]&1)===1},i.prototype.andln=function(u){return this.words[0]&u},i.prototype.bincn=function(u){t(typeof u=="number");var m=u%26,y=(u-m)/26,w=1<<m;if(this.length<=y)return this._expand(y+1),this.words[y]|=w,this;for(var g=w,_=y;g!==0&&_<this.length;_++){var C=this.words[_]|0;C+=g,g=C>>>26,C&=67108863,this.words[_]=C}return g!==0&&(this.words[_]=g,this.length++),this},i.prototype.isZero=function(){return this.length===1&&this.words[0]===0},i.prototype.cmpn=function(u){var m=u<0;if(this.negative!==0&&!m)return-1;if(this.negative===0&&m)return 1;this.strip();var y;if(this.length>1)y=1;else{m&&(u=-u),t(u<=67108863,"Number is too big");var w=this.words[0]|0;y=w===u?0:w<u?-1:1}return this.negative!==0?-y|0:y},i.prototype.cmp=function(u){if(this.negative!==0&&u.negative===0)return-1;if(this.negative===0&&u.negative!==0)return 1;var m=this.ucmp(u);return this.negative!==0?-m|0:m},i.prototype.ucmp=function(u){if(this.length>u.length)return 1;if(this.length<u.length)return-1;for(var m=0,y=this.length-1;y>=0;y--){var w=this.words[y]|0,g=u.words[y]|0;if(w!==g){w<g?m=-1:w>g&&(m=1);break}}return m},i.prototype.gtn=function(u){return this.cmpn(u)===1},i.prototype.gt=function(u){return this.cmp(u)===1},i.prototype.gten=function(u){return this.cmpn(u)>=0},i.prototype.gte=function(u){return this.cmp(u)>=0},i.prototype.ltn=function(u){return this.cmpn(u)===-1},i.prototype.lt=function(u){return this.cmp(u)===-1},i.prototype.lten=function(u){return this.cmpn(u)<=0},i.prototype.lte=function(u){return this.cmp(u)<=0},i.prototype.eqn=function(u){return this.cmpn(u)===0},i.prototype.eq=function(u){return this.cmp(u)===0},i.red=function(u){return new L(u)},i.prototype.toRed=function(u){return t(!this.red,"Already a number in reduction context"),t(this.negative===0,"red works only with positives"),u.convertTo(this)._forceRed(u)},i.prototype.fromRed=function(){return t(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(u){return this.red=u,this},i.prototype.forceRed=function(u){return t(!this.red,"Already a number in reduction context"),this._forceRed(u)},i.prototype.redAdd=function(u){return t(this.red,"redAdd works only with red numbers"),this.red.add(this,u)},i.prototype.redIAdd=function(u){return t(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,u)},i.prototype.redSub=function(u){return t(this.red,"redSub works only with red numbers"),this.red.sub(this,u)},i.prototype.redISub=function(u){return t(this.red,"redISub works only with red numbers"),this.red.isub(this,u)},i.prototype.redShl=function(u){return t(this.red,"redShl works only with red numbers"),this.red.shl(this,u)},i.prototype.redMul=function(u){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,u),this.red.mul(this,u)},i.prototype.redIMul=function(u){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,u),this.red.imul(this,u)},i.prototype.redSqr=function(){return t(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return t(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return t(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return t(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return t(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(u){return t(this.red&&!u.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,u)};var P={k256:null,p224:null,p192:null,p25519:null};function I(T,u){this.name=T,this.p=new i(u,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}I.prototype._tmp=function(){var u=new i(null);return u.words=new Array(Math.ceil(this.n/13)),u},I.prototype.ireduce=function(u){var m=u,y;do this.split(m,this.tmp),m=this.imulK(m),m=m.iadd(this.tmp),y=m.bitLength();while(y>this.n);var w=y<this.n?-1:m.ucmp(this.p);return w===0?(m.words[0]=0,m.length=1):w>0?m.isub(this.p):m.strip!==void 0?m.strip():m._strip(),m},I.prototype.split=function(u,m){u.iushrn(this.n,0,m)},I.prototype.imulK=function(u){return u.imul(this.k)};function B(){I.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(B,I),B.prototype.split=function(u,m){for(var y=4194303,w=Math.min(u.length,9),g=0;g<w;g++)m.words[g]=u.words[g];if(m.length=w,u.length<=9){u.words[0]=0,u.length=1;return}var _=u.words[9];for(m.words[m.length++]=_&y,g=10;g<u.length;g++){var C=u.words[g]|0;u.words[g-10]=(C&y)<<4|_>>>22,_=C}_>>>=22,u.words[g-10]=_,_===0&&u.length>10?u.length-=10:u.length-=9},B.prototype.imulK=function(u){u.words[u.length]=0,u.words[u.length+1]=0,u.length+=2;for(var m=0,y=0;y<u.length;y++){var w=u.words[y]|0;m+=w*977,u.words[y]=m&67108863,m=w*64+(m/67108864|0)}return u.words[u.length-1]===0&&(u.length--,u.words[u.length-1]===0&&u.length--),u};function V(){I.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}n(V,I);function F(){I.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(F,I);function G(){I.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(G,I),G.prototype.imulK=function(u){for(var m=0,y=0;y<u.length;y++){var w=(u.words[y]|0)*19+m,g=w&67108863;w>>>=26,u.words[y]=g,m=w}return m!==0&&(u.words[u.length++]=m),u},i._prime=function(u){if(P[u])return P[u];var m;if(u==="k256")m=new B;else if(u==="p224")m=new V;else if(u==="p192")m=new F;else if(u==="p25519")m=new G;else throw new Error("Unknown prime "+u);return P[u]=m,m};function L(T){if(typeof T=="string"){var u=i._prime(T);this.m=u.p,this.prime=u}else t(T.gtn(1),"modulus must be greater than 1"),this.m=T,this.prime=null}L.prototype._verify1=function(u){t(u.negative===0,"red works only with positives"),t(u.red,"red works only with red numbers")},L.prototype._verify2=function(u,m){t((u.negative|m.negative)===0,"red works only with positives"),t(u.red&&u.red===m.red,"red works only with red numbers")},L.prototype.imod=function(u){return this.prime?this.prime.ireduce(u)._forceRed(this):u.umod(this.m)._forceRed(this)},L.prototype.neg=function(u){return u.isZero()?u.clone():this.m.sub(u)._forceRed(this)},L.prototype.add=function(u,m){this._verify2(u,m);var y=u.add(m);return y.cmp(this.m)>=0&&y.isub(this.m),y._forceRed(this)},L.prototype.iadd=function(u,m){this._verify2(u,m);var y=u.iadd(m);return y.cmp(this.m)>=0&&y.isub(this.m),y},L.prototype.sub=function(u,m){this._verify2(u,m);var y=u.sub(m);return y.cmpn(0)<0&&y.iadd(this.m),y._forceRed(this)},L.prototype.isub=function(u,m){this._verify2(u,m);var y=u.isub(m);return y.cmpn(0)<0&&y.iadd(this.m),y},L.prototype.shl=function(u,m){return this._verify1(u),this.imod(u.ushln(m))},L.prototype.imul=function(u,m){return this._verify2(u,m),this.imod(u.imul(m))},L.prototype.mul=function(u,m){return this._verify2(u,m),this.imod(u.mul(m))},L.prototype.isqr=function(u){return this.imul(u,u.clone())},L.prototype.sqr=function(u){return this.mul(u,u)},L.prototype.sqrt=function(u){if(u.isZero())return u.clone();var m=this.m.andln(3);if(t(m%2===1),m===3){var y=this.m.add(new i(1)).iushrn(2);return this.pow(u,y)}for(var w=this.m.subn(1),g=0;!w.isZero()&&w.andln(1)===0;)g++,w.iushrn(1);t(!w.isZero());var _=new i(1).toRed(this),C=_.redNeg(),b=this.m.subn(1).iushrn(1),d=this.m.bitLength();for(d=new i(2*d*d).toRed(this);this.pow(d,b).cmp(C)!==0;)d.redIAdd(C);for(var E=this.pow(d,w),q=this.pow(u,w.addn(1).iushrn(1)),O=this.pow(u,w),M=g;O.cmp(_)!==0;){for(var j=O,z=0;j.cmp(_)!==0;z++)j=j.redSqr();t(z<M);var U=this.pow(E,new i(1).iushln(M-z-1));q=q.redMul(U),E=U.redSqr(),O=O.redMul(E),M=z}return q},L.prototype.invm=function(u){var m=u._invmp(this.m);return m.negative!==0?(m.negative=0,this.imod(m).redNeg()):this.imod(m)},L.prototype.pow=function(u,m){if(m.isZero())return new i(1).toRed(this);if(m.cmpn(1)===0)return u.clone();var y=4,w=new Array(1<<y);w[0]=new i(1).toRed(this),w[1]=u;for(var g=2;g<w.length;g++)w[g]=this.mul(w[g-1],u);var _=w[0],C=0,b=0,d=m.bitLength()%26;for(d===0&&(d=26),g=m.length-1;g>=0;g--){for(var E=m.words[g],q=d-1;q>=0;q--){var O=E>>q&1;if(_!==w[0]&&(_=this.sqr(_)),O===0&&C===0){b=0;continue}C<<=1,C|=O,b++,!(b!==y&&(g!==0||q!==0))&&(_=this.mul(_,w[C]),b=0,C=0)}d=26}return _},L.prototype.convertTo=function(u){var m=u.umod(this.m);return m===u?m.clone():m},L.prototype.convertFrom=function(u){var m=u.clone();return m.red=null,m},i.mont=function(u){return new H(u)};function H(T){L.call(this,T),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new i(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}n(H,L),H.prototype.convertTo=function(u){return this.imod(u.ushln(this.shift))},H.prototype.convertFrom=function(u){var m=this.imod(u.mul(this.rinv));return m.red=null,m},H.prototype.imul=function(u,m){if(u.isZero()||m.isZero())return u.words[0]=0,u.length=1,u;var y=u.imul(m),w=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),g=y.isub(w).iushrn(this.shift),_=g;return g.cmp(this.m)>=0?_=g.isub(this.m):g.cmpn(0)<0&&(_=g.iadd(this.m)),_._forceRed(this)},H.prototype.mul=function(u,m){if(u.isZero()||m.isZero())return new i(0)._forceRed(this);var y=u.mul(m),w=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),g=y.isub(w).iushrn(this.shift),_=g;return g.cmp(this.m)>=0?_=g.isub(this.m):g.cmpn(0)<0&&(_=g.iadd(this.m)),_._forceRed(this)},H.prototype.invm=function(u){var m=this.imod(u._invmp(this.m).mul(this.r2));return m._forceRed(this)}})(typeof Oh>"u"||Oh,WS)});var GS=R((iW,Ph)=>{typeof Object.create=="function"?Ph.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Ph.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}});var qn=R((sW,Nh)=>{try{if(Ih=require("util"),typeof Ih.inherits!="function")throw"";Nh.exports=Ih.inherits}catch{Nh.exports=GS()}var Ih});var ql=R((oW,zS)=>{"use strict";var Ul=require("buffer"),Cs=Ul.Buffer,cr={},lr;for(lr in Ul)Ul.hasOwnProperty(lr)&&(lr==="SlowBuffer"||lr==="Buffer"||(cr[lr]=Ul[lr]));var As=cr.Buffer={};for(lr in Cs)Cs.hasOwnProperty(lr)&&(lr==="allocUnsafe"||lr==="allocUnsafeSlow"||(As[lr]=Cs[lr]));cr.Buffer.prototype=Cs.prototype;(!As.from||As.from===Uint8Array.from)&&(As.from=function(r,e,t){if(typeof r=="number")throw new TypeError('The "value" argument must not be of type number. Received type '+typeof r);if(r&&typeof r.length>"u")throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof r);return Cs(r,e,t)});As.alloc||(As.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError('The "size" argument must be of type number. Received type '+typeof r);if(r<0||r>=2*(1<<30))throw new RangeError('The value "'+r+'" is invalid for option "size"');var n=Cs(r);return!e||e.length===0?n.fill(0):typeof t=="string"?n.fill(e,t):n.fill(e),n});if(!cr.kStringMaxLength)try{cr.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch{}cr.constants||(cr.constants={MAX_LENGTH:cr.kMaxLength},cr.kStringMaxLength&&(cr.constants.MAX_STRING_LENGTH=cr.kStringMaxLength));zS.exports=cr});var Hl=R(VS=>{"use strict";var _B=qn();function ur(r){this._reporterState={obj:null,path:[],options:r||{},errors:[]}}VS.Reporter=ur;ur.prototype.isError=function(e){return e instanceof Rs};ur.prototype.save=function(){let e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}};ur.prototype.restore=function(e){let t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)};ur.prototype.enterKey=function(e){return this._reporterState.path.push(e)};ur.prototype.exitKey=function(e){let t=this._reporterState;t.path=t.path.slice(0,e-1)};ur.prototype.leaveKey=function(e,t,n){let i=this._reporterState;this.exitKey(e),i.obj!==null&&(i.obj[t]=n)};ur.prototype.path=function(){return this._reporterState.path.join("/")};ur.prototype.enterObject=function(){let e=this._reporterState,t=e.obj;return e.obj={},t};ur.prototype.leaveObject=function(e){let t=this._reporterState,n=t.obj;return t.obj=e,n};ur.prototype.error=function(e){let t,n=this._reporterState,i=e instanceof Rs;if(i?t=e:t=new Rs(n.path.map(function(s){return"["+JSON.stringify(s)+"]"}).join(""),e.message||e,e.stack),!n.options.partial)throw t;return i||n.errors.push(t),t};ur.prototype.wrapResult=function(e){let t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e};function Rs(r,e){this.path=r,this.rethrow(e)}_B(Rs,Error);Rs.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,Rs),!this.stack)try{throw new Error(this.message)}catch(t){this.stack=t.stack}return this}});var Ms=R(Lh=>{"use strict";var bB=qn(),$l=Hl().Reporter,ks=ql().Buffer;function pr(r,e){if($l.call(this,e),!ks.isBuffer(r)){this.error("Input not Buffer");return}this.base=r,this.offset=0,this.length=r.length}bB(pr,$l);Lh.DecoderBuffer=pr;pr.isDecoderBuffer=function(e){return e instanceof pr?!0:typeof e=="object"&&ks.isBuffer(e.base)&&e.constructor.name==="DecoderBuffer"&&typeof e.offset=="number"&&typeof e.length=="number"&&typeof e.save=="function"&&typeof e.restore=="function"&&typeof e.isEmpty=="function"&&typeof e.readUInt8=="function"&&typeof e.skip=="function"&&typeof e.raw=="function"};pr.prototype.save=function(){return{offset:this.offset,reporter:$l.prototype.save.call(this)}};pr.prototype.restore=function(e){let t=new pr(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,$l.prototype.restore.call(this,e.reporter),t};pr.prototype.isEmpty=function(){return this.offset===this.length};pr.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")};pr.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");let n=new pr(this.base);return n._reporterState=this._reporterState,n.offset=this.offset,n.length=this.offset+e,this.offset+=e,n};pr.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)};function Os(r,e){if(Array.isArray(r))this.length=0,this.value=r.map(function(t){return Os.isEncoderBuffer(t)||(t=new Os(t,e)),this.length+=t.length,t},this);else if(typeof r=="number"){if(!(0<=r&&r<=255))return e.error("non-byte EncoderBuffer value");this.value=r,this.length=1}else if(typeof r=="string")this.value=r,this.length=ks.byteLength(r);else if(ks.isBuffer(r))this.value=r,this.length=r.length;else return e.error("Unsupported type: "+typeof r)}Lh.EncoderBuffer=Os;Os.isEncoderBuffer=function(e){return e instanceof Os?!0:typeof e=="object"&&e.constructor.name==="EncoderBuffer"&&typeof e.length=="number"&&typeof e.join=="function"};Os.prototype.join=function(e,t){return e||(e=ks.alloc(this.length)),t||(t=0),this.length===0||(Array.isArray(this.value)?this.value.forEach(function(n){n.join(e,t),t+=n.length}):(typeof this.value=="number"?e[t]=this.value:typeof this.value=="string"?e.write(this.value,t):ks.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length)),e}});var JS=R((lW,YS)=>{YS.exports=KS;function KS(r,e){if(!r)throw new Error(e||"Assertion failed")}KS.equal=function(e,t,n){if(e!=t)throw new Error(n||"Assertion failed: "+e+" != "+t)}});var Wl=R((uW,ZS)=>{"use strict";var wB=Hl().Reporter,SB=Ms().EncoderBuffer,EB=Ms().DecoderBuffer,kt=JS(),XS=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],TB=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(XS),CB=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];function de(r,e,t){let n={};this._baseState=n,n.name=t,n.enc=r,n.parent=e||null,n.children=null,n.tag=null,n.args=null,n.reverseArgs=null,n.choice=null,n.optional=!1,n.any=!1,n.obj=!1,n.use=null,n.useDecoder=null,n.key=null,n.default=null,n.explicit=null,n.implicit=null,n.contains=null,n.parent||(n.children=[],this._wrap())}ZS.exports=de;var AB=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];de.prototype.clone=function(){let e=this._baseState,t={};AB.forEach(function(i){t[i]=e[i]});let n=new this.constructor(t.parent);return n._baseState=t,n};de.prototype._wrap=function(){let e=this._baseState;TB.forEach(function(t){this[t]=function(){let i=new this.constructor(this);return e.children.push(i),i[t].apply(i,arguments)}},this)};de.prototype._init=function(e){let t=this._baseState;kt(t.parent===null),e.call(this),t.children=t.children.filter(function(n){return n._baseState.parent===this},this),kt.equal(t.children.length,1,"Root node can have only one child")};de.prototype._useArgs=function(e){let t=this._baseState,n=e.filter(function(i){return i instanceof this.constructor},this);e=e.filter(function(i){return!(i instanceof this.constructor)},this),n.length!==0&&(kt(t.children===null),t.children=n,n.forEach(function(i){i._baseState.parent=this},this)),e.length!==0&&(kt(t.args===null),t.args=e,t.reverseArgs=e.map(function(i){if(typeof i!="object"||i.constructor!==Object)return i;let s={};return Object.keys(i).forEach(function(o){o==(o|0)&&(o|=0);let a=i[o];s[a]=o}),s}))};CB.forEach(function(r){de.prototype[r]=function(){let t=this._baseState;throw new Error(r+" not implemented for encoding: "+t.enc)}});XS.forEach(function(r){de.prototype[r]=function(){let t=this._baseState,n=Array.prototype.slice.call(arguments);return kt(t.tag===null),t.tag=r,this._useArgs(n),this}});de.prototype.use=function(e){kt(e);let t=this._baseState;return kt(t.use===null),t.use=e,this};de.prototype.optional=function(){let e=this._baseState;return e.optional=!0,this};de.prototype.def=function(e){let t=this._baseState;return kt(t.default===null),t.default=e,t.optional=!0,this};de.prototype.explicit=function(e){let t=this._baseState;return kt(t.explicit===null&&t.implicit===null),t.explicit=e,this};de.prototype.implicit=function(e){let t=this._baseState;return kt(t.explicit===null&&t.implicit===null),t.implicit=e,this};de.prototype.obj=function(){let e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,t.length!==0&&this._useArgs(t),this};de.prototype.key=function(e){let t=this._baseState;return kt(t.key===null),t.key=e,this};de.prototype.any=function(){let e=this._baseState;return e.any=!0,this};de.prototype.choice=function(e){let t=this._baseState;return kt(t.choice===null),t.choice=e,this._useArgs(Object.keys(e).map(function(n){return e[n]})),this};de.prototype.contains=function(e){let t=this._baseState;return kt(t.use===null),t.contains=e,this};de.prototype._decode=function(e,t){let n=this._baseState;if(n.parent===null)return e.wrapResult(n.children[0]._decode(e,t));let i=n.default,s=!0,o=null;if(n.key!==null&&(o=e.enterKey(n.key)),n.optional){let c=null;if(n.explicit!==null?c=n.explicit:n.implicit!==null?c=n.implicit:n.tag!==null&&(c=n.tag),c===null&&!n.any){let l=e.save();try{n.choice===null?this._decodeGeneric(n.tag,e,t):this._decodeChoice(e,t),s=!0}catch{s=!1}e.restore(l)}else if(s=this._peekTag(e,c,n.any),e.isError(s))return s}let a;if(n.obj&&s&&(a=e.enterObject()),s){if(n.explicit!==null){let l=this._decodeTag(e,n.explicit);if(e.isError(l))return l;e=l}let c=e.offset;if(n.use===null&&n.choice===null){let l;n.any&&(l=e.save());let p=this._decodeTag(e,n.implicit!==null?n.implicit:n.tag,n.any);if(e.isError(p))return p;n.any?i=e.raw(l):e=p}if(t&&t.track&&n.tag!==null&&t.track(e.path(),c,e.length,"tagged"),t&&t.track&&n.tag!==null&&t.track(e.path(),e.offset,e.length,"content"),n.any||(n.choice===null?i=this._decodeGeneric(n.tag,e,t):i=this._decodeChoice(e,t)),e.isError(i))return i;if(!n.any&&n.choice===null&&n.children!==null&&n.children.forEach(function(p){p._decode(e,t)}),n.contains&&(n.tag==="octstr"||n.tag==="bitstr")){let l=new EB(i);i=this._getUse(n.contains,e._reporterState.obj)._decode(l,t)}}return n.obj&&s&&(i=e.leaveObject(a)),n.key!==null&&(i!==null||s===!0)?e.leaveKey(o,n.key,i):o!==null&&e.exitKey(o),i};de.prototype._decodeGeneric=function(e,t,n){let i=this._baseState;return e==="seq"||e==="set"?null:e==="seqof"||e==="setof"?this._decodeList(t,e,i.args[0],n):/str$/.test(e)?this._decodeStr(t,e,n):e==="objid"&&i.args?this._decodeObjid(t,i.args[0],i.args[1],n):e==="objid"?this._decodeObjid(t,null,null,n):e==="gentime"||e==="utctime"?this._decodeTime(t,e,n):e==="null_"?this._decodeNull(t,n):e==="bool"?this._decodeBool(t,n):e==="objDesc"?this._decodeStr(t,e,n):e==="int"||e==="enum"?this._decodeInt(t,i.args&&i.args[0],n):i.use!==null?this._getUse(i.use,t._reporterState.obj)._decode(t,n):t.error("unknown tag: "+e)};de.prototype._getUse=function(e,t){let n=this._baseState;return n.useDecoder=this._use(e,t),kt(n.useDecoder._baseState.parent===null),n.useDecoder=n.useDecoder._baseState.children[0],n.implicit!==n.useDecoder._baseState.implicit&&(n.useDecoder=n.useDecoder.clone(),n.useDecoder._baseState.implicit=n.implicit),n.useDecoder};de.prototype._decodeChoice=function(e,t){let n=this._baseState,i=null,s=!1;return Object.keys(n.choice).some(function(o){let a=e.save(),c=n.choice[o];try{let l=c._decode(e,t);if(e.isError(l))return!1;i={type:o,value:l},s=!0}catch{return e.restore(a),!1}return!0},this),s?i:e.error("Choice not matched")};de.prototype._createEncoderBuffer=function(e){return new SB(e,this.reporter)};de.prototype._encode=function(e,t,n){let i=this._baseState;if(i.default!==null&&i.default===e)return;let s=this._encodeValue(e,t,n);if(s!==void 0&&!this._skipDefault(s,t,n))return s};de.prototype._encodeValue=function(e,t,n){let i=this._baseState;if(i.parent===null)return i.children[0]._encode(e,t||new wB);let s=null;if(this.reporter=t,i.optional&&e===void 0)if(i.default!==null)e=i.default;else return;let o=null,a=!1;if(i.any)s=this._createEncoderBuffer(e);else if(i.choice)s=this._encodeChoice(e,t);else if(i.contains)o=this._getUse(i.contains,n)._encode(e,t),a=!0;else if(i.children)o=i.children.map(function(c){if(c._baseState.tag==="null_")return c._encode(null,t,e);if(c._baseState.key===null)return t.error("Child should have a key");let l=t.enterKey(c._baseState.key);if(typeof e!="object")return t.error("Child expected, but input is not object");let p=c._encode(e[c._baseState.key],t,e);return t.leaveKey(l),p},this).filter(function(c){return c}),o=this._createEncoderBuffer(o);else if(i.tag==="seqof"||i.tag==="setof"){if(!(i.args&&i.args.length===1))return t.error("Too many args for : "+i.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");let c=this.clone();c._baseState.implicit=null,o=this._createEncoderBuffer(e.map(function(l){let p=this._baseState;return this._getUse(p.args[0],e)._encode(l,t)},c))}else i.use!==null?s=this._getUse(i.use,n)._encode(e,t):(o=this._encodePrimitive(i.tag,e),a=!0);if(!i.any&&i.choice===null){let c=i.implicit!==null?i.implicit:i.tag,l=i.implicit===null?"universal":"context";c===null?i.use===null&&t.error("Tag could be omitted only for .use()"):i.use===null&&(s=this._encodeComposite(c,a,l,o))}return i.explicit!==null&&(s=this._encodeComposite(i.explicit,!1,"context",s)),s};de.prototype._encodeChoice=function(e,t){let n=this._baseState,i=n.choice[e.type];return i||kt(!1,e.type+" not found in "+JSON.stringify(Object.keys(n.choice))),i._encode(e.value,t)};de.prototype._encodePrimitive=function(e,t){let n=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if(e==="objid"&&n.args)return this._encodeObjid(t,n.reverseArgs[0],n.args[1]);if(e==="objid")return this._encodeObjid(t,null,null);if(e==="gentime"||e==="utctime")return this._encodeTime(t,e);if(e==="null_")return this._encodeNull();if(e==="int"||e==="enum")return this._encodeInt(t,n.args&&n.reverseArgs[0]);if(e==="bool")return this._encodeBool(t);if(e==="objDesc")return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)};de.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)};de.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(e)}});var Gl=R(mi=>{"use strict";function QS(r){let e={};return Object.keys(r).forEach(function(t){(t|0)==t&&(t=t|0);let n=r[t];e[n]=t}),e}mi.tagClass={0:"universal",1:"application",2:"context",3:"private"};mi.tagClassByName=QS(mi.tagClass);mi.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"};mi.tagByName=QS(mi.tag)});var Bh=R((fW,rE)=>{"use strict";var RB=qn(),gn=ql().Buffer,eE=Wl(),Dh=Gl();function tE(r){this.enc="der",this.name=r.name,this.entity=r,this.tree=new Cr,this.tree._init(r.body)}rE.exports=tE;tE.prototype.encode=function(e,t){return this.tree._encode(e,t).join()};function Cr(r){eE.call(this,"der",r)}RB(Cr,eE);Cr.prototype._encodeComposite=function(e,t,n,i){let s=kB(e,t,n,this.reporter);if(i.length<128){let c=gn.alloc(2);return c[0]=s,c[1]=i.length,this._createEncoderBuffer([c,i])}let o=1;for(let c=i.length;c>=256;c>>=8)o++;let a=gn.alloc(2+o);a[0]=s,a[1]=128|o;for(let c=1+o,l=i.length;l>0;c--,l>>=8)a[c]=l&255;return this._createEncoderBuffer([a,i])};Cr.prototype._encodeStr=function(e,t){if(t==="bitstr")return this._createEncoderBuffer([e.unused|0,e.data]);if(t==="bmpstr"){let n=gn.alloc(e.length*2);for(let i=0;i<e.length;i++)n.writeUInt16BE(e.charCodeAt(i),i*2);return this._createEncoderBuffer(n)}else return t==="numstr"?this._isNumstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: numstr supports only digits and space"):t==="printstr"?this._isPrintstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark"):/str$/.test(t)?this._createEncoderBuffer(e):t==="objDesc"?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: "+t+" unsupported")};Cr.prototype._encodeObjid=function(e,t,n){if(typeof e=="string"){if(!t)return this.reporter.error("string objid given, but no values map found");if(!t.hasOwnProperty(e))return this.reporter.error("objid not found in values map");e=t[e].split(/[\s.]+/g);for(let a=0;a<e.length;a++)e[a]|=0}else if(Array.isArray(e)){e=e.slice();for(let a=0;a<e.length;a++)e[a]|=0}if(!Array.isArray(e))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(e));if(!n){if(e[1]>=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,e[0]*40+e[1])}let i=0;for(let a=0;a<e.length;a++){let c=e[a];for(i++;c>=128;c>>=7)i++}let s=gn.alloc(i),o=s.length-1;for(let a=e.length-1;a>=0;a--){let c=e[a];for(s[o--]=c&127;(c>>=7)>0;)s[o--]=128|c&127}return this._createEncoderBuffer(s)};function fr(r){return r<10?"0"+r:r}Cr.prototype._encodeTime=function(e,t){let n,i=new Date(e);return t==="gentime"?n=[fr(i.getUTCFullYear()),fr(i.getUTCMonth()+1),fr(i.getUTCDate()),fr(i.getUTCHours()),fr(i.getUTCMinutes()),fr(i.getUTCSeconds()),"Z"].join(""):t==="utctime"?n=[fr(i.getUTCFullYear()%100),fr(i.getUTCMonth()+1),fr(i.getUTCDate()),fr(i.getUTCHours()),fr(i.getUTCMinutes()),fr(i.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(n,"octstr")};Cr.prototype._encodeNull=function(){return this._createEncoderBuffer("")};Cr.prototype._encodeInt=function(e,t){if(typeof e=="string"){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if(typeof e!="number"&&!gn.isBuffer(e)){let s=e.toArray();!e.sign&&s[0]&128&&s.unshift(0),e=gn.from(s)}if(gn.isBuffer(e)){let s=e.length;e.length===0&&s++;let o=gn.alloc(s);return e.copy(o),e.length===0&&(o[0]=0),this._createEncoderBuffer(o)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);let n=1;for(let s=e;s>=256;s>>=8)n++;let i=new Array(n);for(let s=i.length-1;s>=0;s--)i[s]=e&255,e>>=8;return i[0]&128&&i.unshift(0),this._createEncoderBuffer(gn.from(i))};Cr.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)};Cr.prototype._use=function(e,t){return typeof e=="function"&&(e=e(t)),e._getEncoder("der").tree};Cr.prototype._skipDefault=function(e,t,n){let i=this._baseState,s;if(i.default===null)return!1;let o=e.join();if(i.defaultBuffer===void 0&&(i.defaultBuffer=this._encodeValue(i.default,t,n).join()),o.length!==i.defaultBuffer.length)return!1;for(s=0;s<o.length;s++)if(o[s]!==i.defaultBuffer[s])return!1;return!0};function kB(r,e,t,n){let i;if(r==="seqof"?r="seq":r==="setof"&&(r="set"),Dh.tagByName.hasOwnProperty(r))i=Dh.tagByName[r];else if(typeof r=="number"&&(r|0)===r)i=r;else return n.error("Unknown tag: "+r);return i>=31?n.error("Multi-octet tag encoding unsupported"):(e||(i|=32),i|=Dh.tagClassByName[t||"universal"]<<6,i)}});var iE=R((dW,nE)=>{"use strict";var OB=qn(),jh=Bh();function Fh(r){jh.call(this,r),this.enc="pem"}OB(Fh,jh);nE.exports=Fh;Fh.prototype.encode=function(e,t){let i=jh.prototype.encode.call(this,e).toString("base64"),s=["-----BEGIN "+t.label+"-----"];for(let o=0;o<i.length;o+=64)s.push(i.slice(o,o+64));return s.push("-----END "+t.label+"-----"),s.join(`
92
- `)}});var Uh=R(oE=>{"use strict";var sE=oE;sE.der=Bh();sE.pem=iE()});var Hh=R((mW,fE)=>{"use strict";var MB=qn(),PB=Mh(),aE=Ms().DecoderBuffer,lE=Wl(),cE=Gl();function uE(r){this.enc="der",this.name=r.name,this.entity=r,this.tree=new Kt,this.tree._init(r.body)}fE.exports=uE;uE.prototype.decode=function(e,t){return aE.isDecoderBuffer(e)||(e=new aE(e,t)),this.tree._decode(e,t)};function Kt(r){lE.call(this,"der",r)}MB(Kt,lE);Kt.prototype._peekTag=function(e,t,n){if(e.isEmpty())return!1;let i=e.save(),s=qh(e,'Failed to peek tag: "'+t+'"');return e.isError(s)?s:(e.restore(i),s.tag===t||s.tagStr===t||s.tagStr+"of"===t||n)};Kt.prototype._decodeTag=function(e,t,n){let i=qh(e,'Failed to decode tag of "'+t+'"');if(e.isError(i))return i;let s=pE(e,i.primitive,'Failed to get length of "'+t+'"');if(e.isError(s))return s;if(!n&&i.tag!==t&&i.tagStr!==t&&i.tagStr+"of"!==t)return e.error('Failed to match tag: "'+t+'"');if(i.primitive||s!==null)return e.skip(s,'Failed to match body of: "'+t+'"');let o=e.save(),a=this._skipUntilEnd(e,'Failed to skip indefinite length body: "'+this.tag+'"');return e.isError(a)?a:(s=e.offset-o.offset,e.restore(o),e.skip(s,'Failed to match body of: "'+t+'"'))};Kt.prototype._skipUntilEnd=function(e,t){for(;;){let n=qh(e,t);if(e.isError(n))return n;let i=pE(e,n.primitive,t);if(e.isError(i))return i;let s;if(n.primitive||i!==null?s=e.skip(i):s=this._skipUntilEnd(e,t),e.isError(s))return s;if(n.tagStr==="end")break}};Kt.prototype._decodeList=function(e,t,n,i){let s=[];for(;!e.isEmpty();){let o=this._peekTag(e,"end");if(e.isError(o))return o;let a=n.decode(e,"der",i);if(e.isError(a)&&o)break;s.push(a)}return s};Kt.prototype._decodeStr=function(e,t){if(t==="bitstr"){let n=e.readUInt8();return e.isError(n)?n:{unused:n,data:e.raw()}}else if(t==="bmpstr"){let n=e.raw();if(n.length%2===1)return e.error("Decoding of string type: bmpstr length mismatch");let i="";for(let s=0;s<n.length/2;s++)i+=String.fromCharCode(n.readUInt16BE(s*2));return i}else if(t==="numstr"){let n=e.raw().toString("ascii");return this._isNumstr(n)?n:e.error("Decoding of string type: numstr unsupported characters")}else{if(t==="octstr")return e.raw();if(t==="objDesc")return e.raw();if(t==="printstr"){let n=e.raw().toString("ascii");return this._isPrintstr(n)?n:e.error("Decoding of string type: printstr unsupported characters")}else return/str$/.test(t)?e.raw().toString():e.error("Decoding of string type: "+t+" unsupported")}};Kt.prototype._decodeObjid=function(e,t,n){let i,s=[],o=0,a=0;for(;!e.isEmpty();)a=e.readUInt8(),o<<=7,o|=a&127,(a&128)===0&&(s.push(o),o=0);a&128&&s.push(o);let c=s[0]/40|0,l=s[0]%40;if(n?i=s:i=[c,l].concat(s.slice(1)),t){let p=t[i.join(" ")];p===void 0&&(p=t[i.join(".")]),p!==void 0&&(i=p)}return i};Kt.prototype._decodeTime=function(e,t){let n=e.raw().toString(),i,s,o,a,c,l;if(t==="gentime")i=n.slice(0,4)|0,s=n.slice(4,6)|0,o=n.slice(6,8)|0,a=n.slice(8,10)|0,c=n.slice(10,12)|0,l=n.slice(12,14)|0;else if(t==="utctime")i=n.slice(0,2)|0,s=n.slice(2,4)|0,o=n.slice(4,6)|0,a=n.slice(6,8)|0,c=n.slice(8,10)|0,l=n.slice(10,12)|0,i<70?i=2e3+i:i=1900+i;else return e.error("Decoding "+t+" time is not supported yet");return Date.UTC(i,s-1,o,a,c,l,0)};Kt.prototype._decodeNull=function(){return null};Kt.prototype._decodeBool=function(e){let t=e.readUInt8();return e.isError(t)?t:t!==0};Kt.prototype._decodeInt=function(e,t){let n=e.raw(),i=new PB(n);return t&&(i=t[i.toString(10)]||i),i};Kt.prototype._use=function(e,t){return typeof e=="function"&&(e=e(t)),e._getDecoder("der").tree};function qh(r,e){let t=r.readUInt8(e);if(r.isError(t))return t;let n=cE.tagClass[t>>6],i=(t&32)===0;if((t&31)===31){let o=t;for(t=0;(o&128)===128;){if(o=r.readUInt8(e),r.isError(o))return o;t<<=7,t|=o&127}}else t&=31;let s=cE.tag[t];return{cls:n,primitive:i,tag:t,tagStr:s}}function pE(r,e,t){let n=r.readUInt8(t);if(r.isError(n))return n;if(!e&&n===128)return null;if((n&128)===0)return n;let i=n&127;if(i>4)return r.error("length octect is too long");n=0;for(let s=0;s<i;s++){n<<=8;let o=r.readUInt8(t);if(r.isError(o))return o;n|=o}return n}});var hE=R((gW,dE)=>{"use strict";var IB=qn(),NB=ql().Buffer,$h=Hh();function Wh(r){$h.call(this,r),this.enc="pem"}IB(Wh,$h);dE.exports=Wh;Wh.prototype.decode=function(e,t){let n=e.toString().split(/[\r\n]+/g),i=t.label.toUpperCase(),s=/^-----(BEGIN|END) ([^-]+)-----$/,o=-1,a=-1;for(let p=0;p<n.length;p++){let f=n[p].match(s);if(f!==null&&f[2]===i)if(o===-1){if(f[1]!=="BEGIN")break;o=p}else{if(f[1]!=="END")break;a=p;break}}if(o===-1||a===-1)throw new Error("PEM section not found for: "+i);let c=n.slice(o+1,a).join("");c.replace(/[^a-z0-9+/=]+/gi,"");let l=NB.from(c,"base64");return $h.prototype.decode.call(this,l,t)}});var Gh=R(gE=>{"use strict";var mE=gE;mE.der=Hh();mE.pem=hE()});var yE=R(vE=>{"use strict";var LB=Uh(),DB=Gh(),BB=qn(),jB=vE;jB.define=function(e,t){return new Ps(e,t)};function Ps(r,e){this.name=r,this.body=e,this.decoders={},this.encoders={}}Ps.prototype._createNamed=function(e){let t=this.name;function n(i){this._initNamed(i,t)}return BB(n,e),n.prototype._initNamed=function(s,o){e.call(this,s,o)},new n(this)};Ps.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(DB[e])),this.decoders[e]};Ps.prototype.decode=function(e,t,n){return this._getDecoder(t).decode(e,n)};Ps.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(LB[e])),this.encoders[e]};Ps.prototype.encode=function(e,t,n){return this._getEncoder(t).encode(e,n)}});var _E=R(xE=>{"use strict";var zl=xE;zl.Reporter=Hl().Reporter;zl.DecoderBuffer=Ms().DecoderBuffer;zl.EncoderBuffer=Ms().EncoderBuffer;zl.Node=Wl()});var SE=R(wE=>{"use strict";var bE=wE;bE._reverse=function(e){let t={};return Object.keys(e).forEach(function(n){(n|0)==n&&(n=n|0);let i=e[n];t[i]=n}),t};bE.der=Gl()});var TE=R(EE=>{"use strict";var Is=EE;Is.bignum=Mh();Is.define=yE().define;Is.base=_E();Is.constants=SE();Is.decoders=Gh();Is.encoders=Uh()});var Ns=R((zh,AE)=>{var Vl=require("buffer"),qr=Vl.Buffer;function CE(r,e){for(var t in r)e[t]=r[t]}qr.from&&qr.alloc&&qr.allocUnsafe&&qr.allocUnsafeSlow?AE.exports=Vl:(CE(Vl,zh),zh.Buffer=gi);function gi(r,e,t){return qr(r,e,t)}gi.prototype=Object.create(qr.prototype);CE(qr,gi);gi.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return qr(r,e,t)};gi.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=qr(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};gi.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return qr(r)};gi.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return Vl.SlowBuffer(r)}});var Vh=R((wW,RE)=>{var Kl=Ns().Buffer,FB=require("stream"),UB=require("util");function Yl(r){if(this.buffer=null,this.writable=!0,this.readable=!0,!r)return this.buffer=Kl.alloc(0),this;if(typeof r.pipe=="function")return this.buffer=Kl.alloc(0),r.pipe(this),this;if(r.length||typeof r=="object")return this.buffer=r,this.writable=!1,process.nextTick(function(){this.emit("end",r),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof r+")")}UB.inherits(Yl,FB);Yl.prototype.write=function(e){this.buffer=Kl.concat([this.buffer,Kl.from(e)]),this.emit("data",e)};Yl.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};RE.exports=Yl});var OE=R((SW,kE)=>{"use strict";function Kh(r){var e=(r/8|0)+(r%8===0?0:1);return e}var qB={ES256:Kh(256),ES384:Kh(384),ES512:Kh(521)};function HB(r){var e=qB[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}kE.exports=HB});var BE=R((EW,DE)=>{"use strict";var Jl=Ns().Buffer,PE=OE(),Xl=128,IE=0,$B=32,WB=16,GB=2,NE=WB|$B|IE<<6,Zl=GB|IE<<6;function zB(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function LE(r){if(Jl.isBuffer(r))return r;if(typeof r=="string")return Jl.from(r,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function VB(r,e){r=LE(r);var t=PE(e),n=t+1,i=r.length,s=0;if(r[s++]!==NE)throw new Error('Could not find expected "seq"');var o=r[s++];if(o===(Xl|1)&&(o=r[s++]),i-s<o)throw new Error('"seq" specified length of "'+o+'", only "'+(i-s)+'" remaining');if(r[s++]!==Zl)throw new Error('Could not find expected "int" for "r"');var a=r[s++];if(i-s-2<a)throw new Error('"r" specified length of "'+a+'", only "'+(i-s-2)+'" available');if(n<a)throw new Error('"r" specified length of "'+a+'", max of "'+n+'" is acceptable');var c=s;if(s+=a,r[s++]!==Zl)throw new Error('Could not find expected "int" for "s"');var l=r[s++];if(i-s!==l)throw new Error('"s" specified length of "'+l+'", expected "'+(i-s)+'"');if(n<l)throw new Error('"s" specified length of "'+l+'", max of "'+n+'" is acceptable');var p=s;if(s+=l,s!==i)throw new Error('Expected to consume entire buffer, but "'+(i-s)+'" bytes remain');var f=t-a,h=t-l,v=Jl.allocUnsafe(f+a+h+l);for(s=0;s<f;++s)v[s]=0;r.copy(v,s,c+Math.max(-f,0),c+a),s=t;for(var x=s;s<x+h;++s)v[s]=0;return r.copy(v,s,p+Math.max(-h,0),p+l),v=v.toString("base64"),v=zB(v),v}function ME(r,e,t){for(var n=0;e+n<t&&r[e+n]===0;)++n;var i=r[e+n]>=Xl;return i&&--n,n}function KB(r,e){r=LE(r);var t=PE(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var i=ME(r,0,t),s=ME(r,t,r.length),o=t-i,a=t-s,c=2+o+1+1+a,l=c<Xl,p=Jl.allocUnsafe((l?2:3)+c),f=0;return p[f++]=NE,l?p[f++]=c:(p[f++]=Xl|1,p[f++]=c&255),p[f++]=Zl,p[f++]=o,i<0?(p[f++]=0,f+=r.copy(p,f,0,t)):f+=r.copy(p,f,i,t),p[f++]=Zl,p[f++]=a,s<0?(p[f++]=0,r.copy(p,f,t)):r.copy(p,f,t+s),p}DE.exports={derToJose:VB,joseToDer:KB}});var FE=R((TW,jE)=>{"use strict";var Vo=require("buffer").Buffer,Yh=require("buffer").SlowBuffer;jE.exports=Ql;function Ql(r,e){if(!Vo.isBuffer(r)||!Vo.isBuffer(e)||r.length!==e.length)return!1;for(var t=0,n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}Ql.install=function(){Vo.prototype.equal=Yh.prototype.equal=function(e){return Ql(this,e)}};var YB=Vo.prototype.equal,JB=Yh.prototype.equal;Ql.restore=function(){Vo.prototype.equal=YB,Yh.prototype.equal=JB}});var Qh=R((CW,KE)=>{var Ds=Ns().Buffer,dr=require("crypto"),qE=BE(),UE=require("util"),XB=`"%s" is not a valid algorithm.
91
+ `),ml.add(e),r.on("close",()=>ml.delete(e))}function gw(r,e){X(e,{...ln,...Er,desktopEnabled:Bt,remoteAvailable:nh})}async function vw(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Pt(),Mi)),n=await t(r,e);n&&(un(n),X(e))}function yw(r,e){X(e),un({step:zn.PREPARING,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null}),Dn("restart-tunnel")}function xw(r,e){X(e),un({step:zn.PREPARING,stepDesc:""}),Dn("start-tunnel")}function _w(r,e){X(e),un({step:zn.STOPPED,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null}),Dn("stop-tunnel")}function bw(r,e){X(e),un({step:zn.STOPPED,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null}),Dn("shutdown")}function ww(r,e){X(e),Dn("update")}function Sw(r,e){X(e,{connections:[...li.values()]})}function Ew(r,e){let t=new URL(r.url,"http://localhost"),n=parseInt(t.searchParams.get("lines")||bp,10);X(e,{logs:Sv(Number.isFinite(n)?n:bp)})}async function Tw(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Pt(),Mi)),n=await t(r,e);if(!n)return;let i=!!n.enabled;if(i&&(!Er.screenRecording||!Er.accessibility)){X(e,{ok:!1,enabled:Bt,reason:"permissions_required"});return}let s=xs();Bt=i,rh(),_t("permissions",{...Er,desktopEnabled:Bt}),xs()!==s&&ih?.(),X(e,{ok:!0,enabled:Bt})}function Cw(r,e){X(e,Er)}async function Aw(r,e){let t=await Vd();X(e,{enabled:t})}async function Rw(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Pt(),Mi)),n=await t(r,e);if(!n)return;let i=await Yb(!!n.enabled),s=await Vd();_t("autostart",{enabled:s}),X(e,{ok:i,enabled:s})}async function kw(r,e){let{parseJsonBody:t}=await Promise.resolve().then(()=>(Pt(),Mi)),n=await t(r,e);if(!n)return;let{type:i}=n;if(process.platform==="darwin"){$b(i);let s=Date.now(),o=setInterval(async()=>{((await vl())[i]||Date.now()-s>gv)&&clearInterval(o)},mv)}X(e)}var Bn,rw,th,ln,Bt,nh,Er,ml,li,gl,ih,pn=Ee(()=>{vt();Ii();vt();hs();Wb();Kd();Pt();nl();vt();Bn=require("fs"),rw=require("path");vt();Yd();th=(0,rw.join)(ie.STATE,"ui-state.json");ln={step:zn.STOPPED,stepDesc:"",tunnelUrl:"",oneTimeKey:"",oneTimeKeyExpiresAt:null,permanentKey:"",qrUrl:"",latency:null,uptime:null,healthCheck:{running:!1,timeoutMs:0,startedAt:null,logs:[]},tunnelHealth:{status:"unknown",checkedAt:null}},Bt=!1,nh=!1,Er={screenRecording:!1,accessibility:!1},ml=new Set,li=new Map;wv(ve);gl=null;ih=null});var Ow={};Vr(Ow,{ScreenHandler:()=>sh,encodeTilesBatch:()=>_s});function Y2(r){let e=Buffer.alloc(28);return e.writeUInt32LE(r.tileIndex,0),e.writeUInt32LE(r.x,4),e.writeUInt32LE(r.y,8),e.writeUInt32LE(r.width,12),e.writeUInt32LE(r.height,16),e.writeUInt32LE(r.imageBuffer.length,20),e.writeUInt32LE(r.hash>>>0,24),Buffer.concat([e,r.imageBuffer])}function _s(r,e){let t=Buffer.alloc(12);return t.writeUInt32LE(r.length,0),t.writeDoubleBE(e,4),Buffer.concat([t,...r.map(Y2)])}var sh,oh=Ee(()=>{qd();at();pn();sh=class{constructor(e,t){this.resourceManager=e,this.screenUpdateHelper=t}setupScreenHandlers(e,t,n){e.on("request-screen",t(async()=>{let i=this.resourceManager.getClient(e.id);if(i)try{let s=await i.tileManager.detectChangedTiles();s.length>0&&n.sendTiles({tiles:s,timestamp:Date.now()},_s),this.resourceManager.updateClientActivity(e.id)}catch(s){me.error("Tile capture error:",s),n.emit("screen-error",{error:s.message})}})),e.on("request-screen-with-hashes",t(async i=>{let s=this.resourceManager.getClient(e.id);if(s)try{let o=i.tileHashes||[],a=await s.tileManager.compareClientTileHashes(o);a?.tiles?.length>0&&n.sendTiles({tiles:a.tiles,timestamp:Date.now()},_s),this.resourceManager.updateClientActivity(e.id)}catch(o){me.error("Tile capture with hashes error:",o),n.emit("screen-error",{error:o.message})}})),e.on("start-streaming",t(async()=>{let i=this.resourceManager.getClient(e.id);if(!i)return;i.streamingTimeout&&(clearTimeout(i.streamingTimeout),i.streamingTimeout=null),me.lifecycle("\u{1F680} Remote streaming started");let{tileFormat:s,webpEffort:o,jpegQuality:a}=$.pipeline;ve(`\u{1F5BC}\uFE0F Remote stream codec: ${s.toUpperCase()}${s==="webp"?` (effort=${o})`:""} q=${a}`),i.idleFrameCount=0,i.isStreaming=!0,i.streamGen=(i.streamGen||0)+1;let c=i.streamGen;i.tileManager.lastTileChecksums.clear();try{let p=await i.tileManager.getScreenDimensions();n.emit("screen-dimensions",p)}catch(p){me.error("Get dimensions error:",p)}let l=async()=>{if(!e.connected||!i.isStreaming||i.streamGen!==c){i.streamingTimeout=null;return}try{let p=performance.now(),f=await i.tileManager.detectChangedTilesWithHashes();if(f.tiles.length>0&&e.connected){let k=n.sendTiles({tiles:f.tiles,timestamp:Date.now(),currentHashes:f.currentHashes},_s);i.tileManager.commitHashes(k||[]),i.idleFrameCount=0}else i.idleFrameCount++;let{activeInterval:h,idleInterval:v,idleThreshold:x}=this.resourceManager.getStreamingConfig(),S=i.idleFrameCount>=x?v:h,A=Math.max(0,S-(performance.now()-p));i.streamingTimeout=setTimeout(l,A)}catch(p){me.error("Auto streaming error:",p),i.streamingTimeout=setTimeout(l,200)}};l()})),e.on("stop-streaming",()=>{let i=this.resourceManager.getClient(e.id);i&&(i.isStreaming=!1,i.streamingTimeout&&(clearTimeout(i.streamingTimeout),i.streamingTimeout=null),i.tileManager?.clearMemory?.(),me.lifecycle("\u23F9\uFE0F Remote streaming stopped"))}),e.on("get-screen-dimensions",t(async()=>{let i=this.resourceManager.getClient(e.id);if(i)try{let s=await i.tileManager.getScreenDimensions();n.emit("screen-dimensions",s)}catch(s){me.error("Get dimensions error:",s),n.emit("screen-error",{error:s.message})}})),e.on("boost-stream",t(()=>{let i=this.resourceManager.getClient(e.id);i&&(i.idleFrameCount=0)})),e.on("set-focus",t(i=>{let s=this.resourceManager.getClient(e.id);if(!s)return;let o=i?.rect||null,a=typeof i?.zoom=="number"?i.zoom:1,c=typeof i?.viewerWidth=="number"?i.viewerWidth:0,l=typeof i?.dpr=="number"?i.dpr:1,p=s.tileManager.pickProfile({zoom:a,viewerWidth:c,dpr:l});if(s.tileManager.setProfile(p),s.tileManager.setFocusRect(o),o){let f=s.tileManager.activeTileSet?.size||0,h=s.tileManager.totalTiles,v=h?(f/h*100).toFixed(0):0;me.focus(`\u{1F3AF} [Focus] rect=${o.x},${o.y} ${o.w}x${o.h} | tiles ${f}/${h} (${v}%)`)}else me.focus("\u{1F3AF} [Focus] cleared \u2192 full screen")}))}}});function Mw(r){ah.add(r)}function bs(r){ah.delete(r)}function bt(r,e,t){for(let n of ah)if(n.hasReadyAdapter?.())try{n.emit(e,t)}catch{}}var ah,ui=Ee(()=>{ah=new Set});async function Vw(){if(Go)return Go;let r=await import("node-screenshots");if(Go=(r.Monitor||r.default?.Monitor).all()[0],!Go)throw new Error("No monitor found via node-screenshots");return Go}async function Kw(r){hh=r,$.pipeline.captureLib==="nodeScreenshots"&&await Vw()}async function Yw(){let{captureLib:r,inputFormat:e}=$.pipeline;if(r==="robotjs"){let{width:s,height:o}=hh.getScreenSize(),a=hh.screen.capture(0,0,s,o),c=a.byteWidth/a.bytesPerPixel;return{buffer:Buffer.from(a.image),width:c,height:a.height,channels:a.bytesPerPixel,format:e}}let n=(await Vw()).captureImageSync();return{buffer:n.toRawSync?n.toRawSync():n.rawSync(),width:n.width,height:n.height,channels:4,format:e}}var hh,Go,Jw=Ee(()=>{at();hh=null,Go=null});function lB(r){return r==="bgra"?gh.FORMAT_BGRA:gh.FORMAT_RGBA}function vh(r){let e=new Uint32Array(r.buffer,r.byteOffset,r.length>>2);for(let t=0;t<e.length;t++){let n=e[t];e[t]=n&4278255360|(n&16711680)>>16|(n&255)<<16}}async function Xw(r,e,t,n=4,i,s){let{encoder:o,inputFormat:a,jpegQuality:c,tileFormat:l,webpEffort:p}=$.pipeline,f=i??c,h=s??a;if(o==="jpegTurbo"&&l!=="webp")return gh.compressSync(r,{width:e,height:t,format:lB(h),quality:f});let v=r;h==="bgra"&&(v=Buffer.from(r),vh(v));let x=(0,kl.default)(v,{raw:{width:e,height:t,channels:n}});return l==="webp"?x.webp({quality:f,effort:p}).toBuffer():x.jpeg({quality:f}).toBuffer()}var kl,mh,gh,Zw=Ee(()=>{kl=K(require("sharp"),1),mh=K(require("@julusian/jpeg-turbo"),1);at();gh=mh.default.default||mh.default;kl.default.cache(!1);kl.default.concurrency(1)});var Ol,Qw=Ee(()=>{at();pn();Ol=class{constructor(){this.cfg=$.logging,this.samples=[],this.lastLogTime=Date.now()}now(){return this.cfg.metrics?performance.now():0}record({capture:e,checksum:t,encode:n,total:i,changedTiles:s,totalTiles:o,tileBytes:a,rawBytes:c}){this.cfg.metrics&&(this.samples.push({capture:e,checksum:t,encode:n,total:i,changedTiles:s,totalTiles:o,tileBytes:a,rawBytes:c}),this.samples.length>=this.cfg.metricsEveryFrames&&this._flush())}_flush(){let e=this.samples.length,t=I=>(this.samples.reduce((B,V)=>B+V[I],0)/e).toFixed(1),n=(Date.now()-this.lastLogTime)/1e3,i=(e/n).toFixed(1),s=[],o=0;for(let I of this.samples){for(let B of I.tileBytes)s.push(B);o+=I.tileBytes.reduce((B,V)=>B+V,0)}let a=(o/e/1024).toFixed(1),c=s.length?(s.reduce((I,B)=>I+B,0)/s.length/1024).toFixed(2):"0",l=s.length?(Math.min(...s)/1024).toFixed(2):"0",p=s.length?(Math.max(...s)/1024).toFixed(2):"0",f=this.samples.reduce((I,B)=>I+B.rawBytes,0)/e,h=o/e,v=h>0?(f/h).toFixed(0):"0",x=(this.samples.reduce((I,B)=>I+B.changedTiles,0)/e).toFixed(0),S=this.samples[0]?.totalTiles||0,A=S?(x/S*100).toFixed(1):"0",k=$.pipeline,P=`[Metrics] ${k.captureLib}+${k.encoder} tile=${k.tileSize} q${k.jpegQuality} scale=${k.outputScale} | fps=${i} | capture=${t("capture")}ms enc=${t("encode")}ms total=${t("total")}ms | tiles=${x}/${S} (${A}%) | data=${a}KB/frame | tileAvg=${c}KB (min ${l}, max ${p}) | compress=${v}x`;ve(P),console.log(P),this.samples=[],this.lastLogTime=Date.now()}}});var rS={};Vr(rS,{TileManager:()=>yh,mapLimit:()=>fi});async function fi(r,e,t){let n=new Array(r.length),i=0,s=Array.from({length:Math.min(e,r.length)},async()=>{for(;i<r.length;){let o=i++;n[o]=await t(r[o],o)}});return await Promise.all(s),n}var Es,Pl,eS,Ml,tS,uB,pB,yh,nS=Ee(()=>{Es=K(require("fs"),1),Pl=K(require("path"),1),eS=K(require("sharp"),1),Ml=require("child_process"),tS=require("url");at();Jw();Zw();Qw();qd();uB=(0,tS.fileURLToPath)(__importMetaUrl),pB=Pl.default.dirname(uB);yh=class{constructor(e){this.robot=e,this.metrics=new Ol,this.tileSize=$.pipeline.tileSize,this.lastTileChecksums=new Map,this.screenWidth=0,this.screenHeight=0,this.tilesPerRow=0,this.tilesPerColumn=0,this.totalTiles=0,this.frameCount=0,this.tempDir=Pl.default.join(pB,"../../temp"),this.changeThreshold=1,this.scaledWidth=0,this.scaledHeight=0,this.isProcessing=!1,this.sharedScreenCache=null,this.lastCaptureTime=0,this.CACHE_TTL=100,this.dpiScale=1,this.captureWidth=0,this.captureHeight=0,this.scaleFactor=$.pipeline.outputScale||1,this.compressionQuality=$.pipeline.jpegQuality,this.activeTileSet=null,this.focusStats={frames:0,scanned:0,changed:0,bytes:0},Es.default.existsSync(this.tempDir)||Es.default.mkdirSync(this.tempDir,{recursive:!0}),Kw(e),this.initializeScreenDimensions()}initializeScreenDimensions(){try{let{width:e,height:t}=this.robot.getScreenSize();this.screenWidth=e,this.screenHeight=t,this.detectDpiScale(),this.scaledWidth=this.captureWidth,this.scaledHeight=this.captureHeight,this.tilesPerRow=Math.ceil(this.scaledWidth/this.tileSize),this.tilesPerColumn=Math.ceil(this.scaledHeight/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn;let n=100;if(this.totalTiles>n){let i=Math.ceil(Math.sqrt(this.scaledWidth*this.scaledHeight/n));this.tileSize=Math.max(i,120),this.tilesPerRow=Math.ceil(this.scaledWidth/this.tileSize),this.tilesPerColumn=Math.ceil(this.scaledHeight/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn}}catch(e){me.error("Screen dimensions error:",e),this.screenWidth=1920,this.screenHeight=1080,this.dpiScale=1,this.captureWidth=1920,this.captureHeight=1080,this.scaledWidth=1728,this.scaledHeight=972,this.tileSize=120,this.tilesPerRow=Math.ceil(this.scaledWidth/this.tileSize),this.tilesPerColumn=Math.ceil(this.scaledHeight/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn}}detectDpiScale(){if(process.platform==="darwin"){let e=this.robot.screen.capture(0,0,this.screenWidth,this.screenHeight),n=e.byteWidth/e.bytesPerPixel/this.screenWidth;n>=1.9&&n<=2.1?this.dpiScale=2:this.dpiScale=1}else process.platform==="win32"?this.dpiScale=this._detectDpiScaleWin32():this.dpiScale=1;this.captureWidth=Math.floor(this.screenWidth*this.dpiScale),this.captureHeight=Math.floor(this.screenHeight*this.dpiScale)}_detectDpiScaleWin32(){me.dpi(`\u{1F50D} [DPI Detection] screenWidth from robot: ${this.screenWidth}x${this.screenHeight}`);try{let e=(0,Ml.execSync)(`powershell -NonInteractive -NoProfile -WindowStyle Hidden -command "try{Get-ItemPropertyValue 'HKCU:\\Control Panel\\Desktop\\WindowMetrics' -Name AppliedDPI}catch{0}"`,{encoding:"utf8",windowsHide:!0}).trim(),t=Number(e);if(me.dpi(`\u{1F50D} [DPI Detection] Strategy 1 (Registry AppliedDPI): ${t} DPI`),t>=96){let n=t/96;return me.dpi(`\u2705 [DPI Detection] Using registry scale: ${n}x (${t}/96)`),n}}catch(e){me.dpi(`\u274C [DPI Detection] Strategy 1 failed: ${e.message}`)}try{let e=(0,Ml.execSync)('powershell -NonInteractive -NoProfile -WindowStyle Hidden -command "(Get-WmiObject -Class Win32_VideoController | Select-Object -First 1).CurrentHorizontalResolution"',{encoding:"utf8",windowsHide:!0}).trim(),t=Number(e);if(me.dpi(`\u{1F50D} [DPI Detection] Strategy 2 (WMI): physical width = ${t}px`),t>0&&t>this.screenWidth){let n=t/this.screenWidth;return me.dpi(`\u2705 [DPI Detection] Using WMI scale: ${n}x (${t}/${this.screenWidth})`),n}}catch(e){me.dpi(`\u274C [DPI Detection] Strategy 2 failed: ${e.message}`)}try{let e=(0,Ml.execSync)(`powershell -NonInteractive -NoProfile -WindowStyle Hidden -command "Add-Type -TypeDefinition 'using System;using System.Runtime.InteropServices;public class Disp{[DllImport(\\"user32\\")]public static extern bool EnumDisplaySettings(string d,int m,ref DEVMODE dm);[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)]public struct DEVMODE{[MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)]public string dmDeviceName;public short dmSpecVersion,dmDriverVersion,dmSize,dmDriverExtra;public int dmFields;public int dmPositionX,dmPositionY,dmDisplayOrientation,dmDisplayFixedOutput;public short dmColor,dmDuplex,dmYResolution,dmTTOption,dmCollate;[MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)]public string dmFormName;public short dmLogPixels;public int dmBitsPerPel,dmPelsWidth,dmPelsHeight,dmDisplayFlags,dmDisplayFrequency;}}'; $dm=New-Object Disp+DEVMODE; $dm.dmSize=[System.Runtime.InteropServices.Marshal]::SizeOf($dm); [Disp]::EnumDisplaySettings($null,-1,[ref]$dm) | Out-Null; Write-Output $dm.dmPelsWidth"`,{encoding:"utf8",windowsHide:!0}).trim(),t=Number(e);if(me.dpi(`\u{1F50D} [DPI Detection] Strategy 3 (EnumDisplaySettings): physical width = ${t}px`),t>0&&t>this.screenWidth){let n=t/this.screenWidth;return me.dpi(`\u2705 [DPI Detection] Using EnumDisplaySettings scale: ${n}x (${t}/${this.screenWidth})`),n}}catch(e){me.dpi(`\u274C [DPI Detection] Strategy 3 failed: ${e.message}`)}return me.dpi("\u26A0\uFE0F [DPI Detection] All strategies failed, fallback to 1x"),1}async captureFullScreen(){let e=await Yw();return{buffer:e.buffer,width:e.width,height:e.height,channels:e.channels}}async getSharedScreenCapture(){let e=Date.now();return this.sharedScreenCache&&e-this.lastCaptureTime<this.CACHE_TTL?this.sharedScreenCache:(this.sharedScreenCache=await this.captureFullScreen(),this.lastCaptureTime=e,this.sharedScreenCache)}clearScreenCache(){}async detectChangedTiles(){return(await this.detectChangedTilesWithHashes()).tiles}async detectChangedTilesWithHashes(){if(this.isProcessing)return{tiles:[],currentHashes:Array.from(this.lastTileChecksums.values())};this.isProcessing=!0;let e=this.metrics.now(),t=e,n=e;try{let i=await this.getSharedScreenCapture();t=this.metrics.now();let s=[],o=[],a=new Map;this.frameCount++;let c=this.activeTileSet;for(let f=0;f<this.totalTiles;f++){if(c&&!c.has(f))continue;let h=this.calculateTileChecksumDirect(i,f);a.set(f,h)}n=this.metrics.now();let l=Array.from(a.values());if(this.lastTileChecksums.size===0){let f=[];for(let v=0;v<this.totalTiles;v++)c&&!c.has(v)||f.push(v);let h=await fi(f,$.pipeline.tileConcurrency,v=>this.processTileAsync(i,v,null,a.get(v)));return s.push(...h),this._recordFrame(e,t,n,s,i),{tiles:s,currentHashes:l}}for(let f=0;f<this.totalTiles;f++){if(c&&!c.has(f))continue;let h=a.get(f),v=this.lastTileChecksums.get(f);h!==v&&o.push(f)}if(o.length/this.totalTiles>this.changeThreshold){let f=[];for(let v=0;v<this.totalTiles;v++)c&&!c.has(v)||f.push(v);let h=await fi(f,$.pipeline.tileConcurrency,v=>this.processTileAsync(i,v,null,a.get(v)));s.push(...h.map(v=>({...v,fullRefresh:!0})))}else if(o.length>0){let f=await fi(o,$.pipeline.tileConcurrency,h=>this.processTileAsync(i,h,null,a.get(h)));s.push(...f)}return this._recordFrame(e,t,n,s,i),{tiles:s,currentHashes:l}}finally{this.isProcessing=!1}}async processTileAsync(e,t,n=null,i=null){let s=n||this.extractTile(e,t),o=await this.compressTileImage(s.buffer,s.width,s.height),{row:a,col:c}=this.getTilePosition(t);return{type:"tile-update",tileIndex:t,x:c*this.tileSize,y:a*this.tileSize,width:s.width,height:s.height,imageBuffer:o,hash:i??this.lastTileChecksums.get(t)??0,timestamp:Date.now(),frameCount:this.frameCount}}commitHashes(e){for(let t of e)this.lastTileChecksums.set(t.tileIndex,t.hash)}calculateTileChecksumDirect(e,t){let{row:n,col:i}=this.getTilePosition(t),s=i*this.tileSize,o=n*this.tileSize,a=Math.min(s+this.tileSize,e.width),c=Math.min(o+this.tileSize,e.height),l=a-s,p=c-o,f=e.channels,h=e.width*f,v=0,{rowStep:x,colStep:S}=$.pipeline.checksumSampling;for(let A=0;A<p;A+=x){let k=(o+A)*h+s*f;for(let P=0;P<l;P+=S){let I=k+P*f,B=P+1;v=v+e.buffer[I]*B>>>0,v^=e.buffer[I+1]<<1,v=v+e.buffer[I+2]*B>>>0,v^=e.buffer[I+3]<<2}}return v>>>0}setFocusRect(e){if(!e){this.activeTileSet=null;return}let t=$.focus.paddingTiles,n=Math.max(0,Math.floor(e.x/this.tileSize)-t),i=Math.max(0,Math.floor(e.y/this.tileSize)-t),s=Math.min(this.tilesPerRow-1,Math.floor((e.x+e.w)/this.tileSize)+t),o=Math.min(this.tilesPerColumn-1,Math.floor((e.y+e.h)/this.tileSize)+t),a=new Set;for(let l=i;l<=o;l++)for(let p=n;p<=s;p++)a.add(l*this.tilesPerRow+p);let c=this.activeTileSet;if(c)for(let l of a)c.has(l)||this.lastTileChecksums.delete(l);this.activeTileSet=a}getTilePosition(e){return{row:Math.floor(e/this.tilesPerRow),col:e%this.tilesPerRow}}extractTile(e,t){let{row:n,col:i}=this.getTilePosition(t),s=i*this.tileSize,o=n*this.tileSize,a=Math.min(s+this.tileSize,e.width),c=Math.min(o+this.tileSize,e.height),l=a-s,p=c-o,f=e.channels,h=l*f,v=Buffer.alloc(l*p*f);for(let x=0;x<p;x++){let S=((o+x)*e.width+s)*f,A=x*h;e.buffer.copy(v,A,S,S+h)}return{buffer:v,width:l,height:p,channels:f,tileIndex:t,x:s,y:o}}async compressTileImage(e,t,n){let i=this.scaleFactor;if(i&&i>0&&i<1){let s=Math.max(1,Math.floor(t*i)),o=Math.max(1,Math.floor(n*i)),{inputFormat:a}=$.pipeline,c=e,l=4;a==="bgra"&&(c=Buffer.from(e),vh(c));let{tileFormat:p,webpEffort:f}=$.pipeline,h=(0,eS.default)(c,{raw:{width:t,height:n,channels:l}}).resize(s,o,{kernel:"lanczos3",fastShrinkOnLoad:!1});return p==="webp"?h.webp({quality:this.compressionQuality,effort:f}).toBuffer():h.jpeg({quality:this.compressionQuality}).toBuffer()}return Xw(e,t,n,4,this.compressionQuality)}pickProfile({zoom:e=1,viewerWidth:t=0,dpr:n=1}={}){let i=$.pipeline.adaptiveTiers||[];if(!i.length)return null;let s=this.captureWidth||this.screenWidth||1,o=t>0?t:s,a=e>0?e:1,c=n>0?n:1,l=o*a*c/s,p=$.pipeline.tierHysteresis||0,f=this._currentTier;for(let v of i){let x=f&&v===f?v.minEffective-p:v.minEffective;if(l>=x)return this._currentTier=v,v}let h=i[i.length-1];return this._currentTier=h,h}setProfile(e){if(!e)return;let t=e.outputScale??this.scaleFactor,n=e.jpegQuality??this.compressionQuality;t===this.scaleFactor&&n===this.compressionQuality||(this.scaleFactor=t,this.compressionQuality=n,this.lastTileChecksums.clear())}_recordFrame(e,t,n,i,s){if(this._recordFocusFrame(i),!this.metrics.cfg.metrics)return;let o=this.metrics.now(),a=i.map(l=>l.imageBuffer?.length||0),c=s?s.width*s.height*s.channels:0;this.metrics.record({capture:t-e,checksum:n-t,encode:o-n,total:o-e,changedTiles:i.length,totalTiles:this.totalTiles,tileBytes:a,rawBytes:c})}_recordFocusFrame(e){let t=this.focusStats;t.frames++,t.scanned+=this.activeTileSet?this.activeTileSet.size:this.totalTiles,t.changed+=e.length;for(let c of e)t.bytes+=c.imageBuffer?.length||0;if(t.frames<$.logging.focusEveryFrames)return;let n=(t.scanned/t.frames).toFixed(0),i=(t.changed/t.frames).toFixed(1),s=(t.bytes/t.frames/1024).toFixed(1),o=this.totalTiles?((1-n/this.totalTiles)*100).toFixed(0):0,a=this.activeTileSet?"focus":"full";me.focus(`\u{1F3AF} [Focus/${a}] ${t.frames}f | scan ${n}/${this.totalTiles} tiles (saved ${o}%) | changed ${i}/f | data ${s}KB/f`),this.focusStats={frames:0,scanned:0,changed:0,bytes:0}}async getScreenDimensions(){try{let e=await this.captureFullScreen();this.scaledWidth=e.width,this.scaledHeight=e.height,this.tilesPerRow=Math.ceil(e.width/this.tileSize),this.tilesPerColumn=Math.ceil(e.height/this.tileSize),this.totalTiles=this.tilesPerRow*this.tilesPerColumn}catch(e){me.error("Error getting dimensions:",e)}return{width:this.scaledWidth,height:this.scaledHeight,tileWidth:this.tileSize,tileHeight:this.tileSize,tileCount:this.totalTiles,scaleFactor:this.scaleFactor,originalWidth:this.screenWidth,originalHeight:this.screenHeight}}async compareClientTileHashes(e){if(this.isProcessing)return{tiles:[],currentHashes:[],changedIndices:[]};this.isProcessing=!0;try{let t=await this.getSharedScreenCapture(),n=[],i=[];this.frameCount++;let s=this.activeTileSet,o=new Map;for(let c=0;c<this.totalTiles;c++){if(s&&!s.has(c))continue;let l=this.calculateTileChecksumDirect(t,c);o.set(c,l),this.lastTileChecksums.set(c,l)}if(!e||e.length===0){let c=[];for(let p=0;p<this.totalTiles;p++)s&&!s.has(p)||c.push(p);let l=await fi(c,$.pipeline.tileConcurrency,p=>this.processTileAsync(t,p));return n.push(...l),{tiles:n,currentHashes:Array.from(o.values())}}for(let c=0;c<this.totalTiles;c++)s&&!s.has(c)||e[c]!==o.get(c)&&i.push(c);if(i.length/this.totalTiles>this.changeThreshold){let c=[];for(let p=0;p<this.totalTiles;p++)s&&!s.has(p)||c.push(p);let l=await fi(c,$.pipeline.tileConcurrency,p=>this.processTileAsync(t,p));n.push(...l.map(p=>({...p,fullRefresh:!0})))}else if(i.length>0){let c=await fi(i,$.pipeline.tileConcurrency,l=>this.processTileAsync(t,l));n.push(...c)}return this._recordFocusFrame(n),{tiles:n,currentHashes:Array.from(o.values()),changedIndices:i}}finally{this.isProcessing=!1}}clearMemory(){this.sharedScreenCache=null,this.lastCaptureTime=0,this.lastTileChecksums.clear()}reset(){this.lastTileChecksums.clear(),this.frameCount=0}cleanup(){try{Es.default.existsSync(this.tempDir)&&Es.default.readdirSync(this.tempDir).forEach(t=>Es.default.unlinkSync(Pl.default.join(this.tempDir,t)))}catch(e){me.warn(`Cleanup error: ${e.message}`)}}}});var iS={};Vr(iS,{ResourceManager:()=>xh});var xh,sS=Ee(()=>{at();ui();xh=class{constructor(){this.activeClients=new Map,this.activeTimers=new Map,this.chunkTimers=new Map,this.memoryCheckInterval=null}startResourceMonitoring(){this.memoryCheckInterval=setInterval(()=>{let e=process.memoryUsage(),t=Math.round(e.heapUsed/1024/1024);t>$.resourceManagement.memoryWarningThreshold&&(console.warn(`\u26A0\uFE0F High memory: ${t}MB`),this.cleanupInactiveClients())},$.resourceManagement.memoryCheckInterval)}stopResourceMonitoring(){this.memoryCheckInterval&&(clearInterval(this.memoryCheckInterval),this.memoryCheckInterval=null)}addClient(e,t){this.activeClients.set(e,{...t,lastActivity:Date.now()})}getClient(e){return this.activeClients.get(e)}updateClientActivity(e){let t=this.activeClients.get(e);t&&(t.lastActivity=Date.now())}cleanupInactiveClients(){let e=Date.now(),t=$.resourceManagement.inactiveTimeout;for(let[n,i]of this.activeClients.entries())e-i.lastActivity>t&&(console.log(`\u{1F9F9} Cleaning inactive client: ${n}`),this.cleanupClientResources(n,i),this.activeClients.delete(n))}cleanupClientResources(e,t){try{t.isStreaming=!1,t?.streamingTimeout&&(clearTimeout(t.streamingTimeout),t.streamingTimeout=null),t?.screenInterval&&(clearInterval(t.screenInterval),t.screenInterval=null);let n=this.activeTimers.get(e);n&&(n.forEach(s=>clearTimeout(s)),this.activeTimers.delete(e));let i=this.chunkTimers.get(e);i&&(i.forEach(s=>clearTimeout(s)),this.chunkTimers.delete(e)),t?.tileManager&&(t.tileManager.clearMemory(),t.tileManager.cleanup(),t.tileManager.reset()),t?.protocol&&(t.protocol.close(),bs(t.protocol))}catch(n){console.error(`Error cleaning up ${e}:`,n.message)}}getStreamingConfig(){return $.streaming}getWebRTCConfig(){return $.webrtc}removeClient(e){let t=this.activeClients.get(e);t&&(this.cleanupClientResources(e,t),this.activeClients.delete(e))}getChunkTimers(e){return this.chunkTimers.has(e)||this.chunkTimers.set(e,new Set),this.chunkTimers.get(e)}cleanupAll(){this.stopResourceMonitoring();for(let[e,t]of this.activeClients.entries())this.cleanupClientResources(e,t);this.activeClients.clear(),this.activeTimers.clear(),this.chunkTimers.clear()}}});var oS={};Vr(oS,{ScreenUpdateHelper:()=>_h});var _h,aS=Ee(()=>{at();_h=class{constructor(e){this.resourceManager=e}async sendTilesInChunks(e,t,n,i=!1){if(!t||t.length===0)return;let s=$.streaming.chunkSize,o=[];for(let c=0;c<t.length;c+=s)o.push(t.slice(c,c+s));let a=this.resourceManager.getChunkTimers(e.id);for(let c=0;c<o.length;c++){let l=o[c],p=c===o.length-1,f=setTimeout(()=>{a.delete(f),e.connected&&e.emit("tiles-data",{tiles:l,timestamp:n,forceRefresh:!1,userAction:i,chunkInfo:{chunkIndex:c,totalChunks:o.length,isLastChunk:p}})},c*$.streaming.chunkDelay);a.add(f)}}}});var cS={};Vr(cS,{MouseHandler:()=>bh});var bh,lS=Ee(()=>{at();bh=class{constructor(e,t){this.robot=e,this.resourceManager=t,this.lastMouseMove=0}setupMouseHandlers(e,t){let n=this.robot;e.on("mouse-move",t(i=>{let s=Date.now();if(!(s-this.lastMouseMove<$.throttling.mouseThrottle)){this.lastMouseMove=s;try{let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),l=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(l,p),this.resourceManager.updateClientActivity(e.id)}catch(o){console.error("Mouse move error:",o.message)}}})),e.on("mouse-click",t(async i=>{try{let s=this.resourceManager.getClient(e.id);if(!s)return;let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),l=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(l,p),n.mouseClick(i.button||"left",i.double||!1),s.idleFrameCount=0,this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Mouse click error:",s.message)}})),e.on("mouse-press",t(async i=>{try{if(!this.resourceManager.getClient(e.id))return;let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),l=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(l,p),n.mouseToggle("down",i.button||"left"),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Mouse press error:",s.message)}})),e.on("mouse-release",t(async i=>{try{if(!this.resourceManager.getClient(e.id))return;let o=n.getScreenSize(),a=Math.round(i.x/100*o.width),c=Math.round(i.y/100*o.height),l=Math.max(0,Math.min(o.width-1,a)),p=Math.max(0,Math.min(o.height-1,c));n.moveMouse(l,p),n.mouseToggle("up",i.button||"left"),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Mouse release error:",s.message)}})),e.on("scroll",t(async i=>{try{let{direction:s,amount:o=60,horizontal:a=!1}=i,c=this.resourceManager.getClient(e.id);if(!c)return;let l=0,p=0;a||s==="left"||s==="right"?l=s==="right"?o:-o:p=s==="down"?-o:o,n.scrollMouse(l,p),c.idleFrameCount=0,this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Scroll error:",s.message)}})),e.on("mouse-drag-select",t(i=>{try{let{startX:s,startY:o,endX:a,endY:c}=i,l=n.getScreenSize(),p=Math.round(s/100*l.width),f=Math.round(o/100*l.height),h=Math.round(a/100*l.width),v=Math.round(c/100*l.height),x=Math.max(0,Math.min(l.width-1,p)),S=Math.max(0,Math.min(l.height-1,f)),A=Math.max(0,Math.min(l.width-1,h)),k=Math.max(0,Math.min(l.height-1,v));n.moveMouse(x,S),n.mouseToggle("down","left"),n.dragMouse(A,k),n.mouseToggle("up","left"),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Drag selection error:",s.message)}}))}}});var pS={};Vr(pS,{KeyboardHandler:()=>wh});function fB(r){let e;r.type==="missionControl"?e='tell application "System Events" to key code 160':e=`tell application "System Events" to key code ${r.keyCode} using ${r.mods}`,(0,uS.execFile)("osascript",["-e",e],t=>{t&&console.error("osascript error:",t.message)})}var uS,wh,fS=Ee(()=>{uS=require("child_process");at();wh=class{constructor(e,t){this.robot=e,this.resourceManager=t,this.lastKeyPress=0,this.lastTypeText=0}setupKeyboardHandlers(e,t){let n=this.robot;e.on("key-press",t(i=>{let s=Date.now();if(!(s-this.lastKeyPress<$.throttling.keyThrottle)){this.lastKeyPress=s;try{if(!i.key||typeof i.key!="string")return;let o=this.resourceManager.getClient(e.id),a=i.key,c=i.modifier||[];if(a.length===1)if(c.filter(p=>p!=="shift").length>0){n.keyTap(a.toLowerCase(),c);for(let p of c)n.keyToggle(p,"up")}else n.typeString(a);else{let p={return:"enter"}[a.toLowerCase()]??a.toLowerCase();n.keyTap(p,c)}o&&(o.idleFrameCount=0),this.resourceManager.updateClientActivity(e.id)}catch(o){console.error("Key press error:",o.message)}}})),e.on("desktop-switch",t(i=>{try{let s=i?.direction,o=$.desktopSwitch[process.platform]?.[s];if(!o)return;process.platform==="darwin"?fB(o):n.keyTap(o[0],o[1]);let a=this.resourceManager.getClient(e.id);a&&(a.idleFrameCount=0),this.resourceManager.updateClientActivity(e.id)}catch(s){console.error("Desktop switch error:",s.message)}})),e.on("type-text",t(i=>{let s=Date.now();if(!(s-this.lastTypeText<$.throttling.typeTextThrottle)){this.lastTypeText=s;try{if(!i.text||typeof i.text!="string")return;let o=i.text;o.length>$.throttling.maxTextLength&&(o=o.substring(0,$.throttling.maxTextLength));let a=o.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),c=this.resourceManager.getClient(e.id);setTimeout(()=>{try{n.typeString(a),this.resourceManager.updateClientActivity(e.id),c&&(c.idleFrameCount=0,c.tileManager&&c.tileManager.clearScreenCache())}catch(l){console.error("Robot typeString error:",l.message)}},10)}catch(o){console.error("Type text error:",o.message)}}}))}}});var Mh=R((WS,Oh)=>{(function(r,e){"use strict";function t(T,u){if(!T)throw new Error(u||"Assertion failed")}function n(T,u){T.super_=u;var m=function(){};m.prototype=u.prototype,T.prototype=new m,T.prototype.constructor=T}function i(T,u,m){if(i.isBN(T))return T;this.negative=0,this.words=null,this.length=0,this.red=null,T!==null&&((u==="le"||u==="be")&&(m=u,u=10),this._init(T||0,u||10,m||"be"))}typeof r=="object"?r.exports=i:e.BN=i,i.BN=i,i.wordSize=26;var s;try{typeof window<"u"&&typeof window.Buffer<"u"?s=window.Buffer:s=require("buffer").Buffer}catch{}i.isBN=function(u){return u instanceof i?!0:u!==null&&typeof u=="object"&&u.constructor.wordSize===i.wordSize&&Array.isArray(u.words)},i.max=function(u,m){return u.cmp(m)>0?u:m},i.min=function(u,m){return u.cmp(m)<0?u:m},i.prototype._init=function(u,m,y){if(typeof u=="number")return this._initNumber(u,m,y);if(typeof u=="object")return this._initArray(u,m,y);m==="hex"&&(m=16),t(m===(m|0)&&m>=2&&m<=36),u=u.toString().replace(/\s+/g,"");var w=0;u[0]==="-"&&(w++,this.negative=1),w<u.length&&(m===16?this._parseHex(u,w,y):(this._parseBase(u,m,w),y==="le"&&this._initArray(this.toArray(),m,y)))},i.prototype._initNumber=function(u,m,y){u<0&&(this.negative=1,u=-u),u<67108864?(this.words=[u&67108863],this.length=1):u<4503599627370496?(this.words=[u&67108863,u/67108864&67108863],this.length=2):(t(u<9007199254740992),this.words=[u&67108863,u/67108864&67108863,1],this.length=3),y==="le"&&this._initArray(this.toArray(),m,y)},i.prototype._initArray=function(u,m,y){if(t(typeof u.length=="number"),u.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(u.length/3),this.words=new Array(this.length);for(var w=0;w<this.length;w++)this.words[w]=0;var g,_,C=0;if(y==="be")for(w=u.length-1,g=0;w>=0;w-=3)_=u[w]|u[w-1]<<8|u[w-2]<<16,this.words[g]|=_<<C&67108863,this.words[g+1]=_>>>26-C&67108863,C+=24,C>=26&&(C-=26,g++);else if(y==="le")for(w=0,g=0;w<u.length;w+=3)_=u[w]|u[w+1]<<8|u[w+2]<<16,this.words[g]|=_<<C&67108863,this.words[g+1]=_>>>26-C&67108863,C+=24,C>=26&&(C-=26,g++);return this.strip()};function o(T,u){var m=T.charCodeAt(u);return m>=65&&m<=70?m-55:m>=97&&m<=102?m-87:m-48&15}function a(T,u,m){var y=o(T,m);return m-1>=u&&(y|=o(T,m-1)<<4),y}i.prototype._parseHex=function(u,m,y){this.length=Math.ceil((u.length-m)/6),this.words=new Array(this.length);for(var w=0;w<this.length;w++)this.words[w]=0;var g=0,_=0,C;if(y==="be")for(w=u.length-1;w>=m;w-=2)C=a(u,m,w)<<g,this.words[_]|=C&67108863,g>=18?(g-=18,_+=1,this.words[_]|=C>>>26):g+=8;else{var b=u.length-m;for(w=b%2===0?m+1:m;w<u.length;w+=2)C=a(u,m,w)<<g,this.words[_]|=C&67108863,g>=18?(g-=18,_+=1,this.words[_]|=C>>>26):g+=8}this.strip()};function c(T,u,m,y){for(var w=0,g=Math.min(T.length,m),_=u;_<g;_++){var C=T.charCodeAt(_)-48;w*=y,C>=49?w+=C-49+10:C>=17?w+=C-17+10:w+=C}return w}i.prototype._parseBase=function(u,m,y){this.words=[0],this.length=1;for(var w=0,g=1;g<=67108863;g*=m)w++;w--,g=g/m|0;for(var _=u.length-y,C=_%w,b=Math.min(_,_-C)+y,d=0,E=y;E<b;E+=w)d=c(u,E,E+w,m),this.imuln(g),this.words[0]+d<67108864?this.words[0]+=d:this._iaddn(d);if(C!==0){var q=1;for(d=c(u,E,u.length,m),E=0;E<C;E++)q*=m;this.imuln(q),this.words[0]+d<67108864?this.words[0]+=d:this._iaddn(d)}this.strip()},i.prototype.copy=function(u){u.words=new Array(this.length);for(var m=0;m<this.length;m++)u.words[m]=this.words[m];u.length=this.length,u.negative=this.negative,u.red=this.red},i.prototype.clone=function(){var u=new i(null);return this.copy(u),u},i.prototype._expand=function(u){for(;this.length<u;)this.words[this.length++]=0;return this},i.prototype.strip=function(){for(;this.length>1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},i.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},i.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var l=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],p=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],f=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];i.prototype.toString=function(u,m){u=u||10,m=m|0||1;var y;if(u===16||u==="hex"){y="";for(var w=0,g=0,_=0;_<this.length;_++){var C=this.words[_],b=((C<<w|g)&16777215).toString(16);g=C>>>24-w&16777215,w+=2,w>=26&&(w-=26,_--),g!==0||_!==this.length-1?y=l[6-b.length]+b+y:y=b+y}for(g!==0&&(y=g.toString(16)+y);y.length%m!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}if(u===(u|0)&&u>=2&&u<=36){var d=p[u],E=f[u];y="";var q=this.clone();for(q.negative=0;!q.isZero();){var O=q.modn(E).toString(u);q=q.idivn(E),q.isZero()?y=O+y:y=l[d-O.length]+O+y}for(this.isZero()&&(y="0"+y);y.length%m!==0;)y="0"+y;return this.negative!==0&&(y="-"+y),y}t(!1,"Base should be between 2 and 36")},i.prototype.toNumber=function(){var u=this.words[0];return this.length===2?u+=this.words[1]*67108864:this.length===3&&this.words[2]===1?u+=4503599627370496+this.words[1]*67108864:this.length>2&&t(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-u:u},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toBuffer=function(u,m){return t(typeof s<"u"),this.toArrayLike(s,u,m)},i.prototype.toArray=function(u,m){return this.toArrayLike(Array,u,m)},i.prototype.toArrayLike=function(u,m,y){var w=this.byteLength(),g=y||Math.max(1,w);t(w<=g,"byte array longer than desired length"),t(g>0,"Requested array length <= 0"),this.strip();var _=m==="le",C=new u(g),b,d,E=this.clone();if(_){for(d=0;!E.isZero();d++)b=E.andln(255),E.iushrn(8),C[d]=b;for(;d<g;d++)C[d]=0}else{for(d=0;d<g-w;d++)C[d]=0;for(d=0;!E.isZero();d++)b=E.andln(255),E.iushrn(8),C[g-d-1]=b}return C},Math.clz32?i.prototype._countBits=function(u){return 32-Math.clz32(u)}:i.prototype._countBits=function(u){var m=u,y=0;return m>=4096&&(y+=13,m>>>=13),m>=64&&(y+=7,m>>>=7),m>=8&&(y+=4,m>>>=4),m>=2&&(y+=2,m>>>=2),y+m},i.prototype._zeroBits=function(u){if(u===0)return 26;var m=u,y=0;return(m&8191)===0&&(y+=13,m>>>=13),(m&127)===0&&(y+=7,m>>>=7),(m&15)===0&&(y+=4,m>>>=4),(m&3)===0&&(y+=2,m>>>=2),(m&1)===0&&y++,y},i.prototype.bitLength=function(){var u=this.words[this.length-1],m=this._countBits(u);return(this.length-1)*26+m};function h(T){for(var u=new Array(T.bitLength()),m=0;m<u.length;m++){var y=m/26|0,w=m%26;u[m]=(T.words[y]&1<<w)>>>w}return u}i.prototype.zeroBits=function(){if(this.isZero())return 0;for(var u=0,m=0;m<this.length;m++){var y=this._zeroBits(this.words[m]);if(u+=y,y!==26)break}return u},i.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},i.prototype.toTwos=function(u){return this.negative!==0?this.abs().inotn(u).iaddn(1):this.clone()},i.prototype.fromTwos=function(u){return this.testn(u-1)?this.notn(u).iaddn(1).ineg():this.clone()},i.prototype.isNeg=function(){return this.negative!==0},i.prototype.neg=function(){return this.clone().ineg()},i.prototype.ineg=function(){return this.isZero()||(this.negative^=1),this},i.prototype.iuor=function(u){for(;this.length<u.length;)this.words[this.length++]=0;for(var m=0;m<u.length;m++)this.words[m]=this.words[m]|u.words[m];return this.strip()},i.prototype.ior=function(u){return t((this.negative|u.negative)===0),this.iuor(u)},i.prototype.or=function(u){return this.length>u.length?this.clone().ior(u):u.clone().ior(this)},i.prototype.uor=function(u){return this.length>u.length?this.clone().iuor(u):u.clone().iuor(this)},i.prototype.iuand=function(u){var m;this.length>u.length?m=u:m=this;for(var y=0;y<m.length;y++)this.words[y]=this.words[y]&u.words[y];return this.length=m.length,this.strip()},i.prototype.iand=function(u){return t((this.negative|u.negative)===0),this.iuand(u)},i.prototype.and=function(u){return this.length>u.length?this.clone().iand(u):u.clone().iand(this)},i.prototype.uand=function(u){return this.length>u.length?this.clone().iuand(u):u.clone().iuand(this)},i.prototype.iuxor=function(u){var m,y;this.length>u.length?(m=this,y=u):(m=u,y=this);for(var w=0;w<y.length;w++)this.words[w]=m.words[w]^y.words[w];if(this!==m)for(;w<m.length;w++)this.words[w]=m.words[w];return this.length=m.length,this.strip()},i.prototype.ixor=function(u){return t((this.negative|u.negative)===0),this.iuxor(u)},i.prototype.xor=function(u){return this.length>u.length?this.clone().ixor(u):u.clone().ixor(this)},i.prototype.uxor=function(u){return this.length>u.length?this.clone().iuxor(u):u.clone().iuxor(this)},i.prototype.inotn=function(u){t(typeof u=="number"&&u>=0);var m=Math.ceil(u/26)|0,y=u%26;this._expand(m),y>0&&m--;for(var w=0;w<m;w++)this.words[w]=~this.words[w]&67108863;return y>0&&(this.words[w]=~this.words[w]&67108863>>26-y),this.strip()},i.prototype.notn=function(u){return this.clone().inotn(u)},i.prototype.setn=function(u,m){t(typeof u=="number"&&u>=0);var y=u/26|0,w=u%26;return this._expand(y+1),m?this.words[y]=this.words[y]|1<<w:this.words[y]=this.words[y]&~(1<<w),this.strip()},i.prototype.iadd=function(u){var m;if(this.negative!==0&&u.negative===0)return this.negative=0,m=this.isub(u),this.negative^=1,this._normSign();if(this.negative===0&&u.negative!==0)return u.negative=0,m=this.isub(u),u.negative=1,m._normSign();var y,w;this.length>u.length?(y=this,w=u):(y=u,w=this);for(var g=0,_=0;_<w.length;_++)m=(y.words[_]|0)+(w.words[_]|0)+g,this.words[_]=m&67108863,g=m>>>26;for(;g!==0&&_<y.length;_++)m=(y.words[_]|0)+g,this.words[_]=m&67108863,g=m>>>26;if(this.length=y.length,g!==0)this.words[this.length]=g,this.length++;else if(y!==this)for(;_<y.length;_++)this.words[_]=y.words[_];return this},i.prototype.add=function(u){var m;return u.negative!==0&&this.negative===0?(u.negative=0,m=this.sub(u),u.negative^=1,m):u.negative===0&&this.negative!==0?(this.negative=0,m=u.sub(this),this.negative=1,m):this.length>u.length?this.clone().iadd(u):u.clone().iadd(this)},i.prototype.isub=function(u){if(u.negative!==0){u.negative=0;var m=this.iadd(u);return u.negative=1,m._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(u),this.negative=1,this._normSign();var y=this.cmp(u);if(y===0)return this.negative=0,this.length=1,this.words[0]=0,this;var w,g;y>0?(w=this,g=u):(w=u,g=this);for(var _=0,C=0;C<g.length;C++)m=(w.words[C]|0)-(g.words[C]|0)+_,_=m>>26,this.words[C]=m&67108863;for(;_!==0&&C<w.length;C++)m=(w.words[C]|0)+_,_=m>>26,this.words[C]=m&67108863;if(_===0&&C<w.length&&w!==this)for(;C<w.length;C++)this.words[C]=w.words[C];return this.length=Math.max(this.length,C),w!==this&&(this.negative=1),this.strip()},i.prototype.sub=function(u){return this.clone().isub(u)};function v(T,u,m){m.negative=u.negative^T.negative;var y=T.length+u.length|0;m.length=y,y=y-1|0;var w=T.words[0]|0,g=u.words[0]|0,_=w*g,C=_&67108863,b=_/67108864|0;m.words[0]=C;for(var d=1;d<y;d++){for(var E=b>>>26,q=b&67108863,O=Math.min(d,u.length-1),M=Math.max(0,d-T.length+1);M<=O;M++){var j=d-M|0;w=T.words[j]|0,g=u.words[M]|0,_=w*g+q,E+=_/67108864|0,q=_&67108863}m.words[d]=q|0,b=E|0}return b!==0?m.words[d]=b|0:m.length--,m.strip()}var x=function(u,m,y){var w=u.words,g=m.words,_=y.words,C=0,b,d,E,q=w[0]|0,O=q&8191,M=q>>>13,j=w[1]|0,z=j&8191,U=j>>>13,Te=w[2]|0,ne=Te&8191,N=Te>>>13,te=w[3]|0,D=te&8191,W=te>>>13,se=w[4]|0,Z=se&8191,J=se>>>13,Tt=w[5]|0,oe=Tt&8191,Oe=Tt>>>13,jg=w[6]|0,Me=jg&8191,Pe=jg>>>13,Fg=w[7]|0,Ie=Fg&8191,Ne=Fg>>>13,Ug=w[8]|0,Le=Ug&8191,De=Ug>>>13,qg=w[9]|0,Be=qg&8191,je=qg>>>13,Hg=g[0]|0,Fe=Hg&8191,Ue=Hg>>>13,$g=g[1]|0,qe=$g&8191,He=$g>>>13,Wg=g[2]|0,$e=Wg&8191,We=Wg>>>13,Gg=g[3]|0,Ge=Gg&8191,ze=Gg>>>13,zg=g[4]|0,Ve=zg&8191,Ke=zg>>>13,Vg=g[5]|0,Ye=Vg&8191,Je=Vg>>>13,Kg=g[6]|0,Xe=Kg&8191,Ze=Kg>>>13,Yg=g[7]|0,Qe=Yg&8191,et=Yg>>>13,Jg=g[8]|0,tt=Jg&8191,rt=Jg>>>13,Xg=g[9]|0,nt=Xg&8191,it=Xg>>>13;y.negative=u.negative^m.negative,y.length=19,b=Math.imul(O,Fe),d=Math.imul(O,Ue),d=d+Math.imul(M,Fe)|0,E=Math.imul(M,Ue);var Yu=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(Yu>>>26)|0,Yu&=67108863,b=Math.imul(z,Fe),d=Math.imul(z,Ue),d=d+Math.imul(U,Fe)|0,E=Math.imul(U,Ue),b=b+Math.imul(O,qe)|0,d=d+Math.imul(O,He)|0,d=d+Math.imul(M,qe)|0,E=E+Math.imul(M,He)|0;var Ju=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(Ju>>>26)|0,Ju&=67108863,b=Math.imul(ne,Fe),d=Math.imul(ne,Ue),d=d+Math.imul(N,Fe)|0,E=Math.imul(N,Ue),b=b+Math.imul(z,qe)|0,d=d+Math.imul(z,He)|0,d=d+Math.imul(U,qe)|0,E=E+Math.imul(U,He)|0,b=b+Math.imul(O,$e)|0,d=d+Math.imul(O,We)|0,d=d+Math.imul(M,$e)|0,E=E+Math.imul(M,We)|0;var Xu=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(Xu>>>26)|0,Xu&=67108863,b=Math.imul(D,Fe),d=Math.imul(D,Ue),d=d+Math.imul(W,Fe)|0,E=Math.imul(W,Ue),b=b+Math.imul(ne,qe)|0,d=d+Math.imul(ne,He)|0,d=d+Math.imul(N,qe)|0,E=E+Math.imul(N,He)|0,b=b+Math.imul(z,$e)|0,d=d+Math.imul(z,We)|0,d=d+Math.imul(U,$e)|0,E=E+Math.imul(U,We)|0,b=b+Math.imul(O,Ge)|0,d=d+Math.imul(O,ze)|0,d=d+Math.imul(M,Ge)|0,E=E+Math.imul(M,ze)|0;var Zu=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(Zu>>>26)|0,Zu&=67108863,b=Math.imul(Z,Fe),d=Math.imul(Z,Ue),d=d+Math.imul(J,Fe)|0,E=Math.imul(J,Ue),b=b+Math.imul(D,qe)|0,d=d+Math.imul(D,He)|0,d=d+Math.imul(W,qe)|0,E=E+Math.imul(W,He)|0,b=b+Math.imul(ne,$e)|0,d=d+Math.imul(ne,We)|0,d=d+Math.imul(N,$e)|0,E=E+Math.imul(N,We)|0,b=b+Math.imul(z,Ge)|0,d=d+Math.imul(z,ze)|0,d=d+Math.imul(U,Ge)|0,E=E+Math.imul(U,ze)|0,b=b+Math.imul(O,Ve)|0,d=d+Math.imul(O,Ke)|0,d=d+Math.imul(M,Ve)|0,E=E+Math.imul(M,Ke)|0;var Qu=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(Qu>>>26)|0,Qu&=67108863,b=Math.imul(oe,Fe),d=Math.imul(oe,Ue),d=d+Math.imul(Oe,Fe)|0,E=Math.imul(Oe,Ue),b=b+Math.imul(Z,qe)|0,d=d+Math.imul(Z,He)|0,d=d+Math.imul(J,qe)|0,E=E+Math.imul(J,He)|0,b=b+Math.imul(D,$e)|0,d=d+Math.imul(D,We)|0,d=d+Math.imul(W,$e)|0,E=E+Math.imul(W,We)|0,b=b+Math.imul(ne,Ge)|0,d=d+Math.imul(ne,ze)|0,d=d+Math.imul(N,Ge)|0,E=E+Math.imul(N,ze)|0,b=b+Math.imul(z,Ve)|0,d=d+Math.imul(z,Ke)|0,d=d+Math.imul(U,Ve)|0,E=E+Math.imul(U,Ke)|0,b=b+Math.imul(O,Ye)|0,d=d+Math.imul(O,Je)|0,d=d+Math.imul(M,Ye)|0,E=E+Math.imul(M,Je)|0;var ep=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(ep>>>26)|0,ep&=67108863,b=Math.imul(Me,Fe),d=Math.imul(Me,Ue),d=d+Math.imul(Pe,Fe)|0,E=Math.imul(Pe,Ue),b=b+Math.imul(oe,qe)|0,d=d+Math.imul(oe,He)|0,d=d+Math.imul(Oe,qe)|0,E=E+Math.imul(Oe,He)|0,b=b+Math.imul(Z,$e)|0,d=d+Math.imul(Z,We)|0,d=d+Math.imul(J,$e)|0,E=E+Math.imul(J,We)|0,b=b+Math.imul(D,Ge)|0,d=d+Math.imul(D,ze)|0,d=d+Math.imul(W,Ge)|0,E=E+Math.imul(W,ze)|0,b=b+Math.imul(ne,Ve)|0,d=d+Math.imul(ne,Ke)|0,d=d+Math.imul(N,Ve)|0,E=E+Math.imul(N,Ke)|0,b=b+Math.imul(z,Ye)|0,d=d+Math.imul(z,Je)|0,d=d+Math.imul(U,Ye)|0,E=E+Math.imul(U,Je)|0,b=b+Math.imul(O,Xe)|0,d=d+Math.imul(O,Ze)|0,d=d+Math.imul(M,Xe)|0,E=E+Math.imul(M,Ze)|0;var tp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(tp>>>26)|0,tp&=67108863,b=Math.imul(Ie,Fe),d=Math.imul(Ie,Ue),d=d+Math.imul(Ne,Fe)|0,E=Math.imul(Ne,Ue),b=b+Math.imul(Me,qe)|0,d=d+Math.imul(Me,He)|0,d=d+Math.imul(Pe,qe)|0,E=E+Math.imul(Pe,He)|0,b=b+Math.imul(oe,$e)|0,d=d+Math.imul(oe,We)|0,d=d+Math.imul(Oe,$e)|0,E=E+Math.imul(Oe,We)|0,b=b+Math.imul(Z,Ge)|0,d=d+Math.imul(Z,ze)|0,d=d+Math.imul(J,Ge)|0,E=E+Math.imul(J,ze)|0,b=b+Math.imul(D,Ve)|0,d=d+Math.imul(D,Ke)|0,d=d+Math.imul(W,Ve)|0,E=E+Math.imul(W,Ke)|0,b=b+Math.imul(ne,Ye)|0,d=d+Math.imul(ne,Je)|0,d=d+Math.imul(N,Ye)|0,E=E+Math.imul(N,Je)|0,b=b+Math.imul(z,Xe)|0,d=d+Math.imul(z,Ze)|0,d=d+Math.imul(U,Xe)|0,E=E+Math.imul(U,Ze)|0,b=b+Math.imul(O,Qe)|0,d=d+Math.imul(O,et)|0,d=d+Math.imul(M,Qe)|0,E=E+Math.imul(M,et)|0;var rp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(rp>>>26)|0,rp&=67108863,b=Math.imul(Le,Fe),d=Math.imul(Le,Ue),d=d+Math.imul(De,Fe)|0,E=Math.imul(De,Ue),b=b+Math.imul(Ie,qe)|0,d=d+Math.imul(Ie,He)|0,d=d+Math.imul(Ne,qe)|0,E=E+Math.imul(Ne,He)|0,b=b+Math.imul(Me,$e)|0,d=d+Math.imul(Me,We)|0,d=d+Math.imul(Pe,$e)|0,E=E+Math.imul(Pe,We)|0,b=b+Math.imul(oe,Ge)|0,d=d+Math.imul(oe,ze)|0,d=d+Math.imul(Oe,Ge)|0,E=E+Math.imul(Oe,ze)|0,b=b+Math.imul(Z,Ve)|0,d=d+Math.imul(Z,Ke)|0,d=d+Math.imul(J,Ve)|0,E=E+Math.imul(J,Ke)|0,b=b+Math.imul(D,Ye)|0,d=d+Math.imul(D,Je)|0,d=d+Math.imul(W,Ye)|0,E=E+Math.imul(W,Je)|0,b=b+Math.imul(ne,Xe)|0,d=d+Math.imul(ne,Ze)|0,d=d+Math.imul(N,Xe)|0,E=E+Math.imul(N,Ze)|0,b=b+Math.imul(z,Qe)|0,d=d+Math.imul(z,et)|0,d=d+Math.imul(U,Qe)|0,E=E+Math.imul(U,et)|0,b=b+Math.imul(O,tt)|0,d=d+Math.imul(O,rt)|0,d=d+Math.imul(M,tt)|0,E=E+Math.imul(M,rt)|0;var np=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(np>>>26)|0,np&=67108863,b=Math.imul(Be,Fe),d=Math.imul(Be,Ue),d=d+Math.imul(je,Fe)|0,E=Math.imul(je,Ue),b=b+Math.imul(Le,qe)|0,d=d+Math.imul(Le,He)|0,d=d+Math.imul(De,qe)|0,E=E+Math.imul(De,He)|0,b=b+Math.imul(Ie,$e)|0,d=d+Math.imul(Ie,We)|0,d=d+Math.imul(Ne,$e)|0,E=E+Math.imul(Ne,We)|0,b=b+Math.imul(Me,Ge)|0,d=d+Math.imul(Me,ze)|0,d=d+Math.imul(Pe,Ge)|0,E=E+Math.imul(Pe,ze)|0,b=b+Math.imul(oe,Ve)|0,d=d+Math.imul(oe,Ke)|0,d=d+Math.imul(Oe,Ve)|0,E=E+Math.imul(Oe,Ke)|0,b=b+Math.imul(Z,Ye)|0,d=d+Math.imul(Z,Je)|0,d=d+Math.imul(J,Ye)|0,E=E+Math.imul(J,Je)|0,b=b+Math.imul(D,Xe)|0,d=d+Math.imul(D,Ze)|0,d=d+Math.imul(W,Xe)|0,E=E+Math.imul(W,Ze)|0,b=b+Math.imul(ne,Qe)|0,d=d+Math.imul(ne,et)|0,d=d+Math.imul(N,Qe)|0,E=E+Math.imul(N,et)|0,b=b+Math.imul(z,tt)|0,d=d+Math.imul(z,rt)|0,d=d+Math.imul(U,tt)|0,E=E+Math.imul(U,rt)|0,b=b+Math.imul(O,nt)|0,d=d+Math.imul(O,it)|0,d=d+Math.imul(M,nt)|0,E=E+Math.imul(M,it)|0;var ip=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(ip>>>26)|0,ip&=67108863,b=Math.imul(Be,qe),d=Math.imul(Be,He),d=d+Math.imul(je,qe)|0,E=Math.imul(je,He),b=b+Math.imul(Le,$e)|0,d=d+Math.imul(Le,We)|0,d=d+Math.imul(De,$e)|0,E=E+Math.imul(De,We)|0,b=b+Math.imul(Ie,Ge)|0,d=d+Math.imul(Ie,ze)|0,d=d+Math.imul(Ne,Ge)|0,E=E+Math.imul(Ne,ze)|0,b=b+Math.imul(Me,Ve)|0,d=d+Math.imul(Me,Ke)|0,d=d+Math.imul(Pe,Ve)|0,E=E+Math.imul(Pe,Ke)|0,b=b+Math.imul(oe,Ye)|0,d=d+Math.imul(oe,Je)|0,d=d+Math.imul(Oe,Ye)|0,E=E+Math.imul(Oe,Je)|0,b=b+Math.imul(Z,Xe)|0,d=d+Math.imul(Z,Ze)|0,d=d+Math.imul(J,Xe)|0,E=E+Math.imul(J,Ze)|0,b=b+Math.imul(D,Qe)|0,d=d+Math.imul(D,et)|0,d=d+Math.imul(W,Qe)|0,E=E+Math.imul(W,et)|0,b=b+Math.imul(ne,tt)|0,d=d+Math.imul(ne,rt)|0,d=d+Math.imul(N,tt)|0,E=E+Math.imul(N,rt)|0,b=b+Math.imul(z,nt)|0,d=d+Math.imul(z,it)|0,d=d+Math.imul(U,nt)|0,E=E+Math.imul(U,it)|0;var sp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(sp>>>26)|0,sp&=67108863,b=Math.imul(Be,$e),d=Math.imul(Be,We),d=d+Math.imul(je,$e)|0,E=Math.imul(je,We),b=b+Math.imul(Le,Ge)|0,d=d+Math.imul(Le,ze)|0,d=d+Math.imul(De,Ge)|0,E=E+Math.imul(De,ze)|0,b=b+Math.imul(Ie,Ve)|0,d=d+Math.imul(Ie,Ke)|0,d=d+Math.imul(Ne,Ve)|0,E=E+Math.imul(Ne,Ke)|0,b=b+Math.imul(Me,Ye)|0,d=d+Math.imul(Me,Je)|0,d=d+Math.imul(Pe,Ye)|0,E=E+Math.imul(Pe,Je)|0,b=b+Math.imul(oe,Xe)|0,d=d+Math.imul(oe,Ze)|0,d=d+Math.imul(Oe,Xe)|0,E=E+Math.imul(Oe,Ze)|0,b=b+Math.imul(Z,Qe)|0,d=d+Math.imul(Z,et)|0,d=d+Math.imul(J,Qe)|0,E=E+Math.imul(J,et)|0,b=b+Math.imul(D,tt)|0,d=d+Math.imul(D,rt)|0,d=d+Math.imul(W,tt)|0,E=E+Math.imul(W,rt)|0,b=b+Math.imul(ne,nt)|0,d=d+Math.imul(ne,it)|0,d=d+Math.imul(N,nt)|0,E=E+Math.imul(N,it)|0;var op=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(op>>>26)|0,op&=67108863,b=Math.imul(Be,Ge),d=Math.imul(Be,ze),d=d+Math.imul(je,Ge)|0,E=Math.imul(je,ze),b=b+Math.imul(Le,Ve)|0,d=d+Math.imul(Le,Ke)|0,d=d+Math.imul(De,Ve)|0,E=E+Math.imul(De,Ke)|0,b=b+Math.imul(Ie,Ye)|0,d=d+Math.imul(Ie,Je)|0,d=d+Math.imul(Ne,Ye)|0,E=E+Math.imul(Ne,Je)|0,b=b+Math.imul(Me,Xe)|0,d=d+Math.imul(Me,Ze)|0,d=d+Math.imul(Pe,Xe)|0,E=E+Math.imul(Pe,Ze)|0,b=b+Math.imul(oe,Qe)|0,d=d+Math.imul(oe,et)|0,d=d+Math.imul(Oe,Qe)|0,E=E+Math.imul(Oe,et)|0,b=b+Math.imul(Z,tt)|0,d=d+Math.imul(Z,rt)|0,d=d+Math.imul(J,tt)|0,E=E+Math.imul(J,rt)|0,b=b+Math.imul(D,nt)|0,d=d+Math.imul(D,it)|0,d=d+Math.imul(W,nt)|0,E=E+Math.imul(W,it)|0;var ap=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(ap>>>26)|0,ap&=67108863,b=Math.imul(Be,Ve),d=Math.imul(Be,Ke),d=d+Math.imul(je,Ve)|0,E=Math.imul(je,Ke),b=b+Math.imul(Le,Ye)|0,d=d+Math.imul(Le,Je)|0,d=d+Math.imul(De,Ye)|0,E=E+Math.imul(De,Je)|0,b=b+Math.imul(Ie,Xe)|0,d=d+Math.imul(Ie,Ze)|0,d=d+Math.imul(Ne,Xe)|0,E=E+Math.imul(Ne,Ze)|0,b=b+Math.imul(Me,Qe)|0,d=d+Math.imul(Me,et)|0,d=d+Math.imul(Pe,Qe)|0,E=E+Math.imul(Pe,et)|0,b=b+Math.imul(oe,tt)|0,d=d+Math.imul(oe,rt)|0,d=d+Math.imul(Oe,tt)|0,E=E+Math.imul(Oe,rt)|0,b=b+Math.imul(Z,nt)|0,d=d+Math.imul(Z,it)|0,d=d+Math.imul(J,nt)|0,E=E+Math.imul(J,it)|0;var cp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(cp>>>26)|0,cp&=67108863,b=Math.imul(Be,Ye),d=Math.imul(Be,Je),d=d+Math.imul(je,Ye)|0,E=Math.imul(je,Je),b=b+Math.imul(Le,Xe)|0,d=d+Math.imul(Le,Ze)|0,d=d+Math.imul(De,Xe)|0,E=E+Math.imul(De,Ze)|0,b=b+Math.imul(Ie,Qe)|0,d=d+Math.imul(Ie,et)|0,d=d+Math.imul(Ne,Qe)|0,E=E+Math.imul(Ne,et)|0,b=b+Math.imul(Me,tt)|0,d=d+Math.imul(Me,rt)|0,d=d+Math.imul(Pe,tt)|0,E=E+Math.imul(Pe,rt)|0,b=b+Math.imul(oe,nt)|0,d=d+Math.imul(oe,it)|0,d=d+Math.imul(Oe,nt)|0,E=E+Math.imul(Oe,it)|0;var lp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(lp>>>26)|0,lp&=67108863,b=Math.imul(Be,Xe),d=Math.imul(Be,Ze),d=d+Math.imul(je,Xe)|0,E=Math.imul(je,Ze),b=b+Math.imul(Le,Qe)|0,d=d+Math.imul(Le,et)|0,d=d+Math.imul(De,Qe)|0,E=E+Math.imul(De,et)|0,b=b+Math.imul(Ie,tt)|0,d=d+Math.imul(Ie,rt)|0,d=d+Math.imul(Ne,tt)|0,E=E+Math.imul(Ne,rt)|0,b=b+Math.imul(Me,nt)|0,d=d+Math.imul(Me,it)|0,d=d+Math.imul(Pe,nt)|0,E=E+Math.imul(Pe,it)|0;var up=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(up>>>26)|0,up&=67108863,b=Math.imul(Be,Qe),d=Math.imul(Be,et),d=d+Math.imul(je,Qe)|0,E=Math.imul(je,et),b=b+Math.imul(Le,tt)|0,d=d+Math.imul(Le,rt)|0,d=d+Math.imul(De,tt)|0,E=E+Math.imul(De,rt)|0,b=b+Math.imul(Ie,nt)|0,d=d+Math.imul(Ie,it)|0,d=d+Math.imul(Ne,nt)|0,E=E+Math.imul(Ne,it)|0;var pp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(pp>>>26)|0,pp&=67108863,b=Math.imul(Be,tt),d=Math.imul(Be,rt),d=d+Math.imul(je,tt)|0,E=Math.imul(je,rt),b=b+Math.imul(Le,nt)|0,d=d+Math.imul(Le,it)|0,d=d+Math.imul(De,nt)|0,E=E+Math.imul(De,it)|0;var fp=(C+b|0)+((d&8191)<<13)|0;C=(E+(d>>>13)|0)+(fp>>>26)|0,fp&=67108863,b=Math.imul(Be,nt),d=Math.imul(Be,it),d=d+Math.imul(je,nt)|0,E=Math.imul(je,it);var dp=(C+b|0)+((d&8191)<<13)|0;return C=(E+(d>>>13)|0)+(dp>>>26)|0,dp&=67108863,_[0]=Yu,_[1]=Ju,_[2]=Xu,_[3]=Zu,_[4]=Qu,_[5]=ep,_[6]=tp,_[7]=rp,_[8]=np,_[9]=ip,_[10]=sp,_[11]=op,_[12]=ap,_[13]=cp,_[14]=lp,_[15]=up,_[16]=pp,_[17]=fp,_[18]=dp,C!==0&&(_[19]=C,y.length++),y};Math.imul||(x=v);function S(T,u,m){m.negative=u.negative^T.negative,m.length=T.length+u.length;for(var y=0,w=0,g=0;g<m.length-1;g++){var _=w;w=0;for(var C=y&67108863,b=Math.min(g,u.length-1),d=Math.max(0,g-T.length+1);d<=b;d++){var E=g-d,q=T.words[E]|0,O=u.words[d]|0,M=q*O,j=M&67108863;_=_+(M/67108864|0)|0,j=j+C|0,C=j&67108863,_=_+(j>>>26)|0,w+=_>>>26,_&=67108863}m.words[g]=C,y=_,_=w}return y!==0?m.words[g]=y:m.length--,m.strip()}function A(T,u,m){var y=new k;return y.mulp(T,u,m)}i.prototype.mulTo=function(u,m){var y,w=this.length+u.length;return this.length===10&&u.length===10?y=x(this,u,m):w<63?y=v(this,u,m):w<1024?y=S(this,u,m):y=A(this,u,m),y};function k(T,u){this.x=T,this.y=u}k.prototype.makeRBT=function(u){for(var m=new Array(u),y=i.prototype._countBits(u)-1,w=0;w<u;w++)m[w]=this.revBin(w,y,u);return m},k.prototype.revBin=function(u,m,y){if(u===0||u===y-1)return u;for(var w=0,g=0;g<m;g++)w|=(u&1)<<m-g-1,u>>=1;return w},k.prototype.permute=function(u,m,y,w,g,_){for(var C=0;C<_;C++)w[C]=m[u[C]],g[C]=y[u[C]]},k.prototype.transform=function(u,m,y,w,g,_){this.permute(_,u,m,y,w,g);for(var C=1;C<g;C<<=1)for(var b=C<<1,d=Math.cos(2*Math.PI/b),E=Math.sin(2*Math.PI/b),q=0;q<g;q+=b)for(var O=d,M=E,j=0;j<C;j++){var z=y[q+j],U=w[q+j],Te=y[q+j+C],ne=w[q+j+C],N=O*Te-M*ne;ne=O*ne+M*Te,Te=N,y[q+j]=z+Te,w[q+j]=U+ne,y[q+j+C]=z-Te,w[q+j+C]=U-ne,j!==b&&(N=d*O-E*M,M=d*M+E*O,O=N)}},k.prototype.guessLen13b=function(u,m){var y=Math.max(m,u)|1,w=y&1,g=0;for(y=y/2|0;y;y=y>>>1)g++;return 1<<g+1+w},k.prototype.conjugate=function(u,m,y){if(!(y<=1))for(var w=0;w<y/2;w++){var g=u[w];u[w]=u[y-w-1],u[y-w-1]=g,g=m[w],m[w]=-m[y-w-1],m[y-w-1]=-g}},k.prototype.normalize13b=function(u,m){for(var y=0,w=0;w<m/2;w++){var g=Math.round(u[2*w+1]/m)*8192+Math.round(u[2*w]/m)+y;u[w]=g&67108863,g<67108864?y=0:y=g/67108864|0}return u},k.prototype.convert13b=function(u,m,y,w){for(var g=0,_=0;_<m;_++)g=g+(u[_]|0),y[2*_]=g&8191,g=g>>>13,y[2*_+1]=g&8191,g=g>>>13;for(_=2*m;_<w;++_)y[_]=0;t(g===0),t((g&-8192)===0)},k.prototype.stub=function(u){for(var m=new Array(u),y=0;y<u;y++)m[y]=0;return m},k.prototype.mulp=function(u,m,y){var w=2*this.guessLen13b(u.length,m.length),g=this.makeRBT(w),_=this.stub(w),C=new Array(w),b=new Array(w),d=new Array(w),E=new Array(w),q=new Array(w),O=new Array(w),M=y.words;M.length=w,this.convert13b(u.words,u.length,C,w),this.convert13b(m.words,m.length,E,w),this.transform(C,_,b,d,w,g),this.transform(E,_,q,O,w,g);for(var j=0;j<w;j++){var z=b[j]*q[j]-d[j]*O[j];d[j]=b[j]*O[j]+d[j]*q[j],b[j]=z}return this.conjugate(b,d,w),this.transform(b,d,M,_,w,g),this.conjugate(M,_,w),this.normalize13b(M,w),y.negative=u.negative^m.negative,y.length=u.length+m.length,y.strip()},i.prototype.mul=function(u){var m=new i(null);return m.words=new Array(this.length+u.length),this.mulTo(u,m)},i.prototype.mulf=function(u){var m=new i(null);return m.words=new Array(this.length+u.length),A(this,u,m)},i.prototype.imul=function(u){return this.clone().mulTo(u,this)},i.prototype.imuln=function(u){t(typeof u=="number"),t(u<67108864);for(var m=0,y=0;y<this.length;y++){var w=(this.words[y]|0)*u,g=(w&67108863)+(m&67108863);m>>=26,m+=w/67108864|0,m+=g>>>26,this.words[y]=g&67108863}return m!==0&&(this.words[y]=m,this.length++),this.length=u===0?1:this.length,this},i.prototype.muln=function(u){return this.clone().imuln(u)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.imul(this.clone())},i.prototype.pow=function(u){var m=h(u);if(m.length===0)return new i(1);for(var y=this,w=0;w<m.length&&m[w]===0;w++,y=y.sqr());if(++w<m.length)for(var g=y.sqr();w<m.length;w++,g=g.sqr())m[w]!==0&&(y=y.mul(g));return y},i.prototype.iushln=function(u){t(typeof u=="number"&&u>=0);var m=u%26,y=(u-m)/26,w=67108863>>>26-m<<26-m,g;if(m!==0){var _=0;for(g=0;g<this.length;g++){var C=this.words[g]&w,b=(this.words[g]|0)-C<<m;this.words[g]=b|_,_=C>>>26-m}_&&(this.words[g]=_,this.length++)}if(y!==0){for(g=this.length-1;g>=0;g--)this.words[g+y]=this.words[g];for(g=0;g<y;g++)this.words[g]=0;this.length+=y}return this.strip()},i.prototype.ishln=function(u){return t(this.negative===0),this.iushln(u)},i.prototype.iushrn=function(u,m,y){t(typeof u=="number"&&u>=0);var w;m?w=(m-m%26)/26:w=0;var g=u%26,_=Math.min((u-g)/26,this.length),C=67108863^67108863>>>g<<g,b=y;if(w-=_,w=Math.max(0,w),b){for(var d=0;d<_;d++)b.words[d]=this.words[d];b.length=_}if(_!==0)if(this.length>_)for(this.length-=_,d=0;d<this.length;d++)this.words[d]=this.words[d+_];else this.words[0]=0,this.length=1;var E=0;for(d=this.length-1;d>=0&&(E!==0||d>=w);d--){var q=this.words[d]|0;this.words[d]=E<<26-g|q>>>g,E=q&C}return b&&E!==0&&(b.words[b.length++]=E),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.ishrn=function(u,m,y){return t(this.negative===0),this.iushrn(u,m,y)},i.prototype.shln=function(u){return this.clone().ishln(u)},i.prototype.ushln=function(u){return this.clone().iushln(u)},i.prototype.shrn=function(u){return this.clone().ishrn(u)},i.prototype.ushrn=function(u){return this.clone().iushrn(u)},i.prototype.testn=function(u){t(typeof u=="number"&&u>=0);var m=u%26,y=(u-m)/26,w=1<<m;if(this.length<=y)return!1;var g=this.words[y];return!!(g&w)},i.prototype.imaskn=function(u){t(typeof u=="number"&&u>=0);var m=u%26,y=(u-m)/26;if(t(this.negative===0,"imaskn works only with positive numbers"),this.length<=y)return this;if(m!==0&&y++,this.length=Math.min(y,this.length),m!==0){var w=67108863^67108863>>>m<<m;this.words[this.length-1]&=w}return this.length===0&&(this.words[0]=0,this.length=1),this.strip()},i.prototype.maskn=function(u){return this.clone().imaskn(u)},i.prototype.iaddn=function(u){return t(typeof u=="number"),t(u<67108864),u<0?this.isubn(-u):this.negative!==0?this.length===1&&(this.words[0]|0)<u?(this.words[0]=u-(this.words[0]|0),this.negative=0,this):(this.negative=0,this.isubn(u),this.negative=1,this):this._iaddn(u)},i.prototype._iaddn=function(u){this.words[0]+=u;for(var m=0;m<this.length&&this.words[m]>=67108864;m++)this.words[m]-=67108864,m===this.length-1?this.words[m+1]=1:this.words[m+1]++;return this.length=Math.max(this.length,m+1),this},i.prototype.isubn=function(u){if(t(typeof u=="number"),t(u<67108864),u<0)return this.iaddn(-u);if(this.negative!==0)return this.negative=0,this.iaddn(u),this.negative=1,this;if(this.words[0]-=u,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var m=0;m<this.length&&this.words[m]<0;m++)this.words[m]+=67108864,this.words[m+1]-=1;return this.strip()},i.prototype.addn=function(u){return this.clone().iaddn(u)},i.prototype.subn=function(u){return this.clone().isubn(u)},i.prototype.iabs=function(){return this.negative=0,this},i.prototype.abs=function(){return this.clone().iabs()},i.prototype._ishlnsubmul=function(u,m,y){var w=u.length+y,g;this._expand(w);var _,C=0;for(g=0;g<u.length;g++){_=(this.words[g+y]|0)+C;var b=(u.words[g]|0)*m;_-=b&67108863,C=(_>>26)-(b/67108864|0),this.words[g+y]=_&67108863}for(;g<this.length-y;g++)_=(this.words[g+y]|0)+C,C=_>>26,this.words[g+y]=_&67108863;if(C===0)return this.strip();for(t(C===-1),C=0,g=0;g<this.length;g++)_=-(this.words[g]|0)+C,C=_>>26,this.words[g]=_&67108863;return this.negative=1,this.strip()},i.prototype._wordDiv=function(u,m){var y=this.length-u.length,w=this.clone(),g=u,_=g.words[g.length-1]|0,C=this._countBits(_);y=26-C,y!==0&&(g=g.ushln(y),w.iushln(y),_=g.words[g.length-1]|0);var b=w.length-g.length,d;if(m!=="mod"){d=new i(null),d.length=b+1,d.words=new Array(d.length);for(var E=0;E<d.length;E++)d.words[E]=0}var q=w.clone()._ishlnsubmul(g,1,b);q.negative===0&&(w=q,d&&(d.words[b]=1));for(var O=b-1;O>=0;O--){var M=(w.words[g.length+O]|0)*67108864+(w.words[g.length+O-1]|0);for(M=Math.min(M/_|0,67108863),w._ishlnsubmul(g,M,O);w.negative!==0;)M--,w.negative=0,w._ishlnsubmul(g,1,O),w.isZero()||(w.negative^=1);d&&(d.words[O]=M)}return d&&d.strip(),w.strip(),m!=="div"&&y!==0&&w.iushrn(y),{div:d||null,mod:w}},i.prototype.divmod=function(u,m,y){if(t(!u.isZero()),this.isZero())return{div:new i(0),mod:new i(0)};var w,g,_;return this.negative!==0&&u.negative===0?(_=this.neg().divmod(u,m),m!=="mod"&&(w=_.div.neg()),m!=="div"&&(g=_.mod.neg(),y&&g.negative!==0&&g.iadd(u)),{div:w,mod:g}):this.negative===0&&u.negative!==0?(_=this.divmod(u.neg(),m),m!=="mod"&&(w=_.div.neg()),{div:w,mod:_.mod}):(this.negative&u.negative)!==0?(_=this.neg().divmod(u.neg(),m),m!=="div"&&(g=_.mod.neg(),y&&g.negative!==0&&g.isub(u)),{div:_.div,mod:g}):u.length>this.length||this.cmp(u)<0?{div:new i(0),mod:this}:u.length===1?m==="div"?{div:this.divn(u.words[0]),mod:null}:m==="mod"?{div:null,mod:new i(this.modn(u.words[0]))}:{div:this.divn(u.words[0]),mod:new i(this.modn(u.words[0]))}:this._wordDiv(u,m)},i.prototype.div=function(u){return this.divmod(u,"div",!1).div},i.prototype.mod=function(u){return this.divmod(u,"mod",!1).mod},i.prototype.umod=function(u){return this.divmod(u,"mod",!0).mod},i.prototype.divRound=function(u){var m=this.divmod(u);if(m.mod.isZero())return m.div;var y=m.div.negative!==0?m.mod.isub(u):m.mod,w=u.ushrn(1),g=u.andln(1),_=y.cmp(w);return _<0||g===1&&_===0?m.div:m.div.negative!==0?m.div.isubn(1):m.div.iaddn(1)},i.prototype.modn=function(u){t(u<=67108863);for(var m=(1<<26)%u,y=0,w=this.length-1;w>=0;w--)y=(m*y+(this.words[w]|0))%u;return y},i.prototype.idivn=function(u){t(u<=67108863);for(var m=0,y=this.length-1;y>=0;y--){var w=(this.words[y]|0)+m*67108864;this.words[y]=w/u|0,m=w%u}return this.strip()},i.prototype.divn=function(u){return this.clone().idivn(u)},i.prototype.egcd=function(u){t(u.negative===0),t(!u.isZero());var m=this,y=u.clone();m.negative!==0?m=m.umod(u):m=m.clone();for(var w=new i(1),g=new i(0),_=new i(0),C=new i(1),b=0;m.isEven()&&y.isEven();)m.iushrn(1),y.iushrn(1),++b;for(var d=y.clone(),E=m.clone();!m.isZero();){for(var q=0,O=1;(m.words[0]&O)===0&&q<26;++q,O<<=1);if(q>0)for(m.iushrn(q);q-- >0;)(w.isOdd()||g.isOdd())&&(w.iadd(d),g.isub(E)),w.iushrn(1),g.iushrn(1);for(var M=0,j=1;(y.words[0]&j)===0&&M<26;++M,j<<=1);if(M>0)for(y.iushrn(M);M-- >0;)(_.isOdd()||C.isOdd())&&(_.iadd(d),C.isub(E)),_.iushrn(1),C.iushrn(1);m.cmp(y)>=0?(m.isub(y),w.isub(_),g.isub(C)):(y.isub(m),_.isub(w),C.isub(g))}return{a:_,b:C,gcd:y.iushln(b)}},i.prototype._invmp=function(u){t(u.negative===0),t(!u.isZero());var m=this,y=u.clone();m.negative!==0?m=m.umod(u):m=m.clone();for(var w=new i(1),g=new i(0),_=y.clone();m.cmpn(1)>0&&y.cmpn(1)>0;){for(var C=0,b=1;(m.words[0]&b)===0&&C<26;++C,b<<=1);if(C>0)for(m.iushrn(C);C-- >0;)w.isOdd()&&w.iadd(_),w.iushrn(1);for(var d=0,E=1;(y.words[0]&E)===0&&d<26;++d,E<<=1);if(d>0)for(y.iushrn(d);d-- >0;)g.isOdd()&&g.iadd(_),g.iushrn(1);m.cmp(y)>=0?(m.isub(y),w.isub(g)):(y.isub(m),g.isub(w))}var q;return m.cmpn(1)===0?q=w:q=g,q.cmpn(0)<0&&q.iadd(u),q},i.prototype.gcd=function(u){if(this.isZero())return u.abs();if(u.isZero())return this.abs();var m=this.clone(),y=u.clone();m.negative=0,y.negative=0;for(var w=0;m.isEven()&&y.isEven();w++)m.iushrn(1),y.iushrn(1);do{for(;m.isEven();)m.iushrn(1);for(;y.isEven();)y.iushrn(1);var g=m.cmp(y);if(g<0){var _=m;m=y,y=_}else if(g===0||y.cmpn(1)===0)break;m.isub(y)}while(!0);return y.iushln(w)},i.prototype.invm=function(u){return this.egcd(u).a.umod(u)},i.prototype.isEven=function(){return(this.words[0]&1)===0},i.prototype.isOdd=function(){return(this.words[0]&1)===1},i.prototype.andln=function(u){return this.words[0]&u},i.prototype.bincn=function(u){t(typeof u=="number");var m=u%26,y=(u-m)/26,w=1<<m;if(this.length<=y)return this._expand(y+1),this.words[y]|=w,this;for(var g=w,_=y;g!==0&&_<this.length;_++){var C=this.words[_]|0;C+=g,g=C>>>26,C&=67108863,this.words[_]=C}return g!==0&&(this.words[_]=g,this.length++),this},i.prototype.isZero=function(){return this.length===1&&this.words[0]===0},i.prototype.cmpn=function(u){var m=u<0;if(this.negative!==0&&!m)return-1;if(this.negative===0&&m)return 1;this.strip();var y;if(this.length>1)y=1;else{m&&(u=-u),t(u<=67108863,"Number is too big");var w=this.words[0]|0;y=w===u?0:w<u?-1:1}return this.negative!==0?-y|0:y},i.prototype.cmp=function(u){if(this.negative!==0&&u.negative===0)return-1;if(this.negative===0&&u.negative!==0)return 1;var m=this.ucmp(u);return this.negative!==0?-m|0:m},i.prototype.ucmp=function(u){if(this.length>u.length)return 1;if(this.length<u.length)return-1;for(var m=0,y=this.length-1;y>=0;y--){var w=this.words[y]|0,g=u.words[y]|0;if(w!==g){w<g?m=-1:w>g&&(m=1);break}}return m},i.prototype.gtn=function(u){return this.cmpn(u)===1},i.prototype.gt=function(u){return this.cmp(u)===1},i.prototype.gten=function(u){return this.cmpn(u)>=0},i.prototype.gte=function(u){return this.cmp(u)>=0},i.prototype.ltn=function(u){return this.cmpn(u)===-1},i.prototype.lt=function(u){return this.cmp(u)===-1},i.prototype.lten=function(u){return this.cmpn(u)<=0},i.prototype.lte=function(u){return this.cmp(u)<=0},i.prototype.eqn=function(u){return this.cmpn(u)===0},i.prototype.eq=function(u){return this.cmp(u)===0},i.red=function(u){return new L(u)},i.prototype.toRed=function(u){return t(!this.red,"Already a number in reduction context"),t(this.negative===0,"red works only with positives"),u.convertTo(this)._forceRed(u)},i.prototype.fromRed=function(){return t(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(u){return this.red=u,this},i.prototype.forceRed=function(u){return t(!this.red,"Already a number in reduction context"),this._forceRed(u)},i.prototype.redAdd=function(u){return t(this.red,"redAdd works only with red numbers"),this.red.add(this,u)},i.prototype.redIAdd=function(u){return t(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,u)},i.prototype.redSub=function(u){return t(this.red,"redSub works only with red numbers"),this.red.sub(this,u)},i.prototype.redISub=function(u){return t(this.red,"redISub works only with red numbers"),this.red.isub(this,u)},i.prototype.redShl=function(u){return t(this.red,"redShl works only with red numbers"),this.red.shl(this,u)},i.prototype.redMul=function(u){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,u),this.red.mul(this,u)},i.prototype.redIMul=function(u){return t(this.red,"redMul works only with red numbers"),this.red._verify2(this,u),this.red.imul(this,u)},i.prototype.redSqr=function(){return t(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return t(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return t(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return t(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return t(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(u){return t(this.red&&!u.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,u)};var P={k256:null,p224:null,p192:null,p25519:null};function I(T,u){this.name=T,this.p=new i(u,16),this.n=this.p.bitLength(),this.k=new i(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}I.prototype._tmp=function(){var u=new i(null);return u.words=new Array(Math.ceil(this.n/13)),u},I.prototype.ireduce=function(u){var m=u,y;do this.split(m,this.tmp),m=this.imulK(m),m=m.iadd(this.tmp),y=m.bitLength();while(y>this.n);var w=y<this.n?-1:m.ucmp(this.p);return w===0?(m.words[0]=0,m.length=1):w>0?m.isub(this.p):m.strip!==void 0?m.strip():m._strip(),m},I.prototype.split=function(u,m){u.iushrn(this.n,0,m)},I.prototype.imulK=function(u){return u.imul(this.k)};function B(){I.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}n(B,I),B.prototype.split=function(u,m){for(var y=4194303,w=Math.min(u.length,9),g=0;g<w;g++)m.words[g]=u.words[g];if(m.length=w,u.length<=9){u.words[0]=0,u.length=1;return}var _=u.words[9];for(m.words[m.length++]=_&y,g=10;g<u.length;g++){var C=u.words[g]|0;u.words[g-10]=(C&y)<<4|_>>>22,_=C}_>>>=22,u.words[g-10]=_,_===0&&u.length>10?u.length-=10:u.length-=9},B.prototype.imulK=function(u){u.words[u.length]=0,u.words[u.length+1]=0,u.length+=2;for(var m=0,y=0;y<u.length;y++){var w=u.words[y]|0;m+=w*977,u.words[y]=m&67108863,m=w*64+(m/67108864|0)}return u.words[u.length-1]===0&&(u.length--,u.words[u.length-1]===0&&u.length--),u};function V(){I.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}n(V,I);function F(){I.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}n(F,I);function G(){I.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}n(G,I),G.prototype.imulK=function(u){for(var m=0,y=0;y<u.length;y++){var w=(u.words[y]|0)*19+m,g=w&67108863;w>>>=26,u.words[y]=g,m=w}return m!==0&&(u.words[u.length++]=m),u},i._prime=function(u){if(P[u])return P[u];var m;if(u==="k256")m=new B;else if(u==="p224")m=new V;else if(u==="p192")m=new F;else if(u==="p25519")m=new G;else throw new Error("Unknown prime "+u);return P[u]=m,m};function L(T){if(typeof T=="string"){var u=i._prime(T);this.m=u.p,this.prime=u}else t(T.gtn(1),"modulus must be greater than 1"),this.m=T,this.prime=null}L.prototype._verify1=function(u){t(u.negative===0,"red works only with positives"),t(u.red,"red works only with red numbers")},L.prototype._verify2=function(u,m){t((u.negative|m.negative)===0,"red works only with positives"),t(u.red&&u.red===m.red,"red works only with red numbers")},L.prototype.imod=function(u){return this.prime?this.prime.ireduce(u)._forceRed(this):u.umod(this.m)._forceRed(this)},L.prototype.neg=function(u){return u.isZero()?u.clone():this.m.sub(u)._forceRed(this)},L.prototype.add=function(u,m){this._verify2(u,m);var y=u.add(m);return y.cmp(this.m)>=0&&y.isub(this.m),y._forceRed(this)},L.prototype.iadd=function(u,m){this._verify2(u,m);var y=u.iadd(m);return y.cmp(this.m)>=0&&y.isub(this.m),y},L.prototype.sub=function(u,m){this._verify2(u,m);var y=u.sub(m);return y.cmpn(0)<0&&y.iadd(this.m),y._forceRed(this)},L.prototype.isub=function(u,m){this._verify2(u,m);var y=u.isub(m);return y.cmpn(0)<0&&y.iadd(this.m),y},L.prototype.shl=function(u,m){return this._verify1(u),this.imod(u.ushln(m))},L.prototype.imul=function(u,m){return this._verify2(u,m),this.imod(u.imul(m))},L.prototype.mul=function(u,m){return this._verify2(u,m),this.imod(u.mul(m))},L.prototype.isqr=function(u){return this.imul(u,u.clone())},L.prototype.sqr=function(u){return this.mul(u,u)},L.prototype.sqrt=function(u){if(u.isZero())return u.clone();var m=this.m.andln(3);if(t(m%2===1),m===3){var y=this.m.add(new i(1)).iushrn(2);return this.pow(u,y)}for(var w=this.m.subn(1),g=0;!w.isZero()&&w.andln(1)===0;)g++,w.iushrn(1);t(!w.isZero());var _=new i(1).toRed(this),C=_.redNeg(),b=this.m.subn(1).iushrn(1),d=this.m.bitLength();for(d=new i(2*d*d).toRed(this);this.pow(d,b).cmp(C)!==0;)d.redIAdd(C);for(var E=this.pow(d,w),q=this.pow(u,w.addn(1).iushrn(1)),O=this.pow(u,w),M=g;O.cmp(_)!==0;){for(var j=O,z=0;j.cmp(_)!==0;z++)j=j.redSqr();t(z<M);var U=this.pow(E,new i(1).iushln(M-z-1));q=q.redMul(U),E=U.redSqr(),O=O.redMul(E),M=z}return q},L.prototype.invm=function(u){var m=u._invmp(this.m);return m.negative!==0?(m.negative=0,this.imod(m).redNeg()):this.imod(m)},L.prototype.pow=function(u,m){if(m.isZero())return new i(1).toRed(this);if(m.cmpn(1)===0)return u.clone();var y=4,w=new Array(1<<y);w[0]=new i(1).toRed(this),w[1]=u;for(var g=2;g<w.length;g++)w[g]=this.mul(w[g-1],u);var _=w[0],C=0,b=0,d=m.bitLength()%26;for(d===0&&(d=26),g=m.length-1;g>=0;g--){for(var E=m.words[g],q=d-1;q>=0;q--){var O=E>>q&1;if(_!==w[0]&&(_=this.sqr(_)),O===0&&C===0){b=0;continue}C<<=1,C|=O,b++,!(b!==y&&(g!==0||q!==0))&&(_=this.mul(_,w[C]),b=0,C=0)}d=26}return _},L.prototype.convertTo=function(u){var m=u.umod(this.m);return m===u?m.clone():m},L.prototype.convertFrom=function(u){var m=u.clone();return m.red=null,m},i.mont=function(u){return new H(u)};function H(T){L.call(this,T),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new i(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}n(H,L),H.prototype.convertTo=function(u){return this.imod(u.ushln(this.shift))},H.prototype.convertFrom=function(u){var m=this.imod(u.mul(this.rinv));return m.red=null,m},H.prototype.imul=function(u,m){if(u.isZero()||m.isZero())return u.words[0]=0,u.length=1,u;var y=u.imul(m),w=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),g=y.isub(w).iushrn(this.shift),_=g;return g.cmp(this.m)>=0?_=g.isub(this.m):g.cmpn(0)<0&&(_=g.iadd(this.m)),_._forceRed(this)},H.prototype.mul=function(u,m){if(u.isZero()||m.isZero())return new i(0)._forceRed(this);var y=u.mul(m),w=y.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),g=y.isub(w).iushrn(this.shift),_=g;return g.cmp(this.m)>=0?_=g.isub(this.m):g.cmpn(0)<0&&(_=g.iadd(this.m)),_._forceRed(this)},H.prototype.invm=function(u){var m=this.imod(u._invmp(this.m).mul(this.r2));return m._forceRed(this)}})(typeof Oh>"u"||Oh,WS)});var GS=R((nW,Ph)=>{typeof Object.create=="function"?Ph.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Ph.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}});var qn=R((iW,Nh)=>{try{if(Ih=require("util"),typeof Ih.inherits!="function")throw"";Nh.exports=Ih.inherits}catch{Nh.exports=GS()}var Ih});var ql=R((sW,zS)=>{"use strict";var Ul=require("buffer"),Cs=Ul.Buffer,cr={},lr;for(lr in Ul)Ul.hasOwnProperty(lr)&&(lr==="SlowBuffer"||lr==="Buffer"||(cr[lr]=Ul[lr]));var As=cr.Buffer={};for(lr in Cs)Cs.hasOwnProperty(lr)&&(lr==="allocUnsafe"||lr==="allocUnsafeSlow"||(As[lr]=Cs[lr]));cr.Buffer.prototype=Cs.prototype;(!As.from||As.from===Uint8Array.from)&&(As.from=function(r,e,t){if(typeof r=="number")throw new TypeError('The "value" argument must not be of type number. Received type '+typeof r);if(r&&typeof r.length>"u")throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof r);return Cs(r,e,t)});As.alloc||(As.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError('The "size" argument must be of type number. Received type '+typeof r);if(r<0||r>=2*(1<<30))throw new RangeError('The value "'+r+'" is invalid for option "size"');var n=Cs(r);return!e||e.length===0?n.fill(0):typeof t=="string"?n.fill(e,t):n.fill(e),n});if(!cr.kStringMaxLength)try{cr.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch{}cr.constants||(cr.constants={MAX_LENGTH:cr.kMaxLength},cr.kStringMaxLength&&(cr.constants.MAX_STRING_LENGTH=cr.kStringMaxLength));zS.exports=cr});var Hl=R(VS=>{"use strict";var _B=qn();function ur(r){this._reporterState={obj:null,path:[],options:r||{},errors:[]}}VS.Reporter=ur;ur.prototype.isError=function(e){return e instanceof Rs};ur.prototype.save=function(){let e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}};ur.prototype.restore=function(e){let t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)};ur.prototype.enterKey=function(e){return this._reporterState.path.push(e)};ur.prototype.exitKey=function(e){let t=this._reporterState;t.path=t.path.slice(0,e-1)};ur.prototype.leaveKey=function(e,t,n){let i=this._reporterState;this.exitKey(e),i.obj!==null&&(i.obj[t]=n)};ur.prototype.path=function(){return this._reporterState.path.join("/")};ur.prototype.enterObject=function(){let e=this._reporterState,t=e.obj;return e.obj={},t};ur.prototype.leaveObject=function(e){let t=this._reporterState,n=t.obj;return t.obj=e,n};ur.prototype.error=function(e){let t,n=this._reporterState,i=e instanceof Rs;if(i?t=e:t=new Rs(n.path.map(function(s){return"["+JSON.stringify(s)+"]"}).join(""),e.message||e,e.stack),!n.options.partial)throw t;return i||n.errors.push(t),t};ur.prototype.wrapResult=function(e){let t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e};function Rs(r,e){this.path=r,this.rethrow(e)}_B(Rs,Error);Rs.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,Rs),!this.stack)try{throw new Error(this.message)}catch(t){this.stack=t.stack}return this}});var Ms=R(Lh=>{"use strict";var bB=qn(),$l=Hl().Reporter,ks=ql().Buffer;function pr(r,e){if($l.call(this,e),!ks.isBuffer(r)){this.error("Input not Buffer");return}this.base=r,this.offset=0,this.length=r.length}bB(pr,$l);Lh.DecoderBuffer=pr;pr.isDecoderBuffer=function(e){return e instanceof pr?!0:typeof e=="object"&&ks.isBuffer(e.base)&&e.constructor.name==="DecoderBuffer"&&typeof e.offset=="number"&&typeof e.length=="number"&&typeof e.save=="function"&&typeof e.restore=="function"&&typeof e.isEmpty=="function"&&typeof e.readUInt8=="function"&&typeof e.skip=="function"&&typeof e.raw=="function"};pr.prototype.save=function(){return{offset:this.offset,reporter:$l.prototype.save.call(this)}};pr.prototype.restore=function(e){let t=new pr(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,$l.prototype.restore.call(this,e.reporter),t};pr.prototype.isEmpty=function(){return this.offset===this.length};pr.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")};pr.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");let n=new pr(this.base);return n._reporterState=this._reporterState,n.offset=this.offset,n.length=this.offset+e,this.offset+=e,n};pr.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)};function Os(r,e){if(Array.isArray(r))this.length=0,this.value=r.map(function(t){return Os.isEncoderBuffer(t)||(t=new Os(t,e)),this.length+=t.length,t},this);else if(typeof r=="number"){if(!(0<=r&&r<=255))return e.error("non-byte EncoderBuffer value");this.value=r,this.length=1}else if(typeof r=="string")this.value=r,this.length=ks.byteLength(r);else if(ks.isBuffer(r))this.value=r,this.length=r.length;else return e.error("Unsupported type: "+typeof r)}Lh.EncoderBuffer=Os;Os.isEncoderBuffer=function(e){return e instanceof Os?!0:typeof e=="object"&&e.constructor.name==="EncoderBuffer"&&typeof e.length=="number"&&typeof e.join=="function"};Os.prototype.join=function(e,t){return e||(e=ks.alloc(this.length)),t||(t=0),this.length===0||(Array.isArray(this.value)?this.value.forEach(function(n){n.join(e,t),t+=n.length}):(typeof this.value=="number"?e[t]=this.value:typeof this.value=="string"?e.write(this.value,t):ks.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length)),e}});var JS=R((cW,YS)=>{YS.exports=KS;function KS(r,e){if(!r)throw new Error(e||"Assertion failed")}KS.equal=function(e,t,n){if(e!=t)throw new Error(n||"Assertion failed: "+e+" != "+t)}});var Wl=R((lW,ZS)=>{"use strict";var wB=Hl().Reporter,SB=Ms().EncoderBuffer,EB=Ms().DecoderBuffer,kt=JS(),XS=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],TB=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(XS),CB=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];function de(r,e,t){let n={};this._baseState=n,n.name=t,n.enc=r,n.parent=e||null,n.children=null,n.tag=null,n.args=null,n.reverseArgs=null,n.choice=null,n.optional=!1,n.any=!1,n.obj=!1,n.use=null,n.useDecoder=null,n.key=null,n.default=null,n.explicit=null,n.implicit=null,n.contains=null,n.parent||(n.children=[],this._wrap())}ZS.exports=de;var AB=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];de.prototype.clone=function(){let e=this._baseState,t={};AB.forEach(function(i){t[i]=e[i]});let n=new this.constructor(t.parent);return n._baseState=t,n};de.prototype._wrap=function(){let e=this._baseState;TB.forEach(function(t){this[t]=function(){let i=new this.constructor(this);return e.children.push(i),i[t].apply(i,arguments)}},this)};de.prototype._init=function(e){let t=this._baseState;kt(t.parent===null),e.call(this),t.children=t.children.filter(function(n){return n._baseState.parent===this},this),kt.equal(t.children.length,1,"Root node can have only one child")};de.prototype._useArgs=function(e){let t=this._baseState,n=e.filter(function(i){return i instanceof this.constructor},this);e=e.filter(function(i){return!(i instanceof this.constructor)},this),n.length!==0&&(kt(t.children===null),t.children=n,n.forEach(function(i){i._baseState.parent=this},this)),e.length!==0&&(kt(t.args===null),t.args=e,t.reverseArgs=e.map(function(i){if(typeof i!="object"||i.constructor!==Object)return i;let s={};return Object.keys(i).forEach(function(o){o==(o|0)&&(o|=0);let a=i[o];s[a]=o}),s}))};CB.forEach(function(r){de.prototype[r]=function(){let t=this._baseState;throw new Error(r+" not implemented for encoding: "+t.enc)}});XS.forEach(function(r){de.prototype[r]=function(){let t=this._baseState,n=Array.prototype.slice.call(arguments);return kt(t.tag===null),t.tag=r,this._useArgs(n),this}});de.prototype.use=function(e){kt(e);let t=this._baseState;return kt(t.use===null),t.use=e,this};de.prototype.optional=function(){let e=this._baseState;return e.optional=!0,this};de.prototype.def=function(e){let t=this._baseState;return kt(t.default===null),t.default=e,t.optional=!0,this};de.prototype.explicit=function(e){let t=this._baseState;return kt(t.explicit===null&&t.implicit===null),t.explicit=e,this};de.prototype.implicit=function(e){let t=this._baseState;return kt(t.explicit===null&&t.implicit===null),t.implicit=e,this};de.prototype.obj=function(){let e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,t.length!==0&&this._useArgs(t),this};de.prototype.key=function(e){let t=this._baseState;return kt(t.key===null),t.key=e,this};de.prototype.any=function(){let e=this._baseState;return e.any=!0,this};de.prototype.choice=function(e){let t=this._baseState;return kt(t.choice===null),t.choice=e,this._useArgs(Object.keys(e).map(function(n){return e[n]})),this};de.prototype.contains=function(e){let t=this._baseState;return kt(t.use===null),t.contains=e,this};de.prototype._decode=function(e,t){let n=this._baseState;if(n.parent===null)return e.wrapResult(n.children[0]._decode(e,t));let i=n.default,s=!0,o=null;if(n.key!==null&&(o=e.enterKey(n.key)),n.optional){let c=null;if(n.explicit!==null?c=n.explicit:n.implicit!==null?c=n.implicit:n.tag!==null&&(c=n.tag),c===null&&!n.any){let l=e.save();try{n.choice===null?this._decodeGeneric(n.tag,e,t):this._decodeChoice(e,t),s=!0}catch{s=!1}e.restore(l)}else if(s=this._peekTag(e,c,n.any),e.isError(s))return s}let a;if(n.obj&&s&&(a=e.enterObject()),s){if(n.explicit!==null){let l=this._decodeTag(e,n.explicit);if(e.isError(l))return l;e=l}let c=e.offset;if(n.use===null&&n.choice===null){let l;n.any&&(l=e.save());let p=this._decodeTag(e,n.implicit!==null?n.implicit:n.tag,n.any);if(e.isError(p))return p;n.any?i=e.raw(l):e=p}if(t&&t.track&&n.tag!==null&&t.track(e.path(),c,e.length,"tagged"),t&&t.track&&n.tag!==null&&t.track(e.path(),e.offset,e.length,"content"),n.any||(n.choice===null?i=this._decodeGeneric(n.tag,e,t):i=this._decodeChoice(e,t)),e.isError(i))return i;if(!n.any&&n.choice===null&&n.children!==null&&n.children.forEach(function(p){p._decode(e,t)}),n.contains&&(n.tag==="octstr"||n.tag==="bitstr")){let l=new EB(i);i=this._getUse(n.contains,e._reporterState.obj)._decode(l,t)}}return n.obj&&s&&(i=e.leaveObject(a)),n.key!==null&&(i!==null||s===!0)?e.leaveKey(o,n.key,i):o!==null&&e.exitKey(o),i};de.prototype._decodeGeneric=function(e,t,n){let i=this._baseState;return e==="seq"||e==="set"?null:e==="seqof"||e==="setof"?this._decodeList(t,e,i.args[0],n):/str$/.test(e)?this._decodeStr(t,e,n):e==="objid"&&i.args?this._decodeObjid(t,i.args[0],i.args[1],n):e==="objid"?this._decodeObjid(t,null,null,n):e==="gentime"||e==="utctime"?this._decodeTime(t,e,n):e==="null_"?this._decodeNull(t,n):e==="bool"?this._decodeBool(t,n):e==="objDesc"?this._decodeStr(t,e,n):e==="int"||e==="enum"?this._decodeInt(t,i.args&&i.args[0],n):i.use!==null?this._getUse(i.use,t._reporterState.obj)._decode(t,n):t.error("unknown tag: "+e)};de.prototype._getUse=function(e,t){let n=this._baseState;return n.useDecoder=this._use(e,t),kt(n.useDecoder._baseState.parent===null),n.useDecoder=n.useDecoder._baseState.children[0],n.implicit!==n.useDecoder._baseState.implicit&&(n.useDecoder=n.useDecoder.clone(),n.useDecoder._baseState.implicit=n.implicit),n.useDecoder};de.prototype._decodeChoice=function(e,t){let n=this._baseState,i=null,s=!1;return Object.keys(n.choice).some(function(o){let a=e.save(),c=n.choice[o];try{let l=c._decode(e,t);if(e.isError(l))return!1;i={type:o,value:l},s=!0}catch{return e.restore(a),!1}return!0},this),s?i:e.error("Choice not matched")};de.prototype._createEncoderBuffer=function(e){return new SB(e,this.reporter)};de.prototype._encode=function(e,t,n){let i=this._baseState;if(i.default!==null&&i.default===e)return;let s=this._encodeValue(e,t,n);if(s!==void 0&&!this._skipDefault(s,t,n))return s};de.prototype._encodeValue=function(e,t,n){let i=this._baseState;if(i.parent===null)return i.children[0]._encode(e,t||new wB);let s=null;if(this.reporter=t,i.optional&&e===void 0)if(i.default!==null)e=i.default;else return;let o=null,a=!1;if(i.any)s=this._createEncoderBuffer(e);else if(i.choice)s=this._encodeChoice(e,t);else if(i.contains)o=this._getUse(i.contains,n)._encode(e,t),a=!0;else if(i.children)o=i.children.map(function(c){if(c._baseState.tag==="null_")return c._encode(null,t,e);if(c._baseState.key===null)return t.error("Child should have a key");let l=t.enterKey(c._baseState.key);if(typeof e!="object")return t.error("Child expected, but input is not object");let p=c._encode(e[c._baseState.key],t,e);return t.leaveKey(l),p},this).filter(function(c){return c}),o=this._createEncoderBuffer(o);else if(i.tag==="seqof"||i.tag==="setof"){if(!(i.args&&i.args.length===1))return t.error("Too many args for : "+i.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");let c=this.clone();c._baseState.implicit=null,o=this._createEncoderBuffer(e.map(function(l){let p=this._baseState;return this._getUse(p.args[0],e)._encode(l,t)},c))}else i.use!==null?s=this._getUse(i.use,n)._encode(e,t):(o=this._encodePrimitive(i.tag,e),a=!0);if(!i.any&&i.choice===null){let c=i.implicit!==null?i.implicit:i.tag,l=i.implicit===null?"universal":"context";c===null?i.use===null&&t.error("Tag could be omitted only for .use()"):i.use===null&&(s=this._encodeComposite(c,a,l,o))}return i.explicit!==null&&(s=this._encodeComposite(i.explicit,!1,"context",s)),s};de.prototype._encodeChoice=function(e,t){let n=this._baseState,i=n.choice[e.type];return i||kt(!1,e.type+" not found in "+JSON.stringify(Object.keys(n.choice))),i._encode(e.value,t)};de.prototype._encodePrimitive=function(e,t){let n=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if(e==="objid"&&n.args)return this._encodeObjid(t,n.reverseArgs[0],n.args[1]);if(e==="objid")return this._encodeObjid(t,null,null);if(e==="gentime"||e==="utctime")return this._encodeTime(t,e);if(e==="null_")return this._encodeNull();if(e==="int"||e==="enum")return this._encodeInt(t,n.args&&n.reverseArgs[0]);if(e==="bool")return this._encodeBool(t);if(e==="objDesc")return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)};de.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)};de.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(e)}});var Gl=R(mi=>{"use strict";function QS(r){let e={};return Object.keys(r).forEach(function(t){(t|0)==t&&(t=t|0);let n=r[t];e[n]=t}),e}mi.tagClass={0:"universal",1:"application",2:"context",3:"private"};mi.tagClassByName=QS(mi.tagClass);mi.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"};mi.tagByName=QS(mi.tag)});var Bh=R((pW,rE)=>{"use strict";var RB=qn(),gn=ql().Buffer,eE=Wl(),Dh=Gl();function tE(r){this.enc="der",this.name=r.name,this.entity=r,this.tree=new Cr,this.tree._init(r.body)}rE.exports=tE;tE.prototype.encode=function(e,t){return this.tree._encode(e,t).join()};function Cr(r){eE.call(this,"der",r)}RB(Cr,eE);Cr.prototype._encodeComposite=function(e,t,n,i){let s=kB(e,t,n,this.reporter);if(i.length<128){let c=gn.alloc(2);return c[0]=s,c[1]=i.length,this._createEncoderBuffer([c,i])}let o=1;for(let c=i.length;c>=256;c>>=8)o++;let a=gn.alloc(2+o);a[0]=s,a[1]=128|o;for(let c=1+o,l=i.length;l>0;c--,l>>=8)a[c]=l&255;return this._createEncoderBuffer([a,i])};Cr.prototype._encodeStr=function(e,t){if(t==="bitstr")return this._createEncoderBuffer([e.unused|0,e.data]);if(t==="bmpstr"){let n=gn.alloc(e.length*2);for(let i=0;i<e.length;i++)n.writeUInt16BE(e.charCodeAt(i),i*2);return this._createEncoderBuffer(n)}else return t==="numstr"?this._isNumstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: numstr supports only digits and space"):t==="printstr"?this._isPrintstr(e)?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark"):/str$/.test(t)?this._createEncoderBuffer(e):t==="objDesc"?this._createEncoderBuffer(e):this.reporter.error("Encoding of string type: "+t+" unsupported")};Cr.prototype._encodeObjid=function(e,t,n){if(typeof e=="string"){if(!t)return this.reporter.error("string objid given, but no values map found");if(!t.hasOwnProperty(e))return this.reporter.error("objid not found in values map");e=t[e].split(/[\s.]+/g);for(let a=0;a<e.length;a++)e[a]|=0}else if(Array.isArray(e)){e=e.slice();for(let a=0;a<e.length;a++)e[a]|=0}if(!Array.isArray(e))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(e));if(!n){if(e[1]>=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,e[0]*40+e[1])}let i=0;for(let a=0;a<e.length;a++){let c=e[a];for(i++;c>=128;c>>=7)i++}let s=gn.alloc(i),o=s.length-1;for(let a=e.length-1;a>=0;a--){let c=e[a];for(s[o--]=c&127;(c>>=7)>0;)s[o--]=128|c&127}return this._createEncoderBuffer(s)};function fr(r){return r<10?"0"+r:r}Cr.prototype._encodeTime=function(e,t){let n,i=new Date(e);return t==="gentime"?n=[fr(i.getUTCFullYear()),fr(i.getUTCMonth()+1),fr(i.getUTCDate()),fr(i.getUTCHours()),fr(i.getUTCMinutes()),fr(i.getUTCSeconds()),"Z"].join(""):t==="utctime"?n=[fr(i.getUTCFullYear()%100),fr(i.getUTCMonth()+1),fr(i.getUTCDate()),fr(i.getUTCHours()),fr(i.getUTCMinutes()),fr(i.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(n,"octstr")};Cr.prototype._encodeNull=function(){return this._createEncoderBuffer("")};Cr.prototype._encodeInt=function(e,t){if(typeof e=="string"){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if(typeof e!="number"&&!gn.isBuffer(e)){let s=e.toArray();!e.sign&&s[0]&128&&s.unshift(0),e=gn.from(s)}if(gn.isBuffer(e)){let s=e.length;e.length===0&&s++;let o=gn.alloc(s);return e.copy(o),e.length===0&&(o[0]=0),this._createEncoderBuffer(o)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);let n=1;for(let s=e;s>=256;s>>=8)n++;let i=new Array(n);for(let s=i.length-1;s>=0;s--)i[s]=e&255,e>>=8;return i[0]&128&&i.unshift(0),this._createEncoderBuffer(gn.from(i))};Cr.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)};Cr.prototype._use=function(e,t){return typeof e=="function"&&(e=e(t)),e._getEncoder("der").tree};Cr.prototype._skipDefault=function(e,t,n){let i=this._baseState,s;if(i.default===null)return!1;let o=e.join();if(i.defaultBuffer===void 0&&(i.defaultBuffer=this._encodeValue(i.default,t,n).join()),o.length!==i.defaultBuffer.length)return!1;for(s=0;s<o.length;s++)if(o[s]!==i.defaultBuffer[s])return!1;return!0};function kB(r,e,t,n){let i;if(r==="seqof"?r="seq":r==="setof"&&(r="set"),Dh.tagByName.hasOwnProperty(r))i=Dh.tagByName[r];else if(typeof r=="number"&&(r|0)===r)i=r;else return n.error("Unknown tag: "+r);return i>=31?n.error("Multi-octet tag encoding unsupported"):(e||(i|=32),i|=Dh.tagClassByName[t||"universal"]<<6,i)}});var iE=R((fW,nE)=>{"use strict";var OB=qn(),jh=Bh();function Fh(r){jh.call(this,r),this.enc="pem"}OB(Fh,jh);nE.exports=Fh;Fh.prototype.encode=function(e,t){let i=jh.prototype.encode.call(this,e).toString("base64"),s=["-----BEGIN "+t.label+"-----"];for(let o=0;o<i.length;o+=64)s.push(i.slice(o,o+64));return s.push("-----END "+t.label+"-----"),s.join(`
92
+ `)}});var Uh=R(oE=>{"use strict";var sE=oE;sE.der=Bh();sE.pem=iE()});var Hh=R((hW,fE)=>{"use strict";var MB=qn(),PB=Mh(),aE=Ms().DecoderBuffer,lE=Wl(),cE=Gl();function uE(r){this.enc="der",this.name=r.name,this.entity=r,this.tree=new Kt,this.tree._init(r.body)}fE.exports=uE;uE.prototype.decode=function(e,t){return aE.isDecoderBuffer(e)||(e=new aE(e,t)),this.tree._decode(e,t)};function Kt(r){lE.call(this,"der",r)}MB(Kt,lE);Kt.prototype._peekTag=function(e,t,n){if(e.isEmpty())return!1;let i=e.save(),s=qh(e,'Failed to peek tag: "'+t+'"');return e.isError(s)?s:(e.restore(i),s.tag===t||s.tagStr===t||s.tagStr+"of"===t||n)};Kt.prototype._decodeTag=function(e,t,n){let i=qh(e,'Failed to decode tag of "'+t+'"');if(e.isError(i))return i;let s=pE(e,i.primitive,'Failed to get length of "'+t+'"');if(e.isError(s))return s;if(!n&&i.tag!==t&&i.tagStr!==t&&i.tagStr+"of"!==t)return e.error('Failed to match tag: "'+t+'"');if(i.primitive||s!==null)return e.skip(s,'Failed to match body of: "'+t+'"');let o=e.save(),a=this._skipUntilEnd(e,'Failed to skip indefinite length body: "'+this.tag+'"');return e.isError(a)?a:(s=e.offset-o.offset,e.restore(o),e.skip(s,'Failed to match body of: "'+t+'"'))};Kt.prototype._skipUntilEnd=function(e,t){for(;;){let n=qh(e,t);if(e.isError(n))return n;let i=pE(e,n.primitive,t);if(e.isError(i))return i;let s;if(n.primitive||i!==null?s=e.skip(i):s=this._skipUntilEnd(e,t),e.isError(s))return s;if(n.tagStr==="end")break}};Kt.prototype._decodeList=function(e,t,n,i){let s=[];for(;!e.isEmpty();){let o=this._peekTag(e,"end");if(e.isError(o))return o;let a=n.decode(e,"der",i);if(e.isError(a)&&o)break;s.push(a)}return s};Kt.prototype._decodeStr=function(e,t){if(t==="bitstr"){let n=e.readUInt8();return e.isError(n)?n:{unused:n,data:e.raw()}}else if(t==="bmpstr"){let n=e.raw();if(n.length%2===1)return e.error("Decoding of string type: bmpstr length mismatch");let i="";for(let s=0;s<n.length/2;s++)i+=String.fromCharCode(n.readUInt16BE(s*2));return i}else if(t==="numstr"){let n=e.raw().toString("ascii");return this._isNumstr(n)?n:e.error("Decoding of string type: numstr unsupported characters")}else{if(t==="octstr")return e.raw();if(t==="objDesc")return e.raw();if(t==="printstr"){let n=e.raw().toString("ascii");return this._isPrintstr(n)?n:e.error("Decoding of string type: printstr unsupported characters")}else return/str$/.test(t)?e.raw().toString():e.error("Decoding of string type: "+t+" unsupported")}};Kt.prototype._decodeObjid=function(e,t,n){let i,s=[],o=0,a=0;for(;!e.isEmpty();)a=e.readUInt8(),o<<=7,o|=a&127,(a&128)===0&&(s.push(o),o=0);a&128&&s.push(o);let c=s[0]/40|0,l=s[0]%40;if(n?i=s:i=[c,l].concat(s.slice(1)),t){let p=t[i.join(" ")];p===void 0&&(p=t[i.join(".")]),p!==void 0&&(i=p)}return i};Kt.prototype._decodeTime=function(e,t){let n=e.raw().toString(),i,s,o,a,c,l;if(t==="gentime")i=n.slice(0,4)|0,s=n.slice(4,6)|0,o=n.slice(6,8)|0,a=n.slice(8,10)|0,c=n.slice(10,12)|0,l=n.slice(12,14)|0;else if(t==="utctime")i=n.slice(0,2)|0,s=n.slice(2,4)|0,o=n.slice(4,6)|0,a=n.slice(6,8)|0,c=n.slice(8,10)|0,l=n.slice(10,12)|0,i<70?i=2e3+i:i=1900+i;else return e.error("Decoding "+t+" time is not supported yet");return Date.UTC(i,s-1,o,a,c,l,0)};Kt.prototype._decodeNull=function(){return null};Kt.prototype._decodeBool=function(e){let t=e.readUInt8();return e.isError(t)?t:t!==0};Kt.prototype._decodeInt=function(e,t){let n=e.raw(),i=new PB(n);return t&&(i=t[i.toString(10)]||i),i};Kt.prototype._use=function(e,t){return typeof e=="function"&&(e=e(t)),e._getDecoder("der").tree};function qh(r,e){let t=r.readUInt8(e);if(r.isError(t))return t;let n=cE.tagClass[t>>6],i=(t&32)===0;if((t&31)===31){let o=t;for(t=0;(o&128)===128;){if(o=r.readUInt8(e),r.isError(o))return o;t<<=7,t|=o&127}}else t&=31;let s=cE.tag[t];return{cls:n,primitive:i,tag:t,tagStr:s}}function pE(r,e,t){let n=r.readUInt8(t);if(r.isError(n))return n;if(!e&&n===128)return null;if((n&128)===0)return n;let i=n&127;if(i>4)return r.error("length octect is too long");n=0;for(let s=0;s<i;s++){n<<=8;let o=r.readUInt8(t);if(r.isError(o))return o;n|=o}return n}});var hE=R((mW,dE)=>{"use strict";var IB=qn(),NB=ql().Buffer,$h=Hh();function Wh(r){$h.call(this,r),this.enc="pem"}IB(Wh,$h);dE.exports=Wh;Wh.prototype.decode=function(e,t){let n=e.toString().split(/[\r\n]+/g),i=t.label.toUpperCase(),s=/^-----(BEGIN|END) ([^-]+)-----$/,o=-1,a=-1;for(let p=0;p<n.length;p++){let f=n[p].match(s);if(f!==null&&f[2]===i)if(o===-1){if(f[1]!=="BEGIN")break;o=p}else{if(f[1]!=="END")break;a=p;break}}if(o===-1||a===-1)throw new Error("PEM section not found for: "+i);let c=n.slice(o+1,a).join("");c.replace(/[^a-z0-9+/=]+/gi,"");let l=NB.from(c,"base64");return $h.prototype.decode.call(this,l,t)}});var Gh=R(gE=>{"use strict";var mE=gE;mE.der=Hh();mE.pem=hE()});var yE=R(vE=>{"use strict";var LB=Uh(),DB=Gh(),BB=qn(),jB=vE;jB.define=function(e,t){return new Ps(e,t)};function Ps(r,e){this.name=r,this.body=e,this.decoders={},this.encoders={}}Ps.prototype._createNamed=function(e){let t=this.name;function n(i){this._initNamed(i,t)}return BB(n,e),n.prototype._initNamed=function(s,o){e.call(this,s,o)},new n(this)};Ps.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(DB[e])),this.decoders[e]};Ps.prototype.decode=function(e,t,n){return this._getDecoder(t).decode(e,n)};Ps.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(LB[e])),this.encoders[e]};Ps.prototype.encode=function(e,t,n){return this._getEncoder(t).encode(e,n)}});var _E=R(xE=>{"use strict";var zl=xE;zl.Reporter=Hl().Reporter;zl.DecoderBuffer=Ms().DecoderBuffer;zl.EncoderBuffer=Ms().EncoderBuffer;zl.Node=Wl()});var SE=R(wE=>{"use strict";var bE=wE;bE._reverse=function(e){let t={};return Object.keys(e).forEach(function(n){(n|0)==n&&(n=n|0);let i=e[n];t[i]=n}),t};bE.der=Gl()});var TE=R(EE=>{"use strict";var Is=EE;Is.bignum=Mh();Is.define=yE().define;Is.base=_E();Is.constants=SE();Is.decoders=Gh();Is.encoders=Uh()});var Ns=R((zh,AE)=>{var Vl=require("buffer"),qr=Vl.Buffer;function CE(r,e){for(var t in r)e[t]=r[t]}qr.from&&qr.alloc&&qr.allocUnsafe&&qr.allocUnsafeSlow?AE.exports=Vl:(CE(Vl,zh),zh.Buffer=gi);function gi(r,e,t){return qr(r,e,t)}gi.prototype=Object.create(qr.prototype);CE(qr,gi);gi.from=function(r,e,t){if(typeof r=="number")throw new TypeError("Argument must not be a number");return qr(r,e,t)};gi.alloc=function(r,e,t){if(typeof r!="number")throw new TypeError("Argument must be a number");var n=qr(r);return e!==void 0?typeof t=="string"?n.fill(e,t):n.fill(e):n.fill(0),n};gi.allocUnsafe=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return qr(r)};gi.allocUnsafeSlow=function(r){if(typeof r!="number")throw new TypeError("Argument must be a number");return Vl.SlowBuffer(r)}});var Vh=R((bW,RE)=>{var Kl=Ns().Buffer,FB=require("stream"),UB=require("util");function Yl(r){if(this.buffer=null,this.writable=!0,this.readable=!0,!r)return this.buffer=Kl.alloc(0),this;if(typeof r.pipe=="function")return this.buffer=Kl.alloc(0),r.pipe(this),this;if(r.length||typeof r=="object")return this.buffer=r,this.writable=!1,process.nextTick(function(){this.emit("end",r),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof r+")")}UB.inherits(Yl,FB);Yl.prototype.write=function(e){this.buffer=Kl.concat([this.buffer,Kl.from(e)]),this.emit("data",e)};Yl.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};RE.exports=Yl});var OE=R((wW,kE)=>{"use strict";function Kh(r){var e=(r/8|0)+(r%8===0?0:1);return e}var qB={ES256:Kh(256),ES384:Kh(384),ES512:Kh(521)};function HB(r){var e=qB[r];if(e)return e;throw new Error('Unknown algorithm "'+r+'"')}kE.exports=HB});var BE=R((SW,DE)=>{"use strict";var Jl=Ns().Buffer,PE=OE(),Xl=128,IE=0,$B=32,WB=16,GB=2,NE=WB|$B|IE<<6,Zl=GB|IE<<6;function zB(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function LE(r){if(Jl.isBuffer(r))return r;if(typeof r=="string")return Jl.from(r,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function VB(r,e){r=LE(r);var t=PE(e),n=t+1,i=r.length,s=0;if(r[s++]!==NE)throw new Error('Could not find expected "seq"');var o=r[s++];if(o===(Xl|1)&&(o=r[s++]),i-s<o)throw new Error('"seq" specified length of "'+o+'", only "'+(i-s)+'" remaining');if(r[s++]!==Zl)throw new Error('Could not find expected "int" for "r"');var a=r[s++];if(i-s-2<a)throw new Error('"r" specified length of "'+a+'", only "'+(i-s-2)+'" available');if(n<a)throw new Error('"r" specified length of "'+a+'", max of "'+n+'" is acceptable');var c=s;if(s+=a,r[s++]!==Zl)throw new Error('Could not find expected "int" for "s"');var l=r[s++];if(i-s!==l)throw new Error('"s" specified length of "'+l+'", expected "'+(i-s)+'"');if(n<l)throw new Error('"s" specified length of "'+l+'", max of "'+n+'" is acceptable');var p=s;if(s+=l,s!==i)throw new Error('Expected to consume entire buffer, but "'+(i-s)+'" bytes remain');var f=t-a,h=t-l,v=Jl.allocUnsafe(f+a+h+l);for(s=0;s<f;++s)v[s]=0;r.copy(v,s,c+Math.max(-f,0),c+a),s=t;for(var x=s;s<x+h;++s)v[s]=0;return r.copy(v,s,p+Math.max(-h,0),p+l),v=v.toString("base64"),v=zB(v),v}function ME(r,e,t){for(var n=0;e+n<t&&r[e+n]===0;)++n;var i=r[e+n]>=Xl;return i&&--n,n}function KB(r,e){r=LE(r);var t=PE(e),n=r.length;if(n!==t*2)throw new TypeError('"'+e+'" signatures must be "'+t*2+'" bytes, saw "'+n+'"');var i=ME(r,0,t),s=ME(r,t,r.length),o=t-i,a=t-s,c=2+o+1+1+a,l=c<Xl,p=Jl.allocUnsafe((l?2:3)+c),f=0;return p[f++]=NE,l?p[f++]=c:(p[f++]=Xl|1,p[f++]=c&255),p[f++]=Zl,p[f++]=o,i<0?(p[f++]=0,f+=r.copy(p,f,0,t)):f+=r.copy(p,f,i,t),p[f++]=Zl,p[f++]=a,s<0?(p[f++]=0,r.copy(p,f,t)):r.copy(p,f,t+s),p}DE.exports={derToJose:VB,joseToDer:KB}});var FE=R((EW,jE)=>{"use strict";var Vo=require("buffer").Buffer,Yh=require("buffer").SlowBuffer;jE.exports=Ql;function Ql(r,e){if(!Vo.isBuffer(r)||!Vo.isBuffer(e)||r.length!==e.length)return!1;for(var t=0,n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}Ql.install=function(){Vo.prototype.equal=Yh.prototype.equal=function(e){return Ql(this,e)}};var YB=Vo.prototype.equal,JB=Yh.prototype.equal;Ql.restore=function(){Vo.prototype.equal=YB,Yh.prototype.equal=JB}});var Qh=R((TW,KE)=>{var Ds=Ns().Buffer,dr=require("crypto"),qE=BE(),UE=require("util"),XB=`"%s" is not a valid algorithm.
93
93
  Supported algorithms are:
94
- "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Ko="secret must be a string or buffer",Ls="key must be a string or a buffer",ZB="key must be a string, a buffer or an object",Xh=typeof dr.createPublicKey=="function";Xh&&(Ls+=" or a KeyObject",Ko+="or a KeyObject");function HE(r){if(!Ds.isBuffer(r)&&typeof r!="string"&&(!Xh||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw Ar(Ls)}function $E(r){if(!Ds.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw Ar(ZB)}function QB(r){if(!Ds.isBuffer(r)){if(typeof r=="string")return r;if(!Xh||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw Ar(Ko)}}function Zh(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function WE(r){r=r.toString();var e=4-r.length%4;if(e!==4)for(var t=0;t<e;++t)r+="=";return r.replace(/\-/g,"+").replace(/_/g,"/")}function Ar(r){var e=[].slice.call(arguments,1),t=UE.format.bind(UE,r).apply(null,e);return new TypeError(t)}function ej(r){return Ds.isBuffer(r)||typeof r=="string"}function Yo(r){return ej(r)||(r=JSON.stringify(r)),r}function GE(r){return function(t,n){QB(n),t=Yo(t);var i=dr.createHmac("sha"+r,n),s=(i.update(t),i.digest("base64"));return Zh(s)}}var Jh,tj="timingSafeEqual"in dr?function(e,t){return e.byteLength!==t.byteLength?!1:dr.timingSafeEqual(e,t)}:function(e,t){return Jh||(Jh=FE()),Jh(e,t)};function rj(r){return function(t,n,i){var s=GE(r)(t,i);return tj(Ds.from(n),Ds.from(s))}}function zE(r){return function(t,n){$E(n),t=Yo(t);var i=dr.createSign("RSA-SHA"+r),s=(i.update(t),i.sign(n,"base64"));return Zh(s)}}function VE(r){return function(t,n,i){HE(i),t=Yo(t),n=WE(n);var s=dr.createVerify("RSA-SHA"+r);return s.update(t),s.verify(i,n,"base64")}}function nj(r){return function(t,n){$E(n),t=Yo(t);var i=dr.createSign("RSA-SHA"+r),s=(i.update(t),i.sign({key:n,padding:dr.constants.RSA_PKCS1_PSS_PADDING,saltLength:dr.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Zh(s)}}function ij(r){return function(t,n,i){HE(i),t=Yo(t),n=WE(n);var s=dr.createVerify("RSA-SHA"+r);return s.update(t),s.verify({key:i,padding:dr.constants.RSA_PKCS1_PSS_PADDING,saltLength:dr.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function sj(r){var e=zE(r);return function(){var n=e.apply(null,arguments);return n=qE.derToJose(n,"ES"+r),n}}function oj(r){var e=VE(r);return function(n,i,s){i=qE.joseToDer(i,"ES"+r).toString("base64");var o=e(n,i,s);return o}}function aj(){return function(){return""}}function cj(){return function(e,t){return t===""}}KE.exports=function(e){var t={hs:GE,rs:zE,ps:nj,es:sj,none:aj},n={hs:rj,rs:VE,ps:ij,es:oj,none:cj},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw Ar(XB,e);var s=(i[1]||i[3]).toLowerCase(),o=i[2];return{sign:t[s](o),verify:n[s](o)}}});var em=R((AW,YE)=>{var lj=require("buffer").Buffer;YE.exports=function(e){return typeof e=="string"?e:typeof e=="number"||lj.isBuffer(e)?e.toString():JSON.stringify(e)}});var t1=R((RW,e1)=>{var uj=Ns().Buffer,JE=Vh(),pj=Qh(),fj=require("stream"),XE=em(),tm=require("util");function ZE(r,e){return uj.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function dj(r,e,t){t=t||"utf8";var n=ZE(XE(r),"binary"),i=ZE(XE(e),t);return tm.format("%s.%s",n,i)}function QE(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,i=r.encoding,s=pj(e.alg),o=dj(e,t,i),a=s.sign(o,n);return tm.format("%s.%s",o,a)}function eu(r){var e=r.secret;if(e=e??r.privateKey,e=e??r.key,/^hs/i.test(r.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new JE(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new JE(r.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}tm.inherits(eu,fj);eu.prototype.sign=function(){try{var e=QE({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(t){this.readable=!1,this.emit("error",t),this.emit("close")}};eu.sign=QE;e1.exports=eu});var p1=R((kW,u1)=>{var n1=Ns().Buffer,r1=Vh(),hj=Qh(),mj=require("stream"),i1=em(),gj=require("util"),vj=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function yj(r){return Object.prototype.toString.call(r)==="[object Object]"}function xj(r){if(yj(r))return r;try{return JSON.parse(r)}catch{return}}function s1(r){var e=r.split(".",1)[0];return xj(n1.from(e,"base64").toString("binary"))}function _j(r){return r.split(".",2).join(".")}function o1(r){return r.split(".")[2]}function bj(r,e){e=e||"utf8";var t=r.split(".")[1];return n1.from(t,"base64").toString(e)}function a1(r){return vj.test(r)&&!!s1(r)}function c1(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=i1(r);var i=o1(r),s=_j(r),o=hj(e);return o.verify(s,i,t)}function l1(r,e){if(e=e||{},r=i1(r),!a1(r))return null;var t=s1(r);if(!t)return null;var n=bj(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:o1(r)}}function Bs(r){r=r||{};var e=r.secret;if(e=e??r.publicKey,e=e??r.key,/^hs/i.test(r.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new r1(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new r1(r.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}gj.inherits(Bs,mj);Bs.prototype.verify=function(){try{var e=c1(this.signature.buffer,this.algorithm,this.key.buffer),t=l1(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Bs.decode=l1;Bs.isValid=a1;Bs.verify=c1;u1.exports=Bs});var d1=R(Hn=>{var f1=t1(),tu=p1(),wj=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Hn.ALGORITHMS=wj;Hn.sign=f1.sign;Hn.verify=tu.verify;Hn.decode=tu.decode;Hn.isValid=tu.isValid;Hn.createSign=function(e){return new f1(e)};Hn.createVerify=function(e){return new tu(e)}});var ru=R((MW,h1)=>{"use strict";var rm={};rm.supportedContentEncodings={AES_GCM:"aesgcm",AES_128_GCM:"aes128gcm"};rm.supportedUrgency={VERY_LOW:"very-low",LOW:"low",NORMAL:"normal",HIGH:"high"};h1.exports=rm});var nm=R((PW,m1)=>{"use strict";function Sj(r){return/^[A-Za-z0-9\-_]+$/.test(r)}m1.exports={validate:Sj}});var sm=R((IW,S1)=>{"use strict";var Ej=require("crypto"),Tj=TE(),Cj=d1(),{URL:v1}=require("url"),g1=ru(),y1=nm(),Aj=720*60,Rj=1440*60,kj=Tj.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").explicit(0).objid().optional(),this.key("publicKey").explicit(1).bitstr().optional())});function Oj(r){return kj.encode({version:1,privateKey:r,parameters:[1,2,840,10045,3,1,7]},"pem",{label:"EC PRIVATE KEY"})}function Mj(){let r=Ej.createECDH("prime256v1");r.generateKeys();let e=r.getPublicKey(),t=r.getPrivateKey();if(t.length<32){let n=Buffer.alloc(32-t.length);n.fill(0),t=Buffer.concat([n,t])}if(e.length<65){let n=Buffer.alloc(65-e.length);n.fill(0),e=Buffer.concat([n,e])}return{publicKey:e.toString("base64url"),privateKey:t.toString("base64url")}}function x1(r){if(!r)throw new Error("No subject set in vapidDetails.subject.");if(typeof r!="string"||r.length===0)throw new Error("The subject value must be a string containing an https: URL or mailto: address. "+r);let e=null;try{e=new v1(r)}catch{throw new Error("Vapid subject is not a valid URL. "+r)}if(!["https:","mailto:"].includes(e.protocol))throw new Error("Vapid subject is not an https: or mailto: URL. "+r);e.hostname==="localhost"&&console.warn("Vapid subject points to a localhost web URI, which is unsupported by Apple's push notification server and will result in a BadJwtToken error when sending notifications.")}function _1(r){if(!r)throw new Error("No key set vapidDetails.publicKey");if(typeof r!="string")throw new Error("Vapid public key is must be a URL safe Base 64 encoded string.");if(!y1.validate(r))throw new Error('Vapid public key must be a URL safe Base 64 (without "=")');if(r=Buffer.from(r,"base64url"),r.length!==65)throw new Error("Vapid public key should be 65 bytes long when decoded.")}function b1(r){if(!r)throw new Error("No key set in vapidDetails.privateKey");if(typeof r!="string")throw new Error("Vapid private key must be a URL safe Base 64 encoded string.");if(!y1.validate(r))throw new Error('Vapid private key must be a URL safe Base 64 (without "=")');if(r=Buffer.from(r,"base64url"),r.length!==32)throw new Error("Vapid private key should be 32 bytes long when decoded.")}function im(r){let e=new Date;return e.setSeconds(e.getSeconds()+r),Math.floor(e.getTime()/1e3)}function w1(r){if(!Number.isInteger(r))throw new Error("`expiration` value must be a number");if(r<0)throw new Error("`expiration` must be a positive integer");let e=im(Rj);if(r>=e)throw new Error("`expiration` value is greater than maximum of 24 hours")}function Pj(r,e,t,n,i,s){if(!r)throw new Error("No audience could be generated for VAPID.");if(typeof r!="string"||r.length===0)throw new Error("The audience value must be a string containing the origin of a push service. "+r);try{new v1(r)}catch{throw new Error("VAPID audience is not a url. "+r)}x1(e),_1(t),b1(n),n=Buffer.from(n,"base64url"),s?w1(s):s=im(Aj);let o={typ:"JWT",alg:"ES256"},a={aud:r,exp:s,sub:e},c=Cj.sign({header:o,payload:a,privateKey:Oj(n)});if(i===g1.supportedContentEncodings.AES_128_GCM)return{Authorization:"vapid t="+c+", k="+t};if(i===g1.supportedContentEncodings.AES_GCM)return{Authorization:"WebPush "+c,"Crypto-Key":"p256ecdsa="+t};throw new Error("Unsupported encoding type specified.")}S1.exports={generateVAPIDKeys:Mj,getFutureExpirationTimestamp:im,getVapidHeaders:Pj,validateSubject:x1,validatePublicKey:_1,validatePrivateKey:b1,validateExpiration:w1}});var N1=R((NW,I1)=>{"use strict";var iu=require("crypto"),T1="aes-128-gcm",su={aes128gcm:1,aesgcm:2},vi=16,Hr=16,Ij=12,C1=32,Jo="encrypt",Xo="decrypt",he;process.env.ECE_KEYLOG==="1"?he=function(r,e){return console.warn(r+" ["+e.length+"]: "+e.toString("base64url")),e}:he=function(r,e){return e};function nu(r){return typeof r=="string"?Buffer.from(r,"base64url"):r}function A1(r,e){var t=iu.createHmac("sha256",r);return t.update(e),t.digest()}function R1(r,e){return he("salt",r),he("ikm",e),he("extract",A1(r,e))}function om(r,e,t){he("prk",r),he("info",e);var n=Buffer.alloc(0),i=Buffer.alloc(0);e=Buffer.from(e,"ascii");for(var s=0,o=Buffer.alloc(1);n.length<t;)o.writeUIntBE(++s,0,1),i=A1(r,Buffer.concat([i,e,o])),n=Buffer.concat([n,i]);return he("expand",n.slice(0,t))}function k1(r,e,t,n){return om(R1(r,e),t,n)}function am(r,e){var t=Buffer.concat([Buffer.from("Content-Encoding: "+r+"\0","ascii"),e]);return he("info "+r,t),t}function E1(r){var e=Buffer.concat([Buffer.alloc(2),r]);return e.writeUIntBE(r.length,0,2),e}function Nj(r,e){var t=r.privateKey,n,i;if(e===Jo)n=t.getPublicKey(),i=r.dh;else if(e===Xo)n=r.dh,i=t.getPublicKey();else throw new Error("Unknown mode only "+Jo+" and "+Xo+" supported");return{secret:t.computeSecret(r.dh),context:Buffer.concat([Buffer.from(r.keylabel,"ascii"),Buffer.from([0]),E1(i),E1(n)])}}function Lj(r,e){var t={secret:null,context:Buffer.alloc(0)};if(r.key){if(t.secret=r.key,t.secret.length!==Hr)throw new Error("An explicit key must be "+Hr+" bytes")}else r.dh?t=Nj(r,e):typeof r.keyid!==void 0&&(t.secret=r.keymap[r.keyid]);if(!t.secret)throw new Error("Unable to determine key");return he("secret",t.secret),he("context",t.context),r.authSecret&&(t.secret=k1(r.authSecret,t.secret,am("auth",Buffer.alloc(0)),C1),he("authsecret",t.secret)),t}function Dj(r,e){if(!r.authSecret)throw new Error("No authentication secret for webpush");he("authsecret",r.authSecret);var t,n,i;if(e===Jo)n=r.privateKey.getPublicKey(),t=i=r.dh;else if(e===Xo)t=n=r.keyid,i=r.privateKey.getPublicKey();else throw new Error("Unknown mode only "+Jo+" and "+Xo+" supported");return he("remote pubkey",t),he("sender pubkey",n),he("receiver pubkey",i),he("secret dh",k1(r.authSecret,r.privateKey.computeSecret(t),Buffer.concat([Buffer.from("WebPush: info\0"),i,n]),C1))}function Bj(r,e,t){if(t&&!zj(t))throw new Error("Callback is not a function");if(r.key){if(r.key.length!==Hr)throw new Error("An explicit key must be "+Hr+" bytes");return he("secret key",r.key)}if(!r.privateKey){if(t)var n=t(r.keyid);else var n=r.keymap&&r.keymap[r.keyid];if(!n)throw new Error('No saved key (keyid: "'+r.keyid+'")');return n}return Dj(r,e)}function O1(r,e,t){if(!r.salt)throw new Error("must include a salt parameter for "+r.version);var n,i,s;if(r.version==="aesgcm"){var o=Lj(r,e,t);n=am("aesgcm",o.context),i=am("nonce",o.context),s=o.secret}else if(r.version==="aes128gcm")n=Buffer.from("Content-Encoding: aes128gcm\0"),i=Buffer.from("Content-Encoding: nonce\0"),s=Bj(r,e,t);else throw new Error("Unable to set context for mode "+r.version);var a=R1(r.salt,s),c={key:om(a,n,Hr),nonce:om(a,i,Ij)};return he("key",c.key),he("nonce base",c.nonce),c}function M1(r){var e={};e.version=r.version||"aes128gcm",e.rs=parseInt(r.rs,10),isNaN(e.rs)&&(e.rs=4096);var t=su[e.version];if(e.version==="aes128gcm"&&(t+=vi),e.rs<=t)throw new Error("The rs parameter has to be greater than "+t);if(r.salt&&(e.salt=nu(r.salt),e.salt.length!==Hr))throw new Error("The salt parameter must be "+Hr+" bytes");return e.keyid=r.keyid,r.key?e.key=nu(r.key):(e.privateKey=r.privateKey,e.privateKey||(e.keymap=r.keymap),e.version!=="aes128gcm"&&(e.keylabel=r.keylabel||"P-256"),r.dh&&(e.dh=nu(r.dh))),r.authSecret&&(e.authSecret=nu(r.authSecret)),e}function P1(r,e){var t=Buffer.from(r),n=t.readUIntBE(t.length-6,6),i=((n^e)&16777215)+((n/16777216^e/16777216)&16777215)*16777216;return t.writeUIntBE(i,t.length-6,6),he("nonce"+e,t),t}function jj(r,e){var t=r.readUIntBE(20,1);return e.salt=r.slice(0,Hr),e.rs=r.readUIntBE(Hr,4),e.keyid=r.slice(21,21+t),21+t}function Fj(r,e){var t=su[e],n=r.readUIntBE(0,t);if(n+t>r.length)throw new Error("padding exceeds block size");he("padding",r.slice(0,t+n));var i=Buffer.alloc(n);if(i.fill(0),i.compare(r.slice(t,t+n))!==0)throw new Error("invalid padding");return r.slice(t+n)}function Uj(r,e){for(var t=r.length-1;t>=0;){if(r[t]){if(e){if(r[t]!==2)throw new Error("last record needs to start padding with a 2")}else if(r[t]!==1)throw new Error("last record needs to start padding with a 2");return r.slice(0,t)}--t}throw new Error("all zero plaintext")}function qj(r,e,t,n,i){he("decrypt",t);var s=P1(r.nonce,e),o=iu.createDecipheriv(T1,r.key,s);o.setAuthTag(t.slice(t.length-vi));var a=o.update(t.slice(0,t.length-vi));return a=Buffer.concat([a,o.final()]),he("decrypted",a),n.version!=="aes128gcm"?Fj(a,n.version):Uj(a,i)}function Hj(r,e,t){var n=M1(e);if(n.version==="aes128gcm"){var i=jj(r,n);r=r.slice(i)}var s=O1(n,Xo,t),o=0,a=Buffer.alloc(0),c=n.rs;n.version!=="aes128gcm"&&(c+=vi);for(var l=0;o<r.length;++l){var p=o+c;if(n.version!=="aes128gcm"&&p===r.length)throw new Error("Truncated payload");if(p=Math.min(p,r.length),p-o<=vi)throw new Error("Invalid block: too small at "+l);var f=qj(s,l,r.slice(o,p),n,p>=r.length);a=Buffer.concat([a,f]),o=p}return a}function $j(r,e,t,n,i,s){he("encrypt",t),n=n||0;var o=P1(r.nonce,e),a=iu.createCipheriv(T1,r.key,o),c=[],l=su[i.version],p=Buffer.alloc(n+l);if(p.fill(0),i.version!=="aes128gcm"){if(p.writeUIntBE(n,0,l),he("padding",p),c.push(a.update(p)),c.push(a.update(t)),!s&&p.length+t.length<i.rs)throw new Error("Unable to pad to record size")}else c.push(a.update(t)),p.writeUIntBE(s?2:1,0,1),he("padding",p),c.push(a.update(p));a.final();var f=a.getAuthTag();if(f.length!==vi)throw new Error("invalid tag generated");return c.push(f),he("encrypted",Buffer.concat(c))}function Wj(r){var e=Buffer.alloc(5),t=Buffer.from(r.keyid||[]);if(t.length>255)throw new Error("keyid is too large");return e.writeUIntBE(r.rs,0,4),e.writeUIntBE(t.length,4,1),Buffer.concat([r.salt,e,t])}function Gj(r,e,t){if(!Buffer.isBuffer(r))throw new Error("buffer argument must be a Buffer");var n=M1(e);n.salt||(n.salt=iu.randomBytes(Hr));var i;n.version==="aes128gcm"?(n.privateKey&&!n.keyid&&(n.keyid=n.privateKey.getPublicKey()),i=Wj(n)):i=Buffer.alloc(0);var s=O1(n,Jo,t),o=0,a=su[n.version],c=a;n.version==="aes128gcm"&&(c+=vi);for(var l=isNaN(parseInt(e.pad,10))?0:parseInt(e.pad,10),p=0,f=!1;!f;){var h=Math.min(n.rs-c-1,l);n.version!=="aes128gcm"&&(h=Math.min((1<<a*8)-1,h)),l>0&&h===0&&++h,l-=h;var v=o+n.rs-c-h;n.version!=="aes128gcm"?f=v>r.length:f=v>=r.length,f=f&&l<=0;var x=$j(s,p,r.slice(o,v),h,n,f);i=Buffer.concat([i,x]),o=v,++p}return i}function zj(r){return typeof r=="function"}I1.exports={decrypt:Hj,encrypt:Gj}});var cm=R((LW,D1)=>{"use strict";var L1=require("crypto"),Vj=N1(),Kj=function(r,e,t,n){if(!r)throw new Error("No user public key provided for encryption.");if(typeof r!="string")throw new Error("The subscription p256dh value must be a string.");if(Buffer.from(r,"base64url").length!==65)throw new Error("The subscription p256dh value should be 65 bytes long.");if(!e)throw new Error("No user auth provided for encryption.");if(typeof e!="string")throw new Error("The subscription auth key must be a string.");if(Buffer.from(e,"base64url").length<16)throw new Error("The subscription auth key should be at least 16 bytes long");if(typeof t!="string"&&!Buffer.isBuffer(t))throw new Error("Payload must be either a string or a Node Buffer.");(typeof t=="string"||t instanceof String)&&(t=Buffer.from(t));let i=L1.createECDH("prime256v1"),s=i.generateKeys(),o=L1.randomBytes(16).toString("base64url"),a=Vj.encrypt(t,{version:n,dh:r,privateKey:i,salt:o,authSecret:e});return{localPublicKey:s,salt:o,cipherText:a}};D1.exports={encrypt:Kj}});var lm=R((DW,j1)=>{"use strict";function B1(r,e,t,n,i){Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=r,this.statusCode=e,this.headers=t,this.body=n,this.endpoint=i}require("util").inherits(B1,Error);j1.exports=B1});var q1=R(jt=>{"use strict";var Yj=jt&&jt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Jj=jt&&jt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),F1=jt&&jt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&Yj(e,r,t);return Jj(e,r),e};Object.defineProperty(jt,"__esModule",{value:!0});jt.req=jt.json=jt.toBuffer=void 0;var Xj=F1(require("http")),Zj=F1(require("https"));async function U1(r){let e=0,t=[];for await(let n of r)e+=n.length,t.push(n);return Buffer.concat(t,e)}jt.toBuffer=U1;async function Qj(r){let t=(await U1(r)).toString("utf8");try{return JSON.parse(t)}catch(n){let i=n;throw i.message+=` (input: ${t})`,i}}jt.json=Qj;function eF(r,e={}){let n=((typeof r=="string"?r:r.href).startsWith("https:")?Zj:Xj).request(r,e),i=new Promise((s,o)=>{n.once("response",s).once("error",o).end()});return n.then=i.then.bind(i),n}jt.req=eF});var G1=R(Yt=>{"use strict";var $1=Yt&&Yt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),tF=Yt&&Yt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),W1=Yt&&Yt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&$1(e,r,t);return tF(e,r),e},rF=Yt&&Yt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&$1(e,r,t)};Object.defineProperty(Yt,"__esModule",{value:!0});Yt.Agent=void 0;var nF=W1(require("net")),H1=W1(require("http")),iF=require("https");rF(q1(),Yt);var $r=Symbol("AgentBaseInternalState"),um=class extends H1.Agent{constructor(e){super(e),this[$r]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
94
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Ko="secret must be a string or buffer",Ls="key must be a string or a buffer",ZB="key must be a string, a buffer or an object",Xh=typeof dr.createPublicKey=="function";Xh&&(Ls+=" or a KeyObject",Ko+="or a KeyObject");function HE(r){if(!Ds.isBuffer(r)&&typeof r!="string"&&(!Xh||typeof r!="object"||typeof r.type!="string"||typeof r.asymmetricKeyType!="string"||typeof r.export!="function"))throw Ar(Ls)}function $E(r){if(!Ds.isBuffer(r)&&typeof r!="string"&&typeof r!="object")throw Ar(ZB)}function QB(r){if(!Ds.isBuffer(r)){if(typeof r=="string")return r;if(!Xh||typeof r!="object"||r.type!=="secret"||typeof r.export!="function")throw Ar(Ko)}}function Zh(r){return r.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function WE(r){r=r.toString();var e=4-r.length%4;if(e!==4)for(var t=0;t<e;++t)r+="=";return r.replace(/\-/g,"+").replace(/_/g,"/")}function Ar(r){var e=[].slice.call(arguments,1),t=UE.format.bind(UE,r).apply(null,e);return new TypeError(t)}function ej(r){return Ds.isBuffer(r)||typeof r=="string"}function Yo(r){return ej(r)||(r=JSON.stringify(r)),r}function GE(r){return function(t,n){QB(n),t=Yo(t);var i=dr.createHmac("sha"+r,n),s=(i.update(t),i.digest("base64"));return Zh(s)}}var Jh,tj="timingSafeEqual"in dr?function(e,t){return e.byteLength!==t.byteLength?!1:dr.timingSafeEqual(e,t)}:function(e,t){return Jh||(Jh=FE()),Jh(e,t)};function rj(r){return function(t,n,i){var s=GE(r)(t,i);return tj(Ds.from(n),Ds.from(s))}}function zE(r){return function(t,n){$E(n),t=Yo(t);var i=dr.createSign("RSA-SHA"+r),s=(i.update(t),i.sign(n,"base64"));return Zh(s)}}function VE(r){return function(t,n,i){HE(i),t=Yo(t),n=WE(n);var s=dr.createVerify("RSA-SHA"+r);return s.update(t),s.verify(i,n,"base64")}}function nj(r){return function(t,n){$E(n),t=Yo(t);var i=dr.createSign("RSA-SHA"+r),s=(i.update(t),i.sign({key:n,padding:dr.constants.RSA_PKCS1_PSS_PADDING,saltLength:dr.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Zh(s)}}function ij(r){return function(t,n,i){HE(i),t=Yo(t),n=WE(n);var s=dr.createVerify("RSA-SHA"+r);return s.update(t),s.verify({key:i,padding:dr.constants.RSA_PKCS1_PSS_PADDING,saltLength:dr.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}function sj(r){var e=zE(r);return function(){var n=e.apply(null,arguments);return n=qE.derToJose(n,"ES"+r),n}}function oj(r){var e=VE(r);return function(n,i,s){i=qE.joseToDer(i,"ES"+r).toString("base64");var o=e(n,i,s);return o}}function aj(){return function(){return""}}function cj(){return function(e,t){return t===""}}KE.exports=function(e){var t={hs:GE,rs:zE,ps:nj,es:sj,none:aj},n={hs:rj,rs:VE,ps:ij,es:oj,none:cj},i=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!i)throw Ar(XB,e);var s=(i[1]||i[3]).toLowerCase(),o=i[2];return{sign:t[s](o),verify:n[s](o)}}});var em=R((CW,YE)=>{var lj=require("buffer").Buffer;YE.exports=function(e){return typeof e=="string"?e:typeof e=="number"||lj.isBuffer(e)?e.toString():JSON.stringify(e)}});var t1=R((AW,e1)=>{var uj=Ns().Buffer,JE=Vh(),pj=Qh(),fj=require("stream"),XE=em(),tm=require("util");function ZE(r,e){return uj.from(r,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function dj(r,e,t){t=t||"utf8";var n=ZE(XE(r),"binary"),i=ZE(XE(e),t);return tm.format("%s.%s",n,i)}function QE(r){var e=r.header,t=r.payload,n=r.secret||r.privateKey,i=r.encoding,s=pj(e.alg),o=dj(e,t,i),a=s.sign(o,n);return tm.format("%s.%s",o,a)}function eu(r){var e=r.secret;if(e=e??r.privateKey,e=e??r.key,/^hs/i.test(r.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new JE(e);this.readable=!0,this.header=r.header,this.encoding=r.encoding,this.secret=this.privateKey=this.key=t,this.payload=new JE(r.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}tm.inherits(eu,fj);eu.prototype.sign=function(){try{var e=QE({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(t){this.readable=!1,this.emit("error",t),this.emit("close")}};eu.sign=QE;e1.exports=eu});var p1=R((RW,u1)=>{var n1=Ns().Buffer,r1=Vh(),hj=Qh(),mj=require("stream"),i1=em(),gj=require("util"),vj=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function yj(r){return Object.prototype.toString.call(r)==="[object Object]"}function xj(r){if(yj(r))return r;try{return JSON.parse(r)}catch{return}}function s1(r){var e=r.split(".",1)[0];return xj(n1.from(e,"base64").toString("binary"))}function _j(r){return r.split(".",2).join(".")}function o1(r){return r.split(".")[2]}function bj(r,e){e=e||"utf8";var t=r.split(".")[1];return n1.from(t,"base64").toString(e)}function a1(r){return vj.test(r)&&!!s1(r)}function c1(r,e,t){if(!e){var n=new Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}r=i1(r);var i=o1(r),s=_j(r),o=hj(e);return o.verify(s,i,t)}function l1(r,e){if(e=e||{},r=i1(r),!a1(r))return null;var t=s1(r);if(!t)return null;var n=bj(r);return(t.typ==="JWT"||e.json)&&(n=JSON.parse(n,e.encoding)),{header:t,payload:n,signature:o1(r)}}function Bs(r){r=r||{};var e=r.secret;if(e=e??r.publicKey,e=e??r.key,/^hs/i.test(r.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var t=new r1(e);this.readable=!0,this.algorithm=r.algorithm,this.encoding=r.encoding,this.secret=this.publicKey=this.key=t,this.signature=new r1(r.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}gj.inherits(Bs,mj);Bs.prototype.verify=function(){try{var e=c1(this.signature.buffer,this.algorithm,this.key.buffer),t=l1(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Bs.decode=l1;Bs.isValid=a1;Bs.verify=c1;u1.exports=Bs});var d1=R(Hn=>{var f1=t1(),tu=p1(),wj=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Hn.ALGORITHMS=wj;Hn.sign=f1.sign;Hn.verify=tu.verify;Hn.decode=tu.decode;Hn.isValid=tu.isValid;Hn.createSign=function(e){return new f1(e)};Hn.createVerify=function(e){return new tu(e)}});var ru=R((OW,h1)=>{"use strict";var rm={};rm.supportedContentEncodings={AES_GCM:"aesgcm",AES_128_GCM:"aes128gcm"};rm.supportedUrgency={VERY_LOW:"very-low",LOW:"low",NORMAL:"normal",HIGH:"high"};h1.exports=rm});var nm=R((MW,m1)=>{"use strict";function Sj(r){return/^[A-Za-z0-9\-_]+$/.test(r)}m1.exports={validate:Sj}});var sm=R((PW,S1)=>{"use strict";var Ej=require("crypto"),Tj=TE(),Cj=d1(),{URL:v1}=require("url"),g1=ru(),y1=nm(),Aj=720*60,Rj=1440*60,kj=Tj.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").explicit(0).objid().optional(),this.key("publicKey").explicit(1).bitstr().optional())});function Oj(r){return kj.encode({version:1,privateKey:r,parameters:[1,2,840,10045,3,1,7]},"pem",{label:"EC PRIVATE KEY"})}function Mj(){let r=Ej.createECDH("prime256v1");r.generateKeys();let e=r.getPublicKey(),t=r.getPrivateKey();if(t.length<32){let n=Buffer.alloc(32-t.length);n.fill(0),t=Buffer.concat([n,t])}if(e.length<65){let n=Buffer.alloc(65-e.length);n.fill(0),e=Buffer.concat([n,e])}return{publicKey:e.toString("base64url"),privateKey:t.toString("base64url")}}function x1(r){if(!r)throw new Error("No subject set in vapidDetails.subject.");if(typeof r!="string"||r.length===0)throw new Error("The subject value must be a string containing an https: URL or mailto: address. "+r);let e=null;try{e=new v1(r)}catch{throw new Error("Vapid subject is not a valid URL. "+r)}if(!["https:","mailto:"].includes(e.protocol))throw new Error("Vapid subject is not an https: or mailto: URL. "+r);e.hostname==="localhost"&&console.warn("Vapid subject points to a localhost web URI, which is unsupported by Apple's push notification server and will result in a BadJwtToken error when sending notifications.")}function _1(r){if(!r)throw new Error("No key set vapidDetails.publicKey");if(typeof r!="string")throw new Error("Vapid public key is must be a URL safe Base 64 encoded string.");if(!y1.validate(r))throw new Error('Vapid public key must be a URL safe Base 64 (without "=")');if(r=Buffer.from(r,"base64url"),r.length!==65)throw new Error("Vapid public key should be 65 bytes long when decoded.")}function b1(r){if(!r)throw new Error("No key set in vapidDetails.privateKey");if(typeof r!="string")throw new Error("Vapid private key must be a URL safe Base 64 encoded string.");if(!y1.validate(r))throw new Error('Vapid private key must be a URL safe Base 64 (without "=")');if(r=Buffer.from(r,"base64url"),r.length!==32)throw new Error("Vapid private key should be 32 bytes long when decoded.")}function im(r){let e=new Date;return e.setSeconds(e.getSeconds()+r),Math.floor(e.getTime()/1e3)}function w1(r){if(!Number.isInteger(r))throw new Error("`expiration` value must be a number");if(r<0)throw new Error("`expiration` must be a positive integer");let e=im(Rj);if(r>=e)throw new Error("`expiration` value is greater than maximum of 24 hours")}function Pj(r,e,t,n,i,s){if(!r)throw new Error("No audience could be generated for VAPID.");if(typeof r!="string"||r.length===0)throw new Error("The audience value must be a string containing the origin of a push service. "+r);try{new v1(r)}catch{throw new Error("VAPID audience is not a url. "+r)}x1(e),_1(t),b1(n),n=Buffer.from(n,"base64url"),s?w1(s):s=im(Aj);let o={typ:"JWT",alg:"ES256"},a={aud:r,exp:s,sub:e},c=Cj.sign({header:o,payload:a,privateKey:Oj(n)});if(i===g1.supportedContentEncodings.AES_128_GCM)return{Authorization:"vapid t="+c+", k="+t};if(i===g1.supportedContentEncodings.AES_GCM)return{Authorization:"WebPush "+c,"Crypto-Key":"p256ecdsa="+t};throw new Error("Unsupported encoding type specified.")}S1.exports={generateVAPIDKeys:Mj,getFutureExpirationTimestamp:im,getVapidHeaders:Pj,validateSubject:x1,validatePublicKey:_1,validatePrivateKey:b1,validateExpiration:w1}});var N1=R((IW,I1)=>{"use strict";var iu=require("crypto"),T1="aes-128-gcm",su={aes128gcm:1,aesgcm:2},vi=16,Hr=16,Ij=12,C1=32,Jo="encrypt",Xo="decrypt",he;process.env.ECE_KEYLOG==="1"?he=function(r,e){return console.warn(r+" ["+e.length+"]: "+e.toString("base64url")),e}:he=function(r,e){return e};function nu(r){return typeof r=="string"?Buffer.from(r,"base64url"):r}function A1(r,e){var t=iu.createHmac("sha256",r);return t.update(e),t.digest()}function R1(r,e){return he("salt",r),he("ikm",e),he("extract",A1(r,e))}function om(r,e,t){he("prk",r),he("info",e);var n=Buffer.alloc(0),i=Buffer.alloc(0);e=Buffer.from(e,"ascii");for(var s=0,o=Buffer.alloc(1);n.length<t;)o.writeUIntBE(++s,0,1),i=A1(r,Buffer.concat([i,e,o])),n=Buffer.concat([n,i]);return he("expand",n.slice(0,t))}function k1(r,e,t,n){return om(R1(r,e),t,n)}function am(r,e){var t=Buffer.concat([Buffer.from("Content-Encoding: "+r+"\0","ascii"),e]);return he("info "+r,t),t}function E1(r){var e=Buffer.concat([Buffer.alloc(2),r]);return e.writeUIntBE(r.length,0,2),e}function Nj(r,e){var t=r.privateKey,n,i;if(e===Jo)n=t.getPublicKey(),i=r.dh;else if(e===Xo)n=r.dh,i=t.getPublicKey();else throw new Error("Unknown mode only "+Jo+" and "+Xo+" supported");return{secret:t.computeSecret(r.dh),context:Buffer.concat([Buffer.from(r.keylabel,"ascii"),Buffer.from([0]),E1(i),E1(n)])}}function Lj(r,e){var t={secret:null,context:Buffer.alloc(0)};if(r.key){if(t.secret=r.key,t.secret.length!==Hr)throw new Error("An explicit key must be "+Hr+" bytes")}else r.dh?t=Nj(r,e):typeof r.keyid!==void 0&&(t.secret=r.keymap[r.keyid]);if(!t.secret)throw new Error("Unable to determine key");return he("secret",t.secret),he("context",t.context),r.authSecret&&(t.secret=k1(r.authSecret,t.secret,am("auth",Buffer.alloc(0)),C1),he("authsecret",t.secret)),t}function Dj(r,e){if(!r.authSecret)throw new Error("No authentication secret for webpush");he("authsecret",r.authSecret);var t,n,i;if(e===Jo)n=r.privateKey.getPublicKey(),t=i=r.dh;else if(e===Xo)t=n=r.keyid,i=r.privateKey.getPublicKey();else throw new Error("Unknown mode only "+Jo+" and "+Xo+" supported");return he("remote pubkey",t),he("sender pubkey",n),he("receiver pubkey",i),he("secret dh",k1(r.authSecret,r.privateKey.computeSecret(t),Buffer.concat([Buffer.from("WebPush: info\0"),i,n]),C1))}function Bj(r,e,t){if(t&&!zj(t))throw new Error("Callback is not a function");if(r.key){if(r.key.length!==Hr)throw new Error("An explicit key must be "+Hr+" bytes");return he("secret key",r.key)}if(!r.privateKey){if(t)var n=t(r.keyid);else var n=r.keymap&&r.keymap[r.keyid];if(!n)throw new Error('No saved key (keyid: "'+r.keyid+'")');return n}return Dj(r,e)}function O1(r,e,t){if(!r.salt)throw new Error("must include a salt parameter for "+r.version);var n,i,s;if(r.version==="aesgcm"){var o=Lj(r,e,t);n=am("aesgcm",o.context),i=am("nonce",o.context),s=o.secret}else if(r.version==="aes128gcm")n=Buffer.from("Content-Encoding: aes128gcm\0"),i=Buffer.from("Content-Encoding: nonce\0"),s=Bj(r,e,t);else throw new Error("Unable to set context for mode "+r.version);var a=R1(r.salt,s),c={key:om(a,n,Hr),nonce:om(a,i,Ij)};return he("key",c.key),he("nonce base",c.nonce),c}function M1(r){var e={};e.version=r.version||"aes128gcm",e.rs=parseInt(r.rs,10),isNaN(e.rs)&&(e.rs=4096);var t=su[e.version];if(e.version==="aes128gcm"&&(t+=vi),e.rs<=t)throw new Error("The rs parameter has to be greater than "+t);if(r.salt&&(e.salt=nu(r.salt),e.salt.length!==Hr))throw new Error("The salt parameter must be "+Hr+" bytes");return e.keyid=r.keyid,r.key?e.key=nu(r.key):(e.privateKey=r.privateKey,e.privateKey||(e.keymap=r.keymap),e.version!=="aes128gcm"&&(e.keylabel=r.keylabel||"P-256"),r.dh&&(e.dh=nu(r.dh))),r.authSecret&&(e.authSecret=nu(r.authSecret)),e}function P1(r,e){var t=Buffer.from(r),n=t.readUIntBE(t.length-6,6),i=((n^e)&16777215)+((n/16777216^e/16777216)&16777215)*16777216;return t.writeUIntBE(i,t.length-6,6),he("nonce"+e,t),t}function jj(r,e){var t=r.readUIntBE(20,1);return e.salt=r.slice(0,Hr),e.rs=r.readUIntBE(Hr,4),e.keyid=r.slice(21,21+t),21+t}function Fj(r,e){var t=su[e],n=r.readUIntBE(0,t);if(n+t>r.length)throw new Error("padding exceeds block size");he("padding",r.slice(0,t+n));var i=Buffer.alloc(n);if(i.fill(0),i.compare(r.slice(t,t+n))!==0)throw new Error("invalid padding");return r.slice(t+n)}function Uj(r,e){for(var t=r.length-1;t>=0;){if(r[t]){if(e){if(r[t]!==2)throw new Error("last record needs to start padding with a 2")}else if(r[t]!==1)throw new Error("last record needs to start padding with a 2");return r.slice(0,t)}--t}throw new Error("all zero plaintext")}function qj(r,e,t,n,i){he("decrypt",t);var s=P1(r.nonce,e),o=iu.createDecipheriv(T1,r.key,s);o.setAuthTag(t.slice(t.length-vi));var a=o.update(t.slice(0,t.length-vi));return a=Buffer.concat([a,o.final()]),he("decrypted",a),n.version!=="aes128gcm"?Fj(a,n.version):Uj(a,i)}function Hj(r,e,t){var n=M1(e);if(n.version==="aes128gcm"){var i=jj(r,n);r=r.slice(i)}var s=O1(n,Xo,t),o=0,a=Buffer.alloc(0),c=n.rs;n.version!=="aes128gcm"&&(c+=vi);for(var l=0;o<r.length;++l){var p=o+c;if(n.version!=="aes128gcm"&&p===r.length)throw new Error("Truncated payload");if(p=Math.min(p,r.length),p-o<=vi)throw new Error("Invalid block: too small at "+l);var f=qj(s,l,r.slice(o,p),n,p>=r.length);a=Buffer.concat([a,f]),o=p}return a}function $j(r,e,t,n,i,s){he("encrypt",t),n=n||0;var o=P1(r.nonce,e),a=iu.createCipheriv(T1,r.key,o),c=[],l=su[i.version],p=Buffer.alloc(n+l);if(p.fill(0),i.version!=="aes128gcm"){if(p.writeUIntBE(n,0,l),he("padding",p),c.push(a.update(p)),c.push(a.update(t)),!s&&p.length+t.length<i.rs)throw new Error("Unable to pad to record size")}else c.push(a.update(t)),p.writeUIntBE(s?2:1,0,1),he("padding",p),c.push(a.update(p));a.final();var f=a.getAuthTag();if(f.length!==vi)throw new Error("invalid tag generated");return c.push(f),he("encrypted",Buffer.concat(c))}function Wj(r){var e=Buffer.alloc(5),t=Buffer.from(r.keyid||[]);if(t.length>255)throw new Error("keyid is too large");return e.writeUIntBE(r.rs,0,4),e.writeUIntBE(t.length,4,1),Buffer.concat([r.salt,e,t])}function Gj(r,e,t){if(!Buffer.isBuffer(r))throw new Error("buffer argument must be a Buffer");var n=M1(e);n.salt||(n.salt=iu.randomBytes(Hr));var i;n.version==="aes128gcm"?(n.privateKey&&!n.keyid&&(n.keyid=n.privateKey.getPublicKey()),i=Wj(n)):i=Buffer.alloc(0);var s=O1(n,Jo,t),o=0,a=su[n.version],c=a;n.version==="aes128gcm"&&(c+=vi);for(var l=isNaN(parseInt(e.pad,10))?0:parseInt(e.pad,10),p=0,f=!1;!f;){var h=Math.min(n.rs-c-1,l);n.version!=="aes128gcm"&&(h=Math.min((1<<a*8)-1,h)),l>0&&h===0&&++h,l-=h;var v=o+n.rs-c-h;n.version!=="aes128gcm"?f=v>r.length:f=v>=r.length,f=f&&l<=0;var x=$j(s,p,r.slice(o,v),h,n,f);i=Buffer.concat([i,x]),o=v,++p}return i}function zj(r){return typeof r=="function"}I1.exports={decrypt:Hj,encrypt:Gj}});var cm=R((NW,D1)=>{"use strict";var L1=require("crypto"),Vj=N1(),Kj=function(r,e,t,n){if(!r)throw new Error("No user public key provided for encryption.");if(typeof r!="string")throw new Error("The subscription p256dh value must be a string.");if(Buffer.from(r,"base64url").length!==65)throw new Error("The subscription p256dh value should be 65 bytes long.");if(!e)throw new Error("No user auth provided for encryption.");if(typeof e!="string")throw new Error("The subscription auth key must be a string.");if(Buffer.from(e,"base64url").length<16)throw new Error("The subscription auth key should be at least 16 bytes long");if(typeof t!="string"&&!Buffer.isBuffer(t))throw new Error("Payload must be either a string or a Node Buffer.");(typeof t=="string"||t instanceof String)&&(t=Buffer.from(t));let i=L1.createECDH("prime256v1"),s=i.generateKeys(),o=L1.randomBytes(16).toString("base64url"),a=Vj.encrypt(t,{version:n,dh:r,privateKey:i,salt:o,authSecret:e});return{localPublicKey:s,salt:o,cipherText:a}};D1.exports={encrypt:Kj}});var lm=R((LW,j1)=>{"use strict";function B1(r,e,t,n,i){Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.message=r,this.statusCode=e,this.headers=t,this.body=n,this.endpoint=i}require("util").inherits(B1,Error);j1.exports=B1});var q1=R(jt=>{"use strict";var Yj=jt&&jt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),Jj=jt&&jt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),F1=jt&&jt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&Yj(e,r,t);return Jj(e,r),e};Object.defineProperty(jt,"__esModule",{value:!0});jt.req=jt.json=jt.toBuffer=void 0;var Xj=F1(require("http")),Zj=F1(require("https"));async function U1(r){let e=0,t=[];for await(let n of r)e+=n.length,t.push(n);return Buffer.concat(t,e)}jt.toBuffer=U1;async function Qj(r){let t=(await U1(r)).toString("utf8");try{return JSON.parse(t)}catch(n){let i=n;throw i.message+=` (input: ${t})`,i}}jt.json=Qj;function eF(r,e={}){let n=((typeof r=="string"?r:r.href).startsWith("https:")?Zj:Xj).request(r,e),i=new Promise((s,o)=>{n.once("response",s).once("error",o).end()});return n.then=i.then.bind(i),n}jt.req=eF});var G1=R(Yt=>{"use strict";var $1=Yt&&Yt.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),tF=Yt&&Yt.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),W1=Yt&&Yt.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&$1(e,r,t);return tF(e,r),e},rF=Yt&&Yt.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&$1(e,r,t)};Object.defineProperty(Yt,"__esModule",{value:!0});Yt.Agent=void 0;var nF=W1(require("net")),H1=W1(require("http")),iF=require("https");rF(q1(),Yt);var $r=Symbol("AgentBaseInternalState"),um=class extends H1.Agent{constructor(e){super(e),this[$r]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:t}=new Error;return typeof t!="string"?!1:t.split(`
95
95
  `).some(n=>n.indexOf("(https.js:")!==-1||n.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let t=new nF.Socket({writable:!1});return this.sockets[e].push(t),this.totalSocketCount++,t}decrementSockets(e,t){if(!this.sockets[e]||t===null)return;let n=this.sockets[e],i=n.indexOf(t);i!==-1&&(n.splice(i,1),this.totalSocketCount--,n.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?iF.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,t,n){let i={...t,secureEndpoint:this.isSecureEndpoint(t)},s=this.getName(i),o=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,i)).then(a=>{if(this.decrementSockets(s,o),a instanceof H1.Agent)try{return a.addRequest(e,i)}catch(c){return n(c)}this[$r].currentSocket=a,super.createSocket(e,t,n)},a=>{this.decrementSockets(s,o),n(a)})}createConnection(){let e=this[$r].currentSocket;if(this[$r].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[$r].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[$r]&&(this[$r].defaultPort=e)}get protocol(){return this[$r].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[$r]&&(this[$r].protocol=e)}};Yt.Agent=um});var z1=R(js=>{"use strict";var sF=js&&js.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(js,"__esModule",{value:!0});js.parseProxyResponse=void 0;var oF=sF(Ce()),ou=(0,oF.default)("https-proxy-agent:parse-proxy-response");function aF(r){return new Promise((e,t)=>{let n=0,i=[];function s(){let p=r.read();p?l(p):r.once("readable",s)}function o(){r.removeListener("end",a),r.removeListener("error",c),r.removeListener("readable",s)}function a(){o(),ou("onend"),t(new Error("Proxy connection ended before receiving CONNECT response"))}function c(p){o(),ou("onerror %o",p),t(p)}function l(p){i.push(p),n+=p.length;let f=Buffer.concat(i,n),h=f.indexOf(`\r
96
96
  \r
97
97
  `);if(h===-1){ou("have not received end of HTTP headers yet..."),s();return}let v=f.slice(0,h).toString("ascii").split(`\r
98
98
  `),x=v.shift();if(!x)return r.destroy(),t(new Error("No header received from proxy CONNECT response"));let S=x.split(" "),A=+S[1],k=S.slice(2).join(" "),P={};for(let I of v){if(!I)continue;let B=I.indexOf(":");if(B===-1)return r.destroy(),t(new Error(`Invalid header from proxy CONNECT response: "${I}"`));let V=I.slice(0,B).toLowerCase(),F=I.slice(B+1).trimStart(),G=P[V];typeof G=="string"?P[V]=[G,F]:Array.isArray(G)?G.push(F):P[V]=F}ou("got proxy server response: %o %o",x,P),o(),e({connect:{statusCode:A,statusText:k,headers:P},buffered:f})}r.on("error",c),r.on("end",a),s()})}js.parseProxyResponse=aF});var Z1=R(hr=>{"use strict";var cF=hr&&hr.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),lF=hr&&hr.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),J1=hr&&hr.__importStar||function(r){if(r&&r.__esModule)return r;var e={};if(r!=null)for(var t in r)t!=="default"&&Object.prototype.hasOwnProperty.call(r,t)&&cF(e,r,t);return lF(e,r),e},X1=hr&&hr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(hr,"__esModule",{value:!0});hr.HttpsProxyAgent=void 0;var au=J1(require("net")),V1=J1(require("tls")),uF=X1(require("assert")),pF=X1(Ce()),fF=G1(),dF=require("url"),hF=z1(),Zo=(0,pF.default)("https-proxy-agent"),K1=r=>r.servername===void 0&&r.host&&!au.isIP(r.host)?{...r,servername:r.host}:r,cu=class extends fF.Agent{constructor(e,t){super(t),this.options={path:void 0},this.proxy=typeof e=="string"?new dF.URL(e):e,this.proxyHeaders=t?.headers??{},Zo("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let n=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),i=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...t?Y1(t,"headers"):null,host:n,port:i}}async connect(e,t){let{proxy:n}=this;if(!t.host)throw new TypeError('No "host" provided');let i;n.protocol==="https:"?(Zo("Creating `tls.Socket`: %o",this.connectOpts),i=V1.connect(K1(this.connectOpts))):(Zo("Creating `net.Socket`: %o",this.connectOpts),i=au.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},o=au.isIPv6(t.host)?`[${t.host}]`:t.host,a=`CONNECT ${o}:${t.port} HTTP/1.1\r
99
99
  `;if(n.username||n.password){let h=`${decodeURIComponent(n.username)}:${decodeURIComponent(n.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(h).toString("base64")}`}s.Host=`${o}:${t.port}`,s["Proxy-Connection"]||(s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let h of Object.keys(s))a+=`${h}: ${s[h]}\r
100
100
  `;let c=(0,hF.parseProxyResponse)(i);i.write(`${a}\r
101
- `);let{connect:l,buffered:p}=await c;if(e.emit("proxyConnect",l),this.emit("proxyConnect",l,e),l.statusCode===200)return e.once("socket",mF),t.secureEndpoint?(Zo("Upgrading socket connection to TLS"),V1.connect({...Y1(K1(t),"host","path","port"),socket:i})):i;i.destroy();let f=new au.Socket({writable:!1});return f.readable=!0,e.once("socket",h=>{Zo("Replaying proxy buffer for failed request"),(0,uF.default)(h.listenerCount("data")>0),h.push(p),h.push(null)}),f}};cu.protocols=["http","https"];hr.HttpsProxyAgent=cu;function mF(r){r.resume()}function Y1(r,...e){let t={},n;for(n in r)e.includes(n)||(t[n]=r[n]);return t}});var nT=R((qW,rT)=>{"use strict";var eT=require("url"),tT=require("https"),gF=lm(),lu=sm(),vF=cm(),Jt=ru(),yF=nm(),Q1=2419200,pm="",fm;function Qo(){}Qo.prototype.setGCMAPIKey=function(r){if(r===null){pm=null;return}if(typeof r>"u"||typeof r!="string"||r.length===0)throw new Error("The GCM API Key should be a non-empty string or null.");pm=r};Qo.prototype.setVapidDetails=function(r,e,t){if(arguments.length===1&&arguments[0]===null){fm=null;return}lu.validateSubject(r),lu.validatePublicKey(e),lu.validatePrivateKey(t),fm={subject:r,publicKey:e,privateKey:t}};Qo.prototype.generateRequestDetails=function(r,e,t){if(!r||!r.endpoint)throw new Error("You must pass in a subscription with at least an endpoint.");if(typeof r.endpoint!="string"||r.endpoint.length===0)throw new Error("The subscription endpoint must be a string with a valid URL.");if(e&&(typeof r!="object"||!r.keys||!r.keys.p256dh||!r.keys.auth))throw new Error("To send a message with a payload, the subscription must have 'auth' and 'p256dh' keys.");let n=pm,i=fm,s=Q1,o={},a=Jt.supportedContentEncodings.AES_128_GCM,c=Jt.supportedUrgency.NORMAL,l,p,f,h;if(t){let k=["headers","gcmAPIKey","vapidDetails","TTL","contentEncoding","urgency","topic","proxy","agent","timeout"],P=Object.keys(t);for(let I=0;I<P.length;I+=1){let B=P[I];if(!k.includes(B))throw new Error("'"+B+"' is an invalid option. The valid options are ['"+k.join("', '")+"'].")}if(t.headers){o=t.headers;let I=Object.keys(o).filter(function(B){return typeof t[B]<"u"});if(I.length>0)throw new Error("Duplicated headers defined ["+I.join(",")+"]. Please either define the header in thetop level options OR in the 'headers' key.")}if(t.gcmAPIKey&&(n=t.gcmAPIKey),t.vapidDetails!==void 0&&(i=t.vapidDetails),t.TTL!==void 0&&(s=Number(t.TTL),s<0))throw new Error("TTL should be a number and should be at least 0");if(t.contentEncoding)if(t.contentEncoding===Jt.supportedContentEncodings.AES_128_GCM||t.contentEncoding===Jt.supportedContentEncodings.AES_GCM)a=t.contentEncoding;else throw new Error("Unsupported content encoding specified.");if(t.urgency)if(t.urgency===Jt.supportedUrgency.VERY_LOW||t.urgency===Jt.supportedUrgency.LOW||t.urgency===Jt.supportedUrgency.NORMAL||t.urgency===Jt.supportedUrgency.HIGH)c=t.urgency;else throw new Error("Unsupported urgency specified.");if(t.topic){if(!yF.validate(t.topic))throw new Error("Unsupported characters set use the URL or filename-safe Base64 characters set");if(t.topic.length>32)throw new Error("use maximum of 32 characters from the URL or filename-safe Base64 characters set");l=t.topic}t.proxy&&(typeof t.proxy=="string"||typeof t.proxy.host=="string"?p=t.proxy:console.warn("Attempt to use proxy option, but invalid type it should be a string or proxy options object.")),t.agent&&(t.agent instanceof tT.Agent?(p&&console.warn("Agent option will be ignored because proxy option is defined."),f=t.agent):console.warn("Wrong type for the agent option, it should be an instance of https.Agent.")),typeof t.timeout=="number"&&(h=t.timeout)}typeof s>"u"&&(s=Q1);let v={method:"POST",headers:{TTL:s}};Object.keys(o).forEach(function(k){v.headers[k]=o[k]});let x=null;if(e){let k=vF.encrypt(r.keys.p256dh,r.keys.auth,e,a);v.headers["Content-Length"]=k.cipherText.length,v.headers["Content-Type"]="application/octet-stream",a===Jt.supportedContentEncodings.AES_128_GCM?v.headers["Content-Encoding"]=Jt.supportedContentEncodings.AES_128_GCM:a===Jt.supportedContentEncodings.AES_GCM&&(v.headers["Content-Encoding"]=Jt.supportedContentEncodings.AES_GCM,v.headers.Encryption="salt="+k.salt,v.headers["Crypto-Key"]="dh="+k.localPublicKey.toString("base64url")),x=k.cipherText}else v.headers["Content-Length"]=0;let S=r.endpoint.startsWith("https://android.googleapis.com/gcm/send"),A=r.endpoint.startsWith("https://fcm.googleapis.com/fcm/send");if(S)n?v.headers.Authorization="key="+n:console.warn("Attempt to send push notification to GCM endpoint, but no GCM key is defined. Please use setGCMApiKey() or add 'gcmAPIKey' as an option.");else if(i){let k=eT.parse(r.endpoint),P=k.protocol+"//"+k.host,I=lu.getVapidHeaders(P,i.subject,i.publicKey,i.privateKey,a);v.headers.Authorization=I.Authorization,a===Jt.supportedContentEncodings.AES_GCM&&(v.headers["Crypto-Key"]?v.headers["Crypto-Key"]+=";"+I["Crypto-Key"]:v.headers["Crypto-Key"]=I["Crypto-Key"])}else A&&n&&(v.headers.Authorization="key="+n);return v.headers.Urgency=c,l&&(v.headers.Topic=l),v.body=x,v.endpoint=r.endpoint,p&&(v.proxy=p),f&&(v.agent=f),h&&(v.timeout=h),v};Qo.prototype.sendNotification=function(r,e,t){let n;try{n=this.generateRequestDetails(r,e,t)}catch(i){return Promise.reject(i)}return new Promise(function(i,s){let o={},a=eT.parse(n.endpoint);if(o.hostname=a.hostname,o.port=a.port,o.path=a.path,o.headers=n.headers,o.method=n.method,n.timeout&&(o.timeout=n.timeout),n.agent&&(o.agent=n.agent),n.proxy){let{HttpsProxyAgent:l}=Z1();o.agent=new l(n.proxy)}let c=tT.request(o,function(l){let p="";l.on("data",function(f){p+=f}),l.on("end",function(){l.statusCode<200||l.statusCode>299?s(new gF("Received unexpected response code",l.statusCode,l.headers,p,n.endpoint)):i({statusCode:l.statusCode,body:p,headers:l.headers})})});n.timeout&&c.on("timeout",function(){c.destroy(new Error("Socket timeout"))}),c.on("error",function(l){s(l)}),n.body&&c.write(n.body),c.end()})};rT.exports=Qo});var oT=R((HW,sT)=>{"use strict";var iT=sm(),xF=cm(),_F=nT(),bF=lm(),wF=ru(),ea=new _F;sT.exports={WebPushError:bF,supportedContentEncodings:wF.supportedContentEncodings,encrypt:xF.encrypt,getVapidHeaders:iT.getVapidHeaders,generateVAPIDKeys:iT.generateVAPIDKeys,setGCMAPIKey:ea.setGCMAPIKey,setVapidDetails:ea.setVapidDetails,generateRequestDetails:ea.generateRequestDetails,sendNotification:ea.sendNotification.bind(ea)}});var sa=R((xG,jT)=>{"use strict";var GF=require("path"),Gr="\\\\/",NT=`[^${Gr}]`,zF=0,yn="\\.",VF="\\+",KF="\\?",mu="\\/",YF="(?=.)",LT="[^/]",mm=`(?:${mu}|$)`,DT=`(?:^|${mu})`,gm=`${yn}{1,2}${mm}`,JF=`(?!${yn})`,XF=`(?!${DT}${gm})`,ZF=`(?!${yn}{0,1}${mm})`,QF=`(?!${gm})`,e3=`[^.${mu}]`,t3=`${LT}*?`,BT={DOT_LITERAL:yn,PLUS_LITERAL:VF,QMARK_LITERAL:KF,SLASH_LITERAL:mu,ONE_CHAR:YF,QMARK:LT,END_ANCHOR:mm,DOTS_SLASH:gm,NO_DOT:JF,NO_DOTS:XF,NO_DOT_SLASH:ZF,NO_DOTS_SLASH:QF,QMARK_NO_DOT:e3,STAR:t3,START_ANCHOR:DT},r3={...BT,SLASH_LITERAL:`[${Gr}]`,QMARK:NT,STAR:`${NT}*?`,DOTS_SLASH:`${yn}{1,2}(?:[${Gr}]|$)`,NO_DOT:`(?!${yn})`,NO_DOTS:`(?!(?:^|[${Gr}])${yn}{1,2}(?:[${Gr}]|$))`,NO_DOT_SLASH:`(?!${yn}{0,1}(?:[${Gr}]|$))`,NO_DOTS_SLASH:`(?!${yn}{1,2}(?:[${Gr}]|$))`,QMARK_NO_DOT:`[^.${Gr}]`,START_ANCHOR:`(?:^|[${Gr}])`,END_ANCHOR:`(?:[${Gr}]|$)`},n3={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};jT.exports={DEFAULT_MAX_EXTGLOB_RECURSION:zF,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:n3,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:GF.sep,extglobChars(r){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${r.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(r){return r===!0?r3:BT}}});var gu=R(Ut=>{"use strict";var i3=require("path"),s3=process.platform==="win32",{REGEX_BACKSLASH:o3,REGEX_REMOVE_BACKSLASH:a3,REGEX_SPECIAL_CHARS:c3,REGEX_SPECIAL_CHARS_GLOBAL:l3}=sa();Ut.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);Ut.hasRegexChars=r=>c3.test(r);Ut.isRegexChar=r=>r.length===1&&Ut.hasRegexChars(r);Ut.escapeRegex=r=>r.replace(l3,"\\$1");Ut.toPosixSlashes=r=>r.replace(o3,"/");Ut.removeBackslashes=r=>r.replace(a3,e=>e==="\\"?"":e);Ut.supportsLookbehinds=()=>{let r=process.version.slice(1).split(".").map(Number);return r.length===3&&r[0]>=9||r[0]===8&&r[1]>=10};Ut.isWindows=r=>r&&typeof r.windows=="boolean"?r.windows:s3===!0||i3.sep==="\\";Ut.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?Ut.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};Ut.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};Ut.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s}});var zT=R((bG,GT)=>{"use strict";var FT=gu(),{CHAR_ASTERISK:vm,CHAR_AT:u3,CHAR_BACKWARD_SLASH:oa,CHAR_COMMA:p3,CHAR_DOT:ym,CHAR_EXCLAMATION_MARK:xm,CHAR_FORWARD_SLASH:WT,CHAR_LEFT_CURLY_BRACE:_m,CHAR_LEFT_PARENTHESES:bm,CHAR_LEFT_SQUARE_BRACKET:f3,CHAR_PLUS:d3,CHAR_QUESTION_MARK:UT,CHAR_RIGHT_CURLY_BRACE:h3,CHAR_RIGHT_PARENTHESES:qT,CHAR_RIGHT_SQUARE_BRACKET:m3}=sa(),HT=r=>r===WT||r===oa,$T=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},g3=(r,e)=>{let t=e||{},n=r.length-1,i=t.parts===!0||t.scanToEnd===!0,s=[],o=[],a=[],c=r,l=-1,p=0,f=0,h=!1,v=!1,x=!1,S=!1,A=!1,k=!1,P=!1,I=!1,B=!1,V=!1,F=0,G,L,H={value:"",depth:0,isGlob:!1},T=()=>l>=n,u=()=>c.charCodeAt(l+1),m=()=>(G=L,c.charCodeAt(++l));for(;l<n;){L=m();let C;if(L===oa){P=H.backslashes=!0,L=m(),L===_m&&(k=!0);continue}if(k===!0||L===_m){for(F++;T()!==!0&&(L=m());){if(L===oa){P=H.backslashes=!0,m();continue}if(L===_m){F++;continue}if(k!==!0&&L===ym&&(L=m())===ym){if(h=H.isBrace=!0,x=H.isGlob=!0,V=!0,i===!0)continue;break}if(k!==!0&&L===p3){if(h=H.isBrace=!0,x=H.isGlob=!0,V=!0,i===!0)continue;break}if(L===h3&&(F--,F===0)){k=!1,h=H.isBrace=!0,V=!0;break}}if(i===!0)continue;break}if(L===WT){if(s.push(l),o.push(H),H={value:"",depth:0,isGlob:!1},V===!0)continue;if(G===ym&&l===p+1){p+=2;continue}f=l+1;continue}if(t.noext!==!0&&(L===d3||L===u3||L===vm||L===UT||L===xm)===!0&&u()===bm){if(x=H.isGlob=!0,S=H.isExtglob=!0,V=!0,L===xm&&l===p&&(B=!0),i===!0){for(;T()!==!0&&(L=m());){if(L===oa){P=H.backslashes=!0,L=m();continue}if(L===qT){x=H.isGlob=!0,V=!0;break}}continue}break}if(L===vm){if(G===vm&&(A=H.isGlobstar=!0),x=H.isGlob=!0,V=!0,i===!0)continue;break}if(L===UT){if(x=H.isGlob=!0,V=!0,i===!0)continue;break}if(L===f3){for(;T()!==!0&&(C=m());){if(C===oa){P=H.backslashes=!0,m();continue}if(C===m3){v=H.isBracket=!0,x=H.isGlob=!0,V=!0;break}}if(i===!0)continue;break}if(t.nonegate!==!0&&L===xm&&l===p){I=H.negated=!0,p++;continue}if(t.noparen!==!0&&L===bm){if(x=H.isGlob=!0,i===!0){for(;T()!==!0&&(L=m());){if(L===bm){P=H.backslashes=!0,L=m();continue}if(L===qT){V=!0;break}}continue}break}if(x===!0){if(V=!0,i===!0)continue;break}}t.noext===!0&&(S=!1,x=!1);let y=c,w="",g="";p>0&&(w=c.slice(0,p),c=c.slice(p),f-=p),y&&x===!0&&f>0?(y=c.slice(0,f),g=c.slice(f)):x===!0?(y="",g=c):y=c,y&&y!==""&&y!=="/"&&y!==c&&HT(y.charCodeAt(y.length-1))&&(y=y.slice(0,-1)),t.unescape===!0&&(g&&(g=FT.removeBackslashes(g)),y&&P===!0&&(y=FT.removeBackslashes(y)));let _={prefix:w,input:r,start:p,base:y,glob:g,isBrace:h,isBracket:v,isGlob:x,isExtglob:S,isGlobstar:A,negated:I,negatedExtglob:B};if(t.tokens===!0&&(_.maxDepth=0,HT(L)||o.push(H),_.tokens=o),t.parts===!0||t.tokens===!0){let C;for(let b=0;b<s.length;b++){let d=C?C+1:p,E=s[b],q=r.slice(d,E);t.tokens&&(b===0&&p!==0?(o[b].isPrefix=!0,o[b].value=w):o[b].value=q,$T(o[b]),_.maxDepth+=o[b].depth),(b!==0||q!=="")&&a.push(q),C=E}if(C&&C+1<r.length){let b=r.slice(C+1);a.push(b),t.tokens&&(o[o.length-1].value=b,$T(o[o.length-1]),_.maxDepth+=o[o.length-1].depth)}_.slashes=s,_.parts=a}return _};GT.exports=g3});var XT=R((wG,JT)=>{"use strict";var aa=sa(),St=gu(),{MAX_LENGTH:vu,POSIX_REGEX_SOURCE:v3,REGEX_NON_SPECIAL_CHARS:y3,REGEX_SPECIAL_CHARS_BACKREF:x3,REPLACEMENTS:VT}=aa,_3=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch{return r.map(i=>St.escapeRegex(i)).join("..")}return t},Us=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,KT=r=>{let e=[],t=0,n=0,i=0,s="",o=!1;for(let a of r){if(o===!0){s+=a,o=!1;continue}if(a==="\\"){s+=a,o=!0;continue}if(a==='"'){i=i===1?0:1,s+=a;continue}if(i===0){if(a==="[")t++;else if(a==="]"&&t>0)t--;else if(t===0){if(a==="(")n++;else if(a===")"&&n>0)n--;else if(a==="|"&&n===0){e.push(s),s="";continue}}}s+=a}return e.push(s),e},b3=r=>{let e=!1;for(let t of r){if(e===!0){e=!1;continue}if(t==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(t))return!1}return!0},YT=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(b3(e))return e.replace(/\\(.)/g,"$1")},w3=r=>{let e=r.map(YT).filter(Boolean);for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++){let i=e[t],s=e[n],o=i[0];if(!(!o||i!==o.repeat(i.length)||s!==o.repeat(s.length))&&(i===s||i.startsWith(s)||s.startsWith(i)))return!0}return!1},wm=(r,e=!0)=>{if(r[0]!=="+"&&r[0]!=="*"||r[1]!=="(")return;let t=0,n=0,i=0,s=!1;for(let o=1;o<r.length;o++){let a=r[o];if(s===!0){s=!1;continue}if(a==="\\"){s=!0;continue}if(a==='"'){i=i===1?0:1;continue}if(i!==1){if(a==="["){t++;continue}if(a==="]"&&t>0){t--;continue}if(!(t>0)){if(a==="("){n++;continue}if(a===")"&&(n--,n===0))return e===!0&&o!==r.length-1?void 0:{type:r[0],body:r.slice(2,o),end:o}}}}},S3=r=>{let e=0,t=[];for(;e<r.length;){let i=wm(r.slice(e),!1);if(!i||i.type!=="*")return;let s=KT(i.body).map(a=>a.trim());if(s.length!==1)return;let o=YT(s[0]);if(!o||o.length!==1)return;t.push(o),e+=i.end+1}return t.length<1?void 0:`${t.length===1?St.escapeRegex(t[0]):`[${t.map(i=>St.escapeRegex(i)).join("")}]`}*`},E3=r=>{let e=0,t=r.trim(),n=wm(t);for(;n;)e++,t=n.body.trim(),n=wm(t);return e},T3=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:aa.DEFAULT_MAX_EXTGLOB_RECURSION,n=KT(r).map(i=>i.trim());if(n.length>1&&(n.some(i=>i==="")||n.some(i=>/^[*?]+$/.test(i))||w3(n)))return{risky:!0};for(let i of n){let s=S3(i);if(s)return{risky:!0,safeOutput:s};if(E3(i)>t)return{risky:!0}}return{risky:!1}},Sm=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=VT[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(vu,t.maxLength):vu,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);let s={type:"bos",value:"",output:t.prepend||""},o=[s],a=t.capture?"":"?:",c=St.isWindows(e),l=aa.globChars(c),p=aa.extglobChars(l),{DOT_LITERAL:f,PLUS_LITERAL:h,SLASH_LITERAL:v,ONE_CHAR:x,DOTS_SLASH:S,NO_DOT:A,NO_DOT_SLASH:k,NO_DOTS_SLASH:P,QMARK:I,QMARK_NO_DOT:B,STAR:V,START_ANCHOR:F}=l,G=N=>`(${a}(?:(?!${F}${N.dot?S:f}).)*?)`,L=t.dot?"":A,H=t.dot?I:B,T=t.bash===!0?G(t):V;t.capture&&(T=`(${T})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let u={input:r,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};r=St.removePrefix(r,u),i=r.length;let m=[],y=[],w=[],g=s,_,C=()=>u.index===i-1,b=u.peek=(N=1)=>r[u.index+N],d=u.advance=()=>r[++u.index]||"",E=()=>r.slice(u.index+1),q=(N="",te=0)=>{u.consumed+=N,u.index+=te},O=N=>{u.output+=N.output!=null?N.output:N.value,q(N.value)},M=()=>{let N=1;for(;b()==="!"&&(b(2)!=="("||b(3)==="?");)d(),u.start++,N++;return N%2===0?!1:(u.negated=!0,u.start++,!0)},j=N=>{u[N]++,w.push(N)},z=N=>{u[N]--,w.pop()},U=N=>{if(g.type==="globstar"){let te=u.braces>0&&(N.type==="comma"||N.type==="brace"),D=N.extglob===!0||m.length&&(N.type==="pipe"||N.type==="paren");N.type!=="slash"&&N.type!=="paren"&&!te&&!D&&(u.output=u.output.slice(0,-g.output.length),g.type="star",g.value="*",g.output=T,u.output+=g.output)}if(m.length&&N.type!=="paren"&&(m[m.length-1].inner+=N.value),(N.value||N.output)&&O(N),g&&g.type==="text"&&N.type==="text"){g.value+=N.value,g.output=(g.output||"")+N.value;return}N.prev=g,o.push(N),g=N},Te=(N,te)=>{let D={...p[te],conditions:1,inner:""};D.prev=g,D.parens=u.parens,D.output=u.output,D.startIndex=u.index,D.tokensIndex=o.length;let W=(t.capture?"(":"")+D.open;j("parens"),U({type:N,value:te,output:u.output?"":x}),U({type:"paren",extglob:!0,value:d(),output:W}),m.push(D)},ne=N=>{let te=r.slice(N.startIndex,u.index+1),D=r.slice(N.startIndex+2,u.index),W=T3(D,t);if((N.type==="plus"||N.type==="star")&&W.risky){let J=W.safeOutput?(N.output?"":x)+(t.capture?`(${W.safeOutput})`:W.safeOutput):void 0,Tt=o[N.tokensIndex];Tt.type="text",Tt.value=te,Tt.output=J||St.escapeRegex(te);for(let oe=N.tokensIndex+1;oe<o.length;oe++)o[oe].value="",o[oe].output="",delete o[oe].suffix;u.output=N.output+Tt.output,u.backtrack=!0,U({type:"paren",extglob:!0,value:_,output:""}),z("parens");return}let se=N.close+(t.capture?")":""),Z;if(N.type==="negate"){let J=T;if(N.inner&&N.inner.length>1&&N.inner.includes("/")&&(J=G(t)),(J!==T||C()||/^\)+$/.test(E()))&&(se=N.close=`)$))${J}`),N.inner.includes("*")&&(Z=E())&&/^\.[^\\/.]+$/.test(Z)){let Tt=Sm(Z,{...e,fastpaths:!1}).output;se=N.close=`)${Tt})${J})`}N.prev.type==="bos"&&(u.negatedExtglob=!0)}U({type:"paren",extglob:!0,value:_,output:se}),z("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let N=!1,te=r.replace(x3,(D,W,se,Z,J,Tt)=>Z==="\\"?(N=!0,D):Z==="?"?W?W+Z+(J?I.repeat(J.length):""):Tt===0?H+(J?I.repeat(J.length):""):I.repeat(se.length):Z==="."?f.repeat(se.length):Z==="*"?W?W+Z+(J?T:""):T:W?D:`\\${D}`);return N===!0&&(t.unescape===!0?te=te.replace(/\\/g,""):te=te.replace(/\\+/g,D=>D.length%2===0?"\\\\":D?"\\":"")),te===r&&t.contains===!0?(u.output=r,u):(u.output=St.wrapOutput(te,u,e),u)}for(;!C();){if(_=d(),_==="\0")continue;if(_==="\\"){let D=b();if(D==="/"&&t.bash!==!0||D==="."||D===";")continue;if(!D){_+="\\",U({type:"text",value:_});continue}let W=/^\\+/.exec(E()),se=0;if(W&&W[0].length>2&&(se=W[0].length,u.index+=se,se%2!==0&&(_+="\\")),t.unescape===!0?_=d():_+=d(),u.brackets===0){U({type:"text",value:_});continue}}if(u.brackets>0&&(_!=="]"||g.value==="["||g.value==="[^")){if(t.posix!==!1&&_===":"){let D=g.value.slice(1);if(D.includes("[")&&(g.posix=!0,D.includes(":"))){let W=g.value.lastIndexOf("["),se=g.value.slice(0,W),Z=g.value.slice(W+2),J=v3[Z];if(J){g.value=se+J,u.backtrack=!0,d(),!s.output&&o.indexOf(g)===1&&(s.output=x);continue}}}(_==="["&&b()!==":"||_==="-"&&b()==="]")&&(_=`\\${_}`),_==="]"&&(g.value==="["||g.value==="[^")&&(_=`\\${_}`),t.posix===!0&&_==="!"&&g.value==="["&&(_="^"),g.value+=_,O({value:_});continue}if(u.quotes===1&&_!=='"'){_=St.escapeRegex(_),g.value+=_,O({value:_});continue}if(_==='"'){u.quotes=u.quotes===1?0:1,t.keepQuotes===!0&&U({type:"text",value:_});continue}if(_==="("){j("parens"),U({type:"paren",value:_});continue}if(_===")"){if(u.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Us("opening","("));let D=m[m.length-1];if(D&&u.parens===D.parens+1){ne(m.pop());continue}U({type:"paren",value:_,output:u.parens?")":"\\)"}),z("parens");continue}if(_==="["){if(t.nobracket===!0||!E().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Us("closing","]"));_=`\\${_}`}else j("brackets");U({type:"bracket",value:_});continue}if(_==="]"){if(t.nobracket===!0||g&&g.type==="bracket"&&g.value.length===1){U({type:"text",value:_,output:`\\${_}`});continue}if(u.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Us("opening","["));U({type:"text",value:_,output:`\\${_}`});continue}z("brackets");let D=g.value.slice(1);if(g.posix!==!0&&D[0]==="^"&&!D.includes("/")&&(_=`/${_}`),g.value+=_,O({value:_}),t.literalBrackets===!1||St.hasRegexChars(D))continue;let W=St.escapeRegex(g.value);if(u.output=u.output.slice(0,-g.value.length),t.literalBrackets===!0){u.output+=W,g.value=W;continue}g.value=`(${a}${W}|${g.value})`,u.output+=g.value;continue}if(_==="{"&&t.nobrace!==!0){j("braces");let D={type:"brace",value:_,output:"(",outputIndex:u.output.length,tokensIndex:u.tokens.length};y.push(D),U(D);continue}if(_==="}"){let D=y[y.length-1];if(t.nobrace===!0||!D){U({type:"text",value:_,output:_});continue}let W=")";if(D.dots===!0){let se=o.slice(),Z=[];for(let J=se.length-1;J>=0&&(o.pop(),se[J].type!=="brace");J--)se[J].type!=="dots"&&Z.unshift(se[J].value);W=_3(Z,t),u.backtrack=!0}if(D.comma!==!0&&D.dots!==!0){let se=u.output.slice(0,D.outputIndex),Z=u.tokens.slice(D.tokensIndex);D.value=D.output="\\{",_=W="\\}",u.output=se;for(let J of Z)u.output+=J.output||J.value}U({type:"brace",value:_,output:W}),z("braces"),y.pop();continue}if(_==="|"){m.length>0&&m[m.length-1].conditions++,U({type:"text",value:_});continue}if(_===","){let D=_,W=y[y.length-1];W&&w[w.length-1]==="braces"&&(W.comma=!0,D="|"),U({type:"comma",value:_,output:D});continue}if(_==="/"){if(g.type==="dot"&&u.index===u.start+1){u.start=u.index+1,u.consumed="",u.output="",o.pop(),g=s;continue}U({type:"slash",value:_,output:v});continue}if(_==="."){if(u.braces>0&&g.type==="dot"){g.value==="."&&(g.output=f);let D=y[y.length-1];g.type="dots",g.output+=_,g.value+=_,D.dots=!0;continue}if(u.braces+u.parens===0&&g.type!=="bos"&&g.type!=="slash"){U({type:"text",value:_,output:f});continue}U({type:"dot",value:_,output:f});continue}if(_==="?"){if(!(g&&g.value==="(")&&t.noextglob!==!0&&b()==="("&&b(2)!=="?"){Te("qmark",_);continue}if(g&&g.type==="paren"){let W=b(),se=_;if(W==="<"&&!St.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(g.value==="("&&!/[!=<:]/.test(W)||W==="<"&&!/<([!=]|\w+>)/.test(E()))&&(se=`\\${_}`),U({type:"text",value:_,output:se});continue}if(t.dot!==!0&&(g.type==="slash"||g.type==="bos")){U({type:"qmark",value:_,output:B});continue}U({type:"qmark",value:_,output:I});continue}if(_==="!"){if(t.noextglob!==!0&&b()==="("&&(b(2)!=="?"||!/[!=<:]/.test(b(3)))){Te("negate",_);continue}if(t.nonegate!==!0&&u.index===0){M();continue}}if(_==="+"){if(t.noextglob!==!0&&b()==="("&&b(2)!=="?"){Te("plus",_);continue}if(g&&g.value==="("||t.regex===!1){U({type:"plus",value:_,output:h});continue}if(g&&(g.type==="bracket"||g.type==="paren"||g.type==="brace")||u.parens>0){U({type:"plus",value:_});continue}U({type:"plus",value:h});continue}if(_==="@"){if(t.noextglob!==!0&&b()==="("&&b(2)!=="?"){U({type:"at",extglob:!0,value:_,output:""});continue}U({type:"text",value:_});continue}if(_!=="*"){(_==="$"||_==="^")&&(_=`\\${_}`);let D=y3.exec(E());D&&(_+=D[0],u.index+=D[0].length),U({type:"text",value:_});continue}if(g&&(g.type==="globstar"||g.star===!0)){g.type="star",g.star=!0,g.value+=_,g.output=T,u.backtrack=!0,u.globstar=!0,q(_);continue}let N=E();if(t.noextglob!==!0&&/^\([^?]/.test(N)){Te("star",_);continue}if(g.type==="star"){if(t.noglobstar===!0){q(_);continue}let D=g.prev,W=D.prev,se=D.type==="slash"||D.type==="bos",Z=W&&(W.type==="star"||W.type==="globstar");if(t.bash===!0&&(!se||N[0]&&N[0]!=="/")){U({type:"star",value:_,output:""});continue}let J=u.braces>0&&(D.type==="comma"||D.type==="brace"),Tt=m.length&&(D.type==="pipe"||D.type==="paren");if(!se&&D.type!=="paren"&&!J&&!Tt){U({type:"star",value:_,output:""});continue}for(;N.slice(0,3)==="/**";){let oe=r[u.index+4];if(oe&&oe!=="/")break;N=N.slice(3),q("/**",3)}if(D.type==="bos"&&C()){g.type="globstar",g.value+=_,g.output=G(t),u.output=g.output,u.globstar=!0,q(_);continue}if(D.type==="slash"&&D.prev.type!=="bos"&&!Z&&C()){u.output=u.output.slice(0,-(D.output+g.output).length),D.output=`(?:${D.output}`,g.type="globstar",g.output=G(t)+(t.strictSlashes?")":"|$)"),g.value+=_,u.globstar=!0,u.output+=D.output+g.output,q(_);continue}if(D.type==="slash"&&D.prev.type!=="bos"&&N[0]==="/"){let oe=N[1]!==void 0?"|$":"";u.output=u.output.slice(0,-(D.output+g.output).length),D.output=`(?:${D.output}`,g.type="globstar",g.output=`${G(t)}${v}|${v}${oe})`,g.value+=_,u.output+=D.output+g.output,u.globstar=!0,q(_+d()),U({type:"slash",value:"/",output:""});continue}if(D.type==="bos"&&N[0]==="/"){g.type="globstar",g.value+=_,g.output=`(?:^|${v}|${G(t)}${v})`,u.output=g.output,u.globstar=!0,q(_+d()),U({type:"slash",value:"/",output:""});continue}u.output=u.output.slice(0,-g.output.length),g.type="globstar",g.output=G(t),g.value+=_,u.output+=g.output,u.globstar=!0,q(_);continue}let te={type:"star",value:_,output:T};if(t.bash===!0){te.output=".*?",(g.type==="bos"||g.type==="slash")&&(te.output=L+te.output),U(te);continue}if(g&&(g.type==="bracket"||g.type==="paren")&&t.regex===!0){te.output=_,U(te);continue}(u.index===u.start||g.type==="slash"||g.type==="dot")&&(g.type==="dot"?(u.output+=k,g.output+=k):t.dot===!0?(u.output+=P,g.output+=P):(u.output+=L,g.output+=L),b()!=="*"&&(u.output+=x,g.output+=x)),U(te)}for(;u.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Us("closing","]"));u.output=St.escapeLast(u.output,"["),z("brackets")}for(;u.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Us("closing",")"));u.output=St.escapeLast(u.output,"("),z("parens")}for(;u.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Us("closing","}"));u.output=St.escapeLast(u.output,"{"),z("braces")}if(t.strictSlashes!==!0&&(g.type==="star"||g.type==="bracket")&&U({type:"maybe_slash",value:"",output:`${v}?`}),u.backtrack===!0){u.output="";for(let N of u.tokens)u.output+=N.output!=null?N.output:N.value,N.suffix&&(u.output+=N.suffix)}return u};Sm.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(vu,t.maxLength):vu,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=VT[r]||r;let s=St.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:c,DOTS_SLASH:l,NO_DOT:p,NO_DOTS:f,NO_DOTS_SLASH:h,STAR:v,START_ANCHOR:x}=aa.globChars(s),S=t.dot?f:p,A=t.dot?h:p,k=t.capture?"":"?:",P={negated:!1,prefix:""},I=t.bash===!0?".*?":v;t.capture&&(I=`(${I})`);let B=L=>L.noglobstar===!0?I:`(${k}(?:(?!${x}${L.dot?l:o}).)*?)`,V=L=>{switch(L){case"*":return`${S}${c}${I}`;case".*":return`${o}${c}${I}`;case"*.*":return`${S}${I}${o}${c}${I}`;case"*/*":return`${S}${I}${a}${c}${A}${I}`;case"**":return S+B(t);case"**/*":return`(?:${S}${B(t)}${a})?${A}${c}${I}`;case"**/*.*":return`(?:${S}${B(t)}${a})?${A}${I}${o}${c}${I}`;case"**/.*":return`(?:${S}${B(t)}${a})?${o}${c}${I}`;default:{let H=/^(.*?)\.(\w+)$/.exec(L);if(!H)return;let T=V(H[1]);return T?T+o+H[2]:void 0}}},F=St.removePrefix(r,P),G=V(F);return G&&t.strictSlashes!==!0&&(G+=`${a}?`),G};JT.exports=Sm});var QT=R((SG,ZT)=>{"use strict";var C3=require("path"),A3=zT(),Em=XT(),Tm=gu(),R3=sa(),k3=r=>r&&typeof r=="object"&&!Array.isArray(r),ke=(r,e,t=!1)=>{if(Array.isArray(r)){let p=r.map(h=>ke(h,e,t));return h=>{for(let v of p){let x=v(h);if(x)return x}return!1}}let n=k3(r)&&r.tokens&&r.input;if(r===""||typeof r!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=Tm.isWindows(e),o=n?ke.compileRe(r,e):ke.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let p={...e,ignore:null,onMatch:null,onResult:null};c=ke(i.ignore,p,t)}let l=(p,f=!1)=>{let{isMatch:h,match:v,output:x}=ke.test(p,o,e,{glob:r,posix:s}),S={glob:r,state:a,regex:o,posix:s,input:p,output:x,match:v,isMatch:h};return typeof i.onResult=="function"&&i.onResult(S),h===!1?(S.isMatch=!1,f?S:!1):c(p)?(typeof i.onIgnore=="function"&&i.onIgnore(S),S.isMatch=!1,f?S:!1):(typeof i.onMatch=="function"&&i.onMatch(S),f?S:!0)};return t&&(l.state=a),l};ke.test=(r,e,t,{glob:n,posix:i}={})=>{if(typeof r!="string")throw new TypeError("Expected input to be a string");if(r==="")return{isMatch:!1,output:""};let s=t||{},o=s.format||(i?Tm.toPosixSlashes:null),a=r===n,c=a&&o?o(r):r;return a===!1&&(c=o?o(r):r,a=c===n),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=ke.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};ke.matchBase=(r,e,t,n=Tm.isWindows(t))=>(e instanceof RegExp?e:ke.makeRe(e,t)).test(C3.basename(r));ke.isMatch=(r,e,t)=>ke(e,t)(r);ke.parse=(r,e)=>Array.isArray(r)?r.map(t=>ke.parse(t,e)):Em(r,{...e,fastpaths:!1});ke.scan=(r,e)=>A3(r,e);ke.compileRe=(r,e,t=!1,n=!1)=>{if(t===!0)return r.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${r.output})${o}`;r&&r.negated===!0&&(a=`^(?!${a}).*$`);let c=ke.toRegex(a,e);return n===!0&&(c.state=r),c};ke.makeRe=(r,e={},t=!1,n=!1)=>{if(!r||typeof r!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(r[0]==="."||r[0]==="*")&&(i.output=Em.fastpaths(r,e)),i.output||(i=Em(r,e)),ke.compileRe(i,e,t,n)};ke.toRegex=(r,e)=>{try{let t=e||{};return new RegExp(r,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};ke.constants=R3;ZT.exports=ke});var Cm=R((EG,eC)=>{"use strict";eC.exports=QT()});var cC=R((TG,aC)=>{"use strict";var la=require("fs"),{Readable:O3}=require("stream"),ca=require("path"),{promisify:bu}=require("util"),Am=Cm(),M3=bu(la.readdir),P3=bu(la.stat),tC=bu(la.lstat),I3=bu(la.realpath),N3="!",sC="READDIRP_RECURSIVE_ERROR",L3=new Set(["ENOENT","EPERM","EACCES","ELOOP",sC]),Rm="files",oC="directories",xu="files_directories",yu="all",rC=[Rm,oC,xu,yu],D3=r=>L3.has(r.code),[nC,B3]=process.versions.node.split(".").slice(0,2).map(r=>Number.parseInt(r,10)),j3=process.platform==="win32"&&(nC>10||nC===10&&B3>=5),iC=r=>{if(r!==void 0){if(typeof r=="function")return r;if(typeof r=="string"){let e=Am(r.trim());return t=>e(t.basename)}if(Array.isArray(r)){let e=[],t=[];for(let n of r){let i=n.trim();i.charAt(0)===N3?t.push(Am(i.slice(1))):e.push(Am(i))}return t.length>0?e.length>0?n=>e.some(i=>i(n.basename))&&!t.some(i=>i(n.basename)):n=>!t.some(i=>i(n.basename)):n=>e.some(i=>i(n.basename))}}},_u=class r extends O3{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:Rm,lstat:!1,depth:2147483648,alwaysStat:!1}}constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark||4096});let t={...r.defaultOptions,...e},{root:n,type:i}=t;this._fileFilter=iC(t.fileFilter),this._directoryFilter=iC(t.directoryFilter);let s=t.lstat?tC:P3;j3?this._stat=o=>s(o,{bigint:!0}):this._stat=s,this._maxDepth=t.depth,this._wantsDir=[oC,xu,yu].includes(i),this._wantsFile=[Rm,xu,yu].includes(i),this._wantsEverything=i===yu,this._root=ca.resolve(n),this._isDirent="Dirent"in la&&!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let{path:t,depth:n,files:i=[]}=this.parent||{};if(i.length>0){let s=i.splice(0,e).map(o=>this._formatEntry(o,t));for(let o of await Promise.all(s)){if(this.destroyed)return;let a=await this._getEntryType(o);a==="directory"&&this._directoryFilter(o)?(n<=this._maxDepth&&this.parents.push(this._exploreDir(o.fullPath,n+1)),this._wantsDir&&(this.push(o),e--)):(a==="file"||this._includeAsFile(o))&&this._fileFilter(o)&&this._wantsFile&&(this.push(o),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}if(this.parent=await s,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await M3(e,this._rdOptions)}catch(i){this._onError(i)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n;try{let i=this._isDirent?e.name:e,s=ca.resolve(ca.join(t,i));n={path:ca.relative(this._root,s),fullPath:s,basename:i},n[this._statsProp]=this._isDirent?e:await this._stat(s)}catch(i){this._onError(i)}return n}_onError(e){D3(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){let t=e&&e[this._statsProp];if(t){if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let n=e.fullPath;try{let i=await I3(n),s=await tC(i);if(s.isFile())return"file";if(s.isDirectory()){let o=i.length;if(n.startsWith(i)&&n.substr(o,1)===ca.sep){let a=new Error(`Circular symlink detected: "${n}" points to "${i}"`);return a.code=sC,this._onError(a)}return"directory"}}catch(i){this._onError(i)}}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}},qs=(r,e={})=>{let t=e.entryType||e.type;if(t==="both"&&(t=xu),t&&(e.type=t),r){if(typeof r!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!rC.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${rC.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new _u(e)},F3=(r,e={})=>new Promise((t,n)=>{let i=[];qs(r,e).on("data",s=>i.push(s)).on("end",()=>t(i)).on("error",s=>n(s))});qs.promise=F3;qs.ReaddirpStream=_u;qs.default=qs;aC.exports=qs});var km=R((CG,lC)=>{lC.exports=function(r,e){if(typeof r!="string")throw new TypeError("expected path to be a string");if(r==="\\"||r==="/")return"/";var t=r.length;if(t<=1)return r;var n="";if(t>4&&r[3]==="\\"){var i=r[2];(i==="?"||i===".")&&r.slice(0,2)==="\\\\"&&(r=r.slice(2),n="//")}var s=r.split(/[/\\]+/);return e!==!1&&s[s.length-1]===""&&s.pop(),n+s.join("/")}});var mC=R((dC,hC)=>{"use strict";Object.defineProperty(dC,"__esModule",{value:!0});var fC=Cm(),U3=km(),uC="!",q3={returnIndex:!1},H3=r=>Array.isArray(r)?r:[r],$3=(r,e)=>{if(typeof r=="function")return r;if(typeof r=="string"){let t=fC(r,e);return n=>r===n||t(n)}return r instanceof RegExp?t=>r.test(t):t=>!1},pC=(r,e,t,n)=>{let i=Array.isArray(t),s=i?t[0]:t;if(!i&&typeof s!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(s));let o=U3(s,!1);for(let c=0;c<e.length;c++){let l=e[c];if(l(o))return n?-1:!1}let a=i&&[o].concat(t.slice(1));for(let c=0;c<r.length;c++){let l=r[c];if(i?l(...a):l(o))return n?c:!0}return n?-1:!1},Om=(r,e,t=q3)=>{if(r==null)throw new TypeError("anymatch: specify first argument");let n=typeof t=="boolean"?{returnIndex:t}:t,i=n.returnIndex||!1,s=H3(r),o=s.filter(c=>typeof c=="string"&&c.charAt(0)===uC).map(c=>c.slice(1)).map(c=>fC(c,n)),a=s.filter(c=>typeof c!="string"||typeof c=="string"&&c.charAt(0)!==uC).map(c=>$3(c,n));return e==null?(c,l=!1)=>pC(a,o,c,typeof l=="boolean"?l:!1):pC(a,o,e,i)};Om.default=Om;hC.exports=Om});var vC=R((AG,gC)=>{gC.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var t;t=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(t[2])return!0;e=e.slice(t.index+t[0].length)}return!1}});var Mm=R((RG,xC)=>{var W3=vC(),yC={"{":"}","(":")","[":"]"},G3=function(r){if(r[0]==="!")return!0;for(var e=0,t=-2,n=-2,i=-2,s=-2,o=-2;e<r.length;){if(r[e]==="*"||r[e+1]==="?"&&/[\].+)]/.test(r[e])||n!==-1&&r[e]==="["&&r[e+1]!=="]"&&(n<e&&(n=r.indexOf("]",e)),n>e&&(o===-1||o>n||(o=r.indexOf("\\",e),o===-1||o>n)))||i!==-1&&r[e]==="{"&&r[e+1]!=="}"&&(i=r.indexOf("}",e),i>e&&(o=r.indexOf("\\",e),o===-1||o>i))||s!==-1&&r[e]==="("&&r[e+1]==="?"&&/[:!=]/.test(r[e+2])&&r[e+3]!==")"&&(s=r.indexOf(")",e),s>e&&(o=r.indexOf("\\",e),o===-1||o>s))||t!==-1&&r[e]==="("&&r[e+1]!=="|"&&(t<e&&(t=r.indexOf("|",e)),t!==-1&&r[t+1]!==")"&&(s=r.indexOf(")",t),s>t&&(o=r.indexOf("\\",t),o===-1||o>s))))return!0;if(r[e]==="\\"){var a=r[e+1];e+=2;var c=yC[a];if(c){var l=r.indexOf(c,e);l!==-1&&(e=l+1)}if(r[e]==="!")return!0}else e++}return!1},z3=function(r){if(r[0]==="!")return!0;for(var e=0;e<r.length;){if(/[*?{}()[\]]/.test(r[e]))return!0;if(r[e]==="\\"){var t=r[e+1];e+=2;var n=yC[t];if(n){var i=r.indexOf(n,e);i!==-1&&(e=i+1)}if(r[e]==="!")return!0}else e++}return!1};xC.exports=function(e,t){if(typeof e!="string"||e==="")return!1;if(W3(e))return!0;var n=G3;return t&&t.strict===!1&&(n=z3),n(e)}});var bC=R((kG,_C)=>{"use strict";var V3=Mm(),K3=require("path").posix.dirname,Y3=require("os").platform()==="win32",Pm="/",J3=/\\/g,X3=/[\{\[].*[\}\]]$/,Z3=/(^|[^\\])([\{\[]|\([^\)]+$)/,Q3=/\\([\!\*\?\|\[\]\(\)\{\}])/g;_C.exports=function(e,t){var n=Object.assign({flipBackslashes:!0},t);n.flipBackslashes&&Y3&&e.indexOf(Pm)<0&&(e=e.replace(J3,Pm)),X3.test(e)&&(e+=Pm),e+="a";do e=K3(e);while(V3(e)||Z3.test(e));return e.replace(Q3,"$1")}});var wu=R(mr=>{"use strict";mr.isInteger=r=>typeof r=="number"?Number.isInteger(r):typeof r=="string"&&r.trim()!==""?Number.isInteger(Number(r)):!1;mr.find=(r,e)=>r.nodes.find(t=>t.type===e);mr.exceedsLimit=(r,e,t=1,n)=>n===!1||!mr.isInteger(r)||!mr.isInteger(e)?!1:(Number(e)-Number(r))/Number(t)>=n;mr.escapeNode=(r,e=0,t)=>{let n=r.nodes[e];n&&(t&&n.type===t||n.type==="open"||n.type==="close")&&n.escaped!==!0&&(n.value="\\"+n.value,n.escaped=!0)};mr.encloseBrace=r=>r.type!=="brace"?!1:r.commas>>0+r.ranges>>0===0?(r.invalid=!0,!0):!1;mr.isInvalidBrace=r=>r.type!=="brace"?!1:r.invalid===!0||r.dollar?!0:r.commas>>0+r.ranges>>0===0||r.open!==!0||r.close!==!0?(r.invalid=!0,!0):!1;mr.isOpenOrClose=r=>r.type==="open"||r.type==="close"?!0:r.open===!0||r.close===!0;mr.reduce=r=>r.reduce((e,t)=>(t.type==="text"&&e.push(t.value),t.type==="range"&&(t.type="text"),e),[]);mr.flatten=(...r)=>{let e=[],t=n=>{for(let i=0;i<n.length;i++){let s=n[i];if(Array.isArray(s)){t(s);continue}s!==void 0&&e.push(s)}return e};return t(r),e}});var Su=R((MG,SC)=>{"use strict";var wC=wu();SC.exports=(r,e={})=>{let t=(n,i={})=>{let s=e.escapeInvalid&&wC.isInvalidBrace(i),o=n.invalid===!0&&e.escapeInvalid===!0,a="";if(n.value)return(s||o)&&wC.isOpenOrClose(n)?"\\"+n.value:n.value;if(n.value)return n.value;if(n.nodes)for(let c of n.nodes)a+=t(c);return a};return t(r)}});var TC=R((PG,EC)=>{"use strict";EC.exports=function(r){return typeof r=="number"?r-r===0:typeof r=="string"&&r.trim()!==""?Number.isFinite?Number.isFinite(+r):isFinite(+r):!1}});var NC=R((IG,IC)=>{"use strict";var CC=TC(),xi=(r,e,t)=>{if(CC(r)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||r===e)return String(r);if(CC(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let n={relaxZeros:!0,...t};typeof n.strictZeros=="boolean"&&(n.relaxZeros=n.strictZeros===!1);let i=String(n.relaxZeros),s=String(n.shorthand),o=String(n.capture),a=String(n.wrap),c=r+":"+e+"="+i+s+o+a;if(xi.cache.hasOwnProperty(c))return xi.cache[c].result;let l=Math.min(r,e),p=Math.max(r,e);if(Math.abs(l-p)===1){let S=r+"|"+e;return n.capture?`(${S})`:n.wrap===!1?S:`(?:${S})`}let f=PC(r)||PC(e),h={min:r,max:e,a:l,b:p},v=[],x=[];if(f&&(h.isPadded=f,h.maxLen=String(h.max).length),l<0){let S=p<0?Math.abs(p):1;x=AC(S,Math.abs(l),h,n),l=h.a=0}return p>=0&&(v=AC(l,p,h,n)),h.negatives=x,h.positives=v,h.result=eU(x,v,n),n.capture===!0?h.result=`(${h.result})`:n.wrap!==!1&&v.length+x.length>1&&(h.result=`(?:${h.result})`),xi.cache[c]=h,h.result};function eU(r,e,t){let n=Im(r,e,"-",!1,t)||[],i=Im(e,r,"",!1,t)||[],s=Im(r,e,"-?",!0,t)||[];return n.concat(s).concat(i).join("|")}function tU(r,e){let t=1,n=1,i=kC(r,t),s=new Set([e]);for(;r<=i&&i<=e;)s.add(i),t+=1,i=kC(r,t);for(i=OC(e+1,n)-1;r<i&&i<=e;)s.add(i),n+=1,i=OC(e+1,n)-1;return s=[...s],s.sort(iU),s}function rU(r,e,t){if(r===e)return{pattern:r,count:[],digits:0};let n=nU(r,e),i=n.length,s="",o=0;for(let a=0;a<i;a++){let[c,l]=n[a];c===l?s+=c:c!=="0"||l!=="9"?s+=sU(c,l,t):o++}return o&&(s+=t.shorthand===!0?"\\d":"[0-9]"),{pattern:s,count:[o],digits:i}}function AC(r,e,t,n){let i=tU(r,e),s=[],o=r,a;for(let c=0;c<i.length;c++){let l=i[c],p=rU(String(o),String(l),n),f="";if(!t.isPadded&&a&&a.pattern===p.pattern){a.count.length>1&&a.count.pop(),a.count.push(p.count[0]),a.string=a.pattern+MC(a.count),o=l+1;continue}t.isPadded&&(f=oU(l,t,n)),p.string=f+p.pattern+MC(p.count),s.push(p),o=l+1,a=p}return s}function Im(r,e,t,n,i){let s=[];for(let o of r){let{string:a}=o;!n&&!RC(e,"string",a)&&s.push(t+a),n&&RC(e,"string",a)&&s.push(t+a)}return s}function nU(r,e){let t=[];for(let n=0;n<r.length;n++)t.push([r[n],e[n]]);return t}function iU(r,e){return r>e?1:e>r?-1:0}function RC(r,e,t){return r.some(n=>n[e]===t)}function kC(r,e){return Number(String(r).slice(0,-e)+"9".repeat(e))}function OC(r,e){return r-r%Math.pow(10,e)}function MC(r){let[e=0,t=""]=r;return t||e>1?`{${e+(t?","+t:"")}}`:""}function sU(r,e,t){return`[${r}${e-r===1?"":"-"}${e}]`}function PC(r){return/^-?(0+)\d/.test(r)}function oU(r,e,t){if(!e.isPadded)return r;let n=Math.abs(e.maxLen-String(r).length),i=t.relaxZeros!==!1;switch(n){case 0:return"";case 1:return i?"0?":"0";case 2:return i?"0{0,2}":"00";default:return i?`0{0,${n}}`:`0{${n}}`}}xi.cache={};xi.clearCache=()=>xi.cache={};IC.exports=xi});var Dm=R((NG,qC)=>{"use strict";var aU=require("util"),DC=NC(),LC=r=>r!==null&&typeof r=="object"&&!Array.isArray(r),cU=r=>e=>r===!0?Number(e):String(e),Nm=r=>typeof r=="number"||typeof r=="string"&&r!=="",ua=r=>Number.isInteger(+r),Lm=r=>{let e=`${r}`,t=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++t]==="0";);return t>0},lU=(r,e,t)=>typeof r=="string"||typeof e=="string"?!0:t.stringify===!0,uU=(r,e,t)=>{if(e>0){let n=r[0]==="-"?"-":"";n&&(r=r.slice(1)),r=n+r.padStart(n?e-1:e,"0")}return t===!1?String(r):r},Tu=(r,e)=>{let t=r[0]==="-"?"-":"";for(t&&(r=r.slice(1),e--);r.length<e;)r="0"+r;return t?"-"+r:r},pU=(r,e,t)=>{r.negatives.sort((a,c)=>a<c?-1:a>c?1:0),r.positives.sort((a,c)=>a<c?-1:a>c?1:0);let n=e.capture?"":"?:",i="",s="",o;return r.positives.length&&(i=r.positives.map(a=>Tu(String(a),t)).join("|")),r.negatives.length&&(s=`-(${n}${r.negatives.map(a=>Tu(String(a),t)).join("|")})`),i&&s?o=`${i}|${s}`:o=i||s,e.wrap?`(${n}${o})`:o},BC=(r,e,t,n)=>{if(t)return DC(r,e,{wrap:!1,...n});let i=String.fromCharCode(r);if(r===e)return i;let s=String.fromCharCode(e);return`[${i}-${s}]`},jC=(r,e,t)=>{if(Array.isArray(r)){let n=t.wrap===!0,i=t.capture?"":"?:";return n?`(${i}${r.join("|")})`:r.join("|")}return DC(r,e,t)},FC=(...r)=>new RangeError("Invalid range arguments: "+aU.inspect(...r)),UC=(r,e,t)=>{if(t.strictRanges===!0)throw FC([r,e]);return[]},fU=(r,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${r}" to be a number`);return[]},dU=(r,e,t=1,n={})=>{let i=Number(r),s=Number(e);if(!Number.isInteger(i)||!Number.isInteger(s)){if(n.strictRanges===!0)throw FC([r,e]);return[]}i===0&&(i=0),s===0&&(s=0);let o=i>s,a=String(r),c=String(e),l=String(t);t=Math.max(Math.abs(t),1);let p=Lm(a)||Lm(c)||Lm(l),f=p?Math.max(a.length,c.length,l.length):0,h=p===!1&&lU(r,e,n)===!1,v=n.transform||cU(h);if(n.toRegex&&t===1)return BC(Tu(r,f),Tu(e,f),!0,n);let x={negatives:[],positives:[]},S=P=>x[P<0?"negatives":"positives"].push(Math.abs(P)),A=[],k=0;for(;o?i>=s:i<=s;)n.toRegex===!0&&t>1?S(i):A.push(uU(v(i,k),f,h)),i=o?i-t:i+t,k++;return n.toRegex===!0?t>1?pU(x,n,f):jC(A,null,{wrap:!1,...n}):A},hU=(r,e,t=1,n={})=>{if(!ua(r)&&r.length>1||!ua(e)&&e.length>1)return UC(r,e,n);let i=n.transform||(h=>String.fromCharCode(h)),s=`${r}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=s>o,c=Math.min(s,o),l=Math.max(s,o);if(n.toRegex&&t===1)return BC(c,l,!1,n);let p=[],f=0;for(;a?s>=o:s<=o;)p.push(i(s,f)),s=a?s-t:s+t,f++;return n.toRegex===!0?jC(p,null,{wrap:!1,options:n}):p},Eu=(r,e,t,n={})=>{if(e==null&&Nm(r))return[r];if(!Nm(r)||!Nm(e))return UC(r,e,n);if(typeof t=="function")return Eu(r,e,1,{transform:t});if(LC(t))return Eu(r,e,0,t);let i={...n};return i.capture===!0&&(i.wrap=!0),t=t||i.step||1,ua(t)?ua(r)&&ua(e)?dU(r,e,t,i):hU(r,e,Math.max(Math.abs(t),1),i):t!=null&&!LC(t)?fU(t,i):Eu(r,e,1,t)};qC.exports=Eu});var WC=R((LG,$C)=>{"use strict";var mU=Dm(),HC=wu(),gU=(r,e={})=>{let t=(n,i={})=>{let s=HC.isInvalidBrace(i),o=n.invalid===!0&&e.escapeInvalid===!0,a=s===!0||o===!0,c=e.escapeInvalid===!0?"\\":"",l="";if(n.isOpen===!0)return c+n.value;if(n.isClose===!0)return console.log("node.isClose",c,n.value),c+n.value;if(n.type==="open")return a?c+n.value:"(";if(n.type==="close")return a?c+n.value:")";if(n.type==="comma")return n.prev.type==="comma"?"":a?n.value:"|";if(n.value)return n.value;if(n.nodes&&n.ranges>0){let p=HC.reduce(n.nodes),f=mU(...p,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(f.length!==0)return p.length>1&&f.length>1?`(${f})`:f}if(n.nodes)for(let p of n.nodes)l+=t(p,n);return l};return t(r)};$C.exports=gU});var VC=R((DG,zC)=>{"use strict";var vU=Dm(),GC=Su(),Hs=wu(),_i=(r="",e="",t=!1)=>{let n=[];if(r=[].concat(r),e=[].concat(e),!e.length)return r;if(!r.length)return t?Hs.flatten(e).map(i=>`{${i}}`):e;for(let i of r)if(Array.isArray(i))for(let s of i)n.push(_i(s,e,t));else for(let s of e)t===!0&&typeof s=="string"&&(s=`{${s}}`),n.push(Array.isArray(s)?_i(i,s,t):i+s);return Hs.flatten(n)},yU=(r,e={})=>{let t=e.rangeLimit===void 0?1e3:e.rangeLimit,n=(i,s={})=>{i.queue=[];let o=s,a=s.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(i.invalid||i.dollar){a.push(_i(a.pop(),GC(i,e)));return}if(i.type==="brace"&&i.invalid!==!0&&i.nodes.length===2){a.push(_i(a.pop(),["{}"]));return}if(i.nodes&&i.ranges>0){let f=Hs.reduce(i.nodes);if(Hs.exceedsLimit(...f,e.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let h=vU(...f,e);h.length===0&&(h=GC(i,e)),a.push(_i(a.pop(),h)),i.nodes=[];return}let c=Hs.encloseBrace(i),l=i.queue,p=i;for(;p.type!=="brace"&&p.type!=="root"&&p.parent;)p=p.parent,l=p.queue;for(let f=0;f<i.nodes.length;f++){let h=i.nodes[f];if(h.type==="comma"&&i.type==="brace"){f===1&&l.push(""),l.push("");continue}if(h.type==="close"){a.push(_i(a.pop(),l,c));continue}if(h.value&&h.type!=="open"){l.push(_i(l.pop(),h.value));continue}h.nodes&&n(h,i)}return l};return Hs.flatten(n(r))};zC.exports=yU});var YC=R((BG,KC)=>{"use strict";KC.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
102
- `,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var eA=R((jG,QC)=>{"use strict";var xU=Su(),{MAX_LENGTH:JC,CHAR_BACKSLASH:Bm,CHAR_BACKTICK:_U,CHAR_COMMA:bU,CHAR_DOT:wU,CHAR_LEFT_PARENTHESES:SU,CHAR_RIGHT_PARENTHESES:EU,CHAR_LEFT_CURLY_BRACE:TU,CHAR_RIGHT_CURLY_BRACE:CU,CHAR_LEFT_SQUARE_BRACKET:XC,CHAR_RIGHT_SQUARE_BRACKET:ZC,CHAR_DOUBLE_QUOTE:AU,CHAR_SINGLE_QUOTE:RU,CHAR_NO_BREAK_SPACE:kU,CHAR_ZERO_WIDTH_NOBREAK_SPACE:OU}=YC(),MU=(r,e={})=>{if(typeof r!="string")throw new TypeError("Expected a string");let t=e||{},n=typeof t.maxLength=="number"?Math.min(JC,t.maxLength):JC;if(r.length>n)throw new SyntaxError(`Input length (${r.length}), exceeds max characters (${n})`);let i={type:"root",input:r,nodes:[]},s=[i],o=i,a=i,c=0,l=r.length,p=0,f=0,h,v=()=>r[p++],x=S=>{if(S.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&S.type==="text"){a.value+=S.value;return}return o.nodes.push(S),S.parent=o,S.prev=a,a=S,S};for(x({type:"bos"});p<l;)if(o=s[s.length-1],h=v(),!(h===OU||h===kU)){if(h===Bm){x({type:"text",value:(e.keepEscaping?h:"")+v()});continue}if(h===ZC){x({type:"text",value:"\\"+h});continue}if(h===XC){c++;let S;for(;p<l&&(S=v());){if(h+=S,S===XC){c++;continue}if(S===Bm){h+=v();continue}if(S===ZC&&(c--,c===0))break}x({type:"text",value:h});continue}if(h===SU){o=x({type:"paren",nodes:[]}),s.push(o),x({type:"text",value:h});continue}if(h===EU){if(o.type!=="paren"){x({type:"text",value:h});continue}o=s.pop(),x({type:"text",value:h}),o=s[s.length-1];continue}if(h===AU||h===RU||h===_U){let S=h,A;for(e.keepQuotes!==!0&&(h="");p<l&&(A=v());){if(A===Bm){h+=A+v();continue}if(A===S){e.keepQuotes===!0&&(h+=A);break}h+=A}x({type:"text",value:h});continue}if(h===TU){f++;let A={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:f,commas:0,ranges:0,nodes:[]};o=x(A),s.push(o),x({type:"open",value:h});continue}if(h===CU){if(o.type!=="brace"){x({type:"text",value:h});continue}let S="close";o=s.pop(),o.close=!0,x({type:S,value:h}),f--,o=s[s.length-1];continue}if(h===bU&&f>0){if(o.ranges>0){o.ranges=0;let S=o.nodes.shift();o.nodes=[S,{type:"text",value:xU(o)}]}x({type:"comma",value:h}),o.commas++;continue}if(h===wU&&f>0&&o.commas===0){let S=o.nodes;if(f===0||S.length===0){x({type:"text",value:h});continue}if(a.type==="dot"){if(o.range=[],a.value+=h,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){S.pop();let A=S[S.length-1];A.value+=a.value+h,a=A,o.ranges--;continue}x({type:"dot",value:h});continue}x({type:"text",value:h})}do if(o=s.pop(),o.type!=="root"){o.nodes.forEach(k=>{k.nodes||(k.type==="open"&&(k.isOpen=!0),k.type==="close"&&(k.isClose=!0),k.nodes||(k.type="text"),k.invalid=!0)});let S=s[s.length-1],A=S.nodes.indexOf(o);S.nodes.splice(A,1,...o.nodes)}while(s.length>0);return x({type:"eos"}),i};QC.exports=MU});var nA=R((FG,rA)=>{"use strict";var tA=Su(),PU=WC(),IU=VC(),NU=eA(),Xt=(r,e={})=>{let t=[];if(Array.isArray(r))for(let n of r){let i=Xt.create(n,e);Array.isArray(i)?t.push(...i):t.push(i)}else t=[].concat(Xt.create(r,e));return e&&e.expand===!0&&e.nodupes===!0&&(t=[...new Set(t)]),t};Xt.parse=(r,e={})=>NU(r,e);Xt.stringify=(r,e={})=>tA(typeof r=="string"?Xt.parse(r,e):r,e);Xt.compile=(r,e={})=>(typeof r=="string"&&(r=Xt.parse(r,e)),PU(r,e));Xt.expand=(r,e={})=>{typeof r=="string"&&(r=Xt.parse(r,e));let t=IU(r,e);return e.noempty===!0&&(t=t.filter(Boolean)),e.nodupes===!0&&(t=[...new Set(t)]),t};Xt.create=(r,e={})=>r===""||r.length<3?[r]:e.expand!==!0?Xt.compile(r,e):Xt.expand(r,e);rA.exports=Xt});var iA=R((UG,LU)=>{LU.exports=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]});var oA=R((qG,sA)=>{sA.exports=iA()});var cA=R((HG,aA)=>{"use strict";var DU=require("path"),BU=oA(),jU=new Set(BU);aA.exports=r=>jU.has(DU.extname(r).slice(1).toLowerCase())});var Cu=R(Y=>{"use strict";var{sep:FU}=require("path"),{platform:jm}=process,UU=require("os");Y.EV_ALL="all";Y.EV_READY="ready";Y.EV_ADD="add";Y.EV_CHANGE="change";Y.EV_ADD_DIR="addDir";Y.EV_UNLINK="unlink";Y.EV_UNLINK_DIR="unlinkDir";Y.EV_RAW="raw";Y.EV_ERROR="error";Y.STR_DATA="data";Y.STR_END="end";Y.STR_CLOSE="close";Y.FSEVENT_CREATED="created";Y.FSEVENT_MODIFIED="modified";Y.FSEVENT_DELETED="deleted";Y.FSEVENT_MOVED="moved";Y.FSEVENT_CLONED="cloned";Y.FSEVENT_UNKNOWN="unknown";Y.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;Y.FSEVENT_TYPE_FILE="file";Y.FSEVENT_TYPE_DIRECTORY="directory";Y.FSEVENT_TYPE_SYMLINK="symlink";Y.KEY_LISTENERS="listeners";Y.KEY_ERR="errHandlers";Y.KEY_RAW="rawEmitters";Y.HANDLER_KEYS=[Y.KEY_LISTENERS,Y.KEY_ERR,Y.KEY_RAW];Y.DOT_SLASH=`.${FU}`;Y.BACK_SLASH_RE=/\\/g;Y.DOUBLE_SLASH_RE=/\/\//;Y.SLASH_OR_BACK_SLASH_RE=/[/\\]/;Y.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;Y.REPLACER_RE=/^\.[/\\]/;Y.SLASH="/";Y.SLASH_SLASH="//";Y.BRACE_START="{";Y.BANG="!";Y.ONE_DOT=".";Y.TWO_DOTS="..";Y.STAR="*";Y.GLOBSTAR="**";Y.ROOT_GLOBSTAR="/**/*";Y.SLASH_GLOBSTAR="/**";Y.DIR_SUFFIX="Dir";Y.ANYMATCH_OPTS={dot:!0};Y.STRING_TYPE="string";Y.FUNCTION_TYPE="function";Y.EMPTY_STR="";Y.EMPTY_FN=()=>{};Y.IDENTITY_FN=r=>r;Y.isWindows=jm==="win32";Y.isMacos=jm==="darwin";Y.isLinux=jm==="linux";Y.isIBMi=UU.type()==="OS400"});var hA=R((WG,dA)=>{"use strict";var xn=require("fs"),mt=require("path"),{promisify:ha}=require("util"),qU=cA(),{isWindows:HU,isLinux:$U,EMPTY_FN:WU,EMPTY_STR:GU,KEY_LISTENERS:$s,KEY_ERR:Fm,KEY_RAW:pa,HANDLER_KEYS:zU,EV_CHANGE:Ru,EV_ADD:Au,EV_ADD_DIR:VU,EV_ERROR:uA,STR_DATA:KU,STR_END:YU,BRACE_START:JU,STAR:XU}=Cu(),ZU="watch",QU=ha(xn.open),pA=ha(xn.stat),eq=ha(xn.lstat),tq=ha(xn.close),Um=ha(xn.realpath),rq={lstat:eq,stat:pA},Hm=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},fa=(r,e,t)=>{let n=r[e];n instanceof Set||(r[e]=n=new Set([n])),n.add(t)},nq=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},da=(r,e,t)=>{let n=r[e];n instanceof Set?n.delete(t):n===t&&delete r[e]},fA=r=>r instanceof Set?r.size===0:!r,ku=new Map;function lA(r,e,t,n,i){let s=(o,a)=>{t(r),i(o,a,{watchedPath:r}),a&&r!==a&&Ou(mt.resolve(r,a),$s,mt.join(r,a))};try{return xn.watch(r,e,s)}catch(o){n(o)}}var Ou=(r,e,t,n,i)=>{let s=ku.get(r);s&&Hm(s[e],o=>{o(t,n,i)})},iq=(r,e,t,n)=>{let{listener:i,errHandler:s,rawEmitter:o}=n,a=ku.get(e),c;if(!t.persistent)return c=lA(r,t,i,s,o),c.close.bind(c);if(a)fa(a,$s,i),fa(a,Fm,s),fa(a,pa,o);else{if(c=lA(r,t,Ou.bind(null,e,$s),s,Ou.bind(null,e,pa)),!c)return;c.on(uA,async l=>{let p=Ou.bind(null,e,Fm);if(a.watcherUnusable=!0,HU&&l.code==="EPERM")try{let f=await QU(r,"r");await tq(f),p(l)}catch{}else p(l)}),a={listeners:i,errHandlers:s,rawEmitters:o,watcher:c},ku.set(e,a)}return()=>{da(a,$s,i),da(a,Fm,s),da(a,pa,o),fA(a.listeners)&&(a.watcher.close(),ku.delete(e),zU.forEach(nq(a)),a.watcher=void 0,Object.freeze(a))}},qm=new Map,sq=(r,e,t,n)=>{let{listener:i,rawEmitter:s}=n,o=qm.get(e),a=new Set,c=new Set,l=o&&o.options;return l&&(l.persistent<t.persistent||l.interval>t.interval)&&(a=o.listeners,c=o.rawEmitters,xn.unwatchFile(e),o=void 0),o?(fa(o,$s,i),fa(o,pa,s)):(o={listeners:i,rawEmitters:s,options:t,watcher:xn.watchFile(e,t,(p,f)=>{Hm(o.rawEmitters,v=>{v(Ru,e,{curr:p,prev:f})});let h=p.mtimeMs;(p.size!==f.size||h>f.mtimeMs||h===0)&&Hm(o.listeners,v=>v(r,p))})},qm.set(e,o)),()=>{da(o,$s,i),da(o,pa,s),fA(o.listeners)&&(qm.delete(e),xn.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},$m=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,i=mt.dirname(e),s=mt.basename(e);this.fsw._getWatchedDir(i).add(s);let a=mt.resolve(e),c={persistent:n.persistent};t||(t=WU);let l;return n.usePolling?(c.interval=n.enableBinaryInterval&&qU(s)?n.binaryInterval:n.interval,l=sq(e,a,c,{listener:t,rawEmitter:this.fsw._emitRaw})):l=iq(e,a,c,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),l}_handleFile(e,t,n){if(this.fsw.closed)return;let i=mt.dirname(e),s=mt.basename(e),o=this.fsw._getWatchedDir(i),a=t;if(o.has(s))return;let c=async(p,f)=>{if(this.fsw._throttle(ZU,e,5)){if(!f||f.mtimeMs===0)try{let h=await pA(e);if(this.fsw.closed)return;let v=h.atimeMs,x=h.mtimeMs;(!v||v<=x||x!==a.mtimeMs)&&this.fsw._emit(Ru,e,h),$U&&a.ino!==h.ino?(this.fsw._closeFile(p),a=h,this.fsw._addPathCloser(p,this._watchWithNodeFs(e,c))):a=h}catch{this.fsw._remove(i,s)}else if(o.has(s)){let h=f.atimeMs,v=f.mtimeMs;(!h||h<=v||v!==a.mtimeMs)&&this.fsw._emit(Ru,e,f),a=f}}},l=this._watchWithNodeFs(e,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Au,e,0))return;this.fsw._emit(Au,e,t)}return l}async _handleSymlink(e,t,n,i){if(this.fsw.closed)return;let s=e.fullPath,o=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await Um(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(i)?this.fsw._symlinkPaths.get(s)!==a&&(this.fsw._symlinkPaths.set(s,a),this.fsw._emit(Ru,n,e.stats)):(o.add(i),this.fsw._symlinkPaths.set(s,a),this.fsw._emit(Au,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,t,n,i,s,o,a){if(e=mt.join(e,GU),!n.hasGlob&&(a=this.fsw._throttle("readdir",e,1e3),!a))return;let c=this.fsw._getWatchedDir(n.path),l=new Set,p=this.fsw._readdirp(e,{fileFilter:f=>n.filterPath(f),directoryFilter:f=>n.filterDir(f),depth:0}).on(KU,async f=>{if(this.fsw.closed){p=void 0;return}let h=f.path,v=mt.join(e,h);if(l.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,e,v,h))){if(this.fsw.closed){p=void 0;return}(h===i||!i&&!c.has(h))&&(this.fsw._incrReadyCount(),v=mt.join(s,mt.relative(s,v)),this._addToNodeFs(v,t,n,o+1))}}).on(uA,this._boundHandleError);return new Promise(f=>p.once(YU,()=>{if(this.fsw.closed){p=void 0;return}let h=a?a.clear():!1;f(),c.getChildren().filter(v=>v!==e&&!l.has(v)&&(!n.hasGlob||n.filterPath({fullPath:mt.resolve(e,v)}))).forEach(v=>{this.fsw._remove(e,v)}),p=void 0,h&&this._handleRead(e,!1,n,i,s,o,a)}))}async _handleDir(e,t,n,i,s,o,a){let c=this.fsw._getWatchedDir(mt.dirname(e)),l=c.has(mt.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!s&&!l&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(VU,e,t),c.add(mt.basename(e)),this.fsw._getWatchedDir(e);let p,f,h=this.fsw.options.depth;if((h==null||i<=h)&&!this.fsw._symlinkPaths.has(a)){if(!s&&(await this._handleRead(e,n,o,s,e,i,p),this.fsw.closed))return;f=this._watchWithNodeFs(e,(v,x)=>{x&&x.mtimeMs===0||this._handleRead(v,!1,o,s,e,i,p)})}return f}async _addToNodeFs(e,t,n,i,s){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e,i);!a.hasGlob&&n&&(a.hasGlob=n.hasGlob,a.globFilter=n.globFilter,a.filterPath=c=>n.filterPath(c),a.filterDir=c=>n.filterDir(c));try{let c=await rq[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))return o(),!1;let l=this.fsw.options.followSymlinks&&!e.includes(XU)&&!e.includes(JU),p;if(c.isDirectory()){let f=mt.resolve(e),h=l?await Um(e):e;if(this.fsw.closed||(p=await this._handleDir(a.watchPath,c,t,i,s,a,h),this.fsw.closed))return;f!==h&&h!==void 0&&this.fsw._symlinkPaths.set(f,h)}else if(c.isSymbolicLink()){let f=l?await Um(e):e;if(this.fsw.closed)return;let h=mt.dirname(a.watchPath);if(this.fsw._getWatchedDir(h).add(a.watchPath),this.fsw._emit(Au,a.watchPath,c),p=await this._handleDir(h,c,t,i,e,a,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(mt.resolve(e),f)}else p=this._handleFile(a.watchPath,c,t);return o(),this.fsw._addPathCloser(e,p),!1}catch(c){if(this.fsw._handleError(c))return o(),e}}};dA.exports=$m});var bA=R((GG,Xm)=>{"use strict";var Ym=require("fs"),gt=require("path"),{promisify:Jm}=require("util"),Ws;try{Ws=require("fsevents")}catch(r){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(r)}if(Ws){let r=process.version.match(/v(\d+)\.(\d+)/);if(r&&r[1]&&r[2]){let e=Number.parseInt(r[1],10),t=Number.parseInt(r[2],10);e===8&&t<16&&(Ws=void 0)}}var{EV_ADD:Wm,EV_CHANGE:oq,EV_ADD_DIR:mA,EV_UNLINK:Mu,EV_ERROR:aq,STR_DATA:cq,STR_END:lq,FSEVENT_CREATED:uq,FSEVENT_MODIFIED:pq,FSEVENT_DELETED:fq,FSEVENT_MOVED:dq,FSEVENT_UNKNOWN:hq,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:mq,FSEVENT_TYPE_FILE:gq,FSEVENT_TYPE_DIRECTORY:ma,FSEVENT_TYPE_SYMLINK:_A,ROOT_GLOBSTAR:gA,DIR_SUFFIX:vq,DOT_SLASH:vA,FUNCTION_TYPE:Gm,EMPTY_FN:yq,IDENTITY_FN:xq}=Cu(),_q=r=>isNaN(r)?{}:{depth:r},Vm=Jm(Ym.stat),bq=Jm(Ym.lstat),yA=Jm(Ym.realpath),wq={stat:Vm,lstat:bq},bi=new Map,Sq=10,Eq=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),Tq=(r,e)=>({stop:Ws.watch(r,e)});function Cq(r,e,t,n){let i=gt.extname(e)?gt.dirname(e):e,s=gt.dirname(i),o=bi.get(i);Aq(s)&&(i=s);let a=gt.resolve(r),c=a!==e,l=(f,h,v)=>{c&&(f=f.replace(e,a)),(f===a||!f.indexOf(a+gt.sep))&&t(f,h,v)},p=!1;for(let f of bi.keys())if(e.indexOf(gt.resolve(f)+gt.sep)===0){i=f,o=bi.get(i),p=!0;break}return o||p?o.listeners.add(l):(o={listeners:new Set([l]),rawEmitter:n,watcher:Tq(i,(f,h)=>{if(!o.listeners.size||h&mq)return;let v=Ws.getInfo(f,h);o.listeners.forEach(x=>{x(f,h,v)}),o.rawEmitter(v.event,f,v)})},bi.set(i,o)),()=>{let f=o.listeners;if(f.delete(l),!f.size&&(bi.delete(i),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var Aq=r=>{let e=0;for(let t of bi.keys())if(t.indexOf(r)===0&&(e++,e>=Sq))return!0;return!1},Rq=()=>Ws&&bi.size<128,zm=(r,e)=>{let t=0;for(;!r.indexOf(e)&&(r=gt.dirname(r))!==e;)t++;return t},xA=(r,e)=>r.type===ma&&e.isDirectory()||r.type===_A&&e.isSymbolicLink()||r.type===gq&&e.isFile(),Km=class{constructor(e){this.fsw=e}checkIgnored(e,t){let n=this.fsw._ignoredPaths;if(this.fsw._isIgnored(e,t))return n.add(e),t&&t.isDirectory()&&n.add(e+gA),!0;n.delete(e),n.delete(e+gA)}addOrChange(e,t,n,i,s,o,a,c){let l=s.has(o)?oq:Wm;this.handleEvent(l,e,t,n,i,s,o,a,c)}async checkExists(e,t,n,i,s,o,a,c){try{let l=await Vm(e);if(this.fsw.closed)return;xA(a,l)?this.addOrChange(e,t,n,i,s,o,a,c):this.handleEvent(Mu,e,t,n,i,s,o,a,c)}catch(l){l.code==="EACCES"?this.addOrChange(e,t,n,i,s,o,a,c):this.handleEvent(Mu,e,t,n,i,s,o,a,c)}}handleEvent(e,t,n,i,s,o,a,c,l){if(!(this.fsw.closed||this.checkIgnored(t)))if(e===Mu){let p=c.type===ma;(p||o.has(a))&&this.fsw._remove(s,a,p)}else{if(e===Wm){if(c.type===ma&&this.fsw._getWatchedDir(t),c.type===_A&&l.followSymlinks){let f=l.depth===void 0?void 0:zm(n,i)+1;return this._addToFsEvents(t,!1,!0,f)}this.fsw._getWatchedDir(s).add(a)}let p=c.type===ma?e+vq:e;this.fsw._emit(p,t),p===mA&&this._addToFsEvents(t,!1,!0)}}_watchWithFsEvents(e,t,n,i){if(this.fsw.closed||this.fsw._isIgnored(e))return;let s=this.fsw.options,a=Cq(e,t,async(c,l,p)=>{if(this.fsw.closed||s.depth!==void 0&&zm(c,t)>s.depth)return;let f=n(gt.join(e,gt.relative(e,c)));if(i&&!i(f))return;let h=gt.dirname(f),v=gt.basename(f),x=this.fsw._getWatchedDir(p.type===ma?f:h);if(Eq.has(l)||p.event===hq)if(typeof s.ignored===Gm){let S;try{S=await Vm(f)}catch{}if(this.fsw.closed||this.checkIgnored(f,S))return;xA(p,S)?this.addOrChange(f,c,t,h,x,v,p,s):this.handleEvent(Mu,f,c,t,h,x,v,p,s)}else this.checkExists(f,c,t,h,x,v,p,s);else switch(p.event){case uq:case pq:return this.addOrChange(f,c,t,h,x,v,p,s);case fq:case dq:return this.checkExists(f,c,t,h,x,v,p,s)}},this.fsw._emitRaw);return this.fsw._emitReady(),a}async _handleFsEventsSymlink(e,t,n,i){if(!(this.fsw.closed||this.fsw._symlinkPaths.has(t))){this.fsw._symlinkPaths.set(t,!0),this.fsw._incrReadyCount();try{let s=await yA(e);if(this.fsw.closed)return;if(this.fsw._isIgnored(s))return this.fsw._emitReady();this.fsw._incrReadyCount(),this._addToFsEvents(s||e,o=>{let a=e;return s&&s!==vA?a=o.replace(s,e):o!==vA&&(a=gt.join(e,o)),n(a)},!1,i)}catch(s){if(this.fsw._handleError(s))return this.fsw._emitReady()}}}emitAdd(e,t,n,i,s){let o=n(e),a=t.isDirectory(),c=this.fsw._getWatchedDir(gt.dirname(o)),l=gt.basename(o);a&&this.fsw._getWatchedDir(o),!c.has(l)&&(c.add(l),(!i.ignoreInitial||s===!0)&&this.fsw._emit(a?mA:Wm,o,t))}initWatch(e,t,n,i){if(this.fsw.closed)return;let s=this._watchWithFsEvents(n.watchPath,gt.resolve(e||n.watchPath),i,n.globFilter);this.fsw._addPathCloser(t,s)}async _addToFsEvents(e,t,n,i){if(this.fsw.closed)return;let s=this.fsw.options,o=typeof t===Gm?t:xq,a=this.fsw._getWatchHelpers(e);try{let c=await wq[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))throw null;if(c.isDirectory()){if(a.globFilter||this.emitAdd(o(e),c,o,s,n),i&&i>s.depth)return;this.fsw._readdirp(a.watchPath,{fileFilter:l=>a.filterPath(l),directoryFilter:l=>a.filterDir(l),..._q(s.depth-(i||0))}).on(cq,l=>{if(this.fsw.closed||l.stats.isDirectory()&&!a.filterPath(l))return;let p=gt.join(a.watchPath,l.path),{fullPath:f}=l;if(a.followSymlinks&&l.stats.isSymbolicLink()){let h=s.depth===void 0?void 0:zm(p,gt.resolve(a.watchPath))+1;this._handleFsEventsSymlink(p,f,o,h)}else this.emitAdd(p,l.stats,o,s,n)}).on(aq,yq).on(lq,()=>{this.fsw._emitReady()})}else this.emitAdd(a.watchPath,c,o,s,n),this.fsw._emitReady()}catch(c){(!c||this.fsw._handleError(c))&&(this.fsw._emitReady(),this.fsw._emitReady())}if(s.persistent&&n!==!0)if(typeof t===Gm)this.initWatch(void 0,e,a,o);else{let c;try{c=await yA(a.watchPath)}catch{}this.initWatch(c,e,a,o)}}};Xm.exports=Km;Xm.exports.canUse=Rq});var PA=R(fg=>{"use strict";var{EventEmitter:kq}=require("events"),ug=require("fs"),le=require("path"),{promisify:RA}=require("util"),Oq=cC(),ng=mC().default,Mq=bC(),Zm=Mm(),Pq=nA(),Iq=km(),Nq=hA(),wA=bA(),{EV_ALL:Qm,EV_READY:Lq,EV_ADD:Pu,EV_CHANGE:ga,EV_UNLINK:SA,EV_ADD_DIR:Dq,EV_UNLINK_DIR:Bq,EV_RAW:jq,EV_ERROR:eg,STR_CLOSE:Fq,STR_END:Uq,BACK_SLASH_RE:qq,DOUBLE_SLASH_RE:EA,SLASH_OR_BACK_SLASH_RE:Hq,DOT_RE:$q,REPLACER_RE:Wq,SLASH:tg,SLASH_SLASH:Gq,BRACE_START:zq,BANG:ig,ONE_DOT:kA,TWO_DOTS:Vq,GLOBSTAR:Kq,SLASH_GLOBSTAR:rg,ANYMATCH_OPTS:sg,STRING_TYPE:pg,FUNCTION_TYPE:Yq,EMPTY_STR:og,EMPTY_FN:Jq,isWindows:Xq,isMacos:Zq,isIBMi:Qq}=Cu(),eH=RA(ug.stat),tH=RA(ug.readdir),ag=(r=[])=>Array.isArray(r)?r:[r],OA=(r,e=[])=>(r.forEach(t=>{Array.isArray(t)?OA(t,e):e.push(t)}),e),TA=r=>{let e=OA(ag(r));if(!e.every(t=>typeof t===pg))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(MA)},CA=r=>{let e=r.replace(qq,tg),t=!1;for(e.startsWith(Gq)&&(t=!0);e.match(EA);)e=e.replace(EA,tg);return t&&(e=tg+e),e},MA=r=>CA(le.normalize(CA(r))),AA=(r=og)=>e=>typeof e!==pg?e:MA(le.isAbsolute(e)?e:le.join(r,e)),rH=(r,e)=>le.isAbsolute(r)?r:r.startsWith(ig)?ig+le.join(e,r.slice(1)):le.join(e,r),kr=(r,e)=>r[e]===void 0,cg=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==kA&&e!==Vq&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await tH(n)}catch{this._removeWatcher&&this._removeWatcher(le.dirname(n),le.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;if(e)return[...e.values()]}dispose(){this.items.clear(),delete this.path,delete this._removeWatcher,delete this.items,Object.freeze(this)}},nH="stat",iH="lstat",lg=class{constructor(e,t,n,i){this.fsw=i,this.path=e=e.replace(Wq,og),this.watchPath=t,this.fullWatchPath=le.resolve(t),this.hasGlob=t!==e,e===og&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&n?void 0:!1,this.globFilter=this.hasGlob?ng(e,void 0,sg):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=n,this.statMethod=n?nH:iH}checkGlobSymlink(e){return this.globSymlink===void 0&&(this.globSymlink=e.fullParentDir===this.fullWatchPath?!1:{realPath:e.fullParentDir,linkPath:this.fullWatchPath}),this.globSymlink?e.fullPath.replace(this.globSymlink.realPath,this.globSymlink.linkPath):e.fullPath}entryPath(e){return le.join(this.watchPath,le.relative(this.watchPath,this.checkGlobSymlink(e)))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return(this.hasGlob&&typeof this.globFilter===Yq?this.globFilter(n):!0)&&this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}getDirParts(e){if(!this.hasGlob)return[];let t=[];return(e.includes(zq)?Pq.expand(e):[e]).forEach(i=>{t.push(le.relative(this.watchPath,i).split(Hq))}),t}filterDir(e){if(this.hasGlob){let t=this.getDirParts(this.checkGlobSymlink(e)),n=!1;this.unmatchedGlob=!this.dirParts.some(i=>i.every((s,o)=>(s===Kq&&(n=!0),n||!t[0][o]||ng(s,t[0][o],sg))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Iu=class extends kq{constructor(e){super();let t={};e&&Object.assign(t,e),this._watched=new Map,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._symlinkPaths=new Map,this._streams=new Set,this.closed=!1,kr(t,"persistent")&&(t.persistent=!0),kr(t,"ignoreInitial")&&(t.ignoreInitial=!1),kr(t,"ignorePermissionErrors")&&(t.ignorePermissionErrors=!1),kr(t,"interval")&&(t.interval=100),kr(t,"binaryInterval")&&(t.binaryInterval=300),kr(t,"disableGlobbing")&&(t.disableGlobbing=!1),t.enableBinaryInterval=t.binaryInterval!==t.interval,kr(t,"useFsEvents")&&(t.useFsEvents=!t.usePolling),wA.canUse()||(t.useFsEvents=!1),kr(t,"usePolling")&&!t.useFsEvents&&(t.usePolling=Zq),Qq&&(t.usePolling=!0);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let c=i.toLowerCase();c==="false"||c==="0"?t.usePolling=!1:c==="true"||c==="1"?t.usePolling=!0:t.usePolling=!!c}let s=process.env.CHOKIDAR_INTERVAL;s&&(t.interval=Number.parseInt(s,10)),kr(t,"atomic")&&(t.atomic=!t.usePolling&&!t.useFsEvents),t.atomic&&(this._pendingUnlinks=new Map),kr(t,"followSymlinks")&&(t.followSymlinks=!0),kr(t,"awaitWriteFinish")&&(t.awaitWriteFinish=!1),t.awaitWriteFinish===!0&&(t.awaitWriteFinish={});let o=t.awaitWriteFinish;o&&(o.stabilityThreshold||(o.stabilityThreshold=2e3),o.pollInterval||(o.pollInterval=100),this._pendingWrites=new Map),t.ignored&&(t.ignored=ag(t.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Jq,this._readyEmitted=!0,process.nextTick(()=>this.emit(Lq)))},this._emitRaw=(...c)=>this.emit(jq,...c),this._readyEmitted=!1,this.options=t,t.useFsEvents?this._fsEventsHandler=new wA(this):this._nodeFsHandler=new Nq(this),Object.freeze(t)}add(e,t,n){let{cwd:i,disableGlobbing:s}=this.options;this.closed=!1;let o=TA(e);return i&&(o=o.map(a=>{let c=rH(a,i);return s||!Zm(a)?c:Iq(c)})),o=o.filter(a=>a.startsWith(ig)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+rg),this._userIgnored=void 0,!0)),this.options.useFsEvents&&this._fsEventsHandler?(this._readyCount||(this._readyCount=o.length),this.options.persistent&&(this._readyCount+=o.length),o.forEach(a=>this._fsEventsHandler._addToFsEvents(a))):(this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!n,0,0,t);return c&&this._emitReady(),c})).then(a=>{this.closed||a.filter(c=>c).forEach(c=>{this.add(le.dirname(c),le.basename(t||c))})})),this}unwatch(e){if(this.closed)return this;let t=TA(e),{cwd:n}=this.options;return t.forEach(i=>{!le.isAbsolute(i)&&!this._closers.has(i)&&(n&&(i=le.join(n,i)),i=le.resolve(i)),this._closePath(i),this._ignoredPaths.add(i),this._watched.has(i)&&this._ignoredPaths.add(i+rg),this._userIgnored=void 0}),this}close(){if(this.closed)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(n=>{let i=n();i instanceof Promise&&e.push(i)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),["closers","watched","streams","symlinkPaths","throttled"].forEach(t=>{this[`_${t}`].clear()}),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let i=this.options.cwd?le.relative(this.options.cwd,n):n;e[i||kA]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(...t),e!==eg&&this.emit(Qm,...t)}async _emit(e,t,n,i,s){if(this.closed)return;let o=this.options;Xq&&(t=le.normalize(t)),o.cwd&&(t=le.relative(o.cwd,t));let a=[e,t];s!==void 0?a.push(n,i,s):i!==void 0?a.push(n,i):n!==void 0&&a.push(n);let c=o.awaitWriteFinish,l;if(c&&(l=this._pendingWrites.get(t)))return l.lastChange=new Date,this;if(o.atomic){if(e===SA)return this._pendingUnlinks.set(t,a),setTimeout(()=>{this._pendingUnlinks.forEach((p,f)=>{this.emit(...p),this.emit(Qm,...p),this._pendingUnlinks.delete(f)})},typeof o.atomic=="number"?o.atomic:100),this;e===Pu&&this._pendingUnlinks.has(t)&&(e=a[0]=ga,this._pendingUnlinks.delete(t))}if(c&&(e===Pu||e===ga)&&this._readyEmitted){let p=(f,h)=>{f?(e=a[0]=eg,a[1]=f,this.emitWithAll(e,a)):h&&(a.length>2?a[2]=h:a.push(h),this.emitWithAll(e,a))};return this._awaitWriteFinish(t,c.stabilityThreshold,e,p),this}if(e===ga&&!this._throttle(ga,t,50))return this;if(o.alwaysStat&&n===void 0&&(e===Pu||e===Dq||e===ga)){let p=o.cwd?le.join(o.cwd,t):t,f;try{f=await eH(p)}catch{}if(!f||this.closed)return;a.push(f)}return this.emitWithAll(e,a),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(eg,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let i=this._throttled.get(e),s=i.get(t);if(s)return s.count++,!1;let o,a=()=>{let l=i.get(t),p=l?l.count:0;return i.delete(t),clearTimeout(o),l&&clearTimeout(l.timeoutObject),p};o=setTimeout(a,n);let c={timeoutObject:o,clear:a,count:0};return i.set(t,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,i){let s,o=e;this.options.cwd&&!le.isAbsolute(e)&&(o=le.join(this.options.cwd,e));let a=new Date,c=l=>{ug.stat(o,(p,f)=>{if(p||!this._pendingWrites.has(e)){p&&p.code!=="ENOENT"&&i(p);return}let h=Number(new Date);l&&f.size!==l.size&&(this._pendingWrites.get(e).lastChange=h);let v=this._pendingWrites.get(e);h-v.lastChange>=t?(this._pendingWrites.delete(e),i(void 0,f)):s=setTimeout(c,this.options.awaitWriteFinish.pollInterval,f)})};this._pendingWrites.has(e)||(this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>(this._pendingWrites.delete(e),clearTimeout(s),n)}),s=setTimeout(c,this.options.awaitWriteFinish.pollInterval))}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,t){if(this.options.atomic&&$q.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=this.options.ignored,s=i&&i.map(AA(n)),o=ag(s).filter(c=>typeof c===pg&&!Zm(c)).map(c=>c+rg),a=this._getGlobIgnored().map(AA(n)).concat(s,o);this._userIgnored=ng(a,void 0,sg)}return this._userIgnored([e,t])}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e,t){let n=t||this.options.disableGlobbing||!Zm(e)?e:Mq(e),i=this.options.followSymlinks;return new lg(e,n,i,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let t=le.resolve(e);return this._watched.has(t)||this._watched.set(t,new cg(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){if(this.options.ignorePermissionErrors)return!0;let n=(e&&Number.parseInt(e.mode,10))&511;return!!(4&Number.parseInt(n.toString(8)[0],10))}_remove(e,t,n){let i=le.join(e,t),s=le.resolve(i);if(n=n??(this._watched.has(i)||this._watched.has(s)),!this._throttle("remove",i,100))return;!n&&!this.options.useFsEvents&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(i).getChildren().forEach(h=>this._remove(i,h));let c=this._getWatchedDir(e),l=c.has(t);c.remove(t),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let p=i;if(this.options.cwd&&(p=le.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(p)&&this._pendingWrites.get(p).cancelWait()===Pu)return;this._watched.delete(i),this._watched.delete(s);let f=n?Bq:SA;l&&!this._isIgnored(i)&&this._emit(f,i),this.options.useFsEvents||this._closePath(i)}_closePath(e){this._closeFile(e);let t=le.dirname(e);this._getWatchedDir(t).remove(le.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(n=>n()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n={type:Qm,alwaysStat:!0,lstat:!0,...t},i=Oq(e,n);return this._streams.add(i),i.once(Fq,()=>{i=void 0}),i.once(Uq,()=>{i&&(this._streams.delete(i),i=void 0)}),i}};fg.FSWatcher=Iu;var sH=(r,e)=>{let t=new Iu(e);return t.add(r),t};fg.watch=sH});var bR=R((_z,vg)=>{"use strict";var fH=Object.prototype.hasOwnProperty,Ot="~";function wa(){}Object.create&&(wa.prototype=Object.create(null),new wa().__proto__||(Ot=!1));function dH(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function _R(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new dH(t,n||r,i),o=Ot?Ot+e:e;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],s]:r._events[o].push(s):(r._events[o]=s,r._eventsCount++),r}function qu(r,e){--r._eventsCount===0?r._events=new wa:delete r._events[e]}function Et(){this._events=new wa,this._eventsCount=0}Et.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)fH.call(t,n)&&e.push(Ot?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Et.prototype.listeners=function(e){var t=Ot?Ot+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o};Et.prototype.listenerCount=function(e){var t=Ot?Ot+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Et.prototype.emit=function(e,t,n,i,s,o){var a=Ot?Ot+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,p,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,s),!0;case 6:return c.fn.call(c.context,t,n,i,s,o),!0}for(f=1,p=new Array(l-1);f<l;f++)p[f-1]=arguments[f];c.fn.apply(c.context,p)}else{var h=c.length,v;for(f=0;f<h;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,i);break;default:if(!p)for(v=1,p=new Array(l-1);v<l;v++)p[v-1]=arguments[v];c[f].fn.apply(c[f].context,p)}}return!0};Et.prototype.on=function(e,t,n){return _R(this,e,t,n,!1)};Et.prototype.once=function(e,t,n){return _R(this,e,t,n,!0)};Et.prototype.removeListener=function(e,t,n,i){var s=Ot?Ot+e:e;if(!this._events[s])return this;if(!t)return qu(this,s),this;var o=this._events[s];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&qu(this,s);else{for(var a=0,c=[],l=o.length;a<l;a++)(o[a].fn!==t||i&&!o[a].once||n&&o[a].context!==n)&&c.push(o[a]);c.length?this._events[s]=c.length===1?c[0]:c:qu(this,s)}return this};Et.prototype.removeAllListeners=function(e){var t;return e?(t=Ot?Ot+e:e,this._events[t]&&qu(this,t)):(this._events=new wa,this._eventsCount=0),this};Et.prototype.off=Et.prototype.removeListener;Et.prototype.addListener=Et.prototype.on;Et.prefixed=Ot;Et.EventEmitter=Et;typeof vg<"u"&&(vg.exports=Et)});var SR=R((bz,wR)=>{"use strict";wR.exports=function(e,t){if(t=t.split(":")[0],e=+e,!e)return!1;switch(t){case"http":case"ws":return e!==80;case"https":case"wss":return e!==443;case"ftp":return e!==21;case"gopher":return e!==70;case"file":return!1}return e!==0}});var Hu=R(TR=>{var wn=TR,hH=require("url"),ER=require("util")._extend,mH=SR(),gH=/(^|,)\s*upgrade\s*($|,)/i,yg=/^https|wss/;wn.isSSL=yg;wn.setupOutgoing=function(r,e,t,n){r.port=e[n||"target"].port||(yg.test(e[n||"target"].protocol)?443:80),["host","hostname","socketPath","pfx","key","passphrase","cert","ca","ciphers","secureProtocol"].forEach(function(a){r[a]=e[n||"target"][a]}),r.method=e.method||t.method,r.headers=ER({},t.headers),e.headers&&ER(r.headers,e.headers),e.auth&&(r.auth=e.auth),e.ca&&(r.ca=e.ca),yg.test(e[n||"target"].protocol)&&(r.rejectUnauthorized=typeof e.secure>"u"?!0:e.secure),r.agent=e.agent||!1,r.localAddress=e.localAddress,r.agent||(r.headers=r.headers||{},(typeof r.headers.connection!="string"||!gH.test(r.headers.connection))&&(r.headers.connection="close"));var i=e[n||"target"],s=i&&e.prependPath!==!1&&i.path||"",o=e.toProxy?t.url:hH.parse(t.url).path||"";return o=e.ignorePath?"":o,r.path=wn.urlJoin(s,o),e.changeOrigin&&(r.headers.host=mH(r.port,e[n||"target"].protocol)&&!vH(r.host)?r.host+":"+r.port:r.host),r};wn.setupSocket=function(r){return r.setTimeout(0),r.setNoDelay(!0),r.setKeepAlive(!0,0),r};wn.getPort=function(r){var e=r.headers.host?r.headers.host.match(/:(\d+)/):"";return e?e[1]:wn.hasEncryptedConnection(r)?"443":"80"};wn.hasEncryptedConnection=function(r){return!!(r.connection.encrypted||r.connection.pair)};wn.urlJoin=function(){var r=Array.prototype.slice.call(arguments),e=r.length-1,t=r[e],n=t.split("?"),i;return r[e]=n.shift(),i=[r.filter(Boolean).join("/").replace(/\/+/g,"/").replace("http:/","http://").replace("https:/","https://")],i.push.apply(i,n),i.join("?")};wn.rewriteCookieProperty=function r(e,t,n){return Array.isArray(e)?e.map(function(i){return r(i,t,n)}):e.replace(new RegExp("(;\\s*"+n+"=)([^;]+)","i"),function(i,s,o){var a;if(o in t)a=t[o];else if("*"in t)a=t["*"];else return i;return a?s+a:""})};function vH(r){return!!~r.indexOf(":")}});var kR=R((Sz,RR)=>{var CR=require("url"),AR=Hu(),yH=/^201|30(1|2|7|8)$/;RR.exports={removeChunked:function(e,t,n){e.httpVersion==="1.0"&&delete n.headers["transfer-encoding"]},setConnection:function(e,t,n){e.httpVersion==="1.0"?n.headers.connection=e.headers.connection||"close":e.httpVersion!=="2.0"&&!n.headers.connection&&(n.headers.connection=e.headers.connection||"keep-alive")},setRedirectHostRewrite:function(e,t,n,i){if((i.hostRewrite||i.autoRewrite||i.protocolRewrite)&&n.headers.location&&yH.test(n.statusCode)){var s=CR.parse(i.target),o=CR.parse(n.headers.location);if(s.host!=o.host)return;i.hostRewrite?o.host=i.hostRewrite:i.autoRewrite&&(o.host=e.headers.host),i.protocolRewrite&&(o.protocol=i.protocolRewrite),n.headers.location=o.format()}},writeHeaders:function(e,t,n,i){var s=i.cookieDomainRewrite,o=i.cookiePathRewrite,a=i.preserveHeaderKeyCase,c,l=function(h,v){v!=null&&(s&&h.toLowerCase()==="set-cookie"&&(v=AR.rewriteCookieProperty(v,s,"domain")),o&&h.toLowerCase()==="set-cookie"&&(v=AR.rewriteCookieProperty(v,o,"path")),t.setHeader(String(h).trim(),v))};if(typeof s=="string"&&(s={"*":s}),typeof o=="string"&&(o={"*":o}),a&&n.rawHeaders!=null){c={};for(var p=0;p<n.rawHeaders.length;p+=2){var f=n.rawHeaders[p];c[f.toLowerCase()]=f}}Object.keys(n.headers).forEach(function(h){var v=n.headers[h];a&&c&&(h=c[h]||h),l(h,v)})},writeStatusCode:function(e,t,n){n.statusMessage?(t.statusCode=n.statusCode,t.statusMessage=n.statusMessage):t.statusCode=n.statusCode}}});var MR=R((Ez,OR)=>{var Sa;OR.exports=function(){if(!Sa){try{Sa=Ce()("follow-redirects")}catch{}typeof Sa!="function"&&(Sa=function(){})}Sa.apply(null,arguments)}});var DR=R((Tz,Og)=>{var Ta=require("url"),Ea=Ta.URL,xH=require("http"),_H=require("https"),Sg=require("stream").Writable,Eg=require("assert"),PR=MR();(function(){var e=typeof process<"u",t=typeof window<"u"&&typeof document<"u",n=Ci(Error.captureStackTrace);!e&&(t||!n)&&console.warn("The follow-redirects package should be excluded from browser builds.")})();var Tg=!1;try{Eg(new Ea(""))}catch(r){Tg=r.code==="ERR_INVALID_URL"}var bH=["Authorization","Proxy-Authorization","Cookie"],wH=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],Cg=["abort","aborted","connect","error","socket","timeout"],Ag=Object.create(null);Cg.forEach(function(r){Ag[r]=function(e,t,n){this._redirectable.emit(r,e,t,n)}});var _g=Ca("ERR_INVALID_URL","Invalid URL",TypeError),bg=Ca("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),SH=Ca("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",bg),EH=Ca("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),TH=Ca("ERR_STREAM_WRITE_AFTER_END","write after end"),CH=Sg.prototype.destroy||NR;function Ht(r,e){Sg.call(this),this._sanitizeOptions(r),this._options=r,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],e&&this.on("response",e);var t=this;this._onNativeResponse=function(n){try{t._processResponse(n)}catch(i){t.emit("error",i instanceof bg?i:new bg({cause:i}))}},this._headerFilter=new RegExp("^(?:"+bH.concat(r.sensitiveHeaders).map(PH).join("|")+")$","i"),this._performRequest()}Ht.prototype=Object.create(Sg.prototype);Ht.prototype.abort=function(){kg(this._currentRequest),this._currentRequest.abort(),this.emit("abort")};Ht.prototype.destroy=function(r){return kg(this._currentRequest,r),CH.call(this,r),this};Ht.prototype.write=function(r,e,t){if(this._ending)throw new TH;if(!Ti(r)&&!OH(r))throw new TypeError("data should be a string, Buffer or Uint8Array");if(Ci(e)&&(t=e,e=null),r.length===0){t&&t();return}this._requestBodyLength+r.length<=this._options.maxBodyLength?(this._requestBodyLength+=r.length,this._requestBodyBuffers.push({data:r,encoding:e}),this._currentRequest.write(r,e,t)):(this.emit("error",new EH),this.abort())};Ht.prototype.end=function(r,e,t){if(Ci(r)?(t=r,r=e=null):Ci(e)&&(t=e,e=null),!r)this._ended=this._ending=!0,this._currentRequest.end(null,null,t);else{var n=this,i=this._currentRequest;this.write(r,e,function(){n._ended=!0,i.end(null,null,t)}),this._ending=!0}};Ht.prototype.setHeader=function(r,e){this._options.headers[r]=e,this._currentRequest.setHeader(r,e)};Ht.prototype.removeHeader=function(r){delete this._options.headers[r],this._currentRequest.removeHeader(r)};Ht.prototype.setTimeout=function(r,e){var t=this;function n(o){o.setTimeout(r),o.removeListener("timeout",o.destroy),o.addListener("timeout",o.destroy)}function i(o){t._timeout&&clearTimeout(t._timeout),t._timeout=setTimeout(function(){t.emit("timeout"),s()},r),n(o)}function s(){t._timeout&&(clearTimeout(t._timeout),t._timeout=null),t.removeListener("abort",s),t.removeListener("error",s),t.removeListener("response",s),t.removeListener("close",s),e&&t.removeListener("timeout",e),t.socket||t._currentRequest.removeListener("socket",i)}return e&&this.on("timeout",e),this.socket?i(this.socket):this._currentRequest.once("socket",i),this.on("socket",n),this.on("abort",s),this.on("error",s),this.on("response",s),this.on("close",s),this};["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(r){Ht.prototype[r]=function(e,t){return this._currentRequest[r](e,t)}});["aborted","connection","socket"].forEach(function(r){Object.defineProperty(Ht.prototype,r,{get:function(){return this._currentRequest[r]}})});Ht.prototype._sanitizeOptions=function(r){if(r.headers||(r.headers={}),kH(r.sensitiveHeaders)||(r.sensitiveHeaders=[]),r.host&&(r.hostname||(r.hostname=r.host),delete r.host),!r.pathname&&r.path){var e=r.path.indexOf("?");e<0?r.pathname=r.path:(r.pathname=r.path.substring(0,e),r.search=r.path.substring(e))}};Ht.prototype._performRequest=function(){var r=this._options.protocol,e=this._options.nativeProtocols[r];if(!e)throw new TypeError("Unsupported protocol "+r);if(this._options.agents){var t=r.slice(0,-1);this._options.agent=this._options.agents[t]}var n=this._currentRequest=e.request(this._options,this._onNativeResponse);n._redirectable=this;for(var i of Cg)n.on(i,Ag[i]);if(this._currentUrl=/^\//.test(this._options.path)?Ta.format(this._options):this._options.path,this._isRedirect){var s=0,o=this,a=this._requestBodyBuffers;(function c(l){if(n===o._currentRequest)if(l)o.emit("error",l);else if(s<a.length){var p=a[s++];n.finished||n.write(p.data,p.encoding,c)}else o._ended&&n.end()})()}};Ht.prototype._processResponse=function(r){var e=r.statusCode;this._options.trackRedirects&&this._redirects.push({url:this._currentUrl,headers:r.headers,statusCode:e});var t=r.headers.location;if(!t||this._options.followRedirects===!1||e<300||e>=400){r.responseUrl=this._currentUrl,r.redirects=this._redirects,this.emit("response",r),this._requestBodyBuffers=[];return}if(kg(this._currentRequest),r.destroy(),++this._redirectCount>this._options.maxRedirects)throw new SH;var n,i=this._options.beforeRedirect;i&&(n=Object.assign({Host:r.req.getHeader("host")},this._options.headers));var s=this._options.method;((e===301||e===302)&&this._options.method==="POST"||e===303&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],xg(/^content-/i,this._options.headers));var o=xg(/^host$/i,this._options.headers),a=Rg(this._currentUrl),c=o||a.host,l=/^\w+:/.test(t)?this._currentUrl:Ta.format(Object.assign(a,{host:c})),p=AH(t,l);if(PR("redirecting to",p.href),this._isRedirect=!0,wg(p,this._options),(p.protocol!==a.protocol&&p.protocol!=="https:"||p.host!==c&&!RH(p.host,c))&&xg(this._headerFilter,this._options.headers),Ci(i)){var f={headers:r.headers,statusCode:e},h={url:l,method:s,headers:n};i(this._options,f,h),this._sanitizeOptions(this._options)}this._performRequest()};function IR(r){var e={maxRedirects:21,maxBodyLength:10485760},t={};return Object.keys(r).forEach(function(n){var i=n+":",s=t[i]=r[n],o=e[n]=Object.create(s);function a(l,p,f){return MH(l)?l=wg(l):Ti(l)?l=wg(Rg(l)):(f=p,p=LR(l),l={protocol:i}),Ci(p)&&(f=p,p=null),p=Object.assign({maxRedirects:e.maxRedirects,maxBodyLength:e.maxBodyLength},l,p),p.nativeProtocols=t,!Ti(p.host)&&!Ti(p.hostname)&&(p.hostname="::1"),Eg.equal(p.protocol,i,"protocol mismatch"),PR("options",p),new Ht(p,f)}function c(l,p,f){var h=o.request(l,p,f);return h.end(),h}Object.defineProperties(o,{request:{value:a,configurable:!0,enumerable:!0,writable:!0},get:{value:c,configurable:!0,enumerable:!0,writable:!0}})}),e}function NR(){}function Rg(r){var e;if(Tg)e=new Ea(r);else if(e=LR(Ta.parse(r)),!Ti(e.protocol))throw new _g({input:r});return e}function AH(r,e){return Tg?new Ea(r,e):Rg(Ta.resolve(e,r))}function LR(r){if(/^\[/.test(r.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(r.hostname))throw new _g({input:r.href||r});if(/^\[/.test(r.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(r.host))throw new _g({input:r.href||r});return r}function wg(r,e){var t=e||{};for(var n of wH)t[n]=r[n];return t.hostname.startsWith("[")&&(t.hostname=t.hostname.slice(1,-1)),t.port!==""&&(t.port=Number(t.port)),t.path=t.search?t.pathname+t.search:t.pathname,t}function xg(r,e){var t;for(var n in e)r.test(n)&&(t=e[n],delete e[n]);return t===null||typeof t>"u"?void 0:String(t).trim()}function Ca(r,e,t){function n(i){Ci(Error.captureStackTrace)&&Error.captureStackTrace(this,this.constructor),Object.assign(this,i||{}),this.code=r,this.message=this.cause?e+": "+this.cause.message:e}return n.prototype=new(t||Error),Object.defineProperties(n.prototype,{constructor:{value:n,enumerable:!1},name:{value:"Error ["+r+"]",enumerable:!1}}),n}function kg(r,e){for(var t of Cg)r.removeListener(t,Ag[t]);r.on("error",NR),r.destroy(e)}function RH(r,e){Eg(Ti(r)&&Ti(e));var t=r.length-e.length-1;return t>0&&r[t]==="."&&r.endsWith(e)}function kH(r){return r instanceof Array}function Ti(r){return typeof r=="string"||r instanceof String}function Ci(r){return typeof r=="function"}function OH(r){return typeof r=="object"&&"length"in r}function MH(r){return Ea&&r instanceof Ea}function PH(r){return r.replace(/[\]\\/()*+?.$]/g,"\\$&")}Og.exports=IR({http:xH,https:_H});Og.exports.wrap=IR});var jR=R((Cz,BR)=>{var IH=require("http"),NH=require("https"),Aa=kR(),$u=Hu(),LH=DR();Aa=Object.keys(Aa).map(function(r){return Aa[r]});var DH={http:IH,https:NH};BR.exports={deleteLength:function(e,t,n){(e.method==="DELETE"||e.method==="OPTIONS")&&!e.headers["content-length"]&&(e.headers["content-length"]="0",delete e.headers["transfer-encoding"])},timeout:function(e,t,n){n.timeout&&e.socket.setTimeout(n.timeout)},XHeaders:function(e,t,n){if(n.xfwd){var i=e.isSpdy||$u.hasEncryptedConnection(e),s={for:e.connection.remoteAddress||e.socket.remoteAddress,port:$u.getPort(e),proto:i?"https":"http"};["for","port","proto"].forEach(function(o){e.headers["x-forwarded-"+o]=(e.headers["x-forwarded-"+o]||"")+(e.headers["x-forwarded-"+o]?",":"")+s[o]}),e.headers["x-forwarded-host"]=e.headers["x-forwarded-host"]||e.headers.host||""}},stream:function(e,t,n,i,s,o){s.emit("start",e,t,n.target||n.forward);var a=n.followRedirects?LH:DH,c=a.http,l=a.https;if(n.forward){var p=(n.forward.protocol==="https:"?l:c).request($u.setupOutgoing(n.ssl||{},n,e,"forward")),f=x(p,n.forward);if(e.on("error",f),p.on("error",f),(n.buffer||e).pipe(p),!n.target)return t.end()}var h=(n.target.protocol==="https:"?l:c).request($u.setupOutgoing(n.ssl||{},n,e));h.on("socket",function(S){s&&!h.getHeader("expect")&&s.emit("proxyReq",h,e,t,n)}),n.proxyTimeout&&h.setTimeout(n.proxyTimeout,function(){h.abort()}),e.on("aborted",function(){h.abort()});var v=x(h,n.target);e.on("error",v),h.on("error",v);function x(S,A){return function(P){if(e.socket.destroyed&&P.code==="ECONNRESET")return s.emit("econnreset",P,e,t,A),S.abort();o?o(P,e,t,A):s.emit("error",P,e,t,A)}}(n.buffer||e).pipe(h),h.on("response",function(S){if(s&&s.emit("proxyRes",S,e,t),!t.headersSent&&!n.selfHandleResponse)for(var A=0;A<Aa.length&&!Aa[A](e,t,S,n);A++);t.finished?s&&s.emit("end",e,t,S):(S.on("end",function(){s&&s.emit("end",e,t,S)}),n.selfHandleResponse||S.pipe(t))})}}});var UR=R((Az,FR)=>{var BH=require("http"),jH=require("https"),Xs=Hu();FR.exports={checkMethodAndHeader:function(e,t){if(e.method!=="GET"||!e.headers.upgrade||e.headers.upgrade.toLowerCase()!=="websocket")return t.destroy(),!0},XHeaders:function(e,t,n){if(n.xfwd){var i={for:e.connection.remoteAddress||e.socket.remoteAddress,port:Xs.getPort(e),proto:Xs.hasEncryptedConnection(e)?"wss":"ws"};["for","port","proto"].forEach(function(s){e.headers["x-forwarded-"+s]=(e.headers["x-forwarded-"+s]||"")+(e.headers["x-forwarded-"+s]?",":"")+i[s]})}},stream:function(e,t,n,i,s,o){var a=function(p,f){return Object.keys(f).reduce(function(h,v){var x=f[v];if(!Array.isArray(x))return h.push(v+": "+x),h;for(var S=0;S<x.length;S++)h.push(v+": "+x[S]);return h},[p]).join(`\r
101
+ `);let{connect:l,buffered:p}=await c;if(e.emit("proxyConnect",l),this.emit("proxyConnect",l,e),l.statusCode===200)return e.once("socket",mF),t.secureEndpoint?(Zo("Upgrading socket connection to TLS"),V1.connect({...Y1(K1(t),"host","path","port"),socket:i})):i;i.destroy();let f=new au.Socket({writable:!1});return f.readable=!0,e.once("socket",h=>{Zo("Replaying proxy buffer for failed request"),(0,uF.default)(h.listenerCount("data")>0),h.push(p),h.push(null)}),f}};cu.protocols=["http","https"];hr.HttpsProxyAgent=cu;function mF(r){r.resume()}function Y1(r,...e){let t={},n;for(n in r)e.includes(n)||(t[n]=r[n]);return t}});var nT=R((UW,rT)=>{"use strict";var eT=require("url"),tT=require("https"),gF=lm(),lu=sm(),vF=cm(),Jt=ru(),yF=nm(),Q1=2419200,pm="",fm;function Qo(){}Qo.prototype.setGCMAPIKey=function(r){if(r===null){pm=null;return}if(typeof r>"u"||typeof r!="string"||r.length===0)throw new Error("The GCM API Key should be a non-empty string or null.");pm=r};Qo.prototype.setVapidDetails=function(r,e,t){if(arguments.length===1&&arguments[0]===null){fm=null;return}lu.validateSubject(r),lu.validatePublicKey(e),lu.validatePrivateKey(t),fm={subject:r,publicKey:e,privateKey:t}};Qo.prototype.generateRequestDetails=function(r,e,t){if(!r||!r.endpoint)throw new Error("You must pass in a subscription with at least an endpoint.");if(typeof r.endpoint!="string"||r.endpoint.length===0)throw new Error("The subscription endpoint must be a string with a valid URL.");if(e&&(typeof r!="object"||!r.keys||!r.keys.p256dh||!r.keys.auth))throw new Error("To send a message with a payload, the subscription must have 'auth' and 'p256dh' keys.");let n=pm,i=fm,s=Q1,o={},a=Jt.supportedContentEncodings.AES_128_GCM,c=Jt.supportedUrgency.NORMAL,l,p,f,h;if(t){let k=["headers","gcmAPIKey","vapidDetails","TTL","contentEncoding","urgency","topic","proxy","agent","timeout"],P=Object.keys(t);for(let I=0;I<P.length;I+=1){let B=P[I];if(!k.includes(B))throw new Error("'"+B+"' is an invalid option. The valid options are ['"+k.join("', '")+"'].")}if(t.headers){o=t.headers;let I=Object.keys(o).filter(function(B){return typeof t[B]<"u"});if(I.length>0)throw new Error("Duplicated headers defined ["+I.join(",")+"]. Please either define the header in thetop level options OR in the 'headers' key.")}if(t.gcmAPIKey&&(n=t.gcmAPIKey),t.vapidDetails!==void 0&&(i=t.vapidDetails),t.TTL!==void 0&&(s=Number(t.TTL),s<0))throw new Error("TTL should be a number and should be at least 0");if(t.contentEncoding)if(t.contentEncoding===Jt.supportedContentEncodings.AES_128_GCM||t.contentEncoding===Jt.supportedContentEncodings.AES_GCM)a=t.contentEncoding;else throw new Error("Unsupported content encoding specified.");if(t.urgency)if(t.urgency===Jt.supportedUrgency.VERY_LOW||t.urgency===Jt.supportedUrgency.LOW||t.urgency===Jt.supportedUrgency.NORMAL||t.urgency===Jt.supportedUrgency.HIGH)c=t.urgency;else throw new Error("Unsupported urgency specified.");if(t.topic){if(!yF.validate(t.topic))throw new Error("Unsupported characters set use the URL or filename-safe Base64 characters set");if(t.topic.length>32)throw new Error("use maximum of 32 characters from the URL or filename-safe Base64 characters set");l=t.topic}t.proxy&&(typeof t.proxy=="string"||typeof t.proxy.host=="string"?p=t.proxy:console.warn("Attempt to use proxy option, but invalid type it should be a string or proxy options object.")),t.agent&&(t.agent instanceof tT.Agent?(p&&console.warn("Agent option will be ignored because proxy option is defined."),f=t.agent):console.warn("Wrong type for the agent option, it should be an instance of https.Agent.")),typeof t.timeout=="number"&&(h=t.timeout)}typeof s>"u"&&(s=Q1);let v={method:"POST",headers:{TTL:s}};Object.keys(o).forEach(function(k){v.headers[k]=o[k]});let x=null;if(e){let k=vF.encrypt(r.keys.p256dh,r.keys.auth,e,a);v.headers["Content-Length"]=k.cipherText.length,v.headers["Content-Type"]="application/octet-stream",a===Jt.supportedContentEncodings.AES_128_GCM?v.headers["Content-Encoding"]=Jt.supportedContentEncodings.AES_128_GCM:a===Jt.supportedContentEncodings.AES_GCM&&(v.headers["Content-Encoding"]=Jt.supportedContentEncodings.AES_GCM,v.headers.Encryption="salt="+k.salt,v.headers["Crypto-Key"]="dh="+k.localPublicKey.toString("base64url")),x=k.cipherText}else v.headers["Content-Length"]=0;let S=r.endpoint.startsWith("https://android.googleapis.com/gcm/send"),A=r.endpoint.startsWith("https://fcm.googleapis.com/fcm/send");if(S)n?v.headers.Authorization="key="+n:console.warn("Attempt to send push notification to GCM endpoint, but no GCM key is defined. Please use setGCMApiKey() or add 'gcmAPIKey' as an option.");else if(i){let k=eT.parse(r.endpoint),P=k.protocol+"//"+k.host,I=lu.getVapidHeaders(P,i.subject,i.publicKey,i.privateKey,a);v.headers.Authorization=I.Authorization,a===Jt.supportedContentEncodings.AES_GCM&&(v.headers["Crypto-Key"]?v.headers["Crypto-Key"]+=";"+I["Crypto-Key"]:v.headers["Crypto-Key"]=I["Crypto-Key"])}else A&&n&&(v.headers.Authorization="key="+n);return v.headers.Urgency=c,l&&(v.headers.Topic=l),v.body=x,v.endpoint=r.endpoint,p&&(v.proxy=p),f&&(v.agent=f),h&&(v.timeout=h),v};Qo.prototype.sendNotification=function(r,e,t){let n;try{n=this.generateRequestDetails(r,e,t)}catch(i){return Promise.reject(i)}return new Promise(function(i,s){let o={},a=eT.parse(n.endpoint);if(o.hostname=a.hostname,o.port=a.port,o.path=a.path,o.headers=n.headers,o.method=n.method,n.timeout&&(o.timeout=n.timeout),n.agent&&(o.agent=n.agent),n.proxy){let{HttpsProxyAgent:l}=Z1();o.agent=new l(n.proxy)}let c=tT.request(o,function(l){let p="";l.on("data",function(f){p+=f}),l.on("end",function(){l.statusCode<200||l.statusCode>299?s(new gF("Received unexpected response code",l.statusCode,l.headers,p,n.endpoint)):i({statusCode:l.statusCode,body:p,headers:l.headers})})});n.timeout&&c.on("timeout",function(){c.destroy(new Error("Socket timeout"))}),c.on("error",function(l){s(l)}),n.body&&c.write(n.body),c.end()})};rT.exports=Qo});var oT=R((qW,sT)=>{"use strict";var iT=sm(),xF=cm(),_F=nT(),bF=lm(),wF=ru(),ea=new _F;sT.exports={WebPushError:bF,supportedContentEncodings:wF.supportedContentEncodings,encrypt:xF.encrypt,getVapidHeaders:iT.getVapidHeaders,generateVAPIDKeys:iT.generateVAPIDKeys,setGCMAPIKey:ea.setGCMAPIKey,setVapidDetails:ea.setVapidDetails,generateRequestDetails:ea.generateRequestDetails,sendNotification:ea.sendNotification.bind(ea)}});var sa=R((yG,jT)=>{"use strict";var GF=require("path"),Gr="\\\\/",NT=`[^${Gr}]`,zF=0,yn="\\.",VF="\\+",KF="\\?",mu="\\/",YF="(?=.)",LT="[^/]",mm=`(?:${mu}|$)`,DT=`(?:^|${mu})`,gm=`${yn}{1,2}${mm}`,JF=`(?!${yn})`,XF=`(?!${DT}${gm})`,ZF=`(?!${yn}{0,1}${mm})`,QF=`(?!${gm})`,e3=`[^.${mu}]`,t3=`${LT}*?`,BT={DOT_LITERAL:yn,PLUS_LITERAL:VF,QMARK_LITERAL:KF,SLASH_LITERAL:mu,ONE_CHAR:YF,QMARK:LT,END_ANCHOR:mm,DOTS_SLASH:gm,NO_DOT:JF,NO_DOTS:XF,NO_DOT_SLASH:ZF,NO_DOTS_SLASH:QF,QMARK_NO_DOT:e3,STAR:t3,START_ANCHOR:DT},r3={...BT,SLASH_LITERAL:`[${Gr}]`,QMARK:NT,STAR:`${NT}*?`,DOTS_SLASH:`${yn}{1,2}(?:[${Gr}]|$)`,NO_DOT:`(?!${yn})`,NO_DOTS:`(?!(?:^|[${Gr}])${yn}{1,2}(?:[${Gr}]|$))`,NO_DOT_SLASH:`(?!${yn}{0,1}(?:[${Gr}]|$))`,NO_DOTS_SLASH:`(?!${yn}{1,2}(?:[${Gr}]|$))`,QMARK_NO_DOT:`[^.${Gr}]`,START_ANCHOR:`(?:^|[${Gr}])`,END_ANCHOR:`(?:[${Gr}]|$)`},n3={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};jT.exports={DEFAULT_MAX_EXTGLOB_RECURSION:zF,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:n3,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:GF.sep,extglobChars(r){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${r.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(r){return r===!0?r3:BT}}});var gu=R(Ut=>{"use strict";var i3=require("path"),s3=process.platform==="win32",{REGEX_BACKSLASH:o3,REGEX_REMOVE_BACKSLASH:a3,REGEX_SPECIAL_CHARS:c3,REGEX_SPECIAL_CHARS_GLOBAL:l3}=sa();Ut.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);Ut.hasRegexChars=r=>c3.test(r);Ut.isRegexChar=r=>r.length===1&&Ut.hasRegexChars(r);Ut.escapeRegex=r=>r.replace(l3,"\\$1");Ut.toPosixSlashes=r=>r.replace(o3,"/");Ut.removeBackslashes=r=>r.replace(a3,e=>e==="\\"?"":e);Ut.supportsLookbehinds=()=>{let r=process.version.slice(1).split(".").map(Number);return r.length===3&&r[0]>=9||r[0]===8&&r[1]>=10};Ut.isWindows=r=>r&&typeof r.windows=="boolean"?r.windows:s3===!0||i3.sep==="\\";Ut.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?Ut.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};Ut.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};Ut.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s}});var zT=R((_G,GT)=>{"use strict";var FT=gu(),{CHAR_ASTERISK:vm,CHAR_AT:u3,CHAR_BACKWARD_SLASH:oa,CHAR_COMMA:p3,CHAR_DOT:ym,CHAR_EXCLAMATION_MARK:xm,CHAR_FORWARD_SLASH:WT,CHAR_LEFT_CURLY_BRACE:_m,CHAR_LEFT_PARENTHESES:bm,CHAR_LEFT_SQUARE_BRACKET:f3,CHAR_PLUS:d3,CHAR_QUESTION_MARK:UT,CHAR_RIGHT_CURLY_BRACE:h3,CHAR_RIGHT_PARENTHESES:qT,CHAR_RIGHT_SQUARE_BRACKET:m3}=sa(),HT=r=>r===WT||r===oa,$T=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},g3=(r,e)=>{let t=e||{},n=r.length-1,i=t.parts===!0||t.scanToEnd===!0,s=[],o=[],a=[],c=r,l=-1,p=0,f=0,h=!1,v=!1,x=!1,S=!1,A=!1,k=!1,P=!1,I=!1,B=!1,V=!1,F=0,G,L,H={value:"",depth:0,isGlob:!1},T=()=>l>=n,u=()=>c.charCodeAt(l+1),m=()=>(G=L,c.charCodeAt(++l));for(;l<n;){L=m();let C;if(L===oa){P=H.backslashes=!0,L=m(),L===_m&&(k=!0);continue}if(k===!0||L===_m){for(F++;T()!==!0&&(L=m());){if(L===oa){P=H.backslashes=!0,m();continue}if(L===_m){F++;continue}if(k!==!0&&L===ym&&(L=m())===ym){if(h=H.isBrace=!0,x=H.isGlob=!0,V=!0,i===!0)continue;break}if(k!==!0&&L===p3){if(h=H.isBrace=!0,x=H.isGlob=!0,V=!0,i===!0)continue;break}if(L===h3&&(F--,F===0)){k=!1,h=H.isBrace=!0,V=!0;break}}if(i===!0)continue;break}if(L===WT){if(s.push(l),o.push(H),H={value:"",depth:0,isGlob:!1},V===!0)continue;if(G===ym&&l===p+1){p+=2;continue}f=l+1;continue}if(t.noext!==!0&&(L===d3||L===u3||L===vm||L===UT||L===xm)===!0&&u()===bm){if(x=H.isGlob=!0,S=H.isExtglob=!0,V=!0,L===xm&&l===p&&(B=!0),i===!0){for(;T()!==!0&&(L=m());){if(L===oa){P=H.backslashes=!0,L=m();continue}if(L===qT){x=H.isGlob=!0,V=!0;break}}continue}break}if(L===vm){if(G===vm&&(A=H.isGlobstar=!0),x=H.isGlob=!0,V=!0,i===!0)continue;break}if(L===UT){if(x=H.isGlob=!0,V=!0,i===!0)continue;break}if(L===f3){for(;T()!==!0&&(C=m());){if(C===oa){P=H.backslashes=!0,m();continue}if(C===m3){v=H.isBracket=!0,x=H.isGlob=!0,V=!0;break}}if(i===!0)continue;break}if(t.nonegate!==!0&&L===xm&&l===p){I=H.negated=!0,p++;continue}if(t.noparen!==!0&&L===bm){if(x=H.isGlob=!0,i===!0){for(;T()!==!0&&(L=m());){if(L===bm){P=H.backslashes=!0,L=m();continue}if(L===qT){V=!0;break}}continue}break}if(x===!0){if(V=!0,i===!0)continue;break}}t.noext===!0&&(S=!1,x=!1);let y=c,w="",g="";p>0&&(w=c.slice(0,p),c=c.slice(p),f-=p),y&&x===!0&&f>0?(y=c.slice(0,f),g=c.slice(f)):x===!0?(y="",g=c):y=c,y&&y!==""&&y!=="/"&&y!==c&&HT(y.charCodeAt(y.length-1))&&(y=y.slice(0,-1)),t.unescape===!0&&(g&&(g=FT.removeBackslashes(g)),y&&P===!0&&(y=FT.removeBackslashes(y)));let _={prefix:w,input:r,start:p,base:y,glob:g,isBrace:h,isBracket:v,isGlob:x,isExtglob:S,isGlobstar:A,negated:I,negatedExtglob:B};if(t.tokens===!0&&(_.maxDepth=0,HT(L)||o.push(H),_.tokens=o),t.parts===!0||t.tokens===!0){let C;for(let b=0;b<s.length;b++){let d=C?C+1:p,E=s[b],q=r.slice(d,E);t.tokens&&(b===0&&p!==0?(o[b].isPrefix=!0,o[b].value=w):o[b].value=q,$T(o[b]),_.maxDepth+=o[b].depth),(b!==0||q!=="")&&a.push(q),C=E}if(C&&C+1<r.length){let b=r.slice(C+1);a.push(b),t.tokens&&(o[o.length-1].value=b,$T(o[o.length-1]),_.maxDepth+=o[o.length-1].depth)}_.slashes=s,_.parts=a}return _};GT.exports=g3});var XT=R((bG,JT)=>{"use strict";var aa=sa(),St=gu(),{MAX_LENGTH:vu,POSIX_REGEX_SOURCE:v3,REGEX_NON_SPECIAL_CHARS:y3,REGEX_SPECIAL_CHARS_BACKREF:x3,REPLACEMENTS:VT}=aa,_3=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch{return r.map(i=>St.escapeRegex(i)).join("..")}return t},Us=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,KT=r=>{let e=[],t=0,n=0,i=0,s="",o=!1;for(let a of r){if(o===!0){s+=a,o=!1;continue}if(a==="\\"){s+=a,o=!0;continue}if(a==='"'){i=i===1?0:1,s+=a;continue}if(i===0){if(a==="[")t++;else if(a==="]"&&t>0)t--;else if(t===0){if(a==="(")n++;else if(a===")"&&n>0)n--;else if(a==="|"&&n===0){e.push(s),s="";continue}}}s+=a}return e.push(s),e},b3=r=>{let e=!1;for(let t of r){if(e===!0){e=!1;continue}if(t==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(t))return!1}return!0},YT=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(b3(e))return e.replace(/\\(.)/g,"$1")},w3=r=>{let e=r.map(YT).filter(Boolean);for(let t=0;t<e.length;t++)for(let n=t+1;n<e.length;n++){let i=e[t],s=e[n],o=i[0];if(!(!o||i!==o.repeat(i.length)||s!==o.repeat(s.length))&&(i===s||i.startsWith(s)||s.startsWith(i)))return!0}return!1},wm=(r,e=!0)=>{if(r[0]!=="+"&&r[0]!=="*"||r[1]!=="(")return;let t=0,n=0,i=0,s=!1;for(let o=1;o<r.length;o++){let a=r[o];if(s===!0){s=!1;continue}if(a==="\\"){s=!0;continue}if(a==='"'){i=i===1?0:1;continue}if(i!==1){if(a==="["){t++;continue}if(a==="]"&&t>0){t--;continue}if(!(t>0)){if(a==="("){n++;continue}if(a===")"&&(n--,n===0))return e===!0&&o!==r.length-1?void 0:{type:r[0],body:r.slice(2,o),end:o}}}}},S3=r=>{let e=0,t=[];for(;e<r.length;){let i=wm(r.slice(e),!1);if(!i||i.type!=="*")return;let s=KT(i.body).map(a=>a.trim());if(s.length!==1)return;let o=YT(s[0]);if(!o||o.length!==1)return;t.push(o),e+=i.end+1}return t.length<1?void 0:`${t.length===1?St.escapeRegex(t[0]):`[${t.map(i=>St.escapeRegex(i)).join("")}]`}*`},E3=r=>{let e=0,t=r.trim(),n=wm(t);for(;n;)e++,t=n.body.trim(),n=wm(t);return e},T3=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:aa.DEFAULT_MAX_EXTGLOB_RECURSION,n=KT(r).map(i=>i.trim());if(n.length>1&&(n.some(i=>i==="")||n.some(i=>/^[*?]+$/.test(i))||w3(n)))return{risky:!0};for(let i of n){let s=S3(i);if(s)return{risky:!0,safeOutput:s};if(E3(i)>t)return{risky:!0}}return{risky:!1}},Sm=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=VT[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(vu,t.maxLength):vu,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);let s={type:"bos",value:"",output:t.prepend||""},o=[s],a=t.capture?"":"?:",c=St.isWindows(e),l=aa.globChars(c),p=aa.extglobChars(l),{DOT_LITERAL:f,PLUS_LITERAL:h,SLASH_LITERAL:v,ONE_CHAR:x,DOTS_SLASH:S,NO_DOT:A,NO_DOT_SLASH:k,NO_DOTS_SLASH:P,QMARK:I,QMARK_NO_DOT:B,STAR:V,START_ANCHOR:F}=l,G=N=>`(${a}(?:(?!${F}${N.dot?S:f}).)*?)`,L=t.dot?"":A,H=t.dot?I:B,T=t.bash===!0?G(t):V;t.capture&&(T=`(${T})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let u={input:r,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};r=St.removePrefix(r,u),i=r.length;let m=[],y=[],w=[],g=s,_,C=()=>u.index===i-1,b=u.peek=(N=1)=>r[u.index+N],d=u.advance=()=>r[++u.index]||"",E=()=>r.slice(u.index+1),q=(N="",te=0)=>{u.consumed+=N,u.index+=te},O=N=>{u.output+=N.output!=null?N.output:N.value,q(N.value)},M=()=>{let N=1;for(;b()==="!"&&(b(2)!=="("||b(3)==="?");)d(),u.start++,N++;return N%2===0?!1:(u.negated=!0,u.start++,!0)},j=N=>{u[N]++,w.push(N)},z=N=>{u[N]--,w.pop()},U=N=>{if(g.type==="globstar"){let te=u.braces>0&&(N.type==="comma"||N.type==="brace"),D=N.extglob===!0||m.length&&(N.type==="pipe"||N.type==="paren");N.type!=="slash"&&N.type!=="paren"&&!te&&!D&&(u.output=u.output.slice(0,-g.output.length),g.type="star",g.value="*",g.output=T,u.output+=g.output)}if(m.length&&N.type!=="paren"&&(m[m.length-1].inner+=N.value),(N.value||N.output)&&O(N),g&&g.type==="text"&&N.type==="text"){g.value+=N.value,g.output=(g.output||"")+N.value;return}N.prev=g,o.push(N),g=N},Te=(N,te)=>{let D={...p[te],conditions:1,inner:""};D.prev=g,D.parens=u.parens,D.output=u.output,D.startIndex=u.index,D.tokensIndex=o.length;let W=(t.capture?"(":"")+D.open;j("parens"),U({type:N,value:te,output:u.output?"":x}),U({type:"paren",extglob:!0,value:d(),output:W}),m.push(D)},ne=N=>{let te=r.slice(N.startIndex,u.index+1),D=r.slice(N.startIndex+2,u.index),W=T3(D,t);if((N.type==="plus"||N.type==="star")&&W.risky){let J=W.safeOutput?(N.output?"":x)+(t.capture?`(${W.safeOutput})`:W.safeOutput):void 0,Tt=o[N.tokensIndex];Tt.type="text",Tt.value=te,Tt.output=J||St.escapeRegex(te);for(let oe=N.tokensIndex+1;oe<o.length;oe++)o[oe].value="",o[oe].output="",delete o[oe].suffix;u.output=N.output+Tt.output,u.backtrack=!0,U({type:"paren",extglob:!0,value:_,output:""}),z("parens");return}let se=N.close+(t.capture?")":""),Z;if(N.type==="negate"){let J=T;if(N.inner&&N.inner.length>1&&N.inner.includes("/")&&(J=G(t)),(J!==T||C()||/^\)+$/.test(E()))&&(se=N.close=`)$))${J}`),N.inner.includes("*")&&(Z=E())&&/^\.[^\\/.]+$/.test(Z)){let Tt=Sm(Z,{...e,fastpaths:!1}).output;se=N.close=`)${Tt})${J})`}N.prev.type==="bos"&&(u.negatedExtglob=!0)}U({type:"paren",extglob:!0,value:_,output:se}),z("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let N=!1,te=r.replace(x3,(D,W,se,Z,J,Tt)=>Z==="\\"?(N=!0,D):Z==="?"?W?W+Z+(J?I.repeat(J.length):""):Tt===0?H+(J?I.repeat(J.length):""):I.repeat(se.length):Z==="."?f.repeat(se.length):Z==="*"?W?W+Z+(J?T:""):T:W?D:`\\${D}`);return N===!0&&(t.unescape===!0?te=te.replace(/\\/g,""):te=te.replace(/\\+/g,D=>D.length%2===0?"\\\\":D?"\\":"")),te===r&&t.contains===!0?(u.output=r,u):(u.output=St.wrapOutput(te,u,e),u)}for(;!C();){if(_=d(),_==="\0")continue;if(_==="\\"){let D=b();if(D==="/"&&t.bash!==!0||D==="."||D===";")continue;if(!D){_+="\\",U({type:"text",value:_});continue}let W=/^\\+/.exec(E()),se=0;if(W&&W[0].length>2&&(se=W[0].length,u.index+=se,se%2!==0&&(_+="\\")),t.unescape===!0?_=d():_+=d(),u.brackets===0){U({type:"text",value:_});continue}}if(u.brackets>0&&(_!=="]"||g.value==="["||g.value==="[^")){if(t.posix!==!1&&_===":"){let D=g.value.slice(1);if(D.includes("[")&&(g.posix=!0,D.includes(":"))){let W=g.value.lastIndexOf("["),se=g.value.slice(0,W),Z=g.value.slice(W+2),J=v3[Z];if(J){g.value=se+J,u.backtrack=!0,d(),!s.output&&o.indexOf(g)===1&&(s.output=x);continue}}}(_==="["&&b()!==":"||_==="-"&&b()==="]")&&(_=`\\${_}`),_==="]"&&(g.value==="["||g.value==="[^")&&(_=`\\${_}`),t.posix===!0&&_==="!"&&g.value==="["&&(_="^"),g.value+=_,O({value:_});continue}if(u.quotes===1&&_!=='"'){_=St.escapeRegex(_),g.value+=_,O({value:_});continue}if(_==='"'){u.quotes=u.quotes===1?0:1,t.keepQuotes===!0&&U({type:"text",value:_});continue}if(_==="("){j("parens"),U({type:"paren",value:_});continue}if(_===")"){if(u.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Us("opening","("));let D=m[m.length-1];if(D&&u.parens===D.parens+1){ne(m.pop());continue}U({type:"paren",value:_,output:u.parens?")":"\\)"}),z("parens");continue}if(_==="["){if(t.nobracket===!0||!E().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Us("closing","]"));_=`\\${_}`}else j("brackets");U({type:"bracket",value:_});continue}if(_==="]"){if(t.nobracket===!0||g&&g.type==="bracket"&&g.value.length===1){U({type:"text",value:_,output:`\\${_}`});continue}if(u.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Us("opening","["));U({type:"text",value:_,output:`\\${_}`});continue}z("brackets");let D=g.value.slice(1);if(g.posix!==!0&&D[0]==="^"&&!D.includes("/")&&(_=`/${_}`),g.value+=_,O({value:_}),t.literalBrackets===!1||St.hasRegexChars(D))continue;let W=St.escapeRegex(g.value);if(u.output=u.output.slice(0,-g.value.length),t.literalBrackets===!0){u.output+=W,g.value=W;continue}g.value=`(${a}${W}|${g.value})`,u.output+=g.value;continue}if(_==="{"&&t.nobrace!==!0){j("braces");let D={type:"brace",value:_,output:"(",outputIndex:u.output.length,tokensIndex:u.tokens.length};y.push(D),U(D);continue}if(_==="}"){let D=y[y.length-1];if(t.nobrace===!0||!D){U({type:"text",value:_,output:_});continue}let W=")";if(D.dots===!0){let se=o.slice(),Z=[];for(let J=se.length-1;J>=0&&(o.pop(),se[J].type!=="brace");J--)se[J].type!=="dots"&&Z.unshift(se[J].value);W=_3(Z,t),u.backtrack=!0}if(D.comma!==!0&&D.dots!==!0){let se=u.output.slice(0,D.outputIndex),Z=u.tokens.slice(D.tokensIndex);D.value=D.output="\\{",_=W="\\}",u.output=se;for(let J of Z)u.output+=J.output||J.value}U({type:"brace",value:_,output:W}),z("braces"),y.pop();continue}if(_==="|"){m.length>0&&m[m.length-1].conditions++,U({type:"text",value:_});continue}if(_===","){let D=_,W=y[y.length-1];W&&w[w.length-1]==="braces"&&(W.comma=!0,D="|"),U({type:"comma",value:_,output:D});continue}if(_==="/"){if(g.type==="dot"&&u.index===u.start+1){u.start=u.index+1,u.consumed="",u.output="",o.pop(),g=s;continue}U({type:"slash",value:_,output:v});continue}if(_==="."){if(u.braces>0&&g.type==="dot"){g.value==="."&&(g.output=f);let D=y[y.length-1];g.type="dots",g.output+=_,g.value+=_,D.dots=!0;continue}if(u.braces+u.parens===0&&g.type!=="bos"&&g.type!=="slash"){U({type:"text",value:_,output:f});continue}U({type:"dot",value:_,output:f});continue}if(_==="?"){if(!(g&&g.value==="(")&&t.noextglob!==!0&&b()==="("&&b(2)!=="?"){Te("qmark",_);continue}if(g&&g.type==="paren"){let W=b(),se=_;if(W==="<"&&!St.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(g.value==="("&&!/[!=<:]/.test(W)||W==="<"&&!/<([!=]|\w+>)/.test(E()))&&(se=`\\${_}`),U({type:"text",value:_,output:se});continue}if(t.dot!==!0&&(g.type==="slash"||g.type==="bos")){U({type:"qmark",value:_,output:B});continue}U({type:"qmark",value:_,output:I});continue}if(_==="!"){if(t.noextglob!==!0&&b()==="("&&(b(2)!=="?"||!/[!=<:]/.test(b(3)))){Te("negate",_);continue}if(t.nonegate!==!0&&u.index===0){M();continue}}if(_==="+"){if(t.noextglob!==!0&&b()==="("&&b(2)!=="?"){Te("plus",_);continue}if(g&&g.value==="("||t.regex===!1){U({type:"plus",value:_,output:h});continue}if(g&&(g.type==="bracket"||g.type==="paren"||g.type==="brace")||u.parens>0){U({type:"plus",value:_});continue}U({type:"plus",value:h});continue}if(_==="@"){if(t.noextglob!==!0&&b()==="("&&b(2)!=="?"){U({type:"at",extglob:!0,value:_,output:""});continue}U({type:"text",value:_});continue}if(_!=="*"){(_==="$"||_==="^")&&(_=`\\${_}`);let D=y3.exec(E());D&&(_+=D[0],u.index+=D[0].length),U({type:"text",value:_});continue}if(g&&(g.type==="globstar"||g.star===!0)){g.type="star",g.star=!0,g.value+=_,g.output=T,u.backtrack=!0,u.globstar=!0,q(_);continue}let N=E();if(t.noextglob!==!0&&/^\([^?]/.test(N)){Te("star",_);continue}if(g.type==="star"){if(t.noglobstar===!0){q(_);continue}let D=g.prev,W=D.prev,se=D.type==="slash"||D.type==="bos",Z=W&&(W.type==="star"||W.type==="globstar");if(t.bash===!0&&(!se||N[0]&&N[0]!=="/")){U({type:"star",value:_,output:""});continue}let J=u.braces>0&&(D.type==="comma"||D.type==="brace"),Tt=m.length&&(D.type==="pipe"||D.type==="paren");if(!se&&D.type!=="paren"&&!J&&!Tt){U({type:"star",value:_,output:""});continue}for(;N.slice(0,3)==="/**";){let oe=r[u.index+4];if(oe&&oe!=="/")break;N=N.slice(3),q("/**",3)}if(D.type==="bos"&&C()){g.type="globstar",g.value+=_,g.output=G(t),u.output=g.output,u.globstar=!0,q(_);continue}if(D.type==="slash"&&D.prev.type!=="bos"&&!Z&&C()){u.output=u.output.slice(0,-(D.output+g.output).length),D.output=`(?:${D.output}`,g.type="globstar",g.output=G(t)+(t.strictSlashes?")":"|$)"),g.value+=_,u.globstar=!0,u.output+=D.output+g.output,q(_);continue}if(D.type==="slash"&&D.prev.type!=="bos"&&N[0]==="/"){let oe=N[1]!==void 0?"|$":"";u.output=u.output.slice(0,-(D.output+g.output).length),D.output=`(?:${D.output}`,g.type="globstar",g.output=`${G(t)}${v}|${v}${oe})`,g.value+=_,u.output+=D.output+g.output,u.globstar=!0,q(_+d()),U({type:"slash",value:"/",output:""});continue}if(D.type==="bos"&&N[0]==="/"){g.type="globstar",g.value+=_,g.output=`(?:^|${v}|${G(t)}${v})`,u.output=g.output,u.globstar=!0,q(_+d()),U({type:"slash",value:"/",output:""});continue}u.output=u.output.slice(0,-g.output.length),g.type="globstar",g.output=G(t),g.value+=_,u.output+=g.output,u.globstar=!0,q(_);continue}let te={type:"star",value:_,output:T};if(t.bash===!0){te.output=".*?",(g.type==="bos"||g.type==="slash")&&(te.output=L+te.output),U(te);continue}if(g&&(g.type==="bracket"||g.type==="paren")&&t.regex===!0){te.output=_,U(te);continue}(u.index===u.start||g.type==="slash"||g.type==="dot")&&(g.type==="dot"?(u.output+=k,g.output+=k):t.dot===!0?(u.output+=P,g.output+=P):(u.output+=L,g.output+=L),b()!=="*"&&(u.output+=x,g.output+=x)),U(te)}for(;u.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Us("closing","]"));u.output=St.escapeLast(u.output,"["),z("brackets")}for(;u.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Us("closing",")"));u.output=St.escapeLast(u.output,"("),z("parens")}for(;u.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Us("closing","}"));u.output=St.escapeLast(u.output,"{"),z("braces")}if(t.strictSlashes!==!0&&(g.type==="star"||g.type==="bracket")&&U({type:"maybe_slash",value:"",output:`${v}?`}),u.backtrack===!0){u.output="";for(let N of u.tokens)u.output+=N.output!=null?N.output:N.value,N.suffix&&(u.output+=N.suffix)}return u};Sm.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(vu,t.maxLength):vu,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=VT[r]||r;let s=St.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:c,DOTS_SLASH:l,NO_DOT:p,NO_DOTS:f,NO_DOTS_SLASH:h,STAR:v,START_ANCHOR:x}=aa.globChars(s),S=t.dot?f:p,A=t.dot?h:p,k=t.capture?"":"?:",P={negated:!1,prefix:""},I=t.bash===!0?".*?":v;t.capture&&(I=`(${I})`);let B=L=>L.noglobstar===!0?I:`(${k}(?:(?!${x}${L.dot?l:o}).)*?)`,V=L=>{switch(L){case"*":return`${S}${c}${I}`;case".*":return`${o}${c}${I}`;case"*.*":return`${S}${I}${o}${c}${I}`;case"*/*":return`${S}${I}${a}${c}${A}${I}`;case"**":return S+B(t);case"**/*":return`(?:${S}${B(t)}${a})?${A}${c}${I}`;case"**/*.*":return`(?:${S}${B(t)}${a})?${A}${I}${o}${c}${I}`;case"**/.*":return`(?:${S}${B(t)}${a})?${o}${c}${I}`;default:{let H=/^(.*?)\.(\w+)$/.exec(L);if(!H)return;let T=V(H[1]);return T?T+o+H[2]:void 0}}},F=St.removePrefix(r,P),G=V(F);return G&&t.strictSlashes!==!0&&(G+=`${a}?`),G};JT.exports=Sm});var QT=R((wG,ZT)=>{"use strict";var C3=require("path"),A3=zT(),Em=XT(),Tm=gu(),R3=sa(),k3=r=>r&&typeof r=="object"&&!Array.isArray(r),ke=(r,e,t=!1)=>{if(Array.isArray(r)){let p=r.map(h=>ke(h,e,t));return h=>{for(let v of p){let x=v(h);if(x)return x}return!1}}let n=k3(r)&&r.tokens&&r.input;if(r===""||typeof r!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=Tm.isWindows(e),o=n?ke.compileRe(r,e):ke.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let p={...e,ignore:null,onMatch:null,onResult:null};c=ke(i.ignore,p,t)}let l=(p,f=!1)=>{let{isMatch:h,match:v,output:x}=ke.test(p,o,e,{glob:r,posix:s}),S={glob:r,state:a,regex:o,posix:s,input:p,output:x,match:v,isMatch:h};return typeof i.onResult=="function"&&i.onResult(S),h===!1?(S.isMatch=!1,f?S:!1):c(p)?(typeof i.onIgnore=="function"&&i.onIgnore(S),S.isMatch=!1,f?S:!1):(typeof i.onMatch=="function"&&i.onMatch(S),f?S:!0)};return t&&(l.state=a),l};ke.test=(r,e,t,{glob:n,posix:i}={})=>{if(typeof r!="string")throw new TypeError("Expected input to be a string");if(r==="")return{isMatch:!1,output:""};let s=t||{},o=s.format||(i?Tm.toPosixSlashes:null),a=r===n,c=a&&o?o(r):r;return a===!1&&(c=o?o(r):r,a=c===n),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=ke.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};ke.matchBase=(r,e,t,n=Tm.isWindows(t))=>(e instanceof RegExp?e:ke.makeRe(e,t)).test(C3.basename(r));ke.isMatch=(r,e,t)=>ke(e,t)(r);ke.parse=(r,e)=>Array.isArray(r)?r.map(t=>ke.parse(t,e)):Em(r,{...e,fastpaths:!1});ke.scan=(r,e)=>A3(r,e);ke.compileRe=(r,e,t=!1,n=!1)=>{if(t===!0)return r.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${r.output})${o}`;r&&r.negated===!0&&(a=`^(?!${a}).*$`);let c=ke.toRegex(a,e);return n===!0&&(c.state=r),c};ke.makeRe=(r,e={},t=!1,n=!1)=>{if(!r||typeof r!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(r[0]==="."||r[0]==="*")&&(i.output=Em.fastpaths(r,e)),i.output||(i=Em(r,e)),ke.compileRe(i,e,t,n)};ke.toRegex=(r,e)=>{try{let t=e||{};return new RegExp(r,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};ke.constants=R3;ZT.exports=ke});var Cm=R((SG,eC)=>{"use strict";eC.exports=QT()});var cC=R((EG,aC)=>{"use strict";var la=require("fs"),{Readable:O3}=require("stream"),ca=require("path"),{promisify:bu}=require("util"),Am=Cm(),M3=bu(la.readdir),P3=bu(la.stat),tC=bu(la.lstat),I3=bu(la.realpath),N3="!",sC="READDIRP_RECURSIVE_ERROR",L3=new Set(["ENOENT","EPERM","EACCES","ELOOP",sC]),Rm="files",oC="directories",xu="files_directories",yu="all",rC=[Rm,oC,xu,yu],D3=r=>L3.has(r.code),[nC,B3]=process.versions.node.split(".").slice(0,2).map(r=>Number.parseInt(r,10)),j3=process.platform==="win32"&&(nC>10||nC===10&&B3>=5),iC=r=>{if(r!==void 0){if(typeof r=="function")return r;if(typeof r=="string"){let e=Am(r.trim());return t=>e(t.basename)}if(Array.isArray(r)){let e=[],t=[];for(let n of r){let i=n.trim();i.charAt(0)===N3?t.push(Am(i.slice(1))):e.push(Am(i))}return t.length>0?e.length>0?n=>e.some(i=>i(n.basename))&&!t.some(i=>i(n.basename)):n=>!t.some(i=>i(n.basename)):n=>e.some(i=>i(n.basename))}}},_u=class r extends O3{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:Rm,lstat:!1,depth:2147483648,alwaysStat:!1}}constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark||4096});let t={...r.defaultOptions,...e},{root:n,type:i}=t;this._fileFilter=iC(t.fileFilter),this._directoryFilter=iC(t.directoryFilter);let s=t.lstat?tC:P3;j3?this._stat=o=>s(o,{bigint:!0}):this._stat=s,this._maxDepth=t.depth,this._wantsDir=[oC,xu,yu].includes(i),this._wantsFile=[Rm,xu,yu].includes(i),this._wantsEverything=i===yu,this._root=ca.resolve(n),this._isDirent="Dirent"in la&&!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let{path:t,depth:n,files:i=[]}=this.parent||{};if(i.length>0){let s=i.splice(0,e).map(o=>this._formatEntry(o,t));for(let o of await Promise.all(s)){if(this.destroyed)return;let a=await this._getEntryType(o);a==="directory"&&this._directoryFilter(o)?(n<=this._maxDepth&&this.parents.push(this._exploreDir(o.fullPath,n+1)),this._wantsDir&&(this.push(o),e--)):(a==="file"||this._includeAsFile(o))&&this._fileFilter(o)&&this._wantsFile&&(this.push(o),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}if(this.parent=await s,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await M3(e,this._rdOptions)}catch(i){this._onError(i)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n;try{let i=this._isDirent?e.name:e,s=ca.resolve(ca.join(t,i));n={path:ca.relative(this._root,s),fullPath:s,basename:i},n[this._statsProp]=this._isDirent?e:await this._stat(s)}catch(i){this._onError(i)}return n}_onError(e){D3(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){let t=e&&e[this._statsProp];if(t){if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let n=e.fullPath;try{let i=await I3(n),s=await tC(i);if(s.isFile())return"file";if(s.isDirectory()){let o=i.length;if(n.startsWith(i)&&n.substr(o,1)===ca.sep){let a=new Error(`Circular symlink detected: "${n}" points to "${i}"`);return a.code=sC,this._onError(a)}return"directory"}}catch(i){this._onError(i)}}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}},qs=(r,e={})=>{let t=e.entryType||e.type;if(t==="both"&&(t=xu),t&&(e.type=t),r){if(typeof r!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!rC.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${rC.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new _u(e)},F3=(r,e={})=>new Promise((t,n)=>{let i=[];qs(r,e).on("data",s=>i.push(s)).on("end",()=>t(i)).on("error",s=>n(s))});qs.promise=F3;qs.ReaddirpStream=_u;qs.default=qs;aC.exports=qs});var km=R((TG,lC)=>{lC.exports=function(r,e){if(typeof r!="string")throw new TypeError("expected path to be a string");if(r==="\\"||r==="/")return"/";var t=r.length;if(t<=1)return r;var n="";if(t>4&&r[3]==="\\"){var i=r[2];(i==="?"||i===".")&&r.slice(0,2)==="\\\\"&&(r=r.slice(2),n="//")}var s=r.split(/[/\\]+/);return e!==!1&&s[s.length-1]===""&&s.pop(),n+s.join("/")}});var mC=R((dC,hC)=>{"use strict";Object.defineProperty(dC,"__esModule",{value:!0});var fC=Cm(),U3=km(),uC="!",q3={returnIndex:!1},H3=r=>Array.isArray(r)?r:[r],$3=(r,e)=>{if(typeof r=="function")return r;if(typeof r=="string"){let t=fC(r,e);return n=>r===n||t(n)}return r instanceof RegExp?t=>r.test(t):t=>!1},pC=(r,e,t,n)=>{let i=Array.isArray(t),s=i?t[0]:t;if(!i&&typeof s!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(s));let o=U3(s,!1);for(let c=0;c<e.length;c++){let l=e[c];if(l(o))return n?-1:!1}let a=i&&[o].concat(t.slice(1));for(let c=0;c<r.length;c++){let l=r[c];if(i?l(...a):l(o))return n?c:!0}return n?-1:!1},Om=(r,e,t=q3)=>{if(r==null)throw new TypeError("anymatch: specify first argument");let n=typeof t=="boolean"?{returnIndex:t}:t,i=n.returnIndex||!1,s=H3(r),o=s.filter(c=>typeof c=="string"&&c.charAt(0)===uC).map(c=>c.slice(1)).map(c=>fC(c,n)),a=s.filter(c=>typeof c!="string"||typeof c=="string"&&c.charAt(0)!==uC).map(c=>$3(c,n));return e==null?(c,l=!1)=>pC(a,o,c,typeof l=="boolean"?l:!1):pC(a,o,e,i)};Om.default=Om;hC.exports=Om});var vC=R((CG,gC)=>{gC.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var t;t=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(t[2])return!0;e=e.slice(t.index+t[0].length)}return!1}});var Mm=R((AG,xC)=>{var W3=vC(),yC={"{":"}","(":")","[":"]"},G3=function(r){if(r[0]==="!")return!0;for(var e=0,t=-2,n=-2,i=-2,s=-2,o=-2;e<r.length;){if(r[e]==="*"||r[e+1]==="?"&&/[\].+)]/.test(r[e])||n!==-1&&r[e]==="["&&r[e+1]!=="]"&&(n<e&&(n=r.indexOf("]",e)),n>e&&(o===-1||o>n||(o=r.indexOf("\\",e),o===-1||o>n)))||i!==-1&&r[e]==="{"&&r[e+1]!=="}"&&(i=r.indexOf("}",e),i>e&&(o=r.indexOf("\\",e),o===-1||o>i))||s!==-1&&r[e]==="("&&r[e+1]==="?"&&/[:!=]/.test(r[e+2])&&r[e+3]!==")"&&(s=r.indexOf(")",e),s>e&&(o=r.indexOf("\\",e),o===-1||o>s))||t!==-1&&r[e]==="("&&r[e+1]!=="|"&&(t<e&&(t=r.indexOf("|",e)),t!==-1&&r[t+1]!==")"&&(s=r.indexOf(")",t),s>t&&(o=r.indexOf("\\",t),o===-1||o>s))))return!0;if(r[e]==="\\"){var a=r[e+1];e+=2;var c=yC[a];if(c){var l=r.indexOf(c,e);l!==-1&&(e=l+1)}if(r[e]==="!")return!0}else e++}return!1},z3=function(r){if(r[0]==="!")return!0;for(var e=0;e<r.length;){if(/[*?{}()[\]]/.test(r[e]))return!0;if(r[e]==="\\"){var t=r[e+1];e+=2;var n=yC[t];if(n){var i=r.indexOf(n,e);i!==-1&&(e=i+1)}if(r[e]==="!")return!0}else e++}return!1};xC.exports=function(e,t){if(typeof e!="string"||e==="")return!1;if(W3(e))return!0;var n=G3;return t&&t.strict===!1&&(n=z3),n(e)}});var bC=R((RG,_C)=>{"use strict";var V3=Mm(),K3=require("path").posix.dirname,Y3=require("os").platform()==="win32",Pm="/",J3=/\\/g,X3=/[\{\[].*[\}\]]$/,Z3=/(^|[^\\])([\{\[]|\([^\)]+$)/,Q3=/\\([\!\*\?\|\[\]\(\)\{\}])/g;_C.exports=function(e,t){var n=Object.assign({flipBackslashes:!0},t);n.flipBackslashes&&Y3&&e.indexOf(Pm)<0&&(e=e.replace(J3,Pm)),X3.test(e)&&(e+=Pm),e+="a";do e=K3(e);while(V3(e)||Z3.test(e));return e.replace(Q3,"$1")}});var wu=R(mr=>{"use strict";mr.isInteger=r=>typeof r=="number"?Number.isInteger(r):typeof r=="string"&&r.trim()!==""?Number.isInteger(Number(r)):!1;mr.find=(r,e)=>r.nodes.find(t=>t.type===e);mr.exceedsLimit=(r,e,t=1,n)=>n===!1||!mr.isInteger(r)||!mr.isInteger(e)?!1:(Number(e)-Number(r))/Number(t)>=n;mr.escapeNode=(r,e=0,t)=>{let n=r.nodes[e];n&&(t&&n.type===t||n.type==="open"||n.type==="close")&&n.escaped!==!0&&(n.value="\\"+n.value,n.escaped=!0)};mr.encloseBrace=r=>r.type!=="brace"?!1:r.commas>>0+r.ranges>>0===0?(r.invalid=!0,!0):!1;mr.isInvalidBrace=r=>r.type!=="brace"?!1:r.invalid===!0||r.dollar?!0:r.commas>>0+r.ranges>>0===0||r.open!==!0||r.close!==!0?(r.invalid=!0,!0):!1;mr.isOpenOrClose=r=>r.type==="open"||r.type==="close"?!0:r.open===!0||r.close===!0;mr.reduce=r=>r.reduce((e,t)=>(t.type==="text"&&e.push(t.value),t.type==="range"&&(t.type="text"),e),[]);mr.flatten=(...r)=>{let e=[],t=n=>{for(let i=0;i<n.length;i++){let s=n[i];if(Array.isArray(s)){t(s);continue}s!==void 0&&e.push(s)}return e};return t(r),e}});var Su=R((OG,SC)=>{"use strict";var wC=wu();SC.exports=(r,e={})=>{let t=(n,i={})=>{let s=e.escapeInvalid&&wC.isInvalidBrace(i),o=n.invalid===!0&&e.escapeInvalid===!0,a="";if(n.value)return(s||o)&&wC.isOpenOrClose(n)?"\\"+n.value:n.value;if(n.value)return n.value;if(n.nodes)for(let c of n.nodes)a+=t(c);return a};return t(r)}});var TC=R((MG,EC)=>{"use strict";EC.exports=function(r){return typeof r=="number"?r-r===0:typeof r=="string"&&r.trim()!==""?Number.isFinite?Number.isFinite(+r):isFinite(+r):!1}});var NC=R((PG,IC)=>{"use strict";var CC=TC(),xi=(r,e,t)=>{if(CC(r)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||r===e)return String(r);if(CC(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let n={relaxZeros:!0,...t};typeof n.strictZeros=="boolean"&&(n.relaxZeros=n.strictZeros===!1);let i=String(n.relaxZeros),s=String(n.shorthand),o=String(n.capture),a=String(n.wrap),c=r+":"+e+"="+i+s+o+a;if(xi.cache.hasOwnProperty(c))return xi.cache[c].result;let l=Math.min(r,e),p=Math.max(r,e);if(Math.abs(l-p)===1){let S=r+"|"+e;return n.capture?`(${S})`:n.wrap===!1?S:`(?:${S})`}let f=PC(r)||PC(e),h={min:r,max:e,a:l,b:p},v=[],x=[];if(f&&(h.isPadded=f,h.maxLen=String(h.max).length),l<0){let S=p<0?Math.abs(p):1;x=AC(S,Math.abs(l),h,n),l=h.a=0}return p>=0&&(v=AC(l,p,h,n)),h.negatives=x,h.positives=v,h.result=eU(x,v,n),n.capture===!0?h.result=`(${h.result})`:n.wrap!==!1&&v.length+x.length>1&&(h.result=`(?:${h.result})`),xi.cache[c]=h,h.result};function eU(r,e,t){let n=Im(r,e,"-",!1,t)||[],i=Im(e,r,"",!1,t)||[],s=Im(r,e,"-?",!0,t)||[];return n.concat(s).concat(i).join("|")}function tU(r,e){let t=1,n=1,i=kC(r,t),s=new Set([e]);for(;r<=i&&i<=e;)s.add(i),t+=1,i=kC(r,t);for(i=OC(e+1,n)-1;r<i&&i<=e;)s.add(i),n+=1,i=OC(e+1,n)-1;return s=[...s],s.sort(iU),s}function rU(r,e,t){if(r===e)return{pattern:r,count:[],digits:0};let n=nU(r,e),i=n.length,s="",o=0;for(let a=0;a<i;a++){let[c,l]=n[a];c===l?s+=c:c!=="0"||l!=="9"?s+=sU(c,l,t):o++}return o&&(s+=t.shorthand===!0?"\\d":"[0-9]"),{pattern:s,count:[o],digits:i}}function AC(r,e,t,n){let i=tU(r,e),s=[],o=r,a;for(let c=0;c<i.length;c++){let l=i[c],p=rU(String(o),String(l),n),f="";if(!t.isPadded&&a&&a.pattern===p.pattern){a.count.length>1&&a.count.pop(),a.count.push(p.count[0]),a.string=a.pattern+MC(a.count),o=l+1;continue}t.isPadded&&(f=oU(l,t,n)),p.string=f+p.pattern+MC(p.count),s.push(p),o=l+1,a=p}return s}function Im(r,e,t,n,i){let s=[];for(let o of r){let{string:a}=o;!n&&!RC(e,"string",a)&&s.push(t+a),n&&RC(e,"string",a)&&s.push(t+a)}return s}function nU(r,e){let t=[];for(let n=0;n<r.length;n++)t.push([r[n],e[n]]);return t}function iU(r,e){return r>e?1:e>r?-1:0}function RC(r,e,t){return r.some(n=>n[e]===t)}function kC(r,e){return Number(String(r).slice(0,-e)+"9".repeat(e))}function OC(r,e){return r-r%Math.pow(10,e)}function MC(r){let[e=0,t=""]=r;return t||e>1?`{${e+(t?","+t:"")}}`:""}function sU(r,e,t){return`[${r}${e-r===1?"":"-"}${e}]`}function PC(r){return/^-?(0+)\d/.test(r)}function oU(r,e,t){if(!e.isPadded)return r;let n=Math.abs(e.maxLen-String(r).length),i=t.relaxZeros!==!1;switch(n){case 0:return"";case 1:return i?"0?":"0";case 2:return i?"0{0,2}":"00";default:return i?`0{0,${n}}`:`0{${n}}`}}xi.cache={};xi.clearCache=()=>xi.cache={};IC.exports=xi});var Dm=R((IG,qC)=>{"use strict";var aU=require("util"),DC=NC(),LC=r=>r!==null&&typeof r=="object"&&!Array.isArray(r),cU=r=>e=>r===!0?Number(e):String(e),Nm=r=>typeof r=="number"||typeof r=="string"&&r!=="",ua=r=>Number.isInteger(+r),Lm=r=>{let e=`${r}`,t=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++t]==="0";);return t>0},lU=(r,e,t)=>typeof r=="string"||typeof e=="string"?!0:t.stringify===!0,uU=(r,e,t)=>{if(e>0){let n=r[0]==="-"?"-":"";n&&(r=r.slice(1)),r=n+r.padStart(n?e-1:e,"0")}return t===!1?String(r):r},Tu=(r,e)=>{let t=r[0]==="-"?"-":"";for(t&&(r=r.slice(1),e--);r.length<e;)r="0"+r;return t?"-"+r:r},pU=(r,e,t)=>{r.negatives.sort((a,c)=>a<c?-1:a>c?1:0),r.positives.sort((a,c)=>a<c?-1:a>c?1:0);let n=e.capture?"":"?:",i="",s="",o;return r.positives.length&&(i=r.positives.map(a=>Tu(String(a),t)).join("|")),r.negatives.length&&(s=`-(${n}${r.negatives.map(a=>Tu(String(a),t)).join("|")})`),i&&s?o=`${i}|${s}`:o=i||s,e.wrap?`(${n}${o})`:o},BC=(r,e,t,n)=>{if(t)return DC(r,e,{wrap:!1,...n});let i=String.fromCharCode(r);if(r===e)return i;let s=String.fromCharCode(e);return`[${i}-${s}]`},jC=(r,e,t)=>{if(Array.isArray(r)){let n=t.wrap===!0,i=t.capture?"":"?:";return n?`(${i}${r.join("|")})`:r.join("|")}return DC(r,e,t)},FC=(...r)=>new RangeError("Invalid range arguments: "+aU.inspect(...r)),UC=(r,e,t)=>{if(t.strictRanges===!0)throw FC([r,e]);return[]},fU=(r,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${r}" to be a number`);return[]},dU=(r,e,t=1,n={})=>{let i=Number(r),s=Number(e);if(!Number.isInteger(i)||!Number.isInteger(s)){if(n.strictRanges===!0)throw FC([r,e]);return[]}i===0&&(i=0),s===0&&(s=0);let o=i>s,a=String(r),c=String(e),l=String(t);t=Math.max(Math.abs(t),1);let p=Lm(a)||Lm(c)||Lm(l),f=p?Math.max(a.length,c.length,l.length):0,h=p===!1&&lU(r,e,n)===!1,v=n.transform||cU(h);if(n.toRegex&&t===1)return BC(Tu(r,f),Tu(e,f),!0,n);let x={negatives:[],positives:[]},S=P=>x[P<0?"negatives":"positives"].push(Math.abs(P)),A=[],k=0;for(;o?i>=s:i<=s;)n.toRegex===!0&&t>1?S(i):A.push(uU(v(i,k),f,h)),i=o?i-t:i+t,k++;return n.toRegex===!0?t>1?pU(x,n,f):jC(A,null,{wrap:!1,...n}):A},hU=(r,e,t=1,n={})=>{if(!ua(r)&&r.length>1||!ua(e)&&e.length>1)return UC(r,e,n);let i=n.transform||(h=>String.fromCharCode(h)),s=`${r}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=s>o,c=Math.min(s,o),l=Math.max(s,o);if(n.toRegex&&t===1)return BC(c,l,!1,n);let p=[],f=0;for(;a?s>=o:s<=o;)p.push(i(s,f)),s=a?s-t:s+t,f++;return n.toRegex===!0?jC(p,null,{wrap:!1,options:n}):p},Eu=(r,e,t,n={})=>{if(e==null&&Nm(r))return[r];if(!Nm(r)||!Nm(e))return UC(r,e,n);if(typeof t=="function")return Eu(r,e,1,{transform:t});if(LC(t))return Eu(r,e,0,t);let i={...n};return i.capture===!0&&(i.wrap=!0),t=t||i.step||1,ua(t)?ua(r)&&ua(e)?dU(r,e,t,i):hU(r,e,Math.max(Math.abs(t),1),i):t!=null&&!LC(t)?fU(t,i):Eu(r,e,1,t)};qC.exports=Eu});var WC=R((NG,$C)=>{"use strict";var mU=Dm(),HC=wu(),gU=(r,e={})=>{let t=(n,i={})=>{let s=HC.isInvalidBrace(i),o=n.invalid===!0&&e.escapeInvalid===!0,a=s===!0||o===!0,c=e.escapeInvalid===!0?"\\":"",l="";if(n.isOpen===!0)return c+n.value;if(n.isClose===!0)return console.log("node.isClose",c,n.value),c+n.value;if(n.type==="open")return a?c+n.value:"(";if(n.type==="close")return a?c+n.value:")";if(n.type==="comma")return n.prev.type==="comma"?"":a?n.value:"|";if(n.value)return n.value;if(n.nodes&&n.ranges>0){let p=HC.reduce(n.nodes),f=mU(...p,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(f.length!==0)return p.length>1&&f.length>1?`(${f})`:f}if(n.nodes)for(let p of n.nodes)l+=t(p,n);return l};return t(r)};$C.exports=gU});var VC=R((LG,zC)=>{"use strict";var vU=Dm(),GC=Su(),Hs=wu(),_i=(r="",e="",t=!1)=>{let n=[];if(r=[].concat(r),e=[].concat(e),!e.length)return r;if(!r.length)return t?Hs.flatten(e).map(i=>`{${i}}`):e;for(let i of r)if(Array.isArray(i))for(let s of i)n.push(_i(s,e,t));else for(let s of e)t===!0&&typeof s=="string"&&(s=`{${s}}`),n.push(Array.isArray(s)?_i(i,s,t):i+s);return Hs.flatten(n)},yU=(r,e={})=>{let t=e.rangeLimit===void 0?1e3:e.rangeLimit,n=(i,s={})=>{i.queue=[];let o=s,a=s.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(i.invalid||i.dollar){a.push(_i(a.pop(),GC(i,e)));return}if(i.type==="brace"&&i.invalid!==!0&&i.nodes.length===2){a.push(_i(a.pop(),["{}"]));return}if(i.nodes&&i.ranges>0){let f=Hs.reduce(i.nodes);if(Hs.exceedsLimit(...f,e.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let h=vU(...f,e);h.length===0&&(h=GC(i,e)),a.push(_i(a.pop(),h)),i.nodes=[];return}let c=Hs.encloseBrace(i),l=i.queue,p=i;for(;p.type!=="brace"&&p.type!=="root"&&p.parent;)p=p.parent,l=p.queue;for(let f=0;f<i.nodes.length;f++){let h=i.nodes[f];if(h.type==="comma"&&i.type==="brace"){f===1&&l.push(""),l.push("");continue}if(h.type==="close"){a.push(_i(a.pop(),l,c));continue}if(h.value&&h.type!=="open"){l.push(_i(l.pop(),h.value));continue}h.nodes&&n(h,i)}return l};return Hs.flatten(n(r))};zC.exports=yU});var YC=R((DG,KC)=>{"use strict";KC.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
102
+ `,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var eA=R((BG,QC)=>{"use strict";var xU=Su(),{MAX_LENGTH:JC,CHAR_BACKSLASH:Bm,CHAR_BACKTICK:_U,CHAR_COMMA:bU,CHAR_DOT:wU,CHAR_LEFT_PARENTHESES:SU,CHAR_RIGHT_PARENTHESES:EU,CHAR_LEFT_CURLY_BRACE:TU,CHAR_RIGHT_CURLY_BRACE:CU,CHAR_LEFT_SQUARE_BRACKET:XC,CHAR_RIGHT_SQUARE_BRACKET:ZC,CHAR_DOUBLE_QUOTE:AU,CHAR_SINGLE_QUOTE:RU,CHAR_NO_BREAK_SPACE:kU,CHAR_ZERO_WIDTH_NOBREAK_SPACE:OU}=YC(),MU=(r,e={})=>{if(typeof r!="string")throw new TypeError("Expected a string");let t=e||{},n=typeof t.maxLength=="number"?Math.min(JC,t.maxLength):JC;if(r.length>n)throw new SyntaxError(`Input length (${r.length}), exceeds max characters (${n})`);let i={type:"root",input:r,nodes:[]},s=[i],o=i,a=i,c=0,l=r.length,p=0,f=0,h,v=()=>r[p++],x=S=>{if(S.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&S.type==="text"){a.value+=S.value;return}return o.nodes.push(S),S.parent=o,S.prev=a,a=S,S};for(x({type:"bos"});p<l;)if(o=s[s.length-1],h=v(),!(h===OU||h===kU)){if(h===Bm){x({type:"text",value:(e.keepEscaping?h:"")+v()});continue}if(h===ZC){x({type:"text",value:"\\"+h});continue}if(h===XC){c++;let S;for(;p<l&&(S=v());){if(h+=S,S===XC){c++;continue}if(S===Bm){h+=v();continue}if(S===ZC&&(c--,c===0))break}x({type:"text",value:h});continue}if(h===SU){o=x({type:"paren",nodes:[]}),s.push(o),x({type:"text",value:h});continue}if(h===EU){if(o.type!=="paren"){x({type:"text",value:h});continue}o=s.pop(),x({type:"text",value:h}),o=s[s.length-1];continue}if(h===AU||h===RU||h===_U){let S=h,A;for(e.keepQuotes!==!0&&(h="");p<l&&(A=v());){if(A===Bm){h+=A+v();continue}if(A===S){e.keepQuotes===!0&&(h+=A);break}h+=A}x({type:"text",value:h});continue}if(h===TU){f++;let A={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:f,commas:0,ranges:0,nodes:[]};o=x(A),s.push(o),x({type:"open",value:h});continue}if(h===CU){if(o.type!=="brace"){x({type:"text",value:h});continue}let S="close";o=s.pop(),o.close=!0,x({type:S,value:h}),f--,o=s[s.length-1];continue}if(h===bU&&f>0){if(o.ranges>0){o.ranges=0;let S=o.nodes.shift();o.nodes=[S,{type:"text",value:xU(o)}]}x({type:"comma",value:h}),o.commas++;continue}if(h===wU&&f>0&&o.commas===0){let S=o.nodes;if(f===0||S.length===0){x({type:"text",value:h});continue}if(a.type==="dot"){if(o.range=[],a.value+=h,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){S.pop();let A=S[S.length-1];A.value+=a.value+h,a=A,o.ranges--;continue}x({type:"dot",value:h});continue}x({type:"text",value:h})}do if(o=s.pop(),o.type!=="root"){o.nodes.forEach(k=>{k.nodes||(k.type==="open"&&(k.isOpen=!0),k.type==="close"&&(k.isClose=!0),k.nodes||(k.type="text"),k.invalid=!0)});let S=s[s.length-1],A=S.nodes.indexOf(o);S.nodes.splice(A,1,...o.nodes)}while(s.length>0);return x({type:"eos"}),i};QC.exports=MU});var nA=R((jG,rA)=>{"use strict";var tA=Su(),PU=WC(),IU=VC(),NU=eA(),Xt=(r,e={})=>{let t=[];if(Array.isArray(r))for(let n of r){let i=Xt.create(n,e);Array.isArray(i)?t.push(...i):t.push(i)}else t=[].concat(Xt.create(r,e));return e&&e.expand===!0&&e.nodupes===!0&&(t=[...new Set(t)]),t};Xt.parse=(r,e={})=>NU(r,e);Xt.stringify=(r,e={})=>tA(typeof r=="string"?Xt.parse(r,e):r,e);Xt.compile=(r,e={})=>(typeof r=="string"&&(r=Xt.parse(r,e)),PU(r,e));Xt.expand=(r,e={})=>{typeof r=="string"&&(r=Xt.parse(r,e));let t=IU(r,e);return e.noempty===!0&&(t=t.filter(Boolean)),e.nodupes===!0&&(t=[...new Set(t)]),t};Xt.create=(r,e={})=>r===""||r.length<3?[r]:e.expand!==!0?Xt.compile(r,e):Xt.expand(r,e);rA.exports=Xt});var iA=R((FG,LU)=>{LU.exports=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]});var oA=R((UG,sA)=>{sA.exports=iA()});var cA=R((qG,aA)=>{"use strict";var DU=require("path"),BU=oA(),jU=new Set(BU);aA.exports=r=>jU.has(DU.extname(r).slice(1).toLowerCase())});var Cu=R(Y=>{"use strict";var{sep:FU}=require("path"),{platform:jm}=process,UU=require("os");Y.EV_ALL="all";Y.EV_READY="ready";Y.EV_ADD="add";Y.EV_CHANGE="change";Y.EV_ADD_DIR="addDir";Y.EV_UNLINK="unlink";Y.EV_UNLINK_DIR="unlinkDir";Y.EV_RAW="raw";Y.EV_ERROR="error";Y.STR_DATA="data";Y.STR_END="end";Y.STR_CLOSE="close";Y.FSEVENT_CREATED="created";Y.FSEVENT_MODIFIED="modified";Y.FSEVENT_DELETED="deleted";Y.FSEVENT_MOVED="moved";Y.FSEVENT_CLONED="cloned";Y.FSEVENT_UNKNOWN="unknown";Y.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;Y.FSEVENT_TYPE_FILE="file";Y.FSEVENT_TYPE_DIRECTORY="directory";Y.FSEVENT_TYPE_SYMLINK="symlink";Y.KEY_LISTENERS="listeners";Y.KEY_ERR="errHandlers";Y.KEY_RAW="rawEmitters";Y.HANDLER_KEYS=[Y.KEY_LISTENERS,Y.KEY_ERR,Y.KEY_RAW];Y.DOT_SLASH=`.${FU}`;Y.BACK_SLASH_RE=/\\/g;Y.DOUBLE_SLASH_RE=/\/\//;Y.SLASH_OR_BACK_SLASH_RE=/[/\\]/;Y.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;Y.REPLACER_RE=/^\.[/\\]/;Y.SLASH="/";Y.SLASH_SLASH="//";Y.BRACE_START="{";Y.BANG="!";Y.ONE_DOT=".";Y.TWO_DOTS="..";Y.STAR="*";Y.GLOBSTAR="**";Y.ROOT_GLOBSTAR="/**/*";Y.SLASH_GLOBSTAR="/**";Y.DIR_SUFFIX="Dir";Y.ANYMATCH_OPTS={dot:!0};Y.STRING_TYPE="string";Y.FUNCTION_TYPE="function";Y.EMPTY_STR="";Y.EMPTY_FN=()=>{};Y.IDENTITY_FN=r=>r;Y.isWindows=jm==="win32";Y.isMacos=jm==="darwin";Y.isLinux=jm==="linux";Y.isIBMi=UU.type()==="OS400"});var hA=R(($G,dA)=>{"use strict";var xn=require("fs"),mt=require("path"),{promisify:ha}=require("util"),qU=cA(),{isWindows:HU,isLinux:$U,EMPTY_FN:WU,EMPTY_STR:GU,KEY_LISTENERS:$s,KEY_ERR:Fm,KEY_RAW:pa,HANDLER_KEYS:zU,EV_CHANGE:Ru,EV_ADD:Au,EV_ADD_DIR:VU,EV_ERROR:uA,STR_DATA:KU,STR_END:YU,BRACE_START:JU,STAR:XU}=Cu(),ZU="watch",QU=ha(xn.open),pA=ha(xn.stat),eq=ha(xn.lstat),tq=ha(xn.close),Um=ha(xn.realpath),rq={lstat:eq,stat:pA},Hm=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},fa=(r,e,t)=>{let n=r[e];n instanceof Set||(r[e]=n=new Set([n])),n.add(t)},nq=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},da=(r,e,t)=>{let n=r[e];n instanceof Set?n.delete(t):n===t&&delete r[e]},fA=r=>r instanceof Set?r.size===0:!r,ku=new Map;function lA(r,e,t,n,i){let s=(o,a)=>{t(r),i(o,a,{watchedPath:r}),a&&r!==a&&Ou(mt.resolve(r,a),$s,mt.join(r,a))};try{return xn.watch(r,e,s)}catch(o){n(o)}}var Ou=(r,e,t,n,i)=>{let s=ku.get(r);s&&Hm(s[e],o=>{o(t,n,i)})},iq=(r,e,t,n)=>{let{listener:i,errHandler:s,rawEmitter:o}=n,a=ku.get(e),c;if(!t.persistent)return c=lA(r,t,i,s,o),c.close.bind(c);if(a)fa(a,$s,i),fa(a,Fm,s),fa(a,pa,o);else{if(c=lA(r,t,Ou.bind(null,e,$s),s,Ou.bind(null,e,pa)),!c)return;c.on(uA,async l=>{let p=Ou.bind(null,e,Fm);if(a.watcherUnusable=!0,HU&&l.code==="EPERM")try{let f=await QU(r,"r");await tq(f),p(l)}catch{}else p(l)}),a={listeners:i,errHandlers:s,rawEmitters:o,watcher:c},ku.set(e,a)}return()=>{da(a,$s,i),da(a,Fm,s),da(a,pa,o),fA(a.listeners)&&(a.watcher.close(),ku.delete(e),zU.forEach(nq(a)),a.watcher=void 0,Object.freeze(a))}},qm=new Map,sq=(r,e,t,n)=>{let{listener:i,rawEmitter:s}=n,o=qm.get(e),a=new Set,c=new Set,l=o&&o.options;return l&&(l.persistent<t.persistent||l.interval>t.interval)&&(a=o.listeners,c=o.rawEmitters,xn.unwatchFile(e),o=void 0),o?(fa(o,$s,i),fa(o,pa,s)):(o={listeners:i,rawEmitters:s,options:t,watcher:xn.watchFile(e,t,(p,f)=>{Hm(o.rawEmitters,v=>{v(Ru,e,{curr:p,prev:f})});let h=p.mtimeMs;(p.size!==f.size||h>f.mtimeMs||h===0)&&Hm(o.listeners,v=>v(r,p))})},qm.set(e,o)),()=>{da(o,$s,i),da(o,pa,s),fA(o.listeners)&&(qm.delete(e),xn.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},$m=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,i=mt.dirname(e),s=mt.basename(e);this.fsw._getWatchedDir(i).add(s);let a=mt.resolve(e),c={persistent:n.persistent};t||(t=WU);let l;return n.usePolling?(c.interval=n.enableBinaryInterval&&qU(s)?n.binaryInterval:n.interval,l=sq(e,a,c,{listener:t,rawEmitter:this.fsw._emitRaw})):l=iq(e,a,c,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),l}_handleFile(e,t,n){if(this.fsw.closed)return;let i=mt.dirname(e),s=mt.basename(e),o=this.fsw._getWatchedDir(i),a=t;if(o.has(s))return;let c=async(p,f)=>{if(this.fsw._throttle(ZU,e,5)){if(!f||f.mtimeMs===0)try{let h=await pA(e);if(this.fsw.closed)return;let v=h.atimeMs,x=h.mtimeMs;(!v||v<=x||x!==a.mtimeMs)&&this.fsw._emit(Ru,e,h),$U&&a.ino!==h.ino?(this.fsw._closeFile(p),a=h,this.fsw._addPathCloser(p,this._watchWithNodeFs(e,c))):a=h}catch{this.fsw._remove(i,s)}else if(o.has(s)){let h=f.atimeMs,v=f.mtimeMs;(!h||h<=v||v!==a.mtimeMs)&&this.fsw._emit(Ru,e,f),a=f}}},l=this._watchWithNodeFs(e,c);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Au,e,0))return;this.fsw._emit(Au,e,t)}return l}async _handleSymlink(e,t,n,i){if(this.fsw.closed)return;let s=e.fullPath,o=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await Um(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(i)?this.fsw._symlinkPaths.get(s)!==a&&(this.fsw._symlinkPaths.set(s,a),this.fsw._emit(Ru,n,e.stats)):(o.add(i),this.fsw._symlinkPaths.set(s,a),this.fsw._emit(Au,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,t,n,i,s,o,a){if(e=mt.join(e,GU),!n.hasGlob&&(a=this.fsw._throttle("readdir",e,1e3),!a))return;let c=this.fsw._getWatchedDir(n.path),l=new Set,p=this.fsw._readdirp(e,{fileFilter:f=>n.filterPath(f),directoryFilter:f=>n.filterDir(f),depth:0}).on(KU,async f=>{if(this.fsw.closed){p=void 0;return}let h=f.path,v=mt.join(e,h);if(l.add(h),!(f.stats.isSymbolicLink()&&await this._handleSymlink(f,e,v,h))){if(this.fsw.closed){p=void 0;return}(h===i||!i&&!c.has(h))&&(this.fsw._incrReadyCount(),v=mt.join(s,mt.relative(s,v)),this._addToNodeFs(v,t,n,o+1))}}).on(uA,this._boundHandleError);return new Promise(f=>p.once(YU,()=>{if(this.fsw.closed){p=void 0;return}let h=a?a.clear():!1;f(),c.getChildren().filter(v=>v!==e&&!l.has(v)&&(!n.hasGlob||n.filterPath({fullPath:mt.resolve(e,v)}))).forEach(v=>{this.fsw._remove(e,v)}),p=void 0,h&&this._handleRead(e,!1,n,i,s,o,a)}))}async _handleDir(e,t,n,i,s,o,a){let c=this.fsw._getWatchedDir(mt.dirname(e)),l=c.has(mt.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!s&&!l&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit(VU,e,t),c.add(mt.basename(e)),this.fsw._getWatchedDir(e);let p,f,h=this.fsw.options.depth;if((h==null||i<=h)&&!this.fsw._symlinkPaths.has(a)){if(!s&&(await this._handleRead(e,n,o,s,e,i,p),this.fsw.closed))return;f=this._watchWithNodeFs(e,(v,x)=>{x&&x.mtimeMs===0||this._handleRead(v,!1,o,s,e,i,p)})}return f}async _addToNodeFs(e,t,n,i,s){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e,i);!a.hasGlob&&n&&(a.hasGlob=n.hasGlob,a.globFilter=n.globFilter,a.filterPath=c=>n.filterPath(c),a.filterDir=c=>n.filterDir(c));try{let c=await rq[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))return o(),!1;let l=this.fsw.options.followSymlinks&&!e.includes(XU)&&!e.includes(JU),p;if(c.isDirectory()){let f=mt.resolve(e),h=l?await Um(e):e;if(this.fsw.closed||(p=await this._handleDir(a.watchPath,c,t,i,s,a,h),this.fsw.closed))return;f!==h&&h!==void 0&&this.fsw._symlinkPaths.set(f,h)}else if(c.isSymbolicLink()){let f=l?await Um(e):e;if(this.fsw.closed)return;let h=mt.dirname(a.watchPath);if(this.fsw._getWatchedDir(h).add(a.watchPath),this.fsw._emit(Au,a.watchPath,c),p=await this._handleDir(h,c,t,i,e,a,f),this.fsw.closed)return;f!==void 0&&this.fsw._symlinkPaths.set(mt.resolve(e),f)}else p=this._handleFile(a.watchPath,c,t);return o(),this.fsw._addPathCloser(e,p),!1}catch(c){if(this.fsw._handleError(c))return o(),e}}};dA.exports=$m});var bA=R((WG,Xm)=>{"use strict";var Ym=require("fs"),gt=require("path"),{promisify:Jm}=require("util"),Ws;try{Ws=require("fsevents")}catch(r){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(r)}if(Ws){let r=process.version.match(/v(\d+)\.(\d+)/);if(r&&r[1]&&r[2]){let e=Number.parseInt(r[1],10),t=Number.parseInt(r[2],10);e===8&&t<16&&(Ws=void 0)}}var{EV_ADD:Wm,EV_CHANGE:oq,EV_ADD_DIR:mA,EV_UNLINK:Mu,EV_ERROR:aq,STR_DATA:cq,STR_END:lq,FSEVENT_CREATED:uq,FSEVENT_MODIFIED:pq,FSEVENT_DELETED:fq,FSEVENT_MOVED:dq,FSEVENT_UNKNOWN:hq,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:mq,FSEVENT_TYPE_FILE:gq,FSEVENT_TYPE_DIRECTORY:ma,FSEVENT_TYPE_SYMLINK:_A,ROOT_GLOBSTAR:gA,DIR_SUFFIX:vq,DOT_SLASH:vA,FUNCTION_TYPE:Gm,EMPTY_FN:yq,IDENTITY_FN:xq}=Cu(),_q=r=>isNaN(r)?{}:{depth:r},Vm=Jm(Ym.stat),bq=Jm(Ym.lstat),yA=Jm(Ym.realpath),wq={stat:Vm,lstat:bq},bi=new Map,Sq=10,Eq=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),Tq=(r,e)=>({stop:Ws.watch(r,e)});function Cq(r,e,t,n){let i=gt.extname(e)?gt.dirname(e):e,s=gt.dirname(i),o=bi.get(i);Aq(s)&&(i=s);let a=gt.resolve(r),c=a!==e,l=(f,h,v)=>{c&&(f=f.replace(e,a)),(f===a||!f.indexOf(a+gt.sep))&&t(f,h,v)},p=!1;for(let f of bi.keys())if(e.indexOf(gt.resolve(f)+gt.sep)===0){i=f,o=bi.get(i),p=!0;break}return o||p?o.listeners.add(l):(o={listeners:new Set([l]),rawEmitter:n,watcher:Tq(i,(f,h)=>{if(!o.listeners.size||h&mq)return;let v=Ws.getInfo(f,h);o.listeners.forEach(x=>{x(f,h,v)}),o.rawEmitter(v.event,f,v)})},bi.set(i,o)),()=>{let f=o.listeners;if(f.delete(l),!f.size&&(bi.delete(i),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var Aq=r=>{let e=0;for(let t of bi.keys())if(t.indexOf(r)===0&&(e++,e>=Sq))return!0;return!1},Rq=()=>Ws&&bi.size<128,zm=(r,e)=>{let t=0;for(;!r.indexOf(e)&&(r=gt.dirname(r))!==e;)t++;return t},xA=(r,e)=>r.type===ma&&e.isDirectory()||r.type===_A&&e.isSymbolicLink()||r.type===gq&&e.isFile(),Km=class{constructor(e){this.fsw=e}checkIgnored(e,t){let n=this.fsw._ignoredPaths;if(this.fsw._isIgnored(e,t))return n.add(e),t&&t.isDirectory()&&n.add(e+gA),!0;n.delete(e),n.delete(e+gA)}addOrChange(e,t,n,i,s,o,a,c){let l=s.has(o)?oq:Wm;this.handleEvent(l,e,t,n,i,s,o,a,c)}async checkExists(e,t,n,i,s,o,a,c){try{let l=await Vm(e);if(this.fsw.closed)return;xA(a,l)?this.addOrChange(e,t,n,i,s,o,a,c):this.handleEvent(Mu,e,t,n,i,s,o,a,c)}catch(l){l.code==="EACCES"?this.addOrChange(e,t,n,i,s,o,a,c):this.handleEvent(Mu,e,t,n,i,s,o,a,c)}}handleEvent(e,t,n,i,s,o,a,c,l){if(!(this.fsw.closed||this.checkIgnored(t)))if(e===Mu){let p=c.type===ma;(p||o.has(a))&&this.fsw._remove(s,a,p)}else{if(e===Wm){if(c.type===ma&&this.fsw._getWatchedDir(t),c.type===_A&&l.followSymlinks){let f=l.depth===void 0?void 0:zm(n,i)+1;return this._addToFsEvents(t,!1,!0,f)}this.fsw._getWatchedDir(s).add(a)}let p=c.type===ma?e+vq:e;this.fsw._emit(p,t),p===mA&&this._addToFsEvents(t,!1,!0)}}_watchWithFsEvents(e,t,n,i){if(this.fsw.closed||this.fsw._isIgnored(e))return;let s=this.fsw.options,a=Cq(e,t,async(c,l,p)=>{if(this.fsw.closed||s.depth!==void 0&&zm(c,t)>s.depth)return;let f=n(gt.join(e,gt.relative(e,c)));if(i&&!i(f))return;let h=gt.dirname(f),v=gt.basename(f),x=this.fsw._getWatchedDir(p.type===ma?f:h);if(Eq.has(l)||p.event===hq)if(typeof s.ignored===Gm){let S;try{S=await Vm(f)}catch{}if(this.fsw.closed||this.checkIgnored(f,S))return;xA(p,S)?this.addOrChange(f,c,t,h,x,v,p,s):this.handleEvent(Mu,f,c,t,h,x,v,p,s)}else this.checkExists(f,c,t,h,x,v,p,s);else switch(p.event){case uq:case pq:return this.addOrChange(f,c,t,h,x,v,p,s);case fq:case dq:return this.checkExists(f,c,t,h,x,v,p,s)}},this.fsw._emitRaw);return this.fsw._emitReady(),a}async _handleFsEventsSymlink(e,t,n,i){if(!(this.fsw.closed||this.fsw._symlinkPaths.has(t))){this.fsw._symlinkPaths.set(t,!0),this.fsw._incrReadyCount();try{let s=await yA(e);if(this.fsw.closed)return;if(this.fsw._isIgnored(s))return this.fsw._emitReady();this.fsw._incrReadyCount(),this._addToFsEvents(s||e,o=>{let a=e;return s&&s!==vA?a=o.replace(s,e):o!==vA&&(a=gt.join(e,o)),n(a)},!1,i)}catch(s){if(this.fsw._handleError(s))return this.fsw._emitReady()}}}emitAdd(e,t,n,i,s){let o=n(e),a=t.isDirectory(),c=this.fsw._getWatchedDir(gt.dirname(o)),l=gt.basename(o);a&&this.fsw._getWatchedDir(o),!c.has(l)&&(c.add(l),(!i.ignoreInitial||s===!0)&&this.fsw._emit(a?mA:Wm,o,t))}initWatch(e,t,n,i){if(this.fsw.closed)return;let s=this._watchWithFsEvents(n.watchPath,gt.resolve(e||n.watchPath),i,n.globFilter);this.fsw._addPathCloser(t,s)}async _addToFsEvents(e,t,n,i){if(this.fsw.closed)return;let s=this.fsw.options,o=typeof t===Gm?t:xq,a=this.fsw._getWatchHelpers(e);try{let c=await wq[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))throw null;if(c.isDirectory()){if(a.globFilter||this.emitAdd(o(e),c,o,s,n),i&&i>s.depth)return;this.fsw._readdirp(a.watchPath,{fileFilter:l=>a.filterPath(l),directoryFilter:l=>a.filterDir(l),..._q(s.depth-(i||0))}).on(cq,l=>{if(this.fsw.closed||l.stats.isDirectory()&&!a.filterPath(l))return;let p=gt.join(a.watchPath,l.path),{fullPath:f}=l;if(a.followSymlinks&&l.stats.isSymbolicLink()){let h=s.depth===void 0?void 0:zm(p,gt.resolve(a.watchPath))+1;this._handleFsEventsSymlink(p,f,o,h)}else this.emitAdd(p,l.stats,o,s,n)}).on(aq,yq).on(lq,()=>{this.fsw._emitReady()})}else this.emitAdd(a.watchPath,c,o,s,n),this.fsw._emitReady()}catch(c){(!c||this.fsw._handleError(c))&&(this.fsw._emitReady(),this.fsw._emitReady())}if(s.persistent&&n!==!0)if(typeof t===Gm)this.initWatch(void 0,e,a,o);else{let c;try{c=await yA(a.watchPath)}catch{}this.initWatch(c,e,a,o)}}};Xm.exports=Km;Xm.exports.canUse=Rq});var PA=R(fg=>{"use strict";var{EventEmitter:kq}=require("events"),ug=require("fs"),le=require("path"),{promisify:RA}=require("util"),Oq=cC(),ng=mC().default,Mq=bC(),Zm=Mm(),Pq=nA(),Iq=km(),Nq=hA(),wA=bA(),{EV_ALL:Qm,EV_READY:Lq,EV_ADD:Pu,EV_CHANGE:ga,EV_UNLINK:SA,EV_ADD_DIR:Dq,EV_UNLINK_DIR:Bq,EV_RAW:jq,EV_ERROR:eg,STR_CLOSE:Fq,STR_END:Uq,BACK_SLASH_RE:qq,DOUBLE_SLASH_RE:EA,SLASH_OR_BACK_SLASH_RE:Hq,DOT_RE:$q,REPLACER_RE:Wq,SLASH:tg,SLASH_SLASH:Gq,BRACE_START:zq,BANG:ig,ONE_DOT:kA,TWO_DOTS:Vq,GLOBSTAR:Kq,SLASH_GLOBSTAR:rg,ANYMATCH_OPTS:sg,STRING_TYPE:pg,FUNCTION_TYPE:Yq,EMPTY_STR:og,EMPTY_FN:Jq,isWindows:Xq,isMacos:Zq,isIBMi:Qq}=Cu(),eH=RA(ug.stat),tH=RA(ug.readdir),ag=(r=[])=>Array.isArray(r)?r:[r],OA=(r,e=[])=>(r.forEach(t=>{Array.isArray(t)?OA(t,e):e.push(t)}),e),TA=r=>{let e=OA(ag(r));if(!e.every(t=>typeof t===pg))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(MA)},CA=r=>{let e=r.replace(qq,tg),t=!1;for(e.startsWith(Gq)&&(t=!0);e.match(EA);)e=e.replace(EA,tg);return t&&(e=tg+e),e},MA=r=>CA(le.normalize(CA(r))),AA=(r=og)=>e=>typeof e!==pg?e:MA(le.isAbsolute(e)?e:le.join(r,e)),rH=(r,e)=>le.isAbsolute(r)?r:r.startsWith(ig)?ig+le.join(e,r.slice(1)):le.join(e,r),kr=(r,e)=>r[e]===void 0,cg=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==kA&&e!==Vq&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await tH(n)}catch{this._removeWatcher&&this._removeWatcher(le.dirname(n),le.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;if(e)return[...e.values()]}dispose(){this.items.clear(),delete this.path,delete this._removeWatcher,delete this.items,Object.freeze(this)}},nH="stat",iH="lstat",lg=class{constructor(e,t,n,i){this.fsw=i,this.path=e=e.replace(Wq,og),this.watchPath=t,this.fullWatchPath=le.resolve(t),this.hasGlob=t!==e,e===og&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&n?void 0:!1,this.globFilter=this.hasGlob?ng(e,void 0,sg):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=n,this.statMethod=n?nH:iH}checkGlobSymlink(e){return this.globSymlink===void 0&&(this.globSymlink=e.fullParentDir===this.fullWatchPath?!1:{realPath:e.fullParentDir,linkPath:this.fullWatchPath}),this.globSymlink?e.fullPath.replace(this.globSymlink.realPath,this.globSymlink.linkPath):e.fullPath}entryPath(e){return le.join(this.watchPath,le.relative(this.watchPath,this.checkGlobSymlink(e)))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return(this.hasGlob&&typeof this.globFilter===Yq?this.globFilter(n):!0)&&this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}getDirParts(e){if(!this.hasGlob)return[];let t=[];return(e.includes(zq)?Pq.expand(e):[e]).forEach(i=>{t.push(le.relative(this.watchPath,i).split(Hq))}),t}filterDir(e){if(this.hasGlob){let t=this.getDirParts(this.checkGlobSymlink(e)),n=!1;this.unmatchedGlob=!this.dirParts.some(i=>i.every((s,o)=>(s===Kq&&(n=!0),n||!t[0][o]||ng(s,t[0][o],sg))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Iu=class extends kq{constructor(e){super();let t={};e&&Object.assign(t,e),this._watched=new Map,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._symlinkPaths=new Map,this._streams=new Set,this.closed=!1,kr(t,"persistent")&&(t.persistent=!0),kr(t,"ignoreInitial")&&(t.ignoreInitial=!1),kr(t,"ignorePermissionErrors")&&(t.ignorePermissionErrors=!1),kr(t,"interval")&&(t.interval=100),kr(t,"binaryInterval")&&(t.binaryInterval=300),kr(t,"disableGlobbing")&&(t.disableGlobbing=!1),t.enableBinaryInterval=t.binaryInterval!==t.interval,kr(t,"useFsEvents")&&(t.useFsEvents=!t.usePolling),wA.canUse()||(t.useFsEvents=!1),kr(t,"usePolling")&&!t.useFsEvents&&(t.usePolling=Zq),Qq&&(t.usePolling=!0);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let c=i.toLowerCase();c==="false"||c==="0"?t.usePolling=!1:c==="true"||c==="1"?t.usePolling=!0:t.usePolling=!!c}let s=process.env.CHOKIDAR_INTERVAL;s&&(t.interval=Number.parseInt(s,10)),kr(t,"atomic")&&(t.atomic=!t.usePolling&&!t.useFsEvents),t.atomic&&(this._pendingUnlinks=new Map),kr(t,"followSymlinks")&&(t.followSymlinks=!0),kr(t,"awaitWriteFinish")&&(t.awaitWriteFinish=!1),t.awaitWriteFinish===!0&&(t.awaitWriteFinish={});let o=t.awaitWriteFinish;o&&(o.stabilityThreshold||(o.stabilityThreshold=2e3),o.pollInterval||(o.pollInterval=100),this._pendingWrites=new Map),t.ignored&&(t.ignored=ag(t.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Jq,this._readyEmitted=!0,process.nextTick(()=>this.emit(Lq)))},this._emitRaw=(...c)=>this.emit(jq,...c),this._readyEmitted=!1,this.options=t,t.useFsEvents?this._fsEventsHandler=new wA(this):this._nodeFsHandler=new Nq(this),Object.freeze(t)}add(e,t,n){let{cwd:i,disableGlobbing:s}=this.options;this.closed=!1;let o=TA(e);return i&&(o=o.map(a=>{let c=rH(a,i);return s||!Zm(a)?c:Iq(c)})),o=o.filter(a=>a.startsWith(ig)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+rg),this._userIgnored=void 0,!0)),this.options.useFsEvents&&this._fsEventsHandler?(this._readyCount||(this._readyCount=o.length),this.options.persistent&&(this._readyCount+=o.length),o.forEach(a=>this._fsEventsHandler._addToFsEvents(a))):(this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!n,0,0,t);return c&&this._emitReady(),c})).then(a=>{this.closed||a.filter(c=>c).forEach(c=>{this.add(le.dirname(c),le.basename(t||c))})})),this}unwatch(e){if(this.closed)return this;let t=TA(e),{cwd:n}=this.options;return t.forEach(i=>{!le.isAbsolute(i)&&!this._closers.has(i)&&(n&&(i=le.join(n,i)),i=le.resolve(i)),this._closePath(i),this._ignoredPaths.add(i),this._watched.has(i)&&this._ignoredPaths.add(i+rg),this._userIgnored=void 0}),this}close(){if(this.closed)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(n=>{let i=n();i instanceof Promise&&e.push(i)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),["closers","watched","streams","symlinkPaths","throttled"].forEach(t=>{this[`_${t}`].clear()}),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let i=this.options.cwd?le.relative(this.options.cwd,n):n;e[i||kA]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(...t),e!==eg&&this.emit(Qm,...t)}async _emit(e,t,n,i,s){if(this.closed)return;let o=this.options;Xq&&(t=le.normalize(t)),o.cwd&&(t=le.relative(o.cwd,t));let a=[e,t];s!==void 0?a.push(n,i,s):i!==void 0?a.push(n,i):n!==void 0&&a.push(n);let c=o.awaitWriteFinish,l;if(c&&(l=this._pendingWrites.get(t)))return l.lastChange=new Date,this;if(o.atomic){if(e===SA)return this._pendingUnlinks.set(t,a),setTimeout(()=>{this._pendingUnlinks.forEach((p,f)=>{this.emit(...p),this.emit(Qm,...p),this._pendingUnlinks.delete(f)})},typeof o.atomic=="number"?o.atomic:100),this;e===Pu&&this._pendingUnlinks.has(t)&&(e=a[0]=ga,this._pendingUnlinks.delete(t))}if(c&&(e===Pu||e===ga)&&this._readyEmitted){let p=(f,h)=>{f?(e=a[0]=eg,a[1]=f,this.emitWithAll(e,a)):h&&(a.length>2?a[2]=h:a.push(h),this.emitWithAll(e,a))};return this._awaitWriteFinish(t,c.stabilityThreshold,e,p),this}if(e===ga&&!this._throttle(ga,t,50))return this;if(o.alwaysStat&&n===void 0&&(e===Pu||e===Dq||e===ga)){let p=o.cwd?le.join(o.cwd,t):t,f;try{f=await eH(p)}catch{}if(!f||this.closed)return;a.push(f)}return this.emitWithAll(e,a),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(eg,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let i=this._throttled.get(e),s=i.get(t);if(s)return s.count++,!1;let o,a=()=>{let l=i.get(t),p=l?l.count:0;return i.delete(t),clearTimeout(o),l&&clearTimeout(l.timeoutObject),p};o=setTimeout(a,n);let c={timeoutObject:o,clear:a,count:0};return i.set(t,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,i){let s,o=e;this.options.cwd&&!le.isAbsolute(e)&&(o=le.join(this.options.cwd,e));let a=new Date,c=l=>{ug.stat(o,(p,f)=>{if(p||!this._pendingWrites.has(e)){p&&p.code!=="ENOENT"&&i(p);return}let h=Number(new Date);l&&f.size!==l.size&&(this._pendingWrites.get(e).lastChange=h);let v=this._pendingWrites.get(e);h-v.lastChange>=t?(this._pendingWrites.delete(e),i(void 0,f)):s=setTimeout(c,this.options.awaitWriteFinish.pollInterval,f)})};this._pendingWrites.has(e)||(this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>(this._pendingWrites.delete(e),clearTimeout(s),n)}),s=setTimeout(c,this.options.awaitWriteFinish.pollInterval))}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,t){if(this.options.atomic&&$q.test(e))return!0;if(!this._userIgnored){let{cwd:n}=this.options,i=this.options.ignored,s=i&&i.map(AA(n)),o=ag(s).filter(c=>typeof c===pg&&!Zm(c)).map(c=>c+rg),a=this._getGlobIgnored().map(AA(n)).concat(s,o);this._userIgnored=ng(a,void 0,sg)}return this._userIgnored([e,t])}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e,t){let n=t||this.options.disableGlobbing||!Zm(e)?e:Mq(e),i=this.options.followSymlinks;return new lg(e,n,i,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let t=le.resolve(e);return this._watched.has(t)||this._watched.set(t,new cg(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){if(this.options.ignorePermissionErrors)return!0;let n=(e&&Number.parseInt(e.mode,10))&511;return!!(4&Number.parseInt(n.toString(8)[0],10))}_remove(e,t,n){let i=le.join(e,t),s=le.resolve(i);if(n=n??(this._watched.has(i)||this._watched.has(s)),!this._throttle("remove",i,100))return;!n&&!this.options.useFsEvents&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(i).getChildren().forEach(h=>this._remove(i,h));let c=this._getWatchedDir(e),l=c.has(t);c.remove(t),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let p=i;if(this.options.cwd&&(p=le.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(p)&&this._pendingWrites.get(p).cancelWait()===Pu)return;this._watched.delete(i),this._watched.delete(s);let f=n?Bq:SA;l&&!this._isIgnored(i)&&this._emit(f,i),this.options.useFsEvents||this._closePath(i)}_closePath(e){this._closeFile(e);let t=le.dirname(e);this._getWatchedDir(t).remove(le.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(n=>n()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n={type:Qm,alwaysStat:!0,lstat:!0,...t},i=Oq(e,n);return this._streams.add(i),i.once(Fq,()=>{i=void 0}),i.once(Uq,()=>{i&&(this._streams.delete(i),i=void 0)}),i}};fg.FSWatcher=Iu;var sH=(r,e)=>{let t=new Iu(e);return t.add(r),t};fg.watch=sH});var bR=R((xz,vg)=>{"use strict";var fH=Object.prototype.hasOwnProperty,Ot="~";function wa(){}Object.create&&(wa.prototype=Object.create(null),new wa().__proto__||(Ot=!1));function dH(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function _R(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var s=new dH(t,n||r,i),o=Ot?Ot+e:e;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],s]:r._events[o].push(s):(r._events[o]=s,r._eventsCount++),r}function qu(r,e){--r._eventsCount===0?r._events=new wa:delete r._events[e]}function Et(){this._events=new wa,this._eventsCount=0}Et.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)fH.call(t,n)&&e.push(Ot?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};Et.prototype.listeners=function(e){var t=Ot?Ot+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o};Et.prototype.listenerCount=function(e){var t=Ot?Ot+e:e,n=this._events[t];return n?n.fn?1:n.length:0};Et.prototype.emit=function(e,t,n,i,s,o){var a=Ot?Ot+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,p,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,s),!0;case 6:return c.fn.call(c.context,t,n,i,s,o),!0}for(f=1,p=new Array(l-1);f<l;f++)p[f-1]=arguments[f];c.fn.apply(c.context,p)}else{var h=c.length,v;for(f=0;f<h;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,i);break;default:if(!p)for(v=1,p=new Array(l-1);v<l;v++)p[v-1]=arguments[v];c[f].fn.apply(c[f].context,p)}}return!0};Et.prototype.on=function(e,t,n){return _R(this,e,t,n,!1)};Et.prototype.once=function(e,t,n){return _R(this,e,t,n,!0)};Et.prototype.removeListener=function(e,t,n,i){var s=Ot?Ot+e:e;if(!this._events[s])return this;if(!t)return qu(this,s),this;var o=this._events[s];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&qu(this,s);else{for(var a=0,c=[],l=o.length;a<l;a++)(o[a].fn!==t||i&&!o[a].once||n&&o[a].context!==n)&&c.push(o[a]);c.length?this._events[s]=c.length===1?c[0]:c:qu(this,s)}return this};Et.prototype.removeAllListeners=function(e){var t;return e?(t=Ot?Ot+e:e,this._events[t]&&qu(this,t)):(this._events=new wa,this._eventsCount=0),this};Et.prototype.off=Et.prototype.removeListener;Et.prototype.addListener=Et.prototype.on;Et.prefixed=Ot;Et.EventEmitter=Et;typeof vg<"u"&&(vg.exports=Et)});var SR=R((_z,wR)=>{"use strict";wR.exports=function(e,t){if(t=t.split(":")[0],e=+e,!e)return!1;switch(t){case"http":case"ws":return e!==80;case"https":case"wss":return e!==443;case"ftp":return e!==21;case"gopher":return e!==70;case"file":return!1}return e!==0}});var Hu=R(TR=>{var wn=TR,hH=require("url"),ER=require("util")._extend,mH=SR(),gH=/(^|,)\s*upgrade\s*($|,)/i,yg=/^https|wss/;wn.isSSL=yg;wn.setupOutgoing=function(r,e,t,n){r.port=e[n||"target"].port||(yg.test(e[n||"target"].protocol)?443:80),["host","hostname","socketPath","pfx","key","passphrase","cert","ca","ciphers","secureProtocol"].forEach(function(a){r[a]=e[n||"target"][a]}),r.method=e.method||t.method,r.headers=ER({},t.headers),e.headers&&ER(r.headers,e.headers),e.auth&&(r.auth=e.auth),e.ca&&(r.ca=e.ca),yg.test(e[n||"target"].protocol)&&(r.rejectUnauthorized=typeof e.secure>"u"?!0:e.secure),r.agent=e.agent||!1,r.localAddress=e.localAddress,r.agent||(r.headers=r.headers||{},(typeof r.headers.connection!="string"||!gH.test(r.headers.connection))&&(r.headers.connection="close"));var i=e[n||"target"],s=i&&e.prependPath!==!1&&i.path||"",o=e.toProxy?t.url:hH.parse(t.url).path||"";return o=e.ignorePath?"":o,r.path=wn.urlJoin(s,o),e.changeOrigin&&(r.headers.host=mH(r.port,e[n||"target"].protocol)&&!vH(r.host)?r.host+":"+r.port:r.host),r};wn.setupSocket=function(r){return r.setTimeout(0),r.setNoDelay(!0),r.setKeepAlive(!0,0),r};wn.getPort=function(r){var e=r.headers.host?r.headers.host.match(/:(\d+)/):"";return e?e[1]:wn.hasEncryptedConnection(r)?"443":"80"};wn.hasEncryptedConnection=function(r){return!!(r.connection.encrypted||r.connection.pair)};wn.urlJoin=function(){var r=Array.prototype.slice.call(arguments),e=r.length-1,t=r[e],n=t.split("?"),i;return r[e]=n.shift(),i=[r.filter(Boolean).join("/").replace(/\/+/g,"/").replace("http:/","http://").replace("https:/","https://")],i.push.apply(i,n),i.join("?")};wn.rewriteCookieProperty=function r(e,t,n){return Array.isArray(e)?e.map(function(i){return r(i,t,n)}):e.replace(new RegExp("(;\\s*"+n+"=)([^;]+)","i"),function(i,s,o){var a;if(o in t)a=t[o];else if("*"in t)a=t["*"];else return i;return a?s+a:""})};function vH(r){return!!~r.indexOf(":")}});var kR=R((wz,RR)=>{var CR=require("url"),AR=Hu(),yH=/^201|30(1|2|7|8)$/;RR.exports={removeChunked:function(e,t,n){e.httpVersion==="1.0"&&delete n.headers["transfer-encoding"]},setConnection:function(e,t,n){e.httpVersion==="1.0"?n.headers.connection=e.headers.connection||"close":e.httpVersion!=="2.0"&&!n.headers.connection&&(n.headers.connection=e.headers.connection||"keep-alive")},setRedirectHostRewrite:function(e,t,n,i){if((i.hostRewrite||i.autoRewrite||i.protocolRewrite)&&n.headers.location&&yH.test(n.statusCode)){var s=CR.parse(i.target),o=CR.parse(n.headers.location);if(s.host!=o.host)return;i.hostRewrite?o.host=i.hostRewrite:i.autoRewrite&&(o.host=e.headers.host),i.protocolRewrite&&(o.protocol=i.protocolRewrite),n.headers.location=o.format()}},writeHeaders:function(e,t,n,i){var s=i.cookieDomainRewrite,o=i.cookiePathRewrite,a=i.preserveHeaderKeyCase,c,l=function(h,v){v!=null&&(s&&h.toLowerCase()==="set-cookie"&&(v=AR.rewriteCookieProperty(v,s,"domain")),o&&h.toLowerCase()==="set-cookie"&&(v=AR.rewriteCookieProperty(v,o,"path")),t.setHeader(String(h).trim(),v))};if(typeof s=="string"&&(s={"*":s}),typeof o=="string"&&(o={"*":o}),a&&n.rawHeaders!=null){c={};for(var p=0;p<n.rawHeaders.length;p+=2){var f=n.rawHeaders[p];c[f.toLowerCase()]=f}}Object.keys(n.headers).forEach(function(h){var v=n.headers[h];a&&c&&(h=c[h]||h),l(h,v)})},writeStatusCode:function(e,t,n){n.statusMessage?(t.statusCode=n.statusCode,t.statusMessage=n.statusMessage):t.statusCode=n.statusCode}}});var MR=R((Sz,OR)=>{var Sa;OR.exports=function(){if(!Sa){try{Sa=Ce()("follow-redirects")}catch{}typeof Sa!="function"&&(Sa=function(){})}Sa.apply(null,arguments)}});var DR=R((Ez,Og)=>{var Ta=require("url"),Ea=Ta.URL,xH=require("http"),_H=require("https"),Sg=require("stream").Writable,Eg=require("assert"),PR=MR();(function(){var e=typeof process<"u",t=typeof window<"u"&&typeof document<"u",n=Ci(Error.captureStackTrace);!e&&(t||!n)&&console.warn("The follow-redirects package should be excluded from browser builds.")})();var Tg=!1;try{Eg(new Ea(""))}catch(r){Tg=r.code==="ERR_INVALID_URL"}var bH=["Authorization","Proxy-Authorization","Cookie"],wH=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],Cg=["abort","aborted","connect","error","socket","timeout"],Ag=Object.create(null);Cg.forEach(function(r){Ag[r]=function(e,t,n){this._redirectable.emit(r,e,t,n)}});var _g=Ca("ERR_INVALID_URL","Invalid URL",TypeError),bg=Ca("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),SH=Ca("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",bg),EH=Ca("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),TH=Ca("ERR_STREAM_WRITE_AFTER_END","write after end"),CH=Sg.prototype.destroy||NR;function Ht(r,e){Sg.call(this),this._sanitizeOptions(r),this._options=r,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],e&&this.on("response",e);var t=this;this._onNativeResponse=function(n){try{t._processResponse(n)}catch(i){t.emit("error",i instanceof bg?i:new bg({cause:i}))}},this._headerFilter=new RegExp("^(?:"+bH.concat(r.sensitiveHeaders).map(PH).join("|")+")$","i"),this._performRequest()}Ht.prototype=Object.create(Sg.prototype);Ht.prototype.abort=function(){kg(this._currentRequest),this._currentRequest.abort(),this.emit("abort")};Ht.prototype.destroy=function(r){return kg(this._currentRequest,r),CH.call(this,r),this};Ht.prototype.write=function(r,e,t){if(this._ending)throw new TH;if(!Ti(r)&&!OH(r))throw new TypeError("data should be a string, Buffer or Uint8Array");if(Ci(e)&&(t=e,e=null),r.length===0){t&&t();return}this._requestBodyLength+r.length<=this._options.maxBodyLength?(this._requestBodyLength+=r.length,this._requestBodyBuffers.push({data:r,encoding:e}),this._currentRequest.write(r,e,t)):(this.emit("error",new EH),this.abort())};Ht.prototype.end=function(r,e,t){if(Ci(r)?(t=r,r=e=null):Ci(e)&&(t=e,e=null),!r)this._ended=this._ending=!0,this._currentRequest.end(null,null,t);else{var n=this,i=this._currentRequest;this.write(r,e,function(){n._ended=!0,i.end(null,null,t)}),this._ending=!0}};Ht.prototype.setHeader=function(r,e){this._options.headers[r]=e,this._currentRequest.setHeader(r,e)};Ht.prototype.removeHeader=function(r){delete this._options.headers[r],this._currentRequest.removeHeader(r)};Ht.prototype.setTimeout=function(r,e){var t=this;function n(o){o.setTimeout(r),o.removeListener("timeout",o.destroy),o.addListener("timeout",o.destroy)}function i(o){t._timeout&&clearTimeout(t._timeout),t._timeout=setTimeout(function(){t.emit("timeout"),s()},r),n(o)}function s(){t._timeout&&(clearTimeout(t._timeout),t._timeout=null),t.removeListener("abort",s),t.removeListener("error",s),t.removeListener("response",s),t.removeListener("close",s),e&&t.removeListener("timeout",e),t.socket||t._currentRequest.removeListener("socket",i)}return e&&this.on("timeout",e),this.socket?i(this.socket):this._currentRequest.once("socket",i),this.on("socket",n),this.on("abort",s),this.on("error",s),this.on("response",s),this.on("close",s),this};["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(r){Ht.prototype[r]=function(e,t){return this._currentRequest[r](e,t)}});["aborted","connection","socket"].forEach(function(r){Object.defineProperty(Ht.prototype,r,{get:function(){return this._currentRequest[r]}})});Ht.prototype._sanitizeOptions=function(r){if(r.headers||(r.headers={}),kH(r.sensitiveHeaders)||(r.sensitiveHeaders=[]),r.host&&(r.hostname||(r.hostname=r.host),delete r.host),!r.pathname&&r.path){var e=r.path.indexOf("?");e<0?r.pathname=r.path:(r.pathname=r.path.substring(0,e),r.search=r.path.substring(e))}};Ht.prototype._performRequest=function(){var r=this._options.protocol,e=this._options.nativeProtocols[r];if(!e)throw new TypeError("Unsupported protocol "+r);if(this._options.agents){var t=r.slice(0,-1);this._options.agent=this._options.agents[t]}var n=this._currentRequest=e.request(this._options,this._onNativeResponse);n._redirectable=this;for(var i of Cg)n.on(i,Ag[i]);if(this._currentUrl=/^\//.test(this._options.path)?Ta.format(this._options):this._options.path,this._isRedirect){var s=0,o=this,a=this._requestBodyBuffers;(function c(l){if(n===o._currentRequest)if(l)o.emit("error",l);else if(s<a.length){var p=a[s++];n.finished||n.write(p.data,p.encoding,c)}else o._ended&&n.end()})()}};Ht.prototype._processResponse=function(r){var e=r.statusCode;this._options.trackRedirects&&this._redirects.push({url:this._currentUrl,headers:r.headers,statusCode:e});var t=r.headers.location;if(!t||this._options.followRedirects===!1||e<300||e>=400){r.responseUrl=this._currentUrl,r.redirects=this._redirects,this.emit("response",r),this._requestBodyBuffers=[];return}if(kg(this._currentRequest),r.destroy(),++this._redirectCount>this._options.maxRedirects)throw new SH;var n,i=this._options.beforeRedirect;i&&(n=Object.assign({Host:r.req.getHeader("host")},this._options.headers));var s=this._options.method;((e===301||e===302)&&this._options.method==="POST"||e===303&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],xg(/^content-/i,this._options.headers));var o=xg(/^host$/i,this._options.headers),a=Rg(this._currentUrl),c=o||a.host,l=/^\w+:/.test(t)?this._currentUrl:Ta.format(Object.assign(a,{host:c})),p=AH(t,l);if(PR("redirecting to",p.href),this._isRedirect=!0,wg(p,this._options),(p.protocol!==a.protocol&&p.protocol!=="https:"||p.host!==c&&!RH(p.host,c))&&xg(this._headerFilter,this._options.headers),Ci(i)){var f={headers:r.headers,statusCode:e},h={url:l,method:s,headers:n};i(this._options,f,h),this._sanitizeOptions(this._options)}this._performRequest()};function IR(r){var e={maxRedirects:21,maxBodyLength:10485760},t={};return Object.keys(r).forEach(function(n){var i=n+":",s=t[i]=r[n],o=e[n]=Object.create(s);function a(l,p,f){return MH(l)?l=wg(l):Ti(l)?l=wg(Rg(l)):(f=p,p=LR(l),l={protocol:i}),Ci(p)&&(f=p,p=null),p=Object.assign({maxRedirects:e.maxRedirects,maxBodyLength:e.maxBodyLength},l,p),p.nativeProtocols=t,!Ti(p.host)&&!Ti(p.hostname)&&(p.hostname="::1"),Eg.equal(p.protocol,i,"protocol mismatch"),PR("options",p),new Ht(p,f)}function c(l,p,f){var h=o.request(l,p,f);return h.end(),h}Object.defineProperties(o,{request:{value:a,configurable:!0,enumerable:!0,writable:!0},get:{value:c,configurable:!0,enumerable:!0,writable:!0}})}),e}function NR(){}function Rg(r){var e;if(Tg)e=new Ea(r);else if(e=LR(Ta.parse(r)),!Ti(e.protocol))throw new _g({input:r});return e}function AH(r,e){return Tg?new Ea(r,e):Rg(Ta.resolve(e,r))}function LR(r){if(/^\[/.test(r.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(r.hostname))throw new _g({input:r.href||r});if(/^\[/.test(r.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(r.host))throw new _g({input:r.href||r});return r}function wg(r,e){var t=e||{};for(var n of wH)t[n]=r[n];return t.hostname.startsWith("[")&&(t.hostname=t.hostname.slice(1,-1)),t.port!==""&&(t.port=Number(t.port)),t.path=t.search?t.pathname+t.search:t.pathname,t}function xg(r,e){var t;for(var n in e)r.test(n)&&(t=e[n],delete e[n]);return t===null||typeof t>"u"?void 0:String(t).trim()}function Ca(r,e,t){function n(i){Ci(Error.captureStackTrace)&&Error.captureStackTrace(this,this.constructor),Object.assign(this,i||{}),this.code=r,this.message=this.cause?e+": "+this.cause.message:e}return n.prototype=new(t||Error),Object.defineProperties(n.prototype,{constructor:{value:n,enumerable:!1},name:{value:"Error ["+r+"]",enumerable:!1}}),n}function kg(r,e){for(var t of Cg)r.removeListener(t,Ag[t]);r.on("error",NR),r.destroy(e)}function RH(r,e){Eg(Ti(r)&&Ti(e));var t=r.length-e.length-1;return t>0&&r[t]==="."&&r.endsWith(e)}function kH(r){return r instanceof Array}function Ti(r){return typeof r=="string"||r instanceof String}function Ci(r){return typeof r=="function"}function OH(r){return typeof r=="object"&&"length"in r}function MH(r){return Ea&&r instanceof Ea}function PH(r){return r.replace(/[\]\\/()*+?.$]/g,"\\$&")}Og.exports=IR({http:xH,https:_H});Og.exports.wrap=IR});var jR=R((Tz,BR)=>{var IH=require("http"),NH=require("https"),Aa=kR(),$u=Hu(),LH=DR();Aa=Object.keys(Aa).map(function(r){return Aa[r]});var DH={http:IH,https:NH};BR.exports={deleteLength:function(e,t,n){(e.method==="DELETE"||e.method==="OPTIONS")&&!e.headers["content-length"]&&(e.headers["content-length"]="0",delete e.headers["transfer-encoding"])},timeout:function(e,t,n){n.timeout&&e.socket.setTimeout(n.timeout)},XHeaders:function(e,t,n){if(n.xfwd){var i=e.isSpdy||$u.hasEncryptedConnection(e),s={for:e.connection.remoteAddress||e.socket.remoteAddress,port:$u.getPort(e),proto:i?"https":"http"};["for","port","proto"].forEach(function(o){e.headers["x-forwarded-"+o]=(e.headers["x-forwarded-"+o]||"")+(e.headers["x-forwarded-"+o]?",":"")+s[o]}),e.headers["x-forwarded-host"]=e.headers["x-forwarded-host"]||e.headers.host||""}},stream:function(e,t,n,i,s,o){s.emit("start",e,t,n.target||n.forward);var a=n.followRedirects?LH:DH,c=a.http,l=a.https;if(n.forward){var p=(n.forward.protocol==="https:"?l:c).request($u.setupOutgoing(n.ssl||{},n,e,"forward")),f=x(p,n.forward);if(e.on("error",f),p.on("error",f),(n.buffer||e).pipe(p),!n.target)return t.end()}var h=(n.target.protocol==="https:"?l:c).request($u.setupOutgoing(n.ssl||{},n,e));h.on("socket",function(S){s&&!h.getHeader("expect")&&s.emit("proxyReq",h,e,t,n)}),n.proxyTimeout&&h.setTimeout(n.proxyTimeout,function(){h.abort()}),e.on("aborted",function(){h.abort()});var v=x(h,n.target);e.on("error",v),h.on("error",v);function x(S,A){return function(P){if(e.socket.destroyed&&P.code==="ECONNRESET")return s.emit("econnreset",P,e,t,A),S.abort();o?o(P,e,t,A):s.emit("error",P,e,t,A)}}(n.buffer||e).pipe(h),h.on("response",function(S){if(s&&s.emit("proxyRes",S,e,t),!t.headersSent&&!n.selfHandleResponse)for(var A=0;A<Aa.length&&!Aa[A](e,t,S,n);A++);t.finished?s&&s.emit("end",e,t,S):(S.on("end",function(){s&&s.emit("end",e,t,S)}),n.selfHandleResponse||S.pipe(t))})}}});var UR=R((Cz,FR)=>{var BH=require("http"),jH=require("https"),Xs=Hu();FR.exports={checkMethodAndHeader:function(e,t){if(e.method!=="GET"||!e.headers.upgrade||e.headers.upgrade.toLowerCase()!=="websocket")return t.destroy(),!0},XHeaders:function(e,t,n){if(n.xfwd){var i={for:e.connection.remoteAddress||e.socket.remoteAddress,port:Xs.getPort(e),proto:Xs.hasEncryptedConnection(e)?"wss":"ws"};["for","port","proto"].forEach(function(s){e.headers["x-forwarded-"+s]=(e.headers["x-forwarded-"+s]||"")+(e.headers["x-forwarded-"+s]?",":"")+i[s]})}},stream:function(e,t,n,i,s,o){var a=function(p,f){return Object.keys(f).reduce(function(h,v){var x=f[v];if(!Array.isArray(x))return h.push(v+": "+x),h;for(var S=0;S<x.length;S++)h.push(v+": "+x[S]);return h},[p]).join(`\r
103
103
  `)+`\r
104
104
  \r
105
- `};Xs.setupSocket(t),i&&i.length&&t.unshift(i);var c=(Xs.isSSL.test(n.target.protocol)?jH:BH).request(Xs.setupOutgoing(n.ssl||{},n,e));return s&&s.emit("proxyReqWs",c,e,t,n,i),c.on("error",l),c.on("response",function(p){p.upgrade||(t.write(a("HTTP/"+p.httpVersion+" "+p.statusCode+" "+p.statusMessage,p.headers)),p.pipe(t))}),c.on("upgrade",function(p,f,h){f.on("error",l),f.on("end",function(){s.emit("close",p,f,h)}),t.on("error",function(){f.end()}),Xs.setupSocket(f),h&&h.length&&f.unshift(h),t.write(a("HTTP/1.1 101 Switching Protocols",p.headers)),f.pipe(t).pipe(f),s.emit("open",f),s.emit("proxySocket",f)}),c.end();function l(p){o?o(p,e,t):s.emit("error",p,e,t),t.end()}}}});var VR=R((Rz,zR)=>{var WR=zR.exports,qR=require("util")._extend,FH=require("url").parse,GR=bR(),UH=require("http"),qH=require("https"),HR=jR(),$R=UR();WR.Server=Ai;function Mg(r){return function(e){return function(t,n){var i=r==="ws"?this.wsPasses:this.webPasses,s=[].slice.call(arguments),o=s.length-1,a,c;typeof s[o]=="function"&&(c=s[o],o--);var l=e;if(!(s[o]instanceof Buffer)&&s[o]!==n&&(l=qR({},e),qR(l,s[o]),o--),s[o]instanceof Buffer&&(a=s[o]),["target","forward"].forEach(function(f){typeof l[f]=="string"&&(l[f]=FH(l[f]))}),!l.target&&!l.forward)return this.emit("error",new Error("Must provide a proper URL as target"));for(var p=0;p<i.length&&!i[p](t,n,l,a,this,c);p++);}}}WR.createRightProxy=Mg;function Ai(r){GR.call(this),r=r||{},r.prependPath=r.prependPath!==!1,this.web=this.proxyRequest=Mg("web")(r),this.ws=this.proxyWebsocketRequest=Mg("ws")(r),this.options=r,this.webPasses=Object.keys(HR).map(function(e){return HR[e]}),this.wsPasses=Object.keys($R).map(function(e){return $R[e]}),this.on("error",this.onError,this)}require("util").inherits(Ai,GR);Ai.prototype.onError=function(r){if(this.listeners("error").length===1)throw r};Ai.prototype.listen=function(r,e){var t=this,n=function(i,s){t.web(i,s)};return this._server=this.options.ssl?qH.createServer(this.options.ssl,n):UH.createServer(n),this.options.ws&&this._server.on("upgrade",function(i,s,o){t.ws(i,s,o)}),this._server.listen(r,e),this};Ai.prototype.close=function(r){var e=this;this._server&&this._server.close(t);function t(){e._server=null,r&&r.apply(null,arguments)}};Ai.prototype.before=function(r,e,t){if(r!=="ws"&&r!=="web")throw new Error("type must be `web` or `ws`");var n=r==="ws"?this.wsPasses:this.webPasses,i=!1;if(n.forEach(function(s,o){s.name===e&&(i=o)}),i===!1)throw new Error("No such pass");n.splice(i,0,t)};Ai.prototype.after=function(r,e,t){if(r!=="ws"&&r!=="web")throw new Error("type must be `web` or `ws`");var n=r==="ws"?this.wsPasses:this.webPasses,i=!1;if(n.forEach(function(s,o){s.name===e&&(i=o)}),i===!1)throw new Error("No such pass");n.splice(i++,0,t)}});var YR=R((kz,KR)=>{var Ra=VR().Server;function Pg(r){return new Ra(r)}Ra.createProxyServer=Pg;Ra.createServer=Pg;Ra.createProxy=Pg;KR.exports=Ra});var XR=R((Oz,JR)=>{JR.exports=YR()});var _k=R((Oa,Ng)=>{(function(r,e){typeof Oa=="object"&&typeof Ng=="object"?Ng.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof Oa=="object"?Oa["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(Oa,function(r,e){return(function(t){function n(s){if(i[s])return i[s].exports;var o=i[s]={exports:{},id:s,loaded:!1};return t[s].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var i={};return n.m=t,n.c=i,n.p="",n(0)})([function(t,n,i){t.exports=i(34)},function(t,n,i){var s=i(29)("wks"),o=i(33),a=i(2).Symbol,c=typeof a=="function",l=t.exports=function(p){return s[p]||(s[p]=c&&a[p]||(c?a:o)("Symbol."+p))};l.store=s},function(t,n){var i=t.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=i)},function(t,n,i){var s=i(9);t.exports=function(o){if(!s(o))throw TypeError(o+" is not an object!");return o}},function(t,n,i){t.exports=!i(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,n,i){var s=i(12),o=i(17);t.exports=i(4)?function(a,c,l){return s.f(a,c,o(1,l))}:function(a,c,l){return a[c]=l,a}},function(t,n){var i=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=i)},function(t,n,i){var s=i(14);t.exports=function(o,a,c){if(s(o),a===void 0)return o;switch(c){case 1:return function(l){return o.call(a,l)};case 2:return function(l,p){return o.call(a,l,p)};case 3:return function(l,p,f){return o.call(a,l,p,f)}}return function(){return o.apply(a,arguments)}}},function(t,n){var i={}.hasOwnProperty;t.exports=function(s,o){return i.call(s,o)}},function(t,n){t.exports=function(i){return typeof i=="object"?i!==null:typeof i=="function"}},function(t,n){t.exports={}},function(t,n){var i={}.toString;t.exports=function(s){return i.call(s).slice(8,-1)}},function(t,n,i){var s=i(3),o=i(26),a=i(32),c=Object.defineProperty;n.f=i(4)?Object.defineProperty:function(l,p,f){if(s(l),p=a(p,!0),s(f),o)try{return c(l,p,f)}catch{}if("get"in f||"set"in f)throw TypeError("Accessors not supported!");return"value"in f&&(l[p]=f.value),l}},function(t,n,i){var s=i(42),o=i(15);t.exports=function(a){return s(o(a))}},function(t,n){t.exports=function(i){if(typeof i!="function")throw TypeError(i+" is not a function!");return i}},function(t,n){t.exports=function(i){if(i==null)throw TypeError("Can't call method on "+i);return i}},function(t,n,i){var s=i(9),o=i(2).document,a=s(o)&&s(o.createElement);t.exports=function(c){return a?o.createElement(c):{}}},function(t,n){t.exports=function(i,s){return{enumerable:!(1&i),configurable:!(2&i),writable:!(4&i),value:s}}},function(t,n,i){var s=i(12).f,o=i(8),a=i(1)("toStringTag");t.exports=function(c,l,p){c&&!o(c=p?c:c.prototype,a)&&s(c,a,{configurable:!0,value:l})}},function(t,n,i){var s=i(29)("keys"),o=i(33);t.exports=function(a){return s[a]||(s[a]=o(a))}},function(t,n){var i=Math.ceil,s=Math.floor;t.exports=function(o){return isNaN(o=+o)?0:(o>0?s:i)(o)}},function(t,n,i){var s=i(11),o=i(1)("toStringTag"),a=s((function(){return arguments})())=="Arguments",c=function(l,p){try{return l[p]}catch{}};t.exports=function(l){var p,f,h;return l===void 0?"Undefined":l===null?"Null":typeof(f=c(p=Object(l),o))=="string"?f:a?s(p):(h=s(p))=="Object"&&typeof p.callee=="function"?"Arguments":h}},function(t,n){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,n,i){var s=i(2),o=i(6),a=i(7),c=i(5),l="prototype",p=function(f,h,v){var x,S,A,k=f&p.F,P=f&p.G,I=f&p.S,B=f&p.P,V=f&p.B,F=f&p.W,G=P?o:o[h]||(o[h]={}),L=G[l],H=P?s:I?s[h]:(s[h]||{})[l];P&&(v=h);for(x in v)S=!k&&H&&H[x]!==void 0,S&&x in G||(A=S?H[x]:v[x],G[x]=P&&typeof H[x]!="function"?v[x]:V&&S?a(A,s):F&&H[x]==A?(function(T){var u=function(m,y,w){if(this instanceof T){switch(arguments.length){case 0:return new T;case 1:return new T(m);case 2:return new T(m,y)}return new T(m,y,w)}return T.apply(this,arguments)};return u[l]=T[l],u})(A):B&&typeof A=="function"?a(Function.call,A):A,B&&((G.virtual||(G.virtual={}))[x]=A,f&p.R&&L&&!L[x]&&c(L,x,A)))};p.F=1,p.G=2,p.S=4,p.P=8,p.B=16,p.W=32,p.U=64,p.R=128,t.exports=p},function(t,n){t.exports=function(i){try{return!!i()}catch{return!0}}},function(t,n,i){t.exports=i(2).document&&document.documentElement},function(t,n,i){t.exports=!i(4)&&!i(24)(function(){return Object.defineProperty(i(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,n,i){"use strict";var s=i(28),o=i(23),a=i(57),c=i(5),l=i(8),p=i(10),f=i(45),h=i(18),v=i(52),x=i(1)("iterator"),S=!([].keys&&"next"in[].keys()),A="@@iterator",k="keys",P="values",I=function(){return this};t.exports=function(B,V,F,G,L,H,T){f(F,V,G);var u,m,y,w=function(M){if(!S&&M in b)return b[M];switch(M){case k:return function(){return new F(this,M)};case P:return function(){return new F(this,M)}}return function(){return new F(this,M)}},g=V+" Iterator",_=L==P,C=!1,b=B.prototype,d=b[x]||b[A]||L&&b[L],E=d||w(L),q=L?_?w("entries"):E:void 0,O=V=="Array"&&b.entries||d;if(O&&(y=v(O.call(new B)),y!==Object.prototype&&(h(y,g,!0),s||l(y,x)||c(y,x,I))),_&&d&&d.name!==P&&(C=!0,E=function(){return d.call(this)}),s&&!T||!S&&!C&&b[x]||c(b,x,E),p[V]=E,p[g]=I,L)if(u={values:_?E:w(P),keys:H?E:w(k),entries:q},T)for(m in u)m in b||a(b,m,u[m]);else o(o.P+o.F*(S||C),V,u);return u}},function(t,n){t.exports=!0},function(t,n,i){var s=i(2),o="__core-js_shared__",a=s[o]||(s[o]={});t.exports=function(c){return a[c]||(a[c]={})}},function(t,n,i){var s,o,a,c=i(7),l=i(41),p=i(25),f=i(16),h=i(2),v=h.process,x=h.setImmediate,S=h.clearImmediate,A=h.MessageChannel,k=0,P={},I="onreadystatechange",B=function(){var F=+this;if(P.hasOwnProperty(F)){var G=P[F];delete P[F],G()}},V=function(F){B.call(F.data)};x&&S||(x=function(F){for(var G=[],L=1;arguments.length>L;)G.push(arguments[L++]);return P[++k]=function(){l(typeof F=="function"?F:Function(F),G)},s(k),k},S=function(F){delete P[F]},i(11)(v)=="process"?s=function(F){v.nextTick(c(B,F,1))}:A?(o=new A,a=o.port2,o.port1.onmessage=V,s=c(a.postMessage,a,1)):h.addEventListener&&typeof postMessage=="function"&&!h.importScripts?(s=function(F){h.postMessage(F+"","*")},h.addEventListener("message",V,!1)):s=I in f("script")?function(F){p.appendChild(f("script"))[I]=function(){p.removeChild(this),B.call(F)}}:function(F){setTimeout(c(B,F,1),0)}),t.exports={set:x,clear:S}},function(t,n,i){var s=i(20),o=Math.min;t.exports=function(a){return a>0?o(s(a),9007199254740991):0}},function(t,n,i){var s=i(9);t.exports=function(o,a){if(!s(o))return o;var c,l;if(a&&typeof(c=o.toString)=="function"&&!s(l=c.call(o))||typeof(c=o.valueOf)=="function"&&!s(l=c.call(o))||!a&&typeof(c=o.toString)=="function"&&!s(l=c.call(o)))return l;throw TypeError("Can't convert object to primitive value")}},function(t,n){var i=0,s=Math.random();t.exports=function(o){return"Symbol(".concat(o===void 0?"":o,")_",(++i+s).toString(36))}},function(t,n,i){"use strict";function s(I){return I&&I.__esModule?I:{default:I}}function o(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function a(I){return(0,x.createHash)("sha256").update(I).digest("hex")}function c(I){switch(A){case"darwin":return I.split("IOPlatformUUID")[1].split(`
105
+ `};Xs.setupSocket(t),i&&i.length&&t.unshift(i);var c=(Xs.isSSL.test(n.target.protocol)?jH:BH).request(Xs.setupOutgoing(n.ssl||{},n,e));return s&&s.emit("proxyReqWs",c,e,t,n,i),c.on("error",l),c.on("response",function(p){p.upgrade||(t.write(a("HTTP/"+p.httpVersion+" "+p.statusCode+" "+p.statusMessage,p.headers)),p.pipe(t))}),c.on("upgrade",function(p,f,h){f.on("error",l),f.on("end",function(){s.emit("close",p,f,h)}),t.on("error",function(){f.end()}),Xs.setupSocket(f),h&&h.length&&f.unshift(h),t.write(a("HTTP/1.1 101 Switching Protocols",p.headers)),f.pipe(t).pipe(f),s.emit("open",f),s.emit("proxySocket",f)}),c.end();function l(p){o?o(p,e,t):s.emit("error",p,e,t),t.end()}}}});var VR=R((Az,zR)=>{var WR=zR.exports,qR=require("util")._extend,FH=require("url").parse,GR=bR(),UH=require("http"),qH=require("https"),HR=jR(),$R=UR();WR.Server=Ai;function Mg(r){return function(e){return function(t,n){var i=r==="ws"?this.wsPasses:this.webPasses,s=[].slice.call(arguments),o=s.length-1,a,c;typeof s[o]=="function"&&(c=s[o],o--);var l=e;if(!(s[o]instanceof Buffer)&&s[o]!==n&&(l=qR({},e),qR(l,s[o]),o--),s[o]instanceof Buffer&&(a=s[o]),["target","forward"].forEach(function(f){typeof l[f]=="string"&&(l[f]=FH(l[f]))}),!l.target&&!l.forward)return this.emit("error",new Error("Must provide a proper URL as target"));for(var p=0;p<i.length&&!i[p](t,n,l,a,this,c);p++);}}}WR.createRightProxy=Mg;function Ai(r){GR.call(this),r=r||{},r.prependPath=r.prependPath!==!1,this.web=this.proxyRequest=Mg("web")(r),this.ws=this.proxyWebsocketRequest=Mg("ws")(r),this.options=r,this.webPasses=Object.keys(HR).map(function(e){return HR[e]}),this.wsPasses=Object.keys($R).map(function(e){return $R[e]}),this.on("error",this.onError,this)}require("util").inherits(Ai,GR);Ai.prototype.onError=function(r){if(this.listeners("error").length===1)throw r};Ai.prototype.listen=function(r,e){var t=this,n=function(i,s){t.web(i,s)};return this._server=this.options.ssl?qH.createServer(this.options.ssl,n):UH.createServer(n),this.options.ws&&this._server.on("upgrade",function(i,s,o){t.ws(i,s,o)}),this._server.listen(r,e),this};Ai.prototype.close=function(r){var e=this;this._server&&this._server.close(t);function t(){e._server=null,r&&r.apply(null,arguments)}};Ai.prototype.before=function(r,e,t){if(r!=="ws"&&r!=="web")throw new Error("type must be `web` or `ws`");var n=r==="ws"?this.wsPasses:this.webPasses,i=!1;if(n.forEach(function(s,o){s.name===e&&(i=o)}),i===!1)throw new Error("No such pass");n.splice(i,0,t)};Ai.prototype.after=function(r,e,t){if(r!=="ws"&&r!=="web")throw new Error("type must be `web` or `ws`");var n=r==="ws"?this.wsPasses:this.webPasses,i=!1;if(n.forEach(function(s,o){s.name===e&&(i=o)}),i===!1)throw new Error("No such pass");n.splice(i++,0,t)}});var YR=R((Rz,KR)=>{var Ra=VR().Server;function Pg(r){return new Ra(r)}Ra.createProxyServer=Pg;Ra.createServer=Pg;Ra.createProxy=Pg;KR.exports=Ra});var XR=R((kz,JR)=>{JR.exports=YR()});var _k=R((Oa,Ng)=>{(function(r,e){typeof Oa=="object"&&typeof Ng=="object"?Ng.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof Oa=="object"?Oa["electron-machine-id"]=e(require("child_process"),require("crypto")):r["electron-machine-id"]=e(r.child_process,r.crypto)})(Oa,function(r,e){return(function(t){function n(s){if(i[s])return i[s].exports;var o=i[s]={exports:{},id:s,loaded:!1};return t[s].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var i={};return n.m=t,n.c=i,n.p="",n(0)})([function(t,n,i){t.exports=i(34)},function(t,n,i){var s=i(29)("wks"),o=i(33),a=i(2).Symbol,c=typeof a=="function",l=t.exports=function(p){return s[p]||(s[p]=c&&a[p]||(c?a:o)("Symbol."+p))};l.store=s},function(t,n){var i=t.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=i)},function(t,n,i){var s=i(9);t.exports=function(o){if(!s(o))throw TypeError(o+" is not an object!");return o}},function(t,n,i){t.exports=!i(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(t,n,i){var s=i(12),o=i(17);t.exports=i(4)?function(a,c,l){return s.f(a,c,o(1,l))}:function(a,c,l){return a[c]=l,a}},function(t,n){var i=t.exports={version:"2.4.0"};typeof __e=="number"&&(__e=i)},function(t,n,i){var s=i(14);t.exports=function(o,a,c){if(s(o),a===void 0)return o;switch(c){case 1:return function(l){return o.call(a,l)};case 2:return function(l,p){return o.call(a,l,p)};case 3:return function(l,p,f){return o.call(a,l,p,f)}}return function(){return o.apply(a,arguments)}}},function(t,n){var i={}.hasOwnProperty;t.exports=function(s,o){return i.call(s,o)}},function(t,n){t.exports=function(i){return typeof i=="object"?i!==null:typeof i=="function"}},function(t,n){t.exports={}},function(t,n){var i={}.toString;t.exports=function(s){return i.call(s).slice(8,-1)}},function(t,n,i){var s=i(3),o=i(26),a=i(32),c=Object.defineProperty;n.f=i(4)?Object.defineProperty:function(l,p,f){if(s(l),p=a(p,!0),s(f),o)try{return c(l,p,f)}catch{}if("get"in f||"set"in f)throw TypeError("Accessors not supported!");return"value"in f&&(l[p]=f.value),l}},function(t,n,i){var s=i(42),o=i(15);t.exports=function(a){return s(o(a))}},function(t,n){t.exports=function(i){if(typeof i!="function")throw TypeError(i+" is not a function!");return i}},function(t,n){t.exports=function(i){if(i==null)throw TypeError("Can't call method on "+i);return i}},function(t,n,i){var s=i(9),o=i(2).document,a=s(o)&&s(o.createElement);t.exports=function(c){return a?o.createElement(c):{}}},function(t,n){t.exports=function(i,s){return{enumerable:!(1&i),configurable:!(2&i),writable:!(4&i),value:s}}},function(t,n,i){var s=i(12).f,o=i(8),a=i(1)("toStringTag");t.exports=function(c,l,p){c&&!o(c=p?c:c.prototype,a)&&s(c,a,{configurable:!0,value:l})}},function(t,n,i){var s=i(29)("keys"),o=i(33);t.exports=function(a){return s[a]||(s[a]=o(a))}},function(t,n){var i=Math.ceil,s=Math.floor;t.exports=function(o){return isNaN(o=+o)?0:(o>0?s:i)(o)}},function(t,n,i){var s=i(11),o=i(1)("toStringTag"),a=s((function(){return arguments})())=="Arguments",c=function(l,p){try{return l[p]}catch{}};t.exports=function(l){var p,f,h;return l===void 0?"Undefined":l===null?"Null":typeof(f=c(p=Object(l),o))=="string"?f:a?s(p):(h=s(p))=="Object"&&typeof p.callee=="function"?"Arguments":h}},function(t,n){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,n,i){var s=i(2),o=i(6),a=i(7),c=i(5),l="prototype",p=function(f,h,v){var x,S,A,k=f&p.F,P=f&p.G,I=f&p.S,B=f&p.P,V=f&p.B,F=f&p.W,G=P?o:o[h]||(o[h]={}),L=G[l],H=P?s:I?s[h]:(s[h]||{})[l];P&&(v=h);for(x in v)S=!k&&H&&H[x]!==void 0,S&&x in G||(A=S?H[x]:v[x],G[x]=P&&typeof H[x]!="function"?v[x]:V&&S?a(A,s):F&&H[x]==A?(function(T){var u=function(m,y,w){if(this instanceof T){switch(arguments.length){case 0:return new T;case 1:return new T(m);case 2:return new T(m,y)}return new T(m,y,w)}return T.apply(this,arguments)};return u[l]=T[l],u})(A):B&&typeof A=="function"?a(Function.call,A):A,B&&((G.virtual||(G.virtual={}))[x]=A,f&p.R&&L&&!L[x]&&c(L,x,A)))};p.F=1,p.G=2,p.S=4,p.P=8,p.B=16,p.W=32,p.U=64,p.R=128,t.exports=p},function(t,n){t.exports=function(i){try{return!!i()}catch{return!0}}},function(t,n,i){t.exports=i(2).document&&document.documentElement},function(t,n,i){t.exports=!i(4)&&!i(24)(function(){return Object.defineProperty(i(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(t,n,i){"use strict";var s=i(28),o=i(23),a=i(57),c=i(5),l=i(8),p=i(10),f=i(45),h=i(18),v=i(52),x=i(1)("iterator"),S=!([].keys&&"next"in[].keys()),A="@@iterator",k="keys",P="values",I=function(){return this};t.exports=function(B,V,F,G,L,H,T){f(F,V,G);var u,m,y,w=function(M){if(!S&&M in b)return b[M];switch(M){case k:return function(){return new F(this,M)};case P:return function(){return new F(this,M)}}return function(){return new F(this,M)}},g=V+" Iterator",_=L==P,C=!1,b=B.prototype,d=b[x]||b[A]||L&&b[L],E=d||w(L),q=L?_?w("entries"):E:void 0,O=V=="Array"&&b.entries||d;if(O&&(y=v(O.call(new B)),y!==Object.prototype&&(h(y,g,!0),s||l(y,x)||c(y,x,I))),_&&d&&d.name!==P&&(C=!0,E=function(){return d.call(this)}),s&&!T||!S&&!C&&b[x]||c(b,x,E),p[V]=E,p[g]=I,L)if(u={values:_?E:w(P),keys:H?E:w(k),entries:q},T)for(m in u)m in b||a(b,m,u[m]);else o(o.P+o.F*(S||C),V,u);return u}},function(t,n){t.exports=!0},function(t,n,i){var s=i(2),o="__core-js_shared__",a=s[o]||(s[o]={});t.exports=function(c){return a[c]||(a[c]={})}},function(t,n,i){var s,o,a,c=i(7),l=i(41),p=i(25),f=i(16),h=i(2),v=h.process,x=h.setImmediate,S=h.clearImmediate,A=h.MessageChannel,k=0,P={},I="onreadystatechange",B=function(){var F=+this;if(P.hasOwnProperty(F)){var G=P[F];delete P[F],G()}},V=function(F){B.call(F.data)};x&&S||(x=function(F){for(var G=[],L=1;arguments.length>L;)G.push(arguments[L++]);return P[++k]=function(){l(typeof F=="function"?F:Function(F),G)},s(k),k},S=function(F){delete P[F]},i(11)(v)=="process"?s=function(F){v.nextTick(c(B,F,1))}:A?(o=new A,a=o.port2,o.port1.onmessage=V,s=c(a.postMessage,a,1)):h.addEventListener&&typeof postMessage=="function"&&!h.importScripts?(s=function(F){h.postMessage(F+"","*")},h.addEventListener("message",V,!1)):s=I in f("script")?function(F){p.appendChild(f("script"))[I]=function(){p.removeChild(this),B.call(F)}}:function(F){setTimeout(c(B,F,1),0)}),t.exports={set:x,clear:S}},function(t,n,i){var s=i(20),o=Math.min;t.exports=function(a){return a>0?o(s(a),9007199254740991):0}},function(t,n,i){var s=i(9);t.exports=function(o,a){if(!s(o))return o;var c,l;if(a&&typeof(c=o.toString)=="function"&&!s(l=c.call(o))||typeof(c=o.valueOf)=="function"&&!s(l=c.call(o))||!a&&typeof(c=o.toString)=="function"&&!s(l=c.call(o)))return l;throw TypeError("Can't convert object to primitive value")}},function(t,n){var i=0,s=Math.random();t.exports=function(o){return"Symbol(".concat(o===void 0?"":o,")_",(++i+s).toString(36))}},function(t,n,i){"use strict";function s(I){return I&&I.__esModule?I:{default:I}}function o(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function a(I){return(0,x.createHash)("sha256").update(I).digest("hex")}function c(I){switch(A){case"darwin":return I.split("IOPlatformUUID")[1].split(`
106
106
  `)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return I.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return I.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return I.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function l(I){var B=c((0,v.execSync)(P[A]).toString());return I?B:a(B)}function p(I){return new h.default(function(B,V){return(0,v.exec)(P[A],{},function(F,G,L){if(F)return V(new Error("Error while obtaining machine id: "+F.stack));var H=c(G.toString());return B(I?H:a(H))})})}Object.defineProperty(n,"__esModule",{value:!0});var f=i(35),h=s(f);n.machineIdSync=l,n.machineId=p;var v=i(70),x=i(71),S=process,A=S.platform,k={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},P={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:k[o()]+"\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :",freebsd:"kenv -q smbios.system.uuid || sysctl -n kern.hostuuid"}},function(t,n,i){t.exports={default:i(36),__esModule:!0}},function(t,n,i){i(66),i(68),i(69),i(67),t.exports=i(6).Promise},function(t,n){t.exports=function(){}},function(t,n){t.exports=function(i,s,o,a){if(!(i instanceof s)||a!==void 0&&a in i)throw TypeError(o+": incorrect invocation!");return i}},function(t,n,i){var s=i(13),o=i(31),a=i(62);t.exports=function(c){return function(l,p,f){var h,v=s(l),x=o(v.length),S=a(f,x);if(c&&p!=p){for(;x>S;)if(h=v[S++],h!=h)return!0}else for(;x>S;S++)if((c||S in v)&&v[S]===p)return c||S||0;return!c&&-1}}},function(t,v,i){var s=i(7),o=i(44),a=i(43),c=i(3),l=i(31),p=i(64),f={},h={},v=t.exports=function(x,S,A,k,P){var I,B,V,F,G=P?function(){return x}:p(x),L=s(A,k,S?2:1),H=0;if(typeof G!="function")throw TypeError(x+" is not iterable!");if(a(G)){for(I=l(x.length);I>H;H++)if(F=S?L(c(B=x[H])[0],B[1]):L(x[H]),F===f||F===h)return F}else for(V=G.call(x);!(B=V.next()).done;)if(F=o(V,L,B.value,S),F===f||F===h)return F};v.BREAK=f,v.RETURN=h},function(t,n){t.exports=function(i,s,o){var a=o===void 0;switch(s.length){case 0:return a?i():i.call(o);case 1:return a?i(s[0]):i.call(o,s[0]);case 2:return a?i(s[0],s[1]):i.call(o,s[0],s[1]);case 3:return a?i(s[0],s[1],s[2]):i.call(o,s[0],s[1],s[2]);case 4:return a?i(s[0],s[1],s[2],s[3]):i.call(o,s[0],s[1],s[2],s[3])}return i.apply(o,s)}},function(t,n,i){var s=i(11);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(o){return s(o)=="String"?o.split(""):Object(o)}},function(t,n,i){var s=i(10),o=i(1)("iterator"),a=Array.prototype;t.exports=function(c){return c!==void 0&&(s.Array===c||a[o]===c)}},function(t,n,i){var s=i(3);t.exports=function(o,a,c,l){try{return l?a(s(c)[0],c[1]):a(c)}catch(f){var p=o.return;throw p!==void 0&&s(p.call(o)),f}}},function(t,n,i){"use strict";var s=i(49),o=i(17),a=i(18),c={};i(5)(c,i(1)("iterator"),function(){return this}),t.exports=function(l,p,f){l.prototype=s(c,{next:o(1,f)}),a(l,p+" Iterator")}},function(t,n,i){var s=i(1)("iterator"),o=!1;try{var a=[7][s]();a.return=function(){o=!0},Array.from(a,function(){throw 2})}catch{}t.exports=function(c,l){if(!l&&!o)return!1;var p=!1;try{var f=[7],h=f[s]();h.next=function(){return{done:p=!0}},f[s]=function(){return h},c(f)}catch{}return p}},function(t,n){t.exports=function(i,s){return{value:s,done:!!i}}},function(t,n,i){var s=i(2),o=i(30).set,a=s.MutationObserver||s.WebKitMutationObserver,c=s.process,l=s.Promise,p=i(11)(c)=="process";t.exports=function(){var f,h,v,x=function(){var P,I;for(p&&(P=c.domain)&&P.exit();f;){I=f.fn,f=f.next;try{I()}catch(B){throw f?v():h=void 0,B}}h=void 0,P&&P.enter()};if(p)v=function(){c.nextTick(x)};else if(a){var S=!0,A=document.createTextNode("");new a(x).observe(A,{characterData:!0}),v=function(){A.data=S=!S}}else if(l&&l.resolve){var k=l.resolve();v=function(){k.then(x)}}else v=function(){o.call(s,x)};return function(P){var I={fn:P,next:void 0};h&&(h.next=I),f||(f=I,v()),h=I}}},function(t,n,i){var s=i(3),o=i(50),a=i(22),c=i(19)("IE_PROTO"),l=function(){},p="prototype",f=function(){var h,v=i(16)("iframe"),x=a.length,S=">";for(v.style.display="none",i(25).appendChild(v),v.src="javascript:",h=v.contentWindow.document,h.open(),h.write("<script>document.F=Object</script"+S),h.close(),f=h.F;x--;)delete f[p][a[x]];return f()};t.exports=Object.create||function(h,v){var x;return h!==null?(l[p]=s(h),x=new l,l[p]=null,x[c]=h):x=f(),v===void 0?x:o(x,v)}},function(t,n,i){var s=i(12),o=i(3),a=i(54);t.exports=i(4)?Object.defineProperties:function(c,l){o(c);for(var p,f=a(l),h=f.length,v=0;h>v;)s.f(c,p=f[v++],l[p]);return c}},function(t,n,i){var s=i(55),o=i(17),a=i(13),c=i(32),l=i(8),p=i(26),f=Object.getOwnPropertyDescriptor;n.f=i(4)?f:function(h,v){if(h=a(h),v=c(v,!0),p)try{return f(h,v)}catch{}if(l(h,v))return o(!s.f.call(h,v),h[v])}},function(t,n,i){var s=i(8),o=i(63),a=i(19)("IE_PROTO"),c=Object.prototype;t.exports=Object.getPrototypeOf||function(l){return l=o(l),s(l,a)?l[a]:typeof l.constructor=="function"&&l instanceof l.constructor?l.constructor.prototype:l instanceof Object?c:null}},function(t,n,i){var s=i(8),o=i(13),a=i(39)(!1),c=i(19)("IE_PROTO");t.exports=function(l,p){var f,h=o(l),v=0,x=[];for(f in h)f!=c&&s(h,f)&&x.push(f);for(;p.length>v;)s(h,f=p[v++])&&(~a(x,f)||x.push(f));return x}},function(t,n,i){var s=i(53),o=i(22);t.exports=Object.keys||function(a){return s(a,o)}},function(t,n){n.f={}.propertyIsEnumerable},function(t,n,i){var s=i(5);t.exports=function(o,a,c){for(var l in a)c&&o[l]?o[l]=a[l]:s(o,l,a[l]);return o}},function(t,n,i){t.exports=i(5)},function(t,n,i){var s=i(9),o=i(3),a=function(c,l){if(o(c),!s(l)&&l!==null)throw TypeError(l+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(c,l,p){try{p=i(7)(Function.call,i(51).f(Object.prototype,"__proto__").set,2),p(c,[]),l=!(c instanceof Array)}catch{l=!0}return function(f,h){return a(f,h),l?f.__proto__=h:p(f,h),f}})({},!1):void 0),check:a}},function(t,n,i){"use strict";var s=i(2),o=i(6),a=i(12),c=i(4),l=i(1)("species");t.exports=function(p){var f=typeof o[p]=="function"?o[p]:s[p];c&&f&&!f[l]&&a.f(f,l,{configurable:!0,get:function(){return this}})}},function(t,n,i){var s=i(3),o=i(14),a=i(1)("species");t.exports=function(c,l){var p,f=s(c).constructor;return f===void 0||(p=s(f)[a])==null?l:o(p)}},function(t,n,i){var s=i(20),o=i(15);t.exports=function(a){return function(c,l){var p,f,h=String(o(c)),v=s(l),x=h.length;return v<0||v>=x?a?"":void 0:(p=h.charCodeAt(v),p<55296||p>56319||v+1===x||(f=h.charCodeAt(v+1))<56320||f>57343?a?h.charAt(v):p:a?h.slice(v,v+2):(p-55296<<10)+(f-56320)+65536)}}},function(t,n,i){var s=i(20),o=Math.max,a=Math.min;t.exports=function(c,l){return c=s(c),c<0?o(c+l,0):a(c,l)}},function(t,n,i){var s=i(15);t.exports=function(o){return Object(s(o))}},function(t,n,i){var s=i(21),o=i(1)("iterator"),a=i(10);t.exports=i(6).getIteratorMethod=function(c){if(c!=null)return c[o]||c["@@iterator"]||a[s(c)]}},function(t,n,i){"use strict";var s=i(37),o=i(47),a=i(10),c=i(13);t.exports=i(27)(Array,"Array",function(l,p){this._t=c(l),this._i=0,this._k=p},function(){var l=this._t,p=this._k,f=this._i++;return!l||f>=l.length?(this._t=void 0,o(1)):p=="keys"?o(0,f):p=="values"?o(0,l[f]):o(0,[f,l[f]])},"values"),a.Arguments=a.Array,s("keys"),s("values"),s("entries")},function(t,n){},function(t,n,i){"use strict";var s,o,a,c=i(28),l=i(2),p=i(7),f=i(21),h=i(23),v=i(9),x=(i(3),i(14)),S=i(38),A=i(40),k=(i(58).set,i(60)),P=i(30).set,I=i(48)(),B="Promise",V=l.TypeError,G=l.process,F=l[B],G=l.process,L=f(G)=="process",H=function(){},T=!!(function(){try{var O=F.resolve(1),M=(O.constructor={})[i(1)("species")]=function(j){j(H,H)};return(L||typeof PromiseRejectionEvent=="function")&&O.then(H)instanceof M}catch{}})(),u=function(O,M){return O===M||O===F&&M===a},m=function(O){var M;return!(!v(O)||typeof(M=O.then)!="function")&&M},y=function(O){return u(F,O)?new w(O):new o(O)},w=o=function(O){var M,j;this.promise=new O(function(z,U){if(M!==void 0||j!==void 0)throw V("Bad Promise constructor");M=z,j=U}),this.resolve=x(M),this.reject=x(j)},g=function(O){try{O()}catch(M){return{error:M}}},_=function(O,M){if(!O._n){O._n=!0;var j=O._c;I(function(){for(var z=O._v,U=O._s==1,Te=0,ne=function(N){var te,D,W=U?N.ok:N.fail,se=N.resolve,Z=N.reject,J=N.domain;try{W?(U||(O._h==2&&d(O),O._h=1),W===!0?te=z:(J&&J.enter(),te=W(z),J&&J.exit()),te===N.promise?Z(V("Promise-chain cycle")):(D=m(te))?D.call(te,se,Z):se(te)):Z(z)}catch(Tt){Z(Tt)}};j.length>Te;)ne(j[Te++]);O._c=[],O._n=!1,M&&!O._h&&C(O)})}},C=function(O){P.call(l,function(){var M,j,z,U=O._v;if(b(O)&&(M=g(function(){L?G.emit("unhandledRejection",U,O):(j=l.onunhandledrejection)?j({promise:O,reason:U}):(z=l.console)&&z.error&&z.error("Unhandled promise rejection",U)}),O._h=L||b(O)?2:1),O._a=void 0,M)throw M.error})},b=function(O){if(O._h==1)return!1;for(var M,j=O._a||O._c,z=0;j.length>z;)if(M=j[z++],M.fail||!b(M.promise))return!1;return!0},d=function(O){P.call(l,function(){var M;L?G.emit("rejectionHandled",O):(M=l.onrejectionhandled)&&M({promise:O,reason:O._v})})},E=function(O){var M=this;M._d||(M._d=!0,M=M._w||M,M._v=O,M._s=2,M._a||(M._a=M._c.slice()),_(M,!0))},q=function(O){var M,j=this;if(!j._d){j._d=!0,j=j._w||j;try{if(j===O)throw V("Promise can't be resolved itself");(M=m(O))?I(function(){var z={_w:j,_d:!1};try{M.call(O,p(q,z,1),p(E,z,1))}catch(U){E.call(z,U)}}):(j._v=O,j._s=1,_(j,!1))}catch(z){E.call({_w:j,_d:!1},z)}}};T||(F=function(O){S(this,F,B,"_h"),x(O),s.call(this);try{O(p(q,this,1),p(E,this,1))}catch(M){E.call(this,M)}},s=function(O){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},s.prototype=i(56)(F.prototype,{then:function(O,M){var j=y(k(this,F));return j.ok=typeof O!="function"||O,j.fail=typeof M=="function"&&M,j.domain=L?G.domain:void 0,this._c.push(j),this._a&&this._a.push(j),this._s&&_(this,!1),j.promise},catch:function(O){return this.then(void 0,O)}}),w=function(){var O=new s;this.promise=O,this.resolve=p(q,O,1),this.reject=p(E,O,1)}),h(h.G+h.W+h.F*!T,{Promise:F}),i(18)(F,B),i(59)(B),a=i(6)[B],h(h.S+h.F*!T,B,{reject:function(O){var M=y(this),j=M.reject;return j(O),M.promise}}),h(h.S+h.F*(c||!T),B,{resolve:function(O){if(O instanceof F&&u(O.constructor,this))return O;var M=y(this),j=M.resolve;return j(O),M.promise}}),h(h.S+h.F*!(T&&i(46)(function(O){F.all(O).catch(H)})),B,{all:function(O){var M=this,j=y(M),z=j.resolve,U=j.reject,Te=g(function(){var ne=[],N=0,te=1;A(O,!1,function(D){var W=N++,se=!1;ne.push(void 0),te++,M.resolve(D).then(function(Z){se||(se=!0,ne[W]=Z,--te||z(ne))},U)}),--te||z(ne)});return Te&&U(Te.error),j.promise},race:function(O){var M=this,j=y(M),z=j.reject,U=g(function(){A(O,!1,function(Te){M.resolve(Te).then(j.resolve,z)})});return U&&z(U.error),j.promise}})},function(t,n,i){"use strict";var s=i(61)(!0);i(27)(String,"String",function(o){this._t=String(o),this._i=0},function(){var o,a=this._t,c=this._i;return c>=a.length?{value:void 0,done:!0}:(o=s(a,c),this._i+=o.length,{value:o,done:!1})})},function(t,n,i){i(65);for(var s=i(2),o=i(5),a=i(10),c=i(1)("toStringTag"),l=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],p=0;p<5;p++){var f=l[p],h=s[f],v=h&&h.prototype;v&&!v[c]&&o(v,c,f),a[f]=a.Array}},function(t,n){t.exports=require("child_process")},function(t,n){t.exports=require("crypto")}])})});var h$={};Vr(h$,{startServer:()=>eO});module.exports=oO(h$);var Vu=require("http"),Ku=require("child_process"),Ri=require("fs"),Zt=require("path"),Xk=require("url");var Qg=(r=0)=>e=>`\x1B[${e+r}m`,ev=(r=0)=>e=>`\x1B[${38+r};5;${e}m`,tv=(r=0)=>(e,t,n)=>`\x1B[${38+r};2;${e};${t};${n}m`,ye={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},g$=Object.keys(ye.modifier),aO=Object.keys(ye.color),cO=Object.keys(ye.bgColor),v$=[...aO,...cO];function lO(){let r=new Map;for(let[e,t]of Object.entries(ye)){for(let[n,i]of Object.entries(t))ye[n]={open:`\x1B[${i[0]}m`,close:`\x1B[${i[1]}m`},t[n]=ye[n],r.set(i[0],i[1]);Object.defineProperty(ye,e,{value:t,enumerable:!1})}return Object.defineProperty(ye,"codes",{value:r,enumerable:!1}),ye.color.close="\x1B[39m",ye.bgColor.close="\x1B[49m",ye.color.ansi=Qg(),ye.color.ansi256=ev(),ye.color.ansi16m=tv(),ye.bgColor.ansi=Qg(10),ye.bgColor.ansi256=ev(10),ye.bgColor.ansi16m=tv(10),Object.defineProperties(ye,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(s=>s+s).join(""));let i=Number.parseInt(n,16);return[i>>16&255,i>>8&255,i&255]},enumerable:!1},hexToAnsi256:{value:e=>ye.rgbToAnsi256(...ye.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,i;if(e>=232)t=((e-232)*10+8)/255,n=t,i=t;else{e-=16;let a=e%36;t=Math.floor(e/36)/5,n=Math.floor(a/6)/5,i=a%6/5}let s=Math.max(t,n,i)*2;if(s===0)return 30;let o=30+(Math.round(i)<<2|Math.round(n)<<1|Math.round(t));return s===2&&(o+=60),o},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>ye.ansi256ToAnsi(ye.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>ye.ansi256ToAnsi(ye.hexToAnsi256(e)),enumerable:!1}}),ye}var uO=lO(),yr=uO;var Na=K(require("node:process"),1),nv=K(require("node:os"),1),hp=K(require("node:tty"),1);function Qt(r,e=globalThis.Deno?globalThis.Deno.args:Na.default.argv){let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),i=e.indexOf("--");return n!==-1&&(i===-1||n<i)}var{env:xe}=Na.default,Ia;Qt("no-color")||Qt("no-colors")||Qt("color=false")||Qt("color=never")?Ia=0:(Qt("color")||Qt("colors")||Qt("color=true")||Qt("color=always"))&&(Ia=1);function pO(){if("FORCE_COLOR"in xe)return xe.FORCE_COLOR==="true"?1:xe.FORCE_COLOR==="false"?0:xe.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(xe.FORCE_COLOR,10),3)}function fO(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function dO(r,{streamIsTTY:e,sniffFlags:t=!0}={}){let n=pO();n!==void 0&&(Ia=n);let i=t?Ia:n;if(i===0)return 0;if(t){if(Qt("color=16m")||Qt("color=full")||Qt("color=truecolor"))return 3;if(Qt("color=256"))return 2}if("TF_BUILD"in xe&&"AGENT_NAME"in xe)return 1;if(r&&!e&&i===void 0)return 0;let s=i||0;if(xe.TERM==="dumb")return s;if(Na.default.platform==="win32"){let o=nv.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in xe)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in xe)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in xe)||xe.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in xe)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(xe.TEAMCITY_VERSION)?1:0;if(xe.COLORTERM==="truecolor"||xe.TERM==="xterm-kitty"||xe.TERM==="xterm-ghostty"||xe.TERM==="wezterm")return 3;if("TERM_PROGRAM"in xe){let o=Number.parseInt((xe.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(xe.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(xe.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(xe.TERM)||"COLORTERM"in xe?1:s}function rv(r,e={}){let t=dO(r,{streamIsTTY:r&&r.isTTY,...e});return fO(t)}var hO={stdout:rv({isTTY:hp.default.isatty(1)}),stderr:rv({isTTY:hp.default.isatty(2)})},iv=hO;function sv(r,e,t){let n=r.indexOf(e);if(n===-1)return r;let i=e.length,s=0,o="";do o+=r.slice(s,n)+e+t,s=n+i,n=r.indexOf(e,s);while(n!==-1);return o+=r.slice(s),o}function ov(r,e,t,n){let i=0,s="";do{let o=r[n-1]==="\r";s+=r.slice(i,o?n-1:n)+e+(o?`\r
107
107
  `:`
108
108
  `)+t,i=n+1,n=r.indexOf(`
109
109
  `,i)}while(n!==-1);return s+=r.slice(i),s}var{stdout:av,stderr:cv}=iv,mp=Symbol("GENERATOR"),ki=Symbol("STYLER"),Qs=Symbol("IS_EMPTY"),lv=["ansi","ansi","ansi256","ansi16m"],Oi=Object.create(null),mO=(r,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let t=av?av.level:0;r.level=e.level===void 0?t:e.level};var gO=r=>{let e=(...t)=>t.join(" ");return mO(e,r),Object.setPrototypeOf(e,eo.prototype),e};function eo(r){return gO(r)}Object.setPrototypeOf(eo.prototype,Function.prototype);for(let[r,e]of Object.entries(yr))Oi[r]={get(){let t=La(this,vp(e.open,e.close,this[ki]),this[Qs]);return Object.defineProperty(this,r,{value:t}),t}};Oi.visible={get(){let r=La(this,this[ki],!0);return Object.defineProperty(this,"visible",{value:r}),r}};var gp=(r,e,t,...n)=>r==="rgb"?e==="ansi16m"?yr[t].ansi16m(...n):e==="ansi256"?yr[t].ansi256(yr.rgbToAnsi256(...n)):yr[t].ansi(yr.rgbToAnsi(...n)):r==="hex"?gp("rgb",e,t,...yr.hexToRgb(...n)):yr[t][r](...n),vO=["rgb","hex","ansi256"];for(let r of vO){Oi[r]={get(){let{level:t}=this;return function(...n){let i=vp(gp(r,lv[t],"color",...n),yr.color.close,this[ki]);return La(this,i,this[Qs])}}};let e="bg"+r[0].toUpperCase()+r.slice(1);Oi[e]={get(){let{level:t}=this;return function(...n){let i=vp(gp(r,lv[t],"bgColor",...n),yr.bgColor.close,this[ki]);return La(this,i,this[Qs])}}}}var yO=Object.defineProperties(()=>{},{...Oi,level:{enumerable:!0,get(){return this[mp].level},set(r){this[mp].level=r}}}),vp=(r,e,t)=>{let n,i;return t===void 0?(n=r,i=e):(n=t.openAll+r,i=e+t.closeAll),{open:r,close:e,openAll:n,closeAll:i,parent:t}},La=(r,e,t)=>{let n=(...i)=>xO(n,i.length===1?""+i[0]:i.join(" "));return Object.setPrototypeOf(n,yO),n[mp]=r,n[ki]=e,n[Qs]=t,n},xO=(r,e)=>{if(r.level<=0||!e)return r[Qs]?"":e;let t=r[ki];if(t===void 0)return e;let{openAll:n,closeAll:i}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=sv(e,t.close,t.open),t=t.parent;let s=e.indexOf(`
110
- `);return s!==-1&&(e=ov(e,i,n,s)),n+e+i};Object.defineProperties(eo.prototype,Oi);var _O=eo(),E$=eo({level:cv?cv.level:0});var to=_O;Pt();vt();Ii();var Eb=K(Sb(),1),{Server:Tb,Namespace:x6,Socket:_6}=Eb.default;var fR=require("fs"),dR=require("path");vt();nl();var at={control:"control",binary:"binary"},st={idle:"idle",connecting:"connecting",open:"open",degraded:"degraded",closed:"closed"},kb={clientApp:{enabled:["ws","rtc"],channels:{control:{strategy:"priority",prefer:"rtc"},binary:{strategy:"priority",prefer:"rtc"}}},remoteDesktop:{enabled:["ws","rtc"],channels:{control:{strategy:"priority",prefer:"rtc"},binary:{strategy:"priority",prefer:"rtc"}}}};var ds=class{static id="base";static capabilities={control:!1,binary:!1,signaling:"none"};static priority={control:0,binary:0};constructor(){this._listeners=new Map,this._state=st.idle}get state(){return this._state}get ready(){return this._state===st.open}supports(e){return!!this.constructor.capabilities[e]}on(e,t){this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t)}off(e,t){this._listeners.get(e)?.delete(t)}_emit(e,...t){let n=this._listeners.get(e);if(n)for(let i of n)i(...t)}_setState(e){this._state!==e&&(this._state=e,this._emit("stateChange",e))}connect(e){throw new Error("Not implemented: connect")}disconnect(){throw new Error("Not implemented: disconnect")}send(e,t){throw new Error("Not implemented: send")}};ot();var sl=class extends ds{static id="ws";static capabilities={control:!0,binary:!0,signaling:"ws"};static priority={control:100,binary:10};constructor(){super(),this._socket=null}get socket(){return this._socket}connect(e){this._socket=e.socket,this._setState(e.socket.connected?st.open:st.connecting),e.socket.on("connect",()=>this._setState(st.open)),e.socket.on("disconnect",()=>this._setState(st.closed)),e.socket.onAny?.((t,n)=>this._emit("message",{event:t,data:n,source:"ws"}))}disconnect(){this._socket=null,this._setState(st.closed)}send(e,t){if(!this._socket?.connected)return!1;let n=this._socket._rawEmit||this._socket.emit.bind(this._socket);if(e===at.control){let{event:i,args:s=[]}=t;return n(i,...s),!0}return e===at.binary?($.streaming.wsVolatileTiles&&this._socket.volatile?this._socket.volatile.emit("tiles-bin-v2",t):n("tiles-bin-v2",t),!0):!1}};var Db=K(require("node-datachannel"),1);function g2(r,e){return e&&typeof e=="object"&&e.type==="Buffer"&&Array.isArray(e.data)?{__b:Buffer.from(e.data).toString("base64")}:e}function v2(r,e){return e&&typeof e=="object"&&typeof e.__b=="string"?Buffer.from(e.__b,"base64"):e}function Mb(r){return JSON.stringify(r,g2)}function Pb(r){return JSON.parse(typeof r=="string"?r:Buffer.from(r).toString("utf8"),v2)}ot();var Nb=K(require("node:dns/promises"),1),y2=3e4,x2=/\s([0-9a-f-]{8,}\.local)\s/i,Ib=new Map;async function _2(r){let e=Ib.get(r);if(e&&Date.now()-e.ts<y2)return e.ip;try{let{address:t}=await Nb.default.lookup(r);return Ib.set(r,{ip:t,ts:Date.now()}),t}catch{return null}}async function Lb(r){let e=r.match(x2);if(!e)return r;let t=await _2(e[1]);return t?r.replace(e[1],t):null}var{PeerConnection:b2}=Db.default,w2=[{hostname:"stun.l.google.com",port:19302,type:"Stun"},{hostname:"stun1.l.google.com",port:19302,type:"Stun"},{hostname:"stun2.l.google.com",port:19302,type:"Stun"},{hostname:"stun3.l.google.com",port:19302,type:"Stun"},{hostname:"stun4.l.google.com",port:19302,type:"Stun"},{hostname:"global.stun.twilio.com",port:3478,type:"Stun"},{hostname:"stun.cloudflare.com",port:3478,type:"Stun"}];async function S2(r,e){try{let t=await fetch(r,{headers:{"X-API-Key":e}});if(!t.ok)throw new Error(`HTTP ${t.status}`);let{iceServers:n}=await t.json(),i=[];for(let s of n)for(let o of s.urls)if(o.startsWith("stun:")){let a=o.replace("stun:","").split(":")[0],c=parseInt(o.split(":")[2]||"3478");i.push({hostname:a,port:c,type:"Stun"})}else if(o.startsWith("turn:")||o.startsWith("turns:")){let a=o.startsWith("turns:"),l=o.replace(/^turns?:/,"").split("?")[0],p=l.split(":")[0],f=parseInt(l.split(":")[1]||(a?"5349":"3478")),h=o.includes("transport=tcp")?"Tcp":"Udp";i.push({hostname:p,port:f,type:a?"Tls":"Turn",relayType:h,username:s.username,password:s.credential})}return i}catch(t){return console.error("[WebRtcProtocol] TURN fetch failed:",t.message),null}}var ol=class extends ds{static id="rtc";static capabilities={control:!0,binary:!0,signaling:"external"};static priority={control:50,binary:100};constructor(){super(),this._pc=null,this._dcControl=null,this._dcBinary=null,this._iceServers=w2,this._refreshTimer=null,this._remoteSet=!1,this._pendingCandidates=[],this._signaling=null,this._iceGraceTimer=null}async connect(e){this._ctx=e,this._setState(st.connecting);let t=e.profile?.rtc||{};t.enableTurn&&e.auth?.apiKey&&t.turnApiUrl&&await this._refreshTurn(t),this._signaling=e.signaling,this._signaling?.on?.(n=>this._handleSignal(n,t))}disconnect(){clearTimeout(this._refreshTimer),this._signaling?.off?.(),this._signaling=null,this._cleanupPeer(),this._setState(st.closed)}send(e,t){if(e===at.control){if(!this._dcControl)return!1;try{return this._dcControl.sendMessage(Mb({event:t.event,args:t.args||[],ackId:t.ackId||null})),!0}catch(n){return console.error("[WebRtcProtocol] send control:",n.message),!1}}if(e===at.binary){if(!this._dcBinary)return!1;try{let n=Array.isArray(t)?t:[t],i=this._ctx.profile?.rtc?.dcMaxMessageSize??65536,s=$.webrtc.dcBufferThreshold;for(let o of n){if(this._dcBinary.bufferedAmount()>s)return!0;o.length<=i&&this._dcBinary.sendMessageBinary(o)}return!0}catch(n){return console.error("[WebRtcProtocol] send binary:",n.message),!1}}return!1}_handleSignal(e,t){if(e.type==="offer")this._processOffer(e.sdp,t);else if(e.type==="ice"){if(!this._remoteSet||!this._pc){this._pendingCandidates.push({candidate:e.candidate,mid:e.mid||"0"});return}this._addRemoteCandidate(e.candidate,e.mid||"0")}}async _addRemoteCandidate(e,t){try{let n=await Lb(e);if(!n||!this._pc)return;this._pc.addRemoteCandidate(n,t)}catch(n){console.error("[WebRtcProtocol] addRemoteCandidate:",n.message)}}_createPeer(e){try{this._pc?.close()}catch{}this._pc=null,this._dcControl=null,this._dcBinary=null,this._remoteSet=!1,this._pendingCandidates=[],this._iceGraceTimer&&(clearTimeout(this._iceGraceTimer),this._iceGraceTimer=null);let t=this._ctx?.auth?.socketId||"anon",n=new b2(`peer-${t}`,{iceServers:this._iceServers});this._pcState="new",n.onStateChange(i=>{if(this._pcState=i,i==="failed"||i==="closed")this._iceGraceTimer&&(clearTimeout(this._iceGraceTimer),this._iceGraceTimer=null),this._setState(st.closed);else if(i==="disconnected"){if(this._iceGraceTimer)return;this._iceGraceTimer=setTimeout(()=>{this._iceGraceTimer=null,this._pcState!=="connected"&&this._setState(st.closed)},$.webrtc.iceDisconnectGraceMs)}else i==="connected"&&this._iceGraceTimer&&(clearTimeout(this._iceGraceTimer),this._iceGraceTimer=null)}),n.onDataChannel(i=>{let s=i.getLabel?.()||"",o=()=>{s==="control"?this._dcControl=i:s==="binary"&&(this._dcBinary=i),this._dcControl&&this._dcBinary&&this._setState(st.open)};i.onOpen(o),i.onClosed(()=>{s==="control"&&(this._dcControl=null),s==="binary"&&(this._dcBinary=null),!this._dcControl&&!this._dcBinary&&this._setState(st.closed)}),i.onError(a=>console.error(`[WebRtcProtocol] DC[${s}] error:`,a)),i.onMessage(a=>{if(s!=="control")return;let c;try{c=Pb(a)}catch(l){console.error("[WebRtcProtocol] control parse:",l.message);return}try{this._emit("message",{event:c.event,data:c,source:"rtc"})}catch(l){console.error(`[WebRtcProtocol] handler error event=${c.event}:`,l.message)}})}),this._pc=n}_processOffer(e,t){return this._createPeer(t),new Promise((n,i)=>{this._pc.onLocalDescription((o,a)=>{a==="answer"&&(this._signaling?.send?.({type:"answer",sdp:o}),n())}),this._pc.onLocalCandidate((o,a)=>{o&&this._signaling?.send?.({type:"ice",candidate:o,mid:a})});try{this._pc.setRemoteDescription(e,"offer"),this._remoteSet=!0;for(let{candidate:o,mid:a}of this._pendingCandidates)this._addRemoteCandidate(o,a);this._pendingCandidates=[],this._pc.setLocalDescription()}catch(o){this._signaling?.send?.({type:"error",message:o.message}),i(o)}let s=t?.answerTimeout||1e4;setTimeout(()=>i(new Error("Answer timeout")),s)})}_cleanupPeer(){this._iceGraceTimer&&(clearTimeout(this._iceGraceTimer),this._iceGraceTimer=null);try{this._pc?.close()}catch{}this._pc=null,this._dcControl=null,this._dcBinary=null}async _refreshTurn(e){let t=await S2(e.turnApiUrl,this._ctx.auth.apiKey);t?.length&&(this._iceServers=t,$.logging?.webrtc&&console.log(`[WebRtcProtocol] TURN credentials loaded (${t.length} servers)`)),clearTimeout(this._refreshTimer),this._refreshTimer=setTimeout(()=>this._refreshTurn(e),e.turnRefreshInterval)}};var Bb=new Map;function Ud(r){if(!r?.id)throw new Error("Adapter missing static id");Bb.set(r.id,r)}function jb(r){return Bb.get(r)}oh();Ud(sl);Ud(ol);var yl=class{constructor(e,t){let n=t.enableWebRTC?"remoteDesktop":"clientApp",i={...kb[n]};t.enableWebRTC||(i.enabled=["ws"]),i.rtc={enableTurn:!!(t.apiKey&&t.turnApiUrl),turnApiUrl:t.turnApiUrl||null,turnRefreshInterval:t.turnRefreshInterval,dcMaxMessageSize:t.dcMaxMessageSize,answerTimeout:t.answerTimeout},this._profile=i,this._auth={apiKey:t.apiKey||null,socketId:e.id},this._socket=e,this._wsChunkSize=t.wsChunkSize,this._dcChunkSize=t.dcChunkSize,this._dcMaxTilesPerFrame=t.dcMaxTilesPerFrame,this._maxControlBuffer=t.maxControlBuffer,this._adapters=new Map,this._listeners=new Map,this._buffer=[],this._rtcSignalingHandler=null,this._sigListeners=null}get type(){return this._pickAdapter(at.binary)?.constructor.id==="rtc"?"dc":"ws"}async init(){for(let e of this._profile.enabled){let t=jb(e);if(!t)continue;let n=new t;n.on("stateChange",s=>this._onAdapterStateChange(e,s)),n.on("message",({event:s,data:o,source:a})=>this._dispatch(s,o,a)),this._adapters.set(e,n);let i=this._buildCtx(e);await n.connect(i)}}setupSignaling(e){this._installSignalingListeners()}emit(e,...t){this._sendControl(e,t)}sendTiles(e,t){let{tiles:n,timestamp:i}=e;if(!n?.length)return;let s=this._pickAdapter(at.binary),o=i??Date.now();if(s?.constructor.id==="rtc"&&t){let a=[];for(let c=0;c<n.length;c+=this._dcChunkSize)a.push(t(n.slice(c,c+this._dcChunkSize),o));s.send(at.binary,a);return}this._emitTilesChunked(n,o)}close(){for(let e of this._adapters.values())try{e.disconnect()}catch{}this._adapters.clear(),this._buffer=[]}attachAsBus(e){if(e._rawEmit)return;let t=e.emit.bind(e);e._rawEmit=t;let n=new Set(["error","disconnect","disconnecting","connect","newListener","removeListener"]);e.emit=(i,...s)=>n.has(i)?t(i,...s):(this._sendControl(i,s),!0)}_emitTilesChunked(e,t){let n=this._adapters.get("ws");if(!n?.ready)return;let i=this._wsChunkSize;for(let s=0;s<e.length;s+=i){let o=e.slice(s,s+i);n.send(at.binary,_s(o,t))}}_buildCtx(e){let t={auth:this._auth,profile:this._profile};return e==="ws"&&(t.socket=this._socket),e==="rtc"&&(t.signaling={send:n=>this._sendSignaling(n),on:n=>{this._rtcSignalingHandler=n,this._installSignalingListeners()},off:()=>{this._rtcSignalingHandler=null,this._removeSignalingListeners()}}),t}_onAdapterStateChange(e,t){t===st.open&&this._flushBuffer()}_pickAdapter(e){let t=this._profile.channels[e];if(!t)return null;let n=[...this._adapters.values()].filter(i=>i.supports(e)&&i.ready);if(t.prefer){let i=n.find(s=>s.constructor.id===t.prefer);if(i)return i}return n.sort((i,s)=>(s.constructor.priority[e]??0)-(i.constructor.priority[e]??0)),n[0]||null}hasReadyAdapter(){return!!(this._pickAdapter(at.control)||this._pickAdapter(at.binary))}_sendControl(e,t,n){let i=this._pickAdapter(at.control);if(!i){this._buffer.push({event:e,args:t,ackId:n}),this._buffer.length>this._maxControlBuffer&&this._buffer.shift();return}i.constructor.id==="rtc"?i.send(at.control,{event:e,args:t,ackId:n}):i.send(at.control,{event:e,args:t})}_flushBuffer(){if(!(!this._buffer.length||!this._pickAdapter(at.control)))for(;this._buffer.length;){let{event:t,args:n,ackId:i}=this._buffer.shift();this._sendControl(t,n,i)}}_dispatch(e,t,n){if(n==="rtc"){let s=Array.isArray(t?.args)?[...t.args]:[],o=t?.ackId;o&&s.push((...l)=>this._sendAck(o,l));let a=this._listeners.get(e);if(a)for(let l of a)l(...s);let c=this._socket.listeners?.(e)||[];for(let l of c)l(...s);return}let i=this._listeners.get(e);if(i)for(let s of i)s(t)}_sendAck(e,t){let n=this._adapters.get("rtc");n?.ready&&n.send(at.control,{event:"__ack",args:t,ackId:e})}_sendSignaling(e){let t=this._adapters.get("ws");if(t?.ready){t.send(at.control,{event:this._sigEvent(e.type),args:[this._sigData(e)]});return}console.warn("[ProtocolManager] signaling unavailable (ws down)")}_sigEvent(e){return e==="offer"?"webrtc:offer":e==="answer"?"webrtc:answer":e==="ice"?"webrtc:ice-candidate":"webrtc:error"}_sigData(e){return e.type==="offer"||e.type==="answer"?{sdp:e.sdp}:e.type==="ice"?{candidate:e.candidate,mid:e.mid}:e}_installSignalingListeners(){if(!this._rtcSignalingHandler||this._sigListeners)return;let e=({sdp:n})=>this._rtcSignalingHandler?.({type:"offer",sdp:n}),t=({candidate:n,mid:i})=>this._rtcSignalingHandler?.({type:"ice",candidate:n,mid:i});this._sigListeners={onOffer:e,onIce:t},this._socket.on("webrtc:offer",e),this._socket.on("webrtc:ice-candidate",t)}_removeSignalingListeners(){this._sigListeners&&(this._socket.off("webrtc:offer",this._sigListeners.onOffer),this._socket.off("webrtc:ice-candidate",this._sigListeners.onIce),this._sigListeners=null)}};ui();ot();var TT=require("path"),CT=require("url");var El=K(require("net"),1),ae=K(require("fs"),1),fe=K(require("path"),1),Dw=K(require("os"),1),Bw=require("child_process"),jw=require("url");var ch={win32:[{id:"cmd",label:"Command Prompt",path:"cmd.exe",args:[]},{id:"powershell",label:"PowerShell",path:"powershell.exe",args:["-NoLogo"]},{id:"pwsh",label:"PowerShell Core",path:"pwsh.exe",args:["-NoLogo"]}],unix:[{id:"bash",label:"Bash",path:"/bin/bash",args:["-l"]},{id:"zsh",label:"Zsh",path:"/bin/zsh",args:["-l"]},{id:"sh",label:"Sh",path:"/bin/sh",args:["-l"]}]};function Pw(){return process.platform==="win32"?ch.win32:[]}function Iw(r){if(process.platform==="win32"){let n=r?ch.win32.find(s=>s.id===r):null;if(n)return n;let i=process.env.COMSPEC;return i?{id:"cmd",label:"Command Prompt",path:i,args:[]}:ch.win32[0]}let e=process.env.SHELL||"/bin/bash",t=e.split("/").pop();return{id:t,label:t,path:e,args:["-l"]}}var uh=fe.default.dirname((0,jw.fileURLToPath)(__importMetaUrl)),fn=fe.default.join(Dw.default.homedir(),".9remote"),Wo=process.platform==="win32"?"\\\\.\\pipe\\9remote-pty":fe.default.join(fn,"pty-daemon.sock"),Nw=fe.default.join(uh,"ptyDaemon.js"),Lw=fe.default.join(uh,"ptyDaemon.cjs"),xl=fe.default.join(fn,"daemon");function Fw(r,e){if(ae.default.existsSync(r)){ae.default.mkdirSync(e,{recursive:!0});for(let t of ae.default.readdirSync(r,{withFileTypes:!0})){let n=fe.default.join(r,t.name),i=fe.default.join(e,t.name);t.isDirectory()?Fw(n,i):t.isFile()&&ae.default.copyFileSync(n,i)}}}function J2(r,e){let t=r;for(let n=0;n<6;n++){let i=fe.default.join(t,"node_modules",e);if(ae.default.existsSync(i))return i;let s=fe.default.dirname(t);if(s===t)break;t=s}return null}var X2=r=>J2(r,"node-pty");function Z2(r){try{if(!ae.default.existsSync(xl))return;let e=fe.default.join(fn,"pids","ptyDaemon.pid"),t=!1;try{let n=parseInt(ae.default.readFileSync(e,"utf8").trim(),10);if(Number.isFinite(n)&&n>0)try{process.kill(n,0),t=!0}catch{}}catch{}if(t)return;for(let n of ae.default.readdirSync(xl))if(n!==`v${r}`)try{ae.default.rmSync(fe.default.join(xl,n),{recursive:!0,force:!0})}catch{}}catch{}}function Q2(r){Z2("18");let e=fe.default.join(xl,`v${"18"}`),t=r.endsWith(".js"),n=t?fe.default.join(e,"features","terminal"):e,i=fe.default.join(n,fe.default.basename(r)),s=fe.default.join(n,"node_modules","node-pty");if(ae.default.existsSync(i)&&ae.default.existsSync(s))return{script:i,cwd:n};try{if(ae.default.mkdirSync(n,{recursive:!0}),ae.default.copyFileSync(r,i),t){let a=fe.default.dirname(r);ae.default.copyFileSync(fe.default.join(a,"constants.js"),fe.default.join(n,"constants.js"));let c=fe.default.join(e,"lib");ae.default.mkdirSync(c,{recursive:!0}),ae.default.copyFileSync(fe.default.resolve(a,"..","..","lib","constants.js"),fe.default.join(c,"constants.js"))}let o=X2(fe.default.dirname(r));return o?(Fw(o,s),{script:i,cwd:n}):null}catch{return null}}var Fr=null,ws=!1,jn=!1,lh="",eB=0,Ss=new Map,_l=new Map;function tB(){return++eB}function Tl(r,e){_l.has(r)||_l.set(r,[]),_l.get(r).push(e)}function wl(r,e){let t=_l.get(r);if(t)for(let n of t)try{n(e)}catch(i){console.error(`[DaemonClient] Error in ${r} handler:`,i)}}function ph(r){if(!Fr||!ws)return!1;try{return Fr.write(JSON.stringify(r)+`
110
+ `);return s!==-1&&(e=ov(e,i,n,s)),n+e+i};Object.defineProperties(eo.prototype,Oi);var _O=eo(),E$=eo({level:cv?cv.level:0});var to=_O;Pt();vt();Ii();var Eb=K(Sb(),1),{Server:Tb,Namespace:x6,Socket:_6}=Eb.default;var fR=require("fs"),dR=require("path");vt();nl();var ot={control:"control",binary:"binary"},st={idle:"idle",connecting:"connecting",open:"open",degraded:"degraded",closed:"closed"},kb={clientApp:{enabled:["ws","rtc"],channels:{control:{strategy:"priority",prefer:"rtc"},binary:{strategy:"priority",prefer:"rtc"}}},remoteDesktop:{enabled:["ws","rtc"],channels:{control:{strategy:"priority",prefer:"rtc"},binary:{strategy:"priority",prefer:"rtc"}}}};var ds=class{static id="base";static capabilities={control:!1,binary:!1,signaling:"none"};static priority={control:0,binary:0};constructor(){this._listeners=new Map,this._state=st.idle}get state(){return this._state}get ready(){return this._state===st.open}supports(e){return!!this.constructor.capabilities[e]}on(e,t){this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t)}off(e,t){this._listeners.get(e)?.delete(t)}_emit(e,...t){let n=this._listeners.get(e);if(n)for(let i of n)i(...t)}_setState(e){this._state!==e&&(this._state=e,this._emit("stateChange",e))}connect(e){throw new Error("Not implemented: connect")}disconnect(){throw new Error("Not implemented: disconnect")}send(e,t){throw new Error("Not implemented: send")}};var il=class extends ds{static id="ws";static capabilities={control:!0,binary:!0,signaling:"ws"};static priority={control:100,binary:10};constructor(){super(),this._socket=null}get socket(){return this._socket}connect(e){this._socket=e.socket,this._setState(e.socket.connected?st.open:st.connecting),e.socket.on("connect",()=>this._setState(st.open)),e.socket.on("disconnect",()=>this._setState(st.closed)),e.socket.onAny?.((t,n)=>this._emit("message",{event:t,data:n,source:"ws"}))}disconnect(){this._socket=null,this._setState(st.closed)}send(e,t){if(!this._socket?.connected)return!1;let n=this._socket._rawEmit||this._socket.emit.bind(this._socket);if(e===ot.control){let{event:i,args:s=[]}=t;return n(i,...s),!0}if(e===ot.binary){let i=this._socket.conn?.transport;return i&&i.writable===!1?!1:(n("tiles-bin-v2",t),!0)}return!1}};var Db=K(require("node-datachannel"),1);function g2(r,e){return e&&typeof e=="object"&&e.type==="Buffer"&&Array.isArray(e.data)?{__b:Buffer.from(e.data).toString("base64")}:e}function v2(r,e){return e&&typeof e=="object"&&typeof e.__b=="string"?Buffer.from(e.__b,"base64"):e}function Ob(r){return JSON.stringify(r,g2)}function Mb(r){return JSON.parse(typeof r=="string"?r:Buffer.from(r).toString("utf8"),v2)}at();var Nb=K(require("node:dns/promises"),1),y2=3e4,x2=/\s([0-9a-f-]{8,}\.local)\s/i,Ib=new Map;async function _2(r){let e=Ib.get(r);if(e&&Date.now()-e.ts<y2)return e.ip;try{let{address:t}=await Nb.default.lookup(r);return Ib.set(r,{ip:t,ts:Date.now()}),t}catch{return null}}async function Lb(r){let e=r.match(x2);if(!e)return r;let t=await _2(e[1]);return t?r.replace(e[1],t):null}var{PeerConnection:b2}=Db.default,w2=[{hostname:"stun.l.google.com",port:19302,type:"Stun"},{hostname:"stun1.l.google.com",port:19302,type:"Stun"},{hostname:"stun2.l.google.com",port:19302,type:"Stun"},{hostname:"stun3.l.google.com",port:19302,type:"Stun"},{hostname:"stun4.l.google.com",port:19302,type:"Stun"},{hostname:"global.stun.twilio.com",port:3478,type:"Stun"},{hostname:"stun.cloudflare.com",port:3478,type:"Stun"}];async function S2(r,e){try{let t=await fetch(r,{headers:{"X-API-Key":e}});if(!t.ok)throw new Error(`HTTP ${t.status}`);let{iceServers:n}=await t.json(),i=[];for(let s of n)for(let o of s.urls)if(o.startsWith("stun:")){let a=o.replace("stun:","").split(":")[0],c=parseInt(o.split(":")[2]||"3478");i.push({hostname:a,port:c,type:"Stun"})}else if(o.startsWith("turn:")||o.startsWith("turns:")){let a=o.startsWith("turns:"),l=o.replace(/^turns?:/,"").split("?")[0],p=l.split(":")[0],f=parseInt(l.split(":")[1]||(a?"5349":"3478")),h=o.includes("transport=tcp")?"Tcp":"Udp";i.push({hostname:p,port:f,type:a?"Tls":"Turn",relayType:h,username:s.username,password:s.credential})}return i}catch(t){return console.error("[WebRtcProtocol] TURN fetch failed:",t.message),null}}var ol=class extends ds{static id="rtc";static capabilities={control:!0,binary:!0,signaling:"external"};static priority={control:50,binary:100};constructor(){super(),this._pc=null,this._dcControl=null,this._dcBinary=null,this._iceServers=w2,this._refreshTimer=null,this._remoteSet=!1,this._pendingCandidates=[],this._signaling=null,this._iceGraceTimer=null}async connect(e){this._ctx=e,this._setState(st.connecting);let t=e.profile?.rtc||{};t.enableTurn&&e.auth?.apiKey&&t.turnApiUrl&&await this._refreshTurn(t),this._signaling=e.signaling,this._signaling?.on?.(n=>this._handleSignal(n,t))}disconnect(){clearTimeout(this._refreshTimer),this._signaling?.off?.(),this._signaling=null,this._cleanupPeer(),this._setState(st.closed)}send(e,t){if(e===ot.control){if(!this._dcControl)return!1;try{return this._dcControl.sendMessage(Ob({event:t.event,args:t.args||[],ackId:t.ackId||null})),!0}catch(n){return console.error("[WebRtcProtocol] send control:",n.message),!1}}if(e===ot.binary){if(!this._dcBinary)return!1;try{let n=Array.isArray(t)?t:[t],i=this._ctx.profile?.rtc?.dcMaxMessageSize??65536,s=$.webrtc.dcBufferThreshold;for(let o of n){if(this._dcBinary.bufferedAmount()>s)return!0;o.length<=i&&this._dcBinary.sendMessageBinary(o)}return!0}catch(n){return console.error("[WebRtcProtocol] send binary:",n.message),!1}}return!1}_handleSignal(e,t){if(e.type==="offer")this._processOffer(e.sdp,t);else if(e.type==="ice"){if(!this._remoteSet||!this._pc){this._pendingCandidates.push({candidate:e.candidate,mid:e.mid||"0"});return}this._addRemoteCandidate(e.candidate,e.mid||"0")}}async _addRemoteCandidate(e,t){try{let n=await Lb(e);if(!n||!this._pc)return;this._pc.addRemoteCandidate(n,t)}catch(n){console.error("[WebRtcProtocol] addRemoteCandidate:",n.message)}}_createPeer(e){try{this._pc?.close()}catch{}this._pc=null,this._dcControl=null,this._dcBinary=null,this._remoteSet=!1,this._pendingCandidates=[],this._iceGraceTimer&&(clearTimeout(this._iceGraceTimer),this._iceGraceTimer=null);let t=this._ctx?.auth?.socketId||"anon",n=new b2(`peer-${t}`,{iceServers:this._iceServers});this._pcState="new",n.onStateChange(i=>{if(this._pcState=i,i==="failed"||i==="closed")this._iceGraceTimer&&(clearTimeout(this._iceGraceTimer),this._iceGraceTimer=null),this._setState(st.closed);else if(i==="disconnected"){if(this._iceGraceTimer)return;this._iceGraceTimer=setTimeout(()=>{this._iceGraceTimer=null,this._pcState!=="connected"&&this._setState(st.closed)},$.webrtc.iceDisconnectGraceMs)}else i==="connected"&&this._iceGraceTimer&&(clearTimeout(this._iceGraceTimer),this._iceGraceTimer=null)}),n.onDataChannel(i=>{let s=i.getLabel?.()||"",o=()=>{s==="control"?this._dcControl=i:s==="binary"&&(this._dcBinary=i),this._dcControl&&this._dcBinary&&this._setState(st.open)};i.onOpen(o),i.onClosed(()=>{s==="control"&&(this._dcControl=null),s==="binary"&&(this._dcBinary=null),!this._dcControl&&!this._dcBinary&&this._setState(st.closed)}),i.onError(a=>console.error(`[WebRtcProtocol] DC[${s}] error:`,a)),i.onMessage(a=>{if(s!=="control")return;let c;try{c=Mb(a)}catch(l){console.error("[WebRtcProtocol] control parse:",l.message);return}try{this._emit("message",{event:c.event,data:c,source:"rtc"})}catch(l){console.error(`[WebRtcProtocol] handler error event=${c.event}:`,l.message)}})}),this._pc=n}_processOffer(e,t){return this._createPeer(t),new Promise((n,i)=>{this._pc.onLocalDescription((o,a)=>{a==="answer"&&(this._signaling?.send?.({type:"answer",sdp:o}),n())}),this._pc.onLocalCandidate((o,a)=>{o&&this._signaling?.send?.({type:"ice",candidate:o,mid:a})});try{this._pc.setRemoteDescription(e,"offer"),this._remoteSet=!0;for(let{candidate:o,mid:a}of this._pendingCandidates)this._addRemoteCandidate(o,a);this._pendingCandidates=[],this._pc.setLocalDescription()}catch(o){this._signaling?.send?.({type:"error",message:o.message}),i(o)}let s=t?.answerTimeout||1e4;setTimeout(()=>i(new Error("Answer timeout")),s)})}_cleanupPeer(){this._iceGraceTimer&&(clearTimeout(this._iceGraceTimer),this._iceGraceTimer=null);try{this._pc?.close()}catch{}this._pc=null,this._dcControl=null,this._dcBinary=null}async _refreshTurn(e){let t=await S2(e.turnApiUrl,this._ctx.auth.apiKey);t?.length&&(this._iceServers=t,$.logging?.webrtc&&console.log(`[WebRtcProtocol] TURN credentials loaded (${t.length} servers)`)),clearTimeout(this._refreshTimer),this._refreshTimer=setTimeout(()=>this._refreshTurn(e),e.turnRefreshInterval)}};var Bb=new Map;function Ud(r){if(!r?.id)throw new Error("Adapter missing static id");Bb.set(r.id,r)}function jb(r){return Bb.get(r)}oh();Ud(il);Ud(ol);var yl=class{constructor(e,t){let n=t.enableWebRTC?"remoteDesktop":"clientApp",i={...kb[n]};t.enableWebRTC||(i.enabled=["ws"]),i.rtc={enableTurn:!!(t.apiKey&&t.turnApiUrl),turnApiUrl:t.turnApiUrl||null,turnRefreshInterval:t.turnRefreshInterval,dcMaxMessageSize:t.dcMaxMessageSize,answerTimeout:t.answerTimeout},this._profile=i,this._auth={apiKey:t.apiKey||null,socketId:e.id},this._socket=e,this._wsChunkSize=t.wsChunkSize,this._dcChunkSize=t.dcChunkSize,this._dcMaxTilesPerFrame=t.dcMaxTilesPerFrame,this._maxControlBuffer=t.maxControlBuffer,this._adapters=new Map,this._listeners=new Map,this._buffer=[],this._rtcSignalingHandler=null,this._sigListeners=null}get type(){return this._pickAdapter(ot.binary)?.constructor.id==="rtc"?"dc":"ws"}async init(){for(let e of this._profile.enabled){let t=jb(e);if(!t)continue;let n=new t;n.on("stateChange",s=>this._onAdapterStateChange(e,s)),n.on("message",({event:s,data:o,source:a})=>this._dispatch(s,o,a)),this._adapters.set(e,n);let i=this._buildCtx(e);await n.connect(i)}}setupSignaling(e){this._installSignalingListeners()}emit(e,...t){this._sendControl(e,t)}sendTiles(e,t){let{tiles:n,timestamp:i}=e;if(!n?.length)return[];let s=this._pickAdapter(ot.binary),o=i??Date.now();if(s?.constructor.id==="rtc"&&t){let a=[];for(let c=0;c<n.length;c+=this._dcChunkSize)a.push(t(n.slice(c,c+this._dcChunkSize),o));return s.send(ot.binary,a),n}return this._emitTilesChunked(n,o)}close(){for(let e of this._adapters.values())try{e.disconnect()}catch{}this._adapters.clear(),this._buffer=[]}attachAsBus(e){if(e._rawEmit)return;let t=e.emit.bind(e);e._rawEmit=t;let n=new Set(["error","disconnect","disconnecting","connect","newListener","removeListener"]);e.emit=(i,...s)=>n.has(i)?t(i,...s):(this._sendControl(i,s),!0)}_emitTilesChunked(e,t){let n=this._adapters.get("ws");if(!n?.ready)return[];let i=this._wsChunkSize,s=[];for(let o=0;o<e.length;o+=i){let a=e.slice(o,o+i);if(n.send(ot.binary,_s(a,t))===!1)break;s.push(...a)}return s}_buildCtx(e){let t={auth:this._auth,profile:this._profile};return e==="ws"&&(t.socket=this._socket),e==="rtc"&&(t.signaling={send:n=>this._sendSignaling(n),on:n=>{this._rtcSignalingHandler=n,this._installSignalingListeners()},off:()=>{this._rtcSignalingHandler=null,this._removeSignalingListeners()}}),t}_onAdapterStateChange(e,t){t===st.open&&this._flushBuffer()}_pickAdapter(e){let t=this._profile.channels[e];if(!t)return null;let n=[...this._adapters.values()].filter(i=>i.supports(e)&&i.ready);if(t.prefer){let i=n.find(s=>s.constructor.id===t.prefer);if(i)return i}return n.sort((i,s)=>(s.constructor.priority[e]??0)-(i.constructor.priority[e]??0)),n[0]||null}hasReadyAdapter(){return!!(this._pickAdapter(ot.control)||this._pickAdapter(ot.binary))}_sendControl(e,t,n){let i=this._pickAdapter(ot.control);if(!i){this._buffer.push({event:e,args:t,ackId:n}),this._buffer.length>this._maxControlBuffer&&this._buffer.shift();return}i.constructor.id==="rtc"?i.send(ot.control,{event:e,args:t,ackId:n}):i.send(ot.control,{event:e,args:t})}_flushBuffer(){if(!(!this._buffer.length||!this._pickAdapter(ot.control)))for(;this._buffer.length;){let{event:t,args:n,ackId:i}=this._buffer.shift();this._sendControl(t,n,i)}}_dispatch(e,t,n){if(n==="rtc"){let s=Array.isArray(t?.args)?[...t.args]:[],o=t?.ackId;o&&s.push((...l)=>this._sendAck(o,l));let a=this._listeners.get(e);if(a)for(let l of a)l(...s);let c=this._socket.listeners?.(e)||[];for(let l of c)l(...s);return}let i=this._listeners.get(e);if(i)for(let s of i)s(t)}_sendAck(e,t){let n=this._adapters.get("rtc");n?.ready&&n.send(ot.control,{event:"__ack",args:t,ackId:e})}_sendSignaling(e){let t=this._adapters.get("ws");if(t?.ready){t.send(ot.control,{event:this._sigEvent(e.type),args:[this._sigData(e)]});return}console.warn("[ProtocolManager] signaling unavailable (ws down)")}_sigEvent(e){return e==="offer"?"webrtc:offer":e==="answer"?"webrtc:answer":e==="ice"?"webrtc:ice-candidate":"webrtc:error"}_sigData(e){return e.type==="offer"||e.type==="answer"?{sdp:e.sdp}:e.type==="ice"?{candidate:e.candidate,mid:e.mid}:e}_installSignalingListeners(){if(!this._rtcSignalingHandler||this._sigListeners)return;let e=({sdp:n})=>this._rtcSignalingHandler?.({type:"offer",sdp:n}),t=({candidate:n,mid:i})=>this._rtcSignalingHandler?.({type:"ice",candidate:n,mid:i});this._sigListeners={onOffer:e,onIce:t},this._socket.on("webrtc:offer",e),this._socket.on("webrtc:ice-candidate",t)}_removeSignalingListeners(){this._sigListeners&&(this._socket.off("webrtc:offer",this._sigListeners.onOffer),this._socket.off("webrtc:ice-candidate",this._sigListeners.onIce),this._sigListeners=null)}};ui();at();var TT=require("path"),CT=require("url");var El=K(require("net"),1),ae=K(require("fs"),1),fe=K(require("path"),1),Dw=K(require("os"),1),Bw=require("child_process"),jw=require("url");var ch={win32:[{id:"cmd",label:"Command Prompt",path:"cmd.exe",args:[]},{id:"powershell",label:"PowerShell",path:"powershell.exe",args:["-NoLogo"]},{id:"pwsh",label:"PowerShell Core",path:"pwsh.exe",args:["-NoLogo"]}],unix:[{id:"bash",label:"Bash",path:"/bin/bash",args:["-l"]},{id:"zsh",label:"Zsh",path:"/bin/zsh",args:["-l"]},{id:"sh",label:"Sh",path:"/bin/sh",args:["-l"]}]};function Pw(){return process.platform==="win32"?ch.win32:[]}function Iw(r){if(process.platform==="win32"){let n=r?ch.win32.find(s=>s.id===r):null;if(n)return n;let i=process.env.COMSPEC;return i?{id:"cmd",label:"Command Prompt",path:i,args:[]}:ch.win32[0]}let e=process.env.SHELL||"/bin/bash",t=e.split("/").pop();return{id:t,label:t,path:e,args:["-l"]}}var uh=fe.default.dirname((0,jw.fileURLToPath)(__importMetaUrl)),fn=fe.default.join(Dw.default.homedir(),".9remote"),Wo=process.platform==="win32"?"\\\\.\\pipe\\9remote-pty":fe.default.join(fn,"pty-daemon.sock"),Nw=fe.default.join(uh,"ptyDaemon.js"),Lw=fe.default.join(uh,"ptyDaemon.cjs"),xl=fe.default.join(fn,"daemon");function Fw(r,e){if(ae.default.existsSync(r)){ae.default.mkdirSync(e,{recursive:!0});for(let t of ae.default.readdirSync(r,{withFileTypes:!0})){let n=fe.default.join(r,t.name),i=fe.default.join(e,t.name);t.isDirectory()?Fw(n,i):t.isFile()&&ae.default.copyFileSync(n,i)}}}function J2(r,e){let t=r;for(let n=0;n<6;n++){let i=fe.default.join(t,"node_modules",e);if(ae.default.existsSync(i))return i;let s=fe.default.dirname(t);if(s===t)break;t=s}return null}var X2=r=>J2(r,"node-pty");function Z2(r){try{if(!ae.default.existsSync(xl))return;let e=fe.default.join(fn,"pids","ptyDaemon.pid"),t=!1;try{let n=parseInt(ae.default.readFileSync(e,"utf8").trim(),10);if(Number.isFinite(n)&&n>0)try{process.kill(n,0),t=!0}catch{}}catch{}if(t)return;for(let n of ae.default.readdirSync(xl))if(n!==`v${r}`)try{ae.default.rmSync(fe.default.join(xl,n),{recursive:!0,force:!0})}catch{}}catch{}}function Q2(r){Z2("18");let e=fe.default.join(xl,`v${"18"}`),t=r.endsWith(".js"),n=t?fe.default.join(e,"features","terminal"):e,i=fe.default.join(n,fe.default.basename(r)),s=fe.default.join(n,"node_modules","node-pty");if(ae.default.existsSync(i)&&ae.default.existsSync(s))return{script:i,cwd:n};try{if(ae.default.mkdirSync(n,{recursive:!0}),ae.default.copyFileSync(r,i),t){let a=fe.default.dirname(r);ae.default.copyFileSync(fe.default.join(a,"constants.js"),fe.default.join(n,"constants.js"));let c=fe.default.join(e,"lib");ae.default.mkdirSync(c,{recursive:!0}),ae.default.copyFileSync(fe.default.resolve(a,"..","..","lib","constants.js"),fe.default.join(c,"constants.js"))}let o=X2(fe.default.dirname(r));return o?(Fw(o,s),{script:i,cwd:n}):null}catch{return null}}var Fr=null,ws=!1,jn=!1,lh="",eB=0,Ss=new Map,_l=new Map;function tB(){return++eB}function Tl(r,e){_l.has(r)||_l.set(r,[]),_l.get(r).push(e)}function wl(r,e){let t=_l.get(r);if(t)for(let n of t)try{n(e)}catch(i){console.error(`[DaemonClient] Error in ${r} handler:`,i)}}function ph(r){if(!Fr||!ws)return!1;try{return Fr.write(JSON.stringify(r)+`
111
111
  `),!0}catch(e){return console.error("[DaemonClient] Send error:",e),!1}}function Cl(r,e=5e3){return new Promise((t,n)=>{let i=tB();r.requestId=i;let s=setTimeout(()=>{Ss.delete(i),n(new Error("Request timeout"))},e);Ss.set(i,{resolve:t,reject:n,timer:s}),ph(r)||(clearTimeout(s),Ss.delete(i),n(new Error("Not connected to daemon")))})}function rB(r){let{type:e,requestId:t,...n}=r;if(t&&Ss.has(t)){let{resolve:i,timer:s}=Ss.get(t);clearTimeout(s),Ss.delete(t),i({type:e,...n});return}switch(e){case"output":wl("output",{sessionId:n.sessionId,data:Buffer.from(n.data,"base64")});break;case"sessionClosed":wl("sessionClosed",n.sessionId);break;case"pong":break;default:console.log("[DaemonClient] Unknown message:",e)}}function Sl(){return new Promise(r=>{let e=El.default.connect(Wo),t=setTimeout(()=>{e.destroy(),r(!1)},1e3);e.on("connect",()=>{clearTimeout(t),e.destroy(),r(!0)}),e.on("error",()=>{if(clearTimeout(t),process.platform!=="win32"&&ae.default.existsSync(Wo))try{ae.default.unlinkSync(Wo)}catch{}r(!1)})})}function nB(){ae.default.existsSync(fn)||ae.default.mkdirSync(fn,{recursive:!0});let r=ae.default.existsSync(Nw)?Nw:ae.default.existsSync(Lw)?Lw:null;if(!r)return console.error("[DaemonClient] \u274C Daemon script not found"),null;let e=Q2(r);return e||{script:r,cwd:uh}}async function iB(){if(!ae.default.existsSync(fn))try{ae.default.mkdirSync(fn,{recursive:!0})}catch(a){return console.error("[DaemonClient] Failed to create socket directory:",a.message),!1}let r=nB();if(!r)return!1;let{script:e,cwd:t}=r,n=fe.default.join(fn,"logs");try{ae.default.mkdirSync(n,{recursive:!0})}catch{}let i=fe.default.join(n,"daemon.log"),s;try{s=ae.default.openSync(i,"w")}catch(a){console.error("[DaemonClient] Failed to open log file:",a.message),s="ignore"}if((0,Bw.spawn)("node",[e],{detached:!0,stdio:["ignore",s,s],cwd:t}).unref(),typeof s=="number")try{ae.default.closeSync(s)}catch{}for(let a=0;a<20;a++)if(await new Promise(c=>setTimeout(c,100)),await Sl())return!0;console.error("[DaemonClient] \u274C Failed to start daemon");try{let a=ae.default.readFileSync(i,"utf8");a.trim()&&(console.error("[DaemonClient] Daemon log:"),console.error(a))}catch{}return!1}function sB(){return new Promise(r=>{let e=El.default.connect(Wo),t="",n=s=>{try{e.destroy()}catch{}r(s)},i=setTimeout(()=>n(null),2e3);e.on("connect",()=>e.write(JSON.stringify({type:"ping",requestId:-1})+`
112
112
  `)),e.on("data",s=>{t+=s.toString();let o=t.indexOf(`
113
113
  `);if(o!==-1){clearTimeout(i);try{let a=JSON.parse(t.slice(0,o));n(a.version||"unknown")}catch{n(null)}}}),e.on("error",()=>{clearTimeout(i),n(null)})})}async function oB(){try{let r=fe.default.join(fn,"pids","ptyDaemon.pid"),e=parseInt(ae.default.readFileSync(r,"utf8").trim(),10);Number.isFinite(e)&&e>0&&process.kill(e,"SIGTERM")}catch{}for(let r=0;r<20;r++){if(!await Sl())return;await new Promise(e=>setTimeout(e,100))}}async function Uw(){if(!(ws||jn)){jn=!0;try{if(await Sl()){let r=await sB();r!=="18"&&(console.log(`[DaemonClient] Daemon v${r} != v${"18"}, restarting`),await oB())}return!await Sl()&&!await iB()?(console.error("[DaemonClient] \u274C Failed to start daemon"),jn=!1,!1):new Promise(r=>{let e=setTimeout(()=>{console.error("[DaemonClient] \u274C Connection timeout after 5s"),Fr&&Fr.destroy(),jn=!1,r(!1)},5e3);Fr=El.default.connect(Wo),Fr.on("connect",()=>{clearTimeout(e),ws=!0,jn=!1,wl("connected"),r(!0)}),Fr.on("data",t=>{lh+=t.toString();let n=lh.split(`
114
- `);lh=n.pop()||"";for(let i of n)if(i.trim())try{rB(JSON.parse(i))}catch{console.error("[DaemonClient] Invalid message:",i)}}),Fr.on("close",()=>{ws=!1,Fr=null,wl("disconnected"),setTimeout(()=>{!ws&&!jn&&Uw()},2e3)}),Fr.on("error",t=>{clearTimeout(e),console.error("[DaemonClient] \u274C Connection error:",t.message),console.error("[DaemonClient] Error code:",t.code),jn=!1,r(!1)})})}catch(r){return console.error("[DaemonClient] \u274C Connect error:",r),jn=!1,!1}}}async function qw(){return Uw()}function Tr(){return ws}async function Al(){return(await Cl({type:"listSessions"})).sessions||[]}async function fh(r,e=80,t=24,n=null,i=`session-${Date.now()}`,s=null){return await Cl({type:"createSession",sessionId:i,name:r,cols:e,rows:t,shellId:n,cwd:s})}async function Hw(r){return await Cl({type:"joinSession",sessionId:r})}function dh(r,e){return ph({type:"input",sessionId:r,data:e})}function $w(r,e,t){return ph({type:"resize",sessionId:r,cols:e,rows:t})}async function pi(r){return await Cl({type:"deleteSession",sessionId:r})}ui();Ii();var Gw=require("child_process");ot();var aB={darwin:()=>({cmd:"caffeinate",args:["-u","-t",String($.displayWake.macDurationSec)]}),linux:()=>({cmd:"xset",args:["dpms","force","on"]}),win32:()=>({cmd:"powershell.exe",args:["-NonInteractive","-NoProfile","-WindowStyle","Hidden","-Command",`Add-Type -Name K -Namespace W -MemberDefinition '[System.Runtime.InteropServices.DllImport("kernel32")]public static extern uint SetThreadExecutionState(uint e);'; [void][W.K]::SetThreadExecutionState(0x80000003)`]})},Ww=0;function zw(){let r=$.displayWake;if(!r?.enabled)return;let e=Date.now();if(e-Ww<r.throttleMs)return;Ww=e;let t=aB[process.platform];if(t)try{let{cmd:n,args:i}=t(),s=(0,Gw.spawn)(n,i,{detached:!0,stdio:"ignore",windowsHide:!0});s.on("error",()=>{}),s.unref()}catch{}}ot();var dS=Tn("remote"),dn=null;function dB(){return process.env.CODESPACES==="true"||process.env.GITPOD_WORKSPACE_ID||process.platform==="linux"&&!process.env.DISPLAY}async function yS(){if(dn!==null)return dn;if(dB())return dn=!1,dS.info("\u2705 Remote desktop not available (headless environment)"),dn;try{let r=await import("@hurdlegroup/robotjs");(r.default||r).getScreenSize(),dn=!0}catch{dn=!1,dS.info("\u2705 Remote desktop not available (no display or robotjs not installed)")}return dn}function Il(){return dn===!0}function xS(){return Ur}var di=null,_S=null,bS=null,wS=null,SS=null,ES=null,TS=null,Ur=null,hS=null,mS=null,gS=null,vS=null;async function hB(){if(di)return!0;try{let r=await import("@hurdlegroup/robotjs");di=r.default||r;let{TileManager:e}=await Promise.resolve().then(()=>(nS(),rS)),{ResourceManager:t}=await Promise.resolve().then(()=>(sS(),iS)),{ScreenUpdateHelper:n}=await Promise.resolve().then(()=>(aS(),oS)),{MouseHandler:i}=await Promise.resolve().then(()=>(lS(),cS)),{KeyboardHandler:s}=await Promise.resolve().then(()=>(fS(),pS)),{ScreenHandler:o}=await Promise.resolve().then(()=>(oh(),Ow));return _S=e,bS=t,wS=n,SS=i,ES=s,TS=o,di.setMouseDelay(2),di.setKeyboardDelay(2),!0}catch(r){return console.error("\u274C Failed to load remote modules:",r.message),!1}}async function CS(r,e){if(!dn){r.emit("remote:unavailable");return}if(!await hB()){r.emit("remote:unavailable");return}Ur||(Ur=new bS,hS=new wS(Ur),mS=new SS(di,Ur),gS=new ES(di,Ur),vS=new TS(Ur,hS),Ur.startResourceMonitoring());let n=r.data.protocol;if(!n){r.emit("remote:unavailable");return}let i=r.handshake.auth?.apiKey,s=new _S(di);Ur.addClient(r.id,{tileManager:s,protocol:n,screenInterval:null,authenticated:!0,apiKey:i}),r.data.remoteAttached=!0;let o=a=>(...c)=>(zw(),a(...c));mS.setupMouseHandlers(r,o),gS.setupKeyboardHandlers(r,o),vS.setupScreenHandlers(r,o,n),r.on("disconnect",()=>{let a=n._adapters?.get("rtc"),c=!1,l=null,p=null,f=()=>{c||(c=!0,l&&(clearTimeout(l),l=null),a&&p&&a.off("stateChange",p),Ur.removeClient(r.id),n.close(),bs(n))};if(!a?.ready)return f();p=h=>{h===st.closed&&f()},a.on("stateChange",p),l=setTimeout(f,$.resourceManagement.disconnectGraceMs)}),r.emit("remote:ready")}pn();var Fn=K(require("fs"),1),Sh=K(require("path"),1),Nl=0,zo=null,mB=6e4,gB={name:"9Remote",postCreateCommand:"npm install -g 9remote@latest",postAttachCommand:"9remote start",forwardPorts:[2208],portsAttributes:{2208:{label:"9Remote Server",onAutoForward:"notify"}}};function hn(){return process.env.CODESPACES==="true"}function AS(){return hn()?{isCodespaces:!0,codespaceName:process.env.CODESPACE_NAME||"unknown",workspacePath:process.env.CODESPACE_VSCODE_FOLDER||process.cwd()}:null}function RS(){Nl++,hn()&&Nl===1&&vB()}function kS(){Nl--,hn()&&Nl===0&&yB()}function vB(){zo||(zo=setInterval(()=>{process.memoryUsage()},mB))}function yB(){zo&&(console.log("\u23F8\uFE0F Stopping Codespaces heartbeat"),clearInterval(zo),zo=null)}function OS(r){return Sh.default.join(r,".devcontainer","devcontainer.json")}function MS(r){try{let e=OS(r);if(!Fn.default.existsSync(e))return{enabled:!1,exists:!1};let t=JSON.parse(Fn.default.readFileSync(e,"utf8"));return{enabled:t.postAttachCommand==="9remote start"||t.postAttachCommand==="9remote",exists:!0}}catch{return{enabled:!1,exists:!1,error:"Failed to read config"}}}function PS(r,e){try{let t=Sh.default.join(r,".devcontainer"),n=OS(r);Fn.default.existsSync(t)||Fn.default.mkdirSync(t,{recursive:!0});let i={...gB};if(Fn.default.existsSync(n))try{i={...JSON.parse(Fn.default.readFileSync(n,"utf8"))}}catch{}return e?(i.postAttachCommand="9remote start",i.postCreateCommand||(i.postCreateCommand="npm install -g 9remote@latest")):delete i.postAttachCommand,Fn.default.writeFileSync(n,JSON.stringify(i,null,2)),{success:!0,enabled:e}}catch(t){return{success:!1,error:t.message}}}var Ll=K(require("os"),1),Re=K(require("fs"),1),Un=K(require("path"),1);vt();var Ts=ie.BUFFERS,Dl=Un.default.join(ie.STATE,"sessions.json"),Bl=Un.default.join(ie.STATE,"terminalGroups.json"),jl="/tmp/9remote-uploads";Re.default.existsSync(jl)||Re.default.mkdirSync(jl,{recursive:!0});function Eh(){return process.platform==="win32"?process.env.COMSPEC||"powershell.exe":process.env.SHELL||"/bin/zsh"}function Th(r){return r?"/workspaces":Ll.default.homedir()}function Ch(){let r=Ll.default.homedir(),e=Ll.default.userInfo().username,t=Eh(),n={...process.env};if(delete n.PORT,Object.assign(n,{HOME:r,USER:e,LOGNAME:e,SHELL:t,TERM:"xterm-256color",COLORTERM:"truecolor",LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8",LC_CTYPE:"en_US.UTF-8",PWD:r,OLDPWD:r,TMPDIR:n.TMPDIR||(process.platform==="win32"?n.TEMP||n.TMP:"/tmp"),__CF_USER_TEXT_ENCODING:n.__CF_USER_TEXT_ENCODING,XPC_FLAGS:n.XPC_FLAGS,XPC_SERVICE_NAME:n.XPC_SERVICE_NAME,SSH_AUTH_SOCK:n.SSH_AUTH_SOCK,TERM_PROGRAM:"9Remote",TERM_PROGRAM_VERSION:"1.0.0",ITERM_SESSION_ID:`9remote-${Date.now()}`,SHLVL:"1"}),t.includes("bash")){let i=n.PROMPT_COMMAND||"";n.PROMPT_COMMAND=`printf "\\e]7;file://%s\\a" "\${HOSTNAME}\${PWD}"${i?`; ${i}`:""}`}return n}function IS(){Re.default.existsSync(Ts)||Re.default.mkdirSync(Ts,{recursive:!0})}function Ah(r,e,t){if(t==="buffer"){IS();try{Re.default.writeFileSync(Un.default.join(Ts,`${r}.buf`),e.join(""),"utf8")}catch(n){console.log(`\u26A0\uFE0F Failed to save buffer for ${r}:`,n.message)}}}function NS(r,e){if(e!=="buffer")return null;let t=Un.default.join(Ts,`${r}.buf`);try{if(Re.default.existsSync(t))return Re.default.readFileSync(t,"utf8")}catch(n){console.log(`\u26A0\uFE0F Failed to load buffer for ${r}:`,n.message)}return null}function Fl(r){let e=Un.default.join(Ts,`${r}.buf`);try{Re.default.existsSync(e)&&Re.default.unlinkSync(e)}catch{}}function LS(){IS();try{return Re.default.readdirSync(Ts).filter(r=>r.endsWith(".buf")).map(r=>r.replace(".buf",""))}catch{return[]}}function Rh(){try{if(Re.default.existsSync(Dl))return JSON.parse(Re.default.readFileSync(Dl,"utf8"))}catch(r){console.log("\u26A0\uFE0F Failed to load session metadata:",r.message)}return{}}function mn(r){try{let e={};for(let[n,i]of r)e[n]={name:i.name,createdAt:i.createdAt,shellId:i.shellId,cwd:i.cwd};let t=Un.default.dirname(Dl);Re.default.existsSync(t)||Re.default.mkdirSync(t,{recursive:!0}),Re.default.writeFileSync(Dl,JSON.stringify(e,null,2),"utf8")}catch(e){console.log("\u26A0\uFE0F Failed to save session metadata:",e.message)}}function DS(){try{if(Re.default.existsSync(Bl)){let r=JSON.parse(Re.default.readFileSync(Bl,"utf8"));return{groups:r.groups||[],sessionGroups:r.sessionGroups||{}}}}catch(r){console.log("\u26A0\uFE0F Failed to load groups:",r.message)}return{groups:[],sessionGroups:{}}}function BS(r,e){try{let t=Un.default.dirname(Bl);Re.default.existsSync(t)||Re.default.mkdirSync(t,{recursive:!0});let n={groups:Array.from(r.values()),sessionGroups:e};Re.default.writeFileSync(Bl,JSON.stringify(n,null,2),"utf8")}catch(t){console.log("\u26A0\uFE0F Failed to save groups:",t.message)}}var kh=K(require("node-pty"),1);ui();var jS=2*1024*1024,xB=256*1024,hi="daemon";function FS(r,e,t,n,i){let s=null;r.onData(o=>{t.buffer.push(o),t.buffer.reduce((c,l)=>c+l.length,0)>jS&&(t.buffer=[t.buffer.join("").slice(-jS)]),bt(n,"output",{sessionId:e,data:Buffer.from(o,"utf-8")}),hi==="buffer"&&(s&&clearTimeout(s),s=setTimeout(()=>Ah(e,t.buffer,hi),2e3))}),r.onExit(({exitCode:o})=>{console.log(`PTY exited: sessionId=${e}, code=${o}`),hi==="buffer"&&t.buffer.length>0&&Ah(e,t.buffer,hi),i.delete(e),Fl(e),bt(n,"sessionClosed",e)})}function US(r,e,t,n,i){let s=()=>BS(n,i);r.on("getSessions",o=>{let a=[];for(let[c,l]of t)a.push({id:c,name:l.name,createdAt:l.createdAt,restored:l.restored||!1,shellId:l.shellId,shellLabel:l.shellLabel,groupId:i[c]||null});o(a)}),r.on("getShells",o=>{o({platform:process.platform,shells:Pw()})}),r.on("getGroups",o=>{o(Array.from(n.values()))}),r.on("createGroup",({name:o},a)=>{let c=`group-${Date.now()}`,l={id:c,name:o||"Group",createdAt:Date.now()};n.set(c,l),s(),bt(e,"groupsChanged"),a({success:!0,group:l})}),r.on("renameGroup",({groupId:o,name:a},c)=>{let l=n.get(o);if(!l)return c({success:!1,error:"Group not found"});l.name=a,s(),bt(e,"groupsChanged"),c({success:!0})}),r.on("deleteGroup",async({groupId:o},a)=>{if(!n.delete(o))return a({success:!1,error:"Group not found"});let c=Object.keys(i).filter(l=>i[l]===o);for(let l of c){let p=t.get(l);if(p){if(p.daemon&&Tr())try{await pi(l)}catch{}else p.pty&&(p.pty.kill(),Fl(l));t.delete(l),bt(e,"sessionClosed",l)}delete i[l]}s(),bt(e,"groupsChanged"),a({success:!0})}),r.on("moveSession",({sessionId:o,groupId:a},c)=>{a&&n.has(a)?i[o]=a:delete i[o],s(),bt(e,"groupsChanged"),c({success:!0})}),r.on("createSession",async({name:o,shellId:a,groupId:c},l)=>{let p=`session-${Date.now()}`,f=Iw(a),h=Ch();h.NINE_REMOTE_SESSION_ID=p;let v=Th(hn());try{let x=o||`${f.label} ${t.size+1}`;if(hi==="daemon"&&Tr()){let k=await fh(x,80,24,a,p,v);k.success?(t.set(k.sessionId,{daemon:!0,name:x,createdAt:Date.now(),cwd:k.cwd,shellId:k.shellId,shellLabel:k.shellLabel}),c&&n.has(c)&&(i[k.sessionId]=c,s()),mn(t),l({success:!0,sessionId:k.sessionId,shellLabel:k.shellLabel})):l({success:!1,error:k.error});return}let S=kh.default.spawn(f.path,f.args,{name:"xterm-256color",cols:80,rows:24,cwd:v,env:h,useConpty:!1}),A={pty:S,name:x,createdAt:Date.now(),buffer:[],cwd:v,shellId:f.id,shellLabel:f.label};FS(S,p,A,e,t),t.set(p,A),c&&n.has(c)&&(i[p]=c,s()),l({success:!0,sessionId:p,shellLabel:f.label})}catch(x){console.error("Failed to create session:",x),l({success:!1,error:x.message})}}),r.on("joinSession",async(o,a)=>{let c=t.get(o);if(!c)return a({success:!1,error:"Session not found"});if(c.daemon&&Tr()){try{if(c.needsRespawn){let p=await fh(c.name,80,24,c.shellId,o,c.cwd);if(!p.success)return a({success:!1,error:p.error});delete c.needsRespawn,c.cwd=p.cwd,c.shellLabel=p.shellLabel,mn(t)}let l=await Hw(o);l.cwd&&l.cwd!==c.cwd&&(c.cwd=l.cwd,mn(t)),a({success:l.success,name:c.name,cwd:l.cwd||c.cwd,error:l.error})}catch(l){a({success:!1,error:l.message})}return}if(c.needsRestore&&hi==="buffer")try{let l=Eh(),p=process.platform==="win32"?[]:["-l"],f=Th(hn()),h=kh.default.spawn(l,p,{name:"xterm-256color",cols:80,rows:24,cwd:f,env:Ch(),useConpty:!1});c.pty=h,c.needsRestore=!1,c.cwd=f;let v=NS(o,hi);v&&(c.buffer=[v]),FS(h,o,c,e,t),console.log(`\u2705 Restored PTY session: ${o}`)}catch(l){return console.error("Failed to restore session:",l),a({success:!1,error:"Failed to restore session"})}c.buffer?.length>0&&r.emit("output",{sessionId:o,data:Buffer.from(c.buffer.join("").slice(-xB),"utf-8")}),a({success:!0,name:c.name,cwd:c.cwd})}),r.on("deleteSession",async(o,a)=>{let c=t.get(o);if(!c)return a({success:!1,error:"Session not found"});if(c.daemon&&Tr()){try{await pi(o),t.delete(o),i[o]&&(delete i[o],s()),mn(t),a({success:!0})}catch(l){a({success:!1,error:l.message})}return}c.pty&&c.pty.kill(),t.delete(o),i[o]&&(delete i[o],s()),Fl(o),bt(e,"sessionClosed",o),mn(t),a({success:!0})}),r.on("renameSession",async({sessionId:o,name:a},c)=>{let l=t.get(o);if(!l)return c({success:!1,error:"Session not found"});l.name=a,bt(e,"session-renamed",{sessionId:o,name:a}),mn(t),c({success:!0})})}var qS=K(require("fs"),1),HS=K(require("path"),1);function $S(r,e){r.on("input",({sessionId:t,data:n})=>{if(!t)return;let i=e.get(t);if(i){if(i.daemon&&Tr())return dh(t,n);i.pty&&i.pty.write(Buffer.isBuffer(n)?n.toString("utf-8"):n)}}),r.on("resize",({sessionId:t,cols:n,rows:i})=>{if(!t)return;let s=e.get(t);if(s){if(s.daemon&&Tr())return $w(t,n,i);if(s.pty)try{s.pty.resize(n,i)}catch(o){console.log(`Resize failed for ${t}: ${o.message}`)}}}),r.on("upload-file",({sessionId:t,filename:n,size:i,content:s})=>{if(!t)return;let o=e.get(t);if(o)try{let a=n.replace(/[^a-zA-Z0-9._-]/g,"_"),c=HS.default.join(jl,`${Date.now()}_${a}`);qS.default.writeFileSync(c,Buffer.from(s,"base64")),console.log(`\u{1F4CE} File uploaded: ${c} (${i} bytes)`),o.daemon&&Tr()?dh(t,c):o.pty&&o.pty.write(c)}catch(a){console.error("File upload error:",a),r.emit("output",{sessionId:t,data:Buffer.from(`\r
114
+ `);lh=n.pop()||"";for(let i of n)if(i.trim())try{rB(JSON.parse(i))}catch{console.error("[DaemonClient] Invalid message:",i)}}),Fr.on("close",()=>{ws=!1,Fr=null,wl("disconnected"),setTimeout(()=>{!ws&&!jn&&Uw()},2e3)}),Fr.on("error",t=>{clearTimeout(e),console.error("[DaemonClient] \u274C Connection error:",t.message),console.error("[DaemonClient] Error code:",t.code),jn=!1,r(!1)})})}catch(r){return console.error("[DaemonClient] \u274C Connect error:",r),jn=!1,!1}}}async function qw(){return Uw()}function Tr(){return ws}async function Al(){return(await Cl({type:"listSessions"})).sessions||[]}async function fh(r,e=80,t=24,n=null,i=`session-${Date.now()}`,s=null){return await Cl({type:"createSession",sessionId:i,name:r,cols:e,rows:t,shellId:n,cwd:s})}async function Hw(r){return await Cl({type:"joinSession",sessionId:r})}function dh(r,e){return ph({type:"input",sessionId:r,data:e})}function $w(r,e,t){return ph({type:"resize",sessionId:r,cols:e,rows:t})}async function pi(r){return await Cl({type:"deleteSession",sessionId:r})}ui();Ii();var Gw=require("child_process");at();var aB={darwin:()=>({cmd:"caffeinate",args:["-u","-t",String($.displayWake.macDurationSec)]}),linux:()=>({cmd:"xset",args:["dpms","force","on"]}),win32:()=>({cmd:"powershell.exe",args:["-NonInteractive","-NoProfile","-WindowStyle","Hidden","-Command",`Add-Type -Name K -Namespace W -MemberDefinition '[System.Runtime.InteropServices.DllImport("kernel32")]public static extern uint SetThreadExecutionState(uint e);'; [void][W.K]::SetThreadExecutionState(0x80000003)`]})},Ww=0;function zw(){let r=$.displayWake;if(!r?.enabled)return;let e=Date.now();if(e-Ww<r.throttleMs)return;Ww=e;let t=aB[process.platform];if(t)try{let{cmd:n,args:i}=t(),s=(0,Gw.spawn)(n,i,{detached:!0,stdio:"ignore",windowsHide:!0});s.on("error",()=>{}),s.unref()}catch{}}at();var dS=Tn("remote"),dn=null;function dB(){return process.env.CODESPACES==="true"||process.env.GITPOD_WORKSPACE_ID||process.platform==="linux"&&!process.env.DISPLAY}async function yS(){if(dn!==null)return dn;if(dB())return dn=!1,dS.info("\u2705 Remote desktop not available (headless environment)"),dn;try{let r=await import("@hurdlegroup/robotjs");(r.default||r).getScreenSize(),dn=!0}catch{dn=!1,dS.info("\u2705 Remote desktop not available (no display or robotjs not installed)")}return dn}function Il(){return dn===!0}function xS(){return Ur}var di=null,_S=null,bS=null,wS=null,SS=null,ES=null,TS=null,Ur=null,hS=null,mS=null,gS=null,vS=null;async function hB(){if(di)return!0;try{let r=await import("@hurdlegroup/robotjs");di=r.default||r;let{TileManager:e}=await Promise.resolve().then(()=>(nS(),rS)),{ResourceManager:t}=await Promise.resolve().then(()=>(sS(),iS)),{ScreenUpdateHelper:n}=await Promise.resolve().then(()=>(aS(),oS)),{MouseHandler:i}=await Promise.resolve().then(()=>(lS(),cS)),{KeyboardHandler:s}=await Promise.resolve().then(()=>(fS(),pS)),{ScreenHandler:o}=await Promise.resolve().then(()=>(oh(),Ow));return _S=e,bS=t,wS=n,SS=i,ES=s,TS=o,di.setMouseDelay(2),di.setKeyboardDelay(2),!0}catch(r){return console.error("\u274C Failed to load remote modules:",r.message),!1}}async function CS(r,e){if(!dn){r.emit("remote:unavailable");return}if(!await hB()){r.emit("remote:unavailable");return}Ur||(Ur=new bS,hS=new wS(Ur),mS=new SS(di,Ur),gS=new ES(di,Ur),vS=new TS(Ur,hS),Ur.startResourceMonitoring());let n=r.data.protocol;if(!n){r.emit("remote:unavailable");return}let i=r.handshake.auth?.apiKey,s=new _S(di);Ur.addClient(r.id,{tileManager:s,protocol:n,screenInterval:null,authenticated:!0,apiKey:i}),r.data.remoteAttached=!0;let o=a=>(...c)=>(zw(),a(...c));mS.setupMouseHandlers(r,o),gS.setupKeyboardHandlers(r,o),vS.setupScreenHandlers(r,o,n),r.on("disconnect",()=>{let a=n._adapters?.get("rtc"),c=!1,l=null,p=null,f=()=>{c||(c=!0,l&&(clearTimeout(l),l=null),a&&p&&a.off("stateChange",p),Ur.removeClient(r.id),n.close(),bs(n))};if(!a?.ready)return f();p=h=>{h===st.closed&&f()},a.on("stateChange",p),l=setTimeout(f,$.resourceManagement.disconnectGraceMs)}),r.emit("remote:ready")}pn();var Fn=K(require("fs"),1),Sh=K(require("path"),1),Nl=0,zo=null,mB=6e4,gB={name:"9Remote",postCreateCommand:"npm install -g 9remote@latest",postAttachCommand:"9remote start",forwardPorts:[2208],portsAttributes:{2208:{label:"9Remote Server",onAutoForward:"notify"}}};function hn(){return process.env.CODESPACES==="true"}function AS(){return hn()?{isCodespaces:!0,codespaceName:process.env.CODESPACE_NAME||"unknown",workspacePath:process.env.CODESPACE_VSCODE_FOLDER||process.cwd()}:null}function RS(){Nl++,hn()&&Nl===1&&vB()}function kS(){Nl--,hn()&&Nl===0&&yB()}function vB(){zo||(zo=setInterval(()=>{process.memoryUsage()},mB))}function yB(){zo&&(console.log("\u23F8\uFE0F Stopping Codespaces heartbeat"),clearInterval(zo),zo=null)}function OS(r){return Sh.default.join(r,".devcontainer","devcontainer.json")}function MS(r){try{let e=OS(r);if(!Fn.default.existsSync(e))return{enabled:!1,exists:!1};let t=JSON.parse(Fn.default.readFileSync(e,"utf8"));return{enabled:t.postAttachCommand==="9remote start"||t.postAttachCommand==="9remote",exists:!0}}catch{return{enabled:!1,exists:!1,error:"Failed to read config"}}}function PS(r,e){try{let t=Sh.default.join(r,".devcontainer"),n=OS(r);Fn.default.existsSync(t)||Fn.default.mkdirSync(t,{recursive:!0});let i={...gB};if(Fn.default.existsSync(n))try{i={...JSON.parse(Fn.default.readFileSync(n,"utf8"))}}catch{}return e?(i.postAttachCommand="9remote start",i.postCreateCommand||(i.postCreateCommand="npm install -g 9remote@latest")):delete i.postAttachCommand,Fn.default.writeFileSync(n,JSON.stringify(i,null,2)),{success:!0,enabled:e}}catch(t){return{success:!1,error:t.message}}}var Ll=K(require("os"),1),Re=K(require("fs"),1),Un=K(require("path"),1);vt();var Ts=ie.BUFFERS,Dl=Un.default.join(ie.STATE,"sessions.json"),Bl=Un.default.join(ie.STATE,"terminalGroups.json"),jl="/tmp/9remote-uploads";Re.default.existsSync(jl)||Re.default.mkdirSync(jl,{recursive:!0});function Eh(){return process.platform==="win32"?process.env.COMSPEC||"powershell.exe":process.env.SHELL||"/bin/zsh"}function Th(r){return r?"/workspaces":Ll.default.homedir()}function Ch(){let r=Ll.default.homedir(),e=Ll.default.userInfo().username,t=Eh(),n={...process.env};if(delete n.PORT,Object.assign(n,{HOME:r,USER:e,LOGNAME:e,SHELL:t,TERM:"xterm-256color",COLORTERM:"truecolor",LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8",LC_CTYPE:"en_US.UTF-8",PWD:r,OLDPWD:r,TMPDIR:n.TMPDIR||(process.platform==="win32"?n.TEMP||n.TMP:"/tmp"),__CF_USER_TEXT_ENCODING:n.__CF_USER_TEXT_ENCODING,XPC_FLAGS:n.XPC_FLAGS,XPC_SERVICE_NAME:n.XPC_SERVICE_NAME,SSH_AUTH_SOCK:n.SSH_AUTH_SOCK,TERM_PROGRAM:"9Remote",TERM_PROGRAM_VERSION:"1.0.0",ITERM_SESSION_ID:`9remote-${Date.now()}`,SHLVL:"1"}),t.includes("bash")){let i=n.PROMPT_COMMAND||"";n.PROMPT_COMMAND=`printf "\\e]7;file://%s\\a" "\${HOSTNAME}\${PWD}"${i?`; ${i}`:""}`}return n}function IS(){Re.default.existsSync(Ts)||Re.default.mkdirSync(Ts,{recursive:!0})}function Ah(r,e,t){if(t==="buffer"){IS();try{Re.default.writeFileSync(Un.default.join(Ts,`${r}.buf`),e.join(""),"utf8")}catch(n){console.log(`\u26A0\uFE0F Failed to save buffer for ${r}:`,n.message)}}}function NS(r,e){if(e!=="buffer")return null;let t=Un.default.join(Ts,`${r}.buf`);try{if(Re.default.existsSync(t))return Re.default.readFileSync(t,"utf8")}catch(n){console.log(`\u26A0\uFE0F Failed to load buffer for ${r}:`,n.message)}return null}function Fl(r){let e=Un.default.join(Ts,`${r}.buf`);try{Re.default.existsSync(e)&&Re.default.unlinkSync(e)}catch{}}function LS(){IS();try{return Re.default.readdirSync(Ts).filter(r=>r.endsWith(".buf")).map(r=>r.replace(".buf",""))}catch{return[]}}function Rh(){try{if(Re.default.existsSync(Dl))return JSON.parse(Re.default.readFileSync(Dl,"utf8"))}catch(r){console.log("\u26A0\uFE0F Failed to load session metadata:",r.message)}return{}}function mn(r){try{let e={};for(let[n,i]of r)e[n]={name:i.name,createdAt:i.createdAt,shellId:i.shellId,cwd:i.cwd};let t=Un.default.dirname(Dl);Re.default.existsSync(t)||Re.default.mkdirSync(t,{recursive:!0}),Re.default.writeFileSync(Dl,JSON.stringify(e,null,2),"utf8")}catch(e){console.log("\u26A0\uFE0F Failed to save session metadata:",e.message)}}function DS(){try{if(Re.default.existsSync(Bl)){let r=JSON.parse(Re.default.readFileSync(Bl,"utf8"));return{groups:r.groups||[],sessionGroups:r.sessionGroups||{}}}}catch(r){console.log("\u26A0\uFE0F Failed to load groups:",r.message)}return{groups:[],sessionGroups:{}}}function BS(r,e){try{let t=Un.default.dirname(Bl);Re.default.existsSync(t)||Re.default.mkdirSync(t,{recursive:!0});let n={groups:Array.from(r.values()),sessionGroups:e};Re.default.writeFileSync(Bl,JSON.stringify(n,null,2),"utf8")}catch(t){console.log("\u26A0\uFE0F Failed to save groups:",t.message)}}var kh=K(require("node-pty"),1);ui();var jS=2*1024*1024,xB=256*1024,hi="daemon";function FS(r,e,t,n,i){let s=null;r.onData(o=>{t.buffer.push(o),t.buffer.reduce((c,l)=>c+l.length,0)>jS&&(t.buffer=[t.buffer.join("").slice(-jS)]),bt(n,"output",{sessionId:e,data:Buffer.from(o,"utf-8")}),hi==="buffer"&&(s&&clearTimeout(s),s=setTimeout(()=>Ah(e,t.buffer,hi),2e3))}),r.onExit(({exitCode:o})=>{console.log(`PTY exited: sessionId=${e}, code=${o}`),hi==="buffer"&&t.buffer.length>0&&Ah(e,t.buffer,hi),i.delete(e),Fl(e),bt(n,"sessionClosed",e)})}function US(r,e,t,n,i){let s=()=>BS(n,i);r.on("getSessions",o=>{let a=[];for(let[c,l]of t)a.push({id:c,name:l.name,createdAt:l.createdAt,restored:l.restored||!1,shellId:l.shellId,shellLabel:l.shellLabel,groupId:i[c]||null});o(a)}),r.on("getShells",o=>{o({platform:process.platform,shells:Pw()})}),r.on("getGroups",o=>{o(Array.from(n.values()))}),r.on("createGroup",({name:o},a)=>{let c=`group-${Date.now()}`,l={id:c,name:o||"Group",createdAt:Date.now()};n.set(c,l),s(),bt(e,"groupsChanged"),a({success:!0,group:l})}),r.on("renameGroup",({groupId:o,name:a},c)=>{let l=n.get(o);if(!l)return c({success:!1,error:"Group not found"});l.name=a,s(),bt(e,"groupsChanged"),c({success:!0})}),r.on("deleteGroup",async({groupId:o},a)=>{if(!n.delete(o))return a({success:!1,error:"Group not found"});let c=Object.keys(i).filter(l=>i[l]===o);for(let l of c){let p=t.get(l);if(p){if(p.daemon&&Tr())try{await pi(l)}catch{}else p.pty&&(p.pty.kill(),Fl(l));t.delete(l),bt(e,"sessionClosed",l)}delete i[l]}s(),bt(e,"groupsChanged"),a({success:!0})}),r.on("moveSession",({sessionId:o,groupId:a},c)=>{a&&n.has(a)?i[o]=a:delete i[o],s(),bt(e,"groupsChanged"),c({success:!0})}),r.on("createSession",async({name:o,shellId:a,groupId:c},l)=>{let p=`session-${Date.now()}`,f=Iw(a),h=Ch();h.NINE_REMOTE_SESSION_ID=p;let v=Th(hn());try{let x=o||`${f.label} ${t.size+1}`;if(hi==="daemon"&&Tr()){let k=await fh(x,80,24,a,p,v);k.success?(t.set(k.sessionId,{daemon:!0,name:x,createdAt:Date.now(),cwd:k.cwd,shellId:k.shellId,shellLabel:k.shellLabel}),c&&n.has(c)&&(i[k.sessionId]=c,s()),mn(t),l({success:!0,sessionId:k.sessionId,shellLabel:k.shellLabel})):l({success:!1,error:k.error});return}let S=kh.default.spawn(f.path,f.args,{name:"xterm-256color",cols:80,rows:24,cwd:v,env:h,useConpty:!1}),A={pty:S,name:x,createdAt:Date.now(),buffer:[],cwd:v,shellId:f.id,shellLabel:f.label};FS(S,p,A,e,t),t.set(p,A),c&&n.has(c)&&(i[p]=c,s()),l({success:!0,sessionId:p,shellLabel:f.label})}catch(x){console.error("Failed to create session:",x),l({success:!1,error:x.message})}}),r.on("joinSession",async(o,a)=>{let c=t.get(o);if(!c)return a({success:!1,error:"Session not found"});if(c.daemon&&Tr()){try{if(c.needsRespawn){let p=await fh(c.name,80,24,c.shellId,o,c.cwd);if(!p.success)return a({success:!1,error:p.error});delete c.needsRespawn,c.cwd=p.cwd,c.shellLabel=p.shellLabel,mn(t)}let l=await Hw(o);l.cwd&&l.cwd!==c.cwd&&(c.cwd=l.cwd,mn(t)),a({success:l.success,name:c.name,cwd:l.cwd||c.cwd,error:l.error})}catch(l){a({success:!1,error:l.message})}return}if(c.needsRestore&&hi==="buffer")try{let l=Eh(),p=process.platform==="win32"?[]:["-l"],f=Th(hn()),h=kh.default.spawn(l,p,{name:"xterm-256color",cols:80,rows:24,cwd:f,env:Ch(),useConpty:!1});c.pty=h,c.needsRestore=!1,c.cwd=f;let v=NS(o,hi);v&&(c.buffer=[v]),FS(h,o,c,e,t),console.log(`\u2705 Restored PTY session: ${o}`)}catch(l){return console.error("Failed to restore session:",l),a({success:!1,error:"Failed to restore session"})}c.buffer?.length>0&&r.emit("output",{sessionId:o,data:Buffer.from(c.buffer.join("").slice(-xB),"utf-8")}),a({success:!0,name:c.name,cwd:c.cwd})}),r.on("deleteSession",async(o,a)=>{let c=t.get(o);if(!c)return a({success:!1,error:"Session not found"});if(c.daemon&&Tr()){try{await pi(o),t.delete(o),i[o]&&(delete i[o],s()),mn(t),a({success:!0})}catch(l){a({success:!1,error:l.message})}return}c.pty&&c.pty.kill(),t.delete(o),i[o]&&(delete i[o],s()),Fl(o),bt(e,"sessionClosed",o),mn(t),a({success:!0})}),r.on("renameSession",async({sessionId:o,name:a},c)=>{let l=t.get(o);if(!l)return c({success:!1,error:"Session not found"});l.name=a,bt(e,"session-renamed",{sessionId:o,name:a}),mn(t),c({success:!0})})}var qS=K(require("fs"),1),HS=K(require("path"),1);function $S(r,e){r.on("input",({sessionId:t,data:n})=>{if(!t)return;let i=e.get(t);if(i){if(i.daemon&&Tr())return dh(t,n);i.pty&&i.pty.write(Buffer.isBuffer(n)?n.toString("utf-8"):n)}}),r.on("resize",({sessionId:t,cols:n,rows:i})=>{if(!t)return;let s=e.get(t);if(s){if(s.daemon&&Tr())return $w(t,n,i);if(s.pty)try{s.pty.resize(n,i)}catch(o){console.log(`Resize failed for ${t}: ${o.message}`)}}}),r.on("upload-file",({sessionId:t,filename:n,size:i,content:s})=>{if(!t)return;let o=e.get(t);if(o)try{let a=n.replace(/[^a-zA-Z0-9._-]/g,"_"),c=HS.default.join(jl,`${Date.now()}_${a}`);qS.default.writeFileSync(c,Buffer.from(s,"base64")),console.log(`\u{1F4CE} File uploaded: ${c} (${i} bytes)`),o.daemon&&Tr()?dh(t,c):o.pty&&o.pty.write(c)}catch(a){console.error("File upload error:",a),r.emit("output",{sessionId:t,data:Buffer.from(`\r
115
115
  Error uploading file: ${a.message}\r
116
- `,"utf-8")})}})}var Rr=K(require("fs"),1),ta=K(require("path"),1),uu=K(oT(),1);vt();pn();var pu=ta.default.join(ie.CONFIG,"vapid.json"),fu=ta.default.join(ie.CONFIG,"push-subscriptions.json"),GW=1800*1e3,wt=[];function SF(){try{if(Rr.default.existsSync(pu))return JSON.parse(Rr.default.readFileSync(pu,"utf8"))}catch{}return null}function EF(r){let e=ta.default.dirname(pu);Rr.default.existsSync(e)||Rr.default.mkdirSync(e,{recursive:!0}),Rr.default.writeFileSync(pu,JSON.stringify(r,null,2),"utf8")}function TF(){let r=SF();if(!r){let e=uu.default.generateVAPIDKeys();r={publicKey:e.publicKey,privateKey:e.privateKey},EF(r)}return uu.default.setVapidDetails("mailto:admin@9remote.cc",r.publicKey,r.privateKey),r}function CF(){try{Rr.default.existsSync(fu)&&(wt=JSON.parse(Rr.default.readFileSync(fu,"utf8")))}catch{wt=[]}}function ra(){try{let r=ta.default.dirname(fu);Rr.default.existsSync(r)||Rr.default.mkdirSync(r,{recursive:!0}),Rr.default.writeFileSync(fu,JSON.stringify(wt,null,2),"utf8")}catch(r){ve(`Failed to save push subscriptions: ${r.message}`)}}function yi(r){return r.type==="expo"?r.token:r.endpoint}function aT(r,e){let t=yi(r),n=wt.find(i=>yi(i)===t);wt=wt.filter(i=>yi(i)!==t),wt.push({...r,socketId:e,lastConnectedAt:Date.now(),hidden:n?.hidden??!1}),ra()}function cT(r,e){for(let t of wt)t.socketId===r&&(t.hidden=!!e,e||(t.disconnectedAt=null))}function lT(){let r=wt.reduce((e,t)=>(e?.lastConnectedAt??0)>=(t?.lastConnectedAt??0)?e:t,null);return r?r.disconnectedAt!=null||!!r.hidden:!1}function uT(r){wt=wt.filter(e=>yi(e)!==r),ra()}function pT(r){for(let e of wt)e.socketId===r&&(e.disconnectedAt=Date.now());ra()}function fT(r,e){for(let t of wt)yi(t)===e&&(t.socketId=r,t.disconnectedAt=null,t.lastConnectedAt=Date.now());ra()}async function AF(r,e,t){let n={to:r.token,sound:"default",title:t.type==="stop"?`${e} \u2705`:`${e} \u{1F514}`,body:t.type==="stop"?`${e} completed the task`:`${e} needs your input`,data:{url:`/workspace?t=${t.sessionId}`,sessionId:t.sessionId,type:t.type}},s=await(await fetch("https://exp.host/--/api/v2/push/send",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(n)})).json();if(s.data?.status==="error")throw new Error(s.data.message);ve(`Expo push sent to ${r.token.slice(0,30)}...`)}async function dT(r){let e=yv[r.tool]||"AI",t=wt.reduce((i,s)=>(i?.lastConnectedAt??0)>=(s?.lastConnectedAt??0)?i:s,null);if(!t)return;let n=yi(t);try{if(t.type==="expo")await AF(t,e,r);else{let i=JSON.stringify({title:r.type==="stop"?`${e} \u2705`:`${e} \u{1F514}`,body:r.type==="stop"?`${e} completed the task`:`${e} needs your input`,data:{url:`/workspace?t=${r.sessionId}`,sessionId:r.sessionId,type:r.type}});await uu.default.sendNotification({endpoint:t.endpoint,keys:t.keys},i),ve(`WebPush sent to ${t.endpoint.slice(0,50)}...`)}}catch(i){ve(`Push failed: ${i.statusCode||i.message}`),(i.statusCode===410||i.statusCode===404||i.message?.includes("DeviceNotRegistered"))&&(wt=wt.filter(o=>yi(o)!==n),ra())}}var RF=TF();CF();function hT(){return RF.publicKey}var dm={};function mT(r,e){dm[r]=e}function du(r){delete dm[r]}function gT(){return{...dm}}hs();function vT(r){r.on("getNotificationState",()=>{r.emit("notificationState",gT())}),r.on("requestUpdate",()=>Dn("update")),r.on("clearNotification",e=>{e&&(du(e),r.broadcast.emit("notificationCleared",e))}),r.on("getVapidKey",e=>e(hT())),r.on("pushSubscribe",e=>{let t=e?.type==="expo"?e.token:e?.endpoint;t&&(fT(r.id,t),aT(e,r.id))}),r.on("pushUnsubscribe",e=>{e&&uT(e)}),r.on("visibilityChange",e=>cT(r.id,e)),r.on("getAutoStartStatus",e=>{if(!hn())return e({success:!1,error:"Not in Codespaces"});let t=process.env.CODESPACE_VSCODE_FOLDER||process.cwd();e({success:!0,...MS(t)})}),r.on("setAutoStart",({enabled:e},t)=>{if(!hn())return t({success:!1,error:"Not in Codespaces"});let n=process.env.CODESPACE_VSCODE_FOLDER||process.cwd();t(PS(n,e))})}var Wr=K(require("os"),1),ht=K(require("fs"),1),Ft=K(require("path"),1);vt();var xT=`http://localhost:${Da}/api/notify`,_T="nineRemoteNotify",kF=Ft.default.join(ie.STATE,"claudeEnvBackup.json"),vn={claude:()=>Ft.default.join(Wr.default.homedir(),".claude","settings.json"),codex:()=>Ft.default.join(Wr.default.homedir(),".codex","config.toml"),gemini:()=>Ft.default.join(Wr.default.homedir(),".gemini","settings.json"),opencode:()=>Ft.default.join(Wr.default.homedir(),".config","opencode","plugin",`${_T}.js`)},OF={claude:()=>Ft.default.join(Wr.default.homedir(),".claude"),codex:()=>Ft.default.join(Wr.default.homedir(),".codex"),gemini:()=>Ft.default.join(Wr.default.homedir(),".gemini"),opencode:()=>[Ft.default.join(Wr.default.homedir(),".config","opencode"),Ft.default.join(Wr.default.homedir(),".opencode")]},na=(r,e)=>`command -v curl >/dev/null 2>&1 && curl -s --connect-timeout 1 --max-time 2 "${xT}?type=${r}&sessionId=$NINE_REMOTE_SESSION_ID&tool=${e}" > /dev/null 2>&1 & true`;function ia(r){try{if(ht.default.existsSync(r))return JSON.parse(ht.default.readFileSync(r,"utf8"))}catch{}return{}}function hu(r,e){let t=Ft.default.dirname(r);ht.default.existsSync(t)||ht.default.mkdirSync(t,{recursive:!0}),ht.default.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function bT(r){let e={},t=r.env||{};for(let n of Object.keys(io))e[n]=t[n]??null;hu(kF,e),r.env={...t,...io}}function MF(){let r=vn.claude(),e=ia(r),t=na("stop","claude"),n=na("notification","claude");return e.hooks={...e.hooks||{},Stop:[{matcher:"",hooks:[{type:"command",command:t}]}],Notification:[{matcher:"permission_prompt|idle_prompt",hooks:[{type:"command",command:n}]}]},bT(e),hu(r,e),{success:!0}}var PF=/# 9Remote notification\nnotify\s*=.*\n?/g,IF="# 9Remote-saved: ";function NF(r){let e=r.search(/^\[/m);return e===-1?[r,""]:[r.slice(0,e),r.slice(e)]}var yT=/^notify\s*=\s*(\[[^\n]*\])\s*$/m;function LF(){let r=vn.codex(),e=Ft.default.dirname(r);ht.default.existsSync(e)||ht.default.mkdirSync(e,{recursive:!0});let t=ht.default.existsSync(r)?ht.default.readFileSync(r,"utf8"):"";t=t.replace(PF,"");let[n,i]=NF(t),s="",o=n.match(yT);if(o){try{let l=JSON.parse(o[1]);Array.isArray(l)&&l.length&&(s=` ; exec ${l.map(p=>`'${String(p).replace(/'/g,"'\\''")}'`).join(" ")} "$@"`)}catch{}n=n.replace(yT,`${IF}$&`)}let a=`${na("stop","codex")}${s}`,c=`# 9Remote notification
116
+ `,"utf-8")})}})}var Rr=K(require("fs"),1),ta=K(require("path"),1),uu=K(oT(),1);vt();pn();var pu=ta.default.join(ie.CONFIG,"vapid.json"),fu=ta.default.join(ie.CONFIG,"push-subscriptions.json"),WW=1800*1e3,wt=[];function SF(){try{if(Rr.default.existsSync(pu))return JSON.parse(Rr.default.readFileSync(pu,"utf8"))}catch{}return null}function EF(r){let e=ta.default.dirname(pu);Rr.default.existsSync(e)||Rr.default.mkdirSync(e,{recursive:!0}),Rr.default.writeFileSync(pu,JSON.stringify(r,null,2),"utf8")}function TF(){let r=SF();if(!r){let e=uu.default.generateVAPIDKeys();r={publicKey:e.publicKey,privateKey:e.privateKey},EF(r)}return uu.default.setVapidDetails("mailto:admin@9remote.cc",r.publicKey,r.privateKey),r}function CF(){try{Rr.default.existsSync(fu)&&(wt=JSON.parse(Rr.default.readFileSync(fu,"utf8")))}catch{wt=[]}}function ra(){try{let r=ta.default.dirname(fu);Rr.default.existsSync(r)||Rr.default.mkdirSync(r,{recursive:!0}),Rr.default.writeFileSync(fu,JSON.stringify(wt,null,2),"utf8")}catch(r){ve(`Failed to save push subscriptions: ${r.message}`)}}function yi(r){return r.type==="expo"?r.token:r.endpoint}function aT(r,e){let t=yi(r),n=wt.find(i=>yi(i)===t);wt=wt.filter(i=>yi(i)!==t),wt.push({...r,socketId:e,lastConnectedAt:Date.now(),hidden:n?.hidden??!1}),ra()}function cT(r,e){for(let t of wt)t.socketId===r&&(t.hidden=!!e,e||(t.disconnectedAt=null))}function lT(){let r=wt.reduce((e,t)=>(e?.lastConnectedAt??0)>=(t?.lastConnectedAt??0)?e:t,null);return r?r.disconnectedAt!=null||!!r.hidden:!1}function uT(r){wt=wt.filter(e=>yi(e)!==r),ra()}function pT(r){for(let e of wt)e.socketId===r&&(e.disconnectedAt=Date.now());ra()}function fT(r,e){for(let t of wt)yi(t)===e&&(t.socketId=r,t.disconnectedAt=null,t.lastConnectedAt=Date.now());ra()}async function AF(r,e,t){let n={to:r.token,sound:"default",title:t.type==="stop"?`${e} \u2705`:`${e} \u{1F514}`,body:t.type==="stop"?`${e} completed the task`:`${e} needs your input`,data:{url:`/workspace?t=${t.sessionId}`,sessionId:t.sessionId,type:t.type}},s=await(await fetch("https://exp.host/--/api/v2/push/send",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(n)})).json();if(s.data?.status==="error")throw new Error(s.data.message);ve(`Expo push sent to ${r.token.slice(0,30)}...`)}async function dT(r){let e=yv[r.tool]||"AI",t=wt.reduce((i,s)=>(i?.lastConnectedAt??0)>=(s?.lastConnectedAt??0)?i:s,null);if(!t)return;let n=yi(t);try{if(t.type==="expo")await AF(t,e,r);else{let i=JSON.stringify({title:r.type==="stop"?`${e} \u2705`:`${e} \u{1F514}`,body:r.type==="stop"?`${e} completed the task`:`${e} needs your input`,data:{url:`/workspace?t=${r.sessionId}`,sessionId:r.sessionId,type:r.type}});await uu.default.sendNotification({endpoint:t.endpoint,keys:t.keys},i),ve(`WebPush sent to ${t.endpoint.slice(0,50)}...`)}}catch(i){ve(`Push failed: ${i.statusCode||i.message}`),(i.statusCode===410||i.statusCode===404||i.message?.includes("DeviceNotRegistered"))&&(wt=wt.filter(o=>yi(o)!==n),ra())}}var RF=TF();CF();function hT(){return RF.publicKey}var dm={};function mT(r,e){dm[r]=e}function du(r){delete dm[r]}function gT(){return{...dm}}hs();function vT(r){r.on("getNotificationState",()=>{r.emit("notificationState",gT())}),r.on("requestUpdate",()=>Dn("update")),r.on("clearNotification",e=>{e&&(du(e),r.broadcast.emit("notificationCleared",e))}),r.on("getVapidKey",e=>e(hT())),r.on("pushSubscribe",e=>{let t=e?.type==="expo"?e.token:e?.endpoint;t&&(fT(r.id,t),aT(e,r.id))}),r.on("pushUnsubscribe",e=>{e&&uT(e)}),r.on("visibilityChange",e=>cT(r.id,e)),r.on("getAutoStartStatus",e=>{if(!hn())return e({success:!1,error:"Not in Codespaces"});let t=process.env.CODESPACE_VSCODE_FOLDER||process.cwd();e({success:!0,...MS(t)})}),r.on("setAutoStart",({enabled:e},t)=>{if(!hn())return t({success:!1,error:"Not in Codespaces"});let n=process.env.CODESPACE_VSCODE_FOLDER||process.cwd();t(PS(n,e))})}var Wr=K(require("os"),1),ht=K(require("fs"),1),Ft=K(require("path"),1);vt();var xT=`http://localhost:${Da}/api/notify`,_T="nineRemoteNotify",kF=Ft.default.join(ie.STATE,"claudeEnvBackup.json"),vn={claude:()=>Ft.default.join(Wr.default.homedir(),".claude","settings.json"),codex:()=>Ft.default.join(Wr.default.homedir(),".codex","config.toml"),gemini:()=>Ft.default.join(Wr.default.homedir(),".gemini","settings.json"),opencode:()=>Ft.default.join(Wr.default.homedir(),".config","opencode","plugin",`${_T}.js`)},OF={claude:()=>Ft.default.join(Wr.default.homedir(),".claude"),codex:()=>Ft.default.join(Wr.default.homedir(),".codex"),gemini:()=>Ft.default.join(Wr.default.homedir(),".gemini"),opencode:()=>[Ft.default.join(Wr.default.homedir(),".config","opencode"),Ft.default.join(Wr.default.homedir(),".opencode")]},na=(r,e)=>`command -v curl >/dev/null 2>&1 && curl -s --connect-timeout 1 --max-time 2 "${xT}?type=${r}&sessionId=$NINE_REMOTE_SESSION_ID&tool=${e}" > /dev/null 2>&1 & true`;function ia(r){try{if(ht.default.existsSync(r))return JSON.parse(ht.default.readFileSync(r,"utf8"))}catch{}return{}}function hu(r,e){let t=Ft.default.dirname(r);ht.default.existsSync(t)||ht.default.mkdirSync(t,{recursive:!0}),ht.default.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function bT(r){let e={},t=r.env||{};for(let n of Object.keys(io))e[n]=t[n]??null;hu(kF,e),r.env={...t,...io}}function MF(){let r=vn.claude(),e=ia(r),t=na("stop","claude"),n=na("notification","claude");return e.hooks={...e.hooks||{},Stop:[{matcher:"",hooks:[{type:"command",command:t}]}],Notification:[{matcher:"permission_prompt|idle_prompt",hooks:[{type:"command",command:n}]}]},bT(e),hu(r,e),{success:!0}}var PF=/# 9Remote notification\nnotify\s*=.*\n?/g,IF="# 9Remote-saved: ";function NF(r){let e=r.search(/^\[/m);return e===-1?[r,""]:[r.slice(0,e),r.slice(e)]}var yT=/^notify\s*=\s*(\[[^\n]*\])\s*$/m;function LF(){let r=vn.codex(),e=Ft.default.dirname(r);ht.default.existsSync(e)||ht.default.mkdirSync(e,{recursive:!0});let t=ht.default.existsSync(r)?ht.default.readFileSync(r,"utf8"):"";t=t.replace(PF,"");let[n,i]=NF(t),s="",o=n.match(yT);if(o){try{let l=JSON.parse(o[1]);Array.isArray(l)&&l.length&&(s=` ; exec ${l.map(p=>`'${String(p).replace(/'/g,"'\\''")}'`).join(" ")} "$@"`)}catch{}n=n.replace(yT,`${IF}$&`)}let a=`${na("stop","codex")}${s}`,c=`# 9Remote notification
117
117
  notify = ["bash", "-c", ${JSON.stringify(a)}, "9remote"]
118
118
  `;return n.length&&!n.endsWith(`
119
119
  `)&&(n+=`
@@ -131,7 +131,7 @@ export const ${_T} = async () => ({
131
131
  else if (event.type === "permission.asked") post("notification");
132
132
  },
133
133
  });
134
- `}function jF(){let r=vn.opencode(),e=Ft.default.dirname(r);return ht.default.existsSync(e)||ht.default.mkdirSync(e,{recursive:!0}),ht.default.writeFileSync(r,BF(),"utf8"),{success:!0}}function FF(r){switch(r){case"claude":{let e=ia(vn.claude());return!!(e.hooks?.Stop||e.hooks?.Notification)}case"codex":{let e=vn.codex();return ht.default.existsSync(e)&&ht.default.readFileSync(e,"utf8").includes("# 9Remote notification")}case"gemini":{let e=ia(vn.gemini());return!!(e.hooks?.AfterAgent||e.hooks?.Notification)}case"opencode":return ht.default.existsSync(vn.opencode());default:return!1}}function UF(r){let e=OF[r]?.();return e?(Array.isArray(e)?e:[e]).some(n=>ht.default.existsSync(n)):!1}var qF={claude:MF,codex:LF,gemini:DF,opencode:jF};var HF=vv;function $F(r){return qF[r]?.()||{success:!1,error:"Unknown tool"}}function wT(){let r={};for(let e of HF)if(!(!UF(e)||FF(e)))try{r[e]=$F(e).success}catch{r[e]=!1}return r}function ST(){let r=vn.claude(),e=ia(r);if(!e.hooks?.Stop&&!e.hooks?.Notification)return;let t=e.env||{};Object.keys(io).some(i=>t[i]!==io[i])&&(bT(e),hu(r,e))}ui();var gG=(0,TT.dirname)((0,CT.fileURLToPath)(__importMetaUrl)),vG=to.rgb(230,138,110),hm="daemon",WF="2.0.65",$n=new Map,AT=new Map,RT={};async function ET(){let r=await Al(),e=new Map(r.map(n=>[n.id,n])),t=Rh();for(let n of r)if(!t[n.id])try{await pi(n.id)}catch{}$n.clear();for(let[n,i]of Object.entries(t)){let s=e.get(n);$n.set(n,{daemon:!0,name:i.name,createdAt:i.createdAt,shellId:i.shellId,cwd:s?.cwd||i.cwd,needsRespawn:!s})}mn($n)}async function kT(){let r=DS();for(let n of r.groups)AT.set(n.id,n);Object.assign(RT,r.sessionGroups);try{ST()}catch{}try{wT()}catch{}if(hm==="daemon")if(!await qw())console.error("\u274C Failed to connect to PTY daemon, falling back to buffer mode");else{await ET(),Tl("connected",()=>{ET().catch(()=>{})});return}console.log("\u{1F4E6} Buffer persistence mode - scrollback enabled");let e=LS(),t=Rh();for(let n of e){let i=t[n]||{};$n.set(n,{pty:null,name:i.name||`Terminal ${$n.size+1}`,createdAt:i.createdAt||Date.now(),buffer:[],needsRestore:!0}),console.log(`\u{1F504} Found saved session: ${n}`)}e.length>0&&console.log(`\u2705 Found ${e.length} saved session(s)`)}function Fs(r,e){hm==="daemon"&&(Tl("output",({sessionId:i,data:s})=>bt(r,"output",{sessionId:i,data:s})),Tl("sessionClosed",i=>{$n.delete(i),du(i),bt(r,"sessionClosed",i),bt(r,"notificationCleared",i)}));let t=()=>({version:WF,remoteAvailable:xs(),daemonMode:hm==="daemon"&&Tr(),platform:process.platform,updateAvailable:aw(),canSelfUpdate:!0,...AS()}),n=()=>{let i=t();for(let s of r.sockets.sockets.values())s.data?.approved&&s.emit("serverInfo",i)};uw(n),Fs._buildServerInfo=t,Fs._emitServerInfo=n}function OT(){Fs._emitServerInfo?.()}var MT=null;function PT(r){MT=r}async function IT(r,e,t){RS(),MT?.(),r.emit("serverInfo",Fs._buildServerInfo?.()),US(r,e,$n,AT,RT),$S(r,$n),vT(r),Il()&&await CS(r,t).catch(n=>{console.error("\u274C Failed to setup remote handlers:",n.message)}),r.on("disconnect",()=>{pT(r.id),kS()})}var re=K(require("fs"),1),gr=K(require("path"),1),zr=K(require("os"),1),zs=require("child_process"),qA=K(PA(),1);var dg=["node_modules",".git","dist","build",".next","coverage","__pycache__",".cache",".vscode",".idea",".turbo",".vercel",".output","out",".nuxt",".svelte-kit","target","vendor",".gradle",".pytest_cache",".mypy_cache",".tox",".venv","venv","env",".DS_Store",".parcel-cache",".rollup.cache"],Nu=[".png",".jpg",".jpeg",".gif",".webp",".ico",".svg",".bmp",".pdf",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".dylib",".mp3",".mp4",".wav",".avi",".mov",".webm",".woff",".woff2",".ttf",".eot",".otf",".sqlite",".db"];var IA=[".ssh",".aws",".gnupg",".kube",".docker",".cargo",".npmrc",".netrc",".pypirc",".config/gh",".config/gcloud"],NA=["/etc/shadow","/etc/sudoers","/etc/ssh","/root","/private/etc/sudoers"];var LA=K(require("fs"),1),va=K(require("path"),1),DA=K(require("os"),1);var BA=DA.default.homedir();function oH(r){if(!r)return null;let e=r.startsWith("~")?r.replace(/^~/,BA):r;try{return LA.default.realpathSync(e)}catch{return va.default.resolve(e)}}function _n(r){let e=oH(r);if(!e)return!1;for(let t of NA)if(e===t||e.startsWith(t+va.default.sep))return!0;for(let t of IA){let n=va.default.join(BA,t);if(e===n||e.startsWith(n+va.default.sep))return!0}return!1}function Lu(r){return dg.includes(r)}function Vs(r){return Nu.includes(gr.default.extname(r).toLowerCase())}function cH(r,e){return r.isDirectory()?"folder":Vs(e)?"binary":"file"}function ya(r){return r<1024?`${r}B`:r<1024*1024?`${(r/1024).toFixed(1)}KB`:`${(r/(1024*1024)).toFixed(1)}MB`}function HA(r,e,t,n=50){if(!(t.length>=n))try{for(let i of re.default.readdirSync(r)){if(t.length>=n)return;if(i.startsWith(".")||Lu(i))continue;let s=gr.default.join(r,i);try{let o=re.default.statSync(s);o.isDirectory()?HA(s,e,t,n):i.toLowerCase().includes(e.toLowerCase())&&t.push({name:i,path:s,type:Vs(i)?"binary":"file",size:o.size,sizeFormatted:ya(o.size)})}catch{}}}catch{}}function UA(r){if(!r)return null;let e=r.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"::ANY::").replace(/\*/g,"[^/]*").replace(/::ANY::/g,".*").replace(/\?/g,".");return new RegExp(`^${e}$`)}function $A(r,e,t,n,i,s){if(s.length>=200)return;let o;try{o=re.default.readdirSync(r,{withFileTypes:!0})}catch{return}for(let a of o){if(s.length>=200)return;if(Lu(a.name))continue;let c=gr.default.join(r,a.name),l=gr.default.relative(e,c);if(a.isDirectory()){$A(c,e,t,n,i,s);continue}if(a.isFile()&&!Vs(a.name)&&!(i&&i.test(l))&&!(n&&!n.test(l)))try{if(re.default.statSync(c).size>512e3)continue;let h=re.default.readFileSync(c,"utf-8").split(`
134
+ `}function jF(){let r=vn.opencode(),e=Ft.default.dirname(r);return ht.default.existsSync(e)||ht.default.mkdirSync(e,{recursive:!0}),ht.default.writeFileSync(r,BF(),"utf8"),{success:!0}}function FF(r){switch(r){case"claude":{let e=ia(vn.claude());return!!(e.hooks?.Stop||e.hooks?.Notification)}case"codex":{let e=vn.codex();return ht.default.existsSync(e)&&ht.default.readFileSync(e,"utf8").includes("# 9Remote notification")}case"gemini":{let e=ia(vn.gemini());return!!(e.hooks?.AfterAgent||e.hooks?.Notification)}case"opencode":return ht.default.existsSync(vn.opencode());default:return!1}}function UF(r){let e=OF[r]?.();return e?(Array.isArray(e)?e:[e]).some(n=>ht.default.existsSync(n)):!1}var qF={claude:MF,codex:LF,gemini:DF,opencode:jF};var HF=vv;function $F(r){return qF[r]?.()||{success:!1,error:"Unknown tool"}}function wT(){let r={};for(let e of HF)if(!(!UF(e)||FF(e)))try{r[e]=$F(e).success}catch{r[e]=!1}return r}function ST(){let r=vn.claude(),e=ia(r);if(!e.hooks?.Stop&&!e.hooks?.Notification)return;let t=e.env||{};Object.keys(io).some(i=>t[i]!==io[i])&&(bT(e),hu(r,e))}ui();var mG=(0,TT.dirname)((0,CT.fileURLToPath)(__importMetaUrl)),gG=to.rgb(230,138,110),hm="daemon",WF="2.0.67",$n=new Map,AT=new Map,RT={};async function ET(){let r=await Al(),e=new Map(r.map(n=>[n.id,n])),t=Rh();for(let n of r)if(!t[n.id])try{await pi(n.id)}catch{}$n.clear();for(let[n,i]of Object.entries(t)){let s=e.get(n);$n.set(n,{daemon:!0,name:i.name,createdAt:i.createdAt,shellId:i.shellId,cwd:s?.cwd||i.cwd,needsRespawn:!s})}mn($n)}async function kT(){let r=DS();for(let n of r.groups)AT.set(n.id,n);Object.assign(RT,r.sessionGroups);try{ST()}catch{}try{wT()}catch{}if(hm==="daemon")if(!await qw())console.error("\u274C Failed to connect to PTY daemon, falling back to buffer mode");else{await ET(),Tl("connected",()=>{ET().catch(()=>{})});return}console.log("\u{1F4E6} Buffer persistence mode - scrollback enabled");let e=LS(),t=Rh();for(let n of e){let i=t[n]||{};$n.set(n,{pty:null,name:i.name||`Terminal ${$n.size+1}`,createdAt:i.createdAt||Date.now(),buffer:[],needsRestore:!0}),console.log(`\u{1F504} Found saved session: ${n}`)}e.length>0&&console.log(`\u2705 Found ${e.length} saved session(s)`)}function Fs(r,e){hm==="daemon"&&(Tl("output",({sessionId:i,data:s})=>bt(r,"output",{sessionId:i,data:s})),Tl("sessionClosed",i=>{$n.delete(i),du(i),bt(r,"sessionClosed",i),bt(r,"notificationCleared",i)}));let t=()=>({version:WF,remoteAvailable:xs(),daemonMode:hm==="daemon"&&Tr(),platform:process.platform,updateAvailable:aw(),canSelfUpdate:!0,...AS()}),n=()=>{let i=t();for(let s of r.sockets.sockets.values())s.data?.approved&&s.emit("serverInfo",i)};uw(n),Fs._buildServerInfo=t,Fs._emitServerInfo=n}function OT(){Fs._emitServerInfo?.()}var MT=null;function PT(r){MT=r}async function IT(r,e,t){RS(),MT?.(),r.emit("serverInfo",Fs._buildServerInfo?.()),US(r,e,$n,AT,RT),$S(r,$n),vT(r),Il()&&await CS(r,t).catch(n=>{console.error("\u274C Failed to setup remote handlers:",n.message)}),r.on("disconnect",()=>{pT(r.id),kS()})}var re=K(require("fs"),1),gr=K(require("path"),1),zr=K(require("os"),1),zs=require("child_process"),qA=K(PA(),1);var dg=["node_modules",".git","dist","build",".next","coverage","__pycache__",".cache",".vscode",".idea",".turbo",".vercel",".output","out",".nuxt",".svelte-kit","target","vendor",".gradle",".pytest_cache",".mypy_cache",".tox",".venv","venv","env",".DS_Store",".parcel-cache",".rollup.cache"],Nu=[".png",".jpg",".jpeg",".gif",".webp",".ico",".svg",".bmp",".pdf",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".dylib",".mp3",".mp4",".wav",".avi",".mov",".webm",".woff",".woff2",".ttf",".eot",".otf",".sqlite",".db"];var IA=[".ssh",".aws",".gnupg",".kube",".docker",".cargo",".npmrc",".netrc",".pypirc",".config/gh",".config/gcloud"],NA=["/etc/shadow","/etc/sudoers","/etc/ssh","/root","/private/etc/sudoers"];var LA=K(require("fs"),1),va=K(require("path"),1),DA=K(require("os"),1);var BA=DA.default.homedir();function oH(r){if(!r)return null;let e=r.startsWith("~")?r.replace(/^~/,BA):r;try{return LA.default.realpathSync(e)}catch{return va.default.resolve(e)}}function _n(r){let e=oH(r);if(!e)return!1;for(let t of NA)if(e===t||e.startsWith(t+va.default.sep))return!0;for(let t of IA){let n=va.default.join(BA,t);if(e===n||e.startsWith(n+va.default.sep))return!0}return!1}function Lu(r){return dg.includes(r)}function Vs(r){return Nu.includes(gr.default.extname(r).toLowerCase())}function cH(r,e){return r.isDirectory()?"folder":Vs(e)?"binary":"file"}function ya(r){return r<1024?`${r}B`:r<1024*1024?`${(r/1024).toFixed(1)}KB`:`${(r/(1024*1024)).toFixed(1)}MB`}function HA(r,e,t,n=50){if(!(t.length>=n))try{for(let i of re.default.readdirSync(r)){if(t.length>=n)return;if(i.startsWith(".")||Lu(i))continue;let s=gr.default.join(r,i);try{let o=re.default.statSync(s);o.isDirectory()?HA(s,e,t,n):i.toLowerCase().includes(e.toLowerCase())&&t.push({name:i,path:s,type:Vs(i)?"binary":"file",size:o.size,sizeFormatted:ya(o.size)})}catch{}}}catch{}}function UA(r){if(!r)return null;let e=r.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"::ANY::").replace(/\*/g,"[^/]*").replace(/::ANY::/g,".*").replace(/\?/g,".");return new RegExp(`^${e}$`)}function $A(r,e,t,n,i,s){if(s.length>=200)return;let o;try{o=re.default.readdirSync(r,{withFileTypes:!0})}catch{return}for(let a of o){if(s.length>=200)return;if(Lu(a.name))continue;let c=gr.default.join(r,a.name),l=gr.default.relative(e,c);if(a.isDirectory()){$A(c,e,t,n,i,s);continue}if(a.isFile()&&!Vs(a.name)&&!(i&&i.test(l))&&!(n&&!n.test(l)))try{if(re.default.statSync(c).size>512e3)continue;let h=re.default.readFileSync(c,"utf-8").split(`
135
135
  `),v=[];for(let x=0;x<h.length&&v.length<10;x++){let S=h[x],A=t(S);for(let k of A){if(v.length>=10)break;v.push({line:x+1,column:k.column+1,lineText:S,matchLength:k.length})}}v.length&&s.push({path:c,matches:v})}catch{}}}function WA(r,e,t){let n;try{n=re.default.readdirSync(r,{withFileTypes:!0})}catch{return[]}let i=[];for(let s of n){if(!t&&s.name.startsWith(".")&&s.name!==".env"&&s.name!==".env.example"||Lu(s.name))continue;let o=gr.default.join(r,s.name);if(s.isDirectory()){let a={name:s.name,path:o,type:"folder"};e>0&&(a.children=WA(o,e-1,t)),i.push(a)}else s.isFile()&&i.push({name:s.name,path:o,type:Vs(s.name)?"binary":"file"})}return i.sort((s,o)=>s.type==="folder"&&o.type!=="folder"?-1:s.type!=="folder"&&o.type==="folder"?1:s.name.localeCompare(o.name)),i}function lH(){if(process.platform!=="win32")return[];try{return(0,zs.execSync)("wmic logicaldisk get name",{encoding:"utf-8",stdio:["pipe","pipe","pipe"],windowsHide:!0}).split(/\r?\n/).map(e=>e.trim()).filter(e=>/^[A-Z]:$/.test(e)).map(e=>({letter:e[0],path:e+"\\"}))}catch{return"CDEFGHIJ".split("").map(r=>`${r}:\\`).filter(r=>re.default.existsSync(r)).map(r=>({letter:r[0],path:r}))}}function GA(r){r.on("getSystemInfo",t=>{let n=process.platform;t({success:!0,platform:n,isWindows:n==="win32",drives:n==="win32"?lH():[],homedir:zr.default.homedir()})}),r.on("getFiles",({dirPath:t,showHidden:n},i)=>{try{let s=t||zr.default.homedir(),o=s.startsWith("~")?s.replace("~",zr.default.homedir()):s;if(_n(o))return i({success:!1,error:"Access denied"});if(!re.default.existsSync(o))return i({success:!1,error:"Directory not found"});let a=[];for(let c of re.default.readdirSync(o))if(!(!n&&c.startsWith(".")&&c!==".env"&&c!==".env.example")&&!Lu(c))try{let l=gr.default.join(o,c),p=re.default.statSync(l);a.push({name:c,path:l,type:cH(p,c),size:p.isFile()?p.size:null,sizeFormatted:p.isFile()?ya(p.size):null,modified:p.mtime.getTime()})}catch{}a.sort((c,l)=>c.type==="folder"&&l.type!=="folder"?-1:c.type!=="folder"&&l.type==="folder"?1:c.name.localeCompare(l.name)),i({success:!0,files:a,currentPath:o,parentPath:gr.default.dirname(o)})}catch(s){i({success:!1,error:s.message})}}),r.on("searchFiles",({workspace:t,query:n},i)=>{try{if(!n||n.length<2)return i({success:!0,files:[]});let s=(t||zr.default.homedir()).replace(/^~/,zr.default.homedir());if(!re.default.existsSync(s))return i({success:!1,error:"Workspace not found"});let o=[];HA(s,n,o,50),o.sort((a,c)=>{let l=a.name.toLowerCase()===n.toLowerCase(),p=c.name.toLowerCase()===n.toLowerCase();return l&&!p?-1:!l&&p?1:a.path.length-c.path.length}),i({success:!0,files:o})}catch(s){i({success:!1,error:s.message})}}),r.on("readFile",({filePath:t},n)=>{try{if(_n(t))return n({success:!1,error:"Access denied"});if(!re.default.existsSync(t))return n({success:!1,error:"File not found"});let i=re.default.statSync(t);if(i.size>512e3)return n({success:!1,error:`File too large (${ya(i.size)}). Max ${ya(512e3)}`});if(Vs(t))return n({success:!1,error:"Cannot open binary file"});n({success:!0,content:re.default.readFileSync(t,"utf-8")})}catch(i){n({success:!1,error:i.message})}}),r.on("readImage",({filePath:t},n)=>{try{if(_n(t))return n({success:!1,error:"Access denied"});if(!re.default.existsSync(t))return n({success:!1,error:"File not found"});let i=re.default.statSync(t),s=10*1024*1024;if(i.size>s)return n({success:!1,error:`Image too large (${ya(i.size)})`});let o=gr.default.extname(t).toLowerCase().slice(1),c={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",bmp:"image/bmp"}[o]||"application/octet-stream",l=re.default.readFileSync(t),p=`data:${c};base64,${l.toString("base64")}`;n({success:!0,dataUrl:p,size:i.size,mime:c})}catch(i){n({success:!1,error:i.message})}}),r.on("writeFile",({filePath:t,content:n},i)=>{try{if(_n(t))return i({success:!1,error:"Access denied"});re.default.writeFileSync(t,n,"utf-8"),i({success:!0})}catch(s){i({success:!1,error:s.message})}}),r.on("createItem",({itemPath:t,type:n},i)=>{try{if(_n(t))return i({success:!1,error:"Access denied"});if(re.default.existsSync(t))return i({success:!1,error:"Item already exists"});n==="folder"?re.default.mkdirSync(t,{recursive:!0}):re.default.writeFileSync(t,"","utf-8"),i({success:!0})}catch(s){i({success:!1,error:s.message})}}),r.on("deleteItem",({itemPath:t},n)=>{try{if(_n(t))return n({success:!1,error:"Access denied"});if(!re.default.existsSync(t))return n({success:!1,error:"Item not found"});re.default.statSync(t).isDirectory()?re.default.rmSync(t,{recursive:!0}):re.default.unlinkSync(t),n({success:!0})}catch(i){n({success:!1,error:i.message})}}),r.on("renameItem",({oldPath:t,newPath:n},i)=>{try{if(_n(t)||_n(n))return i({success:!1,error:"Access denied"});if(!re.default.existsSync(t))return i({success:!1,error:"Item not found"});if(re.default.existsSync(n))return i({success:!1,error:"Target already exists"});re.default.renameSync(t,n),i({success:!0})}catch(s){i({success:!1,error:s.message})}}),r.on("searchInFiles",({workspace:t,query:n,caseSensitive:i,regex:s,includeGlob:o,excludeGlob:a},c)=>{try{if(!n)return c({success:!0,results:[]});let l=(t||zr.default.homedir()).replace(/^~/,zr.default.homedir());if(!re.default.existsSync(l))return c({success:!1,error:"Workspace not found"});let p;if(s){let x;try{x=new RegExp(n,i?"g":"gi")}catch(S){return c({success:!1,error:`Invalid regex: ${S.message}`})}p=S=>{let A=[],k;for(x.lastIndex=0;(k=x.exec(S))!==null;)A.push({column:k.index,length:k[0].length}),k.index===x.lastIndex&&x.lastIndex++;return A}}else{let x=i?n:n.toLowerCase();p=S=>{let A=i?S:S.toLowerCase(),k=[],P=0;for(;(P=A.indexOf(x,P))!==-1;)k.push({column:P,length:x.length}),P+=x.length||1;return k}}let f=UA(o),h=UA(a),v=[];$A(l,l,p,f,h,v),c({success:!0,results:v})}catch(l){c({success:!1,error:l.message})}}),r.on("replaceInFiles",({workspace:t,query:n,replacement:i,caseSensitive:s,regex:o,files:a},c)=>{try{if(!n||!Array.isArray(a)||!a.length)return c({success:!0,replacedCount:0,fileCount:0});let l;if(o){let h;try{h=new RegExp(n,s?"g":"gi")}catch(v){return c({success:!1,error:`Invalid regex: ${v.message}`})}l=v=>{let x=0;return{next:v.replace(h,A=>(x++,i)),count:x}}}else l=h=>{let v=0,x=s?"g":"gi",S=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),A=new RegExp(S,x);return{next:h.replace(A,()=>(v++,i)),count:v}};let p=0,f=0;for(let h of a)try{if(!re.default.existsSync(h)||Vs(h))continue;let v=re.default.statSync(h);if(!v.isFile()||v.size>512e3)continue;let x=re.default.readFileSync(h,"utf-8"),{next:S,count:A}=l(x);A>0&&(re.default.writeFileSync(h,S,"utf-8"),p+=A,f++)}catch{}c({success:!0,replacedCount:p,fileCount:f})}catch(l){c({success:!1,error:l.message})}});let e=new Map;r.on("watchDir",({dirPath:t},n)=>{try{if(!t||!re.default.existsSync(t))return n({success:!1,error:"Directory not found"});let i=e.get(t);if(i)return i.count++,n({success:!0});let s=qA.default.watch(t,{depth:0,ignoreInitial:!0,persistent:!0,ignored:a=>dg.includes(gr.default.basename(a))}),o=a=>c=>r.emit("fileChange",{type:a,path:c});s.on("add",o("add")).on("change",o("change")).on("unlink",o("unlink")).on("addDir",o("addDir")).on("unlinkDir",o("unlinkDir")),e.set(t,{w:s,count:1}),n({success:!0})}catch(i){n({success:!1,error:i.message})}}),r.on("unwatchDir",({dirPath:t},n)=>{try{let i=e.get(t);i&&--i.count<=0&&(i.w.close(),e.delete(t)),n({success:!0})}catch(i){n({success:!1,error:i.message})}}),r.once("disconnect",()=>{for(let{w:t}of e.values())try{t.close()}catch{}e.clear()}),r.on("revealInOS",({filePath:t},n)=>{try{if(!t)return n({success:!1,error:"No path"});let i=process.platform,s,o;i==="darwin"?(s="open",o=["-R",t]):i==="win32"?(s="explorer",o=[`/select,${t}`]):(s="xdg-open",o=[gr.default.dirname(t)]);let a=(0,zs.spawn)(s,o,{detached:!0,stdio:"ignore",windowsHide:!0});a.on("error",c=>n({success:!1,error:c.message})),a.unref(),n({success:!0})}catch(i){n({success:!1,error:i.message})}}),r.on("openInTerminal",({dirPath:t},n)=>{try{if(!t||!re.default.existsSync(t))return n({success:!1,error:"Directory not found"});let i=process.platform,s,o,a={detached:!0,stdio:"ignore",windowsHide:!0};i==="darwin"?(s="open",o=["-a","Terminal",t]):i==="win32"?(s="cmd",o=["/C","start","cmd","/K",`cd /d "${t}"`],a.shell=!1):(s="gnome-terminal",o=[`--working-directory=${t}`]);let c=(0,zs.spawn)(s,o,a);c.on("error",()=>{if(i==="linux"){let l=(0,zs.spawn)("xterm",["-e",`cd "${t}" && bash`],a);l.on("error",p=>n({success:!1,error:p.message})),l.unref()}else n({success:!1,error:"Failed to open terminal"})}),c.unref(),n({success:!0})}catch(i){n({success:!1,error:i.message})}}),r.on("getFileTree",({dirPath:t,depth:n,showHidden:i},s)=>{try{let o=(t||zr.default.homedir()).replace(/^~/,zr.default.homedir());if(!re.default.existsSync(o))return s({success:!1,error:"Directory not found"});let c=WA(o,typeof n=="number"?n:3,!!i);s({success:!0,tree:{name:gr.default.basename(o)||o,path:o,type:"folder",children:c}})}catch(o){s({success:!1,error:o.message})}})}var qt=K(require("fs"),1),Si=K(require("path"),1),vr=require("child_process");function wi(r,e){return new Promise(t=>{let n=(0,vr.spawn)("git",r,{cwd:e,windowsHide:!0}),i="",s="";n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.on("error",o=>t({code:-1,stdout:i,stderr:o.message})),n.on("close",o=>t({code:o,stdout:i,stderr:s}))})}function zA(r){return Nu.includes(Si.default.extname(r).toLowerCase())}function VA(r){r.on("gitStatus",({repoPath:e},t)=>{try{let n=(0,vr.execSync)("git status --porcelain",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"],windowsHide:!0}),i={};try{(0,vr.execSync)("git diff HEAD --numstat",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"],windowsHide:!0}).trim().split(`
136
136
  `).filter(Boolean).forEach(a=>{let c=a.split(" ");c.length>=3&&(i[c[2]]={added:c[0]==="-"?0:parseInt(c[0],10)||0,deleted:c[1]==="-"?0:parseInt(c[1],10)||0})})}catch{}let s=[];for(let o of n.trim().split(`
137
137
  `).filter(Boolean)){let a=o.match(/^([MADRCU?! ]{1,2})\s+(.+)$/);if(!a)continue;let c=a[1],l=a[2];if(!l)continue;let p;c.includes("?")?p="?":c.includes("A")?p="A":c.includes("D")?p="D":c.includes("M")?p="M":c.includes("R")?p="R":p=c.trim()[0]||"?";let f=i[l]||{added:0,deleted:0};if(p==="?")try{let h=Si.default.join(e,l);if(qt.default.existsSync(h)&&!zA(l)){let v=qt.default.readFileSync(h,"utf-8");f.added=v.split(`
@@ -262,7 +262,7 @@ self.addEventListener('fetch', (event) => {
262
262
  </body>
263
263
  </html>
264
264
  `);return}e._proxyTargetPort=n,e.url=i+(s||""),r.web(e,t,{target:`http://localhost:${n}`,changeOrigin:!0},o=>{t.writeHead(502),t.end(`Bad Gateway: ${o.message}`)})}var ok=K(require("http"),1),ak=K(require("https"),1),ck=require("child_process"),lk=require("util"),VH=(0,lk.promisify)(ck.exec);async function KH(){let r=process.platform,e=new Set([80,443]);try{let t;if(r==="win32")t="netstat -ano | findstr LISTENING";else{let s="/dev/null";t=`lsof -iTCP -sTCP:LISTEN -P -n 2>${s} || netstat -tlnp 2>${s}`}let{stdout:n}=await VH(t),i=n.split(`
265
- `);for(let s of i){let o=s.match(/[:\*\]](\d{2,5})(?:\s|$)/g);if(o)for(let a of o){let c=parseInt(a.replace(/[:\*\]\s]/g,""),10);c>0&&c<=65535&&(c===80||c===443||c>=1024)&&e.add(c)}}return Array.from(e)}catch(t){return console.error("Failed to get listening ports:",t.message),[80,443,3e3,3001,4200,5e3,5173,8e3,8080,9e3]}}function YH(r,e=2e3){return new Promise(t=>{let n=ok.default.request({host:"localhost",port:r,method:"GET",path:"/",timeout:e},i=>{i.on("data",()=>{}),i.on("end",()=>{}),t({active:!0,protocol:"http",status:i.statusCode})});n.on("error",i=>{t({active:!1,error:i.message})}),n.on("timeout",()=>{n.destroy(),t({active:!1,error:"timeout"})}),n.end()})}function JH(r,e=2e3){return new Promise(t=>{let n=ak.default.request({host:"localhost",port:r,method:"GET",path:"/",timeout:e,rejectUnauthorized:!1},i=>{i.on("data",()=>{}),i.on("end",()=>{}),t({active:!0,protocol:"https",status:i.statusCode})});n.on("error",i=>{t({active:!1,error:i.message})}),n.on("timeout",()=>{n.destroy(),t({active:!1,error:"timeout"})}),n.end()})}async function XH(r){let[e,t]=await Promise.all([YH(r),JH(r)]);return t.active?{port:r,...t}:e.active?{port:r,...e}:{port:r,active:!1}}async function uk(){let r=await KH();return(await Promise.all(r.map(t=>XH(t)))).filter(t=>t.active).map(t=>({port:t.port,protocol:t.protocol,url:`${t.protocol}://localhost:${t.port}`,name:`localhost:${t.port}`,status:t.status})).sort((t,n)=>t.port-n.port)}var pk=K(require("crypto"),1),ZH=process.env.API_KEY_SECRET||"9remote-api-key-secret";function QH(){let r="abcdefghijklmnopqrstuvwxyz0123456789",e="";for(let t=0;t<4;t++)e+=r.charAt(Math.floor(Math.random()*r.length));return e}function fk(r,e){return pk.default.createHmac("sha256",ZH).update(r+e).digest("hex").slice(0,6)}function dk(r){let e=r.slice(0,8),t=QH(),n=fk(e,t);return{key:`sk-${e}-${t}-${n}`,keyId:t}}function e$(r){if(!r||!r.startsWith("sk-"))return null;let e=r.split("-");if(e.length===4){let[,t,n,i]=e,s=fk(t,n);return i!==s?null:{machineId:t,keyId:n}}return null}function Gu(r){return e$(r)!==null}async function hk(r,e){let t=r.headers.authorization;if(!t||!t.startsWith("Bearer ")){e.setHeader("Content-Type","application/json"),e.writeHead(401),e.end(JSON.stringify({error:"Unauthorized: Missing API key"}));return}let n=t.slice(7);if(!Gu(n)){e.setHeader("Content-Type","application/json"),e.writeHead(401),e.end(JSON.stringify({error:"Unauthorized: Invalid API key"}));return}let i=await uk();e.setHeader("Content-Type","application/json"),e.writeHead(200),e.end(JSON.stringify(i))}nl();var vk=require("url");var zu=K(require("path"),1),yk=K(require("os"),1);vt();var mk=K(require("path"),1),gk=K(require("os"),1);var Wz=mk.default.join(gk.default.homedir(),".9remote","pids");Kd();var ka={checkIntervalMs:36e5,connectCheckDebounceMs:9e5,maxRetry:3,retryDelayMs:3e3,verifyTimeoutMs:15e3,lockTtlMs:3e5,lockFile:"update.lock"};var Vz={orange:to.rgb(230,138,110),orangeDim:to.rgb(200,120,95)};var tV=zu.default.dirname((0,vk.fileURLToPath)(__importMetaUrl));var rV=zu.default.join(yk.default.homedir(),".9remote","cloudflared.pid");function xk(r,e){let t=r.split(".").map(Number),n=e.split(".").map(Number);for(let i=0;i<3;i++){if(n[i]>t[i])return!0;if(n[i]<t[i])return!1}return!1}var nV=zu.default.join(ie.STATE,ka.lockFile);pn();Pt();vt();hs();var bk=K(_k(),1),Lg=K(require("crypto"),1),{machineIdSync:t$}=bk.default;async function wk(r=null){let e=r||process.env.MACHINE_ID_SALT||"9remote-salt";try{let t=t$();return Lg.default.createHash("sha256").update(t+e).digest("hex").substring(0,16)}catch(t){return console.error("Error getting machine ID:",t),Lg.default.randomUUID().replace(/-/g,"").substring(0,16)}}pn();async function Sk(r,e){let t=sw(),n=t.workerUrl||"https://9remote.cc";if(!t.permanentKey){ce(e,400,"No permanent key set");return}try{let s=await(await so(`${n}/api/temp-key/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.permanentKey,expiryMinutes:30})})).json(),o=`${n}/login?k=${s.tempKey}`;un({oneTimeKey:s.tempKey,oneTimeKeyExpiresAt:s.expiresAt,qrUrl:o}),X(e,{oneTimeKey:s.tempKey,expiresAt:s.expiresAt,qrUrl:o})}catch(i){ce(e,500,i.message)}}async function Ek(r,e){try{let t=await wk(),{key:n}=dk(t),i=Ub();qb(t,n,i?.name||"Default"),un({permanentKey:n}),X(e,{ok:!0,permanentKey:n})}catch(t){ce(e,500,t.message)}}Pt();async function Tk(r,e){let t=await Mt(r,e);if(!t)return;let n=hR(t.socketId);X(e,{ok:n})}async function Ck(r,e){let t=await Mt(r,e);if(!t)return;let n=gR(t.socketId);X(e,{ok:n})}function Ak(r,e){X(e,{pending:sR()})}function Rk(r,e){X(e,{devices:rR()})}function kk(r,e){X(e,{rejected:lR()})}async function Ok(r,e){let t=await Mt(r,e);if(!t)return;let n=mR(t.deviceId);X(e,{ok:n})}async function Mk(r,e){let t=await Mt(r,e);t&&(Uu(t.deviceId),Js(t.deviceId),X(e))}async function Pk(r,e){let t=await Mt(r,e);t&&(Uu(t.deviceId),eR(t.deviceId),X(e))}async function Ik(r,e){let t=await Mt(r,e);if(!t)return;let n=Uu(t.deviceId);X(e,{disconnected:n})}function Nk(r,e){X(e,{enabled:Fu()})}async function Lk(r,e){let t=await Mt(r,e);if(!t)return;let n=tR(t.deviceId,t.label);X(e,{ok:n})}async function Dk(r,e){let t=await Mt(r,e);if(!t)return;let n=pR(!!t.enabled);X(e,{enabled:n})}Pt();ui();var Bk={},r$=1e4;function jk(r,e){if(e)return{type:e.type||"stop",sessionId:e.sessionId||"",tool:e.tool||"claude"};let t=JSON.parse(r||"{}");return{type:t.type||"stop",sessionId:t.sessionId||"",tool:t.tool||"claude"}}async function Fk(r,e){let t="";await new Promise(n=>{r.on("data",i=>t+=i),r.on("end",n)});try{qk(jk(t,null)),X(e,{success:!0})}catch{ce(e,400,"Invalid JSON")}}function Uk(r,e,{query:t}){qk(jk(null,t)),X(e,{success:!0})}function qk({type:r,sessionId:e,tool:t}){let n=Date.now(),i=ba();if(!i||!e)return;let s={type:r,sessionId:e,tool:t,timestamp:n};if(mT(e,s),bt(i,"chatNotification",s),!lT())return;let o=`${e}:${r}`;n-(Bk[o]||0)<r$||(Bk[o]=n,dT(s))}Pt();hl();hs();ot();pn();function Hk(){return{mode:eh(),active:Qd(),presets:Object.keys($.sleepInhibit?.presets||{})}}function $k(r,e){X(e,Hk())}async function Wk(r,e){let t=await Mt(r,e);if(!t)return;let n=$o(t.mode);Fb({sleepInhibitMode:n});let i=Hk();_t("sleepInhibit",i),X(e,i)}Pt();async function Gk(r,e){try{let t=await Al();X(e,{sessions:t})}catch(t){ce(e,500,t.message)}}async function zk(r,e){let t=await Mt(r,e);if(t){if(!t.sessionId)return ce(e,400,"sessionId required");try{await pi(t.sessionId),X(e)}catch(n){ce(e,500,n.message)}}}var Sn=K(require("os"),1);ot();Pt();function n$(){let r=xS();if(!r?.activeClients)return{total:0,streaming:0};let e=0;for(let t of r.activeClients.values())t.isStreaming&&e++;return{total:r.activeClients.size,streaming:e}}function i$(){let r=process.memoryUsage(),e=Sn.default.cpus();return{agent:{pid:process.pid,version:"2.0.65",nodeVersion:process.version,platform:`${process.platform}/${process.arch}`,uptimeSec:Math.round(process.uptime()),memory:{heapUsedMB:Math.round(r.heapUsed/1048576*10)/10,heapTotalMB:Math.round(r.heapTotal/1048576*10)/10,rssMB:Math.round(r.rss/1048576*10)/10,externalMB:Math.round(r.external/1048576*10)/10}},os:{hostname:Sn.default.hostname(),platform:Sn.default.platform(),arch:Sn.default.arch(),uptimeSec:Math.round(Sn.default.uptime()),loadAvg:Sn.default.loadavg(),cpuModel:e?.[0]?.model||"unknown",cpuCount:e.length,totalMemMB:Math.round(Sn.default.totalmem()/1048576),freeMemMB:Math.round(Sn.default.freemem()/1048576)},remote:{available:Il(),...n$(),memoryWarningThresholdMB:$.resourceManagement.memoryWarningThreshold},timestamp:Date.now()}}function Vk(r,e){try{X(e,i$())}catch(t){ce(e,500,"stats error",t.message)}}hl();hs();ot();bv();var Wn=Tn("server"),Gn=(0,Xk.fileURLToPath)(new URL(".",__importMetaUrl)),Zk=process.env.NODE_ENV==="development",s$=5173,Dg=(0,Ri.existsSync)((0,Zt.join)(Gn,"ui","dist"))?(0,Zt.join)(Gn,"ui","dist"):(0,Zt.join)(Gn,"ui"),o$={".html":"text/html",".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff"};function a$(r,e,t){let n=(0,Vu.request)({hostname:"localhost",port:s$,path:r.url,method:r.method,headers:r.headers},i=>{e.writeHead(i.statusCode,i.headers),i.pipe(e)});n.on("error",()=>t?t():void(e.writeHead(502),e.end("Vite dev server not ready"))),r.pipe(n)}function Kk(r,e){if(!(0,Ri.existsSync)(e))return!1;let t=o$[(0,Zt.extname)(e)]||"application/octet-stream";return r.setHeader("Content-Type",t),r.writeHead(200),r.end((0,Ri.readFileSync)(e)),!0}async function Bg(r){try{let e=await so(_p);if(!e.ok)return;let{version:t}=await e.json();t&&xk(r,t)&&(cw({version:t}),_t("updateAvailable",{version:t}),OT())}catch{}}var Yk=0;function c$(r){let e=Date.now();e-Yk<ka.connectCheckDebounceMs||(Yk=e,Bg(r))}function l$(r,e){if(process.env.CODESPACES!=="true"){ce(e,400,"Not running on Codespaces");return}let t=process.env.CODESPACE_NAME;if(!t){ce(e,400,"Codespace name not found");return}let n=ba();n&&n.emit("codespace:stopping"),X(e,{success:!0,message:"Stopping codespace..."}),setTimeout(()=>(0,Ku.execFile)("gh",["codespace","stop","-c",t],{windowsHide:!0}),500)}var Qk;async function Jk(r,e,{pathname:t}){let n=r.headers.authorization;if(!n||!n.startsWith("Bearer ")||!Gu(n.slice(7))){ce(e,401,"Unauthorized");return}let{parseJsonBody:i}=await Promise.resolve().then(()=>(Pt(),Mi)),s=await i(r,e);if(s){if(!s.port){ce(e,400,"Port required");return}t.endsWith("start")?rk(s.port):nk(s.port),X(e,{success:!0})}}function u$(r,e,{pathname:t,search:n}){let i=t.match(/^\/proxy\/(\d+)(\/.*)?$/);i?sk(Qk,r,e,i[1],i[2]||"/",n):ce(e,404,"Not found")}var p$=[{path:"/api/health",method:"GET",public:!0,handler:(r,e)=>X(e,{status:"ok",timestamp:Date.now()})},{path:"/api/version",method:"GET",public:!0,handler:(r,e)=>{X(e,{version:"2.0.65"})}},{path:"/api/notify",method:"POST",public:!0,handler:Fk},{path:"/api/notify",method:"GET",public:!0,handler:Uk},{path:"/proxy/*",method:"*",public:!0,handler:u$},{path:"/api/ui/events",method:"GET",handler:mw},{path:"/api/local-token",method:"GET",handler:pw},{path:"/api/ui/state",method:"GET",handler:gw},{path:"/api/ui/state",method:"POST",handler:vw},{path:"/api/ui/stop",method:"POST",handler:yw},{path:"/api/ui/start",method:"POST",handler:xw},{path:"/api/ui/stop-tunnel",method:"POST",handler:_w},{path:"/api/ui/shutdown",method:"POST",handler:bw},{path:"/api/update",method:"POST",handler:ww},{path:"/api/system/stats",method:"GET",handler:Vk},{path:"/api/key/one-time",method:"POST",handler:Sk},{path:"/api/key/regenerate",method:"POST",handler:Ek},{path:"/api/device/approve",method:"POST",handler:Tk},{path:"/api/device/reject",method:"POST",handler:Ck},{path:"/api/device/pending",method:"GET",handler:Ak},{path:"/api/device/approved",method:"GET",handler:Rk},{path:"/api/device/rejected",method:"GET",handler:kk},{path:"/api/device/approve-rejected",method:"POST",handler:Ok},{path:"/api/device/clear-rejected",method:"POST",handler:Mk},{path:"/api/device/remove",method:"POST",handler:Pk},{path:"/api/device/label",method:"POST",handler:Lk},{path:"/api/device/disconnect",method:"POST",handler:Ik},{path:"/api/device/auto-approve",method:"GET",handler:Nk},{path:"/api/device/auto-approve",method:"POST",handler:Dk},{path:"/api/connections",method:"GET",handler:Sw},{path:"/api/logs",method:"GET",handler:Ew},{path:"/api/permissions",method:"GET",handler:Cw},{path:"/api/permissions/request",method:"POST",handler:kw},{path:"/api/desktop/toggle",method:"POST",handler:Tw},{path:"/api/autostart",method:"GET",handler:Aw},{path:"/api/autostart",method:"POST",handler:Rw},{path:"/api/sleep-inhibit",method:"GET",handler:$k},{path:"/api/sleep-inhibit",method:"POST",handler:Wk},{path:"/api/sessions",method:"GET",handler:Gk},{path:"/api/sessions/delete",method:"POST",handler:zk},{path:"/api/local-sites",method:"*",public:!0,handler:hk},{path:"/api/codespace/stop",method:"POST",handler:l$},{path:"/api/proxy/start",method:"POST",public:!0,handler:Jk},{path:"/api/proxy/end",method:"POST",public:!0,handler:Jk}];var f$=parseInt(process.env.PORT||"2208",10),Ma=null;function d$(){if(!Zk)return;let r=(0,Zt.join)(Gn,"vite.config.js");if(!(0,Ri.existsSync)(r))return;let e=(0,Ri.existsSync)((0,Zt.join)(Gn,"node_modules",".bin","vite"))?(0,Zt.join)(Gn,"node_modules",".bin","vite"):(0,Zt.join)(Gn,"..","node_modules",".bin","vite");Ma=(0,Ku.spawn)("node",[e,"--config",r],{cwd:Gn,stdio:"ignore",detached:!1}),Ma.on("error",()=>{}),Ma.unref()}async function eO(){let r=Wd(),e=r.sleepInhibitMode;e||(r.sleepInhibit===!1?e="never":e=$.sleepInhibit?.defaultMode||"never"),$o(e),await kT(),Qk=ik(),d$();let n=yp(p$,{fallback:(a,c,{pathname:l})=>{if(l.startsWith("/api/")||l.startsWith("/socket.io")){ce(c,404,"Not found");return}let p=!!a.headers["cf-connecting-ip"],f=a.socket.remoteAddress==="127.0.0.1"||a.socket.remoteAddress==="::1";if(p||!f){ce(c,403,"Forbidden");return}let h=()=>{let v=l==="/"||l===""?(0,Zt.join)(Dg,"index.html"):(0,Zt.join)(Dg,l);Kk(c,v)||Kk(c,(0,Zt.join)(Dg,"index.html"))};if(Zk){a$(a,c,h);return}h()}}),i=(0,Vu.createServer)(async(a,c)=>{yR(c),!xR(a,c)&&await n(a,c)});Fd(),nw(),iw(),vl(),process.platform==="darwin"&&setInterval(vl,hv),await vR(i),i.listen(f$,a=>{if(a)throw a;let c="2.0.65";Bg(c),setInterval(()=>Bg(c),ka.checkIntervalMs),PT(()=>c$(c))});let s=!1,o=async a=>{if(s)return;s=!0,Zd(),Wn.info(`\u{1F6D1} Received ${a}, shutting down gracefully...`);let c=setTimeout(()=>{Wn.error("\u26A0\uFE0F Forced exit"),process.exit(1)},5e3);try{if(i.close(()=>Wn.info("\u2713 HTTP server closed")),Ma)try{Ma.kill()}catch{}let l=ba();l&&(l.emit("server:shutdown"),l.close(()=>Wn.info("\u2713 Socket.IO closed"))),await new Promise(p=>setTimeout(p,500)),clearTimeout(c),Wn.info("\u2705 Server stopped cleanly"),process.exit(0)}catch(l){Wn.error(`\u274C Error during shutdown: ${l?.message||l}`),clearTimeout(c),process.exit(1)}};return process.on("SIGINT",()=>o("SIGINT")),process.on("SIGTERM",()=>o("SIGTERM")),process.platform==="win32"&&process.on("SIGBREAK",()=>o("SIGBREAK")),process.on("uncaughtException",a=>{Wn.error(`\u26A0\uFE0F uncaughtException: ${a?.stack||a}`)}),process.on("unhandledRejection",a=>{Wn.error(`\u26A0\uFE0F unhandledRejection: ${a?.stack||a}`)}),i}eO();0&&(module.exports={startServer});
265
+ `);for(let s of i){let o=s.match(/[:\*\]](\d{2,5})(?:\s|$)/g);if(o)for(let a of o){let c=parseInt(a.replace(/[:\*\]\s]/g,""),10);c>0&&c<=65535&&(c===80||c===443||c>=1024)&&e.add(c)}}return Array.from(e)}catch(t){return console.error("Failed to get listening ports:",t.message),[80,443,3e3,3001,4200,5e3,5173,8e3,8080,9e3]}}function YH(r,e=2e3){return new Promise(t=>{let n=ok.default.request({host:"localhost",port:r,method:"GET",path:"/",timeout:e},i=>{i.on("data",()=>{}),i.on("end",()=>{}),t({active:!0,protocol:"http",status:i.statusCode})});n.on("error",i=>{t({active:!1,error:i.message})}),n.on("timeout",()=>{n.destroy(),t({active:!1,error:"timeout"})}),n.end()})}function JH(r,e=2e3){return new Promise(t=>{let n=ak.default.request({host:"localhost",port:r,method:"GET",path:"/",timeout:e,rejectUnauthorized:!1},i=>{i.on("data",()=>{}),i.on("end",()=>{}),t({active:!0,protocol:"https",status:i.statusCode})});n.on("error",i=>{t({active:!1,error:i.message})}),n.on("timeout",()=>{n.destroy(),t({active:!1,error:"timeout"})}),n.end()})}async function XH(r){let[e,t]=await Promise.all([YH(r),JH(r)]);return t.active?{port:r,...t}:e.active?{port:r,...e}:{port:r,active:!1}}async function uk(){let r=await KH();return(await Promise.all(r.map(t=>XH(t)))).filter(t=>t.active).map(t=>({port:t.port,protocol:t.protocol,url:`${t.protocol}://localhost:${t.port}`,name:`localhost:${t.port}`,status:t.status})).sort((t,n)=>t.port-n.port)}var pk=K(require("crypto"),1),ZH=process.env.API_KEY_SECRET||"9remote-api-key-secret";function QH(){let r="abcdefghijklmnopqrstuvwxyz0123456789",e="";for(let t=0;t<4;t++)e+=r.charAt(Math.floor(Math.random()*r.length));return e}function fk(r,e){return pk.default.createHmac("sha256",ZH).update(r+e).digest("hex").slice(0,6)}function dk(r){let e=r.slice(0,8),t=QH(),n=fk(e,t);return{key:`sk-${e}-${t}-${n}`,keyId:t}}function e$(r){if(!r||!r.startsWith("sk-"))return null;let e=r.split("-");if(e.length===4){let[,t,n,i]=e,s=fk(t,n);return i!==s?null:{machineId:t,keyId:n}}return null}function Gu(r){return e$(r)!==null}async function hk(r,e){let t=r.headers.authorization;if(!t||!t.startsWith("Bearer ")){e.setHeader("Content-Type","application/json"),e.writeHead(401),e.end(JSON.stringify({error:"Unauthorized: Missing API key"}));return}let n=t.slice(7);if(!Gu(n)){e.setHeader("Content-Type","application/json"),e.writeHead(401),e.end(JSON.stringify({error:"Unauthorized: Invalid API key"}));return}let i=await uk();e.setHeader("Content-Type","application/json"),e.writeHead(200),e.end(JSON.stringify(i))}nl();var vk=require("url");var zu=K(require("path"),1),yk=K(require("os"),1);vt();var mk=K(require("path"),1),gk=K(require("os"),1);var $z=mk.default.join(gk.default.homedir(),".9remote","pids");Kd();var ka={checkIntervalMs:36e5,connectCheckDebounceMs:9e5,maxRetry:3,retryDelayMs:3e3,verifyTimeoutMs:15e3,lockTtlMs:3e5,lockFile:"update.lock"};var zz={orange:to.rgb(230,138,110),orangeDim:to.rgb(200,120,95)};var eV=zu.default.dirname((0,vk.fileURLToPath)(__importMetaUrl));var tV=zu.default.join(yk.default.homedir(),".9remote","cloudflared.pid");function xk(r,e){let t=r.split(".").map(Number),n=e.split(".").map(Number);for(let i=0;i<3;i++){if(n[i]>t[i])return!0;if(n[i]<t[i])return!1}return!1}var rV=zu.default.join(ie.STATE,ka.lockFile);pn();Pt();vt();hs();var bk=K(_k(),1),Lg=K(require("crypto"),1),{machineIdSync:t$}=bk.default;async function wk(r=null){let e=r||process.env.MACHINE_ID_SALT||"9remote-salt";try{let t=t$();return Lg.default.createHash("sha256").update(t+e).digest("hex").substring(0,16)}catch(t){return console.error("Error getting machine ID:",t),Lg.default.randomUUID().replace(/-/g,"").substring(0,16)}}pn();async function Sk(r,e){let t=sw(),n=t.workerUrl||"https://9remote.cc";if(!t.permanentKey){ce(e,400,"No permanent key set");return}try{let s=await(await so(`${n}/api/temp-key/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.permanentKey,expiryMinutes:30})})).json(),o=`${n}/login?k=${s.tempKey}`;un({oneTimeKey:s.tempKey,oneTimeKeyExpiresAt:s.expiresAt,qrUrl:o}),X(e,{oneTimeKey:s.tempKey,expiresAt:s.expiresAt,qrUrl:o})}catch(i){ce(e,500,i.message)}}async function Ek(r,e){try{let t=await wk(),{key:n}=dk(t),i=Ub();qb(t,n,i?.name||"Default"),un({permanentKey:n}),X(e,{ok:!0,permanentKey:n})}catch(t){ce(e,500,t.message)}}Pt();async function Tk(r,e){let t=await Mt(r,e);if(!t)return;let n=hR(t.socketId);X(e,{ok:n})}async function Ck(r,e){let t=await Mt(r,e);if(!t)return;let n=gR(t.socketId);X(e,{ok:n})}function Ak(r,e){X(e,{pending:sR()})}function Rk(r,e){X(e,{devices:rR()})}function kk(r,e){X(e,{rejected:lR()})}async function Ok(r,e){let t=await Mt(r,e);if(!t)return;let n=mR(t.deviceId);X(e,{ok:n})}async function Mk(r,e){let t=await Mt(r,e);t&&(Uu(t.deviceId),Js(t.deviceId),X(e))}async function Pk(r,e){let t=await Mt(r,e);t&&(Uu(t.deviceId),eR(t.deviceId),X(e))}async function Ik(r,e){let t=await Mt(r,e);if(!t)return;let n=Uu(t.deviceId);X(e,{disconnected:n})}function Nk(r,e){X(e,{enabled:Fu()})}async function Lk(r,e){let t=await Mt(r,e);if(!t)return;let n=tR(t.deviceId,t.label);X(e,{ok:n})}async function Dk(r,e){let t=await Mt(r,e);if(!t)return;let n=pR(!!t.enabled);X(e,{enabled:n})}Pt();ui();var Bk={},r$=1e4;function jk(r,e){if(e)return{type:e.type||"stop",sessionId:e.sessionId||"",tool:e.tool||"claude"};let t=JSON.parse(r||"{}");return{type:t.type||"stop",sessionId:t.sessionId||"",tool:t.tool||"claude"}}async function Fk(r,e){let t="";await new Promise(n=>{r.on("data",i=>t+=i),r.on("end",n)});try{qk(jk(t,null)),X(e,{success:!0})}catch{ce(e,400,"Invalid JSON")}}function Uk(r,e,{query:t}){qk(jk(null,t)),X(e,{success:!0})}function qk({type:r,sessionId:e,tool:t}){let n=Date.now(),i=ba();if(!i||!e)return;let s={type:r,sessionId:e,tool:t,timestamp:n};if(mT(e,s),bt(i,"chatNotification",s),!lT())return;let o=`${e}:${r}`;n-(Bk[o]||0)<r$||(Bk[o]=n,dT(s))}Pt();hl();hs();at();pn();function Hk(){return{mode:eh(),active:Qd(),presets:Object.keys($.sleepInhibit?.presets||{})}}function $k(r,e){X(e,Hk())}async function Wk(r,e){let t=await Mt(r,e);if(!t)return;let n=$o(t.mode);Fb({sleepInhibitMode:n});let i=Hk();_t("sleepInhibit",i),X(e,i)}Pt();async function Gk(r,e){try{let t=await Al();X(e,{sessions:t})}catch(t){ce(e,500,t.message)}}async function zk(r,e){let t=await Mt(r,e);if(t){if(!t.sessionId)return ce(e,400,"sessionId required");try{await pi(t.sessionId),X(e)}catch(n){ce(e,500,n.message)}}}var Sn=K(require("os"),1);at();Pt();function n$(){let r=xS();if(!r?.activeClients)return{total:0,streaming:0};let e=0;for(let t of r.activeClients.values())t.isStreaming&&e++;return{total:r.activeClients.size,streaming:e}}function i$(){let r=process.memoryUsage(),e=Sn.default.cpus();return{agent:{pid:process.pid,version:"2.0.67",nodeVersion:process.version,platform:`${process.platform}/${process.arch}`,uptimeSec:Math.round(process.uptime()),memory:{heapUsedMB:Math.round(r.heapUsed/1048576*10)/10,heapTotalMB:Math.round(r.heapTotal/1048576*10)/10,rssMB:Math.round(r.rss/1048576*10)/10,externalMB:Math.round(r.external/1048576*10)/10}},os:{hostname:Sn.default.hostname(),platform:Sn.default.platform(),arch:Sn.default.arch(),uptimeSec:Math.round(Sn.default.uptime()),loadAvg:Sn.default.loadavg(),cpuModel:e?.[0]?.model||"unknown",cpuCount:e.length,totalMemMB:Math.round(Sn.default.totalmem()/1048576),freeMemMB:Math.round(Sn.default.freemem()/1048576)},remote:{available:Il(),...n$(),memoryWarningThresholdMB:$.resourceManagement.memoryWarningThreshold},timestamp:Date.now()}}function Vk(r,e){try{X(e,i$())}catch(t){ce(e,500,"stats error",t.message)}}hl();hs();at();bv();var Wn=Tn("server"),Gn=(0,Xk.fileURLToPath)(new URL(".",__importMetaUrl)),Zk=process.env.NODE_ENV==="development",s$=5173,Dg=(0,Ri.existsSync)((0,Zt.join)(Gn,"ui","dist"))?(0,Zt.join)(Gn,"ui","dist"):(0,Zt.join)(Gn,"ui"),o$={".html":"text/html",".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff"};function a$(r,e,t){let n=(0,Vu.request)({hostname:"localhost",port:s$,path:r.url,method:r.method,headers:r.headers},i=>{e.writeHead(i.statusCode,i.headers),i.pipe(e)});n.on("error",()=>t?t():void(e.writeHead(502),e.end("Vite dev server not ready"))),r.pipe(n)}function Kk(r,e){if(!(0,Ri.existsSync)(e))return!1;let t=o$[(0,Zt.extname)(e)]||"application/octet-stream";return r.setHeader("Content-Type",t),r.writeHead(200),r.end((0,Ri.readFileSync)(e)),!0}async function Bg(r){try{let e=await so(_p);if(!e.ok)return;let{version:t}=await e.json();t&&xk(r,t)&&(cw({version:t}),_t("updateAvailable",{version:t}),OT())}catch{}}var Yk=0;function c$(r){let e=Date.now();e-Yk<ka.connectCheckDebounceMs||(Yk=e,Bg(r))}function l$(r,e){if(process.env.CODESPACES!=="true"){ce(e,400,"Not running on Codespaces");return}let t=process.env.CODESPACE_NAME;if(!t){ce(e,400,"Codespace name not found");return}let n=ba();n&&n.emit("codespace:stopping"),X(e,{success:!0,message:"Stopping codespace..."}),setTimeout(()=>(0,Ku.execFile)("gh",["codespace","stop","-c",t],{windowsHide:!0}),500)}var Qk;async function Jk(r,e,{pathname:t}){let n=r.headers.authorization;if(!n||!n.startsWith("Bearer ")||!Gu(n.slice(7))){ce(e,401,"Unauthorized");return}let{parseJsonBody:i}=await Promise.resolve().then(()=>(Pt(),Mi)),s=await i(r,e);if(s){if(!s.port){ce(e,400,"Port required");return}t.endsWith("start")?rk(s.port):nk(s.port),X(e,{success:!0})}}function u$(r,e,{pathname:t,search:n}){let i=t.match(/^\/proxy\/(\d+)(\/.*)?$/);i?sk(Qk,r,e,i[1],i[2]||"/",n):ce(e,404,"Not found")}var p$=[{path:"/api/health",method:"GET",public:!0,handler:(r,e)=>X(e,{status:"ok",timestamp:Date.now()})},{path:"/api/version",method:"GET",public:!0,handler:(r,e)=>{X(e,{version:"2.0.67"})}},{path:"/api/notify",method:"POST",public:!0,handler:Fk},{path:"/api/notify",method:"GET",public:!0,handler:Uk},{path:"/proxy/*",method:"*",public:!0,handler:u$},{path:"/api/ui/events",method:"GET",handler:mw},{path:"/api/local-token",method:"GET",handler:pw},{path:"/api/ui/state",method:"GET",handler:gw},{path:"/api/ui/state",method:"POST",handler:vw},{path:"/api/ui/stop",method:"POST",handler:yw},{path:"/api/ui/start",method:"POST",handler:xw},{path:"/api/ui/stop-tunnel",method:"POST",handler:_w},{path:"/api/ui/shutdown",method:"POST",handler:bw},{path:"/api/update",method:"POST",handler:ww},{path:"/api/system/stats",method:"GET",handler:Vk},{path:"/api/key/one-time",method:"POST",handler:Sk},{path:"/api/key/regenerate",method:"POST",handler:Ek},{path:"/api/device/approve",method:"POST",handler:Tk},{path:"/api/device/reject",method:"POST",handler:Ck},{path:"/api/device/pending",method:"GET",handler:Ak},{path:"/api/device/approved",method:"GET",handler:Rk},{path:"/api/device/rejected",method:"GET",handler:kk},{path:"/api/device/approve-rejected",method:"POST",handler:Ok},{path:"/api/device/clear-rejected",method:"POST",handler:Mk},{path:"/api/device/remove",method:"POST",handler:Pk},{path:"/api/device/label",method:"POST",handler:Lk},{path:"/api/device/disconnect",method:"POST",handler:Ik},{path:"/api/device/auto-approve",method:"GET",handler:Nk},{path:"/api/device/auto-approve",method:"POST",handler:Dk},{path:"/api/connections",method:"GET",handler:Sw},{path:"/api/logs",method:"GET",handler:Ew},{path:"/api/permissions",method:"GET",handler:Cw},{path:"/api/permissions/request",method:"POST",handler:kw},{path:"/api/desktop/toggle",method:"POST",handler:Tw},{path:"/api/autostart",method:"GET",handler:Aw},{path:"/api/autostart",method:"POST",handler:Rw},{path:"/api/sleep-inhibit",method:"GET",handler:$k},{path:"/api/sleep-inhibit",method:"POST",handler:Wk},{path:"/api/sessions",method:"GET",handler:Gk},{path:"/api/sessions/delete",method:"POST",handler:zk},{path:"/api/local-sites",method:"*",public:!0,handler:hk},{path:"/api/codespace/stop",method:"POST",handler:l$},{path:"/api/proxy/start",method:"POST",public:!0,handler:Jk},{path:"/api/proxy/end",method:"POST",public:!0,handler:Jk}];var f$=parseInt(process.env.PORT||"2208",10),Ma=null;function d$(){if(!Zk)return;let r=(0,Zt.join)(Gn,"vite.config.js");if(!(0,Ri.existsSync)(r))return;let e=(0,Ri.existsSync)((0,Zt.join)(Gn,"node_modules",".bin","vite"))?(0,Zt.join)(Gn,"node_modules",".bin","vite"):(0,Zt.join)(Gn,"..","node_modules",".bin","vite");Ma=(0,Ku.spawn)("node",[e,"--config",r],{cwd:Gn,stdio:"ignore",detached:!1}),Ma.on("error",()=>{}),Ma.unref()}async function eO(){let r=Wd(),e=r.sleepInhibitMode;e||(r.sleepInhibit===!1?e="never":e=$.sleepInhibit?.defaultMode||"never"),$o(e),await kT(),Qk=ik(),d$();let n=yp(p$,{fallback:(a,c,{pathname:l})=>{if(l.startsWith("/api/")||l.startsWith("/socket.io")){ce(c,404,"Not found");return}let p=!!a.headers["cf-connecting-ip"],f=a.socket.remoteAddress==="127.0.0.1"||a.socket.remoteAddress==="::1";if(p||!f){ce(c,403,"Forbidden");return}let h=()=>{let v=l==="/"||l===""?(0,Zt.join)(Dg,"index.html"):(0,Zt.join)(Dg,l);Kk(c,v)||Kk(c,(0,Zt.join)(Dg,"index.html"))};if(Zk){a$(a,c,h);return}h()}}),i=(0,Vu.createServer)(async(a,c)=>{yR(c),!xR(a,c)&&await n(a,c)});Fd(),nw(),iw(),vl(),process.platform==="darwin"&&setInterval(vl,hv),await vR(i),i.listen(f$,a=>{if(a)throw a;let c="2.0.67";Bg(c),setInterval(()=>Bg(c),ka.checkIntervalMs),PT(()=>c$(c))});let s=!1,o=async a=>{if(s)return;s=!0,Zd(),Wn.info(`\u{1F6D1} Received ${a}, shutting down gracefully...`);let c=setTimeout(()=>{Wn.error("\u26A0\uFE0F Forced exit"),process.exit(1)},5e3);try{if(i.close(()=>Wn.info("\u2713 HTTP server closed")),Ma)try{Ma.kill()}catch{}let l=ba();l&&(l.emit("server:shutdown"),l.close(()=>Wn.info("\u2713 Socket.IO closed"))),await new Promise(p=>setTimeout(p,500)),clearTimeout(c),Wn.info("\u2705 Server stopped cleanly"),process.exit(0)}catch(l){Wn.error(`\u274C Error during shutdown: ${l?.message||l}`),clearTimeout(c),process.exit(1)}};return process.on("SIGINT",()=>o("SIGINT")),process.on("SIGTERM",()=>o("SIGTERM")),process.platform==="win32"&&process.on("SIGBREAK",()=>o("SIGBREAK")),process.on("uncaughtException",a=>{Wn.error(`\u26A0\uFE0F uncaughtException: ${a?.stack||a}`)}),process.on("unhandledRejection",a=>{Wn.error(`\u26A0\uFE0F unhandledRejection: ${a?.stack||a}`)}),i}eO();0&&(module.exports={startServer});
266
266
  /*! Bundled license information:
267
267
 
268
268
  negotiator/index.js: