tempest.games 0.1.40 → 0.1.42
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/CHANGELOG.md +12 -0
- package/app/assets/{index-BvW-zGjV.js → index-1StuUZZV.js} +13 -13
- package/app/index.html +1 -1
- package/bin/backend.bun.js +8 -8
- package/package.json +3 -3
package/bin/backend.bun.js
CHANGED
|
@@ -30,7 +30,7 @@ var OG=Object.create;var{getPrototypeOf:_G,defineProperty:L1,getOwnPropertyNames
|
|
|
30
30
|
`+x),i.push(c+"m+"+d0.exports.humanize(this.diff)+"\x1B[0m")}else i[0]=cQ()+o+" "+i[0]}function cQ(){if(R5.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function xQ(...i){return process.stderr.write(t0.formatWithOptions(R5.inspectOpts,...i)+`
|
|
31
31
|
`)}function TQ(i){if(i)process.env.DEBUG=i;else delete process.env.DEBUG}function mQ(){return process.env.DEBUG}function fQ(i){i.inspectOpts={};let o=Object.keys(R5.inspectOpts);for(let n=0;n<o.length;n++)i.inspectOpts[o[n]]=R5.inspectOpts[o[n]]}d0.exports=N$()(R5);var{formatters:W5}=d0.exports;W5.o=function(i){return this.inspectOpts.colors=this.useColors,t0.inspect(i,this.inspectOpts).split(`
|
|
32
32
|
`).map((o)=>o.trim()).join(" ")};W5.O=function(i){return this.inspectOpts.colors=this.useColors,t0.inspect(i,this.inspectOpts)}});var Go=P((eni,j$)=>{if(typeof process==="undefined"||process.type==="renderer"||!1||process.__nwjs)j$.exports=$5();else j$.exports=G5()});var Rc=P((U5)=>{Object.defineProperty(U5,"__esModule",{value:!0});U5.Transport=void 0;var WQ=Hi("events"),RQ=kT(),YQ=x5(),GQ=Go(),K5=GQ.default("engine:transport");function KQ(){}class H5 extends WQ.EventEmitter{get readyState(){return this._readyState}set readyState(i){K5("readyState updated from %s to %s (%s)",this._readyState,i,this.name),this._readyState=i}constructor(i){super();this.writable=!1,this._readyState="open",this.discarded=!1,this.protocol=i._query.EIO==="4"?4:3,this.parser=this.protocol===4?RQ:YQ,this.supportsBinary=!(i._query&&i._query.b64)}discard(){this.discarded=!0}onRequest(i){}close(i){if(this.readyState==="closed"||this.readyState==="closing")return;this.readyState="closing",this.doClose(i||KQ)}onError(i,o){if(this.listeners("error").length){let n=new Error(i);n.type="TransportError",n.description=o,this.emit("error",n)}else K5("ignored transport error %s (%s)",i,o)}onPacket(i){this.emit("packet",i)}onData(i){this.onPacket(this.parser.decodePacket(i))}onClose(){this.readyState="closed",this.emit("close")}}U5.Transport=H5});var P$=P((u5)=>{Object.defineProperty(u5,"__esModule",{value:!0});u5.Polling=void 0;var HQ=Rc(),M5=Hi("zlib"),UQ=B0(),ZQ=Go(),Fn=ZQ.default("engine:polling"),MQ={gzip:M5.createGzip,deflate:M5.createDeflate};class z5 extends HQ.Transport{constructor(i){super(i);this.closeTimeout=30000}get name(){return"polling"}onRequest(i){let o=i.res;if(i.res=null,i.method==="GET")this.onPollRequest(i,o);else if(i.method==="POST")this.onDataRequest(i,o);else o.writeHead(500),o.end()}onPollRequest(i,o){if(this.req){Fn("request overlap"),this.onError("overlap from client"),o.writeHead(400),o.end();return}Fn("setting request"),this.req=i,this.res=o;let n=()=>{this.onError("poll connection closed prematurely")},p=()=>{i.removeListener("close",n),this.req=this.res=null};if(i.cleanup=p,i.on("close",n),this.writable=!0,this.emit("ready"),this.writable&&this.shouldClose)Fn("triggering empty send to append close packet"),this.send([{type:"noop"}])}onDataRequest(i,o){if(this.dataReq){this.onError("data request overlap from client"),o.writeHead(400),o.end();return}let n=i.headers["content-type"]==="application/octet-stream";if(n&&this.protocol===4)return this.onError("invalid content");this.dataReq=i,this.dataRes=o;let p=n?Buffer.concat([]):"",c=()=>{i.removeListener("data",T),i.removeListener("end",m),i.removeListener("close",x),this.dataReq=this.dataRes=p=null},x=()=>{c(),this.onError("data request connection closed prematurely")},T=(f)=>{let F;if(n)p=Buffer.concat([p,f]),F=p.length;else p+=f,F=Buffer.byteLength(p);if(F>this.maxHttpBufferSize)o.writeHead(413).end(),c()},m=()=>{this.onData(p);let f={"Content-Type":"text/html","Content-Length":"2"};o.writeHead(200,this.headers(i,f)),o.end("ok"),c()};if(i.on("close",x),!n)i.setEncoding("utf8");i.on("data",T),i.on("end",m)}onData(i){Fn('received "%s"',i);let o=(n)=>{if(n.type==="close")return Fn("got xhr close packet"),this.onClose(),!1;this.onPacket(n)};if(this.protocol===3)this.parser.decodePayload(i,o);else this.parser.decodePayload(i).forEach(o)}onClose(){if(this.writable)this.send([{type:"noop"}]);super.onClose()}send(i){if(this.writable=!1,this.shouldClose)Fn("appending close packet to payload"),i.push({type:"close"}),this.shouldClose(),this.shouldClose=null;let o=(n)=>{let p=i.some((c)=>{return c.options&&c.options.compress});this.write(n,{compress:p})};if(this.protocol===3)this.parser.encodePayload(i,this.supportsBinary,o);else this.parser.encodePayload(i,o)}write(i,o){Fn('writing "%s"',i),this.doWrite(i,o,()=>{this.req.cleanup(),this.emit("drain")})}doWrite(i,o,n){let p=typeof i==="string",x={"Content-Type":p?"text/plain; charset=UTF-8":"application/octet-stream"},T=(F)=>{x["Content-Length"]=typeof F==="string"?Buffer.byteLength(F):F.length,this.res.writeHead(200,this.headers(this.req,x)),this.res.end(F),n()};if(!this.httpCompression||!o.compress){T(i);return}if((p?Buffer.byteLength(i):i.length)<this.httpCompression.threshold){T(i);return}let f=UQ(this.req).encodings(["gzip","deflate"]);if(!f){T(i);return}this.compress(i,f,(F,$)=>{if(F){this.res.writeHead(500),this.res.end(),n(F);return}x["Content-Encoding"]=f,T($)})}compress(i,o,n){Fn("compressing");let p=[],c=0;MQ[o](this.httpCompression).on("error",n).on("data",function(x){p.push(x),c+=x.length}).on("end",function(){n(null,Buffer.concat(p,c))}).end(i)}doClose(i){Fn("closing");let o;if(this.dataReq)Fn("aborting ongoing data request"),this.dataReq.destroy();let n=()=>{clearTimeout(o),i(),this.onClose()};if(this.writable)Fn("transport writable - closing right away"),this.send([{type:"close"}]),n();else if(this.discarded)Fn("transport discarded - closing right away"),n();else Fn("transport not writable - buffering orderly close"),this.shouldClose=n,o=setTimeout(n,this.closeTimeout)}headers(i,o={}){let n=i.headers["user-agent"];if(n&&(~n.indexOf(";MSIE")||~n.indexOf("Trident/")))o["X-XSS-Protection"]="0";return o["cache-control"]="no-store",this.emit("headers",o,i),o}}u5.Polling=z5});var O5=P((S5)=>{Object.defineProperty(S5,"__esModule",{value:!0});S5.JSONP=void 0;var zQ=P$(),uQ=Hi("querystring"),QQ=/\\\\n/g,VQ=/(\\)?\\n/g;class V5 extends zQ.Polling{constructor(i){super(i);this.head="___eio["+(i._query.j||"").replace(/[^0-9]/g,"")+"](",this.foot=");"}onData(i){if(i=uQ.parse(i).d,typeof i==="string")i=i.replace(VQ,function(o,n){return n?o:`
|
|
33
|
-
`}),super.onData(i.replace(QQ,"\\n"))}doWrite(i,o,n){let p=JSON.stringify(i).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");i=this.head+p+this.foot,super.doWrite(i,o,n)}}S5.JSONP=V5});var D5=P((C5)=>{Object.defineProperty(C5,"__esModule",{value:!0});C5.WebSocket=void 0;var SQ=Rc(),EQ=Go(),_5=EQ.default("engine:ws");class L5 extends SQ.Transport{constructor(i){super(i);this._doSend=(o)=>{this.socket.send(o,this._onSent)},this._doSendLast=(o)=>{this.socket.send(o,this._onSentLast)},this._onSent=(o)=>{if(o)this.onError("write error",o.stack)},this._onSentLast=(o)=>{if(o)this.onError("write error",o.stack);else this.emit("drain"),this.writable=!0,this.emit("ready")},this.socket=i.websocket,this.socket.on("message",(o,n)=>{let p=n?o:o.toString();_5('received "%s"',p),super.onData(p)}),this.socket.once("close",this.onClose.bind(this)),this.socket.on("error",this.onError.bind(this)),this.writable=!0,this.perMessageDeflate=null}get name(){return"websocket"}get handlesUpgrades(){return!0}send(i){this.writable=!1;for(let o=0;o<i.length;o++){let n=i[o],p=o+1===i.length;if(this._canSendPreEncodedFrame(n))this.socket._sender.sendFrame(n.options.wsPreEncodedFrame,p?this._onSentLast:this._onSent);else this.parser.encodePacket(n,this.supportsBinary,p?this._doSendLast:this._doSend)}}_canSendPreEncodedFrame(i){var o,n,p;return!this.perMessageDeflate&&typeof((n=(o=this.socket)===null||o===void 0?void 0:o._sender)===null||n===void 0?void 0:n.sendFrame)==="function"&&((p=i.options)===null||p===void 0?void 0:p.wsPreEncodedFrame)!==void 0}doClose(i){_5("closing"),this.socket.close(),i&&i()}}C5.WebSocket=L5});var a$=P((B5)=>{Object.defineProperty(B5,"__esModule",{value:!0});B5.WebTransport=void 0;var OQ=Rc(),_Q=Go(),LQ=kT(),Ux=_Q.default("engine:webtransport");class I5 extends OQ.Transport{constructor(i,o,n){super({_query:{EIO:"4"}});this.session=i;let p=LQ.createPacketEncoderStream();p.readable.pipeTo(o.writable).catch(()=>{Ux("the stream was closed")}),this.writer=p.writable.getWriter(),(async()=>{try{while(!0){let{value:c,done:x}=await n.read();if(x){Ux("session is closed");break}Ux("received chunk: %o",c),this.onPacket(c)}}catch(c){Ux("error while reading: %s",c.message)}})(),i.closed.then(()=>this.onClose()),this.writable=!0}get name(){return"webtransport"}async send(i){this.writable=!1;try{for(let o=0;o<i.length;o++){let n=i[o];await this.writer.write(n)}}catch(o){Ux("error while writing: %s",o.message)}this.emit("drain"),this.writable=!0,this.emit("ready")}doClose(i){Ux("closing WebTransport session"),this.session.close(),i&&i()}}B5.WebTransport=I5});var l$=P((j5)=>{Object.defineProperty(j5,"__esModule",{value:!0});var CQ=P$(),yQ=O5(),DQ=D5(),IQ=a$();j5.default={polling:b5,websocket:DQ.WebSocket,webtransport:IQ.WebTransport};function b5(i){if(typeof i._query.j==="string")return new yQ.JSONP(i);else return new CQ.Polling(i)}b5.upgradesTo=["websocket","webtransport"]});var q$=P((a5)=>{Object.defineProperty(a5,"__esModule",{value:!0});a5.Socket=void 0;var NQ=Hi("events"),bQ=Go(),wp=Hi("timers"),
|
|
33
|
+
`}),super.onData(i.replace(QQ,"\\n"))}doWrite(i,o,n){let p=JSON.stringify(i).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");i=this.head+p+this.foot,super.doWrite(i,o,n)}}S5.JSONP=V5});var D5=P((C5)=>{Object.defineProperty(C5,"__esModule",{value:!0});C5.WebSocket=void 0;var SQ=Rc(),EQ=Go(),_5=EQ.default("engine:ws");class L5 extends SQ.Transport{constructor(i){super(i);this._doSend=(o)=>{this.socket.send(o,this._onSent)},this._doSendLast=(o)=>{this.socket.send(o,this._onSentLast)},this._onSent=(o)=>{if(o)this.onError("write error",o.stack)},this._onSentLast=(o)=>{if(o)this.onError("write error",o.stack);else this.emit("drain"),this.writable=!0,this.emit("ready")},this.socket=i.websocket,this.socket.on("message",(o,n)=>{let p=n?o:o.toString();_5('received "%s"',p),super.onData(p)}),this.socket.once("close",this.onClose.bind(this)),this.socket.on("error",this.onError.bind(this)),this.writable=!0,this.perMessageDeflate=null}get name(){return"websocket"}get handlesUpgrades(){return!0}send(i){this.writable=!1;for(let o=0;o<i.length;o++){let n=i[o],p=o+1===i.length;if(this._canSendPreEncodedFrame(n))this.socket._sender.sendFrame(n.options.wsPreEncodedFrame,p?this._onSentLast:this._onSent);else this.parser.encodePacket(n,this.supportsBinary,p?this._doSendLast:this._doSend)}}_canSendPreEncodedFrame(i){var o,n,p;return!this.perMessageDeflate&&typeof((n=(o=this.socket)===null||o===void 0?void 0:o._sender)===null||n===void 0?void 0:n.sendFrame)==="function"&&((p=i.options)===null||p===void 0?void 0:p.wsPreEncodedFrame)!==void 0}doClose(i){_5("closing"),this.socket.close(),i&&i()}}C5.WebSocket=L5});var a$=P((B5)=>{Object.defineProperty(B5,"__esModule",{value:!0});B5.WebTransport=void 0;var OQ=Rc(),_Q=Go(),LQ=kT(),Ux=_Q.default("engine:webtransport");class I5 extends OQ.Transport{constructor(i,o,n){super({_query:{EIO:"4"}});this.session=i;let p=LQ.createPacketEncoderStream();p.readable.pipeTo(o.writable).catch(()=>{Ux("the stream was closed")}),this.writer=p.writable.getWriter(),(async()=>{try{while(!0){let{value:c,done:x}=await n.read();if(x){Ux("session is closed");break}Ux("received chunk: %o",c),this.onPacket(c)}}catch(c){Ux("error while reading: %s",c.message)}})(),i.closed.then(()=>this.onClose()),this.writable=!0}get name(){return"webtransport"}async send(i){this.writable=!1;try{for(let o=0;o<i.length;o++){let n=i[o];await this.writer.write(n)}}catch(o){Ux("error while writing: %s",o.message)}this.emit("drain"),this.writable=!0,this.emit("ready")}doClose(i){Ux("closing WebTransport session"),this.session.close(),i&&i()}}B5.WebTransport=I5});var l$=P((j5)=>{Object.defineProperty(j5,"__esModule",{value:!0});var CQ=P$(),yQ=O5(),DQ=D5(),IQ=a$();j5.default={polling:b5,websocket:DQ.WebSocket,webtransport:IQ.WebTransport};function b5(i){if(typeof i._query.j==="string")return new yQ.JSONP(i);else return new CQ.Polling(i)}b5.upgradesTo=["websocket","webtransport"]});var q$=P((a5)=>{Object.defineProperty(a5,"__esModule",{value:!0});a5.Socket=void 0;var NQ=Hi("events"),bQ=Go(),wp=Hi("timers"),ei=bQ.default("engine:socket");class P5 extends NQ.EventEmitter{get readyState(){return this._readyState}set readyState(i){ei("readyState updated from %s to %s",this._readyState,i),this._readyState=i}constructor(i,o,n,p,c){super();if(this._readyState="opening",this.upgrading=!1,this.upgraded=!1,this.writeBuffer=[],this.packetsFn=[],this.sentCallbackFn=[],this.cleanupFn=[],this.id=i,this.server=o,this.request=p,this.protocol=c,p)if(p.websocket&&p.websocket._socket)this.remoteAddress=p.websocket._socket.remoteAddress;else this.remoteAddress=p.connection.remoteAddress;this.pingTimeoutTimer=null,this.pingIntervalTimer=null,this.setTransport(n),this.onOpen()}onOpen(){if(this.readyState="open",this.transport.sid=this.id,this.sendPacket("open",JSON.stringify({sid:this.id,upgrades:this.getAvailableUpgrades(),pingInterval:this.server.opts.pingInterval,pingTimeout:this.server.opts.pingTimeout,maxPayload:this.server.opts.maxHttpBufferSize})),this.server.opts.initialPacket)this.sendPacket("message",this.server.opts.initialPacket);if(this.emit("open"),this.protocol===3)this.resetPingTimeout();else this.schedulePing()}onPacket(i){if(this.readyState!=="open")return ei("packet received with closed socket");switch(ei(`received packet ${i.type}`),this.emit("packet",i),i.type){case"ping":if(this.transport.protocol!==3){this.onError(new Error("invalid heartbeat direction"));return}ei("got ping"),this.pingTimeoutTimer.refresh(),this.sendPacket("pong"),this.emit("heartbeat");break;case"pong":if(this.transport.protocol===3){this.onError(new Error("invalid heartbeat direction"));return}ei("got pong"),wp.clearTimeout(this.pingTimeoutTimer),this.pingIntervalTimer.refresh(),this.emit("heartbeat");break;case"error":this.onClose("parse error");break;case"message":this.emit("data",i.data),this.emit("message",i.data);break}}onError(i){ei("transport error"),this.onClose("transport error",i)}schedulePing(){this.pingIntervalTimer=wp.setTimeout(()=>{ei("writing ping packet - expecting pong within %sms",this.server.opts.pingTimeout),this.sendPacket("ping"),this.resetPingTimeout()},this.server.opts.pingInterval)}resetPingTimeout(){wp.clearTimeout(this.pingTimeoutTimer),this.pingTimeoutTimer=wp.setTimeout(()=>{if(this.readyState==="closed")return;this.onClose("ping timeout")},this.protocol===3?this.server.opts.pingInterval+this.server.opts.pingTimeout:this.server.opts.pingTimeout)}setTransport(i){let o=this.onError.bind(this),n=()=>this.flush(),p=this.onPacket.bind(this),c=this.onDrain.bind(this),x=this.onClose.bind(this,"transport close");this.transport=i,this.transport.once("error",o),this.transport.on("ready",n),this.transport.on("packet",p),this.transport.on("drain",c),this.transport.once("close",x),this.cleanupFn.push(function(){i.removeListener("error",o),i.removeListener("ready",n),i.removeListener("packet",p),i.removeListener("drain",c),i.removeListener("close",x)})}onDrain(){if(this.sentCallbackFn.length>0){ei("executing batch send callback");let i=this.sentCallbackFn.shift();if(i)for(let o=0;o<i.length;o++)i[o](this.transport)}}_maybeUpgrade(i){ei('might upgrade socket transport from "%s" to "%s"',this.transport.name,i.name),this.upgrading=!0;let o=wp.setTimeout(()=>{if(ei("client did not complete upgrade - closing transport"),x(),i.readyState==="open")i.close()},this.server.opts.upgradeTimeout),n,p=(F)=>{if(F.type==="ping"&&F.data==="probe")ei("got probe ping packet, sending pong"),i.send([{type:"pong",data:"probe"}]),this.emit("upgrading",i),clearInterval(n),n=setInterval(c,100);else if(F.type==="upgrade"&&this.readyState!=="closed"){if(ei("got upgrade packet - upgrading"),x(),this.transport.discard(),this.upgraded=!0,this.clearTransport(),this.setTransport(i),this.emit("upgrade",i),this.flush(),this.readyState==="closing")i.close(()=>{this.onClose("forced close")})}else x(),i.close()},c=()=>{if(this.transport.name==="polling"&&this.transport.writable)ei("writing a noop packet to polling for fast upgrade"),this.transport.send([{type:"noop"}])},x=()=>{this.upgrading=!1,clearInterval(n),wp.clearTimeout(o),i.removeListener("packet",p),i.removeListener("close",m),i.removeListener("error",T),this.removeListener("close",f)},T=(F)=>{ei("client did not complete upgrade - %s",F),x(),i.close(),i=null},m=()=>{T("transport closed")},f=()=>{T("socket closed")};i.on("packet",p),i.once("close",m),i.once("error",T),this.once("close",f)}clearTransport(){let i,o=this.cleanupFn.length;for(let n=0;n<o;n++)i=this.cleanupFn.shift(),i();this.transport.on("error",function(){ei("error triggered by discarded transport")}),this.transport.close(),wp.clearTimeout(this.pingTimeoutTimer)}onClose(i,o){if(this.readyState!=="closed")this.readyState="closed",wp.clearTimeout(this.pingIntervalTimer),wp.clearTimeout(this.pingTimeoutTimer),process.nextTick(()=>{this.writeBuffer=[]}),this.packetsFn=[],this.sentCallbackFn=[],this.clearTransport(),this.emit("close",i,o)}send(i,o,n){return this.sendPacket("message",i,o,n),this}write(i,o,n){return this.sendPacket("message",i,o,n),this}sendPacket(i,o,n={},p){if(typeof n==="function")p=n,n={};if(this.readyState!=="closing"&&this.readyState!=="closed"){ei('sending packet "%s" (%s)',i,o),n.compress=n.compress!==!1;let c={type:i,options:n};if(o)c.data=o;if(this.emit("packetCreate",c),this.writeBuffer.push(c),typeof p==="function")this.packetsFn.push(p);this.flush()}}flush(){if(this.readyState!=="closed"&&this.transport.writable&&this.writeBuffer.length){ei("flushing buffer to transport"),this.emit("flush",this.writeBuffer),this.server.emit("flush",this,this.writeBuffer);let i=this.writeBuffer;if(this.writeBuffer=[],this.packetsFn.length)this.sentCallbackFn.push(this.packetsFn),this.packetsFn=[];else this.sentCallbackFn.push(null);this.transport.send(i),this.emit("drain"),this.server.emit("drain",this)}}getAvailableUpgrades(){let i=[],o=this.server.upgrades(this.transport.name);for(let n=0;n<o.length;++n){let p=o[n];if(this.server.opts.transports.indexOf(p)!==-1)i.push(p)}return i}close(i){if(i&&(this.readyState==="open"||this.readyState==="closing"))return this.closeTransport(i);if(this.readyState!=="open")return;if(this.readyState="closing",this.writeBuffer.length){ei("there are %d remaining packets in the buffer, waiting for the 'drain' event",this.writeBuffer.length),this.once("drain",()=>{ei("all packets have been sent, closing the transport"),this.closeTransport(i)});return}ei("the buffer is empty, closing the transport right away"),this.closeTransport(i)}closeTransport(i){if(ei("closing the transport (discard? %s)",!!i),i)this.transport.discard();this.transport.close(this.onClose.bind(this,"forced close"))}}a5.Socket=P5});var h5=P((rQ)=>{/*!
|
|
34
34
|
* cookie
|
|
35
35
|
* Copyright(c) 2012-2014 Roman Shtylman
|
|
36
36
|
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
@@ -44,7 +44,7 @@ Connection: close\r
|
|
|
44
44
|
Content-type: text/html\r
|
|
45
45
|
Content-Length: `+c+`\r
|
|
46
46
|
\r
|
|
47
|
-
`+p)}i.destroy()}var hT=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];function XV(i){if(i+="",i.length<1)return!1;if(!hT[i.charCodeAt(0)])return ci('invalid header, index 0, char "%s"',i.charCodeAt(0)),!0;if(i.length<2)return!1;if(!hT[i.charCodeAt(1)])return ci('invalid header, index 1, char "%s"',i.charCodeAt(1)),!0;if(i.length<3)return!1;if(!hT[i.charCodeAt(2)])return ci('invalid header, index 2, char "%s"',i.charCodeAt(2)),!0;if(i.length<4)return!1;if(!hT[i.charCodeAt(3)])return ci('invalid header, index 3, char "%s"',i.charCodeAt(3)),!0;for(let o=4;o<i.length;++o)if(!hT[i.charCodeAt(o)])return ci('invalid header, index "%i", char "%s"',o,i.charCodeAt(o)),!0;return!1}});var v9=P((J9)=>{Object.defineProperty(J9,"__esModule",{value:!0});J9.Polling=void 0;var RV=Rc(),F9=Hi("zlib"),YV=B0(),GV=Go(),Mn=GV.default("engine:polling"),KV={gzip:F9.createGzip,deflate:F9.createDeflate};class $9 extends RV.Transport{constructor(i){super(i);this.closeTimeout=30000}get name(){return"polling"}onRequest(i){let o=i.res;if(i.res=null,i.getMethod()==="get")this.onPollRequest(i,o);else if(i.getMethod()==="post")this.onDataRequest(i,o);else o.writeStatus("500 Internal Server Error"),o.end()}onPollRequest(i,o){if(this.req){Mn("request overlap"),this.onError("overlap from client"),o.writeStatus("500 Internal Server Error"),o.end();return}Mn("setting request"),this.req=i,this.res=o;let n=()=>{this.writable=!1,this.onError("poll connection closed prematurely")},p=()=>{this.req=this.res=null};if(i.cleanup=p,o.onAborted(n),this.writable=!0,this.emit("ready"),this.writable&&this.shouldClose)Mn("triggering empty send to append close packet"),this.send([{type:"noop"}])}onDataRequest(i,o){if(this.dataReq){this.onError("data request overlap from client"),o.writeStatus("500 Internal Server Error"),o.end();return}let n=Number(i.headers["content-length"]);if(!n){this.onError("content-length header required"),o.writeStatus("411 Length Required").end();return}if(n>this.maxHttpBufferSize){this.onError("payload too large"),o.writeStatus("413 Payload Too Large").end();return}if(i.headers["content-type"]==="application/octet-stream"&&this.protocol===4)return this.onError("invalid content");this.dataReq=i,this.dataRes=o;let c,x=0,T={"Content-Type":"text/html"};this.headers(i,T);for(let f in T)o.writeHeader(f,String(T[f]));let m=(f)=>{this.onData(f.toString()),this.onDataRequestCleanup(),o.cork(()=>{o.end("ok")})};o.onAborted(()=>{this.onDataRequestCleanup(),this.onError("data request connection closed prematurely")}),o.onData((f,F)=>{let $=x+f.byteLength;if($>n){this.onError("content-length mismatch"),o.close();return}if(!c){if(F){m(Buffer.from(f));return}c=Buffer.allocUnsafe(n)}if(Buffer.from(f).copy(c,x),F){if($!=n){this.onError("content-length mismatch"),o.writeStatus("400 Content-Length Mismatch").end(),this.onDataRequestCleanup();return}m(c);return}x=$})}onDataRequestCleanup(){this.dataReq=this.dataRes=null}onData(i){Mn('received "%s"',i);let o=(n)=>{if(n.type==="close")return Mn("got xhr close packet"),this.onClose(),!1;this.onPacket(n)};if(this.protocol===3)this.parser.decodePayload(i,o);else this.parser.decodePayload(i).forEach(o)}onClose(){if(this.writable)this.send([{type:"noop"}]);super.onClose()}send(i){if(this.writable=!1,this.shouldClose)Mn("appending close packet to payload"),i.push({type:"close"}),this.shouldClose(),this.shouldClose=null;let o=(n)=>{let p=i.some((c)=>{return c.options&&c.options.compress});this.write(n,{compress:p})};if(this.protocol===3)this.parser.encodePayload(i,this.supportsBinary,o);else this.parser.encodePayload(i,o)}write(i,o){Mn('writing "%s"',i),this.doWrite(i,o,()=>{this.req.cleanup(),this.emit("drain")})}doWrite(i,o,n){let p=typeof i==="string",x={"Content-Type":p?"text/plain; charset=UTF-8":"application/octet-stream"},T=(F)=>{this.headers(this.req,x),this.res.cork(()=>{Object.keys(x).forEach(($)=>{this.res.writeHeader($,String(x[$]))}),this.res.end(F)}),n()};if(!this.httpCompression||!o.compress){T(i);return}if((p?Buffer.byteLength(i):i.length)<this.httpCompression.threshold){T(i);return}let f=YV(this.req).encodings(["gzip","deflate"]);if(!f){T(i);return}this.compress(i,f,(F,$)=>{if(F){this.res.writeStatus("500 Internal Server Error"),this.res.end(),n(F);return}x["Content-Encoding"]=f,T($)})}compress(i,o,n){Mn("compressing");let p=[],c=0;KV[o](this.httpCompression).on("error",n).on("data",function(x){p.push(x),c+=x.length}).on("end",function(){n(null,Buffer.concat(p,c))}).end(i)}doClose(i){Mn("closing");let o,n=()=>{clearTimeout(o),i(),this.onClose()};if(this.writable)Mn("transport writable - closing right away"),this.send([{type:"close"}]),n();else if(this.discarded)Mn("transport discarded - closing right away"),n();else Mn("transport not writable - buffering orderly close"),this.shouldClose=n,o=setTimeout(n,this.closeTimeout)}headers(i,o){o=o||{};let n=i.headers["user-agent"];if(n&&(~n.indexOf(";MSIE")||~n.indexOf("Trident/")))o["X-XSS-Protection"]="0";return o["cache-control"]="no-store",this.emit("headers",o,i),o}}J9.Polling=$9});var Y9=P((W9)=>{Object.defineProperty(W9,"__esModule",{value:!0});W9.WebSocket=void 0;var HV=Rc(),UV=Go(),w9=UV.default("engine:ws");class X9 extends HV.Transport{constructor(i){super(i);this.writable=!1,this.perMessageDeflate=null}get name(){return"websocket"}get handlesUpgrades(){return!0}send(i){this.writable=!1;for(let o=0;o<i.length;o++){let n=i[o],p=o+1===i.length,c=(x)=>{let T=typeof x!=="string",m=this.perMessageDeflate&&Buffer.byteLength(x)>this.perMessageDeflate.threshold;if(w9('writing "%s"',x),this.socket.send(x,T,m),p)this.emit("drain"),this.writable=!0,this.emit("ready")};if(n.options&&typeof n.options.wsPreEncoded==="string")c(n.options.wsPreEncoded);else this.parser.encodePacket(n,this.supportsBinary,c)}}doClose(i){w9("closing"),i&&i(),this.socket.end()}}W9.WebSocket=X9});var K9=P((G9)=>{Object.defineProperty(G9,"__esModule",{value:!0});var ZV=v9(),MV=Y9();G9.default={polling:ZV.Polling,websocket:MV.WebSocket}});var z9=P((Z9)=>{Object.defineProperty(Z9,"__esModule",{value:!0});Z9.uServer=void 0;var uV=Go(),Yc=g$(),QV=K9(),ap=uV.default("engine:uws");class H9 extends Yc.BaseServer{init(){}cleanup(){}prepare(i,o){i.method=i.getMethod().toUpperCase(),i.url=i.getUrl();let n=new URLSearchParams(i.getQuery());i._query=Object.fromEntries(n.entries()),i.headers={},i.forEach((p,c)=>{i.headers[p]=c}),i.connection={remoteAddress:Buffer.from(o.getRemoteAddressAsText()).toString()},o.onAborted(()=>{ap("response has been aborted")})}createTransport(i,o){return new QV.default[i](o)}attach(i,o={}){let n=this._computePath(o);i.any(n,this.handleRequest.bind(this)).ws(n,{compression:o.compression,idleTimeout:o.idleTimeout,maxBackpressure:o.maxBackpressure,maxPayloadLength:this.opts.maxHttpBufferSize,upgrade:this.handleUpgrade.bind(this),open:(p)=>{let c=p.getUserData().transport;c.socket=p,c.writable=!0,c.emit("ready")},message:(p,c,x)=>{p.getUserData().transport.onData(x?c:Buffer.from(c).toString())},close:(p,c,x)=>{p.getUserData().transport.onClose(c,x)}})}_applyMiddlewares(i,o,n){if(this.middlewares.length===0)return n();i.res=new U9(o),super._applyMiddlewares(i,i.res,(p)=>{i.res.writeHead(),n(p)})}handleRequest(i,o){ap('handling "%s" http request "%s"',o.getMethod(),o.getUrl()),this.prepare(o,i),o.res=i;let n=(p,c)=>{if(p!==void 0){this.emit("connection_error",{req:o,code:p,message:Yc.Server.errorMessages[p],context:c}),this.abortRequest(o.res,p,c);return}if(o._query.sid)ap("setting new request for existing client"),this.clients[o._query.sid].transport.onRequest(o);else{let x=(T,m)=>this.abortRequest(i,T,m);this.handshake(o._query.transport,o,x)}};this._applyMiddlewares(o,i,(p)=>{if(p)n(Yc.Server.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"});else this.verify(o,!1,n)})}handleUpgrade(i,o,n){ap("on upgrade"),this.prepare(o,i),o.res=i;let p=async(c,x)=>{if(c!==void 0){this.emit("connection_error",{req:o,code:c,message:Yc.Server.errorMessages[c],context:x}),this.abortRequest(i,c,x);return}let T=o._query.sid,m;if(T){let f=this.clients[T];if(!f)return ap("upgrade attempt for closed client"),i.close();else if(f.upgrading)return ap("transport has already been trying to upgrade"),i.close();else if(f.upgraded)return ap("transport had already been upgraded"),i.close();else ap("upgrading existing transport"),m=this.createTransport(o._query.transport,o),f._maybeUpgrade(m)}else if(m=await this.handshake(o._query.transport,o,(f,F)=>this.abortRequest(i,f,F)),!m)return;o.res.writeStatus("101 Switching Protocols"),i.upgrade({transport:m},o.getHeader("sec-websocket-key"),o.getHeader("sec-websocket-protocol"),o.getHeader("sec-websocket-extensions"),n)};this._applyMiddlewares(o,i,(c)=>{if(c)p(Yc.Server.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"});else this.verify(o,!0,p)})}abortRequest(i,o,n){let p=o===Yc.Server.errors.FORBIDDEN?"403 Forbidden":"400 Bad Request",c=n&&n.message?n.message:Yc.Server.errorMessages[o];i.writeStatus(p),i.writeHeader("Content-Type","application/json"),i.end(JSON.stringify({code:o,message:c}))}}Z9.uServer=H9;class U9{constructor(i){this.res=i,this.statusWritten=!1,this.headers=[],this.isAborted=!1}set statusCode(i){if(!i)return;this.writeStatus(i===200?"200 OK":"204 No Content")}writeHead(i){this.statusCode=i}setHeader(i,o){if(Array.isArray(o))o.forEach((n)=>{this.writeHeader(i,n)});else this.writeHeader(i,o)}removeHeader(){}getHeader(){}writeStatus(i){if(this.isAborted)return;return this.res.writeStatus(i),this.statusWritten=!0,this.writeBufferedHeaders(),this}writeHeader(i,o){if(this.isAborted)return;if(i==="Content-Length")return;if(this.statusWritten)this.res.writeHeader(i,o);else this.headers.push([i,o])}writeBufferedHeaders(){this.headers.forEach(([i,o])=>{this.res.writeHeader(i,o)})}end(i){if(this.isAborted)return;this.res.cork(()=>{if(!this.statusWritten)this.writeBufferedHeaders();this.res.end(i)})}onData(i){if(this.isAborted)return;this.res.onData(i)}onAborted(i){if(this.isAborted)return;this.res.onAborted(()=>{this.isAborted=!0,i()})}cork(i){if(this.isAborted)return;this.res.cork(i)}}});var E9=P((Mx)=>{Object.defineProperty(Mx,"__esModule",{value:!0});Mx.protocol=Mx.Transport=Mx.Socket=Mx.uServer=Mx.parser=Mx.transports=Mx.Server=void 0;Mx.listen=LV;Mx.attach=V9;var VV=Hi("http"),u9=g$();Object.defineProperty(Mx,"Server",{enumerable:!0,get:function(){return u9.Server}});var SV=l$();Mx.transports=SV.default;var Q9=kT();Mx.parser=Q9;var EV=z9();Object.defineProperty(Mx,"uServer",{enumerable:!0,get:function(){return EV.uServer}});var OV=q$();Object.defineProperty(Mx,"Socket",{enumerable:!0,get:function(){return OV.Socket}});var _V=Rc();Object.defineProperty(Mx,"Transport",{enumerable:!0,get:function(){return _V.Transport}});Mx.protocol=Q9.protocol;function LV(i,o,n){if(typeof o==="function")n=o,o={};let p=VV.createServer(function(x,T){T.writeHead(501),T.end("Not Implemented")}),c=V9(p,o);return c.httpServer=p,p.listen(i,n),c}function V9(i,o){let n=new u9.Server(o);return n.attach(i,o),n}});var O9=P((NV)=>{NV.Emitter=Po;function Po(i){if(i)return BV(i)}function BV(i){for(var o in Po.prototype)i[o]=Po.prototype[o];return i}Po.prototype.on=Po.prototype.addEventListener=function(i,o){return this._callbacks=this._callbacks||{},(this._callbacks["$"+i]=this._callbacks["$"+i]||[]).push(o),this};Po.prototype.once=function(i,o){function n(){this.off(i,n),o.apply(this,arguments)}return n.fn=o,this.on(i,n),this};Po.prototype.off=Po.prototype.removeListener=Po.prototype.removeAllListeners=Po.prototype.removeEventListener=function(i,o){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+i];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+i],this;var p;for(var c=0;c<n.length;c++)if(p=n[c],p===o||p.fn===o){n.splice(c,1);break}if(n.length===0)delete this._callbacks["$"+i];return this};Po.prototype.emit=function(i){this._callbacks=this._callbacks||{};var o=new Array(arguments.length-1),n=this._callbacks["$"+i];for(var p=1;p<arguments.length;p++)o[p-1]=arguments[p];if(n){n=n.slice(0);for(var p=0,c=n.length;p<c;++p)n[p].apply(this,o)}return this};Po.prototype.emitReserved=Po.prototype.emit;Po.prototype.listeners=function(i){return this._callbacks=this._callbacks||{},this._callbacks["$"+i]||[]};Po.prototype.hasListeners=function(i){return!!this.listeners(i).length}});var s$=P((C9)=>{Object.defineProperty(C9,"__esModule",{value:!0});C9.hasBinary=C9.isBinary=void 0;var jV=typeof ArrayBuffer==="function",PV=(i)=>{return typeof ArrayBuffer.isView==="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer},_9=Object.prototype.toString,aV=typeof Blob==="function"||typeof Blob!=="undefined"&&_9.call(Blob)==="[object BlobConstructor]",lV=typeof File==="function"||typeof File!=="undefined"&&_9.call(File)==="[object FileConstructor]";function L9(i){return jV&&(i instanceof ArrayBuffer||PV(i))||aV&&i instanceof Blob||lV&&i instanceof File}C9.isBinary=L9;function e0(i,o){if(!i||typeof i!=="object")return!1;if(Array.isArray(i)){for(let n=0,p=i.length;n<p;n++)if(e0(i[n]))return!0;return!1}if(L9(i))return!0;if(i.toJSON&&typeof i.toJSON==="function"&&arguments.length===1)return e0(i.toJSON(),!0);for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)&&e0(i[n]))return!0;return!1}C9.hasBinary=e0});var B9=P((D9)=>{Object.defineProperty(D9,"__esModule",{value:!0});D9.reconstructPacket=D9.deconstructPacket=void 0;var kV=s$();function hV(i){let o=[],n=i.data,p=i;return p.data=t$(n,o),p.attachments=o.length,{packet:p,buffers:o}}D9.deconstructPacket=hV;function t$(i,o){if(!i)return i;if(kV.isBinary(i)){let n={_placeholder:!0,num:o.length};return o.push(i),n}else if(Array.isArray(i)){let n=new Array(i.length);for(let p=0;p<i.length;p++)n[p]=t$(i[p],o);return n}else if(typeof i==="object"&&!(i instanceof Date)){let n={};for(let p in i)if(Object.prototype.hasOwnProperty.call(i,p))n[p]=t$(i[p],o);return n}return i}function gV(i,o){return i.data=d$(i.data,o),delete i.attachments,i}D9.reconstructPacket=gV;function d$(i,o){if(!i)return i;if(i&&i._placeholder===!0)if(typeof i.num==="number"&&i.num>=0&&i.num<o.length)return o[i.num];else throw new Error("illegal attachments");else if(Array.isArray(i))for(let n=0;n<i.length;n++)i[n]=d$(i[n],o);else if(typeof i==="object"){for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n))i[n]=d$(i[n],o)}return i}});var sT=P((q9)=>{Object.defineProperty(q9,"__esModule",{value:!0});q9.Decoder=q9.Encoder=q9.PacketType=q9.protocol=void 0;var tV=O9(),j9=B9(),P9=s$(),dV=Go(),r$=dV.default("socket.io-parser"),rV=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];q9.protocol=5;var si;(function(i){i[i.CONNECT=0]="CONNECT",i[i.DISCONNECT=1]="DISCONNECT",i[i.EVENT=2]="EVENT",i[i.ACK=3]="ACK",i[i.CONNECT_ERROR=4]="CONNECT_ERROR",i[i.BINARY_EVENT=5]="BINARY_EVENT",i[i.BINARY_ACK=6]="BINARY_ACK"})(si=q9.PacketType||(q9.PacketType={}));class a9{constructor(i){this.replacer=i}encode(i){if(r$("encoding packet %j",i),i.type===si.EVENT||i.type===si.ACK){if(P9.hasBinary(i))return this.encodeAsBinary({type:i.type===si.EVENT?si.BINARY_EVENT:si.BINARY_ACK,nsp:i.nsp,data:i.data,id:i.id})}return[this.encodeAsString(i)]}encodeAsString(i){let o=""+i.type;if(i.type===si.BINARY_EVENT||i.type===si.BINARY_ACK)o+=i.attachments+"-";if(i.nsp&&i.nsp!=="/")o+=i.nsp+",";if(i.id!=null)o+=i.id;if(i.data!=null)o+=JSON.stringify(i.data,this.replacer);return r$("encoded %j as %s",i,o),o}encodeAsBinary(i){let o=j9.deconstructPacket(i),n=this.encodeAsString(o.packet),p=o.buffers;return p.unshift(n),p}}q9.Encoder=a9;function N9(i){return Object.prototype.toString.call(i)==="[object Object]"}class e$ extends tV.Emitter{constructor(i){super();this.reviver=i}add(i){let o;if(typeof i==="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");o=this.decodeString(i);let n=o.type===si.BINARY_EVENT;if(n||o.type===si.BINARY_ACK){if(o.type=n?si.EVENT:si.ACK,this.reconstructor=new l9(o),o.attachments===0)super.emitReserved("decoded",o)}else super.emitReserved("decoded",o)}else if(P9.isBinary(i)||i.base64){if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");else if(o=this.reconstructor.takeBinaryData(i),o)this.reconstructor=null,super.emitReserved("decoded",o)}else throw new Error("Unknown type: "+i)}decodeString(i){let o=0,n={type:Number(i.charAt(0))};if(si[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===si.BINARY_EVENT||n.type===si.BINARY_ACK){let c=o+1;while(i.charAt(++o)!=="-"&&o!=i.length);let x=i.substring(c,o);if(x!=Number(x)||i.charAt(o)!=="-")throw new Error("Illegal attachments");n.attachments=Number(x)}if(i.charAt(o+1)==="/"){let c=o+1;while(++o){if(i.charAt(o)===",")break;if(o===i.length)break}n.nsp=i.substring(c,o)}else n.nsp="/";let p=i.charAt(o+1);if(p!==""&&Number(p)==p){let c=o+1;while(++o){let x=i.charAt(o);if(x==null||Number(x)!=x){--o;break}if(o===i.length)break}n.id=Number(i.substring(c,o+1))}if(i.charAt(++o)){let c=this.tryParse(i.substr(o));if(e$.isPayloadValid(n.type,c))n.data=c;else throw new Error("invalid payload")}return r$("decoded %s as %j",i,n),n}tryParse(i){try{return JSON.parse(i,this.reviver)}catch(o){return!1}}static isPayloadValid(i,o){switch(i){case si.CONNECT:return N9(o);case si.DISCONNECT:return o===void 0;case si.CONNECT_ERROR:return typeof o==="string"||N9(o);case si.EVENT:case si.BINARY_EVENT:return Array.isArray(o)&&(typeof o[0]==="number"||typeof o[0]==="string"&&rV.indexOf(o[0])===-1);case si.ACK:case si.BINARY_ACK:return Array.isArray(o)}}destroy(){if(this.reconstructor)this.reconstructor.finishedReconstruction(),this.reconstructor=null}}q9.Decoder=e$;class l9{constructor(i){this.packet=i,this.buffers=[],this.reconPack=i}takeBinaryData(i){if(this.buffers.push(i),this.buffers.length===this.reconPack.attachments){let o=j9.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),o}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}});var t9=P((g9)=>{Object.defineProperty(g9,"__esModule",{value:!0});g9.Client=void 0;var i1=sT(),oS=Go(),nS=Hi("url"),Nn=oS("socket.io:client");class h9{constructor(i,o){this.sockets=new Map,this.nsps=new Map,this.server=i,this.conn=o,this.encoder=i.encoder,this.decoder=new i._parser.Decoder,this.id=o.id,this.setup()}get request(){return this.conn.request}setup(){this.onclose=this.onclose.bind(this),this.ondata=this.ondata.bind(this),this.onerror=this.onerror.bind(this),this.ondecoded=this.ondecoded.bind(this),this.decoder.on("decoded",this.ondecoded),this.conn.on("data",this.ondata),this.conn.on("error",this.onerror),this.conn.on("close",this.onclose),this.connectTimeout=setTimeout(()=>{if(this.nsps.size===0)Nn("no namespace joined yet, close the client"),this.close();else Nn("the client has already joined a namespace, nothing to do")},this.server._connectTimeout)}connect(i,o={}){if(this.server._nsps.has(i))return Nn("connecting to namespace %s",i),this.doConnect(i,o);this.server._checkNamespace(i,o,(n)=>{if(n)this.doConnect(i,o);else Nn("creation of namespace %s was denied",i),this._packet({type:i1.PacketType.CONNECT_ERROR,nsp:i,data:{message:"Invalid namespace"}})})}doConnect(i,o){let n=this.server.of(i);n._add(this,o,(p)=>{if(this.sockets.set(p.id,p),this.nsps.set(n.name,p),this.connectTimeout)clearTimeout(this.connectTimeout),this.connectTimeout=void 0})}_disconnect(){for(let i of this.sockets.values())i.disconnect();this.sockets.clear(),this.close()}_remove(i){if(this.sockets.has(i.id)){let o=this.sockets.get(i.id).nsp.name;this.sockets.delete(i.id),this.nsps.delete(o)}else Nn("ignoring remove for %s",i.id)}close(){if(this.conn.readyState==="open")Nn("forcing transport close"),this.conn.close(),this.onclose("forced server close")}_packet(i,o={}){if(this.conn.readyState!=="open"){Nn("ignoring packet write %j",i);return}let n=o.preEncoded?i:this.encoder.encode(i);this.writeToEngine(n,o)}writeToEngine(i,o){if(o.volatile&&!this.conn.transport.writable){Nn("volatile packet is discarded since the transport is not currently writable");return}let n=Array.isArray(i)?i:[i];for(let p of n)this.conn.write(p,o)}ondata(i){try{this.decoder.add(i)}catch(o){Nn("invalid packet format"),this.onerror(o)}}ondecoded(i){let o,n;if(this.conn.protocol===3){let c=nS.parse(i.nsp,!0);o=c.pathname,n=c.query}else o=i.nsp,n=i.data;let p=this.nsps.get(o);if(!p&&i.type===i1.PacketType.CONNECT)this.connect(o,n);else if(p&&i.type!==i1.PacketType.CONNECT&&i.type!==i1.PacketType.CONNECT_ERROR)process.nextTick(function(){p._onpacket(i)});else Nn("invalid state (packet type: %s)",i.type),this.close()}onerror(i){for(let o of this.sockets.values())o._onerror(i);this.conn.close()}onclose(i,o){Nn("client close with reason %s",i),this.destroy();for(let n of this.sockets.values())n._onclose(i,o);this.sockets.clear(),this.decoder.destroy()}destroy(){if(this.conn.removeListener("data",this.ondata),this.conn.removeListener("error",this.onerror),this.conn.removeListener("close",this.onclose),this.decoder.removeListener("decoded",this.ondecoded),this.connectTimeout)clearTimeout(this.connectTimeout),this.connectTimeout=void 0}}g9.Client=h9});var o1=P((r9)=>{Object.defineProperty(r9,"__esModule",{value:!0});r9.StrictEventEmitter=void 0;var pS=Hi("events");class d9 extends pS.EventEmitter{on(i,o){return super.on(i,o)}once(i,o){return super.once(i,o)}emit(i,...o){return super.emit(i,...o)}emitReserved(i,...o){return super.emit(i,...o)}emitUntyped(i,...o){return super.emit(i,...o)}listeners(i){return super.listeners(i)}}r9.StrictEventEmitter=d9});var iJ=P((iR)=>{Object.defineProperty(iR,"__esModule",{value:!0});iR.RESERVED_EVENTS=void 0;iR.RESERVED_EVENTS=new Set(["connect","connect_error","disconnect","disconnecting","newListener","removeListener"])});var nJ=P((nR)=>{Object.defineProperty(nR,"__esModule",{value:!0});nR.RemoteSocket=nR.BroadcastOperator=void 0;var cS=iJ(),xS=sT();class Xp{constructor(i,o=new Set,n=new Set,p={}){this.adapter=i,this.rooms=o,this.exceptRooms=n,this.flags=p}to(i){let o=new Set(this.rooms);if(Array.isArray(i))i.forEach((n)=>o.add(n));else o.add(i);return new Xp(this.adapter,o,this.exceptRooms,this.flags)}in(i){return this.to(i)}except(i){let o=new Set(this.exceptRooms);if(Array.isArray(i))i.forEach((n)=>o.add(n));else o.add(i);return new Xp(this.adapter,this.rooms,o,this.flags)}compress(i){let o=Object.assign({},this.flags,{compress:i});return new Xp(this.adapter,this.rooms,this.exceptRooms,o)}get volatile(){let i=Object.assign({},this.flags,{volatile:!0});return new Xp(this.adapter,this.rooms,this.exceptRooms,i)}get local(){let i=Object.assign({},this.flags,{local:!0});return new Xp(this.adapter,this.rooms,this.exceptRooms,i)}timeout(i){let o=Object.assign({},this.flags,{timeout:i});return new Xp(this.adapter,this.rooms,this.exceptRooms,o)}emit(i,...o){if(cS.RESERVED_EVENTS.has(i))throw new Error(`"${String(i)}" is a reserved event name`);let n=[i,...o],p={type:xS.PacketType.EVENT,data:n};if(typeof n[n.length-1]!=="function")return this.adapter.broadcast(p,{rooms:this.rooms,except:this.exceptRooms,flags:this.flags}),!0;let x=n.pop(),T=!1,m=[],f=setTimeout(()=>{T=!0,x.apply(this,[new Error("operation has timed out"),this.flags.expectSingleResponse?null:m])},this.flags.timeout),F=-1,$=0,J=0,A=()=>{if(!T&&F===$&&m.length===J)clearTimeout(f),x.apply(this,[null,this.flags.expectSingleResponse?m[0]:m])};return this.adapter.broadcastWithAck(p,{rooms:this.rooms,except:this.exceptRooms,flags:this.flags},(X)=>{J+=X,$++,A()},(X)=>{m.push(X),A()}),this.adapter.serverCount().then((X)=>{F=X,A()}),!0}emitWithAck(i,...o){return new Promise((n,p)=>{o.push((c,x)=>{if(c)return c.responses=x,p(c);else return n(x)}),this.emit(i,...o)})}allSockets(){if(!this.adapter)throw new Error("No adapter for this namespace, are you trying to get the list of clients of a dynamic namespace?");return this.adapter.sockets(this.rooms)}fetchSockets(){return this.adapter.fetchSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags}).then((i)=>{return i.map((o)=>{if(o.server)return o;else return new oJ(this.adapter,o)})})}socketsJoin(i){this.adapter.addSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags},Array.isArray(i)?i:[i])}socketsLeave(i){this.adapter.delSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags},Array.isArray(i)?i:[i])}disconnectSockets(i=!1){this.adapter.disconnectSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags},i)}}nR.BroadcastOperator=Xp;class oJ{constructor(i,o){this.id=o.id,this.handshake=o.handshake,this.rooms=new Set(o.rooms),this.data=o.data,this.operator=new Xp(i,new Set([this.id]),new Set,{expectSingleResponse:!0})}timeout(i){return this.operator.timeout(i)}emit(i,...o){return this.operator.emit(i,...o)}join(i){return this.operator.socketsJoin(i)}leave(i){return this.operator.socketsLeave(i)}disconnect(i=!1){return this.operator.disconnectSockets(i),this}}nR.RemoteSocket=oJ});var pJ=P((zx)=>{var TR=zx&&zx.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(zx,"__esModule",{value:!0});zx.Socket=void 0;var zn=sT(),mS=TR(Go()),fS=o1(),cR=TR(S$()),FS=nJ(),$S=iJ(),yo=mS.default("socket.io:socket"),JS=new Set(["transport error","transport close","forced close","ping timeout","server shutting down","forced server close"]);function xR(){}class mR extends fS.StrictEventEmitter{constructor(i,o,n,p){super();if(this.nsp=i,this.client=o,this.recovered=!1,this.data={},this.connected=!1,this.acks=new Map,this.fns=[],this.flags={},this.server=i.server,this.adapter=this.nsp.adapter,p)this.id=p.sid,this.pid=p.pid,p.rooms.forEach((c)=>this.join(c)),this.data=p.data,p.missedPackets.forEach((c)=>{this.packet({type:zn.PacketType.EVENT,data:c})}),this.recovered=!0;else{if(o.conn.protocol===3)this.id=i.name!=="/"?i.name+"#"+o.id:o.id;else this.id=cR.default.generateId();if(this.server._opts.connectionStateRecovery)this.pid=cR.default.generateId()}this.handshake=this.buildHandshake(n),this.on("error",xR)}buildHandshake(i){var o,n,p,c;return{headers:((o=this.request)===null||o===void 0?void 0:o.headers)||{},time:new Date+"",address:this.conn.remoteAddress,xdomain:!!((n=this.request)===null||n===void 0?void 0:n.headers.origin),secure:!this.request||!!this.request.connection.encrypted,issued:+new Date,url:(p=this.request)===null||p===void 0?void 0:p.url,query:((c=this.request)===null||c===void 0?void 0:c._query)||{},auth:i}}emit(i,...o){if($S.RESERVED_EVENTS.has(i))throw new Error(`"${String(i)}" is a reserved event name`);let n=[i,...o],p={type:zn.PacketType.EVENT,data:n};if(typeof n[n.length-1]==="function"){let x=this.nsp._ids++;yo("emitting packet with ack id %d",x),this.registerAckCallback(x,n.pop()),p.id=x}let c=Object.assign({},this.flags);if(this.flags={},this.nsp.server.opts.connectionStateRecovery)this.adapter.broadcast(p,{rooms:new Set([this.id]),except:new Set,flags:c});else this.notifyOutgoingListeners(p),this.packet(p,c);return!0}emitWithAck(i,...o){let n=this.flags.timeout!==void 0;return new Promise((p,c)=>{o.push((x,T)=>{if(n)return x?c(x):p(T);else return p(x)}),this.emit(i,...o)})}registerAckCallback(i,o){let n=this.flags.timeout;if(n===void 0){this.acks.set(i,o);return}let p=setTimeout(()=>{yo("event with ack id %d has timed out after %d ms",i,n),this.acks.delete(i),o.call(this,new Error("operation has timed out"))},n);this.acks.set(i,(...c)=>{clearTimeout(p),o.apply(this,[null,...c])})}to(i){return this.newBroadcastOperator().to(i)}in(i){return this.newBroadcastOperator().in(i)}except(i){return this.newBroadcastOperator().except(i)}send(...i){return this.emit("message",...i),this}write(...i){return this.emit("message",...i),this}packet(i,o={}){i.nsp=this.nsp.name,o.compress=o.compress!==!1,this.client._packet(i,o)}join(i){return yo("join room %s",i),this.adapter.addAll(this.id,new Set(Array.isArray(i)?i:[i]))}leave(i){return yo("leave room %s",i),this.adapter.del(this.id,i)}leaveAll(){this.adapter.delAll(this.id)}_onconnect(){if(yo("socket connected - writing packet"),this.connected=!0,this.join(this.id),this.conn.protocol===3)this.packet({type:zn.PacketType.CONNECT});else this.packet({type:zn.PacketType.CONNECT,data:{sid:this.id,pid:this.pid}})}_onpacket(i){switch(yo("got packet %j",i),i.type){case zn.PacketType.EVENT:this.onevent(i);break;case zn.PacketType.BINARY_EVENT:this.onevent(i);break;case zn.PacketType.ACK:this.onack(i);break;case zn.PacketType.BINARY_ACK:this.onack(i);break;case zn.PacketType.DISCONNECT:this.ondisconnect();break}}onevent(i){let o=i.data||[];if(yo("emitting event %j",o),i.id!=null)yo("attaching ack callback to event"),o.push(this.ack(i.id));if(this._anyListeners&&this._anyListeners.length){let n=this._anyListeners.slice();for(let p of n)p.apply(this,o)}this.dispatch(o)}ack(i){let o=this,n=!1;return function(){if(n)return;let p=Array.prototype.slice.call(arguments);yo("sending ack %j",p),o.packet({id:i,type:zn.PacketType.ACK,data:p}),n=!0}}onack(i){let o=this.acks.get(i.id);if(typeof o=="function")yo("calling ack %s with %j",i.id,i.data),o.apply(this,i.data),this.acks.delete(i.id);else yo("bad ack %s",i.id)}ondisconnect(){yo("got disconnect packet"),this._onclose("client namespace disconnect")}_onerror(i){this.emitReserved("error",i)}_onclose(i,o){if(!this.connected)return this;if(yo("closing socket - reason %s",i),this.emitReserved("disconnecting",i,o),this.server._opts.connectionStateRecovery&&JS.has(i))yo("connection state recovery is enabled for sid %s",this.id),this.adapter.persistSession({sid:this.id,pid:this.pid,rooms:[...this.rooms],data:this.data});this._cleanup(),this.client._remove(this),this.connected=!1,this.emitReserved("disconnect",i,o);return}_cleanup(){this.leaveAll(),this.nsp._remove(this),this.join=xR}_error(i){this.packet({type:zn.PacketType.CONNECT_ERROR,data:i})}disconnect(i=!1){if(!this.connected)return this;if(i)this.client._disconnect();else this.packet({type:zn.PacketType.DISCONNECT}),this._onclose("server namespace disconnect");return this}compress(i){return this.flags.compress=i,this}get volatile(){return this.flags.volatile=!0,this}get broadcast(){return this.newBroadcastOperator()}get local(){return this.newBroadcastOperator().local}timeout(i){return this.flags.timeout=i,this}dispatch(i){yo("dispatching an event %j",i),this.run(i,(o)=>{process.nextTick(()=>{if(o)return this._onerror(o);if(this.connected)super.emitUntyped.apply(this,i);else yo("ignore packet received after disconnection")})})}use(i){return this.fns.push(i),this}run(i,o){if(!this.fns.length)return o();let n=this.fns.slice(0);function p(c){n[c](i,(x)=>{if(x)return o(x);if(!n[c+1])return o();p(c+1)})}p(0)}get disconnected(){return!this.connected}get request(){return this.client.request}get conn(){return this.client.conn}get rooms(){return this.adapter.socketRooms(this.id)||new Set}onAny(i){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(i),this}prependAny(i){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(i),this}offAny(i){if(!this._anyListeners)return this;if(i){let o=this._anyListeners;for(let n=0;n<o.length;n++)if(i===o[n])return o.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(i){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(i),this}prependAnyOutgoing(i){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(i),this}offAnyOutgoing(i){if(!this._anyOutgoingListeners)return this;if(i){let o=this._anyOutgoingListeners;for(let n=0;n<o.length;n++)if(i===o[n])return o.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(i){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let o=this._anyOutgoingListeners.slice();for(let n of o)n.apply(this,i.data)}}newBroadcastOperator(){let i=Object.assign({},this.flags);return this.flags={},new FS.BroadcastOperator(this.adapter,new Set,new Set([this.id]),i)}}zx.Socket=mR});var cJ=P((Wp)=>{var AS=Wp&&Wp.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Wp,"__esModule",{value:!0});Wp.Namespace=Wp.RESERVED_EVENTS=void 0;var fR=pJ(),vS=o1(),wS=AS(Go()),$n=nJ(),tT=wS.default("socket.io:namespace");Wp.RESERVED_EVENTS=new Set(["connect","connection","new_namespace"]);class FR extends vS.StrictEventEmitter{constructor(i,o){super();this.sockets=new Map,this._preConnectSockets=new Map,this._fns=[],this._ids=0,this.server=i,this.name=o,this._initAdapter()}_initAdapter(){this.adapter=new(this.server.adapter())(this)}use(i){return this._fns.push(i),this}run(i,o){if(!this._fns.length)return o();let n=this._fns.slice(0);function p(c){n[c](i,(x)=>{if(x)return o(x);if(!n[c+1])return o();p(c+1)})}p(0)}to(i){return new $n.BroadcastOperator(this.adapter).to(i)}in(i){return new $n.BroadcastOperator(this.adapter).in(i)}except(i){return new $n.BroadcastOperator(this.adapter).except(i)}async _add(i,o,n){var p;tT("adding socket to nsp %s",this.name);let c=await this._createSocket(i,o);if(this._preConnectSockets.set(c.id,c),((p=this.server.opts.connectionStateRecovery)===null||p===void 0?void 0:p.skipMiddlewares)&&c.recovered&&i.conn.readyState==="open")return this._doConnect(c,n);this.run(c,(x)=>{process.nextTick(()=>{if(i.conn.readyState!=="open"){tT("next called after client was closed - ignoring socket"),c._cleanup();return}if(x)if(tT("middleware error, sending CONNECT_ERROR packet to the client"),c._cleanup(),i.conn.protocol===3)return c._error(x.data||x.message);else return c._error({message:x.message,data:x.data});this._doConnect(c,n)})})}async _createSocket(i,o){let{pid:n,offset:p}=o;if(this.server.opts.connectionStateRecovery&&typeof n==="string"&&typeof p==="string"){let c;try{c=await this.adapter.restoreSession(n,p)}catch(x){tT("error while restoring session: %s",x)}if(c)return tT("connection state recovered for sid %s",c.sid),new fR.Socket(this,i,o,c)}return new fR.Socket(this,i,o)}_doConnect(i,o){if(this._preConnectSockets.delete(i.id),this.sockets.set(i.id,i),i._onconnect(),o)o(i);this.emitReserved("connect",i),this.emitReserved("connection",i)}_remove(i){this.sockets.delete(i.id)||this._preConnectSockets.delete(i.id)}emit(i,...o){return new $n.BroadcastOperator(this.adapter).emit(i,...o)}send(...i){return this.emit("message",...i),this}write(...i){return this.emit("message",...i),this}serverSideEmit(i,...o){if(Wp.RESERVED_EVENTS.has(i))throw new Error(`"${String(i)}" is a reserved event name`);return o.unshift(i),this.adapter.serverSideEmit(o),!0}serverSideEmitWithAck(i,...o){return new Promise((n,p)=>{o.push((c,x)=>{if(c)return c.responses=x,p(c);else return n(x)}),this.serverSideEmit(i,...o)})}_onServerSideEmit(i){super.emitUntyped.apply(this,i)}allSockets(){return new $n.BroadcastOperator(this.adapter).allSockets()}compress(i){return new $n.BroadcastOperator(this.adapter).compress(i)}get volatile(){return new $n.BroadcastOperator(this.adapter).volatile}get local(){return new $n.BroadcastOperator(this.adapter).local}timeout(i){return new $n.BroadcastOperator(this.adapter).timeout(i)}fetchSockets(){return new $n.BroadcastOperator(this.adapter).fetchSockets()}socketsJoin(i){return new $n.BroadcastOperator(this.adapter).socketsJoin(i)}socketsLeave(i){return new $n.BroadcastOperator(this.adapter).socketsLeave(i)}disconnectSockets(i=!1){return new $n.BroadcastOperator(this.adapter).disconnectSockets(i)}}Wp.Namespace=FR});var WR=P((wR)=>{Object.defineProperty(wR,"__esModule",{value:!0});wR.yeast=wR.decode=wR.encode=void 0;var AR="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),n1=64,vR={},$R=0,lp=0,JR;function xJ(i){let o="";do o=AR[i%n1]+o,i=Math.floor(i/n1);while(i>0);return o}wR.encode=xJ;function XS(i){let o=0;for(lp=0;lp<i.length;lp++)o=o*n1+vR[i.charAt(lp)];return o}wR.decode=XS;function WS(){let i=xJ(+new Date);if(i!==JR)return $R=0,JR=i;return i+"."+xJ($R++)}wR.yeast=WS;for(;lp<n1;lp++)vR[AR[lp]]=lp});var fJ=P((YR)=>{var TJ;Object.defineProperty(YR,"__esModule",{value:!0});YR.SessionAwareAdapter=YR.Adapter=void 0;var GS=Hi("events"),KS=WR(),p1=Hi("ws"),HS=typeof((TJ=p1===null||p1===void 0?void 0:p1.Sender)===null||TJ===void 0?void 0:TJ.frame)==="function";class mJ extends GS.EventEmitter{constructor(i){super();this.nsp=i,this.rooms=new Map,this.sids=new Map,this.encoder=i.server.encoder}init(){}close(){}serverCount(){return Promise.resolve(1)}addAll(i,o){if(!this.sids.has(i))this.sids.set(i,new Set);for(let n of o){if(this.sids.get(i).add(n),!this.rooms.has(n))this.rooms.set(n,new Set),this.emit("create-room",n);if(!this.rooms.get(n).has(i))this.rooms.get(n).add(i),this.emit("join-room",n,i)}}del(i,o){if(this.sids.has(i))this.sids.get(i).delete(o);this._del(o,i)}_del(i,o){let n=this.rooms.get(i);if(n!=null){if(n.delete(o))this.emit("leave-room",i,o);if(n.size===0&&this.rooms.delete(i))this.emit("delete-room",i)}}delAll(i){if(!this.sids.has(i))return;for(let o of this.sids.get(i))this._del(o,i);this.sids.delete(i)}broadcast(i,o){let n=o.flags||{},p={preEncoded:!0,volatile:n.volatile,compress:n.compress};i.nsp=this.nsp.name;let c=this._encode(i,p);this.apply(o,(x)=>{if(typeof x.notifyOutgoingListeners==="function")x.notifyOutgoingListeners(i);x.client.writeToEngine(c,p)})}broadcastWithAck(i,o,n,p){let c=o.flags||{},x={preEncoded:!0,volatile:c.volatile,compress:c.compress};i.nsp=this.nsp.name,i.id=this.nsp._ids++;let T=this._encode(i,x),m=0;this.apply(o,(f)=>{if(m++,f.acks.set(i.id,p),typeof f.notifyOutgoingListeners==="function")f.notifyOutgoingListeners(i);f.client.writeToEngine(T,x)}),n(m)}_encode(i,o){let n=this.encoder.encode(i);if(HS&&n.length===1&&typeof n[0]==="string"){let p=Buffer.from("4"+n[0]);o.wsPreEncodedFrame=p1.Sender.frame(p,{readOnly:!1,mask:!1,rsv1:!1,opcode:1,fin:!0})}return n}sockets(i){let o=new Set;return this.apply({rooms:i},(n)=>{o.add(n.id)}),Promise.resolve(o)}socketRooms(i){return this.sids.get(i)}fetchSockets(i){let o=[];return this.apply(i,(n)=>{o.push(n)}),Promise.resolve(o)}addSockets(i,o){this.apply(i,(n)=>{n.join(o)})}delSockets(i,o){this.apply(i,(n)=>{o.forEach((p)=>n.leave(p))})}disconnectSockets(i,o){this.apply(i,(n)=>{n.disconnect(o)})}apply(i,o){let n=i.rooms,p=this.computeExceptSids(i.except);if(n.size){let c=new Set;for(let x of n){if(!this.rooms.has(x))continue;for(let T of this.rooms.get(x)){if(c.has(T)||p.has(T))continue;let m=this.nsp.sockets.get(T);if(m)o(m),c.add(T)}}}else for(let[c]of this.sids){if(p.has(c))continue;let x=this.nsp.sockets.get(c);if(x)o(x)}}computeExceptSids(i){let o=new Set;if(i&&i.size>0){for(let n of i)if(this.rooms.has(n))this.rooms.get(n).forEach((p)=>o.add(p))}return o}serverSideEmit(i){console.warn("this adapter does not support the serverSideEmit() functionality")}persistSession(i){}restoreSession(i,o){return null}}YR.Adapter=mJ;class RR extends mJ{constructor(i){super(i);this.nsp=i,this.sessions=new Map,this.packets=[],this.maxDisconnectionDuration=i.server.opts.connectionStateRecovery.maxDisconnectionDuration,setInterval(()=>{let n=Date.now()-this.maxDisconnectionDuration;this.sessions.forEach((p,c)=>{if(p.disconnectedAt<n)this.sessions.delete(c)});for(let p=this.packets.length-1;p>=0;p--)if(this.packets[p].emittedAt<n){this.packets.splice(0,p+1);break}},60000).unref()}persistSession(i){i.disconnectedAt=Date.now(),this.sessions.set(i.pid,i)}restoreSession(i,o){let n=this.sessions.get(i);if(!n)return null;if(n.disconnectedAt+this.maxDisconnectionDuration<Date.now())return this.sessions.delete(i),null;let c=this.packets.findIndex((T)=>T.id===o);if(c===-1)return null;let x=[];for(let T=c+1;T<this.packets.length;T++){let m=this.packets[T];if(US(n.rooms,m.opts))x.push(m.data)}return Promise.resolve(Object.assign(Object.assign({},n),{missedPackets:x}))}broadcast(i,o){var n;let p=i.type===2,c=i.id===void 0,x=((n=o.flags)===null||n===void 0?void 0:n.volatile)===void 0;if(p&&c&&x){let T=KS.yeast();i.data.push(T),this.packets.push({id:T,opts:o,data:i.data,emittedAt:Date.now()})}super.broadcast(i,o)}}YR.SessionAwareAdapter=RR;function US(i,o){let n=o.rooms.size===0||i.some((c)=>o.rooms.has(c)),p=i.every((c)=>!o.except.has(c));return n&&p}});var HR=P((bn)=>{var MS=bn&&bn.__rest||function(i,o){var n={};for(var p in i)if(Object.prototype.hasOwnProperty.call(i,p)&&o.indexOf(p)<0)n[p]=i[p];if(i!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var c=0,p=Object.getOwnPropertySymbols(i);c<p.length;c++)if(o.indexOf(p[c])<0&&Object.prototype.propertyIsEnumerable.call(i,p[c]))n[p[c]]=i[p[c]]}return n};Object.defineProperty(bn,"__esModule",{value:!0});bn.ClusterAdapterWithHeartbeat=bn.ClusterAdapter=bn.MessageType=void 0;var zS=fJ(),uS=Go(),QS=Hi("crypto"),ei=uS.debug("socket.io-adapter"),VS="emitter",c1=5000;function Qx(){return QS.randomBytes(8).toString("hex")}var ii;(function(i){i[i.INITIAL_HEARTBEAT=1]="INITIAL_HEARTBEAT",i[i.HEARTBEAT=2]="HEARTBEAT",i[i.BROADCAST=3]="BROADCAST",i[i.SOCKETS_JOIN=4]="SOCKETS_JOIN",i[i.SOCKETS_LEAVE=5]="SOCKETS_LEAVE",i[i.DISCONNECT_SOCKETS=6]="DISCONNECT_SOCKETS",i[i.FETCH_SOCKETS=7]="FETCH_SOCKETS",i[i.FETCH_SOCKETS_RESPONSE=8]="FETCH_SOCKETS_RESPONSE",i[i.SERVER_SIDE_EMIT=9]="SERVER_SIDE_EMIT",i[i.SERVER_SIDE_EMIT_RESPONSE=10]="SERVER_SIDE_EMIT_RESPONSE",i[i.BROADCAST_CLIENT_COUNT=11]="BROADCAST_CLIENT_COUNT",i[i.BROADCAST_ACK=12]="BROADCAST_ACK",i[i.ADAPTER_CLOSE=13]="ADAPTER_CLOSE"})(ii=bn.MessageType||(bn.MessageType={}));function Gc(i){return{rooms:[...i.rooms],except:[...i.except],flags:i.flags}}function ux(i){return{rooms:new Set(i.rooms),except:new Set(i.except),flags:i.flags}}class FJ extends zS.Adapter{constructor(i){super(i);this.requests=new Map,this.ackRequests=new Map,this.uid=Qx()}onMessage(i,o){if(i.uid===this.uid)return ei("[%s] ignore message from self",this.uid);switch(ei("[%s] new event of type %d from %s",this.uid,i.type,i.uid),i.type){case ii.BROADCAST:{if(i.data.requestId!==void 0)super.broadcastWithAck(i.data.packet,ux(i.data.opts),(p)=>{ei("[%s] waiting for %d client acknowledgements",this.uid,p),this.publishResponse(i.uid,{type:ii.BROADCAST_CLIENT_COUNT,data:{requestId:i.data.requestId,clientCount:p}})},(p)=>{ei("[%s] received acknowledgement with value %j",this.uid,p),this.publishResponse(i.uid,{type:ii.BROADCAST_ACK,data:{requestId:i.data.requestId,packet:p}})});else{let p=i.data.packet,c=ux(i.data.opts);this.addOffsetIfNecessary(p,c,o),super.broadcast(p,c)}break}case ii.SOCKETS_JOIN:super.addSockets(ux(i.data.opts),i.data.rooms);break;case ii.SOCKETS_LEAVE:super.delSockets(ux(i.data.opts),i.data.rooms);break;case ii.DISCONNECT_SOCKETS:super.disconnectSockets(ux(i.data.opts),i.data.close);break;case ii.FETCH_SOCKETS:{ei("[%s] calling fetchSockets with opts %j",this.uid,i.data.opts),super.fetchSockets(ux(i.data.opts)).then((n)=>{this.publishResponse(i.uid,{type:ii.FETCH_SOCKETS_RESPONSE,data:{requestId:i.data.requestId,sockets:n.map((p)=>{let c=p.handshake,{sessionStore:x}=c,T=MS(c,["sessionStore"]);return{id:p.id,handshake:T,rooms:[...p.rooms],data:p.data}})}})});break}case ii.SERVER_SIDE_EMIT:{let n=i.data.packet;if(i.data.requestId===void 0){this.nsp._onServerSideEmit(n);return}let c=!1,x=(T)=>{if(c)return;c=!0,ei("[%s] calling acknowledgement with %j",this.uid,T),this.publishResponse(i.uid,{type:ii.SERVER_SIDE_EMIT_RESPONSE,data:{requestId:i.data.requestId,packet:T}})};this.nsp._onServerSideEmit([...n,x]);break}case ii.BROADCAST_CLIENT_COUNT:case ii.BROADCAST_ACK:case ii.FETCH_SOCKETS_RESPONSE:case ii.SERVER_SIDE_EMIT_RESPONSE:this.onResponse(i);break;default:ei("[%s] unknown message type: %s",this.uid,i.type)}}onResponse(i){var o,n;let p=i.data.requestId;switch(ei("[%s] received response %s to request %s",this.uid,i.type,p),i.type){case ii.BROADCAST_CLIENT_COUNT:{(o=this.ackRequests.get(p))===null||o===void 0||o.clientCountCallback(i.data.clientCount);break}case ii.BROADCAST_ACK:{(n=this.ackRequests.get(p))===null||n===void 0||n.ack(i.data.packet);break}case ii.FETCH_SOCKETS_RESPONSE:{let c=this.requests.get(p);if(!c)return;if(c.current++,i.data.sockets.forEach((x)=>c.responses.push(x)),c.current===c.expected)clearTimeout(c.timeout),c.resolve(c.responses),this.requests.delete(p);break}case ii.SERVER_SIDE_EMIT_RESPONSE:{let c=this.requests.get(p);if(!c)return;if(c.current++,c.responses.push(i.data.packet),c.current===c.expected)clearTimeout(c.timeout),c.resolve(null,c.responses),this.requests.delete(p);break}default:ei("[%s] unknown response type: %s",this.uid,i.type)}}async broadcast(i,o){var n;if(!((n=o.flags)===null||n===void 0?void 0:n.local))try{let c=await this.publishAndReturnOffset({type:ii.BROADCAST,data:{packet:i,opts:Gc(o)}});this.addOffsetIfNecessary(i,o,c)}catch(c){return ei("[%s] error while broadcasting message: %s",this.uid,c.message)}super.broadcast(i,o)}addOffsetIfNecessary(i,o,n){var p;if(!this.nsp.server.opts.connectionStateRecovery)return;let c=i.type===2,x=i.id===void 0,T=((p=o.flags)===null||p===void 0?void 0:p.volatile)===void 0;if(c&&x&&T)i.data.push(n)}broadcastWithAck(i,o,n,p){var c;if(!((c=o===null||o===void 0?void 0:o.flags)===null||c===void 0?void 0:c.local)){let T=Qx();this.ackRequests.set(T,{clientCountCallback:n,ack:p}),this.publish({type:ii.BROADCAST,data:{packet:i,requestId:T,opts:Gc(o)}}),setTimeout(()=>{this.ackRequests.delete(T)},o.flags.timeout)}super.broadcastWithAck(i,o,n,p)}async addSockets(i,o){var n;if(!((n=i.flags)===null||n===void 0?void 0:n.local))try{await this.publishAndReturnOffset({type:ii.SOCKETS_JOIN,data:{opts:Gc(i),rooms:o}})}catch(c){ei("[%s] error while publishing message: %s",this.uid,c.message)}super.addSockets(i,o)}async delSockets(i,o){var n;if(!((n=i.flags)===null||n===void 0?void 0:n.local))try{await this.publishAndReturnOffset({type:ii.SOCKETS_LEAVE,data:{opts:Gc(i),rooms:o}})}catch(c){ei("[%s] error while publishing message: %s",this.uid,c.message)}super.delSockets(i,o)}async disconnectSockets(i,o){var n;if(!((n=i.flags)===null||n===void 0?void 0:n.local))try{await this.publishAndReturnOffset({type:ii.DISCONNECT_SOCKETS,data:{opts:Gc(i),close:o}})}catch(c){ei("[%s] error while publishing message: %s",this.uid,c.message)}super.disconnectSockets(i,o)}async fetchSockets(i){var o;let[n,p]=await Promise.all([super.fetchSockets(i),this.serverCount()]),c=p-1;if(((o=i.flags)===null||o===void 0?void 0:o.local)||c<=0)return n;let x=Qx();return new Promise((T,m)=>{let f=setTimeout(()=>{let $=this.requests.get(x);if($)m(new Error(`timeout reached: only ${$.current} responses received out of ${$.expected}`)),this.requests.delete(x)},i.flags.timeout||c1),F={type:ii.FETCH_SOCKETS,resolve:T,timeout:f,current:0,expected:c,responses:n};this.requests.set(x,F),this.publish({type:ii.FETCH_SOCKETS,data:{opts:Gc(i),requestId:x}})})}async serverSideEmit(i){if(typeof i[i.length-1]!=="function")return this.publish({type:ii.SERVER_SIDE_EMIT,data:{packet:i}});let n=i.pop(),p=await this.serverCount()-1;if(ei('[%s] waiting for %d responses to "serverSideEmit" request',this.uid,p),p<=0)return n(null,[]);let c=Qx(),x=setTimeout(()=>{let m=this.requests.get(c);if(m)n(new Error(`timeout reached: only ${m.current} responses received out of ${m.expected}`),m.responses),this.requests.delete(c)},c1),T={type:ii.SERVER_SIDE_EMIT,resolve:n,timeout:x,current:0,expected:p,responses:[]};this.requests.set(c,T),this.publish({type:ii.SERVER_SIDE_EMIT,data:{requestId:c,packet:i}})}publish(i){this.publishAndReturnOffset(i).catch((o)=>{ei("[%s] error while publishing message: %s",this.uid,o)})}publishAndReturnOffset(i){return i.uid=this.uid,i.nsp=this.nsp.name,this.doPublish(i)}publishResponse(i,o){o.uid=this.uid,o.nsp=this.nsp.name,this.doPublishResponse(i,o).catch((n)=>{ei("[%s] error while publishing response: %s",this.uid,n)})}}bn.ClusterAdapter=FJ;class KR extends FJ{constructor(i,o){super(i);this.nodesMap=new Map,this.customRequests=new Map,this._opts=Object.assign({heartbeatInterval:5000,heartbeatTimeout:1e4},o),this.cleanupTimer=setInterval(()=>{let n=Date.now();this.nodesMap.forEach((p,c)=>{if(n-p>this._opts.heartbeatTimeout)ei("[%s] node %s seems down",this.uid,c),this.removeNode(c)})},1000)}init(){this.publish({type:ii.INITIAL_HEARTBEAT})}scheduleHeartbeat(){if(this.heartbeatTimer)this.heartbeatTimer.refresh();else this.heartbeatTimer=setTimeout(()=>{this.publish({type:ii.HEARTBEAT})},this._opts.heartbeatInterval)}close(){if(this.publish({type:ii.ADAPTER_CLOSE}),clearTimeout(this.heartbeatTimer),this.cleanupTimer)clearInterval(this.cleanupTimer)}onMessage(i,o){if(i.uid===this.uid)return ei("[%s] ignore message from self",this.uid);if(i.uid&&i.uid!==VS)this.nodesMap.set(i.uid,Date.now());switch(ei("[%s] new event of type %d from %s",this.uid,i.type,i.uid),i.type){case ii.INITIAL_HEARTBEAT:this.publish({type:ii.HEARTBEAT});break;case ii.HEARTBEAT:break;case ii.ADAPTER_CLOSE:this.removeNode(i.uid);break;default:super.onMessage(i,o)}}serverCount(){return Promise.resolve(1+this.nodesMap.size)}publish(i){return this.scheduleHeartbeat(),super.publish(i)}async serverSideEmit(i){if(typeof i[i.length-1]!=="function")return this.publish({type:ii.SERVER_SIDE_EMIT,data:{packet:i}});let n=i.pop(),p=this.nodesMap.size;if(ei('[%s] waiting for %d responses to "serverSideEmit" request',this.uid,p),p<=0)return n(null,[]);let c=Qx(),x=setTimeout(()=>{let m=this.customRequests.get(c);if(m)n(new Error(`timeout reached: missing ${m.missingUids.size} responses`),m.responses),this.customRequests.delete(c)},c1),T={type:ii.SERVER_SIDE_EMIT,resolve:n,timeout:x,missingUids:new Set([...this.nodesMap.keys()]),responses:[]};this.customRequests.set(c,T),this.publish({type:ii.SERVER_SIDE_EMIT,data:{requestId:c,packet:i}})}async fetchSockets(i){var o;let[n,p]=await Promise.all([super.fetchSockets({rooms:i.rooms,except:i.except,flags:{local:!0}}),this.serverCount()]),c=p-1;if(((o=i.flags)===null||o===void 0?void 0:o.local)||c<=0)return n;let x=Qx();return new Promise((T,m)=>{let f=setTimeout(()=>{let $=this.customRequests.get(x);if($)m(new Error(`timeout reached: missing ${$.missingUids.size} responses`)),this.customRequests.delete(x)},i.flags.timeout||c1),F={type:ii.FETCH_SOCKETS,resolve:T,timeout:f,missingUids:new Set([...this.nodesMap.keys()]),responses:n};this.customRequests.set(x,F),this.publish({type:ii.FETCH_SOCKETS,data:{opts:Gc(i),requestId:x}})})}onResponse(i){let o=i.data.requestId;switch(ei("[%s] received response %s to request %s",this.uid,i.type,o),i.type){case ii.FETCH_SOCKETS_RESPONSE:{let n=this.customRequests.get(o);if(!n)return;if(i.data.sockets.forEach((p)=>n.responses.push(p)),n.missingUids.delete(i.uid),n.missingUids.size===0)clearTimeout(n.timeout),n.resolve(n.responses),this.customRequests.delete(o);break}case ii.SERVER_SIDE_EMIT_RESPONSE:{let n=this.customRequests.get(o);if(!n)return;if(n.responses.push(i.data.packet),n.missingUids.delete(i.uid),n.missingUids.size===0)clearTimeout(n.timeout),n.resolve(null,n.responses),this.customRequests.delete(o);break}default:super.onResponse(i)}}removeNode(i){this.customRequests.forEach((o,n)=>{if(o.missingUids.delete(i),o.missingUids.size===0){if(clearTimeout(o.timeout),o.type===ii.FETCH_SOCKETS)o.resolve(o.responses);else if(o.type===ii.SERVER_SIDE_EMIT)o.resolve(null,o.responses);this.customRequests.delete(n)}}),this.nodesMap.delete(i)}}bn.ClusterAdapterWithHeartbeat=KR});var x1=P((Kc)=>{Object.defineProperty(Kc,"__esModule",{value:!0});Kc.MessageType=Kc.ClusterAdapterWithHeartbeat=Kc.ClusterAdapter=Kc.SessionAwareAdapter=Kc.Adapter=void 0;var UR=fJ();Object.defineProperty(Kc,"Adapter",{enumerable:!0,get:function(){return UR.Adapter}});Object.defineProperty(Kc,"SessionAwareAdapter",{enumerable:!0,get:function(){return UR.SessionAwareAdapter}});var $J=HR();Object.defineProperty(Kc,"ClusterAdapter",{enumerable:!0,get:function(){return $J.ClusterAdapter}});Object.defineProperty(Kc,"ClusterAdapterWithHeartbeat",{enumerable:!0,get:function(){return $J.ClusterAdapterWithHeartbeat}});Object.defineProperty(Kc,"MessageType",{enumerable:!0,get:function(){return $J.MessageType}})});var uR=P((Vx)=>{var ES=Vx&&Vx.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Vx,"__esModule",{value:!0});Vx.ParentNamespace=void 0;var ZR=cJ(),OS=x1(),_S=ES(Go()),MR=_S.default("socket.io:parent-namespace");class T1 extends ZR.Namespace{constructor(i){super(i,"/_"+T1.count++);this.children=new Set}_initAdapter(){this.adapter=new zR(this)}emit(i,...o){return this.children.forEach((n)=>{n.emit(i,...o)}),!0}createChild(i){MR("creating child namespace %s",i);let o=new ZR.Namespace(this.server,i);if(this._fns.forEach((n)=>o.use(n)),this.listeners("connect").forEach((n)=>o.on("connect",n)),this.listeners("connection").forEach((n)=>o.on("connection",n)),this.children.add(o),this.server._opts.cleanupEmptyChildNamespaces){let n=o._remove;o._remove=(p)=>{if(n.call(o,p),o.sockets.size===0)MR("closing child namespace %s",i),o.adapter.close(),this.server._nsps.delete(o.name),this.children.delete(o)}}return this.server._nsps.set(i,o),this.server.sockets.emitReserved("new_namespace",o),o}fetchSockets(){throw new Error("fetchSockets() is not supported on parent namespaces")}}Vx.ParentNamespace=T1;T1.count=0;class zR extends OS.Adapter{broadcast(i,o){this.nsp.children.forEach((n)=>{n.adapter.broadcast(i,o)})}}});var _R=P((Uc)=>{var LS=Uc&&Uc.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Uc,"__esModule",{value:!0});Uc.patchAdapter=yS;Uc.restoreAdapter=DS;Uc.serveFile=BS;var Hc=x1(),QR=Hi("fs"),CS=LS(Go()),m1=CS.default("socket.io:adapter-uws"),JJ="\x1F",{addAll:SR,del:ER,broadcast:OR}=Hc.Adapter.prototype;function yS(i){Hc.Adapter.prototype.addAll=function(o,n){let p=!this.sids.has(o);SR.call(this,o,n);let c=this.nsp.sockets.get(o)||this.nsp._preConnectSockets.get(o);if(!c)return;if(c.conn.transport.name==="websocket"){VR(this.nsp.name,c,p,n);return}if(p)c.conn.on("upgrade",()=>{let x=this.sids.get(o);if(x)VR(this.nsp.name,c,p,x)})},Hc.Adapter.prototype.del=function(o,n){ER.call(this,o,n);let p=this.nsp.sockets.get(o)||this.nsp._preConnectSockets.get(o);if(p&&p.conn.transport.name==="websocket"){let c=p.conn.id,x=p.conn.transport.socket,T=`${this.nsp.name}${JJ}${n}`;m1("unsubscribe connection %s from topic %s",c,T),x.unsubscribe(T)}},Hc.Adapter.prototype.broadcast=function(o,n){if(!(n.rooms.size<=1&&n.except.size===0)){OR.call(this,o,n);return}let c=n.flags||{},x={preEncoded:!0,volatile:c.volatile,compress:c.compress};o.nsp=this.nsp.name;let T=this.encoder.encode(o),m=n.rooms.size===0?this.nsp.name:`${this.nsp.name}${JJ}${n.rooms.keys().next().value}`;m1("fast publish to %s",m),T.forEach((f)=>{let F=typeof f!=="string";i.publish(m,F?f:"4"+f,F)}),this.apply(n,(f)=>{if(f.conn.transport.name!=="websocket")f.client.writeToEngine(T,x)})}}function VR(i,o,n,p){let c=o.conn.id,x=o.conn.transport.socket;if(n)m1("subscribe connection %s to topic %s",c,i),x.subscribe(i);p.forEach((T)=>{let m=`${i}${JJ}${T}`;m1("subscribe connection %s to topic %s",c,m),x.subscribe(m)})}function DS(){Hc.Adapter.prototype.addAll=SR,Hc.Adapter.prototype.del=ER,Hc.Adapter.prototype.broadcast=OR}var IS=(i)=>{let{buffer:o,byteOffset:n,byteLength:p}=i;return o.slice(n,n+p)};function BS(i,o){let{size:n}=QR.statSync(o),p=QR.createReadStream(o),c=()=>!p.destroyed&&p.destroy(),x=(m)=>{throw c(),m},T=(m)=>{let f=IS(m);i.cork(()=>{let F=i.getWriteOffset(),[$,J]=i.tryEnd(f,n);if(!J&&!$)p.pause(),i.onWritable((A)=>{let[X,Y]=i.tryEnd(f.slice(A-F),n);if(!Y&&X)p.resume();return X})})};i.onAborted(c),p.on("data",T).on("error",x).on("end",c)}});var LR=P((jpi,NS)=>{NS.exports={name:"socket.io",version:"4.8.1",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"},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 --require ts-node/register --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.3.2","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 PR=P((Do,dT)=>{var __dirname="/home/runner/work/wayforge/wayforge/node_modules/.pnpm/socket.io@4.8.1/node_modules/socket.io/dist",bS=Do&&Do.__createBinding||(Object.create?function(i,o,n,p){if(p===void 0)p=n;var c=Object.getOwnPropertyDescriptor(o,n);if(!c||("get"in c?!o.__esModule:c.writable||c.configurable))c={enumerable:!0,get:function(){return o[n]}};Object.defineProperty(i,p,c)}:function(i,o,n,p){if(p===void 0)p=n;i[p]=o[n]}),jS=Do&&Do.__setModuleDefault||(Object.create?function(i,o){Object.defineProperty(i,"default",{enumerable:!0,value:o})}:function(i,o){i.default=o}),PS=Do&&Do.__importStar||function(i){if(i&&i.__esModule)return i;var o={};if(i!=null){for(var n in i)if(n!=="default"&&Object.prototype.hasOwnProperty.call(i,n))bS(o,i,n)}return jS(o,i),o},bR=Do&&Do.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Do,"__esModule",{value:!0});Do.Namespace=Do.Socket=Do.Server=void 0;var aS=Hi("http"),lS=Hi("fs"),AJ=Hi("zlib"),qS=B0(),f1=Hi("stream"),CR=Hi("path"),yR=E9(),kS=t9(),DR=Hi("events"),wJ=cJ();Object.defineProperty(Do,"Namespace",{enumerable:!0,get:function(){return wJ.Namespace}});var hS=uR(),IR=x1(),gS=PS(sT()),sS=bR(Go()),jR=pJ();Object.defineProperty(Do,"Socket",{enumerable:!0,get:function(){return jR.Socket}});var tS=o1(),vJ=_R(),dS=bR(h$()),on=sS.default("socket.io:server"),BR=LR().version,NR=/\.map/;class Sx extends tS.StrictEventEmitter{constructor(i,o={}){super();if(this._nsps=new Map,this.parentNsps=new Map,this.parentNamespacesFromRegExp=new Map,typeof i==="object"&&i instanceof Object&&!i.listen)o=i,i=void 0;if(this.path(o.path||"/socket.io"),this.connectTimeout(o.connectTimeout||45000),this.serveClient(o.serveClient!==!1),this._parser=o.parser||gS,this.encoder=new this._parser.Encoder,this.opts=o,o.connectionStateRecovery)o.connectionStateRecovery=Object.assign({maxDisconnectionDuration:120000,skipMiddlewares:!0},o.connectionStateRecovery),this.adapter(o.adapter||IR.SessionAwareAdapter);else this.adapter(o.adapter||IR.Adapter);if(o.cleanupEmptyChildNamespaces=!!o.cleanupEmptyChildNamespaces,this.sockets=this.of("/"),i||typeof i=="number")this.attach(i);if(this.opts.cors)this._corsMiddleware=dS.default(this.opts.cors)}get _opts(){return this.opts}serveClient(i){if(!arguments.length)return this._serveClient;return this._serveClient=i,this}_checkNamespace(i,o,n){if(this.parentNsps.size===0)return n(!1);let p=this.parentNsps.keys(),c=()=>{let x=p.next();if(x.done)return n(!1);x.value(i,o,(T,m)=>{if(T||!m)return c();if(this._nsps.has(i))return on("dynamic namespace %s already exists",i),n(this._nsps.get(i));let f=this.parentNsps.get(x.value).createChild(i);on("dynamic namespace %s was created",i),n(f)})};c()}path(i){if(!arguments.length)return this._path;this._path=i.replace(/\/$/,"");let o=this._path.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");return this.clientPathRegex=new RegExp("^"+o+"/socket\\.io(\\.msgpack|\\.esm)?(\\.min)?\\.js(\\.map)?(?:\\?|$)"),this}connectTimeout(i){if(i===void 0)return this._connectTimeout;return this._connectTimeout=i,this}adapter(i){if(!arguments.length)return this._adapter;this._adapter=i;for(let o of this._nsps.values())o._initAdapter();return this}listen(i,o={}){return this.attach(i,o)}attach(i,o={}){if(typeof i=="function")throw new Error("You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.");if(Number(i)==i)i=Number(i);if(typeof i=="number"){on("creating http server and binding to %d",i);let n=i;i=aS.createServer((p,c)=>{c.writeHead(404),c.end()}),i.listen(n)}return Object.assign(o,this.opts),o.path=o.path||this._path,this.initEngine(i,o),this}attachApp(i,o={}){Object.assign(o,this.opts),o.path=o.path||this._path,on("creating uWebSockets.js-based engine with opts %j",o);let n=new yR.uServer(o);if(n.attach(i,o),this.bind(n),this._serveClient)i.get(`${this._path}/*`,(p,c)=>{if(!this.clientPathRegex.test(c.getUrl())){c.setYield(!0);return}let x=c.getUrl().replace(this._path,"").replace(/\?.*$/,"").replace(/^\//,""),T=NR.test(x),m=T?"map":"source",f='"'+BR+'"',F="W/"+f,$=c.getHeader("if-none-match");if($){if(f===$||F===$){on("serve client %s 304",m),p.writeStatus("304 Not Modified"),p.end();return}}on("serve client %s",m),p.writeHeader("cache-control","public, max-age=0"),p.writeHeader("content-type","application/"+(T?"json":"javascript")+"; charset=utf-8"),p.writeHeader("etag",f);let J=CR.join(__dirname,"../client-dist/",x);vJ.serveFile(p,J)});vJ.patchAdapter(i)}initEngine(i,o){if(on("creating engine.io instance with opts %j",o),this.eio=yR.attach(i,o),this._serveClient)this.attachServe(i);this.httpServer=i,this.bind(this.eio)}attachServe(i){on("attaching client serving req handler");let o=i.listeners("request").slice(0);i.removeAllListeners("request"),i.on("request",(n,p)=>{if(this.clientPathRegex.test(n.url))if(this._corsMiddleware)this._corsMiddleware(n,p,()=>{this.serve(n,p)});else this.serve(n,p);else for(let c=0;c<o.length;c++)o[c].call(i,n,p)})}serve(i,o){let n=i.url.replace(this._path,"").replace(/\?.*$/,""),p=NR.test(n),c=p?"map":"source",x='"'+BR+'"',T="W/"+x,m=i.headers["if-none-match"];if(m){if(x===m||T===m){on("serve client %s 304",c),o.writeHead(304),o.end();return}}on("serve client %s",c),o.setHeader("Cache-Control","public, max-age=0"),o.setHeader("Content-Type","application/"+(p?"json":"javascript")+"; charset=utf-8"),o.setHeader("ETag",x),Sx.sendFile(n,i,o)}static sendFile(i,o,n){let p=lS.createReadStream(CR.join(__dirname,"../client-dist/",i)),c=qS(o).encodings(["br","gzip","deflate"]),x=(T)=>{if(T)n.end()};switch(c){case"br":n.writeHead(200,{"content-encoding":"br"}),f1.pipeline(p,AJ.createBrotliCompress(),n,x);break;case"gzip":n.writeHead(200,{"content-encoding":"gzip"}),f1.pipeline(p,AJ.createGzip(),n,x);break;case"deflate":n.writeHead(200,{"content-encoding":"deflate"}),f1.pipeline(p,AJ.createDeflate(),n,x);break;default:n.writeHead(200),f1.pipeline(p,n,x)}}bind(i){return this.engine=i,this.engine.on("connection",this.onconnection.bind(this)),this}onconnection(i){on("incoming connection with id %s",i.id);let o=new kS.Client(this,i);if(i.protocol===3)o.connect("/");return this}of(i,o){if(typeof i==="function"||i instanceof RegExp){let p=new hS.ParentNamespace(this);if(on("initializing parent namespace %s",p.name),typeof i==="function")this.parentNsps.set(i,p);else this.parentNsps.set((c,x,T)=>T(null,i.test(c)),p),this.parentNamespacesFromRegExp.set(i,p);if(o)p.on("connect",o);return p}if(String(i)[0]!=="/")i="/"+i;let n=this._nsps.get(i);if(!n){for(let[p,c]of this.parentNamespacesFromRegExp)if(p.test(i))return on("attaching namespace %s to parent namespace %s",i,p),c.createChild(i);if(on("initializing namespace %s",i),n=new wJ.Namespace(this,i),this._nsps.set(i,n),i!=="/")this.sockets.emitReserved("new_namespace",n)}if(o)n.on("connect",o);return n}async close(i){if(await Promise.allSettled([...this._nsps.values()].map(async(o)=>{o.sockets.forEach((n)=>{n._onclose("server shutting down")}),await o.adapter.close()})),this.engine.close(),vJ.restoreAdapter(),this.httpServer)this.httpServer.close(i);else i&&i()}use(i){return this.sockets.use(i),this}to(i){return this.sockets.to(i)}in(i){return this.sockets.in(i)}except(i){return this.sockets.except(i)}send(...i){return this.sockets.emit("message",...i),this}write(...i){return this.sockets.emit("message",...i),this}serverSideEmit(i,...o){return this.sockets.serverSideEmit(i,...o)}serverSideEmitWithAck(i,...o){return this.sockets.serverSideEmitWithAck(i,...o)}allSockets(){return this.sockets.allSockets()}compress(i){return this.sockets.compress(i)}get volatile(){return this.sockets.volatile}get local(){return this.sockets.local}timeout(i){return this.sockets.timeout(i)}fetchSockets(){return this.sockets.fetchSockets()}socketsJoin(i){return this.sockets.socketsJoin(i)}socketsLeave(i){return this.sockets.socketsLeave(i)}disconnectSockets(i=!1){return this.sockets.disconnectSockets(i)}}Do.Server=Sx;var rS=Object.keys(DR.EventEmitter.prototype).filter(function(i){return typeof DR.EventEmitter.prototype[i]==="function"});rS.forEach(function(i){Sx.prototype[i]=function(){return this.sockets[i].apply(this.sockets,arguments)}});dT.exports=(i,o)=>new Sx(i,o);dT.exports.Server=Sx;dT.exports.Namespace=wJ.Namespace;dT.exports.Socket=jR.Socket});import{createHash as yY}from"crypto";import{createServer as FO}from"http";import{createServer as $O}from"https";var Kp=(i)=>Array.isArray(i)?i:[i],$A=(i,o)=>{let n=[[],[]];for(let p of i)if(o(p))n[0].push(p);else n[1].push(p);return n},$m=Array,op=(i,o)=>i.includes(o),JA=(i,o=0)=>[...new Array(i)].map((n,p)=>p+o),Ai=(i,o,n)=>{if(i===void 0)return o===void 0?[]:Array.isArray(o)?o:[o];if(n?.prepend)if(Array.isArray(o))i.unshift(...o);else i.unshift(o);else if(Array.isArray(o))i.push(...o);else i.push(o);return i},np=(i,o)=>{if(o===void 0||o===null)return i??[];if(i===void 0||i===null)return Kp(o);return i.concat(o)},AA=(...i)=>i.reduce(np,[]),ln=(i,o,n)=>{if(i===void 0)return Array.isArray(o)?o:[o];let p=n?.isEqual??((c,x)=>c===x);return Kp(o).forEach((c)=>{if(!i.some((x)=>p(x,c)))i.push(c)}),i},vA=(i,o)=>i.reduce((n,p)=>{let c=p[o];return n[c]=Ai(n[c],p),n},{}),pp=(i,o,n)=>i.length===o.length&&i.every(n?.isEqual?(p,c)=>n.isEqual(p,o[c]):(p,c)=>p===o[c]);var qo=(i,o)=>Fo(i)===o,Fo=(i)=>{let o=typeof i;return o==="object"?i===null?"null":"object":o==="function"?"object":o},ko={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},wA={...ko,function:"a function"};class XA extends Error{}var Xi=(i)=>cp(i,XA),cp=(i,o=Error)=>{throw new o(i)};class bx extends Error{name="ParseError"}var U=(i)=>cp(i,bx),Sn=(i)=>` ${i}`;var pi=(i,o)=>{let n={},p=Array.isArray(i),c=!1;return Object.entries(i).forEach((x,T)=>{let m=p?o(T,x[1]):o(...x,T);c||=typeof m[0]==="number",(Array.isArray(m[0])||m.length===0?m:[m]).forEach(([F,$])=>{if(typeof F==="object")n[F.group]=Ai(n[F.group],$);else n[F]=$})}),c?Object.values(n):n};var y1=Object.entries;var di=(i,o)=>(i in o),Oc=(i,o)=>(o in i);class D1{constructor(i){Object.assign(this,i)}}var WA=class{};class jx extends WA{}var DG=(i,o)=>{let n={},p={},c;for(c in i)if(c in o)n[c]=i[c];else p[c]=i[c];return[n,p]};var RA=(i,o)=>DG(i,o)[1],qn=(i)=>Object.keys(i).length===0,Px=(i)=>[...Object.entries(i),...Object.getOwnPropertySymbols(i).map((o)=>[o,i[o]])],YA=(i,o)=>Object.defineProperties(i,Object.getOwnPropertyDescriptors(o)),GA=(i)=>{let o=Object.keys(i).sort(),n={};for(let p=0;p<o.length;p++)n[o[p]]=i[o[p]];return n};var nn=Sn("represents an uninitialized value"),KA=(i)=>Object.values(i).filter((o)=>{if(typeof o==="number")return!0;return typeof i[o]!=="number"});var I1={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},B1=globalThis.File??Blob,N1={ArrayBuffer,Blob,File:B1,FormData,Headers,Request,Response,URL},IG={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},hp={...I1,...N1,...IG,String,Number,Boolean},ax=(i)=>{let o=Object.getPrototypeOf(i);while(o?.constructor&&(!di(o.constructor.name,hp)||!(i instanceof hp[o.constructor.name])))o=Object.getPrototypeOf(o);let n=o?.constructor?.name;if(n===void 0||n==="Object")return;return n},lx=(i)=>typeof i==="object"&&i!==null?ax(i)??"object":Fo(i);var Oi=Array.isArray,BG={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},NG={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},bG={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},HA={...BG,...NG,...bG},qx=(i)=>{let o=Object(i).name??null;return o&&di(o,hp)&&hp[o]===i?o:null};var b1=(i,o)=>{let n=i.prototype;while(n!==null){if(n===o.prototype)return!0;n=Object.getPrototypeOf(n)}return!1};var UA=(i)=>ZA(i,new Map),ZA=(i,o)=>{if(typeof i!=="object"||i===null)return i;if(o?.has(i))return o.get(i);let n=qx(i.constructor);if(n==="Date")return new Date(i.getTime());if(n&&n!=="Array")return i;let p=Array.isArray(i)?i.slice():Object.create(Object.getPrototypeOf(i)),c=Object.getOwnPropertyDescriptors(i);if(o){o.set(i,p);for(let x in c){let T=c[x];if("get"in T||"set"in T)continue;T.value=ZA(T.value,o)}}return Object.defineProperties(p,c),p};var jG=(i)=>{let o=nn;return()=>o===nn?o=i():o},Hp=(i)=>typeof i==="function"&&i.length===0;var MA=class extends Function{constructor(...i){let o=i.slice(0,-1),n=i.at(-1);try{super(...o,n)}catch(p){return Xi(`Encountered an unexpected error while compiling your definition:
|
|
47
|
+
`+p)}i.destroy()}var hT=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];function XV(i){if(i+="",i.length<1)return!1;if(!hT[i.charCodeAt(0)])return ci('invalid header, index 0, char "%s"',i.charCodeAt(0)),!0;if(i.length<2)return!1;if(!hT[i.charCodeAt(1)])return ci('invalid header, index 1, char "%s"',i.charCodeAt(1)),!0;if(i.length<3)return!1;if(!hT[i.charCodeAt(2)])return ci('invalid header, index 2, char "%s"',i.charCodeAt(2)),!0;if(i.length<4)return!1;if(!hT[i.charCodeAt(3)])return ci('invalid header, index 3, char "%s"',i.charCodeAt(3)),!0;for(let o=4;o<i.length;++o)if(!hT[i.charCodeAt(o)])return ci('invalid header, index "%i", char "%s"',o,i.charCodeAt(o)),!0;return!1}});var v9=P((J9)=>{Object.defineProperty(J9,"__esModule",{value:!0});J9.Polling=void 0;var RV=Rc(),F9=Hi("zlib"),YV=B0(),GV=Go(),Mn=GV.default("engine:polling"),KV={gzip:F9.createGzip,deflate:F9.createDeflate};class $9 extends RV.Transport{constructor(i){super(i);this.closeTimeout=30000}get name(){return"polling"}onRequest(i){let o=i.res;if(i.res=null,i.getMethod()==="get")this.onPollRequest(i,o);else if(i.getMethod()==="post")this.onDataRequest(i,o);else o.writeStatus("500 Internal Server Error"),o.end()}onPollRequest(i,o){if(this.req){Mn("request overlap"),this.onError("overlap from client"),o.writeStatus("500 Internal Server Error"),o.end();return}Mn("setting request"),this.req=i,this.res=o;let n=()=>{this.writable=!1,this.onError("poll connection closed prematurely")},p=()=>{this.req=this.res=null};if(i.cleanup=p,o.onAborted(n),this.writable=!0,this.emit("ready"),this.writable&&this.shouldClose)Mn("triggering empty send to append close packet"),this.send([{type:"noop"}])}onDataRequest(i,o){if(this.dataReq){this.onError("data request overlap from client"),o.writeStatus("500 Internal Server Error"),o.end();return}let n=Number(i.headers["content-length"]);if(!n){this.onError("content-length header required"),o.writeStatus("411 Length Required").end();return}if(n>this.maxHttpBufferSize){this.onError("payload too large"),o.writeStatus("413 Payload Too Large").end();return}if(i.headers["content-type"]==="application/octet-stream"&&this.protocol===4)return this.onError("invalid content");this.dataReq=i,this.dataRes=o;let c,x=0,T={"Content-Type":"text/html"};this.headers(i,T);for(let f in T)o.writeHeader(f,String(T[f]));let m=(f)=>{this.onData(f.toString()),this.onDataRequestCleanup(),o.cork(()=>{o.end("ok")})};o.onAborted(()=>{this.onDataRequestCleanup(),this.onError("data request connection closed prematurely")}),o.onData((f,F)=>{let $=x+f.byteLength;if($>n){this.onError("content-length mismatch"),o.close();return}if(!c){if(F){m(Buffer.from(f));return}c=Buffer.allocUnsafe(n)}if(Buffer.from(f).copy(c,x),F){if($!=n){this.onError("content-length mismatch"),o.writeStatus("400 Content-Length Mismatch").end(),this.onDataRequestCleanup();return}m(c);return}x=$})}onDataRequestCleanup(){this.dataReq=this.dataRes=null}onData(i){Mn('received "%s"',i);let o=(n)=>{if(n.type==="close")return Mn("got xhr close packet"),this.onClose(),!1;this.onPacket(n)};if(this.protocol===3)this.parser.decodePayload(i,o);else this.parser.decodePayload(i).forEach(o)}onClose(){if(this.writable)this.send([{type:"noop"}]);super.onClose()}send(i){if(this.writable=!1,this.shouldClose)Mn("appending close packet to payload"),i.push({type:"close"}),this.shouldClose(),this.shouldClose=null;let o=(n)=>{let p=i.some((c)=>{return c.options&&c.options.compress});this.write(n,{compress:p})};if(this.protocol===3)this.parser.encodePayload(i,this.supportsBinary,o);else this.parser.encodePayload(i,o)}write(i,o){Mn('writing "%s"',i),this.doWrite(i,o,()=>{this.req.cleanup(),this.emit("drain")})}doWrite(i,o,n){let p=typeof i==="string",x={"Content-Type":p?"text/plain; charset=UTF-8":"application/octet-stream"},T=(F)=>{this.headers(this.req,x),this.res.cork(()=>{Object.keys(x).forEach(($)=>{this.res.writeHeader($,String(x[$]))}),this.res.end(F)}),n()};if(!this.httpCompression||!o.compress){T(i);return}if((p?Buffer.byteLength(i):i.length)<this.httpCompression.threshold){T(i);return}let f=YV(this.req).encodings(["gzip","deflate"]);if(!f){T(i);return}this.compress(i,f,(F,$)=>{if(F){this.res.writeStatus("500 Internal Server Error"),this.res.end(),n(F);return}x["Content-Encoding"]=f,T($)})}compress(i,o,n){Mn("compressing");let p=[],c=0;KV[o](this.httpCompression).on("error",n).on("data",function(x){p.push(x),c+=x.length}).on("end",function(){n(null,Buffer.concat(p,c))}).end(i)}doClose(i){Mn("closing");let o,n=()=>{clearTimeout(o),i(),this.onClose()};if(this.writable)Mn("transport writable - closing right away"),this.send([{type:"close"}]),n();else if(this.discarded)Mn("transport discarded - closing right away"),n();else Mn("transport not writable - buffering orderly close"),this.shouldClose=n,o=setTimeout(n,this.closeTimeout)}headers(i,o){o=o||{};let n=i.headers["user-agent"];if(n&&(~n.indexOf(";MSIE")||~n.indexOf("Trident/")))o["X-XSS-Protection"]="0";return o["cache-control"]="no-store",this.emit("headers",o,i),o}}J9.Polling=$9});var Y9=P((W9)=>{Object.defineProperty(W9,"__esModule",{value:!0});W9.WebSocket=void 0;var HV=Rc(),UV=Go(),w9=UV.default("engine:ws");class X9 extends HV.Transport{constructor(i){super(i);this.writable=!1,this.perMessageDeflate=null}get name(){return"websocket"}get handlesUpgrades(){return!0}send(i){this.writable=!1;for(let o=0;o<i.length;o++){let n=i[o],p=o+1===i.length,c=(x)=>{let T=typeof x!=="string",m=this.perMessageDeflate&&Buffer.byteLength(x)>this.perMessageDeflate.threshold;if(w9('writing "%s"',x),this.socket.send(x,T,m),p)this.emit("drain"),this.writable=!0,this.emit("ready")};if(n.options&&typeof n.options.wsPreEncoded==="string")c(n.options.wsPreEncoded);else this.parser.encodePacket(n,this.supportsBinary,c)}}doClose(i){w9("closing"),i&&i(),this.socket.end()}}W9.WebSocket=X9});var K9=P((G9)=>{Object.defineProperty(G9,"__esModule",{value:!0});var ZV=v9(),MV=Y9();G9.default={polling:ZV.Polling,websocket:MV.WebSocket}});var z9=P((Z9)=>{Object.defineProperty(Z9,"__esModule",{value:!0});Z9.uServer=void 0;var uV=Go(),Yc=g$(),QV=K9(),ap=uV.default("engine:uws");class H9 extends Yc.BaseServer{init(){}cleanup(){}prepare(i,o){i.method=i.getMethod().toUpperCase(),i.url=i.getUrl();let n=new URLSearchParams(i.getQuery());i._query=Object.fromEntries(n.entries()),i.headers={},i.forEach((p,c)=>{i.headers[p]=c}),i.connection={remoteAddress:Buffer.from(o.getRemoteAddressAsText()).toString()},o.onAborted(()=>{ap("response has been aborted")})}createTransport(i,o){return new QV.default[i](o)}attach(i,o={}){let n=this._computePath(o);i.any(n,this.handleRequest.bind(this)).ws(n,{compression:o.compression,idleTimeout:o.idleTimeout,maxBackpressure:o.maxBackpressure,maxPayloadLength:this.opts.maxHttpBufferSize,upgrade:this.handleUpgrade.bind(this),open:(p)=>{let c=p.getUserData().transport;c.socket=p,c.writable=!0,c.emit("ready")},message:(p,c,x)=>{p.getUserData().transport.onData(x?c:Buffer.from(c).toString())},close:(p,c,x)=>{p.getUserData().transport.onClose(c,x)}})}_applyMiddlewares(i,o,n){if(this.middlewares.length===0)return n();i.res=new U9(o),super._applyMiddlewares(i,i.res,(p)=>{i.res.writeHead(),n(p)})}handleRequest(i,o){ap('handling "%s" http request "%s"',o.getMethod(),o.getUrl()),this.prepare(o,i),o.res=i;let n=(p,c)=>{if(p!==void 0){this.emit("connection_error",{req:o,code:p,message:Yc.Server.errorMessages[p],context:c}),this.abortRequest(o.res,p,c);return}if(o._query.sid)ap("setting new request for existing client"),this.clients[o._query.sid].transport.onRequest(o);else{let x=(T,m)=>this.abortRequest(i,T,m);this.handshake(o._query.transport,o,x)}};this._applyMiddlewares(o,i,(p)=>{if(p)n(Yc.Server.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"});else this.verify(o,!1,n)})}handleUpgrade(i,o,n){ap("on upgrade"),this.prepare(o,i),o.res=i;let p=async(c,x)=>{if(c!==void 0){this.emit("connection_error",{req:o,code:c,message:Yc.Server.errorMessages[c],context:x}),this.abortRequest(i,c,x);return}let T=o._query.sid,m;if(T){let f=this.clients[T];if(!f)return ap("upgrade attempt for closed client"),i.close();else if(f.upgrading)return ap("transport has already been trying to upgrade"),i.close();else if(f.upgraded)return ap("transport had already been upgraded"),i.close();else ap("upgrading existing transport"),m=this.createTransport(o._query.transport,o),f._maybeUpgrade(m)}else if(m=await this.handshake(o._query.transport,o,(f,F)=>this.abortRequest(i,f,F)),!m)return;o.res.writeStatus("101 Switching Protocols"),i.upgrade({transport:m},o.getHeader("sec-websocket-key"),o.getHeader("sec-websocket-protocol"),o.getHeader("sec-websocket-extensions"),n)};this._applyMiddlewares(o,i,(c)=>{if(c)p(Yc.Server.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"});else this.verify(o,!0,p)})}abortRequest(i,o,n){let p=o===Yc.Server.errors.FORBIDDEN?"403 Forbidden":"400 Bad Request",c=n&&n.message?n.message:Yc.Server.errorMessages[o];i.writeStatus(p),i.writeHeader("Content-Type","application/json"),i.end(JSON.stringify({code:o,message:c}))}}Z9.uServer=H9;class U9{constructor(i){this.res=i,this.statusWritten=!1,this.headers=[],this.isAborted=!1}set statusCode(i){if(!i)return;this.writeStatus(i===200?"200 OK":"204 No Content")}writeHead(i){this.statusCode=i}setHeader(i,o){if(Array.isArray(o))o.forEach((n)=>{this.writeHeader(i,n)});else this.writeHeader(i,o)}removeHeader(){}getHeader(){}writeStatus(i){if(this.isAborted)return;return this.res.writeStatus(i),this.statusWritten=!0,this.writeBufferedHeaders(),this}writeHeader(i,o){if(this.isAborted)return;if(i==="Content-Length")return;if(this.statusWritten)this.res.writeHeader(i,o);else this.headers.push([i,o])}writeBufferedHeaders(){this.headers.forEach(([i,o])=>{this.res.writeHeader(i,o)})}end(i){if(this.isAborted)return;this.res.cork(()=>{if(!this.statusWritten)this.writeBufferedHeaders();this.res.end(i)})}onData(i){if(this.isAborted)return;this.res.onData(i)}onAborted(i){if(this.isAborted)return;this.res.onAborted(()=>{this.isAborted=!0,i()})}cork(i){if(this.isAborted)return;this.res.cork(i)}}});var E9=P((Mx)=>{Object.defineProperty(Mx,"__esModule",{value:!0});Mx.protocol=Mx.Transport=Mx.Socket=Mx.uServer=Mx.parser=Mx.transports=Mx.Server=void 0;Mx.listen=LV;Mx.attach=V9;var VV=Hi("http"),u9=g$();Object.defineProperty(Mx,"Server",{enumerable:!0,get:function(){return u9.Server}});var SV=l$();Mx.transports=SV.default;var Q9=kT();Mx.parser=Q9;var EV=z9();Object.defineProperty(Mx,"uServer",{enumerable:!0,get:function(){return EV.uServer}});var OV=q$();Object.defineProperty(Mx,"Socket",{enumerable:!0,get:function(){return OV.Socket}});var _V=Rc();Object.defineProperty(Mx,"Transport",{enumerable:!0,get:function(){return _V.Transport}});Mx.protocol=Q9.protocol;function LV(i,o,n){if(typeof o==="function")n=o,o={};let p=VV.createServer(function(x,T){T.writeHead(501),T.end("Not Implemented")}),c=V9(p,o);return c.httpServer=p,p.listen(i,n),c}function V9(i,o){let n=new u9.Server(o);return n.attach(i,o),n}});var O9=P((NV)=>{NV.Emitter=Po;function Po(i){if(i)return BV(i)}function BV(i){for(var o in Po.prototype)i[o]=Po.prototype[o];return i}Po.prototype.on=Po.prototype.addEventListener=function(i,o){return this._callbacks=this._callbacks||{},(this._callbacks["$"+i]=this._callbacks["$"+i]||[]).push(o),this};Po.prototype.once=function(i,o){function n(){this.off(i,n),o.apply(this,arguments)}return n.fn=o,this.on(i,n),this};Po.prototype.off=Po.prototype.removeListener=Po.prototype.removeAllListeners=Po.prototype.removeEventListener=function(i,o){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+i];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+i],this;var p;for(var c=0;c<n.length;c++)if(p=n[c],p===o||p.fn===o){n.splice(c,1);break}if(n.length===0)delete this._callbacks["$"+i];return this};Po.prototype.emit=function(i){this._callbacks=this._callbacks||{};var o=new Array(arguments.length-1),n=this._callbacks["$"+i];for(var p=1;p<arguments.length;p++)o[p-1]=arguments[p];if(n){n=n.slice(0);for(var p=0,c=n.length;p<c;++p)n[p].apply(this,o)}return this};Po.prototype.emitReserved=Po.prototype.emit;Po.prototype.listeners=function(i){return this._callbacks=this._callbacks||{},this._callbacks["$"+i]||[]};Po.prototype.hasListeners=function(i){return!!this.listeners(i).length}});var s$=P((C9)=>{Object.defineProperty(C9,"__esModule",{value:!0});C9.hasBinary=C9.isBinary=void 0;var jV=typeof ArrayBuffer==="function",PV=(i)=>{return typeof ArrayBuffer.isView==="function"?ArrayBuffer.isView(i):i.buffer instanceof ArrayBuffer},_9=Object.prototype.toString,aV=typeof Blob==="function"||typeof Blob!=="undefined"&&_9.call(Blob)==="[object BlobConstructor]",lV=typeof File==="function"||typeof File!=="undefined"&&_9.call(File)==="[object FileConstructor]";function L9(i){return jV&&(i instanceof ArrayBuffer||PV(i))||aV&&i instanceof Blob||lV&&i instanceof File}C9.isBinary=L9;function e0(i,o){if(!i||typeof i!=="object")return!1;if(Array.isArray(i)){for(let n=0,p=i.length;n<p;n++)if(e0(i[n]))return!0;return!1}if(L9(i))return!0;if(i.toJSON&&typeof i.toJSON==="function"&&arguments.length===1)return e0(i.toJSON(),!0);for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)&&e0(i[n]))return!0;return!1}C9.hasBinary=e0});var B9=P((D9)=>{Object.defineProperty(D9,"__esModule",{value:!0});D9.reconstructPacket=D9.deconstructPacket=void 0;var kV=s$();function hV(i){let o=[],n=i.data,p=i;return p.data=t$(n,o),p.attachments=o.length,{packet:p,buffers:o}}D9.deconstructPacket=hV;function t$(i,o){if(!i)return i;if(kV.isBinary(i)){let n={_placeholder:!0,num:o.length};return o.push(i),n}else if(Array.isArray(i)){let n=new Array(i.length);for(let p=0;p<i.length;p++)n[p]=t$(i[p],o);return n}else if(typeof i==="object"&&!(i instanceof Date)){let n={};for(let p in i)if(Object.prototype.hasOwnProperty.call(i,p))n[p]=t$(i[p],o);return n}return i}function gV(i,o){return i.data=d$(i.data,o),delete i.attachments,i}D9.reconstructPacket=gV;function d$(i,o){if(!i)return i;if(i&&i._placeholder===!0)if(typeof i.num==="number"&&i.num>=0&&i.num<o.length)return o[i.num];else throw new Error("illegal attachments");else if(Array.isArray(i))for(let n=0;n<i.length;n++)i[n]=d$(i[n],o);else if(typeof i==="object"){for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n))i[n]=d$(i[n],o)}return i}});var sT=P((q9)=>{Object.defineProperty(q9,"__esModule",{value:!0});q9.Decoder=q9.Encoder=q9.PacketType=q9.protocol=void 0;var tV=O9(),j9=B9(),P9=s$(),dV=Go(),r$=dV.default("socket.io-parser"),rV=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];q9.protocol=5;var si;(function(i){i[i.CONNECT=0]="CONNECT",i[i.DISCONNECT=1]="DISCONNECT",i[i.EVENT=2]="EVENT",i[i.ACK=3]="ACK",i[i.CONNECT_ERROR=4]="CONNECT_ERROR",i[i.BINARY_EVENT=5]="BINARY_EVENT",i[i.BINARY_ACK=6]="BINARY_ACK"})(si=q9.PacketType||(q9.PacketType={}));class a9{constructor(i){this.replacer=i}encode(i){if(r$("encoding packet %j",i),i.type===si.EVENT||i.type===si.ACK){if(P9.hasBinary(i))return this.encodeAsBinary({type:i.type===si.EVENT?si.BINARY_EVENT:si.BINARY_ACK,nsp:i.nsp,data:i.data,id:i.id})}return[this.encodeAsString(i)]}encodeAsString(i){let o=""+i.type;if(i.type===si.BINARY_EVENT||i.type===si.BINARY_ACK)o+=i.attachments+"-";if(i.nsp&&i.nsp!=="/")o+=i.nsp+",";if(i.id!=null)o+=i.id;if(i.data!=null)o+=JSON.stringify(i.data,this.replacer);return r$("encoded %j as %s",i,o),o}encodeAsBinary(i){let o=j9.deconstructPacket(i),n=this.encodeAsString(o.packet),p=o.buffers;return p.unshift(n),p}}q9.Encoder=a9;function N9(i){return Object.prototype.toString.call(i)==="[object Object]"}class e$ extends tV.Emitter{constructor(i){super();this.reviver=i}add(i){let o;if(typeof i==="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");o=this.decodeString(i);let n=o.type===si.BINARY_EVENT;if(n||o.type===si.BINARY_ACK){if(o.type=n?si.EVENT:si.ACK,this.reconstructor=new l9(o),o.attachments===0)super.emitReserved("decoded",o)}else super.emitReserved("decoded",o)}else if(P9.isBinary(i)||i.base64){if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");else if(o=this.reconstructor.takeBinaryData(i),o)this.reconstructor=null,super.emitReserved("decoded",o)}else throw new Error("Unknown type: "+i)}decodeString(i){let o=0,n={type:Number(i.charAt(0))};if(si[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===si.BINARY_EVENT||n.type===si.BINARY_ACK){let c=o+1;while(i.charAt(++o)!=="-"&&o!=i.length);let x=i.substring(c,o);if(x!=Number(x)||i.charAt(o)!=="-")throw new Error("Illegal attachments");n.attachments=Number(x)}if(i.charAt(o+1)==="/"){let c=o+1;while(++o){if(i.charAt(o)===",")break;if(o===i.length)break}n.nsp=i.substring(c,o)}else n.nsp="/";let p=i.charAt(o+1);if(p!==""&&Number(p)==p){let c=o+1;while(++o){let x=i.charAt(o);if(x==null||Number(x)!=x){--o;break}if(o===i.length)break}n.id=Number(i.substring(c,o+1))}if(i.charAt(++o)){let c=this.tryParse(i.substr(o));if(e$.isPayloadValid(n.type,c))n.data=c;else throw new Error("invalid payload")}return r$("decoded %s as %j",i,n),n}tryParse(i){try{return JSON.parse(i,this.reviver)}catch(o){return!1}}static isPayloadValid(i,o){switch(i){case si.CONNECT:return N9(o);case si.DISCONNECT:return o===void 0;case si.CONNECT_ERROR:return typeof o==="string"||N9(o);case si.EVENT:case si.BINARY_EVENT:return Array.isArray(o)&&(typeof o[0]==="number"||typeof o[0]==="string"&&rV.indexOf(o[0])===-1);case si.ACK:case si.BINARY_ACK:return Array.isArray(o)}}destroy(){if(this.reconstructor)this.reconstructor.finishedReconstruction(),this.reconstructor=null}}q9.Decoder=e$;class l9{constructor(i){this.packet=i,this.buffers=[],this.reconPack=i}takeBinaryData(i){if(this.buffers.push(i),this.buffers.length===this.reconPack.attachments){let o=j9.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),o}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}});var t9=P((g9)=>{Object.defineProperty(g9,"__esModule",{value:!0});g9.Client=void 0;var i1=sT(),oS=Go(),nS=Hi("url"),Nn=oS("socket.io:client");class h9{constructor(i,o){this.sockets=new Map,this.nsps=new Map,this.server=i,this.conn=o,this.encoder=i.encoder,this.decoder=new i._parser.Decoder,this.id=o.id,this.setup()}get request(){return this.conn.request}setup(){this.onclose=this.onclose.bind(this),this.ondata=this.ondata.bind(this),this.onerror=this.onerror.bind(this),this.ondecoded=this.ondecoded.bind(this),this.decoder.on("decoded",this.ondecoded),this.conn.on("data",this.ondata),this.conn.on("error",this.onerror),this.conn.on("close",this.onclose),this.connectTimeout=setTimeout(()=>{if(this.nsps.size===0)Nn("no namespace joined yet, close the client"),this.close();else Nn("the client has already joined a namespace, nothing to do")},this.server._connectTimeout)}connect(i,o={}){if(this.server._nsps.has(i))return Nn("connecting to namespace %s",i),this.doConnect(i,o);this.server._checkNamespace(i,o,(n)=>{if(n)this.doConnect(i,o);else Nn("creation of namespace %s was denied",i),this._packet({type:i1.PacketType.CONNECT_ERROR,nsp:i,data:{message:"Invalid namespace"}})})}doConnect(i,o){let n=this.server.of(i);n._add(this,o,(p)=>{if(this.sockets.set(p.id,p),this.nsps.set(n.name,p),this.connectTimeout)clearTimeout(this.connectTimeout),this.connectTimeout=void 0})}_disconnect(){for(let i of this.sockets.values())i.disconnect();this.sockets.clear(),this.close()}_remove(i){if(this.sockets.has(i.id)){let o=this.sockets.get(i.id).nsp.name;this.sockets.delete(i.id),this.nsps.delete(o)}else Nn("ignoring remove for %s",i.id)}close(){if(this.conn.readyState==="open")Nn("forcing transport close"),this.conn.close(),this.onclose("forced server close")}_packet(i,o={}){if(this.conn.readyState!=="open"){Nn("ignoring packet write %j",i);return}let n=o.preEncoded?i:this.encoder.encode(i);this.writeToEngine(n,o)}writeToEngine(i,o){if(o.volatile&&!this.conn.transport.writable){Nn("volatile packet is discarded since the transport is not currently writable");return}let n=Array.isArray(i)?i:[i];for(let p of n)this.conn.write(p,o)}ondata(i){try{this.decoder.add(i)}catch(o){Nn("invalid packet format"),this.onerror(o)}}ondecoded(i){let o,n;if(this.conn.protocol===3){let c=nS.parse(i.nsp,!0);o=c.pathname,n=c.query}else o=i.nsp,n=i.data;let p=this.nsps.get(o);if(!p&&i.type===i1.PacketType.CONNECT)this.connect(o,n);else if(p&&i.type!==i1.PacketType.CONNECT&&i.type!==i1.PacketType.CONNECT_ERROR)process.nextTick(function(){p._onpacket(i)});else Nn("invalid state (packet type: %s)",i.type),this.close()}onerror(i){for(let o of this.sockets.values())o._onerror(i);this.conn.close()}onclose(i,o){Nn("client close with reason %s",i),this.destroy();for(let n of this.sockets.values())n._onclose(i,o);this.sockets.clear(),this.decoder.destroy()}destroy(){if(this.conn.removeListener("data",this.ondata),this.conn.removeListener("error",this.onerror),this.conn.removeListener("close",this.onclose),this.decoder.removeListener("decoded",this.ondecoded),this.connectTimeout)clearTimeout(this.connectTimeout),this.connectTimeout=void 0}}g9.Client=h9});var o1=P((r9)=>{Object.defineProperty(r9,"__esModule",{value:!0});r9.StrictEventEmitter=void 0;var pS=Hi("events");class d9 extends pS.EventEmitter{on(i,o){return super.on(i,o)}once(i,o){return super.once(i,o)}emit(i,...o){return super.emit(i,...o)}emitReserved(i,...o){return super.emit(i,...o)}emitUntyped(i,...o){return super.emit(i,...o)}listeners(i){return super.listeners(i)}}r9.StrictEventEmitter=d9});var iJ=P((iR)=>{Object.defineProperty(iR,"__esModule",{value:!0});iR.RESERVED_EVENTS=void 0;iR.RESERVED_EVENTS=new Set(["connect","connect_error","disconnect","disconnecting","newListener","removeListener"])});var nJ=P((nR)=>{Object.defineProperty(nR,"__esModule",{value:!0});nR.RemoteSocket=nR.BroadcastOperator=void 0;var cS=iJ(),xS=sT();class Xp{constructor(i,o=new Set,n=new Set,p={}){this.adapter=i,this.rooms=o,this.exceptRooms=n,this.flags=p}to(i){let o=new Set(this.rooms);if(Array.isArray(i))i.forEach((n)=>o.add(n));else o.add(i);return new Xp(this.adapter,o,this.exceptRooms,this.flags)}in(i){return this.to(i)}except(i){let o=new Set(this.exceptRooms);if(Array.isArray(i))i.forEach((n)=>o.add(n));else o.add(i);return new Xp(this.adapter,this.rooms,o,this.flags)}compress(i){let o=Object.assign({},this.flags,{compress:i});return new Xp(this.adapter,this.rooms,this.exceptRooms,o)}get volatile(){let i=Object.assign({},this.flags,{volatile:!0});return new Xp(this.adapter,this.rooms,this.exceptRooms,i)}get local(){let i=Object.assign({},this.flags,{local:!0});return new Xp(this.adapter,this.rooms,this.exceptRooms,i)}timeout(i){let o=Object.assign({},this.flags,{timeout:i});return new Xp(this.adapter,this.rooms,this.exceptRooms,o)}emit(i,...o){if(cS.RESERVED_EVENTS.has(i))throw new Error(`"${String(i)}" is a reserved event name`);let n=[i,...o],p={type:xS.PacketType.EVENT,data:n};if(typeof n[n.length-1]!=="function")return this.adapter.broadcast(p,{rooms:this.rooms,except:this.exceptRooms,flags:this.flags}),!0;let x=n.pop(),T=!1,m=[],f=setTimeout(()=>{T=!0,x.apply(this,[new Error("operation has timed out"),this.flags.expectSingleResponse?null:m])},this.flags.timeout),F=-1,$=0,J=0,A=()=>{if(!T&&F===$&&m.length===J)clearTimeout(f),x.apply(this,[null,this.flags.expectSingleResponse?m[0]:m])};return this.adapter.broadcastWithAck(p,{rooms:this.rooms,except:this.exceptRooms,flags:this.flags},(X)=>{J+=X,$++,A()},(X)=>{m.push(X),A()}),this.adapter.serverCount().then((X)=>{F=X,A()}),!0}emitWithAck(i,...o){return new Promise((n,p)=>{o.push((c,x)=>{if(c)return c.responses=x,p(c);else return n(x)}),this.emit(i,...o)})}allSockets(){if(!this.adapter)throw new Error("No adapter for this namespace, are you trying to get the list of clients of a dynamic namespace?");return this.adapter.sockets(this.rooms)}fetchSockets(){return this.adapter.fetchSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags}).then((i)=>{return i.map((o)=>{if(o.server)return o;else return new oJ(this.adapter,o)})})}socketsJoin(i){this.adapter.addSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags},Array.isArray(i)?i:[i])}socketsLeave(i){this.adapter.delSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags},Array.isArray(i)?i:[i])}disconnectSockets(i=!1){this.adapter.disconnectSockets({rooms:this.rooms,except:this.exceptRooms,flags:this.flags},i)}}nR.BroadcastOperator=Xp;class oJ{constructor(i,o){this.id=o.id,this.handshake=o.handshake,this.rooms=new Set(o.rooms),this.data=o.data,this.operator=new Xp(i,new Set([this.id]),new Set,{expectSingleResponse:!0})}timeout(i){return this.operator.timeout(i)}emit(i,...o){return this.operator.emit(i,...o)}join(i){return this.operator.socketsJoin(i)}leave(i){return this.operator.socketsLeave(i)}disconnect(i=!1){return this.operator.disconnectSockets(i),this}}nR.RemoteSocket=oJ});var pJ=P((zx)=>{var TR=zx&&zx.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(zx,"__esModule",{value:!0});zx.Socket=void 0;var zn=sT(),mS=TR(Go()),fS=o1(),cR=TR(S$()),FS=nJ(),$S=iJ(),yo=mS.default("socket.io:socket"),JS=new Set(["transport error","transport close","forced close","ping timeout","server shutting down","forced server close"]);function xR(){}class mR extends fS.StrictEventEmitter{constructor(i,o,n,p){super();if(this.nsp=i,this.client=o,this.recovered=!1,this.data={},this.connected=!1,this.acks=new Map,this.fns=[],this.flags={},this.server=i.server,this.adapter=this.nsp.adapter,p)this.id=p.sid,this.pid=p.pid,p.rooms.forEach((c)=>this.join(c)),this.data=p.data,p.missedPackets.forEach((c)=>{this.packet({type:zn.PacketType.EVENT,data:c})}),this.recovered=!0;else{if(o.conn.protocol===3)this.id=i.name!=="/"?i.name+"#"+o.id:o.id;else this.id=cR.default.generateId();if(this.server._opts.connectionStateRecovery)this.pid=cR.default.generateId()}this.handshake=this.buildHandshake(n),this.on("error",xR)}buildHandshake(i){var o,n,p,c;return{headers:((o=this.request)===null||o===void 0?void 0:o.headers)||{},time:new Date+"",address:this.conn.remoteAddress,xdomain:!!((n=this.request)===null||n===void 0?void 0:n.headers.origin),secure:!this.request||!!this.request.connection.encrypted,issued:+new Date,url:(p=this.request)===null||p===void 0?void 0:p.url,query:((c=this.request)===null||c===void 0?void 0:c._query)||{},auth:i}}emit(i,...o){if($S.RESERVED_EVENTS.has(i))throw new Error(`"${String(i)}" is a reserved event name`);let n=[i,...o],p={type:zn.PacketType.EVENT,data:n};if(typeof n[n.length-1]==="function"){let x=this.nsp._ids++;yo("emitting packet with ack id %d",x),this.registerAckCallback(x,n.pop()),p.id=x}let c=Object.assign({},this.flags);if(this.flags={},this.nsp.server.opts.connectionStateRecovery)this.adapter.broadcast(p,{rooms:new Set([this.id]),except:new Set,flags:c});else this.notifyOutgoingListeners(p),this.packet(p,c);return!0}emitWithAck(i,...o){let n=this.flags.timeout!==void 0;return new Promise((p,c)=>{o.push((x,T)=>{if(n)return x?c(x):p(T);else return p(x)}),this.emit(i,...o)})}registerAckCallback(i,o){let n=this.flags.timeout;if(n===void 0){this.acks.set(i,o);return}let p=setTimeout(()=>{yo("event with ack id %d has timed out after %d ms",i,n),this.acks.delete(i),o.call(this,new Error("operation has timed out"))},n);this.acks.set(i,(...c)=>{clearTimeout(p),o.apply(this,[null,...c])})}to(i){return this.newBroadcastOperator().to(i)}in(i){return this.newBroadcastOperator().in(i)}except(i){return this.newBroadcastOperator().except(i)}send(...i){return this.emit("message",...i),this}write(...i){return this.emit("message",...i),this}packet(i,o={}){i.nsp=this.nsp.name,o.compress=o.compress!==!1,this.client._packet(i,o)}join(i){return yo("join room %s",i),this.adapter.addAll(this.id,new Set(Array.isArray(i)?i:[i]))}leave(i){return yo("leave room %s",i),this.adapter.del(this.id,i)}leaveAll(){this.adapter.delAll(this.id)}_onconnect(){if(yo("socket connected - writing packet"),this.connected=!0,this.join(this.id),this.conn.protocol===3)this.packet({type:zn.PacketType.CONNECT});else this.packet({type:zn.PacketType.CONNECT,data:{sid:this.id,pid:this.pid}})}_onpacket(i){switch(yo("got packet %j",i),i.type){case zn.PacketType.EVENT:this.onevent(i);break;case zn.PacketType.BINARY_EVENT:this.onevent(i);break;case zn.PacketType.ACK:this.onack(i);break;case zn.PacketType.BINARY_ACK:this.onack(i);break;case zn.PacketType.DISCONNECT:this.ondisconnect();break}}onevent(i){let o=i.data||[];if(yo("emitting event %j",o),i.id!=null)yo("attaching ack callback to event"),o.push(this.ack(i.id));if(this._anyListeners&&this._anyListeners.length){let n=this._anyListeners.slice();for(let p of n)p.apply(this,o)}this.dispatch(o)}ack(i){let o=this,n=!1;return function(){if(n)return;let p=Array.prototype.slice.call(arguments);yo("sending ack %j",p),o.packet({id:i,type:zn.PacketType.ACK,data:p}),n=!0}}onack(i){let o=this.acks.get(i.id);if(typeof o=="function")yo("calling ack %s with %j",i.id,i.data),o.apply(this,i.data),this.acks.delete(i.id);else yo("bad ack %s",i.id)}ondisconnect(){yo("got disconnect packet"),this._onclose("client namespace disconnect")}_onerror(i){this.emitReserved("error",i)}_onclose(i,o){if(!this.connected)return this;if(yo("closing socket - reason %s",i),this.emitReserved("disconnecting",i,o),this.server._opts.connectionStateRecovery&&JS.has(i))yo("connection state recovery is enabled for sid %s",this.id),this.adapter.persistSession({sid:this.id,pid:this.pid,rooms:[...this.rooms],data:this.data});this._cleanup(),this.client._remove(this),this.connected=!1,this.emitReserved("disconnect",i,o);return}_cleanup(){this.leaveAll(),this.nsp._remove(this),this.join=xR}_error(i){this.packet({type:zn.PacketType.CONNECT_ERROR,data:i})}disconnect(i=!1){if(!this.connected)return this;if(i)this.client._disconnect();else this.packet({type:zn.PacketType.DISCONNECT}),this._onclose("server namespace disconnect");return this}compress(i){return this.flags.compress=i,this}get volatile(){return this.flags.volatile=!0,this}get broadcast(){return this.newBroadcastOperator()}get local(){return this.newBroadcastOperator().local}timeout(i){return this.flags.timeout=i,this}dispatch(i){yo("dispatching an event %j",i),this.run(i,(o)=>{process.nextTick(()=>{if(o)return this._onerror(o);if(this.connected)super.emitUntyped.apply(this,i);else yo("ignore packet received after disconnection")})})}use(i){return this.fns.push(i),this}run(i,o){if(!this.fns.length)return o();let n=this.fns.slice(0);function p(c){n[c](i,(x)=>{if(x)return o(x);if(!n[c+1])return o();p(c+1)})}p(0)}get disconnected(){return!this.connected}get request(){return this.client.request}get conn(){return this.client.conn}get rooms(){return this.adapter.socketRooms(this.id)||new Set}onAny(i){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(i),this}prependAny(i){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(i),this}offAny(i){if(!this._anyListeners)return this;if(i){let o=this._anyListeners;for(let n=0;n<o.length;n++)if(i===o[n])return o.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(i){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(i),this}prependAnyOutgoing(i){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(i),this}offAnyOutgoing(i){if(!this._anyOutgoingListeners)return this;if(i){let o=this._anyOutgoingListeners;for(let n=0;n<o.length;n++)if(i===o[n])return o.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(i){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let o=this._anyOutgoingListeners.slice();for(let n of o)n.apply(this,i.data)}}newBroadcastOperator(){let i=Object.assign({},this.flags);return this.flags={},new FS.BroadcastOperator(this.adapter,new Set,new Set([this.id]),i)}}zx.Socket=mR});var cJ=P((Wp)=>{var AS=Wp&&Wp.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Wp,"__esModule",{value:!0});Wp.Namespace=Wp.RESERVED_EVENTS=void 0;var fR=pJ(),vS=o1(),wS=AS(Go()),$n=nJ(),tT=wS.default("socket.io:namespace");Wp.RESERVED_EVENTS=new Set(["connect","connection","new_namespace"]);class FR extends vS.StrictEventEmitter{constructor(i,o){super();this.sockets=new Map,this._preConnectSockets=new Map,this._fns=[],this._ids=0,this.server=i,this.name=o,this._initAdapter()}_initAdapter(){this.adapter=new(this.server.adapter())(this)}use(i){return this._fns.push(i),this}run(i,o){if(!this._fns.length)return o();let n=this._fns.slice(0);function p(c){n[c](i,(x)=>{if(x)return o(x);if(!n[c+1])return o();p(c+1)})}p(0)}to(i){return new $n.BroadcastOperator(this.adapter).to(i)}in(i){return new $n.BroadcastOperator(this.adapter).in(i)}except(i){return new $n.BroadcastOperator(this.adapter).except(i)}async _add(i,o,n){var p;tT("adding socket to nsp %s",this.name);let c=await this._createSocket(i,o);if(this._preConnectSockets.set(c.id,c),((p=this.server.opts.connectionStateRecovery)===null||p===void 0?void 0:p.skipMiddlewares)&&c.recovered&&i.conn.readyState==="open")return this._doConnect(c,n);this.run(c,(x)=>{process.nextTick(()=>{if(i.conn.readyState!=="open"){tT("next called after client was closed - ignoring socket"),c._cleanup();return}if(x)if(tT("middleware error, sending CONNECT_ERROR packet to the client"),c._cleanup(),i.conn.protocol===3)return c._error(x.data||x.message);else return c._error({message:x.message,data:x.data});this._doConnect(c,n)})})}async _createSocket(i,o){let{pid:n,offset:p}=o;if(this.server.opts.connectionStateRecovery&&typeof n==="string"&&typeof p==="string"){let c;try{c=await this.adapter.restoreSession(n,p)}catch(x){tT("error while restoring session: %s",x)}if(c)return tT("connection state recovered for sid %s",c.sid),new fR.Socket(this,i,o,c)}return new fR.Socket(this,i,o)}_doConnect(i,o){if(this._preConnectSockets.delete(i.id),this.sockets.set(i.id,i),i._onconnect(),o)o(i);this.emitReserved("connect",i),this.emitReserved("connection",i)}_remove(i){this.sockets.delete(i.id)||this._preConnectSockets.delete(i.id)}emit(i,...o){return new $n.BroadcastOperator(this.adapter).emit(i,...o)}send(...i){return this.emit("message",...i),this}write(...i){return this.emit("message",...i),this}serverSideEmit(i,...o){if(Wp.RESERVED_EVENTS.has(i))throw new Error(`"${String(i)}" is a reserved event name`);return o.unshift(i),this.adapter.serverSideEmit(o),!0}serverSideEmitWithAck(i,...o){return new Promise((n,p)=>{o.push((c,x)=>{if(c)return c.responses=x,p(c);else return n(x)}),this.serverSideEmit(i,...o)})}_onServerSideEmit(i){super.emitUntyped.apply(this,i)}allSockets(){return new $n.BroadcastOperator(this.adapter).allSockets()}compress(i){return new $n.BroadcastOperator(this.adapter).compress(i)}get volatile(){return new $n.BroadcastOperator(this.adapter).volatile}get local(){return new $n.BroadcastOperator(this.adapter).local}timeout(i){return new $n.BroadcastOperator(this.adapter).timeout(i)}fetchSockets(){return new $n.BroadcastOperator(this.adapter).fetchSockets()}socketsJoin(i){return new $n.BroadcastOperator(this.adapter).socketsJoin(i)}socketsLeave(i){return new $n.BroadcastOperator(this.adapter).socketsLeave(i)}disconnectSockets(i=!1){return new $n.BroadcastOperator(this.adapter).disconnectSockets(i)}}Wp.Namespace=FR});var WR=P((wR)=>{Object.defineProperty(wR,"__esModule",{value:!0});wR.yeast=wR.decode=wR.encode=void 0;var AR="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),n1=64,vR={},$R=0,lp=0,JR;function xJ(i){let o="";do o=AR[i%n1]+o,i=Math.floor(i/n1);while(i>0);return o}wR.encode=xJ;function XS(i){let o=0;for(lp=0;lp<i.length;lp++)o=o*n1+vR[i.charAt(lp)];return o}wR.decode=XS;function WS(){let i=xJ(+new Date);if(i!==JR)return $R=0,JR=i;return i+"."+xJ($R++)}wR.yeast=WS;for(;lp<n1;lp++)vR[AR[lp]]=lp});var fJ=P((YR)=>{var TJ;Object.defineProperty(YR,"__esModule",{value:!0});YR.SessionAwareAdapter=YR.Adapter=void 0;var GS=Hi("events"),KS=WR(),p1=Hi("ws"),HS=typeof((TJ=p1===null||p1===void 0?void 0:p1.Sender)===null||TJ===void 0?void 0:TJ.frame)==="function";class mJ extends GS.EventEmitter{constructor(i){super();this.nsp=i,this.rooms=new Map,this.sids=new Map,this.encoder=i.server.encoder}init(){}close(){}serverCount(){return Promise.resolve(1)}addAll(i,o){if(!this.sids.has(i))this.sids.set(i,new Set);for(let n of o){if(this.sids.get(i).add(n),!this.rooms.has(n))this.rooms.set(n,new Set),this.emit("create-room",n);if(!this.rooms.get(n).has(i))this.rooms.get(n).add(i),this.emit("join-room",n,i)}}del(i,o){if(this.sids.has(i))this.sids.get(i).delete(o);this._del(o,i)}_del(i,o){let n=this.rooms.get(i);if(n!=null){if(n.delete(o))this.emit("leave-room",i,o);if(n.size===0&&this.rooms.delete(i))this.emit("delete-room",i)}}delAll(i){if(!this.sids.has(i))return;for(let o of this.sids.get(i))this._del(o,i);this.sids.delete(i)}broadcast(i,o){let n=o.flags||{},p={preEncoded:!0,volatile:n.volatile,compress:n.compress};i.nsp=this.nsp.name;let c=this._encode(i,p);this.apply(o,(x)=>{if(typeof x.notifyOutgoingListeners==="function")x.notifyOutgoingListeners(i);x.client.writeToEngine(c,p)})}broadcastWithAck(i,o,n,p){let c=o.flags||{},x={preEncoded:!0,volatile:c.volatile,compress:c.compress};i.nsp=this.nsp.name,i.id=this.nsp._ids++;let T=this._encode(i,x),m=0;this.apply(o,(f)=>{if(m++,f.acks.set(i.id,p),typeof f.notifyOutgoingListeners==="function")f.notifyOutgoingListeners(i);f.client.writeToEngine(T,x)}),n(m)}_encode(i,o){let n=this.encoder.encode(i);if(HS&&n.length===1&&typeof n[0]==="string"){let p=Buffer.from("4"+n[0]);o.wsPreEncodedFrame=p1.Sender.frame(p,{readOnly:!1,mask:!1,rsv1:!1,opcode:1,fin:!0})}return n}sockets(i){let o=new Set;return this.apply({rooms:i},(n)=>{o.add(n.id)}),Promise.resolve(o)}socketRooms(i){return this.sids.get(i)}fetchSockets(i){let o=[];return this.apply(i,(n)=>{o.push(n)}),Promise.resolve(o)}addSockets(i,o){this.apply(i,(n)=>{n.join(o)})}delSockets(i,o){this.apply(i,(n)=>{o.forEach((p)=>n.leave(p))})}disconnectSockets(i,o){this.apply(i,(n)=>{n.disconnect(o)})}apply(i,o){let n=i.rooms,p=this.computeExceptSids(i.except);if(n.size){let c=new Set;for(let x of n){if(!this.rooms.has(x))continue;for(let T of this.rooms.get(x)){if(c.has(T)||p.has(T))continue;let m=this.nsp.sockets.get(T);if(m)o(m),c.add(T)}}}else for(let[c]of this.sids){if(p.has(c))continue;let x=this.nsp.sockets.get(c);if(x)o(x)}}computeExceptSids(i){let o=new Set;if(i&&i.size>0){for(let n of i)if(this.rooms.has(n))this.rooms.get(n).forEach((p)=>o.add(p))}return o}serverSideEmit(i){console.warn("this adapter does not support the serverSideEmit() functionality")}persistSession(i){}restoreSession(i,o){return null}}YR.Adapter=mJ;class RR extends mJ{constructor(i){super(i);this.nsp=i,this.sessions=new Map,this.packets=[],this.maxDisconnectionDuration=i.server.opts.connectionStateRecovery.maxDisconnectionDuration,setInterval(()=>{let n=Date.now()-this.maxDisconnectionDuration;this.sessions.forEach((p,c)=>{if(p.disconnectedAt<n)this.sessions.delete(c)});for(let p=this.packets.length-1;p>=0;p--)if(this.packets[p].emittedAt<n){this.packets.splice(0,p+1);break}},60000).unref()}persistSession(i){i.disconnectedAt=Date.now(),this.sessions.set(i.pid,i)}restoreSession(i,o){let n=this.sessions.get(i);if(!n)return null;if(n.disconnectedAt+this.maxDisconnectionDuration<Date.now())return this.sessions.delete(i),null;let c=this.packets.findIndex((T)=>T.id===o);if(c===-1)return null;let x=[];for(let T=c+1;T<this.packets.length;T++){let m=this.packets[T];if(US(n.rooms,m.opts))x.push(m.data)}return Promise.resolve(Object.assign(Object.assign({},n),{missedPackets:x}))}broadcast(i,o){var n;let p=i.type===2,c=i.id===void 0,x=((n=o.flags)===null||n===void 0?void 0:n.volatile)===void 0;if(p&&c&&x){let T=KS.yeast();i.data.push(T),this.packets.push({id:T,opts:o,data:i.data,emittedAt:Date.now()})}super.broadcast(i,o)}}YR.SessionAwareAdapter=RR;function US(i,o){let n=o.rooms.size===0||i.some((c)=>o.rooms.has(c)),p=i.every((c)=>!o.except.has(c));return n&&p}});var HR=P((bn)=>{var MS=bn&&bn.__rest||function(i,o){var n={};for(var p in i)if(Object.prototype.hasOwnProperty.call(i,p)&&o.indexOf(p)<0)n[p]=i[p];if(i!=null&&typeof Object.getOwnPropertySymbols==="function"){for(var c=0,p=Object.getOwnPropertySymbols(i);c<p.length;c++)if(o.indexOf(p[c])<0&&Object.prototype.propertyIsEnumerable.call(i,p[c]))n[p[c]]=i[p[c]]}return n};Object.defineProperty(bn,"__esModule",{value:!0});bn.ClusterAdapterWithHeartbeat=bn.ClusterAdapter=bn.MessageType=void 0;var zS=fJ(),uS=Go(),QS=Hi("crypto"),io=uS.debug("socket.io-adapter"),VS="emitter",c1=5000;function Qx(){return QS.randomBytes(8).toString("hex")}var ii;(function(i){i[i.INITIAL_HEARTBEAT=1]="INITIAL_HEARTBEAT",i[i.HEARTBEAT=2]="HEARTBEAT",i[i.BROADCAST=3]="BROADCAST",i[i.SOCKETS_JOIN=4]="SOCKETS_JOIN",i[i.SOCKETS_LEAVE=5]="SOCKETS_LEAVE",i[i.DISCONNECT_SOCKETS=6]="DISCONNECT_SOCKETS",i[i.FETCH_SOCKETS=7]="FETCH_SOCKETS",i[i.FETCH_SOCKETS_RESPONSE=8]="FETCH_SOCKETS_RESPONSE",i[i.SERVER_SIDE_EMIT=9]="SERVER_SIDE_EMIT",i[i.SERVER_SIDE_EMIT_RESPONSE=10]="SERVER_SIDE_EMIT_RESPONSE",i[i.BROADCAST_CLIENT_COUNT=11]="BROADCAST_CLIENT_COUNT",i[i.BROADCAST_ACK=12]="BROADCAST_ACK",i[i.ADAPTER_CLOSE=13]="ADAPTER_CLOSE"})(ii=bn.MessageType||(bn.MessageType={}));function Gc(i){return{rooms:[...i.rooms],except:[...i.except],flags:i.flags}}function ux(i){return{rooms:new Set(i.rooms),except:new Set(i.except),flags:i.flags}}class FJ extends zS.Adapter{constructor(i){super(i);this.requests=new Map,this.ackRequests=new Map,this.uid=Qx()}onMessage(i,o){if(i.uid===this.uid)return io("[%s] ignore message from self",this.uid);switch(io("[%s] new event of type %d from %s",this.uid,i.type,i.uid),i.type){case ii.BROADCAST:{if(i.data.requestId!==void 0)super.broadcastWithAck(i.data.packet,ux(i.data.opts),(p)=>{io("[%s] waiting for %d client acknowledgements",this.uid,p),this.publishResponse(i.uid,{type:ii.BROADCAST_CLIENT_COUNT,data:{requestId:i.data.requestId,clientCount:p}})},(p)=>{io("[%s] received acknowledgement with value %j",this.uid,p),this.publishResponse(i.uid,{type:ii.BROADCAST_ACK,data:{requestId:i.data.requestId,packet:p}})});else{let p=i.data.packet,c=ux(i.data.opts);this.addOffsetIfNecessary(p,c,o),super.broadcast(p,c)}break}case ii.SOCKETS_JOIN:super.addSockets(ux(i.data.opts),i.data.rooms);break;case ii.SOCKETS_LEAVE:super.delSockets(ux(i.data.opts),i.data.rooms);break;case ii.DISCONNECT_SOCKETS:super.disconnectSockets(ux(i.data.opts),i.data.close);break;case ii.FETCH_SOCKETS:{io("[%s] calling fetchSockets with opts %j",this.uid,i.data.opts),super.fetchSockets(ux(i.data.opts)).then((n)=>{this.publishResponse(i.uid,{type:ii.FETCH_SOCKETS_RESPONSE,data:{requestId:i.data.requestId,sockets:n.map((p)=>{let c=p.handshake,{sessionStore:x}=c,T=MS(c,["sessionStore"]);return{id:p.id,handshake:T,rooms:[...p.rooms],data:p.data}})}})});break}case ii.SERVER_SIDE_EMIT:{let n=i.data.packet;if(i.data.requestId===void 0){this.nsp._onServerSideEmit(n);return}let c=!1,x=(T)=>{if(c)return;c=!0,io("[%s] calling acknowledgement with %j",this.uid,T),this.publishResponse(i.uid,{type:ii.SERVER_SIDE_EMIT_RESPONSE,data:{requestId:i.data.requestId,packet:T}})};this.nsp._onServerSideEmit([...n,x]);break}case ii.BROADCAST_CLIENT_COUNT:case ii.BROADCAST_ACK:case ii.FETCH_SOCKETS_RESPONSE:case ii.SERVER_SIDE_EMIT_RESPONSE:this.onResponse(i);break;default:io("[%s] unknown message type: %s",this.uid,i.type)}}onResponse(i){var o,n;let p=i.data.requestId;switch(io("[%s] received response %s to request %s",this.uid,i.type,p),i.type){case ii.BROADCAST_CLIENT_COUNT:{(o=this.ackRequests.get(p))===null||o===void 0||o.clientCountCallback(i.data.clientCount);break}case ii.BROADCAST_ACK:{(n=this.ackRequests.get(p))===null||n===void 0||n.ack(i.data.packet);break}case ii.FETCH_SOCKETS_RESPONSE:{let c=this.requests.get(p);if(!c)return;if(c.current++,i.data.sockets.forEach((x)=>c.responses.push(x)),c.current===c.expected)clearTimeout(c.timeout),c.resolve(c.responses),this.requests.delete(p);break}case ii.SERVER_SIDE_EMIT_RESPONSE:{let c=this.requests.get(p);if(!c)return;if(c.current++,c.responses.push(i.data.packet),c.current===c.expected)clearTimeout(c.timeout),c.resolve(null,c.responses),this.requests.delete(p);break}default:io("[%s] unknown response type: %s",this.uid,i.type)}}async broadcast(i,o){var n;if(!((n=o.flags)===null||n===void 0?void 0:n.local))try{let c=await this.publishAndReturnOffset({type:ii.BROADCAST,data:{packet:i,opts:Gc(o)}});this.addOffsetIfNecessary(i,o,c)}catch(c){return io("[%s] error while broadcasting message: %s",this.uid,c.message)}super.broadcast(i,o)}addOffsetIfNecessary(i,o,n){var p;if(!this.nsp.server.opts.connectionStateRecovery)return;let c=i.type===2,x=i.id===void 0,T=((p=o.flags)===null||p===void 0?void 0:p.volatile)===void 0;if(c&&x&&T)i.data.push(n)}broadcastWithAck(i,o,n,p){var c;if(!((c=o===null||o===void 0?void 0:o.flags)===null||c===void 0?void 0:c.local)){let T=Qx();this.ackRequests.set(T,{clientCountCallback:n,ack:p}),this.publish({type:ii.BROADCAST,data:{packet:i,requestId:T,opts:Gc(o)}}),setTimeout(()=>{this.ackRequests.delete(T)},o.flags.timeout)}super.broadcastWithAck(i,o,n,p)}async addSockets(i,o){var n;if(!((n=i.flags)===null||n===void 0?void 0:n.local))try{await this.publishAndReturnOffset({type:ii.SOCKETS_JOIN,data:{opts:Gc(i),rooms:o}})}catch(c){io("[%s] error while publishing message: %s",this.uid,c.message)}super.addSockets(i,o)}async delSockets(i,o){var n;if(!((n=i.flags)===null||n===void 0?void 0:n.local))try{await this.publishAndReturnOffset({type:ii.SOCKETS_LEAVE,data:{opts:Gc(i),rooms:o}})}catch(c){io("[%s] error while publishing message: %s",this.uid,c.message)}super.delSockets(i,o)}async disconnectSockets(i,o){var n;if(!((n=i.flags)===null||n===void 0?void 0:n.local))try{await this.publishAndReturnOffset({type:ii.DISCONNECT_SOCKETS,data:{opts:Gc(i),close:o}})}catch(c){io("[%s] error while publishing message: %s",this.uid,c.message)}super.disconnectSockets(i,o)}async fetchSockets(i){var o;let[n,p]=await Promise.all([super.fetchSockets(i),this.serverCount()]),c=p-1;if(((o=i.flags)===null||o===void 0?void 0:o.local)||c<=0)return n;let x=Qx();return new Promise((T,m)=>{let f=setTimeout(()=>{let $=this.requests.get(x);if($)m(new Error(`timeout reached: only ${$.current} responses received out of ${$.expected}`)),this.requests.delete(x)},i.flags.timeout||c1),F={type:ii.FETCH_SOCKETS,resolve:T,timeout:f,current:0,expected:c,responses:n};this.requests.set(x,F),this.publish({type:ii.FETCH_SOCKETS,data:{opts:Gc(i),requestId:x}})})}async serverSideEmit(i){if(typeof i[i.length-1]!=="function")return this.publish({type:ii.SERVER_SIDE_EMIT,data:{packet:i}});let n=i.pop(),p=await this.serverCount()-1;if(io('[%s] waiting for %d responses to "serverSideEmit" request',this.uid,p),p<=0)return n(null,[]);let c=Qx(),x=setTimeout(()=>{let m=this.requests.get(c);if(m)n(new Error(`timeout reached: only ${m.current} responses received out of ${m.expected}`),m.responses),this.requests.delete(c)},c1),T={type:ii.SERVER_SIDE_EMIT,resolve:n,timeout:x,current:0,expected:p,responses:[]};this.requests.set(c,T),this.publish({type:ii.SERVER_SIDE_EMIT,data:{requestId:c,packet:i}})}publish(i){this.publishAndReturnOffset(i).catch((o)=>{io("[%s] error while publishing message: %s",this.uid,o)})}publishAndReturnOffset(i){return i.uid=this.uid,i.nsp=this.nsp.name,this.doPublish(i)}publishResponse(i,o){o.uid=this.uid,o.nsp=this.nsp.name,this.doPublishResponse(i,o).catch((n)=>{io("[%s] error while publishing response: %s",this.uid,n)})}}bn.ClusterAdapter=FJ;class KR extends FJ{constructor(i,o){super(i);this.nodesMap=new Map,this.customRequests=new Map,this._opts=Object.assign({heartbeatInterval:5000,heartbeatTimeout:1e4},o),this.cleanupTimer=setInterval(()=>{let n=Date.now();this.nodesMap.forEach((p,c)=>{if(n-p>this._opts.heartbeatTimeout)io("[%s] node %s seems down",this.uid,c),this.removeNode(c)})},1000)}init(){this.publish({type:ii.INITIAL_HEARTBEAT})}scheduleHeartbeat(){if(this.heartbeatTimer)this.heartbeatTimer.refresh();else this.heartbeatTimer=setTimeout(()=>{this.publish({type:ii.HEARTBEAT})},this._opts.heartbeatInterval)}close(){if(this.publish({type:ii.ADAPTER_CLOSE}),clearTimeout(this.heartbeatTimer),this.cleanupTimer)clearInterval(this.cleanupTimer)}onMessage(i,o){if(i.uid===this.uid)return io("[%s] ignore message from self",this.uid);if(i.uid&&i.uid!==VS)this.nodesMap.set(i.uid,Date.now());switch(io("[%s] new event of type %d from %s",this.uid,i.type,i.uid),i.type){case ii.INITIAL_HEARTBEAT:this.publish({type:ii.HEARTBEAT});break;case ii.HEARTBEAT:break;case ii.ADAPTER_CLOSE:this.removeNode(i.uid);break;default:super.onMessage(i,o)}}serverCount(){return Promise.resolve(1+this.nodesMap.size)}publish(i){return this.scheduleHeartbeat(),super.publish(i)}async serverSideEmit(i){if(typeof i[i.length-1]!=="function")return this.publish({type:ii.SERVER_SIDE_EMIT,data:{packet:i}});let n=i.pop(),p=this.nodesMap.size;if(io('[%s] waiting for %d responses to "serverSideEmit" request',this.uid,p),p<=0)return n(null,[]);let c=Qx(),x=setTimeout(()=>{let m=this.customRequests.get(c);if(m)n(new Error(`timeout reached: missing ${m.missingUids.size} responses`),m.responses),this.customRequests.delete(c)},c1),T={type:ii.SERVER_SIDE_EMIT,resolve:n,timeout:x,missingUids:new Set([...this.nodesMap.keys()]),responses:[]};this.customRequests.set(c,T),this.publish({type:ii.SERVER_SIDE_EMIT,data:{requestId:c,packet:i}})}async fetchSockets(i){var o;let[n,p]=await Promise.all([super.fetchSockets({rooms:i.rooms,except:i.except,flags:{local:!0}}),this.serverCount()]),c=p-1;if(((o=i.flags)===null||o===void 0?void 0:o.local)||c<=0)return n;let x=Qx();return new Promise((T,m)=>{let f=setTimeout(()=>{let $=this.customRequests.get(x);if($)m(new Error(`timeout reached: missing ${$.missingUids.size} responses`)),this.customRequests.delete(x)},i.flags.timeout||c1),F={type:ii.FETCH_SOCKETS,resolve:T,timeout:f,missingUids:new Set([...this.nodesMap.keys()]),responses:n};this.customRequests.set(x,F),this.publish({type:ii.FETCH_SOCKETS,data:{opts:Gc(i),requestId:x}})})}onResponse(i){let o=i.data.requestId;switch(io("[%s] received response %s to request %s",this.uid,i.type,o),i.type){case ii.FETCH_SOCKETS_RESPONSE:{let n=this.customRequests.get(o);if(!n)return;if(i.data.sockets.forEach((p)=>n.responses.push(p)),n.missingUids.delete(i.uid),n.missingUids.size===0)clearTimeout(n.timeout),n.resolve(n.responses),this.customRequests.delete(o);break}case ii.SERVER_SIDE_EMIT_RESPONSE:{let n=this.customRequests.get(o);if(!n)return;if(n.responses.push(i.data.packet),n.missingUids.delete(i.uid),n.missingUids.size===0)clearTimeout(n.timeout),n.resolve(null,n.responses),this.customRequests.delete(o);break}default:super.onResponse(i)}}removeNode(i){this.customRequests.forEach((o,n)=>{if(o.missingUids.delete(i),o.missingUids.size===0){if(clearTimeout(o.timeout),o.type===ii.FETCH_SOCKETS)o.resolve(o.responses);else if(o.type===ii.SERVER_SIDE_EMIT)o.resolve(null,o.responses);this.customRequests.delete(n)}}),this.nodesMap.delete(i)}}bn.ClusterAdapterWithHeartbeat=KR});var x1=P((Kc)=>{Object.defineProperty(Kc,"__esModule",{value:!0});Kc.MessageType=Kc.ClusterAdapterWithHeartbeat=Kc.ClusterAdapter=Kc.SessionAwareAdapter=Kc.Adapter=void 0;var UR=fJ();Object.defineProperty(Kc,"Adapter",{enumerable:!0,get:function(){return UR.Adapter}});Object.defineProperty(Kc,"SessionAwareAdapter",{enumerable:!0,get:function(){return UR.SessionAwareAdapter}});var $J=HR();Object.defineProperty(Kc,"ClusterAdapter",{enumerable:!0,get:function(){return $J.ClusterAdapter}});Object.defineProperty(Kc,"ClusterAdapterWithHeartbeat",{enumerable:!0,get:function(){return $J.ClusterAdapterWithHeartbeat}});Object.defineProperty(Kc,"MessageType",{enumerable:!0,get:function(){return $J.MessageType}})});var uR=P((Vx)=>{var ES=Vx&&Vx.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Vx,"__esModule",{value:!0});Vx.ParentNamespace=void 0;var ZR=cJ(),OS=x1(),_S=ES(Go()),MR=_S.default("socket.io:parent-namespace");class T1 extends ZR.Namespace{constructor(i){super(i,"/_"+T1.count++);this.children=new Set}_initAdapter(){this.adapter=new zR(this)}emit(i,...o){return this.children.forEach((n)=>{n.emit(i,...o)}),!0}createChild(i){MR("creating child namespace %s",i);let o=new ZR.Namespace(this.server,i);if(this._fns.forEach((n)=>o.use(n)),this.listeners("connect").forEach((n)=>o.on("connect",n)),this.listeners("connection").forEach((n)=>o.on("connection",n)),this.children.add(o),this.server._opts.cleanupEmptyChildNamespaces){let n=o._remove;o._remove=(p)=>{if(n.call(o,p),o.sockets.size===0)MR("closing child namespace %s",i),o.adapter.close(),this.server._nsps.delete(o.name),this.children.delete(o)}}return this.server._nsps.set(i,o),this.server.sockets.emitReserved("new_namespace",o),o}fetchSockets(){throw new Error("fetchSockets() is not supported on parent namespaces")}}Vx.ParentNamespace=T1;T1.count=0;class zR extends OS.Adapter{broadcast(i,o){this.nsp.children.forEach((n)=>{n.adapter.broadcast(i,o)})}}});var _R=P((Uc)=>{var LS=Uc&&Uc.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Uc,"__esModule",{value:!0});Uc.patchAdapter=yS;Uc.restoreAdapter=DS;Uc.serveFile=BS;var Hc=x1(),QR=Hi("fs"),CS=LS(Go()),m1=CS.default("socket.io:adapter-uws"),JJ="\x1F",{addAll:SR,del:ER,broadcast:OR}=Hc.Adapter.prototype;function yS(i){Hc.Adapter.prototype.addAll=function(o,n){let p=!this.sids.has(o);SR.call(this,o,n);let c=this.nsp.sockets.get(o)||this.nsp._preConnectSockets.get(o);if(!c)return;if(c.conn.transport.name==="websocket"){VR(this.nsp.name,c,p,n);return}if(p)c.conn.on("upgrade",()=>{let x=this.sids.get(o);if(x)VR(this.nsp.name,c,p,x)})},Hc.Adapter.prototype.del=function(o,n){ER.call(this,o,n);let p=this.nsp.sockets.get(o)||this.nsp._preConnectSockets.get(o);if(p&&p.conn.transport.name==="websocket"){let c=p.conn.id,x=p.conn.transport.socket,T=`${this.nsp.name}${JJ}${n}`;m1("unsubscribe connection %s from topic %s",c,T),x.unsubscribe(T)}},Hc.Adapter.prototype.broadcast=function(o,n){if(!(n.rooms.size<=1&&n.except.size===0)){OR.call(this,o,n);return}let c=n.flags||{},x={preEncoded:!0,volatile:c.volatile,compress:c.compress};o.nsp=this.nsp.name;let T=this.encoder.encode(o),m=n.rooms.size===0?this.nsp.name:`${this.nsp.name}${JJ}${n.rooms.keys().next().value}`;m1("fast publish to %s",m),T.forEach((f)=>{let F=typeof f!=="string";i.publish(m,F?f:"4"+f,F)}),this.apply(n,(f)=>{if(f.conn.transport.name!=="websocket")f.client.writeToEngine(T,x)})}}function VR(i,o,n,p){let c=o.conn.id,x=o.conn.transport.socket;if(n)m1("subscribe connection %s to topic %s",c,i),x.subscribe(i);p.forEach((T)=>{let m=`${i}${JJ}${T}`;m1("subscribe connection %s to topic %s",c,m),x.subscribe(m)})}function DS(){Hc.Adapter.prototype.addAll=SR,Hc.Adapter.prototype.del=ER,Hc.Adapter.prototype.broadcast=OR}var IS=(i)=>{let{buffer:o,byteOffset:n,byteLength:p}=i;return o.slice(n,n+p)};function BS(i,o){let{size:n}=QR.statSync(o),p=QR.createReadStream(o),c=()=>!p.destroyed&&p.destroy(),x=(m)=>{throw c(),m},T=(m)=>{let f=IS(m);i.cork(()=>{let F=i.getWriteOffset(),[$,J]=i.tryEnd(f,n);if(!J&&!$)p.pause(),i.onWritable((A)=>{let[X,Y]=i.tryEnd(f.slice(A-F),n);if(!Y&&X)p.resume();return X})})};i.onAborted(c),p.on("data",T).on("error",x).on("end",c)}});var LR=P((jpi,NS)=>{NS.exports={name:"socket.io",version:"4.8.1",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"},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 --require ts-node/register --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.3.2","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 PR=P((Do,dT)=>{var __dirname="/home/runner/work/wayforge/wayforge/node_modules/.pnpm/socket.io@4.8.1/node_modules/socket.io/dist",bS=Do&&Do.__createBinding||(Object.create?function(i,o,n,p){if(p===void 0)p=n;var c=Object.getOwnPropertyDescriptor(o,n);if(!c||("get"in c?!o.__esModule:c.writable||c.configurable))c={enumerable:!0,get:function(){return o[n]}};Object.defineProperty(i,p,c)}:function(i,o,n,p){if(p===void 0)p=n;i[p]=o[n]}),jS=Do&&Do.__setModuleDefault||(Object.create?function(i,o){Object.defineProperty(i,"default",{enumerable:!0,value:o})}:function(i,o){i.default=o}),PS=Do&&Do.__importStar||function(i){if(i&&i.__esModule)return i;var o={};if(i!=null){for(var n in i)if(n!=="default"&&Object.prototype.hasOwnProperty.call(i,n))bS(o,i,n)}return jS(o,i),o},bR=Do&&Do.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Do,"__esModule",{value:!0});Do.Namespace=Do.Socket=Do.Server=void 0;var aS=Hi("http"),lS=Hi("fs"),AJ=Hi("zlib"),qS=B0(),f1=Hi("stream"),CR=Hi("path"),yR=E9(),kS=t9(),DR=Hi("events"),wJ=cJ();Object.defineProperty(Do,"Namespace",{enumerable:!0,get:function(){return wJ.Namespace}});var hS=uR(),IR=x1(),gS=PS(sT()),sS=bR(Go()),jR=pJ();Object.defineProperty(Do,"Socket",{enumerable:!0,get:function(){return jR.Socket}});var tS=o1(),vJ=_R(),dS=bR(h$()),on=sS.default("socket.io:server"),BR=LR().version,NR=/\.map/;class Sx extends tS.StrictEventEmitter{constructor(i,o={}){super();if(this._nsps=new Map,this.parentNsps=new Map,this.parentNamespacesFromRegExp=new Map,typeof i==="object"&&i instanceof Object&&!i.listen)o=i,i=void 0;if(this.path(o.path||"/socket.io"),this.connectTimeout(o.connectTimeout||45000),this.serveClient(o.serveClient!==!1),this._parser=o.parser||gS,this.encoder=new this._parser.Encoder,this.opts=o,o.connectionStateRecovery)o.connectionStateRecovery=Object.assign({maxDisconnectionDuration:120000,skipMiddlewares:!0},o.connectionStateRecovery),this.adapter(o.adapter||IR.SessionAwareAdapter);else this.adapter(o.adapter||IR.Adapter);if(o.cleanupEmptyChildNamespaces=!!o.cleanupEmptyChildNamespaces,this.sockets=this.of("/"),i||typeof i=="number")this.attach(i);if(this.opts.cors)this._corsMiddleware=dS.default(this.opts.cors)}get _opts(){return this.opts}serveClient(i){if(!arguments.length)return this._serveClient;return this._serveClient=i,this}_checkNamespace(i,o,n){if(this.parentNsps.size===0)return n(!1);let p=this.parentNsps.keys(),c=()=>{let x=p.next();if(x.done)return n(!1);x.value(i,o,(T,m)=>{if(T||!m)return c();if(this._nsps.has(i))return on("dynamic namespace %s already exists",i),n(this._nsps.get(i));let f=this.parentNsps.get(x.value).createChild(i);on("dynamic namespace %s was created",i),n(f)})};c()}path(i){if(!arguments.length)return this._path;this._path=i.replace(/\/$/,"");let o=this._path.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");return this.clientPathRegex=new RegExp("^"+o+"/socket\\.io(\\.msgpack|\\.esm)?(\\.min)?\\.js(\\.map)?(?:\\?|$)"),this}connectTimeout(i){if(i===void 0)return this._connectTimeout;return this._connectTimeout=i,this}adapter(i){if(!arguments.length)return this._adapter;this._adapter=i;for(let o of this._nsps.values())o._initAdapter();return this}listen(i,o={}){return this.attach(i,o)}attach(i,o={}){if(typeof i=="function")throw new Error("You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.");if(Number(i)==i)i=Number(i);if(typeof i=="number"){on("creating http server and binding to %d",i);let n=i;i=aS.createServer((p,c)=>{c.writeHead(404),c.end()}),i.listen(n)}return Object.assign(o,this.opts),o.path=o.path||this._path,this.initEngine(i,o),this}attachApp(i,o={}){Object.assign(o,this.opts),o.path=o.path||this._path,on("creating uWebSockets.js-based engine with opts %j",o);let n=new yR.uServer(o);if(n.attach(i,o),this.bind(n),this._serveClient)i.get(`${this._path}/*`,(p,c)=>{if(!this.clientPathRegex.test(c.getUrl())){c.setYield(!0);return}let x=c.getUrl().replace(this._path,"").replace(/\?.*$/,"").replace(/^\//,""),T=NR.test(x),m=T?"map":"source",f='"'+BR+'"',F="W/"+f,$=c.getHeader("if-none-match");if($){if(f===$||F===$){on("serve client %s 304",m),p.writeStatus("304 Not Modified"),p.end();return}}on("serve client %s",m),p.writeHeader("cache-control","public, max-age=0"),p.writeHeader("content-type","application/"+(T?"json":"javascript")+"; charset=utf-8"),p.writeHeader("etag",f);let J=CR.join(__dirname,"../client-dist/",x);vJ.serveFile(p,J)});vJ.patchAdapter(i)}initEngine(i,o){if(on("creating engine.io instance with opts %j",o),this.eio=yR.attach(i,o),this._serveClient)this.attachServe(i);this.httpServer=i,this.bind(this.eio)}attachServe(i){on("attaching client serving req handler");let o=i.listeners("request").slice(0);i.removeAllListeners("request"),i.on("request",(n,p)=>{if(this.clientPathRegex.test(n.url))if(this._corsMiddleware)this._corsMiddleware(n,p,()=>{this.serve(n,p)});else this.serve(n,p);else for(let c=0;c<o.length;c++)o[c].call(i,n,p)})}serve(i,o){let n=i.url.replace(this._path,"").replace(/\?.*$/,""),p=NR.test(n),c=p?"map":"source",x='"'+BR+'"',T="W/"+x,m=i.headers["if-none-match"];if(m){if(x===m||T===m){on("serve client %s 304",c),o.writeHead(304),o.end();return}}on("serve client %s",c),o.setHeader("Cache-Control","public, max-age=0"),o.setHeader("Content-Type","application/"+(p?"json":"javascript")+"; charset=utf-8"),o.setHeader("ETag",x),Sx.sendFile(n,i,o)}static sendFile(i,o,n){let p=lS.createReadStream(CR.join(__dirname,"../client-dist/",i)),c=qS(o).encodings(["br","gzip","deflate"]),x=(T)=>{if(T)n.end()};switch(c){case"br":n.writeHead(200,{"content-encoding":"br"}),f1.pipeline(p,AJ.createBrotliCompress(),n,x);break;case"gzip":n.writeHead(200,{"content-encoding":"gzip"}),f1.pipeline(p,AJ.createGzip(),n,x);break;case"deflate":n.writeHead(200,{"content-encoding":"deflate"}),f1.pipeline(p,AJ.createDeflate(),n,x);break;default:n.writeHead(200),f1.pipeline(p,n,x)}}bind(i){return this.engine=i,this.engine.on("connection",this.onconnection.bind(this)),this}onconnection(i){on("incoming connection with id %s",i.id);let o=new kS.Client(this,i);if(i.protocol===3)o.connect("/");return this}of(i,o){if(typeof i==="function"||i instanceof RegExp){let p=new hS.ParentNamespace(this);if(on("initializing parent namespace %s",p.name),typeof i==="function")this.parentNsps.set(i,p);else this.parentNsps.set((c,x,T)=>T(null,i.test(c)),p),this.parentNamespacesFromRegExp.set(i,p);if(o)p.on("connect",o);return p}if(String(i)[0]!=="/")i="/"+i;let n=this._nsps.get(i);if(!n){for(let[p,c]of this.parentNamespacesFromRegExp)if(p.test(i))return on("attaching namespace %s to parent namespace %s",i,p),c.createChild(i);if(on("initializing namespace %s",i),n=new wJ.Namespace(this,i),this._nsps.set(i,n),i!=="/")this.sockets.emitReserved("new_namespace",n)}if(o)n.on("connect",o);return n}async close(i){if(await Promise.allSettled([...this._nsps.values()].map(async(o)=>{o.sockets.forEach((n)=>{n._onclose("server shutting down")}),await o.adapter.close()})),this.engine.close(),vJ.restoreAdapter(),this.httpServer)this.httpServer.close(i);else i&&i()}use(i){return this.sockets.use(i),this}to(i){return this.sockets.to(i)}in(i){return this.sockets.in(i)}except(i){return this.sockets.except(i)}send(...i){return this.sockets.emit("message",...i),this}write(...i){return this.sockets.emit("message",...i),this}serverSideEmit(i,...o){return this.sockets.serverSideEmit(i,...o)}serverSideEmitWithAck(i,...o){return this.sockets.serverSideEmitWithAck(i,...o)}allSockets(){return this.sockets.allSockets()}compress(i){return this.sockets.compress(i)}get volatile(){return this.sockets.volatile}get local(){return this.sockets.local}timeout(i){return this.sockets.timeout(i)}fetchSockets(){return this.sockets.fetchSockets()}socketsJoin(i){return this.sockets.socketsJoin(i)}socketsLeave(i){return this.sockets.socketsLeave(i)}disconnectSockets(i=!1){return this.sockets.disconnectSockets(i)}}Do.Server=Sx;var rS=Object.keys(DR.EventEmitter.prototype).filter(function(i){return typeof DR.EventEmitter.prototype[i]==="function"});rS.forEach(function(i){Sx.prototype[i]=function(){return this.sockets[i].apply(this.sockets,arguments)}});dT.exports=(i,o)=>new Sx(i,o);dT.exports.Server=Sx;dT.exports.Namespace=wJ.Namespace;dT.exports.Socket=jR.Socket});import{createHash as yY}from"crypto";import{createServer as FO}from"http";import{createServer as $O}from"https";var Kp=(i)=>Array.isArray(i)?i:[i],$A=(i,o)=>{let n=[[],[]];for(let p of i)if(o(p))n[0].push(p);else n[1].push(p);return n},$m=Array,op=(i,o)=>i.includes(o),JA=(i,o=0)=>[...new Array(i)].map((n,p)=>p+o),Ai=(i,o,n)=>{if(i===void 0)return o===void 0?[]:Array.isArray(o)?o:[o];if(n?.prepend)if(Array.isArray(o))i.unshift(...o);else i.unshift(o);else if(Array.isArray(o))i.push(...o);else i.push(o);return i},np=(i,o)=>{if(o===void 0||o===null)return i??[];if(i===void 0||i===null)return Kp(o);return i.concat(o)},AA=(...i)=>i.reduce(np,[]),ln=(i,o,n)=>{if(i===void 0)return Array.isArray(o)?o:[o];let p=n?.isEqual??((c,x)=>c===x);return Kp(o).forEach((c)=>{if(!i.some((x)=>p(x,c)))i.push(c)}),i},vA=(i,o)=>i.reduce((n,p)=>{let c=p[o];return n[c]=Ai(n[c],p),n},{}),pp=(i,o,n)=>i.length===o.length&&i.every(n?.isEqual?(p,c)=>n.isEqual(p,o[c]):(p,c)=>p===o[c]);var qo=(i,o)=>Fo(i)===o,Fo=(i)=>{let o=typeof i;return o==="object"?i===null?"null":"object":o==="function"?"object":o},ko={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},wA={...ko,function:"a function"};class XA extends Error{}var Xi=(i)=>cp(i,XA),cp=(i,o=Error)=>{throw new o(i)};class bx extends Error{name="ParseError"}var U=(i)=>cp(i,bx),Sn=(i)=>` ${i}`;var pi=(i,o)=>{let n={},p=Array.isArray(i),c=!1;return Object.entries(i).forEach((x,T)=>{let m=p?o(T,x[1]):o(...x,T);c||=typeof m[0]==="number",(Array.isArray(m[0])||m.length===0?m:[m]).forEach(([F,$])=>{if(typeof F==="object")n[F.group]=Ai(n[F.group],$);else n[F]=$})}),c?Object.values(n):n};var y1=Object.entries;var di=(i,o)=>(i in o),Oc=(i,o)=>(o in i);class D1{constructor(i){Object.assign(this,i)}}var WA=class{};class jx extends WA{}var DG=(i,o)=>{let n={},p={},c;for(c in i)if(c in o)n[c]=i[c];else p[c]=i[c];return[n,p]};var RA=(i,o)=>DG(i,o)[1],qn=(i)=>Object.keys(i).length===0,Px=(i)=>[...Object.entries(i),...Object.getOwnPropertySymbols(i).map((o)=>[o,i[o]])],YA=(i,o)=>Object.defineProperties(i,Object.getOwnPropertyDescriptors(o)),GA=(i)=>{let o=Object.keys(i).sort(),n={};for(let p=0;p<o.length;p++)n[o[p]]=i[o[p]];return n};var nn=Sn("represents an uninitialized value"),KA=(i)=>Object.values(i).filter((o)=>{if(typeof o==="number")return!0;return typeof i[o]!=="number"});var I1={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},B1=globalThis.File??Blob,N1={ArrayBuffer,Blob,File:B1,FormData,Headers,Request,Response,URL},IG={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},hp={...I1,...N1,...IG,String,Number,Boolean},ax=(i)=>{let o=Object.getPrototypeOf(i);while(o?.constructor&&(!di(o.constructor.name,hp)||!(i instanceof hp[o.constructor.name])))o=Object.getPrototypeOf(o);let n=o?.constructor?.name;if(n===void 0||n==="Object")return;return n},lx=(i)=>typeof i==="object"&&i!==null?ax(i)??"object":Fo(i);var Oi=Array.isArray,BG={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},NG={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},bG={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},HA={...BG,...NG,...bG},qx=(i)=>{let o=Object(i).name??null;return o&&di(o,hp)&&hp[o]===i?o:null};var b1=(i,o)=>{let n=i.prototype;while(n!==null){if(n===o.prototype)return!0;n=Object.getPrototypeOf(n)}return!1};var UA=(i)=>ZA(i,new Map),ZA=(i,o)=>{if(typeof i!=="object"||i===null)return i;if(o?.has(i))return o.get(i);let n=qx(i.constructor);if(n==="Date")return new Date(i.getTime());if(n&&n!=="Array")return i;let p=Array.isArray(i)?i.slice():Object.create(Object.getPrototypeOf(i)),c=Object.getOwnPropertyDescriptors(i);if(o){o.set(i,p);for(let x in c){let T=c[x];if("get"in T||"set"in T)continue;T.value=ZA(T.value,o)}}return Object.defineProperties(p,c),p};var jG=(i)=>{let o=nn;return()=>o===nn?o=i():o},Hp=(i)=>typeof i==="function"&&i.length===0;var MA=class extends Function{constructor(...i){let o=i.slice(0,-1),n=i.at(-1);try{super(...o,n)}catch(p){return Xi(`Encountered an unexpected error while compiling your definition:
|
|
48
48
|
Message: ${p}
|
|
49
49
|
Source: (${i.slice(0,-1)}) => {
|
|
50
50
|
${i.at(-1)}
|
|
@@ -82,7 +82,7 @@ Right: ${o}`;var WK=ni({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUn
|
|
|
82
82
|
${T},
|
|
83
83
|
`;if(!n.hasKind("union"))return m;let f=new dx({kind:"Allows",optimistic:!0}).indent();n.compile(f);let F=f.write(`${n.id}Optimistic`);return`${m}${F},
|
|
84
84
|
`},`{
|
|
85
|
-
`)+"}");class Qm{config;resolvedConfig;name;get[No](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(i,o){if(this.config=rx(V.config,o),this.resolvedConfig=rx(V.resolvedConfig,o),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(Vf).length}`,this.name in Vf)U(`A Scope already named ${this.name} already exists`);Vf[this.name]=this,Object.entries(i).map((p)=>this.preparseOwnAliasEntry(...p)).forEach(([p,c])=>{let x=p;if(p[0]==="#"){if(x=p.slice(1),x in this.aliases)U(Pv(x));this.aliases[x]=c}else{if(x in this.aliases)U(Pv(p));this.aliases[x]=c,this.exportedNames.push(x)}if(!a(c,"module")&&!a(c,"generic")&&!Hp(c)){let T=this.preparseOwnDefinitionFormat(c,{alias:x});if(a(T,"root"))this.resolutions[x]=this.bindReference(T);else this.resolutions[x]=this.createParseContext(T).id}}),av??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[av.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=V.intrinsic?pi(V.intrinsic,(p,c)=>p.startsWith("json")?[]:[p,this.bindReference(c)]):{}}cacheGetter(i,o){return Object.defineProperty(this,i,{value:o}),o}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(i){return i}generic=(...i)=>{let o=this;return(n,p)=>new zp(i,p?new Gm(n):n,o,o,p??null)};units=(i,o)=>{let n=[];for(let c of i)if(!n.includes(c))n.push(c);let p=n.map((c)=>this.node("unit",{unit:c},o));return this.node("union",p,{...o,prereduced:!0})};lazyResolutions=[];lazilyResolve(i,o){let n=this.node("alias",{reference:o??"synthetic",resolve:i},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(n);return n}schema=(i,o)=>this.finalize(this.parseSchema(i,o));parseSchema=(i,o)=>this.node(nT(i),i,o);preparseNode(i,o,n){let p=typeof i==="string"?i:nT(o,i);if(Ii(o)&&o.kind===p)return o;if(p==="alias"&&!n?.prereduced){let{reference:T}=fT.implementation.normalize(o,this);if(T.startsWith("$")){let m=this.resolveRoot(T.slice(1));o=m,p=m.kind}}else if(p==="union"&&qo(o,"object")){let T=yK(o);if(T?.length===1)o=T[0],p=nT(o)}if(Ii(o)&&o.kind===p)return o;let x=jc[p].normalize?.(o,this)??o;if(Ii(x))return x.kind===p?x:DK(p,x.kind);return{...n,$:this,kind:p,def:x,prefix:n.alias??p}}bindReference(i){let o;if(Ii(i))o=i.$===this?i:new i.constructor(i.attachments,this);else o=i.$===this?i:new zp(i.params,i.bodyDef,i.$,this,i.hkt);if(!this.resolved)Object.assign(this.referencesById,o.referencesById);return o}resolveRoot(i){return this.maybeResolveRoot(i)??U(Of(i))}maybeResolveRoot(i){let o=this.maybeResolve(i);if(a(o,"generic"))return;return o}maybeResolveSubalias(i){return Sf(this.aliases,i)??Sf(this.ambient,i)}get ambient(){return V.ambient}maybeResolve(i){let o=this.resolutions[i];if(o){if(typeof o!=="string")return this.bindReference(o);let p=bo[o];if(a(p,"root"))return this.resolutions[i]=p;if(a(p,"context")){if(p.phase==="resolving")return this.node("alias",{reference:`$${i}`},{prereduced:!0});if(p.phase==="resolved")return Xi(`Unexpected resolved context for was uncached by its scope: ${oi(p)}`);p.phase="resolving";let c=this.bindReference(this.parseOwnDefinitionFormat(p.def,p));return p.phase="resolved",bo[c.id]=c,bo[p.id]=c,this.resolutions[i]=c}return Xi(`Unexpected nodesById entry for ${o}: ${oi(p)}`)}let n=this.aliases[i]??this.ambient?.[i];if(!n)return this.maybeResolveSubalias(i);if(n=this.normalizeRootScopeValue(n),a(n,"generic"))return this.resolutions[i]=this.bindReference(n);if(a(n,"module"))if(n.root)return this.resolutions[i]=this.bindReference(n.root);else return U(tv(i));return this.resolutions[i]=this.parse(n,{alias:i})}createParseContext(i){let o=i.id??Jf(i.prefix);return bo[o]=Object.assign(i,{[No]:"context",$:this,id:o,phase:"unresolved"})}traversal(i){return new On(i,this.resolvedConfig)}import(...i){return new lc(pi(this.export(...i),(o,n)=>[`#${o}`,n]))}precompilation;_exportedResolutions;_exports;export(...i){if(!this._exports){this._exports={};for(let n of this.exportedNames){let p=this.aliases[n];this._exports[n]=a(p,"module")?Qf(p,this):lv(this.maybeResolve(n))}if(this.lazyResolutions.forEach((n)=>n.resolution),this._exportedResolutions=sv(this,this._exports),this._json=gv(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let n=hv(this.references);this.precompilation=n.write(qv,4),kv(this.references,n)}this.resolved=!0}let o=i.length?i:this.exportedNames;return new lc(pi(o,(n,p)=>[p,this._exports[p]]))}resolve(i){return this.export()[i]}node=(i,o,n={})=>{let p=this.preparseNode(i,o,n);if(Ii(p))return this.bindReference(p);let c=this.createParseContext(p),x=Af(c),T=this.bindReference(x);return bo[c.id]=T};parse=(i,o={})=>this.finalize(this.parseDefinition(i,o));parseDefinition(i,o={}){if(a(i,"root"))return this.bindReference(i);let n=this.preparseOwnDefinitionFormat(i,o);if(a(n,"root"))return this.bindReference(n);let p=this.createParseContext(n);bo[p.id]=p;let c=this.bindReference(this.parseOwnDefinitionFormat(i,p));if(c.isCyclic)c=Wv(c,p.id);return bo[p.id]=c,c}finalize(i){if(lv(i),!i.precompilation&&!this.resolvedConfig.jitless)IK(i.references);return i}}class Ef extends Qm{parseOwnDefinitionFormat(i,o){return Af(o)}preparseOwnDefinitionFormat(i,o){return this.preparseNode(nT(i),i,o)}preparseOwnAliasEntry(i,o){return[i,o]}normalizeRootScopeValue(i){return i}}var lv=(i)=>{return i.references.filter((o)=>o.hasKind("alias")).forEach((o)=>{Object.assign(o.referencesById,o.resolution.referencesById),i.references.forEach((n)=>{if(o.id in n.referencesById)Object.assign(n.referencesById,o.referencesById)})}),i},gv=(i)=>pi(i,(o,n)=>[o,a(n,"root")||a(n,"generic")?n.json:a(n,"module")?gv(n):Xi(`Unexpected resolution ${oi(n)}`)]),Sf=(i,o)=>{let n=o.indexOf(".");if(n===-1)return;let p=o.slice(0,n),c=i[p];if(c===void 0)return;if(!a(c,"module"))return U(BK(p));let x=o.slice(n+1),T=c[x];if(T===void 0)return Sf(c,x);if(a(T,"root")||a(T,"generic"))return T;if(a(T,"module"))return T.root??U(tv(o));Xi(`Unexpected resolution for alias '${o}': ${oi(T)}`)},Vm=(i,o)=>new Ef(i,o),JT=new Ef({});var sv=(i,o)=>{let n={};for(let p in o){let c=o[p];if(a(c,"module")){let x=sv(i,c),T=pi(x,(m,f)=>[`${p}.${m}`,f]);Object.assign(n,T)}else if(a(c,"root")||a(c,"generic"))n[p]=c;else Xi(`Unexpected scope resolution ${oi(c)}`)}return n},Of=(i)=>`'${i}' is unresolvable`,BK=(i)=>`'${i}' must reference a module to be accessed using dot syntax`,tv=(i)=>`Reference to submodule '${i}' must specify an alias`;JT.export();var{schema:Zi,node:qc,defineSchema:FB,generic:Xn}=JT;var _f="^(?:0|[1-9]\\d*)$",NK=new RegExp(_f),AB=ki(NK);var dv=Vm({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();V.intrinsic={...dv};var rv=Vm({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:_f}},{prereducedAliases:!0}).export();Object.assign(V.intrinsic,rv);var bK=Vm({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),h={...dv,...rv,...bK,emptyStructure:qc("structure",{},{prereduced:!0})};V.intrinsic={...h};var i4=(i)=>typeof i==="string"&&i[0]==="d"&&(i[1]==="'"||i[1]==='"')&&i.at(-1)===i[1],ev=(i)=>i.toString()!=="Invalid Date",o4=(i)=>i.slice(2,-1),Lf=(i)=>`'${i}' could not be parsed by the Date constructor`,n4=(i,o)=>jK(i,o),jK=(i,o)=>{let n=new Date(i);if(ev(n))return n;let p=CA(i);if(p!==void 0){let c=new Date(p);if(ev(c))return c}return o?U(o===!0?Lf(i):o):void 0};var Cf=(i,o)=>{let n=i.scanner.shiftUntil(PK[c4[o]]);if(i.scanner.lookahead==="")return i.error(lK(n,o));if(i.scanner.shift(),o==="/"){try{new RegExp(n)}catch(p){U(String(p))}i.root=i.ctx.$.node("intersection",{domain:"string",pattern:n},{prereduced:!0})}else if(di(o,yf))i.root=i.ctx.$.node("unit",{unit:n});else{let p=n4(n,Lf(n));i.root=i.ctx.$.node("unit",{meta:n,unit:p})}},yf={"'":1,'"':1},p4={"/":1,"'":1,'"':1},c4={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},PK={"'":(i)=>i.lookahead==="'",'"':(i)=>i.lookahead==='"',"/":(i)=>i.lookahead==="/"},aK={'"':"double-quote","'":"single-quote","/":"forward slash"},lK=(i,o)=>`${o}${i} requires a closing ${aK[c4[o]]}`;var x4=(i)=>`Private type references should not include '#'. Use '${i}' instead.`,Sm="Optional definitions like 'string?' are only valid as properties in an object or tuple",Em="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var T4={">":!0,">=":!0},m4={"<":!0,"<=":!0};var kc={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},f4=(i)=>`Unmatched )${i===""?"":` before ${i}`}`,Om=(i)=>`Missing ${i}`,F4=(i,o)=>`Left bounds are only valid when paired with right bounds (try ...${o}${i})`,_m=(i)=>`Left-bounded expressions must specify their limits using < or <= (was ${i})`,$4=(i,o,n,p)=>`An expression may have at most one left bound (parsed ${i}${kc[o]}, ${n}${kc[p]})`;var J4=(i,o,n)=>A4(i,o,n,[]),A4=(i,o,n,p)=>{let c=n.parseUntilFinalizer();if(p.push(c.root),c.finalizer===">"){if(p.length!==o.params.length)return n.error(Df(i,o.names,p.map((x)=>x.expression)));return p}if(c.finalizer===",")return A4(i,o,n,p);return c.error(Om(">"))},Df=(i,o,n)=>`${i}<${o.join(", ")}> requires exactly ${o.length} args (got ${n.length}${n.length===0?"":`: ${n.join(", ")}`})`;var If=(i)=>{let o=i.scanner.shiftUntilNextTerminator();if(o==="keyof")i.addPrefix("keyof");else i.root=kK(i,o)},qK=(i,o,n)=>{if(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()!=="<")return n.error(Df(i,o.names,[]));let c=J4(i,o,n);return o(...c)},kK=(i,o)=>hK(i,o)??gK(i,o)??i.error(o===""?i.scanner.lookahead==="#"?x4(i.shiftedByOne().scanner.shiftUntilNextTerminator()):Bf(i):Of(o)),hK=(i,o)=>{if(i.ctx.args?.[o]){let p=i.ctx.args[o];if(typeof p!=="string")return p;return i.ctx.$.node("alias",{reference:p},{prereduced:!0})}let n=i.ctx.$.maybeResolve(o);if(a(n,"root"))return n;if(n===void 0)return;if(a(n,"generic"))return qK(o,n,i);return U(`Unexpected resolution ${oi(n)}`)},gK=(i,o)=>{let n=yA(o);if(n!==void 0)return i.ctx.$.node("unit",{unit:n});let p=IA(o);if(p!==void 0)return i.ctx.$.node("unit",{unit:p})},Bf=(i)=>{let o=i.previousOperator();return o?Nf(o,i.scanner.unscanned):sK(i.scanner.unscanned)},Nf=(i,o="")=>`Token '${i}' requires a right operand${o?` before '${o}'`:""}`,sK=(i)=>`Expected an expression${i?` before '${i}'`:""}`;var bf=(i)=>i.scanner.lookahead===""?i.error(Bf(i)):i.scanner.lookahead==="("?i.shiftedByOne().reduceGroupOpen():i.scanner.lookaheadIsIn(p4)?Cf(i,i.scanner.shift()):i.scanner.lookaheadIsIn(Up)?bf(i.shiftedByOne()):i.scanner.lookahead==="d"?i.scanner.nextLookahead in yf?Cf(i,`${i.scanner.shift()}${i.scanner.shift()}`):If(i):If(i);class Fp extends q1{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in Fp.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...Up};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(i,o)=>i===">"?o[0]==="="?o[1]==="=":o.trimStart()===""||di(o.trimStart()[0],Fp.terminatingChars):i==="="?o[0]!=="=":i===","||i==="?"}var w4=(i,o)=>{let n=tK(i,o);if(i.root.hasKind("unit")){if(typeof i.root.unit==="number"){i.reduceLeftBound(i.root.unit,n),i.unsetRoot();return}if(i.root.unit instanceof Date){let p=`d'${i.root.description??i.root.unit.toISOString()}'`;i.unsetRoot(),i.reduceLeftBound(p,n);return}}return rK(i,n)},X4={"<":1,">":1,"=":1},tK=(i,o)=>i.scanner.lookaheadIs("=")?`${o}${i.scanner.shift()}`:o;var v4=(i,o,n,p)=>{if(n.extends(V.intrinsic.number)){if(typeof o!=="number")return U(jf(i,o,p));return i==="=="?["min","max"]:i[0]===">"?["min"]:["max"]}if(n.extends(V.intrinsic.lengthBoundable)){if(typeof o!=="number")return U(jf(i,o,p));return i==="=="?["exactLength"]:i[0]===">"?["minLength"]:["maxLength"]}if(n.extends(V.intrinsic.Date))return i==="=="?["after","before"]:i[0]===">"?["after"]:["before"];return U(pv(n.expression))},dK=(i)=>({rule:i4(i.limit)?o4(i.limit):i.limit,exclusive:i.comparator.length===1}),rK=(i,o)=>{let n=i.unsetRoot(),p=i.scanner.location;i.parseOperand();let c=i.unsetRoot(),x=i.scanner.sliceChars(p,i.scanner.location);if(i.root=n,!c.hasKind("unit")||typeof c.unit!=="number"&&!(c.unit instanceof Date))return i.error(jf(o,x,"right"));let T=c.unit,m=o.length===1,f=v4(o,typeof T==="number"?T:x,n,"right");for(let $ of f)i.constrainRoot($,o==="=="?{rule:T}:{rule:T,exclusive:m});if(!i.branches.leftBound)return;if(!di(o,m4))return i.error(_m(o));let F=v4(i.branches.leftBound.comparator,i.branches.leftBound.limit,n,"left");i.constrainRoot(F[0],dK(i.branches.leftBound)),i.branches.leftBound=null},jf=(i,o,n)=>`Comparator ${n==="left"?kc[i]:i} must be ${n==="left"?"preceded":"followed"} by a corresponding literal (was ${o})`;var W4=(i)=>{i.scanner.shiftUntilNonWhitespace();let o=i.scanner.shiftUntilNextTerminator();i.root=i.root.brand(o)};var Y4=(i)=>{let o=i.scanner.shiftUntilNextTerminator(),n=DA(o,{errorOnFail:R4(o)});if(n===0)i.error(R4(0));i.root=i.root.constrain("divisor",n)},R4=(i)=>`% operator must be followed by a non-zero integer literal (was ${i})`;var Pf=(i)=>{let o=i.scanner.shift();return o===""?i.finalize(""):o==="["?i.scanner.shift()==="]"?i.setRoot(i.root.array()):i.error(eK):o==="|"?i.scanner.lookahead===">"?i.shiftedByOne().pushRootToBranch("|>"):i.pushRootToBranch(o):o==="&"?i.pushRootToBranch(o):o===")"?i.finalizeGroup():Fp.lookaheadIsFinalizing(o,i.scanner.unscanned)?i.finalize(o):di(o,X4)?w4(i,o):o==="%"?Y4(i):o==="#"?W4(i):(o in Up)?Pf(i):i.error(Lm(o))},Lm=(i,o="")=>`'${i}' is not allowed here${o&&` (should be ${o})`}`,eK="Missing expected ']'";var G4=(i)=>{let o=i.unsetRoot();i.parseOperand();let n=i.unsetRoot();if(!n.hasKind("unit"))return i.error(iH(n.expression));let p=n.unit instanceof Date?()=>new Date(n.unit):n.unit;return[o,"=",p]},iH=(i)=>`Default value '${i}' must a literal value`;var af=(i,o)=>{let n=o.$.maybeResolveRoot(i);if(n)return n;if(i.endsWith("[]")){let x=o.$.maybeResolveRoot(i.slice(0,-2));if(x)return x.array()}let p=new hc(new Fp(i),o),c=oH(p);if(p.finalizer===">")U(Lm(">"));return c},oH=(i)=>{i.parseOperand();let o=AT(i).root;if(!o)return Xi(`Root was unexpectedly unset after parsing string '${i.scanner.scanned}'`);if(i.finalizer==="=")o=G4(i);else if(i.finalizer==="?")o=[o,"?"];if(i.scanner.shiftUntilNonWhitespace(),i.scanner.lookahead)U(Lm(i.scanner.lookahead));return o},AT=(i)=>{while(i.finalizer===void 0)nH(i);return i},nH=(i)=>i.hasRoot()?i.parseOperator():i.parseOperand();class hc{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(i,o){this.scanner=i,this.ctx=o}error(i){return U(i)}hasRoot(){return this.root!==void 0}setRoot(i){this.root=i}unsetRoot(){let i=this.root;return this.root=void 0,i}constrainRoot(...i){this.root=this.root.constrain(i[0],i[1])}finalize(i){if(this.groups.length)return this.error(Om(")"));this.finalizeBranches(),this.finalizer=i}reduceLeftBound(i,o){let n=kc[o];if(!di(n,T4))return this.error(_m(o));if(this.branches.leftBound)return this.error($4(this.branches.leftBound.limit,this.branches.leftBound.comparator,i,n));this.branches.leftBound={comparator:n,limit:i}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let i=this.groups.pop();if(!i)return this.error(f4(this.scanner.unscanned));this.branches=i}addPrefix(i){this.branches.prefixes.push(i)}applyPrefixes(){while(this.branches.prefixes.length){let i=this.branches.prefixes.pop();this.root=i==="keyof"?this.root.keyof():Xi(`Unexpected prefix '${i}'`)}}pushRootToBranch(i){this.assertRangeUnset(),this.applyPrefixes();let o=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(o)??o,i==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,i==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return AT(new hc(this.scanner,this.ctx))}parseOperator(){return Pf(this)}parseOperand(){return bf(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(F4(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}var pH="An empty string is not a valid generic parameter name",Cm=(i,o,n)=>{i.shiftUntilNonWhitespace();let p=i.shiftUntilNextTerminator();if(p===""){if(i.lookahead===""&&o.length)return o;return U(pH)}return i.shiftUntilNonWhitespace(),cH(i,p,o,n)},K4="extends ",cH=(i,o,n,p)=>{if(i.shiftUntilNonWhitespace(),i.unscanned.startsWith(K4))i.jumpForward(K4.length);else{if(i.lookahead===",")i.shift();return n.push(o),Cm(i,n,p)}let c=AT(new hc(i,p));return n.push([o,c.root]),Cm(i,n,p)};class lf extends En{$;constructor(i){super((...o)=>new vT(i)(...o),{bind:i});this.$=i}in(i){return new vT(this.$,i===void 0?void 0:this.$.parse(i))}at(i,o){return new vT(this.$).at(i,o)}case(i,o){return new vT(this.$).case(i,o)}}class vT extends En{$;in;key;branches=[];constructor(i,o){super((n)=>this.caseEntries(Object.entries(n).map(([p,c])=>p==="default"?[p,c]:[this.$.parse(p),c])));this.$=i,this.in=o}at(i,o){if(this.key)U(TH);if(this.branches.length)U(xH);return this.key=i,o?this.match(o):this}case(i,o){return this.caseEntry(this.$.parse(i),o)}caseEntry(i,o){let p=(this.key?this.$.parse({[this.key]:i}):i).pipe(o);return this.branches.push(p),this}match(i){return this(i)}strings(i){return this.caseEntries(Object.entries(i).map(([o,n])=>o==="default"?[o,n]:[this.$.node("unit",{unit:o}),n]))}caseEntries(i){for(let o=0;o<i.length;o++){let[n,p]=i[o];if(n==="default"){if(o!==i.length-1)U("default may only be specified as the last key of a switch definition");return this.default(p)}if(typeof p!=="function")return U(`Value for case "${n}" must be a function (was ${Fo(p)})`);this.caseEntry(n,p)}return this}default(i){if(typeof i==="function")this.case(h.unknown,i);let o={branches:this.branches,ordered:!0};if(i==="never"||i==="assert")o.meta={onFail:H4};let n=this.$.node("union",o);if(!this.in)return this.$.finalize(n);let p=this.in.pipe(n);if(i==="never"||i==="assert")p=p.configureReferences({onFail:H4},"self");return this.$.finalize(p)}}var H4=(i)=>i.throw(),xH="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",TH="At most one key matcher may be specified per expression";var ym=(i,o)=>{if(Oi(i)){if(i[1]==="=")return[o.$.parseOwnDefinitionFormat(i[0],o),"=",i[2]];if(i[1]==="?")return[o.$.parseOwnDefinitionFormat(i[0],o),"?"]}return Dm(i,o)},U4="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",Z4="Only required keys may specify default values, e.g. { value: 'number = 0' }";var M4=(i,o)=>{let n,p={},c=Px(i);for(let[T,m]of c){let f=FH(T);if(f.kind==="spread"){if(!qn(p))return U(fH);let X=o.$.parseOwnDefinitionFormat(m,o);if(X.equals(h.object))continue;if(!X.hasKind("intersection")||!X.basis?.equals(h.object))return U($H(X.expression));n=X.structure;continue}if(f.kind==="undeclared"){if(m!=="reject"&&m!=="delete"&&m!=="ignore")U(mH(m));p.undeclared=m;continue}let F=ym(m,o),$=f;if(f.kind==="required"){if(!Oi(F))qf(p,"required",{key:f.normalized,value:F},o);else qf(p,"optional",F[1]==="="?{key:f.normalized,value:F[0],default:F[2]}:{key:f.normalized,value:F[0]},o);continue}if(Oi(F)){if(F[1]==="?")U(U4);if(F[1]==="=")U(Z4)}if(f.kind==="optional"){qf(p,"optional",{key:f.normalized,value:F},o);continue}let J=o.$.parseOwnDefinitionFormat($.normalized,o),A=um(J,F,o.$);if(A.index)p.index=Ai(p.index,A.index);if(A.required)p.required=Ai(p.required,A.required)}let x=o.$.node("structure",p);return o.$.parseSchema({domain:"object",structure:n?.merge(x)??x})},qf=(i,o,n,p)=>{i[o]=Ai(i[o],p.$.node(o,n))},mH=(i)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${oi(i)})`,fH="Spread operator may only be used as the first key in an object",FH=(i)=>typeof i==="symbol"?{kind:"required",normalized:i}:i.at(-1)==="?"?i.at(-2)===kx?{kind:"required",normalized:`${i.slice(0,-2)}?`}:{kind:"optional",normalized:i.slice(0,-1)}:i[0]==="["&&i.at(-1)==="]"?{kind:"index",normalized:i.slice(1,-1)}:i[0]===kx&&i[1]==="["&&i.at(-1)==="]"?{kind:"required",normalized:i.slice(1)}:i==="..."?{kind:"spread"}:i==="+"?{kind:"undeclared"}:{kind:"required",normalized:i==="\\..."?"...":i==="\\+"?"+":i},$H=(i)=>`Spread operand must resolve to an object literal type (was ${i})`;var u4=(i,o)=>KH(i)?E4[i[0]](i,o):YH(i)?S4[i[1]](i,o):null,JH=(i,o)=>o.$.parseOwnDefinitionFormat(i[1],o).keyof(),kf=(i,o)=>{if(i[2]===void 0)return U(Nf(i[1],""));let n=o.$.parseOwnDefinitionFormat(i[0],o),p=o.$.parseOwnDefinitionFormat(i[2],o);if(i[1]==="|")return o.$.node("union",{branches:[n,p]});let c=i[1]==="&"?so(n,p,o.$):oT(n,p,o.$);if(c instanceof L)return c.throw();return c},AH=(i,o)=>o.$.parseOwnDefinitionFormat(i[0],o).array(),vH=(i,o)=>{if(typeof i[2]!=="function")return U(Q4("=>",i[2]));return o.$.parseOwnDefinitionFormat(i[0],o).pipe(i[2])},Q4=(i,o)=>`${i===":"?"Narrow":"Morph"} expression requires a function following '${i}' (was ${typeof o})`,wH=(i,o)=>{if(typeof i[2]!=="function")return U(Q4(":",i[2]));return o.$.parseOwnDefinitionFormat(i[0],o).constrain("predicate",i[2])},XH=(i,o)=>o.$.parseOwnDefinitionFormat(i[0],o).configureReferences(i[2],"shallow"),V4=(i)=>i,WH=V4({"[]":AH,"?":()=>U(Sm)}),RH=V4({"|":kf,"&":kf,":":wH,"=>":vH,"|>":kf,"@":XH,"=":()=>U(Em)}),S4={...WH,...RH},YH=(i)=>S4[i[1]]!==void 0,GH=(i)=>i,E4=GH({keyof:JH,instanceof:(i,o)=>{if(typeof i[1]!=="function")return U(z4(lx(i[1])));let n=i.slice(1).map((p)=>typeof p==="function"?o.$.node("proto",{proto:p}):U(z4(lx(p))));return n.length===1?n[0]:o.$.node("union",{branches:n})},"===":(i,o)=>o.$.units(i.slice(1))}),KH=(i)=>E4[i[0]]!==void 0,z4=(i)=>`Expected a constructor following 'instanceof' operator (was ${i})`;var L4=(i,o)=>{let n=[{}],p=0;while(p<i.length){let c=!1;if(i[p]==="..."&&p<i.length-1)c=!0,p++;let x=ym(i[p],o),[T,m,f]=!Oi(x)?[x]:x;if(p++,c){if(!T.extends(V.intrinsic.Array))return U(ZH(T.expression));n=n.flatMap((F)=>T.distribute(($)=>UH(Xm(F),$)))}else n=n.map((F)=>{if(m==="?")return C4(F,T);if(m==="=")return HH(F,T,f);return hf(F,T)})}return o.$.parseSchema(n.map((c)=>qn(c)?{proto:Array,exactLength:0}:{proto:Array,sequence:c}))},hf=(i,o)=>{if(i.defaultables||i.optionals)return U(i.variadic?Mf:MH);if(i.variadic)i.postfix=Ai(i.postfix,o);else i.prefix=Ai(i.prefix,o);return i},C4=(i,o)=>{if(i.variadic)return U(y4);return i.optionals=Ai(i.optionals,o),i},HH=(i,o,n)=>{if(i.variadic)return U(y4);if(i.optionals)return U(zH);return i.defaultables=Ai(i.defaultables,[[o,n]]),i},O4=(i,o)=>{if(i.postfix)U(_4);if(i.variadic){if(!i.variadic.equals(o))U(_4)}else i.variadic=o.internal;return i},UH=(i,o)=>{let n=o.select({method:"find",kind:"sequence"});if(!n)return O4(i,V.intrinsic.unknown);if(n.prefix?.forEach((p)=>hf(i,p)),n.optionals?.forEach((p)=>C4(i,p)),n.variadic)O4(i,n.variadic);return n.postfix?.forEach((p)=>hf(i,p)),i},ZH=(i)=>`Spread element must be an array (was ${i})`,_4="A tuple may have at most one variadic element",MH="A required element may not follow an optional element",y4="An optional element may not follow a variadic element";var zH="A defaultable element may not follow an optional element without a default";var uH={},Dm=(i,o)=>{if(typeof i==="string"){if(o.args&&Object.keys(o.args).some((p)=>i.includes(p)))return af(i,o);let n=uH[o.$.name]??={};return n[i]??=af(i,o)}return qo(i,"object")?QH(i,o):U(gf(Fo(i)))},QH=(i,o)=>{let n=ax(i);switch(n){case void 0:if(a(i,"root"))return i;return M4(i,o);case"Array":return VH(i,o);case"RegExp":return o.$.node("intersection",{domain:"string",pattern:i},{prereduced:!0});case"Function":{let p=Hp(i)?i():i;if(a(p,"root"))return p;return U(gf("Function"))}default:return U(gf(n??oi(i)))}},VH=(i,o)=>u4(i,o)??L4(i,o),gf=(i)=>`Type definitions must be strings or objects (was ${i})`;class sf extends En{constructor(i){let o=Object.assign({errors:ho,hkt:So,$:i,raw:i.parse,module:i.constructor.module,scope:i.constructor.scope,define:i.define,match:i.match,generic:i.generic,schema:i.schema,keywords:i.ambient,unit:i.unit,enumerated:i.enumerated,instanceOf:i.instanceOf,valueOf:i.valueOf,or:i.or,and:i.and,merge:i.merge,pipe:i.pipe},i.ambientAttachments);super((...n)=>{if(n.length===1)return i.parse(n[0]);if(n.length===2&&typeof n[0]==="string"&&n[0][0]==="<"&&n[0].at(-1)===">"){let p=n[0].slice(1,-1),c=i.parseGenericParams(p,{});return new zp(c,n[1],i,i,null)}return i.parse(n)},{bind:i,attach:o})}}var gc=V;class Im extends Qm{get ambientAttachments(){if(!gc.typeAttachments)return;return this.cacheGetter("ambientAttachments",pi(gc.typeAttachments,(i,o)=>[i,this.bindReference(o)]))}preparseOwnAliasEntry(i,o){let n=i.indexOf("<");if(n===-1){if(a(o,"module")||a(o,"generic"))return[i,o];let x=this.name==="ark"?i:i==="root"?this.name:`${this.name}.${i}`,T=this.resolvedConfig.keywords?.[x];if(T)o=[o,"@",T];return[i,o]}if(i.at(-1)!==">")U("'>' must be the last character of a generic declaration in a scope");let p=i.slice(0,n),c=i.slice(n+1,-1);return[p,()=>{let x=this.parseGenericParams(c,{alias:p});return rA(x,o,this)}]}parseGenericParams(i,o){return Cm(new Fp(i),[],this.createParseContext({...o,def:i,prefix:"generic"}))}normalizeRootScopeValue(i){if(Hp(i)&&!a(i,"generic"))return i();return i}preparseOwnDefinitionFormat(i,o){return{...o,def:i,prefix:o.alias??"type"}}parseOwnDefinitionFormat(i,o){if(!(o.alias&&(o.alias in this.aliases))&&!o.args)o.args={this:o.id};let p=Dm(i,o);if(Oi(p)){if(p[1]==="=")return U(Em);if(p[1]==="?")return U(Sm)}return p}unit=(i)=>this.units([i]);valueOf=(i)=>this.units(KA(i));enumerated=(...i)=>this.units(i);instanceOf=(i)=>this.node("proto",{proto:i},{prereduced:!0});or=(...i)=>this.schema(i.map((o)=>this.parse(o)));and=(...i)=>i.reduce((o,n)=>o.and(this.parse(n)),this.intrinsic.unknown);merge=(...i)=>i.reduce((o,n)=>o.merge(this.parse(n)),this.intrinsic.object);pipe=(...i)=>this.intrinsic.unknown.pipe(...i);match=new lf(this);declare=()=>({type:this.type});define(i){return i}type=new sf(this);static scope=(i,o={})=>new Im(i,o);static module=(i,o={})=>this.scope(i,o).export()}var tf=Object.assign(Im.scope,{define:(i)=>i}),fi=Im;class D4 extends So{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var SH=Xn(["base",h.object],["props",h.object])((i)=>i.base.merge(i.props),D4),I4=fi.module({Key:h.key,Merge:SH});class B4 extends So{}var EH=Xn("element")((i)=>{let o=i.element.exclude(h.Array),n=o.array();return o.rawOr(n).pipe(Kp).distribute((p)=>p.assertHasKind("morph").declareOut(n),Zi)},B4),N4=fi.module({root:h.Array,readonly:"root",index:h.nonNegativeIntegerString,liftFrom:EH},{name:"Array"});var df=Zi(["string",gp.FileConstructor]),OH=df.rawOr(df.array()),b4=Zi({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:OH}}),j4=fi.module({root:["instanceof",FormData],value:df,parsed:b4,parse:Zi({in:FormData,morphs:(i)=>{let o={};for(let[n,p]of i)if(n in o){let c=o[n];if(typeof c==="string"||c instanceof gp.FileConstructor)o[n]=[c,p];else c.push(p)}else o[n]=p;return o},declaredOut:b4})},{name:"FormData"});var P4=fi.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var _H={Boolean:1,Number:1,String:1},a4=fi.module({...pi({...I1,...N1},(i,o)=>(i in _H)?[]:[i,["instanceof",o]]),Array:N4,TypedArray:P4,FormData:j4});var LH=Zi({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),CH=Zi({domain:"number",divisor:1}),Bm=fi.module({root:h.number,integer:CH,epoch:LH,safe:Zi({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var Pi=(i,o)=>qc("intersection",{domain:"string",pattern:{rule:i.source,flags:i.flags,meta:o}}),l4=Pi(hx,"a well-formed integer string"),ow=fi.module({root:l4,parse:Zi({in:l4,morphs:(i,o)=>{let n=Number.parseInt(i);return Number.isSafeInteger(n)?n:o.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:h.integer})},{name:"string.integer"}),yH=Pi(/^[0-9a-fA-F]+$/,"hex characters only"),DH=fi.module({root:Pi(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,"base64-encoded"),url:Pi(/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2}(?:==|%3D%3D)?|[A-Za-z0-9_-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),q4=Pi(/^[A-Z].*$/,"capitalized"),IH=fi.module({root:Zi({in:"string",morphs:(i)=>i.charAt(0).toUpperCase()+i.slice(1),declaredOut:q4}),preformatted:q4},{name:"string.capitalize"}),BH=(i)=>{let o=i.replace(/[- ]+/g,""),n=0,p,c,x=!1;for(let T=o.length-1;T>=0;T--){if(p=o.substring(T,T+1),c=Number.parseInt(p,10),x)if(c*=2,c>=10)n+=c%10+1;else n+=c;else n+=c;x=!x}return!!(n%10===0?o:!1)},NH=/^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/,bH=Zi({domain:"string",pattern:{meta:"a credit card number",rule:NH.source},predicate:{meta:"a credit card number",predicate:BH}});var jH=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var PH=(i)=>!Number.isNaN(new Date(i).valueOf()),k4=Zi({domain:"string",predicate:{meta:"a parsable date",predicate:PH}}).assertHasKind("intersection"),h4=ow.root.internal.narrow((i,o)=>{let n=Number.parseInt(i),p=Bm.epoch(n);if(p instanceof ho)return o.errors.merge(p),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),aH=fi.module({root:h4,parse:Zi({in:h4,morphs:(i)=>new Date(i),declaredOut:h.Date})},{name:"string.date.epoch"}),g4=Pi(jH,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),lH=fi.module({root:g4,parse:Zi({in:g4,morphs:(i)=>new Date(i),declaredOut:h.Date})},{name:"string.date.iso"}),qH=fi.module({root:k4,parse:Zi({declaredIn:k4,in:"string",morphs:(i,o)=>{let n=new Date(i);if(Number.isNaN(n.valueOf()))return o.error("a parsable date");return n},declaredOut:h.Date}),iso:lH,epoch:aH},{name:"string.date"}),kH=Pi(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,"an email address"),s4="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",up=`(${s4}[.]){3}${s4}`,hH=new RegExp(`^${up}$`),no="(?:[0-9a-fA-F]{1,4})",gH=new RegExp(`^((?:${no}:){7}(?:${no}|:)|(?:${no}:){6}(?:${up}|:${no}|:)|(?:${no}:){5}(?::${up}|(:${no}){1,2}|:)|(?:${no}:){4}(?:(:${no}){0,1}:${up}|(:${no}){1,3}|:)|(?:${no}:){3}(?:(:${no}){0,2}:${up}|(:${no}){1,4}|:)|(?:${no}:){2}(?:(:${no}){0,3}:${up}|(:${no}){1,5}|:)|(?:${no}:){1}(?:(:${no}){0,4}:${up}|(:${no}){1,6}|:)|(?::((?::${no}){0,5}:${up}|(?::${no}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),sH=fi.module({root:["v4 | v6","@","an IP address"],v4:Pi(hH,"an IPv4 address"),v6:Pi(gH,"an IPv6 address")},{name:"string.ip"}),sc="a JSON string",nw=(i)=>{if(!(i instanceof SyntaxError))throw i;return`must be ${sc} (${i})`},tH=Zi({meta:sc,domain:"string",predicate:{meta:sc,predicate:(i,o)=>{try{return JSON.parse(i),!0}catch(n){return o.reject({code:"predicate",expected:sc,problem:nw(n)})}}}}),dH=(i,o)=>{if(i.length===0)return o.error({code:"predicate",expected:sc,actual:"empty"});try{return JSON.parse(i)}catch(n){return o.error({code:"predicate",expected:sc,problem:nw(n)})}},rH=fi.module({root:tH,parse:Zi({meta:"safe JSON string parser",in:"string",morphs:dH,declaredOut:h.jsonObject})},{name:"string.json"}),t4=Pi(/^[a-z]*$/,"only lowercase letters"),eH=fi.module({root:Zi({in:"string",morphs:(i)=>i.toLowerCase(),declaredOut:t4}),preformatted:t4},{name:"string.lower"}),pw=["NFC","NFD","NFKC","NFKD"],wT=pi(pw,(i,o)=>[o,Zi({domain:"string",predicate:(n)=>n.normalize(o)===n,meta:`${o}-normalized unicode`})]),Nm=pi(pw,(i,o)=>[o,Zi({in:"string",morphs:(n)=>n.normalize(o),declaredOut:wT[o]})]),iU=fi.module({root:Nm.NFC,preformatted:wT.NFC},{name:"string.normalize.NFC"}),oU=fi.module({root:Nm.NFD,preformatted:wT.NFD},{name:"string.normalize.NFD"}),nU=fi.module({root:Nm.NFKC,preformatted:wT.NFKC},{name:"string.normalize.NFKC"}),pU=fi.module({root:Nm.NFKD,preformatted:wT.NFKD},{name:"string.normalize.NFKD"}),cU=fi.module({root:"NFC",NFC:iU,NFD:oU,NFKC:nU,NFKD:pU},{name:"string.normalize"}),d4=Pi(Jm,"a well-formed numeric string"),xU=fi.module({root:d4,parse:Zi({in:d4,morphs:(i)=>Number.parseFloat(i),declaredOut:h.number})},{name:"string.numeric"}),TU=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,mU=Pi(TU,"a semantic version (see https://semver.org/)"),r4=Pi(/^\S.*\S$|^\S?$/,"trimmed"),fU=fi.module({root:Zi({in:"string",morphs:(i)=>i.trim(),declaredOut:r4}),preformatted:r4},{name:"string.trim"}),e4=Pi(/^[A-Z]*$/,"only uppercase letters"),FU=fi.module({root:Zi({in:"string",morphs:(i)=>i.toUpperCase(),declaredOut:e4}),preformatted:e4},{name:"string.upper"}),$U=(i)=>{if(URL.canParse)return URL.canParse(i);try{return new URL(i),!0}catch{return!1}},iw=Zi({domain:"string",predicate:{meta:"a URL string",predicate:$U}}),JU=fi.module({root:iw,parse:Zi({declaredIn:iw,in:"string",morphs:(i,o)=>{try{return new URL(i)}catch{return o.error("a URL string")}},declaredOut:Zi(URL)})},{name:"string.url"}),AU=fi.module({root:["versioned | nil | max","@","a UUID"],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i,v1:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv1"),v2:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-2[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv2"),v3:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv3"),v4:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv4"),v5:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv5"),v6:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-6[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv6"),v7:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv7"),v8:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),cw=fi.module({root:h.string,alpha:Pi(/^[A-Za-z]*$/,"only letters"),alphanumeric:Pi(/^[A-Za-z\d]*$/,"only letters and digits 0-9"),hex:yH,base64:DH,capitalize:IH,creditCard:bH,date:qH,digits:Pi(/^\d*$/,"only digits 0-9"),email:kH,integer:ow,ip:sH,json:rH,lower:eH,normalize:cU,numeric:xU,semver:mU,trim:fU,upper:FU,url:JU,uuid:AU},{name:"string"});var xw=fi.module({bigint:h.bigint,boolean:h.boolean,false:h.false,never:h.never,null:h.null,number:h.number,object:h.object,string:h.string,symbol:h.symbol,true:h.true,unknown:h.unknown,undefined:h.undefined}),Tw=fi.module({root:h.unknown,any:h.unknown},{name:"unknown"}),vU=fi.module({root:h.jsonObject,stringify:qc("morph",{in:h.jsonObject,morphs:(i)=>JSON.stringify(i),declaredOut:h.string})},{name:"object.json"}),mw=fi.module({root:h.object,json:vU},{name:"object"});class fw extends So{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var wU=Xn(["K",h.key],"V")((i)=>({domain:"object",index:{signature:i.K,value:i.V}}),fw);class Fw extends So{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var XU=Xn(["T",h.object],["K",h.key])((i)=>i.T.pick(i.K),Fw);class $w extends So{description='omit a set of properties from an object like `Omit(User, "age")`'}var WU=Xn(["T",h.object],["K",h.key])((i)=>i.T.omit(i.K),$w);class Jw extends So{description="make all named properties of an object optional like `Partial(User)`"}var RU=Xn(["T",h.object])((i)=>i.T.partial(),Jw);class Aw extends So{description="make all named properties of an object required like `Required(User)`"}var YU=Xn(["T",h.object])((i)=>i.T.required(),Aw);class vw extends So{description='exclude branches of a union like `Exclude("boolean", "true")`'}var GU=Xn("T","U")((i)=>i.T.exclude(i.U),vw);class ww extends So{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var KU=Xn("T","U")((i)=>i.T.extract(i.U),ww),Xw=fi.module({Exclude:GU,Extract:KU,Omit:WU,Partial:RU,Pick:XU,Record:wU,Required:YU});var Qp=tf({...xw,...Xw,...a4,...I4,string:cw,number:Bm,object:mw,unknown:Tw},{prereducedAliases:!0,name:"ark"}),$o=Qp.export();Object.assign(gc.ambient,$o);gc.typeAttachments={string:$o.string.root,number:$o.number.root,bigint:$o.bigint,boolean:$o.boolean,symbol:$o.symbol,undefined:$o.undefined,null:$o.null,object:$o.object.root,unknown:$o.unknown.root,false:$o.false,true:$o.true,never:$o.never,arrayIndex:$o.Array.index,Key:$o.Key,Record:$o.Record,Array:$o.Array.root,Date:$o.Date};var po=Object.assign(Qp.type,gc.typeAttachments),HU=Qp.match,UU=Qp.generic,Lj=Qp.schema,ZU=Qp.define,MU=Qp.declare;function bm(i=Math.random){return i().toString(36).slice(2)}class XT extends Promise{fate;resolve;reject;done=!1;constructor(i){let o,n;super((p,c)=>{o=p,n=c});this.resolve=o,this.reject=n,this.use(i instanceof Promise?i:new Promise(i))}pass(i,o){if(i===this.fate)this.resolve(o),this.done=!0}fail(i,o){if(i===this.fate)this.reject(o),this.done=!0}use(i){if(i instanceof Promise){let o=i;this.fate=o,o.then((n)=>{this.pass(o,n)},(n)=>{this.fail(o,n)})}else this.resolve(i),this.fate=void 0}}var Ww=(i,o,n=d.STORE)=>{return rf(n,{key:`${i.key}:JSON`,get:({get:p})=>o.toJson(p(i)),set:({set:p},c)=>{p(i,o.fromJson(c))}})};function I(i){while(i.child!==null)i=i.child;return i}class $i{Subscriber;subscribers=new Map;subscribe(i,o){return this.subscribers.set(i,o),()=>{this.unsubscribe(i)}}unsubscribe(i){this.subscribers.delete(i)}next(i){let o=this.subscribers.values();for(let n of o)n(i)}}class ef extends $i{state;constructor(i){super();this.state=i}next(i){this.state=i,super.next(i)}}function dp(i,o,n){let p={key:o.key,type:"atom_family"},c=i.families.get(o.key);if(c)i.logger.error("\u2757","atom_family",o.key,`Overwriting an existing ${hn(c)} "${c.key}" in store "${i.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let x=new $i,m=Object.assign((f)=>{let F=Ji(f),$={key:o.key,subKey:F},J=`${o.key}(${F})`,A=I(i),X=o.default,Y={key:J,default:X instanceof Function?X(f):X};if(o.effects)Y.effects=o.effects(f);let R=rp(A,Y,$);return x.next({type:"state_creation",token:R}),R},p,{subject:x,install:(f)=>dp(f,o),internalRoles:n});return i.families.set(o.key,m),i.defaults.set(o.key,o.default),p}function Rw(i,o){if("mutable"in o)return WT(i,o);return dp(i,o)}function Vp(i,o,n){let p={key:o.key,type:"readonly_selector_family"},c=i.families.get(o.key);if(c)i.logger.error("\u2757","readonly_selector_family",o.key,`Overwriting an existing ${hn(c)} "${c.key}" in store "${i.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let x=new $i,m=Object.assign((f)=>{let F=Ji(f),$={key:o.key,subKey:F},J=`${o.key}(${F})`,A=I(i),X=RT(A,{key:J,get:o.get(f)},$);return x.next({type:"state_creation",token:X}),X},p,{internalRoles:n,subject:x,install:(f)=>Vp(f,o),default:(f)=>{return o.get(f)({get:(...$)=>Mi(i,...$),find:(...$)=>t(i,...$),json:($)=>Jo(i,$)})}});return i.families.set(o.key,m),p}function Yw(i,o){if("set"in o)return YT(i,o);return Vp(i,o)}class jm{_buffer;_index=0;constructor(i){let o;if(typeof i==="number")o=i;else o=i.length;this._buffer=Array.from({length:o})}get buffer(){return this._buffer}get index(){return this._index}add(i){this._buffer[this._index]=i,this._index=(this._index+1)%this._buffer.length}copy(){let i=new jm([...this._buffer]);return i._index=this._index,i}}var zU={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function Gw(i,o){let n=Ji(o),p=`${i.key}(${n})`,c=zU[i.type],x={key:p,type:c};return Object.assign(x,{family:{key:i.key,subKey:n}}),Object.assign(x,{counterfeit:!0}),x}function gn(i){let o={key:i.key,type:i.type};if("family"in i)o.family=i.family;return o}class Ao{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(i,o)=>`${i}:${o}`;warn;getRelatedKeys(i){return this.relations.get(i)}addRelation(i,o){let n=this.relations.get(i),p=this.relations.get(o);if(n)n.add(o);else n=new Set([o]),this.relations.set(i,n);if(p)p.add(i);else p=new Set([i]),this.relations.set(o,p)}deleteRelation(i,o){let n=this.relations.get(i);if(n){if(n.delete(o),n.size===0)this.relations.delete(i);let p=this.relations.get(o);if(p){if(p.delete(i),p.size===0)this.relations.delete(o)}}}replaceRelationsUnsafely(i,o){this.relations.set(i,new Set(o));for(let n of o){let p=new Set().add(i);this.relations.set(n,p)}}replaceRelationsSafely(i,o){let n=this.relations.get(i),p=this.isAType?.(i)?i:void 0,c=p===void 0?i:void 0;if(n)for(let x of n){p??=x,c??=x;let T=this.relations.get(x);if(T){if(T.size===1)this.relations.delete(x);else T.delete(i);this.contents.delete(this.makeContentKey(p,c))}}this.relations.set(i,new Set(o));for(let x of o){let T=this.relations.get(x);if(T)T.add(i);else T=new Set().add(i),this.relations.set(x,T)}}getContentInternal(i){return this.contents.get(i)}setContent(i,o){this.contents.set(i,o)}deleteContent(i){this.contents.delete(i)}constructor(i,o){if(this.a=i.between[0],this.b=i.between[1],this.cardinality=i.cardinality,!o?.externalStore)this.relations=new Map(i.relations?.map(([n,p])=>[n,new Set(p)])),this.contents=new Map(i.contents);if(this.isAType=o?.isAType??null,this.isBType=o?.isBType??null,this.isContent=o?.isContent??null,o?.makeContentKey)this.makeContentKey=o.makeContentKey;if(o?.externalStore){let n=o.externalStore;if(this.has=(p,c)=>n.has(p,c),this.addRelation=(p,c)=>{n.addRelation(p,c)},this.deleteRelation=(p,c)=>{n.deleteRelation(p,c)},this.replaceRelationsSafely=(p,c)=>{n.replaceRelationsSafely(p,c)},this.replaceRelationsUnsafely=(p,c)=>{n.replaceRelationsUnsafely(p,c)},this.getRelatedKeys=(p)=>n.getRelatedKeys(p),n.getContent)this.getContentInternal=(p)=>{return n.getContent(p)},this.setContent=(p,c)=>{n.setContent(p,c)},this.deleteContent=(p)=>{n.deleteContent(p)};for(let[p,c]of i.relations??[]){let x=this.isAType?.(p)?p:void 0,T=x===void 0?p:void 0;for(let m of c)x??=m,T??=m,this.addRelation(x,T)}for(let[p,c]of i.contents??[])this.setContent(p,c)}if(o?.warn)this.warn=o.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([i,o])=>[i,[...o]]),contents:[...this.contents.entries()]}}set(...i){let o,n,p;switch(i.length){case 1:{let c=i[0];o=c[this.a],n=c[this.b],p=void 0;break}case 2:{let c=i[0];if(typeof c==="string")[o,n]=i;else o=c[this.a],n=c[this.b],p=i[1];break}default:{o=i[0],n=i[1],p=i[2];break}}switch(this.cardinality){case"1:1":{let c=this.getRelatedKey(o);if(c&&c!==n)this.delete(o,c)}case"1:n":{let c=this.getRelatedKey(n);if(c&&c!==o)this.delete(c,n)}break;case"n:n":}if(p){let c=this.makeContentKey(o,n);this.setContent(c,p)}return this.addRelation(o,n),this}delete(i,o){o=typeof o==="string"?o:i[this.b];let n=typeof i==="string"?i:i[this.a];if(n===void 0&&typeof o==="string"){let p=this.getRelatedKeys(o);if(p)for(let c of p)this.delete(c,o)}if(typeof n==="string"&&o===void 0){let p=this.getRelatedKeys(n);if(p)for(let c of p)this.delete(n,c)}if(typeof n==="string"&&typeof o==="string"){this.deleteRelation(n,o);let p=this.makeContentKey(n,o);this.deleteContent(p)}return this}getRelatedKey(i){let o=this.getRelatedKeys(i);if(o){if(o.size>1)this.warn?.(`${o.size} related keys were found for key "${i}": (${[...o].map((p)=>`"${p}"`).join(", ")}). Only one related key was expected.`);let n;for(let p of o){n=p;break}return n}}replaceRelations(i,o,n){let p=!Array.isArray(o),c=p?Object.keys(o):o;if(n?.reckless)this.replaceRelationsUnsafely(i,c);else this.replaceRelationsSafely(i,c);if(p)for(let x of c){let T=this.makeContentKey(i,x),m=o[x];this.setContent(T,m)}return this}getContent(i,o){let n=this.makeContentKey(i,o);return this.getContentInternal(n)}getRelationEntries(i){let o=i[this.a],n=i[this.b];if(o!==void 0&&n===void 0){let p=this.getRelatedKeys(o);if(p)return[...p].map((c)=>{return[c,this.getContent(o,c)]})}if(o===void 0&&n!==void 0){let p=this.getRelatedKeys(n);if(p)return[...p].map((c)=>{return[c,this.getContent(c,n)]})}return[]}has(i,o){if(o)return this.getRelatedKeys(i)?.has(o)??!1;return this.relations.has(i)}}function Ho(i){return"epoch"in i.transactionMeta}function zi(i){return"phase"in i.transactionMeta}var Kw=(i)=>{let o=I(i);if(!zi(o)){i.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}i.logger.info("\uD83E\uDE82","transaction",o.transactionMeta.update.key,"Aborting transaction"),o.parent.child=null};function ui(i){return i[0].toUpperCase()+i.slice(1)}function hn(i){return i.type.split("_").map(ui).join(" ")}class ep extends Error{constructor(i,o){super(`${hn(i)} ${Ji(i.key)} not found in store "${o.config.name}".`)}}function tc(i,o,n){return(...p)=>{let c=Ri(i,o);if(c)return c.run(p,n);throw new ep(o,i)}}var Pm=(i)=>(o)=>i instanceof Function?i(o):i;var Sp=(i,o)=>{if(i.valueMap.has(o.key))return i.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),Hw(o,i);switch(o.type){case"selector":case"readonly_selector":return i.logger.info("\uD83E\uDDEE",o.type,o.key,"computing value"),o.get();case"atom":case"mutable_atom":{let n=o.default,p;if(n instanceof Function)p=n();else p=n;return i.logger.info("\uD83D\uDC81","atom",o.key,"could not find cached value; using default",p),p}}};var Uw=(i,o)=>{if(i.operation.open){let n=performance.now();return i.logger.info("\u2757",o.type,o.key,`deferring setState at T-${n} until setState for "${i.operation.token.key}" is done`),n}i.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:o},i.logger.info("\u2B55",o.type,o.key,`operation start in store "${i.config.name}"${!zi(i)?"":` ${i.transactionMeta.phase} "${i.transactionMeta.update.key}"`}`)},Zw=(i)=>{if(i.operation.open)i.logger.info("\uD83D\uDD34",i.operation.token.type,i.operation.token.key,`operation done in store "${i.config.name}"`);i.operation={open:!1},i.on.operationClose.next(i.operation)},Mw=(i,o)=>{if(!i.operation.open)return i.logger.error("\uD83D\uDC1E","unknown",o,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return i.operation.done.has(o)},dc=(i,o)=>{if(!i.operation.open){i.logger.error("\uD83D\uDC1E","unknown",o,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}i.operation.done.add(o)};var zw=(i,o,n)=>{switch(o.type){case"mutable_atom":i.logger.info("\uD83D\uDCE2",o.type,o.key,"is now (",n.newValue,") subscribers:",o.subject.subscribers);break;case"atom":case"selector":case"readonly_selector":i.logger.info("\uD83D\uDCE2",o.type,o.key,"went (",n.oldValue,"->",n.newValue,") subscribers:",o.subject.subscribers)}o.subject.next(n)};var iF=(i,o)=>{let n=I(i),p=n.selectorAtoms.getRelatedKeys(o.key);if(n.logger.info("\uD83E\uDDF9",o.type,o.key,p?`evicting ${p.size} states downstream:`:"no downstream states",p??"to evict"),p){if(n.operation.open)n.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...n.operation.done].join(", ")} ] already done`);for(let c of p){if(Mw(n,c))continue;uw(c,n),dc(n,c)}}};var Qw=(i,o,n)=>{let p=Sp(i,o),c=p;if(o.type==="mutable_atom"&&zi(i)){let{parent:T}=i;c=GT(i,o,T)}if(c=Pm(n)(c),i.logger.info("\uD83D\uDCDD","atom",o.key,"set to",c),c=Wn(i,o.key,c,o.subject),Sw(i,o.key))Ew(i,o.key);dc(i,o.key),iF(i,o);let x={oldValue:p,newValue:c};if(!zi(i)){zw(i,o,x);return}if(i.on.transactionApplying.state===null){let{key:T}=o;if(Vw(x.newValue))return;let m={type:"atom_update",key:T,...x};if(o.family)m.family=o.family;i.transactionMeta.update.updates.push(m),i.logger.info("\uD83D\uDCC1","atom",T,"stowed (",x.oldValue,"->",x.newValue,")")}else if(o.key.startsWith("*")){let T=o.key.slice(1),m=i.atoms.get(T),f=i.valueMap.get(T);if(m.type==="mutable_atom"&&zi(i)){let{parent:$}=i;f=GT(i,m,$)}if(f.do(x.newValue)===null)iF(i,m)}};var am=(i,o,n)=>{switch(o.type){case"atom":case"mutable_atom":Qw(i,o,n);break;case"selector":o.set(n);break}};function Ow(i,o){if(o.family){let n=i.families.get(o.family.key);if(n)return n}}function _i(i,...o){let n,p,c,x;if(o.length===2){if(n=o[0],x=o[1],p=Ow(i,n)??null,p)c=n.family?Wo(n.family.subKey):null,n=t(i,p,c)}else p=o[0],c=o[1],x=o[2],n=t(i,p,c);if("counterfeit"in n&&"family"in n){let f=n.family.subKey,F=i.disposalTraces.buffer.find(($)=>$?.key===f);i.logger.error("\u274C",n.type,n.key,`could not be set because it was not found in the store "${i.config.name}".`,F?`This state was previously disposed:
|
|
85
|
+
`)+"}");class Qm{config;resolvedConfig;name;get[No](){return"scope"}referencesById={};references=[];resolutions={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};intrinsic;constructor(i,o){if(this.config=rx(V.config,o),this.resolvedConfig=rx(V.resolvedConfig,o),this.name=this.resolvedConfig.name??`anonymousScope${Object.keys(Vf).length}`,this.name in Vf)U(`A Scope already named ${this.name} already exists`);Vf[this.name]=this,Object.entries(i).map((p)=>this.preparseOwnAliasEntry(...p)).forEach(([p,c])=>{let x=p;if(p[0]==="#"){if(x=p.slice(1),x in this.aliases)U(Pv(x));this.aliases[x]=c}else{if(x in this.aliases)U(Pv(p));this.aliases[x]=c,this.exportedNames.push(x)}if(!a(c,"module")&&!a(c,"generic")&&!Hp(c)){let T=this.preparseOwnDefinitionFormat(c,{alias:x});if(a(T,"root"))this.resolutions[x]=this.bindReference(T);else this.resolutions[x]=this.createParseContext(T).id}}),av??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[av.hash]=this.node("intersection",{},{prereduced:!0}),this.intrinsic=V.intrinsic?pi(V.intrinsic,(p,c)=>p.startsWith("json")?[]:[p,this.bindReference(c)]):{}}cacheGetter(i,o){return Object.defineProperty(this,i,{value:o}),o}get internal(){return this}_json;get json(){if(!this._json)this.export();return this._json}defineSchema(i){return i}generic=(...i)=>{let o=this;return(n,p)=>new zp(i,p?new Gm(n):n,o,o,p??null)};units=(i,o)=>{let n=[];for(let c of i)if(!n.includes(c))n.push(c);let p=n.map((c)=>this.node("unit",{unit:c},o));return this.node("union",p,{...o,prereduced:!0})};lazyResolutions=[];lazilyResolve(i,o){let n=this.node("alias",{reference:o??"synthetic",resolve:i},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(n);return n}schema=(i,o)=>this.finalize(this.parseSchema(i,o));parseSchema=(i,o)=>this.node(nT(i),i,o);preparseNode(i,o,n){let p=typeof i==="string"?i:nT(o,i);if(Ii(o)&&o.kind===p)return o;if(p==="alias"&&!n?.prereduced){let{reference:T}=fT.implementation.normalize(o,this);if(T.startsWith("$")){let m=this.resolveRoot(T.slice(1));o=m,p=m.kind}}else if(p==="union"&&qo(o,"object")){let T=yK(o);if(T?.length===1)o=T[0],p=nT(o)}if(Ii(o)&&o.kind===p)return o;let x=jc[p].normalize?.(o,this)??o;if(Ii(x))return x.kind===p?x:DK(p,x.kind);return{...n,$:this,kind:p,def:x,prefix:n.alias??p}}bindReference(i){let o;if(Ii(i))o=i.$===this?i:new i.constructor(i.attachments,this);else o=i.$===this?i:new zp(i.params,i.bodyDef,i.$,this,i.hkt);if(!this.resolved)Object.assign(this.referencesById,o.referencesById);return o}resolveRoot(i){return this.maybeResolveRoot(i)??U(Of(i))}maybeResolveRoot(i){let o=this.maybeResolve(i);if(a(o,"generic"))return;return o}maybeResolveSubalias(i){return Sf(this.aliases,i)??Sf(this.ambient,i)}get ambient(){return V.ambient}maybeResolve(i){let o=this.resolutions[i];if(o){if(typeof o!=="string")return this.bindReference(o);let p=bo[o];if(a(p,"root"))return this.resolutions[i]=p;if(a(p,"context")){if(p.phase==="resolving")return this.node("alias",{reference:`$${i}`},{prereduced:!0});if(p.phase==="resolved")return Xi(`Unexpected resolved context for was uncached by its scope: ${oi(p)}`);p.phase="resolving";let c=this.bindReference(this.parseOwnDefinitionFormat(p.def,p));return p.phase="resolved",bo[c.id]=c,bo[p.id]=c,this.resolutions[i]=c}return Xi(`Unexpected nodesById entry for ${o}: ${oi(p)}`)}let n=this.aliases[i]??this.ambient?.[i];if(!n)return this.maybeResolveSubalias(i);if(n=this.normalizeRootScopeValue(n),a(n,"generic"))return this.resolutions[i]=this.bindReference(n);if(a(n,"module"))if(n.root)return this.resolutions[i]=this.bindReference(n.root);else return U(tv(i));return this.resolutions[i]=this.parse(n,{alias:i})}createParseContext(i){let o=i.id??Jf(i.prefix);return bo[o]=Object.assign(i,{[No]:"context",$:this,id:o,phase:"unresolved"})}traversal(i){return new On(i,this.resolvedConfig)}import(...i){return new lc(pi(this.export(...i),(o,n)=>[`#${o}`,n]))}precompilation;_exportedResolutions;_exports;export(...i){if(!this._exports){this._exports={};for(let n of this.exportedNames){let p=this.aliases[n];this._exports[n]=a(p,"module")?Qf(p,this):lv(this.maybeResolve(n))}if(this.lazyResolutions.forEach((n)=>n.resolution),this._exportedResolutions=sv(this,this._exports),this._json=gv(this._exportedResolutions),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless){let n=hv(this.references);this.precompilation=n.write(qv,4),kv(this.references,n)}this.resolved=!0}let o=i.length?i:this.exportedNames;return new lc(pi(o,(n,p)=>[p,this._exports[p]]))}resolve(i){return this.export()[i]}node=(i,o,n={})=>{let p=this.preparseNode(i,o,n);if(Ii(p))return this.bindReference(p);let c=this.createParseContext(p),x=Af(c),T=this.bindReference(x);return bo[c.id]=T};parse=(i,o={})=>this.finalize(this.parseDefinition(i,o));parseDefinition(i,o={}){if(a(i,"root"))return this.bindReference(i);let n=this.preparseOwnDefinitionFormat(i,o);if(a(n,"root"))return this.bindReference(n);let p=this.createParseContext(n);bo[p.id]=p;let c=this.bindReference(this.parseOwnDefinitionFormat(i,p));if(c.isCyclic)c=Wv(c,p.id);return bo[p.id]=c,c}finalize(i){if(lv(i),!i.precompilation&&!this.resolvedConfig.jitless)IK(i.references);return i}}class Ef extends Qm{parseOwnDefinitionFormat(i,o){return Af(o)}preparseOwnDefinitionFormat(i,o){return this.preparseNode(nT(i),i,o)}preparseOwnAliasEntry(i,o){return[i,o]}normalizeRootScopeValue(i){return i}}var lv=(i)=>{return i.references.filter((o)=>o.hasKind("alias")).forEach((o)=>{Object.assign(o.referencesById,o.resolution.referencesById),i.references.forEach((n)=>{if(o.id in n.referencesById)Object.assign(n.referencesById,o.referencesById)})}),i},gv=(i)=>pi(i,(o,n)=>[o,a(n,"root")||a(n,"generic")?n.json:a(n,"module")?gv(n):Xi(`Unexpected resolution ${oi(n)}`)]),Sf=(i,o)=>{let n=o.indexOf(".");if(n===-1)return;let p=o.slice(0,n),c=i[p];if(c===void 0)return;if(!a(c,"module"))return U(BK(p));let x=o.slice(n+1),T=c[x];if(T===void 0)return Sf(c,x);if(a(T,"root")||a(T,"generic"))return T;if(a(T,"module"))return T.root??U(tv(o));Xi(`Unexpected resolution for alias '${o}': ${oi(T)}`)},Vm=(i,o)=>new Ef(i,o),JT=new Ef({});var sv=(i,o)=>{let n={};for(let p in o){let c=o[p];if(a(c,"module")){let x=sv(i,c),T=pi(x,(m,f)=>[`${p}.${m}`,f]);Object.assign(n,T)}else if(a(c,"root")||a(c,"generic"))n[p]=c;else Xi(`Unexpected scope resolution ${oi(c)}`)}return n},Of=(i)=>`'${i}' is unresolvable`,BK=(i)=>`'${i}' must reference a module to be accessed using dot syntax`,tv=(i)=>`Reference to submodule '${i}' must specify an alias`;JT.export();var{schema:Zi,node:qc,defineSchema:FB,generic:Xn}=JT;var _f="^(?:0|[1-9]\\d*)$",NK=new RegExp(_f),AB=ki(NK);var dv=Vm({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();V.intrinsic={...dv};var rv=Vm({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:_f}},{prereducedAliases:!0}).export();Object.assign(V.intrinsic,rv);var bK=Vm({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonData:["$jsonPrimitive","$jsonObject"]},{prereducedAliases:!0}).export(),h={...dv,...rv,...bK,emptyStructure:qc("structure",{},{prereduced:!0})};V.intrinsic={...h};var i4=(i)=>typeof i==="string"&&i[0]==="d"&&(i[1]==="'"||i[1]==='"')&&i.at(-1)===i[1],ev=(i)=>i.toString()!=="Invalid Date",o4=(i)=>i.slice(2,-1),Lf=(i)=>`'${i}' could not be parsed by the Date constructor`,n4=(i,o)=>jK(i,o),jK=(i,o)=>{let n=new Date(i);if(ev(n))return n;let p=CA(i);if(p!==void 0){let c=new Date(p);if(ev(c))return c}return o?U(o===!0?Lf(i):o):void 0};var Cf=(i,o)=>{let n=i.scanner.shiftUntil(PK[c4[o]]);if(i.scanner.lookahead==="")return i.error(lK(n,o));if(i.scanner.shift(),o==="/"){try{new RegExp(n)}catch(p){U(String(p))}i.root=i.ctx.$.node("intersection",{domain:"string",pattern:n},{prereduced:!0})}else if(di(o,yf))i.root=i.ctx.$.node("unit",{unit:n});else{let p=n4(n,Lf(n));i.root=i.ctx.$.node("unit",{meta:n,unit:p})}},yf={"'":1,'"':1},p4={"/":1,"'":1,'"':1},c4={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},PK={"'":(i)=>i.lookahead==="'",'"':(i)=>i.lookahead==='"',"/":(i)=>i.lookahead==="/"},aK={'"':"double-quote","'":"single-quote","/":"forward slash"},lK=(i,o)=>`${o}${i} requires a closing ${aK[c4[o]]}`;var x4=(i)=>`Private type references should not include '#'. Use '${i}' instead.`,Sm="Optional definitions like 'string?' are only valid as properties in an object or tuple",Em="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var T4={">":!0,">=":!0},m4={"<":!0,"<=":!0};var kc={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},f4=(i)=>`Unmatched )${i===""?"":` before ${i}`}`,Om=(i)=>`Missing ${i}`,F4=(i,o)=>`Left bounds are only valid when paired with right bounds (try ...${o}${i})`,_m=(i)=>`Left-bounded expressions must specify their limits using < or <= (was ${i})`,$4=(i,o,n,p)=>`An expression may have at most one left bound (parsed ${i}${kc[o]}, ${n}${kc[p]})`;var J4=(i,o,n)=>A4(i,o,n,[]),A4=(i,o,n,p)=>{let c=n.parseUntilFinalizer();if(p.push(c.root),c.finalizer===">"){if(p.length!==o.params.length)return n.error(Df(i,o.names,p.map((x)=>x.expression)));return p}if(c.finalizer===",")return A4(i,o,n,p);return c.error(Om(">"))},Df=(i,o,n)=>`${i}<${o.join(", ")}> requires exactly ${o.length} args (got ${n.length}${n.length===0?"":`: ${n.join(", ")}`})`;var If=(i)=>{let o=i.scanner.shiftUntilNextTerminator();if(o==="keyof")i.addPrefix("keyof");else i.root=kK(i,o)},qK=(i,o,n)=>{if(n.scanner.shiftUntilNonWhitespace(),n.scanner.shift()!=="<")return n.error(Df(i,o.names,[]));let c=J4(i,o,n);return o(...c)},kK=(i,o)=>hK(i,o)??gK(i,o)??i.error(o===""?i.scanner.lookahead==="#"?x4(i.shiftedByOne().scanner.shiftUntilNextTerminator()):Bf(i):Of(o)),hK=(i,o)=>{if(i.ctx.args?.[o]){let p=i.ctx.args[o];if(typeof p!=="string")return p;return i.ctx.$.node("alias",{reference:p},{prereduced:!0})}let n=i.ctx.$.maybeResolve(o);if(a(n,"root"))return n;if(n===void 0)return;if(a(n,"generic"))return qK(o,n,i);return U(`Unexpected resolution ${oi(n)}`)},gK=(i,o)=>{let n=yA(o);if(n!==void 0)return i.ctx.$.node("unit",{unit:n});let p=IA(o);if(p!==void 0)return i.ctx.$.node("unit",{unit:p})},Bf=(i)=>{let o=i.previousOperator();return o?Nf(o,i.scanner.unscanned):sK(i.scanner.unscanned)},Nf=(i,o="")=>`Token '${i}' requires a right operand${o?` before '${o}'`:""}`,sK=(i)=>`Expected an expression${i?` before '${i}'`:""}`;var bf=(i)=>i.scanner.lookahead===""?i.error(Bf(i)):i.scanner.lookahead==="("?i.shiftedByOne().reduceGroupOpen():i.scanner.lookaheadIsIn(p4)?Cf(i,i.scanner.shift()):i.scanner.lookaheadIsIn(Up)?bf(i.shiftedByOne()):i.scanner.lookahead==="d"?i.scanner.nextLookahead in yf?Cf(i,`${i.scanner.shift()}${i.scanner.shift()}`):If(i):If(i);class Fp extends q1{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in Fp.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...Up};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(i,o)=>i===">"?o[0]==="="?o[1]==="=":o.trimStart()===""||di(o.trimStart()[0],Fp.terminatingChars):i==="="?o[0]!=="=":i===","||i==="?"}var w4=(i,o)=>{let n=tK(i,o);if(i.root.hasKind("unit")){if(typeof i.root.unit==="number"){i.reduceLeftBound(i.root.unit,n),i.unsetRoot();return}if(i.root.unit instanceof Date){let p=`d'${i.root.description??i.root.unit.toISOString()}'`;i.unsetRoot(),i.reduceLeftBound(p,n);return}}return rK(i,n)},X4={"<":1,">":1,"=":1},tK=(i,o)=>i.scanner.lookaheadIs("=")?`${o}${i.scanner.shift()}`:o;var v4=(i,o,n,p)=>{if(n.extends(V.intrinsic.number)){if(typeof o!=="number")return U(jf(i,o,p));return i==="=="?["min","max"]:i[0]===">"?["min"]:["max"]}if(n.extends(V.intrinsic.lengthBoundable)){if(typeof o!=="number")return U(jf(i,o,p));return i==="=="?["exactLength"]:i[0]===">"?["minLength"]:["maxLength"]}if(n.extends(V.intrinsic.Date))return i==="=="?["after","before"]:i[0]===">"?["after"]:["before"];return U(pv(n.expression))},dK=(i)=>({rule:i4(i.limit)?o4(i.limit):i.limit,exclusive:i.comparator.length===1}),rK=(i,o)=>{let n=i.unsetRoot(),p=i.scanner.location;i.parseOperand();let c=i.unsetRoot(),x=i.scanner.sliceChars(p,i.scanner.location);if(i.root=n,!c.hasKind("unit")||typeof c.unit!=="number"&&!(c.unit instanceof Date))return i.error(jf(o,x,"right"));let T=c.unit,m=o.length===1,f=v4(o,typeof T==="number"?T:x,n,"right");for(let $ of f)i.constrainRoot($,o==="=="?{rule:T}:{rule:T,exclusive:m});if(!i.branches.leftBound)return;if(!di(o,m4))return i.error(_m(o));let F=v4(i.branches.leftBound.comparator,i.branches.leftBound.limit,n,"left");i.constrainRoot(F[0],dK(i.branches.leftBound)),i.branches.leftBound=null},jf=(i,o,n)=>`Comparator ${n==="left"?kc[i]:i} must be ${n==="left"?"preceded":"followed"} by a corresponding literal (was ${o})`;var W4=(i)=>{i.scanner.shiftUntilNonWhitespace();let o=i.scanner.shiftUntilNextTerminator();i.root=i.root.brand(o)};var Y4=(i)=>{let o=i.scanner.shiftUntilNextTerminator(),n=DA(o,{errorOnFail:R4(o)});if(n===0)i.error(R4(0));i.root=i.root.constrain("divisor",n)},R4=(i)=>`% operator must be followed by a non-zero integer literal (was ${i})`;var Pf=(i)=>{let o=i.scanner.shift();return o===""?i.finalize(""):o==="["?i.scanner.shift()==="]"?i.setRoot(i.root.array()):i.error(eK):o==="|"?i.scanner.lookahead===">"?i.shiftedByOne().pushRootToBranch("|>"):i.pushRootToBranch(o):o==="&"?i.pushRootToBranch(o):o===")"?i.finalizeGroup():Fp.lookaheadIsFinalizing(o,i.scanner.unscanned)?i.finalize(o):di(o,X4)?w4(i,o):o==="%"?Y4(i):o==="#"?W4(i):(o in Up)?Pf(i):i.error(Lm(o))},Lm=(i,o="")=>`'${i}' is not allowed here${o&&` (should be ${o})`}`,eK="Missing expected ']'";var G4=(i)=>{let o=i.unsetRoot();i.parseOperand();let n=i.unsetRoot();if(!n.hasKind("unit"))return i.error(iH(n.expression));let p=n.unit instanceof Date?()=>new Date(n.unit):n.unit;return[o,"=",p]},iH=(i)=>`Default value '${i}' must a literal value`;var af=(i,o)=>{let n=o.$.maybeResolveRoot(i);if(n)return n;if(i.endsWith("[]")){let x=o.$.maybeResolveRoot(i.slice(0,-2));if(x)return x.array()}let p=new hc(new Fp(i),o),c=oH(p);if(p.finalizer===">")U(Lm(">"));return c},oH=(i)=>{i.parseOperand();let o=AT(i).root;if(!o)return Xi(`Root was unexpectedly unset after parsing string '${i.scanner.scanned}'`);if(i.finalizer==="=")o=G4(i);else if(i.finalizer==="?")o=[o,"?"];if(i.scanner.shiftUntilNonWhitespace(),i.scanner.lookahead)U(Lm(i.scanner.lookahead));return o},AT=(i)=>{while(i.finalizer===void 0)nH(i);return i},nH=(i)=>i.hasRoot()?i.parseOperator():i.parseOperand();class hc{root;branches={prefixes:[],leftBound:null,intersection:null,union:null,pipe:null};finalizer;groups=[];scanner;ctx;constructor(i,o){this.scanner=i,this.ctx=o}error(i){return U(i)}hasRoot(){return this.root!==void 0}setRoot(i){this.root=i}unsetRoot(){let i=this.root;return this.root=void 0,i}constrainRoot(...i){this.root=this.root.constrain(i[0],i[1])}finalize(i){if(this.groups.length)return this.error(Om(")"));this.finalizeBranches(),this.finalizer=i}reduceLeftBound(i,o){let n=kc[o];if(!di(n,T4))return this.error(_m(o));if(this.branches.leftBound)return this.error($4(this.branches.leftBound.limit,this.branches.leftBound.comparator,i,n));this.branches.leftBound={comparator:n,limit:i}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.pipe){this.pushRootToBranch("|>"),this.root=this.branches.pipe;return}if(this.branches.union){this.pushRootToBranch("|"),this.root=this.branches.union;return}if(this.branches.intersection){this.pushRootToBranch("&"),this.root=this.branches.intersection;return}this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let i=this.groups.pop();if(!i)return this.error(f4(this.scanner.unscanned));this.branches=i}addPrefix(i){this.branches.prefixes.push(i)}applyPrefixes(){while(this.branches.prefixes.length){let i=this.branches.prefixes.pop();this.root=i==="keyof"?this.root.keyof():Xi(`Unexpected prefix '${i}'`)}}pushRootToBranch(i){this.assertRangeUnset(),this.applyPrefixes();let o=this.root;if(this.root=void 0,this.branches.intersection=this.branches.intersection?.rawAnd(o)??o,i==="&")return;if(this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null,i==="|")return;this.branches.pipe=this.branches.pipe?.rawPipeOnce(this.branches.union)??this.branches.union,this.branches.union=null}parseUntilFinalizer(){return AT(new hc(this.scanner,this.ctx))}parseOperator(){return Pf(this)}parseOperand(){return bf(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(F4(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null,pipe:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":this.branches.pipe?"|>":void 0)}shiftedByOne(){return this.scanner.shift(),this}}var pH="An empty string is not a valid generic parameter name",Cm=(i,o,n)=>{i.shiftUntilNonWhitespace();let p=i.shiftUntilNextTerminator();if(p===""){if(i.lookahead===""&&o.length)return o;return U(pH)}return i.shiftUntilNonWhitespace(),cH(i,p,o,n)},K4="extends ",cH=(i,o,n,p)=>{if(i.shiftUntilNonWhitespace(),i.unscanned.startsWith(K4))i.jumpForward(K4.length);else{if(i.lookahead===",")i.shift();return n.push(o),Cm(i,n,p)}let c=AT(new hc(i,p));return n.push([o,c.root]),Cm(i,n,p)};class lf extends En{$;constructor(i){super((...o)=>new vT(i)(...o),{bind:i});this.$=i}in(i){return new vT(this.$,i===void 0?void 0:this.$.parse(i))}at(i,o){return new vT(this.$).at(i,o)}case(i,o){return new vT(this.$).case(i,o)}}class vT extends En{$;in;key;branches=[];constructor(i,o){super((n)=>this.caseEntries(Object.entries(n).map(([p,c])=>p==="default"?[p,c]:[this.$.parse(p),c])));this.$=i,this.in=o}at(i,o){if(this.key)U(TH);if(this.branches.length)U(xH);return this.key=i,o?this.match(o):this}case(i,o){return this.caseEntry(this.$.parse(i),o)}caseEntry(i,o){let p=(this.key?this.$.parse({[this.key]:i}):i).pipe(o);return this.branches.push(p),this}match(i){return this(i)}strings(i){return this.caseEntries(Object.entries(i).map(([o,n])=>o==="default"?[o,n]:[this.$.node("unit",{unit:o}),n]))}caseEntries(i){for(let o=0;o<i.length;o++){let[n,p]=i[o];if(n==="default"){if(o!==i.length-1)U("default may only be specified as the last key of a switch definition");return this.default(p)}if(typeof p!=="function")return U(`Value for case "${n}" must be a function (was ${Fo(p)})`);this.caseEntry(n,p)}return this}default(i){if(typeof i==="function")this.case(h.unknown,i);let o={branches:this.branches,ordered:!0};if(i==="never"||i==="assert")o.meta={onFail:H4};let n=this.$.node("union",o);if(!this.in)return this.$.finalize(n);let p=this.in.pipe(n);if(i==="never"||i==="assert")p=p.configureReferences({onFail:H4},"self");return this.$.finalize(p)}}var H4=(i)=>i.throw(),xH="A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')",TH="At most one key matcher may be specified per expression";var ym=(i,o)=>{if(Oi(i)){if(i[1]==="=")return[o.$.parseOwnDefinitionFormat(i[0],o),"=",i[2]];if(i[1]==="?")return[o.$.parseOwnDefinitionFormat(i[0],o),"?"]}return Dm(i,o)},U4="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",Z4="Only required keys may specify default values, e.g. { value: 'number = 0' }";var M4=(i,o)=>{let n,p={},c=Px(i);for(let[T,m]of c){let f=FH(T);if(f.kind==="spread"){if(!qn(p))return U(fH);let X=o.$.parseOwnDefinitionFormat(m,o);if(X.equals(h.object))continue;if(!X.hasKind("intersection")||!X.basis?.equals(h.object))return U($H(X.expression));n=X.structure;continue}if(f.kind==="undeclared"){if(m!=="reject"&&m!=="delete"&&m!=="ignore")U(mH(m));p.undeclared=m;continue}let F=ym(m,o),$=f;if(f.kind==="required"){if(!Oi(F))qf(p,"required",{key:f.normalized,value:F},o);else qf(p,"optional",F[1]==="="?{key:f.normalized,value:F[0],default:F[2]}:{key:f.normalized,value:F[0]},o);continue}if(Oi(F)){if(F[1]==="?")U(U4);if(F[1]==="=")U(Z4)}if(f.kind==="optional"){qf(p,"optional",{key:f.normalized,value:F},o);continue}let J=o.$.parseOwnDefinitionFormat($.normalized,o),A=um(J,F,o.$);if(A.index)p.index=Ai(p.index,A.index);if(A.required)p.required=Ai(p.required,A.required)}let x=o.$.node("structure",p);return o.$.parseSchema({domain:"object",structure:n?.merge(x)??x})},qf=(i,o,n,p)=>{i[o]=Ai(i[o],p.$.node(o,n))},mH=(i)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${oi(i)})`,fH="Spread operator may only be used as the first key in an object",FH=(i)=>typeof i==="symbol"?{kind:"required",normalized:i}:i.at(-1)==="?"?i.at(-2)===kx?{kind:"required",normalized:`${i.slice(0,-2)}?`}:{kind:"optional",normalized:i.slice(0,-1)}:i[0]==="["&&i.at(-1)==="]"?{kind:"index",normalized:i.slice(1,-1)}:i[0]===kx&&i[1]==="["&&i.at(-1)==="]"?{kind:"required",normalized:i.slice(1)}:i==="..."?{kind:"spread"}:i==="+"?{kind:"undeclared"}:{kind:"required",normalized:i==="\\..."?"...":i==="\\+"?"+":i},$H=(i)=>`Spread operand must resolve to an object literal type (was ${i})`;var u4=(i,o)=>KH(i)?E4[i[0]](i,o):YH(i)?S4[i[1]](i,o):null,JH=(i,o)=>o.$.parseOwnDefinitionFormat(i[1],o).keyof(),kf=(i,o)=>{if(i[2]===void 0)return U(Nf(i[1],""));let n=o.$.parseOwnDefinitionFormat(i[0],o),p=o.$.parseOwnDefinitionFormat(i[2],o);if(i[1]==="|")return o.$.node("union",{branches:[n,p]});let c=i[1]==="&"?so(n,p,o.$):oT(n,p,o.$);if(c instanceof L)return c.throw();return c},AH=(i,o)=>o.$.parseOwnDefinitionFormat(i[0],o).array(),vH=(i,o)=>{if(typeof i[2]!=="function")return U(Q4("=>",i[2]));return o.$.parseOwnDefinitionFormat(i[0],o).pipe(i[2])},Q4=(i,o)=>`${i===":"?"Narrow":"Morph"} expression requires a function following '${i}' (was ${typeof o})`,wH=(i,o)=>{if(typeof i[2]!=="function")return U(Q4(":",i[2]));return o.$.parseOwnDefinitionFormat(i[0],o).constrain("predicate",i[2])},XH=(i,o)=>o.$.parseOwnDefinitionFormat(i[0],o).configureReferences(i[2],"shallow"),V4=(i)=>i,WH=V4({"[]":AH,"?":()=>U(Sm)}),RH=V4({"|":kf,"&":kf,":":wH,"=>":vH,"|>":kf,"@":XH,"=":()=>U(Em)}),S4={...WH,...RH},YH=(i)=>S4[i[1]]!==void 0,GH=(i)=>i,E4=GH({keyof:JH,instanceof:(i,o)=>{if(typeof i[1]!=="function")return U(z4(lx(i[1])));let n=i.slice(1).map((p)=>typeof p==="function"?o.$.node("proto",{proto:p}):U(z4(lx(p))));return n.length===1?n[0]:o.$.node("union",{branches:n})},"===":(i,o)=>o.$.units(i.slice(1))}),KH=(i)=>E4[i[0]]!==void 0,z4=(i)=>`Expected a constructor following 'instanceof' operator (was ${i})`;var L4=(i,o)=>{let n=[{}],p=0;while(p<i.length){let c=!1;if(i[p]==="..."&&p<i.length-1)c=!0,p++;let x=ym(i[p],o),[T,m,f]=!Oi(x)?[x]:x;if(p++,c){if(!T.extends(V.intrinsic.Array))return U(ZH(T.expression));n=n.flatMap((F)=>T.distribute(($)=>UH(Xm(F),$)))}else n=n.map((F)=>{if(m==="?")return C4(F,T);if(m==="=")return HH(F,T,f);return hf(F,T)})}return o.$.parseSchema(n.map((c)=>qn(c)?{proto:Array,exactLength:0}:{proto:Array,sequence:c}))},hf=(i,o)=>{if(i.defaultables||i.optionals)return U(i.variadic?Mf:MH);if(i.variadic)i.postfix=Ai(i.postfix,o);else i.prefix=Ai(i.prefix,o);return i},C4=(i,o)=>{if(i.variadic)return U(y4);return i.optionals=Ai(i.optionals,o),i},HH=(i,o,n)=>{if(i.variadic)return U(y4);if(i.optionals)return U(zH);return i.defaultables=Ai(i.defaultables,[[o,n]]),i},O4=(i,o)=>{if(i.postfix)U(_4);if(i.variadic){if(!i.variadic.equals(o))U(_4)}else i.variadic=o.internal;return i},UH=(i,o)=>{let n=o.select({method:"find",kind:"sequence"});if(!n)return O4(i,V.intrinsic.unknown);if(n.prefix?.forEach((p)=>hf(i,p)),n.optionals?.forEach((p)=>C4(i,p)),n.variadic)O4(i,n.variadic);return n.postfix?.forEach((p)=>hf(i,p)),i},ZH=(i)=>`Spread element must be an array (was ${i})`,_4="A tuple may have at most one variadic element",MH="A required element may not follow an optional element",y4="An optional element may not follow a variadic element";var zH="A defaultable element may not follow an optional element without a default";var uH={},Dm=(i,o)=>{if(typeof i==="string"){if(o.args&&Object.keys(o.args).some((p)=>i.includes(p)))return af(i,o);let n=uH[o.$.name]??={};return n[i]??=af(i,o)}return qo(i,"object")?QH(i,o):U(gf(Fo(i)))},QH=(i,o)=>{let n=ax(i);switch(n){case void 0:if(a(i,"root"))return i;return M4(i,o);case"Array":return VH(i,o);case"RegExp":return o.$.node("intersection",{domain:"string",pattern:i},{prereduced:!0});case"Function":{let p=Hp(i)?i():i;if(a(p,"root"))return p;return U(gf("Function"))}default:return U(gf(n??oi(i)))}},VH=(i,o)=>u4(i,o)??L4(i,o),gf=(i)=>`Type definitions must be strings or objects (was ${i})`;class sf extends En{constructor(i){let o=Object.assign({errors:ho,hkt:So,$:i,raw:i.parse,module:i.constructor.module,scope:i.constructor.scope,define:i.define,match:i.match,generic:i.generic,schema:i.schema,keywords:i.ambient,unit:i.unit,enumerated:i.enumerated,instanceOf:i.instanceOf,valueOf:i.valueOf,or:i.or,and:i.and,merge:i.merge,pipe:i.pipe},i.ambientAttachments);super((...n)=>{if(n.length===1)return i.parse(n[0]);if(n.length===2&&typeof n[0]==="string"&&n[0][0]==="<"&&n[0].at(-1)===">"){let p=n[0].slice(1,-1),c=i.parseGenericParams(p,{});return new zp(c,n[1],i,i,null)}return i.parse(n)},{bind:i,attach:o})}}var gc=V;class Im extends Qm{get ambientAttachments(){if(!gc.typeAttachments)return;return this.cacheGetter("ambientAttachments",pi(gc.typeAttachments,(i,o)=>[i,this.bindReference(o)]))}preparseOwnAliasEntry(i,o){let n=i.indexOf("<");if(n===-1){if(a(o,"module")||a(o,"generic"))return[i,o];let x=this.name==="ark"?i:i==="root"?this.name:`${this.name}.${i}`,T=this.resolvedConfig.keywords?.[x];if(T)o=[o,"@",T];return[i,o]}if(i.at(-1)!==">")U("'>' must be the last character of a generic declaration in a scope");let p=i.slice(0,n),c=i.slice(n+1,-1);return[p,()=>{let x=this.parseGenericParams(c,{alias:p});return rA(x,o,this)}]}parseGenericParams(i,o){return Cm(new Fp(i),[],this.createParseContext({...o,def:i,prefix:"generic"}))}normalizeRootScopeValue(i){if(Hp(i)&&!a(i,"generic"))return i();return i}preparseOwnDefinitionFormat(i,o){return{...o,def:i,prefix:o.alias??"type"}}parseOwnDefinitionFormat(i,o){if(!(o.alias&&(o.alias in this.aliases))&&!o.args)o.args={this:o.id};let p=Dm(i,o);if(Oi(p)){if(p[1]==="=")return U(Em);if(p[1]==="?")return U(Sm)}return p}unit=(i)=>this.units([i]);valueOf=(i)=>this.units(KA(i));enumerated=(...i)=>this.units(i);instanceOf=(i)=>this.node("proto",{proto:i},{prereduced:!0});or=(...i)=>this.schema(i.map((o)=>this.parse(o)));and=(...i)=>i.reduce((o,n)=>o.and(this.parse(n)),this.intrinsic.unknown);merge=(...i)=>i.reduce((o,n)=>o.merge(this.parse(n)),this.intrinsic.object);pipe=(...i)=>this.intrinsic.unknown.pipe(...i);match=new lf(this);declare=()=>({type:this.type});define(i){return i}type=new sf(this);static scope=(i,o={})=>new Im(i,o);static module=(i,o={})=>this.scope(i,o).export()}var tf=Object.assign(Im.scope,{define:(i)=>i}),fi=Im;class D4 extends So{description='merge an object\'s properties onto another like `Merge(User, { isAdmin: "true" })`'}var SH=Xn(["base",h.object],["props",h.object])((i)=>i.base.merge(i.props),D4),I4=fi.module({Key:h.key,Merge:SH});class B4 extends So{}var EH=Xn("element")((i)=>{let o=i.element.exclude(h.Array),n=o.array();return o.rawOr(n).pipe(Kp).distribute((p)=>p.assertHasKind("morph").declareOut(n),Zi)},B4),N4=fi.module({root:h.Array,readonly:"root",index:h.nonNegativeIntegerString,liftFrom:EH},{name:"Array"});var df=Zi(["string",gp.FileConstructor]),OH=df.rawOr(df.array()),b4=Zi({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:OH}}),j4=fi.module({root:["instanceof",FormData],value:df,parsed:b4,parse:Zi({in:FormData,morphs:(i)=>{let o={};for(let[n,p]of i)if(n in o){let c=o[n];if(typeof c==="string"||c instanceof gp.FileConstructor)o[n]=[c,p];else c.push(p)}else o[n]=p;return o},declaredOut:b4})},{name:"FormData"});var P4=fi.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]},{name:"TypedArray"});var _H={Boolean:1,Number:1,String:1},a4=fi.module({...pi({...I1,...N1},(i,o)=>(i in _H)?[]:[i,["instanceof",o]]),Array:N4,TypedArray:P4,FormData:j4});var LH=Zi({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),CH=Zi({domain:"number",divisor:1}),Bm=fi.module({root:h.number,integer:CH,epoch:LH,safe:Zi({domain:{domain:"number",numberAllowsNaN:!1},min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]},{name:"number"});var Pi=(i,o)=>qc("intersection",{domain:"string",pattern:{rule:i.source,flags:i.flags,meta:o}}),l4=Pi(hx,"a well-formed integer string"),ow=fi.module({root:l4,parse:Zi({in:l4,morphs:(i,o)=>{let n=Number.parseInt(i);return Number.isSafeInteger(n)?n:o.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:h.integer})},{name:"string.integer"}),yH=Pi(/^[0-9a-fA-F]+$/,"hex characters only"),DH=fi.module({root:Pi(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,"base64-encoded"),url:Pi(/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2}(?:==|%3D%3D)?|[A-Za-z0-9_-]{3}(?:=|%3D)?)?$/,"base64url-encoded")},{name:"string.base64"}),q4=Pi(/^[A-Z].*$/,"capitalized"),IH=fi.module({root:Zi({in:"string",morphs:(i)=>i.charAt(0).toUpperCase()+i.slice(1),declaredOut:q4}),preformatted:q4},{name:"string.capitalize"}),BH=(i)=>{let o=i.replace(/[- ]+/g,""),n=0,p,c,x=!1;for(let T=o.length-1;T>=0;T--){if(p=o.substring(T,T+1),c=Number.parseInt(p,10),x)if(c*=2,c>=10)n+=c%10+1;else n+=c;else n+=c;x=!x}return!!(n%10===0?o:!1)},NH=/^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/,bH=Zi({domain:"string",pattern:{meta:"a credit card number",rule:NH.source},predicate:{meta:"a credit card number",predicate:BH}});var jH=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var PH=(i)=>!Number.isNaN(new Date(i).valueOf()),k4=Zi({domain:"string",predicate:{meta:"a parsable date",predicate:PH}}).assertHasKind("intersection"),h4=ow.root.internal.narrow((i,o)=>{let n=Number.parseInt(i),p=Bm.epoch(n);if(p instanceof ho)return o.errors.merge(p),!1;return!0}).configure({description:"an integer string representing a safe Unix timestamp"},"self").assertHasKind("intersection"),aH=fi.module({root:h4,parse:Zi({in:h4,morphs:(i)=>new Date(i),declaredOut:h.Date})},{name:"string.date.epoch"}),g4=Pi(jH,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),lH=fi.module({root:g4,parse:Zi({in:g4,morphs:(i)=>new Date(i),declaredOut:h.Date})},{name:"string.date.iso"}),qH=fi.module({root:k4,parse:Zi({declaredIn:k4,in:"string",morphs:(i,o)=>{let n=new Date(i);if(Number.isNaN(n.valueOf()))return o.error("a parsable date");return n},declaredOut:h.Date}),iso:lH,epoch:aH},{name:"string.date"}),kH=Pi(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,"an email address"),s4="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",up=`(${s4}[.]){3}${s4}`,hH=new RegExp(`^${up}$`),po="(?:[0-9a-fA-F]{1,4})",gH=new RegExp(`^((?:${po}:){7}(?:${po}|:)|(?:${po}:){6}(?:${up}|:${po}|:)|(?:${po}:){5}(?::${up}|(:${po}){1,2}|:)|(?:${po}:){4}(?:(:${po}){0,1}:${up}|(:${po}){1,3}|:)|(?:${po}:){3}(?:(:${po}){0,2}:${up}|(:${po}){1,4}|:)|(?:${po}:){2}(?:(:${po}){0,3}:${up}|(:${po}){1,5}|:)|(?:${po}:){1}(?:(:${po}){0,4}:${up}|(:${po}){1,6}|:)|(?::((?::${po}){0,5}:${up}|(?::${po}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),sH=fi.module({root:["v4 | v6","@","an IP address"],v4:Pi(hH,"an IPv4 address"),v6:Pi(gH,"an IPv6 address")},{name:"string.ip"}),sc="a JSON string",nw=(i)=>{if(!(i instanceof SyntaxError))throw i;return`must be ${sc} (${i})`},tH=Zi({meta:sc,domain:"string",predicate:{meta:sc,predicate:(i,o)=>{try{return JSON.parse(i),!0}catch(n){return o.reject({code:"predicate",expected:sc,problem:nw(n)})}}}}),dH=(i,o)=>{if(i.length===0)return o.error({code:"predicate",expected:sc,actual:"empty"});try{return JSON.parse(i)}catch(n){return o.error({code:"predicate",expected:sc,problem:nw(n)})}},rH=fi.module({root:tH,parse:Zi({meta:"safe JSON string parser",in:"string",morphs:dH,declaredOut:h.jsonObject})},{name:"string.json"}),t4=Pi(/^[a-z]*$/,"only lowercase letters"),eH=fi.module({root:Zi({in:"string",morphs:(i)=>i.toLowerCase(),declaredOut:t4}),preformatted:t4},{name:"string.lower"}),pw=["NFC","NFD","NFKC","NFKD"],wT=pi(pw,(i,o)=>[o,Zi({domain:"string",predicate:(n)=>n.normalize(o)===n,meta:`${o}-normalized unicode`})]),Nm=pi(pw,(i,o)=>[o,Zi({in:"string",morphs:(n)=>n.normalize(o),declaredOut:wT[o]})]),iU=fi.module({root:Nm.NFC,preformatted:wT.NFC},{name:"string.normalize.NFC"}),oU=fi.module({root:Nm.NFD,preformatted:wT.NFD},{name:"string.normalize.NFD"}),nU=fi.module({root:Nm.NFKC,preformatted:wT.NFKC},{name:"string.normalize.NFKC"}),pU=fi.module({root:Nm.NFKD,preformatted:wT.NFKD},{name:"string.normalize.NFKD"}),cU=fi.module({root:"NFC",NFC:iU,NFD:oU,NFKC:nU,NFKD:pU},{name:"string.normalize"}),d4=Pi(Jm,"a well-formed numeric string"),xU=fi.module({root:d4,parse:Zi({in:d4,morphs:(i)=>Number.parseFloat(i),declaredOut:h.number})},{name:"string.numeric"}),TU=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,mU=Pi(TU,"a semantic version (see https://semver.org/)"),r4=Pi(/^\S.*\S$|^\S?$/,"trimmed"),fU=fi.module({root:Zi({in:"string",morphs:(i)=>i.trim(),declaredOut:r4}),preformatted:r4},{name:"string.trim"}),e4=Pi(/^[A-Z]*$/,"only uppercase letters"),FU=fi.module({root:Zi({in:"string",morphs:(i)=>i.toUpperCase(),declaredOut:e4}),preformatted:e4},{name:"string.upper"}),$U=(i)=>{if(URL.canParse)return URL.canParse(i);try{return new URL(i),!0}catch{return!1}},iw=Zi({domain:"string",predicate:{meta:"a URL string",predicate:$U}}),JU=fi.module({root:iw,parse:Zi({declaredIn:iw,in:"string",morphs:(i,o)=>{try{return new URL(i)}catch{return o.error("a URL string")}},declaredOut:Zi(URL)})},{name:"string.url"}),AU=fi.module({root:["versioned | nil | max","@","a UUID"],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i,v1:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv1"),v2:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-2[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv2"),v3:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv3"),v4:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv4"),v5:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv5"),v6:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-6[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv6"),v7:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv7"),v8:Pi(/^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv8")},{name:"string.uuid"}),cw=fi.module({root:h.string,alpha:Pi(/^[A-Za-z]*$/,"only letters"),alphanumeric:Pi(/^[A-Za-z\d]*$/,"only letters and digits 0-9"),hex:yH,base64:DH,capitalize:IH,creditCard:bH,date:qH,digits:Pi(/^\d*$/,"only digits 0-9"),email:kH,integer:ow,ip:sH,json:rH,lower:eH,normalize:cU,numeric:xU,semver:mU,trim:fU,upper:FU,url:JU,uuid:AU},{name:"string"});var xw=fi.module({bigint:h.bigint,boolean:h.boolean,false:h.false,never:h.never,null:h.null,number:h.number,object:h.object,string:h.string,symbol:h.symbol,true:h.true,unknown:h.unknown,undefined:h.undefined}),Tw=fi.module({root:h.unknown,any:h.unknown},{name:"unknown"}),vU=fi.module({root:h.jsonObject,stringify:qc("morph",{in:h.jsonObject,morphs:(i)=>JSON.stringify(i),declaredOut:h.string})},{name:"object.json"}),mw=fi.module({root:h.object,json:vU},{name:"object"});class fw extends So{description='instantiate an object from an index signature and corresponding value type like `Record("string", "number")`'}var wU=Xn(["K",h.key],"V")((i)=>({domain:"object",index:{signature:i.K,value:i.V}}),fw);class Fw extends So{description='pick a set of properties from an object like `Pick(User, "name | age")`'}var XU=Xn(["T",h.object],["K",h.key])((i)=>i.T.pick(i.K),Fw);class $w extends So{description='omit a set of properties from an object like `Omit(User, "age")`'}var WU=Xn(["T",h.object],["K",h.key])((i)=>i.T.omit(i.K),$w);class Jw extends So{description="make all named properties of an object optional like `Partial(User)`"}var RU=Xn(["T",h.object])((i)=>i.T.partial(),Jw);class Aw extends So{description="make all named properties of an object required like `Required(User)`"}var YU=Xn(["T",h.object])((i)=>i.T.required(),Aw);class vw extends So{description='exclude branches of a union like `Exclude("boolean", "true")`'}var GU=Xn("T","U")((i)=>i.T.exclude(i.U),vw);class ww extends So{description='extract branches of a union like `Extract("0 | false | 1", "number")`'}var KU=Xn("T","U")((i)=>i.T.extract(i.U),ww),Xw=fi.module({Exclude:GU,Extract:KU,Omit:WU,Partial:RU,Pick:XU,Record:wU,Required:YU});var Qp=tf({...xw,...Xw,...a4,...I4,string:cw,number:Bm,object:mw,unknown:Tw},{prereducedAliases:!0,name:"ark"}),$o=Qp.export();Object.assign(gc.ambient,$o);gc.typeAttachments={string:$o.string.root,number:$o.number.root,bigint:$o.bigint,boolean:$o.boolean,symbol:$o.symbol,undefined:$o.undefined,null:$o.null,object:$o.object.root,unknown:$o.unknown.root,false:$o.false,true:$o.true,never:$o.never,arrayIndex:$o.Array.index,Key:$o.Key,Record:$o.Record,Array:$o.Array.root,Date:$o.Date};var ri=Object.assign(Qp.type,gc.typeAttachments),HU=Qp.match,UU=Qp.generic,Lj=Qp.schema,ZU=Qp.define,MU=Qp.declare;function bm(i=Math.random){return i().toString(36).slice(2)}class XT extends Promise{fate;resolve;reject;done=!1;constructor(i){let o,n;super((p,c)=>{o=p,n=c});this.resolve=o,this.reject=n,this.use(i instanceof Promise?i:new Promise(i))}pass(i,o){if(i===this.fate)this.resolve(o),this.done=!0}fail(i,o){if(i===this.fate)this.reject(o),this.done=!0}use(i){if(i instanceof Promise){let o=i;this.fate=o,o.then((n)=>{this.pass(o,n)},(n)=>{this.fail(o,n)})}else this.resolve(i),this.fate=void 0}}var Ww=(i,o,n=d.STORE)=>{return rf(n,{key:`${i.key}:JSON`,get:({get:p})=>o.toJson(p(i)),set:({set:p},c)=>{p(i,o.fromJson(c))}})};function I(i){while(i.child!==null)i=i.child;return i}class $i{Subscriber;subscribers=new Map;subscribe(i,o){return this.subscribers.set(i,o),()=>{this.unsubscribe(i)}}unsubscribe(i){this.subscribers.delete(i)}next(i){let o=this.subscribers.values();for(let n of o)n(i)}}class ef extends $i{state;constructor(i){super();this.state=i}next(i){this.state=i,super.next(i)}}function dp(i,o,n){let p={key:o.key,type:"atom_family"},c=i.families.get(o.key);if(c)i.logger.error("\u2757","atom_family",o.key,`Overwriting an existing ${hn(c)} "${c.key}" in store "${i.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let x=new $i,m=Object.assign((f)=>{let F=Ji(f),$={key:o.key,subKey:F},J=`${o.key}(${F})`,A=I(i),X=o.default,Y={key:J,default:X instanceof Function?X(f):X};if(o.effects)Y.effects=o.effects(f);let R=rp(A,Y,$);return x.next({type:"state_creation",token:R}),R},p,{subject:x,install:(f)=>dp(f,o),internalRoles:n});return i.families.set(o.key,m),i.defaults.set(o.key,o.default),p}function Rw(i,o){if("mutable"in o)return WT(i,o);return dp(i,o)}function Vp(i,o,n){let p={key:o.key,type:"readonly_selector_family"},c=i.families.get(o.key);if(c)i.logger.error("\u2757","readonly_selector_family",o.key,`Overwriting an existing ${hn(c)} "${c.key}" in store "${i.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let x=new $i,m=Object.assign((f)=>{let F=Ji(f),$={key:o.key,subKey:F},J=`${o.key}(${F})`,A=I(i),X=RT(A,{key:J,get:o.get(f)},$);return x.next({type:"state_creation",token:X}),X},p,{internalRoles:n,subject:x,install:(f)=>Vp(f,o),default:(f)=>{return o.get(f)({get:(...$)=>Mi(i,...$),find:(...$)=>t(i,...$),json:($)=>Jo(i,$)})}});return i.families.set(o.key,m),p}function Yw(i,o){if("set"in o)return YT(i,o);return Vp(i,o)}class jm{_buffer;_index=0;constructor(i){let o;if(typeof i==="number")o=i;else o=i.length;this._buffer=Array.from({length:o})}get buffer(){return this._buffer}get index(){return this._index}add(i){this._buffer[this._index]=i,this._index=(this._index+1)%this._buffer.length}copy(){let i=new jm([...this._buffer]);return i._index=this._index,i}}var zU={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function Gw(i,o){let n=Ji(o),p=`${i.key}(${n})`,c=zU[i.type],x={key:p,type:c};return Object.assign(x,{family:{key:i.key,subKey:n}}),Object.assign(x,{counterfeit:!0}),x}function gn(i){let o={key:i.key,type:i.type};if("family"in i)o.family=i.family;return o}class Ao{a;b;cardinality;relations=new Map;contents=new Map;isAType;isBType;isContent;makeContentKey=(i,o)=>`${i}:${o}`;warn;getRelatedKeys(i){return this.relations.get(i)}addRelation(i,o){let n=this.relations.get(i),p=this.relations.get(o);if(n)n.add(o);else n=new Set([o]),this.relations.set(i,n);if(p)p.add(i);else p=new Set([i]),this.relations.set(o,p)}deleteRelation(i,o){let n=this.relations.get(i);if(n){if(n.delete(o),n.size===0)this.relations.delete(i);let p=this.relations.get(o);if(p){if(p.delete(i),p.size===0)this.relations.delete(o)}}}replaceRelationsUnsafely(i,o){this.relations.set(i,new Set(o));for(let n of o){let p=new Set().add(i);this.relations.set(n,p)}}replaceRelationsSafely(i,o){let n=this.relations.get(i),p=this.isAType?.(i)?i:void 0,c=p===void 0?i:void 0;if(n)for(let x of n){p??=x,c??=x;let T=this.relations.get(x);if(T){if(T.size===1)this.relations.delete(x);else T.delete(i);this.contents.delete(this.makeContentKey(p,c))}}this.relations.set(i,new Set(o));for(let x of o){let T=this.relations.get(x);if(T)T.add(i);else T=new Set().add(i),this.relations.set(x,T)}}getContentInternal(i){return this.contents.get(i)}setContent(i,o){this.contents.set(i,o)}deleteContent(i){this.contents.delete(i)}constructor(i,o){if(this.a=i.between[0],this.b=i.between[1],this.cardinality=i.cardinality,!o?.externalStore)this.relations=new Map(i.relations?.map(([n,p])=>[n,new Set(p)])),this.contents=new Map(i.contents);if(this.isAType=o?.isAType??null,this.isBType=o?.isBType??null,this.isContent=o?.isContent??null,o?.makeContentKey)this.makeContentKey=o.makeContentKey;if(o?.externalStore){let n=o.externalStore;if(this.has=(p,c)=>n.has(p,c),this.addRelation=(p,c)=>{n.addRelation(p,c)},this.deleteRelation=(p,c)=>{n.deleteRelation(p,c)},this.replaceRelationsSafely=(p,c)=>{n.replaceRelationsSafely(p,c)},this.replaceRelationsUnsafely=(p,c)=>{n.replaceRelationsUnsafely(p,c)},this.getRelatedKeys=(p)=>n.getRelatedKeys(p),n.getContent)this.getContentInternal=(p)=>{return n.getContent(p)},this.setContent=(p,c)=>{n.setContent(p,c)},this.deleteContent=(p)=>{n.deleteContent(p)};for(let[p,c]of i.relations??[]){let x=this.isAType?.(p)?p:void 0,T=x===void 0?p:void 0;for(let m of c)x??=m,T??=m,this.addRelation(x,T)}for(let[p,c]of i.contents??[])this.setContent(p,c)}if(o?.warn)this.warn=o.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([i,o])=>[i,[...o]]),contents:[...this.contents.entries()]}}set(...i){let o,n,p;switch(i.length){case 1:{let c=i[0];o=c[this.a],n=c[this.b],p=void 0;break}case 2:{let c=i[0];if(typeof c==="string")[o,n]=i;else o=c[this.a],n=c[this.b],p=i[1];break}default:{o=i[0],n=i[1],p=i[2];break}}switch(this.cardinality){case"1:1":{let c=this.getRelatedKey(o);if(c&&c!==n)this.delete(o,c)}case"1:n":{let c=this.getRelatedKey(n);if(c&&c!==o)this.delete(c,n)}break;case"n:n":}if(p){let c=this.makeContentKey(o,n);this.setContent(c,p)}return this.addRelation(o,n),this}delete(i,o){o=typeof o==="string"?o:i[this.b];let n=typeof i==="string"?i:i[this.a];if(n===void 0&&typeof o==="string"){let p=this.getRelatedKeys(o);if(p)for(let c of p)this.delete(c,o)}if(typeof n==="string"&&o===void 0){let p=this.getRelatedKeys(n);if(p)for(let c of p)this.delete(n,c)}if(typeof n==="string"&&typeof o==="string"){this.deleteRelation(n,o);let p=this.makeContentKey(n,o);this.deleteContent(p)}return this}getRelatedKey(i){let o=this.getRelatedKeys(i);if(o){if(o.size>1)this.warn?.(`${o.size} related keys were found for key "${i}": (${[...o].map((p)=>`"${p}"`).join(", ")}). Only one related key was expected.`);let n;for(let p of o){n=p;break}return n}}replaceRelations(i,o,n){let p=!Array.isArray(o),c=p?Object.keys(o):o;if(n?.reckless)this.replaceRelationsUnsafely(i,c);else this.replaceRelationsSafely(i,c);if(p)for(let x of c){let T=this.makeContentKey(i,x),m=o[x];this.setContent(T,m)}return this}getContent(i,o){let n=this.makeContentKey(i,o);return this.getContentInternal(n)}getRelationEntries(i){let o=i[this.a],n=i[this.b];if(o!==void 0&&n===void 0){let p=this.getRelatedKeys(o);if(p)return[...p].map((c)=>{return[c,this.getContent(o,c)]})}if(o===void 0&&n!==void 0){let p=this.getRelatedKeys(n);if(p)return[...p].map((c)=>{return[c,this.getContent(c,n)]})}return[]}has(i,o){if(o)return this.getRelatedKeys(i)?.has(o)??!1;return this.relations.has(i)}}function Ho(i){return"epoch"in i.transactionMeta}function zi(i){return"phase"in i.transactionMeta}var Kw=(i)=>{let o=I(i);if(!zi(o)){i.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}i.logger.info("\uD83E\uDE82","transaction",o.transactionMeta.update.key,"Aborting transaction"),o.parent.child=null};function ui(i){return i[0].toUpperCase()+i.slice(1)}function hn(i){return i.type.split("_").map(ui).join(" ")}class ep extends Error{constructor(i,o){super(`${hn(i)} ${Ji(i.key)} not found in store "${o.config.name}".`)}}function tc(i,o,n){return(...p)=>{let c=Ri(i,o);if(c)return c.run(p,n);throw new ep(o,i)}}var Pm=(i)=>(o)=>i instanceof Function?i(o):i;var Sp=(i,o)=>{if(i.valueMap.has(o.key))return i.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),Hw(o,i);switch(o.type){case"selector":case"readonly_selector":return i.logger.info("\uD83E\uDDEE",o.type,o.key,"computing value"),o.get();case"atom":case"mutable_atom":{let n=o.default,p;if(n instanceof Function)p=n();else p=n;return i.logger.info("\uD83D\uDC81","atom",o.key,"could not find cached value; using default",p),p}}};var Uw=(i,o)=>{if(i.operation.open){let n=performance.now();return i.logger.info("\u2757",o.type,o.key,`deferring setState at T-${n} until setState for "${i.operation.token.key}" is done`),n}i.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:o},i.logger.info("\u2B55",o.type,o.key,`operation start in store "${i.config.name}"${!zi(i)?"":` ${i.transactionMeta.phase} "${i.transactionMeta.update.key}"`}`)},Zw=(i)=>{if(i.operation.open)i.logger.info("\uD83D\uDD34",i.operation.token.type,i.operation.token.key,`operation done in store "${i.config.name}"`);i.operation={open:!1},i.on.operationClose.next(i.operation)},Mw=(i,o)=>{if(!i.operation.open)return i.logger.error("\uD83D\uDC1E","unknown",o,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return i.operation.done.has(o)},dc=(i,o)=>{if(!i.operation.open){i.logger.error("\uD83D\uDC1E","unknown",o,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}i.operation.done.add(o)};var zw=(i,o,n)=>{switch(o.type){case"mutable_atom":i.logger.info("\uD83D\uDCE2",o.type,o.key,"is now (",n.newValue,") subscribers:",o.subject.subscribers);break;case"atom":case"selector":case"readonly_selector":i.logger.info("\uD83D\uDCE2",o.type,o.key,"went (",n.oldValue,"->",n.newValue,") subscribers:",o.subject.subscribers)}o.subject.next(n)};var iF=(i,o)=>{let n=I(i),p=n.selectorAtoms.getRelatedKeys(o.key);if(n.logger.info("\uD83E\uDDF9",o.type,o.key,p?`evicting ${p.size} states downstream:`:"no downstream states",p??"to evict"),p){if(n.operation.open)n.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...n.operation.done].join(", ")} ] already done`);for(let c of p){if(Mw(n,c))continue;uw(c,n),dc(n,c)}}};var Qw=(i,o,n)=>{let p=Sp(i,o),c=p;if(o.type==="mutable_atom"&&zi(i)){let{parent:T}=i;c=GT(i,o,T)}if(c=Pm(n)(c),i.logger.info("\uD83D\uDCDD","atom",o.key,"set to",c),c=Wn(i,o.key,c,o.subject),Sw(i,o.key))Ew(i,o.key);dc(i,o.key),iF(i,o);let x={oldValue:p,newValue:c};if(!zi(i)){zw(i,o,x);return}if(i.on.transactionApplying.state===null){let{key:T}=o;if(Vw(x.newValue))return;let m={type:"atom_update",key:T,...x};if(o.family)m.family=o.family;i.transactionMeta.update.updates.push(m),i.logger.info("\uD83D\uDCC1","atom",T,"stowed (",x.oldValue,"->",x.newValue,")")}else if(o.key.startsWith("*")){let T=o.key.slice(1),m=i.atoms.get(T),f=i.valueMap.get(T);if(m.type==="mutable_atom"&&zi(i)){let{parent:$}=i;f=GT(i,m,$)}if(f.do(x.newValue)===null)iF(i,m)}};var am=(i,o,n)=>{switch(o.type){case"atom":case"mutable_atom":Qw(i,o,n);break;case"selector":o.set(n);break}};function Ow(i,o){if(o.family){let n=i.families.get(o.family.key);if(n)return n}}function _i(i,...o){let n,p,c,x;if(o.length===2){if(n=o[0],x=o[1],p=Ow(i,n)??null,p)c=n.family?Wo(n.family.subKey):null,n=t(i,p,c)}else p=o[0],c=o[1],x=o[2],n=t(i,p,c);if("counterfeit"in n&&"family"in n){let f=n.family.subKey,F=i.disposalTraces.buffer.find(($)=>$?.key===f);i.logger.error("\u274C",n.type,n.key,`could not be set because it was not found in the store "${i.config.name}".`,F?`This state was previously disposed:
|
|
86
86
|
${F.trace}`:"No previous disposal trace was found.");return}let T=Uw(i,n);if(T){let f=i.on.operationClose.subscribe(`waiting to set "${n.key}" at T-${T}`,()=>{f(),i.logger.info("\uD83D\uDFE2",n.type,n.key,`resuming deferred setState from T-${T}`),_i(i,n,x)});return}let m=Ri(i,n);am(i,m,x),Zw(i)}function lm(i,o,n){let{key:p,newValue:c,oldValue:x}=o,T=i==="newValue"?c:x,m={key:p,type:"atom"};if(o.family)Object.assign(m,{family:o.family});_i(n,m,T)}function _w(i){let{stack:o}=i;if(o)return`
|
|
87
87
|
`+o.split(`
|
|
88
88
|
`)?.slice(1)?.join(`
|
|
@@ -95,8 +95,8 @@ ${X.trace}`:`No previous disposal trace for ${n} was found.`);return}let c=i.mol
|
|
|
95
95
|
${A.trace}`:`No previous disposal trace for ${c} was found.`),n}let m=Ji(o),f=x.molecules.get(m);if(!f){let A=i.disposalTraces.buffer.find((X)=>X?.key===m);return i.logger.error("\u274C","molecule",n,"claim failed:",`Could not allocate to ${m} in store "${i.config.name}".`,A?`
|
|
96
96
|
${m} was most recently disposed
|
|
97
97
|
${A.trace}`:`No previous disposal trace for ${m} was found.`),n}let F=i.moleculeGraph.getRelationEntries({downstreamMoleculeKey:T.stringKey}).filter(([,{source:A}])=>A!==c).map(([A])=>Wo(A));if(p)x.moleculeGraph.delete(c);x.moleculeGraph.set({upstreamMoleculeKey:f.stringKey,downstreamMoleculeKey:T.stringKey},{source:f.stringKey});let $={type:"molecule_transfer",key:T.key,from:F,to:[f.key]};if(zi(x)&&x.transactionMeta.phase==="building")x.transactionMeta.update.updates.push($);return n}function oF(i,o,n){switch(o){case"newValue":{yw(i,n);break}case"oldValue":{nc(n,i.token);break}}}function nF(i,o,n){switch(o){case"newValue":{nc(n,i.token);break}case"oldValue":{if(yw(i,n),i.subType==="atom")n.valueMap.set(i.token.key,i.value);break}}}function yw(i,o){let{family:n}=i.token;if(n){let p=o.families.get(n.key);if(p)t(o,p,Wo(n.subKey))}}function Dw(i,o,n){switch(o){case"newValue":ic(n,i.provenance,i.key);break;case"oldValue":oc(n,i.key);break}}function Iw(i,o,n){switch(o){case"newValue":oc(n,i.key);break;case"oldValue":{let p=i.provenance.map(Wo);ic(n,p,i.key);for(let[c,x]of i.values){let T=n.families.get(c);if(T){t(n,T,i.key);let m=`${c}(${Ji(i.key)})`;n.valueMap.set(m,x)}}}break}}function Bw(i,o,n){switch(o){case"newValue":{let p=i.to.length===1?i.to[0]:i.to;rc(n,p,i.key,"exclusive")}break;case"oldValue":{let p=i.from.length===1?i.from[0]:i.from;rc(n,p,i.key,"exclusive")}break}}function qm(i,o,n){let p=i==="newValue"?o.updates:[...o.updates].reverse();for(let c of p)switch(c.type){case"atom_update":case"selector_update":lm(i,c,n);break;case"state_creation":oF(c,i,n);break;case"state_disposal":nF(c,i,n);break;case"molecule_creation":Dw(c,i,n);break;case"molecule_disposal":Iw(c,i,n);break;case"molecule_transfer":Bw(c,i,n);break;case"transaction_update":qm(i,c,n);break}}function pF(i,o){return i.transactionMeta.actionContinuities.getRelatedKey(o)}function uU(i,o){return i.transactionMeta.epoch.get(o)}function Nw(i,o){if(!Ho(i))return;let p=pF(i,o);if(p===void 0)return;return uU(i,p)}function bw(i,o,n){if(Ho(i)&&o)i.transactionMeta.epoch.set(o,n)}function jw(i,o,n){if(!Ho(i))return;let c=pF(i,o);if(c!==void 0)i.transactionMeta.epoch.set(c,n)}var Pw=(i,o)=>{let n=I(o),{parent:p}=n;if(p===null||!zi(n)||n.transactionMeta?.phase!=="building"){o.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}n.transactionMeta.phase="applying",n.transactionMeta.update.output=i,p.child=null,p.on.transactionApplying.next(n.transactionMeta);let{updates:c}=n.transactionMeta.update;if(o.logger.info("\uD83D\uDEC4","transaction",n.transactionMeta.update.key,`Applying transaction with ${c.length} updates:`,c),qm("newValue",n.transactionMeta.update,p),Ho(p))jw(p,n.transactionMeta.update.key,n.transactionMeta.update.epoch),Ri(o,{key:n.transactionMeta.update.key,type:"transaction"})?.subject.next(n.transactionMeta.update),o.logger.info("\uD83D\uDEEC","transaction",n.transactionMeta.update.key,"Finished applying transaction.");else if(zi(p))p.transactionMeta.update.updates.push(n.transactionMeta.update);p.on.transactionApplying.next(null)};function aw(i,o,n){if(!Ho(i))return;let{epoch:c,actionContinuities:x}=i.transactionMeta;if(x.set(o,n),!c.has(o))c.set(o,-1)}function lw(i){return{store:i}}function Mi(i,...o){let n,p,c;if(o.length===1)n=o[0];else p=o[0],c=o[1],n=t(i,p,c);if("counterfeit"in n&&"family"in n){p=i.families.get(n.family.key);let x=n.family.subKey,T=i.disposalTraces.buffer.find((m)=>m?.key===x);switch(i.logger.error("\u274C",n.type,n.key,`could not be retrieved because it was not found in the store "${i.config.name}".`,T?`This state was previously disposed:
|
|
98
|
-
${T.trace}`:"No previous disposal trace was found."),p.type){case"atom_family":case"mutable_atom_family":return i.defaults.get(p.key);case"selector_family":case"readonly_selector_family":{if(i.defaults.has(p.key))return i.defaults.get(n.family.key);let m=Ri(i,p).default(x);return i.defaults.set(p.key,m),m}}}return Sp(i,Ri(i,n))}class Rn extends Map{deleted=new Set;source;constructor(i){super();this.source=i}get(i){if(super.has(i))return super.get(i);if(!this.deleted.has(i)&&this.source.has(i))return this.source.get(i);return}set(i,o){return this.deleted.delete(i),super.set(i,o)}hasOwn(i){return super.has(i)}has(i){return!this.deleted.has(i)&&(super.has(i)||this.source.has(i))}delete(i){return this.deleted.add(i),super.delete(i)}}var qw=(i,o,n,p)=>{let c=I(i),x={parent:c,child:null,on:c.on,loggers:c.loggers,logger:c.logger,config:c.config,atoms:new Rn(c.atoms),atomsThatAreDefault:new Set(c.atomsThatAreDefault),families:new Rn(c.families),joins:new Rn(c.joins),operation:{open:!1},readonlySelectors:new Rn(c.readonlySelectors),timelines:new Rn(c.timelines),timelineTopics:new Ao(c.timelineTopics.toJSON()),trackers:new Map,transactions:new Rn(c.transactions),selectorAtoms:new Ao(c.selectorAtoms.toJSON()),selectorGraph:new Ao(c.selectorGraph.toJSON(),{makeContentKey:(...F)=>F.sort().join(":")}),selectors:new Rn(c.selectors),valueMap:new Rn(c.valueMap),defaults:c.defaults,disposalTraces:i.disposalTraces.copy(),molecules:new Rn(c.molecules),moleculeGraph:new Ao(c.moleculeGraph.toJSON(),{makeContentKey:c.moleculeGraph.makeContentKey}),moleculeData:new Ao(c.moleculeData.toJSON(),{makeContentKey:c.moleculeData.makeContentKey}),moleculeJoins:new Ao(c.moleculeJoins.toJSON(),{makeContentKey:c.moleculeJoins.makeContentKey}),miscResources:new Rn(c.miscResources)},T=Nw(i,o),m={phase:"building",update:{type:"transaction_update",key:o,id:p,epoch:T===void 0?Number.NaN:T+1,updates:[],params:n,output:void 0},toolkit:{get:(...F)=>Mi(f,...F),set:(...F)=>{_i(f,...F)},run:(F,$=bm())=>tc(f,F,$),find:(...F)=>t(i,...F),json:(F)=>Jo(f,F),dispose:(...F)=>{nc(f,...F)},env:()=>lw(f)}},f=Object.assign(x,{transactionMeta:m});return c.child=f,i.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",n),f};function cF(i,o){let n={key:o.key,type:"transaction",run:(x,T)=>{let m=qw(i,o.key,x,T);try{let f=I(i),{toolkit:F}=m.transactionMeta,$=o.do(F,...x);return Pw($,f),$}catch(f){throw Kw(p),i.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",f),f}},install:(x)=>cF(x,o),subject:new $i},p=I(i);p.transactions.set(n.key,n);let c=gn(n);return i.on.transactionCreation.next(c),c}class kw{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new Ao({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new Ao({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...i)=>i.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new Ao({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new Ao({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new jm(100);molecules=new Map;moleculeJoins=new Ao({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...i)=>i.sort().join(":")});moleculeGraph=new Ao({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...i)=>i.sort().join(":")});moleculeData=new Ao({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...i)=>i.sort().join(":")});miscResources=new Map;on={atomCreation:new $i,atomDisposal:new $i,selectorCreation:new $i,selectorDisposal:new $i,timelineCreation:new $i,transactionCreation:new $i,transactionApplying:new ef(null),operationClose:new $i,moleculeCreation:new $i,moleculeDisposal:new $i};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new pc("warn",(i,o,n)=>!hw(n))];logger={error:(...i)=>{for(let o of this.loggers)o.error(...i)},info:(...i)=>{for(let o of this.loggers)o.info(...i)},warn:(...i)=>{for(let o of this.loggers)o.warn(...i)}};constructor(i,o=null){if(this.config={...o?.config,...i},o!==null){if(this.valueMap=new Map(o?.valueMap),this.operation={...o?.operation},Ho(o))this.transactionMeta={epoch:new Map(o?.transactionMeta.epoch),actionContinuities:new Ao(o?.transactionMeta.actionContinuities.toJSON())};for(let[,p]of o.families){if(p.internalRoles?.includes("mutable")||p.internalRoles?.includes("join"))continue;p.install(this)}let n=new Set;for(let[,p]of o.atoms){if(n.has(p.key))continue;if(p.install(this),p.type==="mutable_atom"){let c=Jo(o,p),x=$p(p);n.add(c.key),n.add(x.key)}}for(let[,p]of o.readonlySelectors)p.install(this);for(let[,p]of o.selectors){if(n.has(p.key))continue;p.install(this)}for(let[,p]of o.transactions)p.install(this);for(let[,p]of o.timelines)p.install(this)}}}var d={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new kw({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function Ri(i,o){let n,p=i;while(p!==null){switch(o.type){case"atom":case"mutable_atom":n=p.atoms.get(o.key);break;case"selector":n=p.selectors.get(o.key);break;case"readonly_selector":n=p.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":n=p.families.get(o.key);break;case"timeline":n=p.timelines.get(o.key);break;case"transaction":n=p.transactions.get(o.key);break}if(n)return n;p=p.child}throw new ep(o,i)}function gw(i,o,n){let p=i.families.get(o.key);if(p===void 0)throw new ep(o,i);let c=p(n),x=I(i);if(c.family){if(Ho(x))switch(c.type){case"atom":case"mutable_atom":i.on.atomCreation.next(c);break;case"selector":case"readonly_selector":i.on.selectorCreation.next(c);break}else if(zi(x)&&x.on.transactionApplying.state===null)x.transactionMeta.update.updates.push({type:"state_creation",token:c})}return c}function sw(i,o,n){let p=Ji(n),c=`${o.key}(${p})`,x=I(i),T;switch(o.type){case"atom_family":case"mutable_atom_family":T=x.atoms.get(c);break;case"selector_family":T=x.selectors.get(c);break;case"readonly_selector_family":T=x.readonlySelectors.get(c);break}if(T)return gn(T);return T}function t(i,o,n){let p=sw(i,o,n);if(p)return p;let c=Ji(n),x=i.molecules.get(c);if(!x&&i.config.lifespan==="immortal"){let T=Gw(o,n);return i.logger.error("\u274C",T.type,T.key,`was not found in store "${i.config.name}"; returned a counterfeit token.`),T}if(p=gw(i,o,n),x)I(i).moleculeData.set(c,o.key);return p}function nc(i,...o){let n;if(o.length===1)n=o[0];else{let p=o[0],c=o[1];n=t(i,p,c)}try{Ri(i,n)}catch(p){i.logger.error("\u274C",n.type,n.key,`could not be disposed because it was not found in the store "${i.config.name}".`);return}switch(n.type){case"atom":case"mutable_atom":xF(i,n);break;case"selector":case"readonly_selector":tw(i,n);break}}var km=(i,o)=>I(i).atoms.has(o),QU=(i,o)=>I(i).selectors.has(o),VU=(i,o)=>I(i).readonlySelectors.has(o),dw=(i,o)=>km(i,o)||QU(i,o)||VU(i,o);var hm=(i,o)=>{return I(o).selectorGraph.getRelationEntries({downstreamSelectorKey:i}).filter(([p,{source:c}])=>c!==i).map(([p,{source:c}])=>c).filter((p)=>dw(o,p))};var TF=(i,o,n)=>{let p=[],c=hm(i,n);while(c.length>0){let x=c.shift();if(o.has(x))continue;if(o.add(x),!km(n,x))c.push(...hm(x,n));else if(!p.includes(x))p.push(x)}return p},rw=(i,o)=>{let n=i.key,p=hm(n,o),c=new Set;return p.flatMap((x)=>km(o,x)?x:TF(x,c,o))};var ew=(i,o,n,p)=>{let c=I(p);if(o.type==="atom"||o.type==="mutable_atom")c.selectorAtoms.set({selectorKey:i,atomKey:o.key}),p.logger.info("\uD83D\uDD0D","selector",i,`discovers root atom "${o.key}"`);else{let x=TF(o.key,n,p);p.logger.info("\uD83D\uDD0D","selector",i,`discovers root atoms: [ ${x.map((T)=>`"${T}"`).join(", ")} ]`);for(let T of x)c.selectorAtoms=c.selectorAtoms.set({selectorKey:i,atomKey:T})}n.add(o.key)};var gm=(i,o,n)=>({get:(...p)=>{let c=I(n),x;if(p.length===2){let[f,F]=p;x=t(n,f,F)}else[x]=p;let T=Ri(n,x),m=Sp(n,T);return n.logger.info("\uD83D\uDD0C","selector",i,`registers dependency ( "${x.key}" =`,m,")"),c.selectorGraph.set({upstreamSelectorKey:x.key,downstreamSelectorKey:i},{source:x.key}),ew(i,x,o,n),m},set:(...p)=>{let c,x;if(p.length===2)c=p[0],x=p[1];else{let f=p[0],F=p[1];x=p[2],c=t(n,f,F)}let T=I(n),m=Ri(T,c);am(T,m,x)},find:(...p)=>t(n,...p),json:(p)=>Jo(n,p)});var RT=(i,o,n)=>{let p=I(i),c=new $i,x=new Set,{get:T,find:m,json:f}=gm(o.key,x,p),F=()=>{let X=o.get({get:T,find:m,json:f});return Wn(I(i),o.key,X,c),x.clear(),X},$={...o,subject:c,install:(X)=>RT(X,o,n),get:F,type:"readonly_selector",...n&&{family:n}};p.readonlySelectors.set(o.key,$);let J=F();i.logger.info("\u2728",$.type,$.key,"=",J);let A={key:o.key,type:"readonly_selector"};if(n)A.family=n;return A};var KT=(i,o,n)=>{let p=I(i),c=new $i,x=new Set,T=gm(o.key,x,p),{find:m,get:f,json:F}=T,$={find:m,get:f,json:F},J=(K=o.get,H=I(i))=>{let z=K($);return Wn(H,o.key,z,c),x.clear(),z},X={...o,subject:c,install:(K)=>KT(K,o,n),get:J,set:(K)=>{let H=I(i),z=J(o.get,H),b=Pm(K)(z);if(i.logger.info("\uD83D\uDCDD","selector",o.key,"set (",z,"->",b,")"),Wn(H,o.key,b,c),dc(H,o.key),Ho(H))c.next({newValue:b,oldValue:z});o.set(T,b)},type:"selector",...n&&{family:n}};p.selectors.set(o.key,X);let Y=J();i.logger.info("\u2728",X.type,X.key,"=",Y);let R={key:o.key,type:"selector"};if(n)R.family=n;return R};function rf(i,o){if("set"in o){let c=KT(i,o,void 0);return i.on.selectorCreation.next(c),c}let p=RT(i,o,void 0);return i.on.selectorCreation.next(p),p}function tw(i,o){let n=I(i),{key:p}=o,c=Ri(n,o);if(!c.family)i.logger.error("\u274C","selector",p,"Standalone selectors cannot be disposed.");else{if(n.molecules.get(c.family.subKey))n.moleculeData.delete(c.family.subKey,c.family.key);let T;switch(o.type){case"selector":n.selectors.delete(p),T={key:c.family.key,type:"selector_family"},Ri(i,T).subject.next({type:"state_disposal",subType:"selector",token:o});break;case"readonly_selector":n.readonlySelectors.delete(p),T={key:c.family.key,type:"readonly_selector_family"},Ri(i,T).subject.next({type:"state_disposal",subType:"selector",token:o});break}if(n.valueMap.delete(p),n.selectorAtoms.delete(p),n.selectorGraph.delete(p),i.logger.info("\uD83D\uDD25",o.type,p,"deleted"),zi(n)&&n.transactionMeta.phase==="building")n.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:o});else i.on.selectorDisposal.next(o)}}function YT(i,o,n){let p={key:o.key,type:"selector_family"},c=i.families.get(o.key);if(c)i.logger.error("\u2757","selector_family",o.key,`Overwriting an existing ${hn(c)} "${c.key}" in store "${i.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let x=new $i,m=Object.assign((f)=>{let F=Ji(f),$={key:o.key,subKey:F},J=`${o.key}(${F})`,A=I(i),X=KT(A,{key:J,get:o.get(f),set:o.set(f)},$);return x.next({type:"state_creation",token:X}),X},p,{internalRoles:n,subject:x,install:(f)=>YT(f,o),default:(f)=>{return o.get(f)({get:(...$)=>Mi(i,...$),find:(...$)=>t(i,...$),json:($)=>Jo(i,$)})}});return i.families.set(o.key,m),p}function i8(i,o,n){return YT(i,{key:`${o.key}:JSON`,get:(c)=>({get:x})=>{let T=x(o,c);return n.toJson(T)},set:(c)=>({set:x},T)=>{x(o,c,n.fromJson(T))}},["mutable","json"])}var Wo=(i)=>JSON.parse(i),Ji=(i)=>JSON.stringify(i),Ek=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var o8=(i,o)=>{let n=I(i);if(n.operation.open)return n.operation.prev.get(o.key);return n.valueMap.get(o.key)};var FF=(i,o)=>{let n=I(i);return rw(o,i).map((c)=>{let x=n.atoms.get(c);if(x===void 0)throw new Error(`Atom "${c}", a dependency of selector "${o.key}", not found in store "${i.config.name}".`);return x.subject.subscribe(`${o.type}:${o.key}`,(T)=>{i.logger.info("\uD83D\uDCE2",o.type,o.key,"root",c,"went",T.oldValue,"->",T.newValue);let m=o8(n,o),f=Sp(n,o);i.logger.info("\u2728",o.type,o.key,"went",m,"->",f),o.subject.next({newValue:f,oldValue:m})})})};function Oo(i,o,n,p){function c(J){if(i.operation.open){let A=i.on.operationClose.subscribe(`state subscription ${n}`,()=>{A(),p(J)})}else p(J)}let x=Ri(i,o);i.logger.info("\uD83D\uDC40",x.type,x.key,`Adding subscription "${n}"`);let T=x.type==="selector"||x.type==="readonly_selector",m=null,f=c;if(T)m=FF(i,x),f=(J)=>{if(m)m.length=0,m.push(...FF(i,x));c(J)};let F=x.subject.subscribe(n,f);return()=>{if(i.logger.info("\uD83D\uDE48",x.type,x.key,`Removing subscription "${n}"`),F(),m)for(let J of m)J()}}var mF=(i,o,n,p)=>{let c=Ri(i,o);i.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${n}"`);let x=c.subject.subscribe(n,p);return()=>{i.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${n}" from timeline`),x()}};var fF=(i,o,n,p)=>{let c=Ri(i,o);i.logger.info("\uD83D\uDC40","transaction",o.key,`Adding subscription "${n}"`);let x=c.subject.subscribe(n,p);return()=>{i.logger.info("\uD83D\uDE48","transaction",o.key,`Removing subscription "${n}"`),x()}};class cc{Update;initializeState(i,o){let n=`*${i.key}`;o.atoms.delete(n),o.valueMap.delete(n);let p=i.family?{key:`*${i.family.key}`,subKey:i.family.subKey}:void 0,c=rp(o,{key:n,default:null},p);if(o.parent?.valueMap.has(n)){let x=o.parent.valueMap.get(n);o.valueMap.set(n,x)}return c}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(i,o,n){let p=`tracker:${n.config.name}:${zi(n)?n.transactionMeta.update.key:"main"}:${i.key}`,c=Mi(n,i);this.unsubscribeFromInnerValue=c.subscribe(p,(x)=>{_i(n,o,x)}),this.unsubscribeFromState=Oo(n,i,p,(x)=>{if(x.newValue!==x.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=x.newValue.subscribe(p,(T)=>{_i(n,o,T)})})}updateCore(i,o,n){let p=`tracker:${n.config.name}:${zi(n)?n.transactionMeta.update.key:"main"}:${i.key}`;Oo(n,o,p,({newValue:c,oldValue:x})=>{let T=n.timelineTopics.getRelatedKey(o.key);if(T){if(n.timelines.get(T)?.timeTraveling){let F=mF(n,{key:T,type:"timeline"},p,($)=>{F(),_i(n,i,(J)=>{if($==="redo"&&c)J.do(c);else if($==="undo"&&x)J.undo(x);return J})});return}}let m=n.on.operationClose.subscribe(p,()=>{m();let f=Mi(n,i),F=c===null?-1:f.getUpdateNumber(c),$=F-f.cacheUpdateNumber;if(c&&$===1)_i(n,i,(J)=>(J.do(c),J));else n.logger.info("\u274C","mutable_atom",i.key,`could not be updated. Expected update number ${f.cacheUpdateNumber+1}, but got ${F}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(i,o){this.mutableState=i;let n=I(o);this.latestUpdateState=this.initializeState(i,n),this.observeCore(i,this.latestUpdateState,n),this.updateCore(i,this.latestUpdateState,n),n.trackers.set(i.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),n.trackers.delete(i.key)}}}function HT(i,o,n){i.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${i.config.name}"`);let p=I(i),c=p.atoms.get(o.key);if(c&&c.type==="mutable_atom")return i.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),gn(c);let x=new $i,T={...o,type:"mutable_atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${F.config.name}"`),HT(F,o,n)},subject:x};if(n)T.family=n;let m=o.default();p.atoms.set(T.key,T),sm(i,o.key),Wn(p,o.key,m,x);let f=gn(T);if(o.effects){let F=0,$=[];for(let J of o.effects){let A=J({setSelf:(X)=>{_i(i,f,X)},onSet:(X)=>Oo(i,f,`effect[${F}]`,X)});if(A)$.push(A);++F}T.cleanup=()=>{for(let J of $)J()}}if(new cc(f,i),!n)Ww(f,o,i);return f}class $F{trackers=new Map;Update;latestUpdateAtoms;mutableAtoms;constructor(i,o){let n=dp(o,{key:`*${i.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=Ri(o,n),this.mutableAtoms=i,this.mutableAtoms.subject.subscribe(`store=${o.config.name}::tracker-atom-family`,(p)=>{let{type:c,token:x}=p;if(x.family){let T=Wo(x.family.subKey);switch(c){case"state_creation":this.trackers.set(T,new cc(x,o));break;case"state_disposal":{let m=this.trackers.get(T);if(m)m[Symbol.dispose](),this.trackers.delete(T)}break}}})}}function WT(i,o,n){let p={key:o.key,type:"mutable_atom_family"},c=i.families.get(o.key);if(c)i.logger.error("\u2757","mutable_atom_family",o.key,`Overwriting an existing ${hn(c)} "${c.key}" in store "${i.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let x=new $i,m=Object.assign((f)=>{let F=Ji(f),$={key:o.key,subKey:F},J=`${o.key}(${F})`,A=I(i),X={key:J,default:()=>o.default(f),toJson:o.toJson,fromJson:o.fromJson,mutable:!0};if(o.effects)X.effects=o.effects(f);let Y=HT(A,X,$);return x.next({type:"state_creation",token:Y}),Y},p,{subject:x,install:(f)=>WT(f,o),toJson:o.toJson,fromJson:o.fromJson,internalRoles:n});return i.families.set(o.key,m),i8(i,m,o),new $F(m,i),p}var JF=(i,o)=>{let n=I(o),p=`${i.key}:JSON`;return n.families.get(p)};var Jo=(i,o)=>{if(o.family){let p=I(i),x={key:`${o.family.key}:JSON`,type:"selector_family"},T=Ri(p,x),m=JSON.parse(o.family.subKey);return t(i,T,m)}return{type:"selector",key:`${o.key}:JSON`}};var $p=(i)=>{let n={type:"atom",key:`*${i.key}`};if(i.family)n.family={key:`*${i.family.key}`,subKey:i.family.subKey};return n};function Vw(i){return typeof i==="object"&&i!==null&&"do"in i&&"undo"in i&&"subscribe"in i}function GT(i,o,n){let p=n.valueMap.get(o.key),c=i.valueMap.get(o.key);if(p!==c)return c;if(p===void 0)return o.default();n.logger.info("\uD83D\uDCC3","atom",o.key,"copying");let x=o.toJson(p),T=o.fromJson(x);return i.valueMap.set(o.key,T),new cc(o,n),T}function Wn(i,o,n,p){let c=i.valueMap.get(o);if(c instanceof XT)c.use(n);if(n instanceof Promise){let x=new XT(n);return i.valueMap.set(o,x),x.then((T)=>{Wn(i,o,T,p),p.next({newValue:T,oldValue:x})}).catch((T)=>{i.logger.error("\uD83D\uDCA5","state",o,"rejected:",T)}),x}return i.valueMap.set(o,n),n}var Hw=(i,o)=>{let n=o.valueMap.get(i.key);if(i.type==="mutable_atom"&&zi(o)){let{parent:p}=o;n=GT(o,i,p)}return n},uw=(i,o)=>{let n=o.valueMap.get(i);if(n instanceof XT){let p=n,c=o.selectors.get(i)??o.readonlySelectors.get(i);if(c)p.use(c.get());return}if(o.operation.open)o.operation.prev.set(i,n);o.valueMap.delete(i),o.logger.info("\uD83D\uDDD1","state",i,"evicted")};var Sw=(i,o)=>{return I(i).atomsThatAreDefault.has(o)},sm=(i,o)=>{let n=I(i);n.atomsThatAreDefault=new Set(n.atomsThatAreDefault).add(o)},Ew=(i,o)=>{let n=I(i);n.atomsThatAreDefault=new Set(I(i).atomsThatAreDefault),n.atomsThatAreDefault.delete(o)};function rp(i,o,n){i.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${i.config.name}"`);let p=I(i),c=p.atoms.get(o.key);if(c&&c.type==="atom")return i.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),gn(c);let x=new $i,T={...o,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${F.config.name}"`),rp(F,o,n)},subject:x};if(n)T.family=n;let m=o.default;if(o.default instanceof Function)m=o.default();p.atoms.set(T.key,T),sm(i,o.key),Wn(p,o.key,m,x);let f=gn(T);if(o.effects){let F=0,$=[];for(let J of o.effects){let A=J({setSelf:(X)=>{_i(i,f,X)},onSet:(X)=>Oo(i,f,`effect[${F}]`,X)});if(A)$.push(A);++F}T.cleanup=()=>{for(let J of $)J()}}return f}function n8(i,o){if("mutable"in o){let c=HT(i,o,void 0);return i.on.atomCreation.next(c),c}let p=rp(i,o,void 0);return i.on.atomCreation.next(p),p}function xF(i,o){let n=I(i),{key:p,family:c}=o,x=Ri(n,o);if(!c)i.logger.error("\u274C","atom",p,"Standalone atoms cannot be disposed.");else{x.cleanup?.();let T=i.valueMap.get(x.key),m=Ri(i,{key:c.key,type:"atom_family"}),f={type:"state_disposal",subType:"atom",token:o,value:T};m.subject.next(f);let F=zi(n);if(n.atoms.delete(p),n.valueMap.delete(p),n.selectorAtoms.delete(p),n.atomsThatAreDefault.delete(p),i.timelineTopics.delete(p),o.type==="mutable_atom"){let $=$p(o);xF(i,$),i.trackers.delete(p)}if(i.logger.info("\uD83D\uDD25","atom",p,"deleted"),F&&n.transactionMeta.phase==="building"){let $=n.transactionMeta.update.updates.at(-1);if(!($?.type==="molecule_disposal"&&$.values.some(([X])=>X===x.family?.key)))n.transactionMeta.update.updates.push(f)}else i.on.atomDisposal.next(o)}}class vo extends Set{mode="record";subject=new $i;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(i,o=0){super(i);if(i instanceof vo)this.parent=i,this.cacheUpdateNumber=i.cacheUpdateNumber;if(o)this.cacheLimit=o,this.cache=new Array(o),this.subscribe("auto cache",(n)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=n})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(i){let o=new vo(i.members,i.cacheLimit);return o.cache=i.cache,o.cacheIdx=i.cacheIdx,o.cacheUpdateNumber=i.cacheUpdateNumber,o}add(i){let o=super.add(i);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${Ji(i)}`);return o}clear(){let i=this.mode==="record"?[...this]:null;if(super.clear(),i)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(i)}`)}delete(i){let o=super.delete(i);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${Ji(i)}`);return o}parent;child=null;transactionUpdates=null;transaction(i){this.mode="transaction",this.transactionUpdates=[],this.child=new vo(this);let o=this.child._subscribe("transaction",(n)=>{this.transactionUpdates?.push(n)});try{if(i(this.child)){for(let p of this.transactionUpdates)this.doStep(p);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(n){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",n),n}finally{o(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(i,o){return this.subject.subscribe(i,o)}subscribe(i,o){return this.subject.subscribe(i,(n)=>{o(`${this.cacheUpdateNumber}=${n}`)})}emit(i){this.subject.next(i)}doStep(i){let o=i.indexOf(":"),n=i.substring(0,o),p=i.substring(o+1);switch(n){case"add":this.add(JSON.parse(p));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(p));break;case"tx":for(let c of p.split(";"))this.doStep(c)}}getUpdateNumber(i){let o=i.indexOf("=");return Number(i.substring(0,o))}do(i){let o=i.indexOf("="),n=Number(i.substring(0,o)),p=n-this.cacheUpdateNumber;if(p>0){if(p===1){this.mode="playback";let x=i.substring(o+1);return this.doStep(x),this.mode="record",this.cacheUpdateNumber=n,null}return this.cacheUpdateNumber+1}if(Math.abs(p)<this.cacheLimit){let x=this.cacheIdx+p;if(this.cache[x]===i)return null;this.mode="playback";let m=!1;while(!m){this.cacheIdx%=this.cacheLimit;let F=this.cache[this.cacheIdx];if(this.cacheIdx--,!F)return"OUT_OF_RANGE";this.undo(F),m=this.cacheIdx===x-1}let f=i.substring(o+1);return this.doStep(f),this.mode="record",this.cacheUpdateNumber=n,null}return"OUT_OF_RANGE"}undoStep(i){let o=i.indexOf(":"),n=i.substring(0,o),p=i.substring(o+1);switch(n){case"add":this.delete(JSON.parse(p));break;case"del":this.add(JSON.parse(p));break;case"clear":{let c=JSON.parse(p);for(let x of c)this.add(x);break}case"tx":{let c=p.split(";");for(let x=c.length-1;x>=0;x--)this.undoStep(c[x])}}}undo(i){let o=i.indexOf("=");if(Number(i.substring(0,o))===this.cacheUpdateNumber){this.mode="playback";let p=i.substring(o+1);return this.undoStep(p),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}class UT{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(i,o){let n=this.toolkit;this.toolkit=i,o(this),this.toolkit=n}store;realm;[Symbol.dispose](){}constructor(i,o,n=d.STORE){this.store=n,this.realm=new AF(n),this.options=i,this.defaultContent=o,this.store.miscResources.set(`join:${i.key}`,this),this.realm.allocate("root",i.key),this.toolkit={get:(...M)=>Mi(n,...M),set:(...M)=>{_i(n,...M)},find:(...M)=>t(n,...M),json:(M)=>Jo(n,M)};let p=i.between[0],c=i.between[1],x=WT(n,{key:`${i.key}/relatedKeys`,default:()=>new vo,mutable:!0,fromJson:(M)=>vo.fromJSON(M),toJson:(M)=>M.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:x};let T=({get:M},u)=>M(x,u),m=({set:M},u,E)=>{if(!this.store.molecules.has(Ji(u)))this.realm.allocate(i.key,u);M(x,u,(S)=>S.add(E)),M(x,E,(S)=>S.add(u))},f=({set:M},u,E)=>{M(x,u,(S)=>{return S.delete(E),S}),M(x,E,(S)=>{return S.delete(u),S})},F=(M,u,E)=>{let{find:S,get:y,set:l}=M,Q=S(x,u),Ti=y(Q);for(let q of Ti){if(E.includes(q))continue;l(x,q,(Ei)=>{return Ei.delete(u),Ei})}l(Q,(q)=>{return q.transaction((mi)=>{mi.clear();for(let Ei of E){let To=T(M,Ei),lo=To.has(u);if(this.relations.cardinality==="1:n"){let ip=[];for(let O of To){if(O===u)continue;let k=T(M,O);if(k.delete(Ei),k.size===0)ip.push(O)}if(!lo&&To.size>0)To.clear();for(let O of ip){let k=[Ei,O].sort(),Yi=`"${k[0]}:${k[1]}"`;this.molecules.delete(Yi)}}if(!lo)To.add(u);mi.add(Ei)}return!0}),q})},$=(M,u,E)=>{let{set:S}=M;S(x,u,(y)=>{return y.transaction((l)=>{for(let Q of E)l.add(Q);return!0}),y});for(let y of E)S(x,y,(l)=>{return l.add(u),l});return!0},J=(M,u,E)=>{let S=T(M,u);return E?S.has(E):S.size>0},A={getRelatedKeys:(M)=>T(this.toolkit,M),addRelation:(M,u)=>{this.store.moleculeJoins.set(M,i.key),this.store.moleculeJoins.set(u,i.key),m(this.toolkit,M,u)},deleteRelation:(M,u)=>{f(this.toolkit,M,u)},replaceRelationsSafely:(M,u)=>{F(this.toolkit,M,u)},replaceRelationsUnsafely:(M,u)=>{$(this.toolkit,M,u)},has:(M,u)=>J(this.toolkit,M,u)},X,Y;if(o){Y=dp(n,{key:`${i.key}/content`,default:o},["join","content"]);let M=({get:S},y)=>S(Y,y),u=({set:S},y,l)=>{S(Y,y,l)};X=Object.assign(A,{getContent:(S)=>{return M(this.toolkit,S)},setContent:(S,y)=>{u(this.toolkit,S,y)},deleteContent:(S)=>{this.realm.deallocate(S)}})}else X=A;let R=new Ao(i,{externalStore:X,isAType:i.isAType,isBType:i.isBType,makeContentKey:(...M)=>{let[u,E]=M,S=M.sort(),y=`${S[0]}:${S[1]}`,l=n.molecules.get(Ji(u)),Q=n.molecules.get(Ji(E));if(!l)this.realm.allocate(i.key,u);if(!Q)this.realm.allocate(i.key,E);return this.realm.allocate(u,y,"all"),this.realm.claim(E,y),this.store.moleculeJoins.set(y,i.key),y}}),K=()=>Vp(n,{key:`${i.key}/singleRelatedKey`,get:(M)=>({get:u})=>{let E=u(x,M);for(let S of E)return S;return null}},["join","keys"]),H=()=>{return Vp(n,{key:`${i.key}/multipleRelatedKeys`,get:(M)=>({get:u})=>{let E=JF(x,n);return u(E,M).members}},["join","keys"])},z=()=>Vp(n,{key:`${i.key}/singleRelatedEntry`,get:(M)=>({get:u})=>{let E=u(x,M);for(let S of E){let y=R.isAType?.(M)?M:void 0,l=y===void 0?M:void 0;y??=S,l??=S;let Q=R.makeContentKey(y,l),Ti=u(Y,Q);return[S,Ti]}return null}},["join","entries"]),b=()=>Vp(n,{key:`${i.key}/multipleRelatedEntries`,get:(M)=>({get:u})=>{let E=JF(x,n);return u(E,M).members.map((y)=>{let l=R.isAType?.(M)?M:void 0,Q=l===void 0?M:void 0;l??=y,Q??=y;let Ti=R.makeContentKey(l,Q),q=u(Y,Ti);return[y,q]})}},["join","entries"]);switch(i.cardinality){case"1:1":{let M=K(),u=`${p}KeyOf${ui(c)}`,E=`${c}KeyOf${ui(p)}`,S={[u]:M,[E]:M},y;if(o){let l=z(),Q=`${p}EntryOf${ui(c)}`,Ti=`${c}EntryOf${ui(p)}`,q={[Q]:l,[Ti]:l};y=Object.assign(S,q)}else y=S;this.relations=R,this.states=y;break}case"1:n":{let M=K(),u=H(),E=`${p}KeyOf${ui(c)}`,S=`${c}KeysOf${ui(p)}`,y={[E]:M,[S]:u},l;if(o){let Q=z(),Ti=b(),q=`${p}EntryOf${ui(c)}`,mi=`${c}EntriesOf${ui(p)}`,Ei={[q]:Q,[mi]:Ti};l=Object.assign(y,Ei)}else l=y;this.relations=R,this.states=l;break}case"n:n":{let M=H(),u=`${p}KeysOf${ui(c)}`,E=`${c}KeysOf${ui(p)}`,S={[u]:M,[E]:M},y;if(o){let l=b(),Q=`${p}EntriesOf${ui(c)}`,Ti=`${c}EntriesOf${ui(p)}`,q={[Q]:l,[Ti]:l};y=Object.assign(S,q)}else y=S;this.relations=R,this.states=y}}}}function ec(i,o){let n=o.joins.get(i.key);if(n===void 0){let c=d.STORE.joins.get(i.key);if(c===void 0)throw new Error(`Join "${i.key}" not found in store "${o.config.name}"`);n=new UT(c.options,c.defaultContent,o),o.joins.set(i.key,n)}return n}function Ep(i,o,n){let p=ec(i,n),c=I(n);if(zi(c)){let{toolkit:x}=c.transactionMeta;p.transact(x,({relations:T})=>{o(T)})}else o(p.relations)}function ix(i,o,n){let p=ec(i,n),c;switch(i.cardinality){case"1:1":{let x=`${i.a}KeyOf${ui(i.b)}`,T=`${i.b}KeyOf${ui(i.a)}`;c={get[x](){let f=p.states[x];return t(n,f,o)},get[T](){let f=p.states[T];return t(n,f,o)}};let m=`${i.a}EntryOf${ui(i.b)}`;if(m in p.states){let f=`${i.b}EntryOf${ui(i.a)}`;Object.assign(c,{get[m](){let F=p.states[m];return t(n,F,o)},get[f](){let F=p.states[f];return t(n,F,o)}})}break}case"1:n":{let x=`${i.a}KeyOf${ui(i.b)}`,T=`${i.b}KeysOf${ui(i.a)}`;c={get[x](){let f=p.states[x];return t(n,f,o)},get[T](){let f=p.states[T];return t(n,f,o)}};let m=`${i.a}EntryOf${ui(i.b)}`;if(m in p.states){let f=`${i.b}EntriesOf${ui(i.a)}`;Object.assign(c,{get[m](){let F=p.states[m];return t(n,F,o)},get[f](){let F=p.states[f];return t(n,F,o)}})}break}case"n:n":{let x=`${i.a}KeysOf${ui(i.b)}`,T=`${i.b}KeysOf${ui(i.a)}`;c={get[x](){let f=p.states[x];return t(n,f,o)},get[T](){let f=p.states[T];return t(n,f,o)}};let m=`${i.a}EntriesOf${ui(i.b)}`;if(m in p.states){let f=`${i.b}EntriesOf${ui(i.a)}`;Object.assign(c,{get[m](){let F=p.states[m];return t(n,F,o)},get[f](){let F=p.states[f];return t(n,F,o)}})}}}return c}function p8(i,o){return ec(i,o).core.relatedKeysAtoms}function hw(i){return i.startsWith("\uD83D\uDD0D ")}function Op(i){return n8(d.STORE,i)}function xc(i){return Rw(d.STORE,i)}function tm(i,o,n=d.STORE){return n.joins.set(i.key,new UT(i,o,n)),{key:i.key,type:"join",a:i.between[0],b:i.between[1],cardinality:i.cardinality}}function c8(i){return p8(i,d.STORE)}var vF=(i)=>(o,n,p,c,...x)=>{console[i](`${o} ${n} "${p}" ${c}`,...x)},SU={error:vF("error"),info:vF("info"),warn:vF("warn")};class pc{logLevel;filter;logger;constructor(i,o,n=SU){this.logLevel=i,this.filter=o,this.logger=n}error=(...i)=>{if((this.filter?.(...i)??!0)&&this.logLevel!==null)this.logger.error(...i)};info=(...i)=>{if((this.filter?.(...i)??!0)&&this.logLevel==="info")this.logger.info(...i)};warn=(...i)=>{if((this.filter?.(...i)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...i)}}var rs=Symbol("claim");class x8{store;constructor(i=d.STORE){this.store=i,Lw("root",i)}allocate(i,o,n){return ic(this.store,i,o,n)}fuse(i,o,n){return Cw(this.store,i,o,n)}deallocate(i){oc(this.store,i)}claim(i,o,n){return rc(this.store,i,o,n)}}class AF{store;realm;constructor(i=d.STORE){this.store=i,this.realm=new x8(i)}allocate(i,o,n){ic(this.store,i,o,n)}deallocate(i){oc(this.store,i)}claim(i,o,n){rc(this.store,i,o,n)}}function dm(i){return Yw(d.STORE,i)}function Tc(i){return cF(d.STORE,i)}class T8 extends Map{set(i,o){if(this.has(i))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:i,value:o}),this;return super.set(i,o)}clear(){throw new Error("Cannot clear an InvariantMap")}}class rm{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(i){this.key=i}static existing=new T8;static create(i,o){let n=new rm(i),{type:p,globals:c,actions:x,perspectives:T}=o(n),m={type:p,key:i,globals:c,actions:x,perspectives:T};return rm.existing.set(i,m),m}add(...i){switch(i[0].type){case"atom":case"mutable_atom":this.globals.push(...i);break;case"transaction":this.actions.push(...i);break;case"atom_family":case"mutable_atom_family":{let[n,p]=i;this.perspectives.push({type:"realtime_perspective",resourceAtoms:n,viewAtoms:p})}break}return this}}function m8(i){let{key:o,config:n}=i,p=rm.create(o,n),{actions:c}=p;for(let x of c)aw(d.STORE,o,x.key);return bw(d.STORE,o,-1),p}var ft=Op({key:"usersInRoomIndex",mutable:!0,default:()=>new vo,toJson:(i)=>i.toJSON(),fromJson:(i)=>vo.fromJSON(i)}),wF=Op({key:"roomIndex",default:()=>new vo,mutable:!0,toJson:(i)=>i.toJSON(),fromJson:(i)=>vo.fromJSON(i)}),EU={enteredAtEpoch:0},ZT=tm({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(i)=>typeof i==="string",isBType:(i)=>typeof i==="string"},EU),Ft=dm({key:"usersInMyRoomView",get:(i)=>({find:o})=>{let n=c8(ZT);return[o(n,i)]}});import{spawn as OU}from"child_process";class ox{listeners;globalListeners;handleEvent(i,...o){for(let p of this.globalListeners)p(i,...o);let n=this.listeners.get(i);if(n)for(let p of n)p(...o)}id="no_id_retrieved";emit;constructor(i){this.emit=i,this.listeners=new Map,this.globalListeners=new Set}on(i,o){let n=this.listeners.get(i);if(n)n.add(o);else this.listeners.set(i,new Set([o]));return this}onAny(i){return this.globalListeners.add(i),this}off(i,o){let n=this.listeners.get(i);if(n)if(o)n.delete(o);else this.listeners.delete(i);return this}offAny(i){return this.globalListeners.delete(i),this}}class MT extends ox{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(i){if(Array.isArray(i)){let[o,...n]=i;switch(o){case"i":this.logger.info(...n);break;case"w":this.logger.warn(...n);break;case"e":this.logger.error(...n);break;default:return}}}constructor(i,o,n){super((p,...c)=>{let x=JSON.stringify([p,...c])+"\x03",T=(m)=>{if(m.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",T)};return this.process.stdin.once("error",T),this.process.stdin.write(x),this});if(this.process=i,this.key=o,this.logger=n??{info:(...p)=>{console.info(this.id,this.key,...p)},warn:(...p)=>{console.warn(this.id,this.key,...p)},error:(...p)=>{console.error(this.id,this.key,...p)}},this.process.stdout.on("data",(p)=>{let c=p.toString();if(c==="ALIVE")return;this.unprocessedEvents.push(...c.split("\x03"));let x=this.unprocessedEvents.shift();this.incompleteData+=x??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let T=Wo(this.incompleteData);this.handleEvent(...T);while(this.unprocessedEvents.length>0){let m=this.unprocessedEvents.shift();if(m){if(this.unprocessedEvents.length===0)this.incompleteData=m;T=Wo(m),this.handleEvent(...T)}}this.incompleteData=""}catch(T){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(T)}}),this.process.stderr.on("data",(p)=>{let c=p.toString();this.unprocessedLogs.push(...c.split("\x03"));let x=this.unprocessedLogs.shift();this.incompleteLog+=x??"";try{let T=Wo(this.incompleteLog);this.handleLog(T);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)T=Wo(this.incompleteLog),this.handleLog(T)}catch(T){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(T),console.error("\u274C\u274C\u274C\uFE0F")}}),i.pid)this.id=i.pid.toString()}}class f8 extends ox{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(i){super((...o)=>{return this.out.next(o),this});this.id=i,this.in=new $i,this.out=new $i,this.in.subscribe("socket",(o)=>{this.handleEvent(...o)})}dispose(){for(let i of this.disposalFunctions)i()}}class XF extends ox{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...i){this.process.stderr.write(Ji(i.map((o)=>o instanceof vo?`{ ${o.toJSON().members.join(" | ")} }`:o))+"\x03")}logger={info:(...i)=>{this.log("i",...i)},warn:(...i)=>{this.log("w",...i)},error:(...i)=>{this.log("e",...i)}};constructor(){super((i,...o)=>{let n=JSON.stringify([i,...o]);return this.process.stdout.write(n+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(i)=>{let o=i.toString();this.unprocessedEvents.push(...o.split("\x03"));let n=this.unprocessedEvents.shift();this.incompleteData+=n??"";try{let p=Wo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",p),this.handleEvent(...p);while(this.unprocessedEvents.length>0){let c=this.unprocessedEvents.shift();if(c){if(this.unprocessedEvents.length===0)this.incompleteData=c;let x=Wo(c);this.handleEvent(...x)}}this.incompleteData=""}catch(p){if(p instanceof Error)this.logger.error("\u2757",p.message,p.cause,p.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(i)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${i}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(i)=>{this.logger.info("\uD83D\uDC64","user",i,"joined");let o=new f8(`user:${i}`);this.relays.set(i,o),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let n of this.relayServices){let p=n(o);if(p)o.disposalFunctions.push(p)}this.on(`user:${i}`,(...n)=>{o.in.next(n)}),o.out.subscribe("socket",(n)=>{this.emit(...n)})}),this.on("user-leaves",(i)=>{let o=this.relays.get(i);if(this.off(`relay:${i}`),o)o.dispose(),this.relays.delete(i)}),process.stdout.write("ALIVE")}relay(i){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(i)}}var WF=xc({key:"roomArguments",default:["echo",["Hello World!"]]}),F8=dm({key:"room",get:(i)=>async({get:o,find:n})=>{let p=n(WF,i),c=o(p),[x,T]=c,m=await new Promise((f)=>{let F=OU(x,T,{env:process.env}),$=(J)=>{if(J.toString()==="ALIVE")F.stdout.off("data",$),f(F)};F.stdout.on("data",$)});return new MT(m,i)}});var Dt=Tc({key:"createRoom",do:({get:i,set:o,find:n},p,c,x)=>{let T=x?[c,x]:[c],m=n(WF,p);o(m,T),o(wF,($)=>$.add(p));let f=n(F8,p);return i(f)}}),It=Tc({key:"joinRoom",do:(i,o,n,p)=>{let c={enteredAtEpoch:p};return Ep(ZT,(x)=>{x.set({room:o,user:n},c)},i.env().store),c}}),Bt=Tc({key:"leaveRoom",do:(i,o,n)=>{Ep(ZT,(p)=>{p.delete({room:o,user:n})},i.env().store)}}),Nt=Tc({key:"destroyRoom",do:(i,o)=>{Ep(ZT,(n)=>{n.delete({room:o})},i.env().store),i.set(wF,(n)=>(n.delete(o),n))}});function RF(i,o){return o.map((n)=>{switch(n.type){case"transaction_update":{let p=RF(i,n.updates);return{...n,updates:p}}case"atom_update":case"selector_update":case"molecule_creation":case"molecule_disposal":case"molecule_transfer":case"state_creation":case"state_disposal":return n}}).filter((n)=>{switch(n.type){case"atom_update":case"selector_update":return i.includes(n.key);case"state_creation":case"state_disposal":return i.includes(n.token.key);case"molecule_creation":case"transaction_update":case"molecule_disposal":case"molecule_transfer":return!0}})}var Pt=xc({key:"redactor",default:{occlude:(i)=>i}}),nx=xc({key:"unacknowledgedUpdates",default:()=>[]});var em=xc({key:"sockets",default:null}),YF=Op({key:"socketsIndex",mutable:!0,default:()=>new vo,toJson:(i)=>i.toJSON(),fromJson:(i)=>vo.fromJSON(i)}),GF=Op({key:"usersIndex",mutable:!0,default:()=>new vo,toJson:(i)=>i.toJSON(),fromJson:(i)=>vo.fromJSON(i)}),mc=tm({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(i)=>i.startsWith("user::"),isBType:(i)=>i.startsWith("socket::")});function $8(i,o,n,p){let c=o.key;return function x(){let T=[];for(let f of o.globals){let F=f.type==="mutable_atom"?Jo(i,f):f,$=Mi(i,F);T.push(F,$)}for(let f of o.perspectives){let{viewAtoms:F,resourceAtoms:$}=f,J=t(i,F,n),A=Mi(i,J);i.logger.info("\uD83D\uDC41","atom",$.key,`${n} can see`,{viewAtoms:F,resourceAtoms:$,userView:A});for(let X of A){let Y=X.type==="mutable_atom"?Jo(i,X):X,R=Mi(i,Y);T.push(Y,R)}}let m=Ho(i)?i.transactionMeta.epoch.get(c)??null:null;p?.emit(`continuity-init:${c}`,m,T)}}function J8(i,o,n){let p=o.key;return function c(x){i.logger.info("\uD83D\uDECE\uFE0F","continuity",p,"received",x);let{key:T,id:m}=x,f=`tx-run:${T}:${m}`,F=`${f}:start`,$=`${f}:end`;performance.mark(F);try{tc(i,{type:"transaction",key:T},m)(...x.params)}catch(A){if(A instanceof Error)i.logger.error("\u274C","continuity",p,`failed to run transaction ${T} from ${n} with update ${m}`,A.message)}performance.mark($);let J=performance.measure(f,F,$);i?.logger.info("\uD83D\uDE80","transaction",T,m,n,J.duration)}}function A8(i,o,n,p){let c=o.key;return function x(T){if(i.logger.info("\uD83D\uDC4D","continuity",c,`${n} acknowledged epoch ${T}`),p[0]?.epoch===T)_i(i,nx,n,(f)=>{return f.shift(),i.logger.info("\uD83D\uDC4D","continuity",c,`${n} unacknowledged update queue now has`,f.length,"items"),f})}}function v8(i,o,n,p){let c=o.key,x=[];for(let T of o.actions){let m=fF(i,T,`sync-continuity:${c}:${n}`,(f)=>{try{let F=o.globals.map((A)=>{if(A.type==="atom")return A.key;return $p(A).key}).concat(o.perspectives.flatMap((A)=>{let{viewAtoms:X}=A,Y=t(i,X,n);return Mi(i,Y).map((K)=>{return K.type==="mutable_atom"?"*"+K.key:K.key})})),$=RF(F,f.updates),J={...f,updates:$};_i(i,nx,n,(A)=>{if(J)A.push(J),A.sort((X,Y)=>X.epoch-Y.epoch),i.logger.info("\uD83D\uDC4D","continuity",c,`${n} unacknowledged update queue now has`,A.length,"items");return A}),p?.emit(`tx-new:${c}`,J)}catch(F){if(F instanceof Error)i.logger.error("\u274C","continuity",c,`${n} failed to send update from transaction ${T.key} to ${n}`,F.message)}});x.push(m)}return x}function w8(i,o,n,p){let c=o.key,x=[];for(let T of o.perspectives){let{viewAtoms:m}=T,f=t(i,m,n),F=Oo(i,f,`sync-continuity:${c}:${n}:perspective:${T.resourceAtoms.key}`,({oldValue:$,newValue:J})=>{let A=$.map((K)=>K.key),X=J.map((K)=>K.key),Y=$.filter((K)=>!X.includes(K.key)),R=J.filter((K)=>!A.includes(K.key)).flatMap((K)=>{let H=K.type==="mutable_atom"?Jo(i,K):K,z=Mi(i,H);return[H,z]});if(i.logger.info("\uD83D\uDC41","atom",T.resourceAtoms.key,`${n} has a new perspective`,{oldKeys:A,newKeys:X,revealed:R,concealed:Y}),R.length>0)p?.emit(`reveal:${c}`,R);if(Y.length>0)p?.emit(`conceal:${c}`,Y)});x.push(F)}return x}function X8({socket:i,store:o=d.STORE}){return function n(p){let c=i,x=p.key,T=ix(mc,`socket::${c.id}`,o).userKeyOfSocket,m=Mi(o,T);if(!m)return o.logger.error("\u274C","continuity",x,`Tried to create a synchronizer for a socket (${c.id}) that is not connected to a user.`),()=>{};let f=ix(mc,m,o).socketKeyOfUser,F=Oo(o,f,`sync-continuity:${x}:${m}`,({newValue:H})=>{if(o.logger.info("\uD83D\uDC4B","continuity",x,`seeing ${m} on new socket ${H}`),H===null){o.logger.warn("\u274C","continuity",x,`User (${m}) is not connected to a socket, waiting for them to reappear.`);return}let z=t(o,em,H);c=Mi(o,z);for(let M of $)c?.emit(`tx-new:${x}`,M)}),$=Mi(o,nx,m),J=[],A=w8(o,p,m,c),X=v8(o,p,m,c);J.push(...A,...X);let Y=$8(o,p,m,i);c.off(`get:${x}`,Y),c.on(`get:${x}`,Y);let R=J8(o,p,m);c.off(`tx-run:${x}`,R),c.on(`tx-run:${x}`,R);let K=A8(o,p,m,$);return c?.on(`ack:${x}`,K),()=>{for(let H of J)H();c?.off(`ack:${x}`,K),c?.off(`get:${x}`,Y),c?.off(`tx-run:${x}`,R)}}}var IY=C1(n$(),1);var w=Symbol.for("drizzle:entityKind"),ed=Symbol.for("drizzle:hasOwnEntityKind");function Z(i,o){if(!i||typeof i!=="object")return!1;if(i instanceof o)return!0;if(!Object.prototype.hasOwnProperty.call(o,w))throw new Error(`Class "${o.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let n=Object.getPrototypeOf(i).constructor;if(n)while(n){if(w in n&&n[w]===o[w])return!0;n=Object.getPrototypeOf(n)}return!1}class Li{constructor(i,o){this.table=i,this.config=o,this.name=o.name,this.keyAsName=o.keyAsName,this.notNull=o.notNull,this.default=o.default,this.defaultFn=o.defaultFn,this.onUpdateFn=o.onUpdateFn,this.hasDefault=o.hasDefault,this.primary=o.primaryKey,this.isUnique=o.isUnique,this.uniqueName=o.uniqueName,this.uniqueType=o.uniqueType,this.dataType=o.dataType,this.columnType=o.columnType,this.generated=o.generated,this.generatedIdentity=o.generatedIdentity}static[w]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(i){return i}mapToDriverValue(i){return i}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class p${static[w]="ColumnBuilder";config;constructor(i,o,n){this.config={name:i,keyAsName:i==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:o,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(i){return this.config.default=i,this.config.hasDefault=!0,this}$defaultFn(i){return this.config.defaultFn=i,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(i){return this.config.onUpdateFn=i,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(i){if(this.config.name!=="")return;this.config.name=i}}var Dn=Symbol.for("drizzle:Name");class c${static[w]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(i,o){if(this.reference=()=>{let{name:n,columns:p,foreignColumns:c}=i();return{name:n,columns:p,foreignTable:c[0].table,foreignColumns:c}},o)this._onUpdate=o.onUpdate,this._onDelete=o.onDelete}onUpdate(i){return this._onUpdate=i===void 0?"no action":i,this}onDelete(i){return this._onDelete=i===void 0?"no action":i,this}build(i){return new A3(i,this)}}class A3{constructor(i,o){this.table=i,this.reference=o.reference,this.onUpdate=o._onUpdate,this.onDelete=o._onDelete}static[w]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:i,columns:o,foreignColumns:n}=this.reference(),p=o.map((T)=>T.name),c=n.map((T)=>T.name),x=[this.table[Dn],...p,n[0].table[Dn],...c];return i??`${x.join("_")}_fk`}}function R0(i,...o){return i(...o)}function v3(i,o){return`${i[Dn]}_${o.join("_")}_unique`}function w3(i,o,n){for(let p=o;p<i.length;p++){let c=i[p];if(c==="\\"){p++;continue}if(c==='"')return[i.slice(o,p).replace(/\\/g,""),p+1];if(n)continue;if(c===","||c==="}")return[i.slice(o,p).replace(/\\/g,""),p]}return[i.slice(o).replace(/\\/g,""),i.length]}function X3(i,o=0){let n=[],p=o,c=!1;while(p<i.length){let x=i[p];if(x===","){if(c||p===o)n.push("");c=!0,p++;continue}if(c=!1,x==="\\"){p+=2;continue}if(x==='"'){let[f,F]=w3(i,p+1,!0);n.push(f),p=F;continue}if(x==="}")return[n,p+1];if(x==="{"){let[f,F]=X3(i,p+1);n.push(f),p=F;continue}let[T,m]=w3(i,p,!1);n.push(T),p=m}return[n,p]}function W3(i){let[o]=X3(i,1);return o}function x$(i){return`{${i.map((o)=>{if(Array.isArray(o))return x$(o);if(typeof o==="string")return`"${o.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${o}`}).join(",")}}`}class j extends p${foreignKeyConfigs=[];static[w]="PgColumnBuilder";array(i){return new Y3(this.config.name,this,i)}references(i,o={}){return this.foreignKeyConfigs.push({ref:i,actions:o}),this}unique(i,o){return this.config.isUnique=!0,this.config.uniqueName=i,this.config.uniqueType=o?.nulls,this}generatedAlwaysAs(i){return this.config.generated={as:i,type:"always",mode:"stored"},this}buildForeignKeys(i,o){return this.foreignKeyConfigs.map(({ref:n,actions:p})=>{return R0((c,x)=>{let T=new c$(()=>{let m=c();return{columns:[i],foreignColumns:[m]}});if(x.onUpdate)T.onUpdate(x.onUpdate);if(x.onDelete)T.onDelete(x.onDelete);return T.build(o)},n,p)})}buildExtraConfigColumn(i){return new R3(i,this.config)}}class _ extends Li{constructor(i,o){if(!o.uniqueName)o.uniqueName=v3(i,[o.name]);super(i,o);this.table=i}static[w]="PgColumn"}class R3 extends _{static[w]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(i){return this.indexConfig.opClass=i,this}}class DT{static[w]="IndexedColumn";constructor(i,o,n,p){this.name=i,this.keyAsName=o,this.type=n,this.indexConfig=p}name;keyAsName;type;indexConfig}class Y3 extends j{static[w]="PgArrayBuilder";constructor(i,o,n){super(i,"array","PgArray");this.config.baseBuilder=o,this.config.size=n}build(i){let o=this.config.baseBuilder.build(i);return new T$(i,this.config,o)}}class T$ extends _{constructor(i,o,n,p){super(i,o);this.baseColumn=n,this.range=p,this.size=o.size}size;static[w]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(i){if(typeof i==="string")i=W3(i);return i.map((o)=>this.baseColumn.mapFromDriverValue(o))}mapToDriverValue(i,o=!1){let n=i.map((p)=>p===null?null:Z(this.baseColumn,T$)?this.baseColumn.mapToDriverValue(p,!0):this.baseColumn.mapToDriverValue(p));if(o)return n;return x$(n)}}var m$=Symbol.for("drizzle:isPgEnum");function G3(i){return!!i&&typeof i==="function"&&m$ in i&&i[m$]===!0}class K3 extends j{static[w]="PgEnumColumnBuilder";constructor(i,o){super(i,"string","PgEnumColumn");this.config.enum=o}build(i){return new H3(i,this.config)}}class H3 extends _{static[w]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(i,o){super(i,o);this.enum=o.enum}getSQLType(){return this.enum.enumName}}function Y0(i,o){return tM(i,o,void 0)}function tM(i,o,n){let p=Object.assign((c)=>new K3(c??"",p),{enumName:i,enumValues:o,schema:n,[m$]:!0});return p}class wo{static[w]="Subquery";constructor(i,o,n,p=!1){this._={brand:"Subquery",sql:i,selectedFields:o,alias:n,isWith:p}}}class IT extends wo{static[w]="WithSubquery"}var U3="0.41.0";var f$,F$,Ci={startActiveSpan(i,o){if(!f$)return o();if(!F$)F$=f$.trace.getTracer("drizzle-orm",U3);return R0((n,p)=>p.startActiveSpan(i,(c)=>{try{return o(c)}catch(x){throw c.setStatus({code:n.SpanStatusCode.ERROR,message:x instanceof Error?x.message:"Unknown error"}),x}finally{c.end()}}),f$,F$)}};var Ni=Symbol.for("drizzle:ViewBaseConfig");var G0=Symbol.for("drizzle:Schema"),K0=Symbol.for("drizzle:Columns"),Z3=Symbol.for("drizzle:ExtraConfigColumns"),$$=Symbol.for("drizzle:OriginalName"),J$=Symbol.for("drizzle:BaseName"),BT=Symbol.for("drizzle:IsAlias"),M3=Symbol.for("drizzle:ExtraConfigBuilder"),dM=Symbol.for("drizzle:IsDrizzleTable");class B{static[w]="Table";static Symbol={Name:Dn,Schema:G0,OriginalName:$$,Columns:K0,ExtraConfigColumns:Z3,BaseName:J$,IsAlias:BT,ExtraConfigBuilder:M3};[Dn];[$$];[G0];[K0];[Z3];[J$];[BT]=!1;[dM]=!0;[M3]=void 0;constructor(i,o,n){this[Dn]=this[$$]=i,this[G0]=o,this[J$]=n}}function Ro(i){return i[Dn]}function vc(i){return`${i[G0]??"public"}.${i[Dn]}`}function A$(i){return i!==null&&i!==void 0&&typeof i.getSQL==="function"}function rM(i){let o={sql:"",params:[]};for(let n of i)if(o.sql+=n.sql,o.params.push(...n.params),n.typings?.length){if(!o.typings)o.typings=[];o.typings.push(...n.typings)}return o}class Xo{static[w]="StringChunk";value;constructor(i){this.value=Array.isArray(i)?i:[i]}getSQL(){return new N([this])}}class N{constructor(i){this.queryChunks=i}static[w]="SQL";decoder=u3;shouldInlineParams=!1;append(i){return this.queryChunks.push(...i.queryChunks),this}toQuery(i){return Ci.startActiveSpan("drizzle.buildSQL",(o)=>{let n=this.buildQueryFromSourceParams(this.queryChunks,i);return o?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(i,o){let n=Object.assign({},o,{inlineParams:o.inlineParams||this.shouldInlineParams,paramStartIndex:o.paramStartIndex||{value:0}}),{casing:p,escapeName:c,escapeParam:x,prepareTyping:T,inlineParams:m,paramStartIndex:f}=n;return rM(i.map((F)=>{if(Z(F,Xo))return{sql:F.value.join(""),params:[]};if(Z(F,H0))return{sql:c(F.value),params:[]};if(F===void 0)return{sql:"",params:[]};if(Array.isArray(F)){let $=[new Xo("(")];for(let[J,A]of F.entries())if($.push(A),J<F.length-1)$.push(new Xo(", "));return $.push(new Xo(")")),this.buildQueryFromSourceParams($,n)}if(Z(F,N))return this.buildQueryFromSourceParams(F.queryChunks,{...n,inlineParams:m||F.shouldInlineParams});if(Z(F,B)){let $=F[B.Symbol.Schema],J=F[B.Symbol.Name];return{sql:$===void 0||F[BT]?c(J):c($)+"."+c(J),params:[]}}if(Z(F,Li)){let $=p.getColumnCasing(F);if(o.invokeSource==="indexes")return{sql:c($),params:[]};let J=F.table[B.Symbol.Schema];return{sql:F.table[BT]||J===void 0?c(F.table[B.Symbol.Name])+"."+c($):c(J)+"."+c(F.table[B.Symbol.Name])+"."+c($),params:[]}}if(Z(F,ro)){let $=F[Ni].schema,J=F[Ni].name;return{sql:$===void 0||F[Ni].isAlias?c(J):c($)+"."+c(J),params:[]}}if(Z(F,Tn)){if(Z(F.value,Ip))return{sql:x(f.value++,F),params:[F],typings:["none"]};let $=F.value===null?null:F.encoder.mapToDriverValue(F.value);if(Z($,N))return this.buildQueryFromSourceParams([$],n);if(m)return{sql:this.mapInlineParam($,n),params:[]};let J=["none"];if(T)J=[T(F.encoder)];return{sql:x(f.value++,$),params:[$],typings:J}}if(Z(F,Ip))return{sql:x(f.value++,F),params:[F],typings:["none"]};if(Z(F,N.Aliased)&&F.fieldAlias!==void 0)return{sql:c(F.fieldAlias),params:[]};if(Z(F,wo)){if(F._.isWith)return{sql:c(F._.alias),params:[]};return this.buildQueryFromSourceParams([new Xo("("),F._.sql,new Xo(") "),new H0(F._.alias)],n)}if(G3(F)){if(F.schema)return{sql:c(F.schema)+"."+c(F.enumName),params:[]};return{sql:c(F.enumName),params:[]}}if(A$(F)){if(F.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([F.getSQL()],n);return this.buildQueryFromSourceParams([new Xo("("),F.getSQL(),new Xo(")")],n)}if(m)return{sql:this.mapInlineParam(F,n),params:[]};return{sql:x(f.value++,F),params:[F],typings:["none"]}}))}mapInlineParam(i,{escapeString:o}){if(i===null)return"null";if(typeof i==="number"||typeof i==="boolean")return i.toString();if(typeof i==="string")return o(i);if(typeof i==="object"){let n=i.toString();if(n==="[object Object]")return o(JSON.stringify(i));return o(n)}throw new Error("Unexpected param value: "+i)}getSQL(){return this}as(i){if(i===void 0)return this;return new N.Aliased(this,i)}mapWith(i){return this.decoder=typeof i==="function"?{mapFromDriverValue:i}:i,this}inlineParams(){return this.shouldInlineParams=!0,this}if(i){return i?this:void 0}}class H0{constructor(i){this.value=i}static[w]="Name";brand;getSQL(){return new N([this])}}function z3(i){return typeof i==="object"&&i!==null&&"mapToDriverValue"in i&&typeof i.mapToDriverValue==="function"}var u3={mapFromDriverValue:(i)=>i},Q3={mapToDriverValue:(i)=>i},jr={...u3,...Q3};class Tn{constructor(i,o=Q3){this.value=i,this.encoder=o}static[w]="Param";brand;getSQL(){return new N([this])}}function W(i,...o){let n=[];if(o.length>0||i.length>0&&i[0]!=="")n.push(new Xo(i[0]));for(let[p,c]of o.entries())n.push(c,new Xo(i[p+1]));return new N(n)}((i)=>{function o(){return new N([])}i.empty=o;function n(f){return new N(f)}i.fromList=n;function p(f){return new N([new Xo(f)])}i.raw=p;function c(f,F){let $=[];for(let[J,A]of f.entries()){if(J>0&&F!==void 0)$.push(F);$.push(A)}return new N($)}i.join=c;function x(f){return new H0(f)}i.identifier=x;function T(f){return new Ip(f)}i.placeholder=T;function m(f,F){return new Tn(f,F)}i.param=m})(W||(W={}));((i)=>{class o{constructor(n,p){this.sql=n,this.fieldAlias=p}static[w]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new o(this.sql,this.fieldAlias)}}i.Aliased=o})(N||(N={}));class Ip{constructor(i){this.name=i}static[w]="Placeholder";getSQL(){return new N([this])}}function v$(i,o){return i.map((n)=>{if(Z(n,Ip)){if(!(n.name in o))throw new Error(`No value for placeholder "${n.name}" was provided`);return o[n.name]}if(Z(n,Tn)&&Z(n.value,Ip)){if(!(n.value.name in o))throw new Error(`No value for placeholder "${n.value.name}" was provided`);return n.encoder.mapToDriverValue(o[n.value.name])}return n})}var eM=Symbol.for("drizzle:IsDrizzleView");class ro{static[w]="View";[Ni];[eM]=!0;constructor({name:i,schema:o,selectedFields:n,query:p}){this[Ni]={name:i,originalName:i,schema:o,selectedFields:n,query:p,isExisting:!p,isAlias:!1}}getSQL(){return new N([this])}}Li.prototype.getSQL=function(){return new N([this])};B.prototype.getSQL=function(){return new N([this])};wo.prototype.getSQL=function(){return new N([this])};class Xx{constructor(i){this.table=i}static[w]="ColumnAliasProxyHandler";get(i,o){if(o==="table")return this.table;return i[o]}}class NT{constructor(i,o){this.alias=i,this.replaceOriginalName=o}static[w]="TableAliasProxyHandler";get(i,o){if(o===B.Symbol.IsAlias)return!0;if(o===B.Symbol.Name)return this.alias;if(this.replaceOriginalName&&o===B.Symbol.OriginalName)return this.alias;if(o===Ni)return{...i[Ni],name:this.alias,isAlias:!0};if(o===B.Symbol.Columns){let p=i[B.Symbol.Columns];if(!p)return p;let c={};return Object.keys(p).map((x)=>{c[x]=new Proxy(p[x],new Xx(new Proxy(i,this)))}),c}let n=i[o];if(Z(n,Li))return new Proxy(n,new Xx(new Proxy(i,this)));return n}}function U0(i,o){return new Proxy(i,new NT(o,!1))}function tn(i,o){return new Proxy(i,new Xx(new Proxy(i.table,new NT(o,!1))))}function w$(i,o){return new N.Aliased(bT(i.sql,o),i.fieldAlias)}function bT(i,o){return W.join(i.queryChunks.map((n)=>{if(Z(n,Li))return tn(n,o);if(Z(n,N))return bT(n,o);if(Z(n,N.Aliased))return w$(n,o);return n}))}class Z0 extends Error{static[w]="DrizzleError";constructor({message:i,cause:o}){super(i);this.name="DrizzleError",this.cause=o}}class X$ extends Z0{static[w]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function eo(i,o){if(z3(o)&&!A$(i)&&!Z(i,Tn)&&!Z(i,Ip)&&!Z(i,Li)&&!Z(i,B)&&!Z(i,ro))return new Tn(i,o);return i}var dn=(i,o)=>{return W`${i} = ${eo(o,i)}`},V3=(i,o)=>{return W`${i} <> ${eo(o,i)}`};function wc(...i){let o=i.filter((n)=>n!==void 0);if(o.length===0)return;if(o.length===1)return new N(o);return new N([new Xo("("),W.join(o,new Xo(" and ")),new Xo(")")])}function S3(...i){let o=i.filter((n)=>n!==void 0);if(o.length===0)return;if(o.length===1)return new N(o);return new N([new Xo("("),W.join(o,new Xo(" or ")),new Xo(")")])}function E3(i){return W`not ${i}`}var M0=(i,o)=>{return W`${i} > ${eo(o,i)}`},O3=(i,o)=>{return W`${i} >= ${eo(o,i)}`},_3=(i,o)=>{return W`${i} < ${eo(o,i)}`},L3=(i,o)=>{return W`${i} <= ${eo(o,i)}`};function C3(i,o){if(Array.isArray(o)){if(o.length===0)return W`false`;return W`${i} in ${o.map((n)=>eo(n,i))}`}return W`${i} in ${eo(o,i)}`}function y3(i,o){if(Array.isArray(o)){if(o.length===0)return W`true`;return W`${i} not in ${o.map((n)=>eo(n,i))}`}return W`${i} not in ${eo(o,i)}`}function D3(i){return W`${i} is null`}function I3(i){return W`${i} is not null`}function B3(i){return W`exists ${i}`}function N3(i){return W`not exists ${i}`}function b3(i,o,n){return W`${i} between ${eo(o,i)} and ${eo(n,i)}`}function j3(i,o,n){return W`${i} not between ${eo(o,i)} and ${eo(n,i)}`}function P3(i,o){return W`${i} like ${o}`}function a3(i,o){return W`${i} not like ${o}`}function l3(i,o){return W`${i} ilike ${o}`}function q3(i,o){return W`${i} not ilike ${o}`}function k3(i){return W`${i} asc`}function h3(i){return W`${i} desc`}class g3{static[w]="ConsoleLogWriter";write(i){console.log(i)}}class W${static[w]="DefaultLogger";writer;constructor(i){this.writer=i?.writer??new g3}logQuery(i,o){let n=o.map((c)=>{try{return JSON.stringify(c)}catch{return String(c)}}),p=n.length?` -- params: [${n.join(", ")}]`:"";this.writer.write(`Query: ${i}${p}`)}}class R${static[w]="NoopLogger";logQuery(){}}class jo{static[w]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(i){return this.then(void 0,i)}finally(i){return this.then((o)=>{return i?.(),o},(o)=>{throw i?.(),o})}then(i,o){return this.execute().then(i,o)}}function s3(i,o,n){let p={},c=i.reduce((x,{path:T,field:m},f)=>{let F;if(Z(m,Li))F=m;else if(Z(m,N))F=m.decoder;else F=m.sql.decoder;let $=x;for(let[J,A]of T.entries())if(J<T.length-1){if(!(A in $))$[A]={};$=$[A]}else{let X=o[f],Y=$[A]=X===null?null:F.mapFromDriverValue(X);if(n&&Z(m,Li)&&T.length===2){let R=T[0];if(!(R in p))p[R]=Y===null?Ro(m.table):!1;else if(typeof p[R]==="string"&&p[R]!==Ro(m.table))p[R]=!1}}return x},{});if(n&&Object.keys(p).length>0){for(let[x,T]of Object.entries(p))if(typeof T==="string"&&!n[T])c[x]=null}return c}function Un(i,o){return Object.entries(i).reduce((n,[p,c])=>{if(typeof p!=="string")return n;let x=o?[...o,p]:[p];if(Z(c,Li)||Z(c,N)||Z(c,N.Aliased))n.push({path:x,field:c});else if(Z(c,B))n.push(...Un(c[B.Symbol.Columns],x));else n.push(...Un(c,x));return n},[])}function jT(i,o){let n=Object.keys(i),p=Object.keys(o);if(n.length!==p.length)return!1;for(let[c,x]of n.entries())if(x!==p[c])return!1;return!0}function z0(i,o){let n=Object.entries(o).filter(([,p])=>p!==void 0).map(([p,c])=>{if(Z(c,N)||Z(c,Li))return[p,c];else return[p,new Tn(c,i[B.Symbol.Columns][p])]});if(n.length===0)throw new Error("No values to set");return Object.fromEntries(n)}function t3(i,o){for(let n of o)for(let p of Object.getOwnPropertyNames(n.prototype)){if(p==="constructor")continue;Object.defineProperty(i.prototype,p,Object.getOwnPropertyDescriptor(n.prototype,p)||Object.create(null))}}function d3(i){return i[B.Symbol.Columns]}function Ap(i){return Z(i,wo)?i._.alias:Z(i,ro)?i[Ni].name:Z(i,N)?void 0:i[B.Symbol.IsAlias]?i[B.Symbol.Name]:i[B.Symbol.BaseName]}function vi(i,o){return{name:typeof i==="string"&&i.length>0?i:"",config:typeof i==="object"?i:o}}function r3(i){if(typeof i!=="object"||i===null)return!1;if(i.constructor.name!=="Object")return!1;if("logger"in i){let o=typeof i.logger;if(o!=="boolean"&&(o!=="object"||typeof i.logger.logQuery!=="function")&&o!=="undefined")return!1;return!0}if("schema"in i){let o=typeof i.schema;if(o!=="object"&&o!=="undefined")return!1;return!0}if("casing"in i){let o=typeof i.casing;if(o!=="string"&&o!=="undefined")return!1;return!0}if("mode"in i){if(i.mode!=="default"||i.mode!=="planetscale"||i.mode!==void 0)return!1;return!0}if("connection"in i){let o=typeof i.connection;if(o!=="string"&&o!=="object"&&o!=="undefined")return!1;return!0}if("client"in i){let o=typeof i.client;if(o!=="object"&&o!=="function"&&o!=="undefined")return!1;return!0}if(Object.keys(i).length===0)return!0;return!1}class Bp extends j{static[w]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(i){if(i){let{name:o,...n}=i;this.config.generatedIdentity={type:"always",sequenceName:o,sequenceOptions:n}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(i){if(i){let{name:o,...n}=i;this.config.generatedIdentity={type:"byDefault",sequenceName:o,sequenceOptions:n}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class e3 extends Bp{static[w]="PgBigInt53Builder";constructor(i){super(i,"number","PgBigInt53")}build(i){return new iX(i,this.config)}}class iX extends _{static[w]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(i){if(typeof i==="number")return i;return Number(i)}}class oX extends Bp{static[w]="PgBigInt64Builder";constructor(i){super(i,"bigint","PgBigInt64")}build(i){return new nX(i,this.config)}}class nX extends _{static[w]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(i){return BigInt(i)}}function pX(i,o){let{name:n,config:p}=vi(i,o);if(p.mode==="number")return new e3(n);return new oX(n)}class cX extends j{static[w]="PgBigSerial53Builder";constructor(i){super(i,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(i){return new xX(i,this.config)}}class xX extends _{static[w]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(i){if(typeof i==="number")return i;return Number(i)}}class TX extends j{static[w]="PgBigSerial64Builder";constructor(i){super(i,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(i){return new mX(i,this.config)}}class mX extends _{static[w]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(i){return BigInt(i)}}function fX(i,o){let{name:n,config:p}=vi(i,o);if(p.mode==="number")return new cX(n);return new TX(n)}class FX extends j{static[w]="PgBooleanBuilder";constructor(i){super(i,"boolean","PgBoolean")}build(i){return new $X(i,this.config)}}class $X extends _{static[w]="PgBoolean";getSQLType(){return"boolean"}}function PT(i){return new FX(i??"")}class JX extends j{static[w]="PgCharBuilder";constructor(i,o){super(i,"string","PgChar");this.config.length=o.length,this.config.enumValues=o.enum}build(i){return new AX(i,this.config)}}class AX extends _{static[w]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function vX(i,o={}){let{name:n,config:p}=vi(i,o);return new JX(n,p)}class wX extends j{static[w]="PgCidrBuilder";constructor(i){super(i,"string","PgCidr")}build(i){return new XX(i,this.config)}}class XX extends _{static[w]="PgCidr";getSQLType(){return"cidr"}}function WX(i){return new wX(i??"")}class RX extends j{static[w]="PgCustomColumnBuilder";constructor(i,o,n){super(i,"custom","PgCustomColumn");this.config.fieldConfig=o,this.config.customTypeParams=n}build(i){return new YX(i,this.config)}}class YX extends _{static[w]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(i,o){super(i,o);this.sqlName=o.customTypeParams.dataType(o.fieldConfig),this.mapTo=o.customTypeParams.toDriver,this.mapFrom=o.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(i){return typeof this.mapFrom==="function"?this.mapFrom(i):i}mapToDriverValue(i){return typeof this.mapTo==="function"?this.mapTo(i):i}}function GX(i){return(o,n)=>{let{name:p,config:c}=vi(o,n);return new RX(p,c,i)}}class vp extends j{static[w]="PgDateColumnBaseBuilder";defaultNow(){return this.default(W`now()`)}}class KX extends vp{static[w]="PgDateBuilder";constructor(i){super(i,"date","PgDate")}build(i){return new u0(i,this.config)}}class u0 extends _{static[w]="PgDate";getSQLType(){return"date"}mapFromDriverValue(i){return new Date(i)}mapToDriverValue(i){return i.toISOString()}}class HX extends vp{static[w]="PgDateStringBuilder";constructor(i){super(i,"string","PgDateString")}build(i){return new Q0(i,this.config)}}class Q0 extends _{static[w]="PgDateString";getSQLType(){return"date"}}function UX(i,o){let{name:n,config:p}=vi(i,o);if(p?.mode==="date")return new KX(n);return new HX(n)}class ZX extends j{static[w]="PgDoublePrecisionBuilder";constructor(i){super(i,"number","PgDoublePrecision")}build(i){return new MX(i,this.config)}}class MX extends _{static[w]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(i){if(typeof i==="string")return Number.parseFloat(i);return i}}function zX(i){return new ZX(i??"")}class uX extends j{static[w]="PgInetBuilder";constructor(i){super(i,"string","PgInet")}build(i){return new QX(i,this.config)}}class QX extends _{static[w]="PgInet";getSQLType(){return"inet"}}function VX(i){return new uX(i??"")}class SX extends Bp{static[w]="PgIntegerBuilder";constructor(i){super(i,"number","PgInteger")}build(i){return new EX(i,this.config)}}class EX extends _{static[w]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(i){if(typeof i==="string")return Number.parseInt(i);return i}}function V0(i){return new SX(i??"")}class OX extends j{static[w]="PgIntervalBuilder";constructor(i,o){super(i,"string","PgInterval");this.config.intervalConfig=o}build(i){return new _X(i,this.config)}}class _X extends _{static[w]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let i=this.fields?` ${this.fields}`:"",o=this.precision?`(${this.precision})`:"";return`interval${i}${o}`}}function LX(i,o={}){let{name:n,config:p}=vi(i,o);return new OX(n,p)}class CX extends j{static[w]="PgJsonBuilder";constructor(i){super(i,"json","PgJson")}build(i){return new S0(i,this.config)}}class S0 extends _{static[w]="PgJson";constructor(i,o){super(i,o)}getSQLType(){return"json"}mapToDriverValue(i){return JSON.stringify(i)}mapFromDriverValue(i){if(typeof i==="string")try{return JSON.parse(i)}catch{return i}return i}}function yX(i){return new CX(i??"")}class DX extends j{static[w]="PgJsonbBuilder";constructor(i){super(i,"json","PgJsonb")}build(i){return new E0(i,this.config)}}class E0 extends _{static[w]="PgJsonb";constructor(i,o){super(i,o)}getSQLType(){return"jsonb"}mapToDriverValue(i){return JSON.stringify(i)}mapFromDriverValue(i){if(typeof i==="string")try{return JSON.parse(i)}catch{return i}return i}}function IX(i){return new DX(i??"")}class BX extends j{static[w]="PgLineBuilder";constructor(i){super(i,"array","PgLine")}build(i){return new NX(i,this.config)}}class NX extends _{static[w]="PgLine";getSQLType(){return"line"}mapFromDriverValue(i){let[o,n,p]=i.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(n),Number.parseFloat(p)]}mapToDriverValue(i){return`{${i[0]},${i[1]},${i[2]}}`}}class bX extends j{static[w]="PgLineABCBuilder";constructor(i){super(i,"json","PgLineABC")}build(i){return new jX(i,this.config)}}class jX extends _{static[w]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(i){let[o,n,p]=i.slice(1,-1).split(",");return{a:Number.parseFloat(o),b:Number.parseFloat(n),c:Number.parseFloat(p)}}mapToDriverValue(i){return`{${i.a},${i.b},${i.c}}`}}function PX(i,o){let{name:n,config:p}=vi(i,o);if(!p?.mode||p.mode==="tuple")return new BX(n);return new bX(n)}class aX extends j{static[w]="PgMacaddrBuilder";constructor(i){super(i,"string","PgMacaddr")}build(i){return new lX(i,this.config)}}class lX extends _{static[w]="PgMacaddr";getSQLType(){return"macaddr"}}function qX(i){return new aX(i??"")}class kX extends j{static[w]="PgMacaddr8Builder";constructor(i){super(i,"string","PgMacaddr8")}build(i){return new hX(i,this.config)}}class hX extends _{static[w]="PgMacaddr8";getSQLType(){return"macaddr8"}}function gX(i){return new kX(i??"")}class sX extends j{static[w]="PgNumericBuilder";constructor(i,o,n){super(i,"string","PgNumeric");this.config.precision=o,this.config.scale=n}build(i){return new O0(i,this.config)}}class O0 extends _{static[w]="PgNumeric";precision;scale;constructor(i,o){super(i,o);this.precision=o.precision,this.scale=o.scale}mapFromDriverValue(i){if(typeof i==="string")return i;return String(i)}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class tX extends j{static[w]="PgNumericNumberBuilder";constructor(i,o,n){super(i,"number","PgNumericNumber");this.config.precision=o,this.config.scale=n}build(i){return new dX(i,this.config)}}class dX extends _{static[w]="PgNumericNumber";precision;scale;constructor(i,o){super(i,o);this.precision=o.precision,this.scale=o.scale}mapFromDriverValue(i){if(typeof i==="number")return i;return Number(i)}mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class rX extends j{static[w]="PgNumericBigIntBuilder";constructor(i,o,n){super(i,"bigint","PgNumericBigInt");this.config.precision=o,this.config.scale=n}build(i){return new eX(i,this.config)}}class eX extends _{static[w]="PgNumericBigInt";precision;scale;constructor(i,o){super(i,o);this.precision=o.precision,this.scale=o.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function i7(i,o){let{name:n,config:p}=vi(i,o),c=p?.mode;return c==="number"?new tX(n,p?.precision,p?.scale):c==="bigint"?new rX(n,p?.precision,p?.scale):new sX(n,p?.precision,p?.scale)}class o7 extends j{static[w]="PgPointTupleBuilder";constructor(i){super(i,"array","PgPointTuple")}build(i){return new n7(i,this.config)}}class n7 extends _{static[w]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(i){if(typeof i==="string"){let[o,n]=i.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(n)]}return[i.x,i.y]}mapToDriverValue(i){return`(${i[0]},${i[1]})`}}class p7 extends j{static[w]="PgPointObjectBuilder";constructor(i){super(i,"json","PgPointObject")}build(i){return new c7(i,this.config)}}class c7 extends _{static[w]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(i){if(typeof i==="string"){let[o,n]=i.slice(1,-1).split(",");return{x:Number.parseFloat(o),y:Number.parseFloat(n)}}return i}mapToDriverValue(i){return`(${i.x},${i.y})`}}function x7(i,o){let{name:n,config:p}=vi(i,o);if(!p?.mode||p.mode==="tuple")return new o7(n);return new p7(n)}function iz(i){let o=[];for(let n=0;n<i.length;n+=2)o.push(Number.parseInt(i.slice(n,n+2),16));return new Uint8Array(o)}function T7(i,o){let n=new ArrayBuffer(8),p=new DataView(n);for(let c=0;c<8;c++)p.setUint8(c,i[o+c]);return p.getFloat64(0,!0)}function Y$(i){let o=iz(i),n=0,p=o[n];n+=1;let c=new DataView(o.buffer),x=c.getUint32(n,p===1);n+=4;let T;if(x&536870912)T=c.getUint32(n,p===1),n+=4;if((x&65535)===1){let m=T7(o,n);n+=8;let f=T7(o,n);return n+=8,[m,f]}throw new Error("Unsupported geometry type")}class m7 extends j{static[w]="PgGeometryBuilder";constructor(i){super(i,"array","PgGeometry")}build(i){return new f7(i,this.config)}}class f7 extends _{static[w]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(i){return Y$(i)}mapToDriverValue(i){return`point(${i[0]} ${i[1]})`}}class F7 extends j{static[w]="PgGeometryObjectBuilder";constructor(i){super(i,"json","PgGeometryObject")}build(i){return new $7(i,this.config)}}class $7 extends _{static[w]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(i){let o=Y$(i);return{x:o[0],y:o[1]}}mapToDriverValue(i){return`point(${i.x} ${i.y})`}}function J7(i,o){let{name:n,config:p}=vi(i,o);if(!p?.mode||p.mode==="tuple")return new m7(n);return new F7(n)}class A7 extends j{static[w]="PgRealBuilder";constructor(i,o){super(i,"number","PgReal");this.config.length=o}build(i){return new v7(i,this.config)}}class v7 extends _{static[w]="PgReal";constructor(i,o){super(i,o)}getSQLType(){return"real"}mapFromDriverValue=(i)=>{if(typeof i==="string")return Number.parseFloat(i);return i}}function w7(i){return new A7(i??"")}class X7 extends j{static[w]="PgSerialBuilder";constructor(i){super(i,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(i){return new W7(i,this.config)}}class W7 extends _{static[w]="PgSerial";getSQLType(){return"serial"}}function R7(i){return new X7(i??"")}class Y7 extends Bp{static[w]="PgSmallIntBuilder";constructor(i){super(i,"number","PgSmallInt")}build(i){return new G7(i,this.config)}}class G7 extends _{static[w]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(i)=>{if(typeof i==="string")return Number(i);return i}}function K7(i){return new Y7(i??"")}class H7 extends j{static[w]="PgSmallSerialBuilder";constructor(i){super(i,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(i){return new U7(i,this.config)}}class U7 extends _{static[w]="PgSmallSerial";getSQLType(){return"smallserial"}}function Z7(i){return new H7(i??"")}class M7 extends j{static[w]="PgTextBuilder";constructor(i,o){super(i,"string","PgText");this.config.enumValues=o.enum}build(i){return new z7(i,this.config)}}class z7 extends _{static[w]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function u7(i,o={}){let{name:n,config:p}=vi(i,o);return new M7(n,p)}class Q7 extends vp{constructor(i,o,n){super(i,"string","PgTime");this.withTimezone=o,this.precision=n,this.config.withTimezone=o,this.config.precision=n}static[w]="PgTimeBuilder";build(i){return new _0(i,this.config)}}class _0 extends _{static[w]="PgTime";withTimezone;precision;constructor(i,o){super(i,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function V7(i,o={}){let{name:n,config:p}=vi(i,o);return new Q7(n,p.withTimezone??!1,p.precision)}class S7 extends vp{static[w]="PgTimestampBuilder";constructor(i,o,n){super(i,"date","PgTimestamp");this.config.withTimezone=o,this.config.precision=n}build(i){return new L0(i,this.config)}}class L0 extends _{static[w]="PgTimestamp";withTimezone;precision;constructor(i,o){super(i,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(i)=>{return new Date(this.withTimezone?i:i+"+0000")};mapToDriverValue=(i)=>{return i.toISOString()}}class E7 extends vp{static[w]="PgTimestampStringBuilder";constructor(i,o,n){super(i,"string","PgTimestampString");this.config.withTimezone=o,this.config.precision=n}build(i){return new C0(i,this.config)}}class C0 extends _{static[w]="PgTimestampString";withTimezone;precision;constructor(i,o){super(i,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function In(i,o={}){let{name:n,config:p}=vi(i,o);if(p?.mode==="string")return new E7(n,p.withTimezone??!1,p.precision);return new S7(n,p?.withTimezone??!1,p?.precision)}class O7 extends j{static[w]="PgUUIDBuilder";constructor(i){super(i,"string","PgUUID")}defaultRandom(){return this.default(W`gen_random_uuid()`)}build(i){return new y0(i,this.config)}}class y0 extends _{static[w]="PgUUID";getSQLType(){return"uuid"}}function mn(i){return new O7(i??"")}class _7 extends j{static[w]="PgVarcharBuilder";constructor(i,o){super(i,"string","PgVarchar");this.config.length=o.length,this.config.enumValues=o.enum}build(i){return new L7(i,this.config)}}class L7 extends _{static[w]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function Zo(i,o={}){let{name:n,config:p}=vi(i,o);return new _7(n,p)}class C7 extends j{static[w]="PgBinaryVectorBuilder";constructor(i,o){super(i,"string","PgBinaryVector");this.config.dimensions=o.dimensions}build(i){return new y7(i,this.config)}}class y7 extends _{static[w]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function D7(i,o){let{name:n,config:p}=vi(i,o);return new C7(n,p)}class I7 extends j{static[w]="PgHalfVectorBuilder";constructor(i,o){super(i,"array","PgHalfVector");this.config.dimensions=o.dimensions}build(i){return new B7(i,this.config)}}class B7 extends _{static[w]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(i){return JSON.stringify(i)}mapFromDriverValue(i){return i.slice(1,-1).split(",").map((o)=>Number.parseFloat(o))}}function N7(i,o){let{name:n,config:p}=vi(i,o);return new I7(n,p)}class b7 extends j{static[w]="PgSparseVectorBuilder";constructor(i,o){super(i,"string","PgSparseVector");this.config.dimensions=o.dimensions}build(i){return new j7(i,this.config)}}class j7 extends _{static[w]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function P7(i,o){let{name:n,config:p}=vi(i,o);return new b7(n,p)}class a7 extends j{static[w]="PgVectorBuilder";constructor(i,o){super(i,"array","PgVector");this.config.dimensions=o.dimensions}build(i){return new l7(i,this.config)}}class l7 extends _{static[w]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(i){return JSON.stringify(i)}mapFromDriverValue(i){return i.slice(1,-1).split(",").map((o)=>Number.parseFloat(o))}}function q7(i,o){let{name:n,config:p}=vi(i,o);return new a7(n,p)}function k7(){return{bigint:pX,bigserial:fX,boolean:PT,char:vX,cidr:WX,customType:GX,date:UX,doublePrecision:zX,inet:VX,integer:V0,interval:LX,json:yX,jsonb:IX,line:PX,macaddr:qX,macaddr8:gX,numeric:i7,point:x7,geometry:J7,real:w7,serial:R7,smallint:K7,smallserial:Z7,text:u7,time:V7,timestamp:In,uuid:mn,varchar:Zo,bit:D7,halfvec:N7,sparsevec:P7,vector:q7}}var G$=Symbol.for("drizzle:PgInlineForeignKeys"),h7=Symbol.for("drizzle:EnableRLS");class Mo extends B{static[w]="PgTable";static Symbol=Object.assign({},B.Symbol,{InlineForeignKeys:G$,EnableRLS:h7});[G$]=[];[h7]=!1;[B.Symbol.ExtraConfigBuilder]=void 0;[B.Symbol.ExtraConfigColumns]={}}function oz(i,o,n,p,c=i){let x=new Mo(i,p,c),T=typeof o==="function"?o(k7()):o,m=Object.fromEntries(Object.entries(T).map(([$,J])=>{let A=J;A.setName($);let X=A.build(x);return x[G$].push(...A.buildForeignKeys(X,x)),[$,X]})),f=Object.fromEntries(Object.entries(T).map(([$,J])=>{let A=J;A.setName($);let X=A.buildExtraConfigColumn(x);return[$,X]})),F=Object.assign(x,m);if(F[B.Symbol.Columns]=m,F[B.Symbol.ExtraConfigColumns]=f,n)F[Mo.Symbol.ExtraConfigBuilder]=n;return Object.assign(F,{enableRLS:()=>{return F[Mo.Symbol.EnableRLS]=!0,F}})}var Np=(i,o,n)=>{return oz(i,o,n,void 0)};function g7(...i){if(i[0].columns)return new aT(i[0].columns,i[0].name);return new aT(i)}class aT{static[w]="PgPrimaryKeyBuilder";columns;name;constructor(i,o){this.columns=i,this.name=o}build(i){return new s7(i,this.columns,this.name)}}class s7{constructor(i,o,n){this.table=i,this.columns=o,this.name=n}static[w]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Mo.Symbol.Name]}_${this.columns.map((i)=>i.name).join("_")}_pk`}}class K${constructor(i,o,n){this.sourceTable=i,this.referencedTable=o,this.relationName=n,this.referencedTableName=o[B.Symbol.Name]}static[w]="Relation";referencedTableName;fieldName}class t7{constructor(i,o){this.table=i,this.config=o}static[w]="Relations"}class bp extends K${constructor(i,o,n,p){super(i,o,n?.relationName);this.config=n,this.isNullable=p}static[w]="One";withFieldName(i){let o=new bp(this.sourceTable,this.referencedTable,this.config,this.isNullable);return o.fieldName=i,o}}class lT extends K${constructor(i,o,n){super(i,o,n?.relationName);this.config=n}static[w]="Many";withFieldName(i){let o=new lT(this.sourceTable,this.referencedTable,this.config);return o.fieldName=i,o}}function d7(){return{and:wc,between:b3,eq:dn,exists:B3,gt:M0,gte:O3,ilike:l3,inArray:C3,isNull:D3,isNotNull:I3,like:P3,lt:_3,lte:L3,ne:V3,not:E3,notBetween:j3,notExists:N3,notLike:a3,notIlike:q3,notInArray:y3,or:S3,sql:W}}function r7(){return{sql:W,asc:k3,desc:h3}}function e7(i,o){if(Object.keys(i).length===1&&"default"in i&&!Z(i.default,B))i=i.default;let n={},p={},c={};for(let[x,T]of Object.entries(i))if(Z(T,B)){let m=vc(T),f=p[m];n[m]=x,c[x]={tsName:x,dbName:T[B.Symbol.Name],schema:T[B.Symbol.Schema],columns:T[B.Symbol.Columns],relations:f?.relations??{},primaryKey:f?.primaryKey??[]};for(let $ of Object.values(T[B.Symbol.Columns]))if($.primary)c[x].primaryKey.push($);let F=T[B.Symbol.ExtraConfigBuilder]?.(T[B.Symbol.ExtraConfigColumns]);if(F){for(let $ of Object.values(F))if(Z($,aT))c[x].primaryKey.push(...$.columns)}}else if(Z(T,t7)){let m=vc(T.table),f=n[m],F=T.config(o(T.table)),$;for(let[J,A]of Object.entries(F))if(f){let X=c[f];if(X.relations[J]=A,$)X.primaryKey.push(...$)}else{if(!(m in p))p[m]={relations:{},primaryKey:$};p[m].relations[J]=A}}return{tables:c,tableNamesMap:n}}function nz(i){return function o(n,p){return new bp(i,n,p,p?.fields.reduce((c,x)=>c&&x.notNull,!0)??!1)}}function pz(i){return function o(n,p){return new lT(i,n,p)}}function iW(i,o,n){if(Z(n,bp)&&n.config)return{fields:n.config.fields,references:n.config.references};let p=o[vc(n.referencedTable)];if(!p)throw new Error(`Table "${n.referencedTable[B.Symbol.Name]}" not found in schema`);let c=i[p];if(!c)throw new Error(`Table "${p}" not found in schema`);let x=n.sourceTable,T=o[vc(x)];if(!T)throw new Error(`Table "${x[B.Symbol.Name]}" not found in schema`);let m=[];for(let f of Object.values(c.relations))if(n.relationName&&n!==f&&f.relationName===n.relationName||!n.relationName&&f.referencedTable===n.sourceTable)m.push(f);if(m.length>1)throw n.relationName?new Error(`There are multiple relations with name "${n.relationName}" in table "${p}"`):new Error(`There are multiple relations between "${p}" and "${n.sourceTable[B.Symbol.Name]}". Please specify relation name`);if(m[0]&&Z(m[0],bp)&&m[0].config)return{fields:m[0].config.references,references:m[0].config.fields};throw new Error(`There is not enough information to infer relation "${T}.${n.fieldName}"`)}function oW(i){return{one:nz(i),many:pz(i)}}function D0(i,o,n,p,c=(x)=>x){let x={};for(let[T,m]of p.entries())if(m.isJson){let f=o.relations[m.tsKey],F=n[T],$=typeof F==="string"?JSON.parse(F):F;x[m.tsKey]=Z(f,bp)?$&&D0(i,i[m.relationTableTsKey],$,m.selection,c):$.map((J)=>D0(i,i[m.relationTableTsKey],J,m.selection,c))}else{let f=c(n[T]),F=m.field,$;if(Z(F,Li))$=F;else if(Z(F,N))$=F.decoder;else $=F.sql.decoder;x[m.tsKey]=f===null?null:$.mapFromDriverValue(f)}return x}var aR=C1(PR(),1),{Server:lR,Namespace:Ppi,Socket:api}=aR.default;import{readFileSync as hR}from"fs";import{resolve as XJ}from"path";function eS(i,o){let n={},p=[];for(let c in i){let x=i[c],T=o[c],m=x["~standard"].validate(T);if(m instanceof Promise)throw new Error(`Validation must be synchronous, but ${c} returned a Promise.`);if(m.issues){p.push(...m.issues.map((f)=>({...f,path:[c,...f.path??[]]})));continue}n[c]=m.value}if(p.length)return{issues:p};return{value:n}}function qR(i){let o=i.runtimeEnvStrict??i.runtimeEnv??process.env;if(i.emptyStringAsUndefined??!1){for(let[z,b]of Object.entries(o))if(b==="")delete o[z]}if(!!i.skipValidation)return o;let c=typeof i.client==="object"?i.client:{},x=typeof i.server==="object"?i.server:{},T=typeof i.shared==="object"?i.shared:{},m=i.isServer??(typeof window==="undefined"||("Deno"in window)),f=m?{...x,...T,...c}:{...c,...T},F=eS(f,o),$=i.onValidationError??((z)=>{throw console.error("\u274C Invalid environment variables:",z),new Error("Invalid environment variables")}),J=i.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(F.issues)return $(F.issues);let A=(z)=>{if(!i.clientPrefix)return!0;return!z.startsWith(i.clientPrefix)&&!(z in T)},X=(z)=>{return m||!A(z)},Y=(z)=>{return z==="__esModule"||z==="$$typeof"},R=(i.extends??[]).reduce((z,b)=>{return Object.assign(z,b)},{}),K=Object.assign(F.value,R);return new Proxy(K,{get(z,b){if(typeof b!=="string")return;if(Y(b))return;if(!X(b))return J(b);return Reflect.get(z,b)}})}var iE="__vite_start_time"in globalThis,oE=typeof window!=="undefined",gpi="vitest"in globalThis,Rp=po("string"),kR=po('"true" | "false" | undefined'),io=qR({isServer:!iE&&!oE,server:{CI:po("string | undefined").pipe(Boolean),POSTGRES_USER:Rp,POSTGRES_PASSWORD:Rp,POSTGRES_DATABASE:Rp,POSTGRES_HOST:Rp,POSTGRES_PORT:Rp.pipe((i)=>Number.parseInt(i,10)),BACKEND_PORT:Rp.pipe((i)=>Number.parseInt(i,10)),RUN_WORKERS_FROM_SOURCE:kR.pipe((i)=>i==="true"),FRONTEND_PORT:Rp.pipe((i)=>Number.parseInt(i,10)),FRONTEND_ORIGINS:Rp.pipe.try((i)=>JSON.parse(i),po("string[]")),OPENAI_API_KEY:po("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Rp,VITE_USE_SELF_SIGNED_CERTIFICATE:kR.pipe((i)=>i==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var gR=XJ(import.meta.dirname,"../dev"),WJ=io.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:hR(XJ(gR,"./cert.pem"),"utf-8"),key:hR(XJ(gR,"./key.pem"),"utf-8")}:void 0;var qp=new XF,xi=io.VITE_USE_SELF_SIGNED_CERTIFICATE?console:qp.logger;d.STORE.loggers[0]=new pc("warn",void 0,xi);if(xi!==console)Object.assign(console,xi,{log:xi.info});import{spawn as nE}from"child_process";import{resolve as pE}from"path";function RJ(i,o,n=i.logger){let p=io.RUN_WORKERS_FROM_SOURCE?"ts":"js",c=o.endsWith(".bun")?"bun":"node",T=[pE(import.meta.dir,`${o}.${p}`)];if(c==="node"&&p==="ts")T.push("--experimental-strip-types");let m=nE(c,T);return new MT(m,o,n)}var sR=C1(n$(),1);var cE=604800000,F1=(()=>{let{__userSessionMap:i}=globalThis;if(!i){i=globalThis.__userSessionMap=new Map;let o=new sR.CronJob("00 00 03 * * *",()=>{for(let[n,p]of i.entries()){let c=Date.now();for(let[x,T]of p.entries())if(c-T>cE)p.delete(x);if(p.size===0)i.delete(n)}});o.start(),process.on("exit",()=>{o.stop(),xi.info("\uD83D\uDEEC autoExpiry stopped")})}return i})();import tE from"path";import VE from"os";import SE from"fs";var $1=new Map,YJ=new Map,GJ=Symbol("OriginError"),Ex={};class un extends Promise{constructor(i,o,n,p,c={}){let x,T;super((m,f)=>{x=m,T=f});this.tagged=Array.isArray(i.raw),this.strings=i,this.args=o,this.handler=n,this.canceller=p,this.options=c,this.state=null,this.statement=null,this.resolve=(m)=>(this.active=!1,x(m)),this.reject=(m)=>(this.active=!1,T(m)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[GJ]=this.handler.debug?new Error:this.tagged&&xE(this.strings)}get origin(){return(this.handler.debug?this[GJ].stack:this.tagged&&YJ.has(this.strings)?YJ.get(this.strings):YJ.set(this.strings,this[GJ].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(i=1,o){if(this.options.simple=!1,typeof i==="function")o=i,i=1;if(this.cursorRows=i,typeof o==="function")return this.cursorFn=o,this;let n;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};n&&n();let p=new Promise((c,x)=>{this.cursorFn=(T)=>{return c({value:T,done:!1}),new Promise((m)=>n=m)},this.resolve=()=>(this.active=!1,c({done:!0})),this.reject=(T)=>(this.active=!1,x(T))});return this.execute(),p},return(){return n&&n(Ex),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(i){return this.forEachFn=i,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function xE(i){if($1.has(i))return $1.get(i);let o=Error.stackTraceLimit;return Error.stackTraceLimit=4,$1.set(i,new Error),Error.stackTraceLimit=o,$1.get(i)}class Ox extends Error{constructor(i){super(i.message);this.name=this.constructor.name,Object.assign(this,i)}}var xo={connection:tR,postgres:dR,generic:rR,notSupported:eR};function tR(i,o,n){let{host:p,port:c}=n||o,x=Object.assign(new Error("write "+i+" "+(o.path||p+":"+c)),{code:i,errno:i,address:o.path||p},o.path?{}:{port:c});return Error.captureStackTrace(x,tR),x}function dR(i){let o=new Ox(i);return Error.captureStackTrace(o,dR),o}function rR(i,o){let n=Object.assign(new Error(i+": "+o),{code:i});return Error.captureStackTrace(n,rR),n}function eR(i){let o=Object.assign(new Error(i+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:i});return Error.captureStackTrace(o,eR),o}var TE={string:{to:25,from:null,serialize:(i)=>""+i},number:{to:0,from:[21,23,26,700,701],serialize:(i)=>""+i,parse:(i)=>+i},json:{to:114,from:[114,3802],serialize:(i)=>JSON.stringify(i),parse:(i)=>JSON.parse(i)},boolean:{to:16,from:16,serialize:(i)=>i===!0?"t":"f",parse:(i)=>i==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(i)=>(i instanceof Date?i:new Date(i)).toISOString(),parse:(i)=>new Date(i)},bytea:{to:17,from:17,serialize:(i)=>"\\x"+Buffer.from(i).toString("hex"),parse:(i)=>Buffer.from(i.slice(2),"hex")}};class v1{then(){KJ()}catch(){KJ()}finally(){KJ()}}class om extends v1{constructor(i){super();this.value=W1(i)}}class en extends v1{constructor(i,o,n){super();this.value=i,this.type=o,this.array=n}}class w1 extends v1{constructor(i,o){super();this.first=i,this.rest=o}build(i,o,n,p){let c=mE.map(([x,T])=>({fn:T,i:i.search(x)})).sort((x,T)=>x.i-T.i).pop();return c.i===-1?zJ(this.first,p):c.fn(this.first,this.rest,o,n,p)}}function X1(i,o,n,p){let c=i instanceof en?i.value:i;if(c===void 0){if(i instanceof en?i.value=p.transform.undefined:c=i=p.transform.undefined,c===void 0)throw xo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+n.push(i instanceof en?(o.push(i.value),i.array?i.array[i.type||A1(i.value)]||i.type||pY(i.value):i.type):(o.push(i),A1(i)))}var oY=xY(TE);function ZJ(i,o,n,p,c,x){for(let T=1;T<i.strings.length;T++)o+=MJ(o,n,p,c,x)+i.strings[T],n=i.args[T];return o}function MJ(i,o,n,p,c){return o instanceof w1?o.build(i,n,p,c):o instanceof un?UJ(o,n,p,c):o instanceof om?o.value:o&&o[0]instanceof un?o.reduce((x,T)=>x+" "+UJ(T,n,p,c),""):X1(o,n,p,c)}function UJ(i,o,n,p){return i.fragment=!0,ZJ(i,i.strings[0],i.args[0],o,n,p)}function nY(i,o,n,p,c){return i.map((x)=>"("+p.map((T)=>MJ("values",x[T],o,n,c)).join(",")+")").join(",")}function iY(i,o,n,p,c){let x=Array.isArray(i[0]),T=o.length?o.flat():Object.keys(x?i[0]:i);return nY(x?i:[i],n,p,T,c)}function J1(i,o,n,p,c){if(typeof i==="string"&&(i=[i].concat(o)),Array.isArray(i))return zJ(i,c);let x;return(o.length?o.flat():Object.keys(i)).map((m)=>{return x=i[m],(x instanceof un?UJ(x,n,p,c):x instanceof om?x.value:X1(x,n,p,c))+" as "+W1(c.transform.column.to?c.transform.column.to(m):m)}).join(",")}var mE=Object.entries({values:iY,in:(...i)=>{let o=iY(...i);return o==="()"?"(null)":o},select:J1,as:J1,returning:J1,"\\(":J1,update(i,o,n,p,c){return(o.length?o.flat():Object.keys(i)).map((x)=>W1(c.transform.column.to?c.transform.column.to(x):x)+"="+MJ("values",i[x],n,p,c))},insert(i,o,n,p,c){let x=o.length?o.flat():Object.keys(Array.isArray(i)?i[0]:i);return"("+zJ(x,c)+")values"+nY(Array.isArray(i)?i:[i],n,p,x,c)}}).map(([i,o])=>[new RegExp("((?:^|[\\s(])"+i+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),o]);function KJ(){throw xo.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:fE,parsers:FE}=oY;function pY(i){if(Array.isArray(i))return pY(i[0]);return typeof i==="string"?1009:0}var cY=function(i){let o=xY(i||{});return{serializers:Object.assign({},fE,o.serializers),parsers:Object.assign({},FE,o.parsers)}};function xY(i){return Object.keys(i).reduce((o,n)=>{if(i[n].from&&[].concat(i[n].from).forEach((p)=>o.parsers[p]=i[n].parse),i[n].serialize)o.serializers[i[n].to]=i[n].serialize,i[n].from&&[].concat(i[n].from).forEach((p)=>o.serializers[p]=i[n].serialize);return o},{parsers:{},serializers:{}})}function zJ(i,{transform:{column:o}}){return i.map((n)=>W1(o.to?o.to(n):n)).join(",")}var W1=function i(o){return'"'+o.replace(/"/g,'""').replace(/\./g,'"."')+'"'},A1=function i(o){return o instanceof en?o.type:o instanceof Date?1184:o instanceof Uint8Array?17:o===!0||o===!1?16:typeof o==="bigint"?20:Array.isArray(o)?i(o[0]):0},$E=/\\/g,JE=/"/g;function AE(i){return i.replace($E,"\\\\").replace(JE,"\\\"")}var TY=function i(o,n,p,c){if(Array.isArray(o)===!1)return o;if(!o.length)return"{}";let x=o[0],T=c===1020?";":",";if(Array.isArray(x)&&!x.type)return"{"+o.map((m)=>i(m,n,p,c)).join(T)+"}";return"{"+o.map((m)=>{if(m===void 0){if(m=p.transform.undefined,m===void 0)throw xo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return m===null?"null":'"'+AE(n?n(m.type?m.value:m):""+m)+'"'}).join(T)+"}"},HJ={i:0,char:null,str:"",quoted:!1,last:0},mY=function i(o,n,p){return HJ.i=HJ.last=0,fY(HJ,o,n,p)};function fY(i,o,n,p){let c=[],x=p===1020?";":",";for(;i.i<o.length;i.i++){if(i.char=o[i.i],i.quoted)if(i.char==="\\")i.str+=o[++i.i];else if(i.char==='"')c.push(n?n(i.str):i.str),i.str="",i.quoted=o[i.i+1]==='"',i.last=i.i+2;else i.str+=i.char;else if(i.char==='"')i.quoted=!0;else if(i.char==="{")i.last=++i.i,c.push(fY(i,o,n,p));else if(i.char==="}"){i.quoted=!1,i.last<i.i&&c.push(n?n(o.slice(i.last,i.i)):o.slice(i.last,i.i)),i.last=i.i+1;break}else if(i.char===x&&i.p!=="}"&&i.p!=='"')c.push(n?n(o.slice(i.last,i.i)):o.slice(i.last,i.i)),i.last=i.i+1;i.p=i.char}return i.last<i.i&&c.push(n?n(o.slice(i.last,i.i+1)):o.slice(i.last,i.i+1)),c}var Zc=(i)=>{let o=i[0];for(let n=1;n<i.length;n++)o+=i[n]==="_"?i[++n].toUpperCase():i[n];return o},Mc=(i)=>{let o=i[0].toUpperCase();for(let n=1;n<i.length;n++)o+=i[n]==="_"?i[++n].toUpperCase():i[n];return o},zc=(i)=>i.replace(/_/g,"-"),rT=(i)=>i.replace(/([A-Z])/g,"_$1").toLowerCase(),eT=(i)=>(i.slice(0,1)+i.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),im=(i)=>i.replace(/-/g,"_");function uJ(i){return function o(n,p){return typeof n==="object"&&n!==null&&(p.type===114||p.type===3802)?Array.isArray(n)?n.map((c)=>o(c,p)):Object.entries(n).reduce((c,[x,T])=>Object.assign(c,{[i(x)]:o(T,p)}),{}):n}}Zc.column={from:Zc};Zc.value={from:uJ(Zc)};rT.column={to:rT};var QJ={...Zc};QJ.column.to=rT;Mc.column={from:Mc};Mc.value={from:uJ(Mc)};eT.column={to:eT};var VJ={...Mc};VJ.column.to=eT;zc.column={from:zc};zc.value={from:uJ(zc)};im.column={to:im};var SJ={...zc};SJ.column.to=im;import FY from"net";import WE from"tls";import nm from"crypto";import EJ from"stream";import{performance as $Y}from"perf_hooks";class uc extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var Jn=vE;function vE(i=[]){let o=i.slice(),n=0;return{get length(){return o.length-n},remove:(p)=>{let c=o.indexOf(p);return c===-1?null:(o.splice(c,1),p)},push:(p)=>(o.push(p),p),shift:()=>{let p=o[n++];if(n===o.length)n=0,o=[];else o[n-1]=void 0;return p}}}var Io=Buffer.allocUnsafe(256),wE="BCcDdEFfHPpQSX".split("").reduce((i,o)=>{let n=o.charCodeAt(0);return i[o]=()=>{return Io[0]=n,Si.i=5,Si},i},{}),Si=Object.assign(XE,wE,{N:String.fromCharCode(0),i:0,inc(i){return Si.i+=i,Si},str(i){let o=Buffer.byteLength(i);return R1(o),Si.i+=Io.write(i,Si.i,o,"utf8"),Si},i16(i){return R1(2),Io.writeUInt16BE(i,Si.i),Si.i+=2,Si},i32(i,o){if(o||o===0)return Io.writeUInt32BE(i,o),Si;return R1(4),Io.writeUInt32BE(i,Si.i),Si.i+=4,Si},z(i){return R1(i),Io.fill(0,Si.i,Si.i+i),Si.i+=i,Si},raw(i){return Io=Buffer.concat([Io.subarray(0,Si.i),i]),Si.i=Io.length,Si},end(i=1){Io.writeUInt32BE(Si.i-i,i);let o=Io.subarray(0,Si.i);return Si.i=0,Io=Buffer.allocUnsafe(256),o}}),g=Si;function R1(i){if(Io.length-Si.i<i){let o=Io,n=o.length;Io=Buffer.allocUnsafe(n+(n>>1)+i),o.copy(Io)}}function XE(){return Si.i=0,Si}var LJ=vY,RE=1,kp=g().S().end(),JY=g().H().end(),YE=g().i32(8).i32(80877103).end(8),GE=Buffer.concat([g().E().str(g.N).i32(0).end(),kp]),KE=g().D().str("S").str(g.N).end(),_x=()=>{},HE=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),UE={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function vY(i,o={},{onopen:n=_x,onend:p=_x,onclose:c=_x}={}){let{ssl:x,max:T,user:m,host:f,port:F,database:$,parsers:J,transform:A,onnotice:X,onnotify:Y,onparameter:R,max_pipeline:K,keep_alive:H,backoff:z,target_session_attrs:b}=i,M=Jn(),u=RE++,E={pid:null,secret:null},S=_J(O1,i.idle_timeout),y=_J(O1,i.max_lifetime),l=_J(lY,i.connect_timeout),Q=null,Ti,q=new uc,mi=Buffer.alloc(0),Ei=i.fetch_types,To={},lo={},ip=Math.random().toString(36).slice(2),O=1,k=0,Yi=0,ai=0,mo=0,Fi=0,yi=0,oo=0,qi=null,bi=null,zo=!1,Di=null,Qn=null,uo=null,Yp=null,fo=null,ji=null,Vn=null,Pn=null,C=null,Ix=null,Qo={queue:o.closed,idleTimer:S,connect(v){uo=v||!0,xA()},terminate:Nx,execute:Bx,cancel:bY,end:O1,count:0,id:u};return o.closed&&o.closed.push(Qo),Qo;async function NY(){let v;try{v=i.socket?await Promise.resolve(i.socket(i)):new FY.Socket}catch(G){Ec(G);return}return v.on("error",Ec),v.on("close",TA),v.on("drain",pA),v}async function bY({pid:v,secret:G},s,Gi){try{Ti=g().i32(16).i32(80877102).i32(v).i32(G).end(16),await cA(),Q.once("error",Gi),Q.once("close",s)}catch(gi){Gi(gi)}}function Bx(v){if(zo)return Fm(v,xo.connection("CONNECTION_DESTROYED",i));if(v.cancelled)return;try{return v.state=E,C?M.push(v):(C=v,C.active=!0),aY(v),Ko(jY(v))&&!v.describeFirst&&!v.cursorFn&&M.length<K&&(!v.options.onexecute||v.options.onexecute(Qo))}catch(G){return M.length===0&&Ko(kp),an(G),!0}}function jY(v){if(v.parameters.length>=65534)throw xo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return v.options.simple?g().Q().str(v.statement.string+g.N).end():v.describeFirst?Buffer.concat([iA(v),JY]):v.prepare?v.prepared?fm(v):Buffer.concat([iA(v),fm(v)]):PY(v)}function iA(v){return Buffer.concat([fA(v.statement.string,v.parameters,v.statement.types,v.statement.name),VG("S",v.statement.name)])}function fm(v){return Buffer.concat([QG(v.parameters,v.statement.types,v.statement.name,v.cursorName),v.cursorFn?FA("",v.cursorRows):GE])}function PY(v){return Buffer.concat([fA(v.statement.string,v.parameters,v.statement.types),KE,fm(v)])}function aY(v){let G=[],s=[],Gi=ZJ(v,v.strings[0],v.args[0],G,s,i);!v.tagged&&v.args.forEach((gi)=>X1(gi,G,s,i)),v.prepare=i.prepare&&("prepare"in v.options?v.options.prepare:!0),v.string=Gi,v.signature=v.prepare&&s+Gi,v.onlyDescribe&&delete lo[v.signature],v.parameters=v.parameters||G,v.prepared=v.prepare&&v.signature in lo,v.describeFirst=v.onlyDescribe||G.length&&!v.prepared,v.statement=v.prepared?lo[v.signature]:{string:Gi,types:s,name:v.prepare?ip+O++:""},typeof i.debug==="function"&&i.debug(u,Gi,G,s)}function Ko(v,G){if(ji=ji?Buffer.concat([ji,v]):Buffer.from(v),G||ji.length>=1024)return oA(G);return bi===null&&(bi=setImmediate(oA)),!0}function oA(v){let G=Q.write(ji,v);return bi!==null&&clearImmediate(bi),ji=bi=null,G}function lY(){an(xo.connection("CONNECT_TIMEOUT",i,Q)),Q.destroy()}async function nA(){if(Ko(YE),!await new Promise((G)=>Q.once("data",(s)=>G(s[0]===83)))&&x==="prefer")return Sc();Q.removeAllListeners(),Q=WE.connect({socket:Q,servername:FY.isIP(Q.host)?void 0:Q.host,...x==="require"||x==="allow"||x==="prefer"?{rejectUnauthorized:!1}:x==="verify-full"?{}:typeof x==="object"?x:{}}),Q.on("secureConnect",Sc),Q.on("error",Ec),Q.on("close",TA),Q.on("drain",pA)}function pA(){!C&&n(Qo)}function E1(v){if(Di){if(Di.push(v),Yi-=v.length,Yi>=0)return}mi=Di?Buffer.concat(Di,Fi-Yi):mi.length===0?v:Buffer.concat([mi,v],mi.length+v.length);while(mi.length>4){if(Fi=mi.readUInt32BE(1),Fi>=mi.length){Yi=Fi-mi.length,Di=[mi];break}try{qY(mi.subarray(0,Fi+1))}catch(G){C&&(C.cursorFn||C.describeFirst)&&Ko(kp),an(G)}mi=mi.subarray(Fi+1),Yi=0,Di=null}}async function cA(){if(zo=!1,To={},Q||(Q=await NY()),!Q)return;if(l.start(),i.socket)return x?nA():Sc();if(Q.on("connect",x?nA:Sc),i.path)return Q.connect(i.path);Q.ssl=x,Q.connect(F[ai],f[ai]),Q.host=f[ai],Q.port=F[ai],ai=(ai+1)%F.length}function xA(){setTimeout(cA,k?k+yi-$Y.now():0)}function Sc(){try{lo={},Ei=i.fetch_types,ip=Math.random().toString(36).slice(2),O=1,y.start(),Q.on("data",E1),H&&Q.setKeepAlive&&Q.setKeepAlive(!0,1000*H);let v=EG();Ko(v)}catch(v){Ec(v)}}function Ec(v){if(Qo.queue===o.connecting&&i.host[mo+1])return;an(v);while(M.length)Fm(M.shift(),v)}function an(v){fo&&(fo.destroy(v),fo=null),C&&Fm(C,v),uo&&(Fm(uo,v),uo=null)}function Fm(v,G){"query"in G||"parameters"in G||Object.defineProperties(G,{stack:{value:G.stack+v.origin.replace(/.*\n/,`
|
|
99
|
-
`),enumerable:i.debug},query:{value:v.string,enumerable:i.debug},parameters:{value:v.parameters,enumerable:i.debug},args:{value:v.args,enumerable:i.debug},types:{value:v.statement&&v.statement.types,enumerable:i.debug}}),v.reject(G)}function O1(){return Yp||(!Qo.reserved&&p(Qo),!Qo.reserved&&!uo&&!C&&M.length===0?(Nx(),new Promise((v)=>Q&&Q.readyState!=="closed"?Q.once("close",v):v())):Yp=new Promise((v)=>Vn=v))}function Nx(){if(zo=!0,fo||C||uo||M.length)Ec(xo.connection("CONNECTION_DESTROYED",i));if(clearImmediate(bi),Q)Q.removeListener("data",E1),Q.removeListener("connect",Sc),Q.readyState==="open"&&Q.end(g().X().end());Vn&&(Vn(),Yp=Vn=null)}async function TA(v){if(mi=Buffer.alloc(0),Yi=0,Di=null,clearImmediate(bi),Q.removeListener("data",E1),Q.removeListener("connect",Sc),S.cancel(),y.cancel(),l.cancel(),Q.removeAllListeners(),Q=null,uo)return xA();!v&&(C||M.length)&&Ec(xo.connection("CONNECTION_CLOSED",i,Q)),k=$Y.now(),v&&i.shared.retries++,yi=(typeof z==="function"?z(i.shared.retries):z)*1000,c(Qo,xo.connection("CONNECTION_CLOSED",i,Q))}function qY(v,G=v[0]){(G===68?kY:G===100?GG:G===65?vG:G===83?hY:G===90?gY:G===67?sY:G===50?mA:G===49?tY:G===116?dY:G===84?rY:G===82?eY:G===110?xG:G===75?TG:G===69?JG:G===115?wG:G===51?XG:G===71?WG:G===78?HG:G===72?RG:G===99?KG:G===73?UG:G===86?ZG:G===118?MG:G===87?YG:zG)(v)}function kY(v){let G=7,s,Gi,gi,Vo=C.isRaw?new Array(C.statement.columns.length):{};for(let Bo=0;Bo<C.statement.columns.length;Bo++)Gi=C.statement.columns[Bo],s=v.readInt32BE(G),G+=4,gi=s===-1?null:C.isRaw===!0?v.subarray(G,G+=s):Gi.parser===void 0?v.toString("utf8",G,G+=s):Gi.parser.array===!0?Gi.parser(v.toString("utf8",G+1,G+=s)):Gi.parser(v.toString("utf8",G,G+=s)),C.isRaw?Vo[Bo]=C.isRaw===!0?gi:A.value.from?A.value.from(gi,Gi):gi:Vo[Gi.name]=A.value.from?A.value.from(gi,Gi):gi;C.forEachFn?C.forEachFn(A.row.from?A.row.from(Vo):Vo,q):q[
|
|
98
|
+
${T.trace}`:"No previous disposal trace was found."),p.type){case"atom_family":case"mutable_atom_family":return i.defaults.get(p.key);case"selector_family":case"readonly_selector_family":{if(i.defaults.has(p.key))return i.defaults.get(n.family.key);let m=Ri(i,p).default(x);return i.defaults.set(p.key,m),m}}}return Sp(i,Ri(i,n))}class Rn extends Map{deleted=new Set;source;constructor(i){super();this.source=i}get(i){if(super.has(i))return super.get(i);if(!this.deleted.has(i)&&this.source.has(i))return this.source.get(i);return}set(i,o){return this.deleted.delete(i),super.set(i,o)}hasOwn(i){return super.has(i)}has(i){return!this.deleted.has(i)&&(super.has(i)||this.source.has(i))}delete(i){return this.deleted.add(i),super.delete(i)}}var qw=(i,o,n,p)=>{let c=I(i),x={parent:c,child:null,on:c.on,loggers:c.loggers,logger:c.logger,config:c.config,atoms:new Rn(c.atoms),atomsThatAreDefault:new Set(c.atomsThatAreDefault),families:new Rn(c.families),joins:new Rn(c.joins),operation:{open:!1},readonlySelectors:new Rn(c.readonlySelectors),timelines:new Rn(c.timelines),timelineTopics:new Ao(c.timelineTopics.toJSON()),trackers:new Map,transactions:new Rn(c.transactions),selectorAtoms:new Ao(c.selectorAtoms.toJSON()),selectorGraph:new Ao(c.selectorGraph.toJSON(),{makeContentKey:(...F)=>F.sort().join(":")}),selectors:new Rn(c.selectors),valueMap:new Rn(c.valueMap),defaults:c.defaults,disposalTraces:i.disposalTraces.copy(),molecules:new Rn(c.molecules),moleculeGraph:new Ao(c.moleculeGraph.toJSON(),{makeContentKey:c.moleculeGraph.makeContentKey}),moleculeData:new Ao(c.moleculeData.toJSON(),{makeContentKey:c.moleculeData.makeContentKey}),moleculeJoins:new Ao(c.moleculeJoins.toJSON(),{makeContentKey:c.moleculeJoins.makeContentKey}),miscResources:new Rn(c.miscResources)},T=Nw(i,o),m={phase:"building",update:{type:"transaction_update",key:o,id:p,epoch:T===void 0?Number.NaN:T+1,updates:[],params:n,output:void 0},toolkit:{get:(...F)=>Mi(f,...F),set:(...F)=>{_i(f,...F)},run:(F,$=bm())=>tc(f,F,$),find:(...F)=>t(i,...F),json:(F)=>Jo(f,F),dispose:(...F)=>{nc(f,...F)},env:()=>lw(f)}},f=Object.assign(x,{transactionMeta:m});return c.child=f,i.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",n),f};function cF(i,o){let n={key:o.key,type:"transaction",run:(x,T)=>{let m=qw(i,o.key,x,T);try{let f=I(i),{toolkit:F}=m.transactionMeta,$=o.do(F,...x);return Pw($,f),$}catch(f){throw Kw(p),i.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",f),f}},install:(x)=>cF(x,o),subject:new $i},p=I(i);p.transactions.set(n.key,n);let c=gn(n);return i.on.transactionCreation.next(c),c}class kw{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new Ao({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new Ao({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...i)=>i.sort().join(":")});trackers=new Map;families=new Map;joins=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new Ao({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new Ao({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new jm(100);molecules=new Map;moleculeJoins=new Ao({between:["moleculeKey","joinKey"],cardinality:"n:n"},{makeContentKey:(...i)=>i.sort().join(":")});moleculeGraph=new Ao({between:["upstreamMoleculeKey","downstreamMoleculeKey"],cardinality:"n:n"},{makeContentKey:(...i)=>i.sort().join(":")});moleculeData=new Ao({between:["moleculeKey","stateFamilyKey"],cardinality:"n:n"},{makeContentKey:(...i)=>i.sort().join(":")});miscResources=new Map;on={atomCreation:new $i,atomDisposal:new $i,selectorCreation:new $i,selectorDisposal:new $i,timelineCreation:new $i,transactionCreation:new $i,transactionApplying:new ef(null),operationClose:new $i,moleculeCreation:new $i,moleculeDisposal:new $i};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new pc("warn",(i,o,n)=>!hw(n))];logger={error:(...i)=>{for(let o of this.loggers)o.error(...i)},info:(...i)=>{for(let o of this.loggers)o.info(...i)},warn:(...i)=>{for(let o of this.loggers)o.warn(...i)}};constructor(i,o=null){if(this.config={...o?.config,...i},o!==null){if(this.valueMap=new Map(o?.valueMap),this.operation={...o?.operation},Ho(o))this.transactionMeta={epoch:new Map(o?.transactionMeta.epoch),actionContinuities:new Ao(o?.transactionMeta.actionContinuities.toJSON())};for(let[,p]of o.families){if(p.internalRoles?.includes("mutable")||p.internalRoles?.includes("join"))continue;p.install(this)}let n=new Set;for(let[,p]of o.atoms){if(n.has(p.key))continue;if(p.install(this),p.type==="mutable_atom"){let c=Jo(o,p),x=$p(p);n.add(c.key),n.add(x.key)}}for(let[,p]of o.readonlySelectors)p.install(this);for(let[,p]of o.selectors){if(n.has(p.key))continue;p.install(this)}for(let[,p]of o.transactions)p.install(this);for(let[,p]of o.timelines)p.install(this)}}}var d={get STORE(){return globalThis.ATOM_IO_IMPLICIT_STORE??=new kw({name:"IMPLICIT_STORE",lifespan:"ephemeral"}),globalThis.ATOM_IO_IMPLICIT_STORE}};function Ri(i,o){let n,p=i;while(p!==null){switch(o.type){case"atom":case"mutable_atom":n=p.atoms.get(o.key);break;case"selector":n=p.selectors.get(o.key);break;case"readonly_selector":n=p.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":n=p.families.get(o.key);break;case"timeline":n=p.timelines.get(o.key);break;case"transaction":n=p.transactions.get(o.key);break}if(n)return n;p=p.child}throw new ep(o,i)}function gw(i,o,n){let p=i.families.get(o.key);if(p===void 0)throw new ep(o,i);let c=p(n),x=I(i);if(c.family){if(Ho(x))switch(c.type){case"atom":case"mutable_atom":i.on.atomCreation.next(c);break;case"selector":case"readonly_selector":i.on.selectorCreation.next(c);break}else if(zi(x)&&x.on.transactionApplying.state===null)x.transactionMeta.update.updates.push({type:"state_creation",token:c})}return c}function sw(i,o,n){let p=Ji(n),c=`${o.key}(${p})`,x=I(i),T;switch(o.type){case"atom_family":case"mutable_atom_family":T=x.atoms.get(c);break;case"selector_family":T=x.selectors.get(c);break;case"readonly_selector_family":T=x.readonlySelectors.get(c);break}if(T)return gn(T);return T}function t(i,o,n){let p=sw(i,o,n);if(p)return p;let c=Ji(n),x=i.molecules.get(c);if(!x&&i.config.lifespan==="immortal"){let T=Gw(o,n);return i.logger.error("\u274C",T.type,T.key,`was not found in store "${i.config.name}"; returned a counterfeit token.`),T}if(p=gw(i,o,n),x)I(i).moleculeData.set(c,o.key);return p}function nc(i,...o){let n;if(o.length===1)n=o[0];else{let p=o[0],c=o[1];n=t(i,p,c)}try{Ri(i,n)}catch(p){i.logger.error("\u274C",n.type,n.key,`could not be disposed because it was not found in the store "${i.config.name}".`);return}switch(n.type){case"atom":case"mutable_atom":xF(i,n);break;case"selector":case"readonly_selector":tw(i,n);break}}var km=(i,o)=>I(i).atoms.has(o),QU=(i,o)=>I(i).selectors.has(o),VU=(i,o)=>I(i).readonlySelectors.has(o),dw=(i,o)=>km(i,o)||QU(i,o)||VU(i,o);var hm=(i,o)=>{return I(o).selectorGraph.getRelationEntries({downstreamSelectorKey:i}).filter(([p,{source:c}])=>c!==i).map(([p,{source:c}])=>c).filter((p)=>dw(o,p))};var TF=(i,o,n)=>{let p=[],c=hm(i,n);while(c.length>0){let x=c.shift();if(o.has(x))continue;if(o.add(x),!km(n,x))c.push(...hm(x,n));else if(!p.includes(x))p.push(x)}return p},rw=(i,o)=>{let n=i.key,p=hm(n,o),c=new Set;return p.flatMap((x)=>km(o,x)?x:TF(x,c,o))};var ew=(i,o,n,p)=>{let c=I(p);if(o.type==="atom"||o.type==="mutable_atom")c.selectorAtoms.set({selectorKey:i,atomKey:o.key}),p.logger.info("\uD83D\uDD0D","selector",i,`discovers root atom "${o.key}"`);else{let x=TF(o.key,n,p);p.logger.info("\uD83D\uDD0D","selector",i,`discovers root atoms: [ ${x.map((T)=>`"${T}"`).join(", ")} ]`);for(let T of x)c.selectorAtoms=c.selectorAtoms.set({selectorKey:i,atomKey:T})}n.add(o.key)};var gm=(i,o,n)=>({get:(...p)=>{let c=I(n),x;if(p.length===2){let[f,F]=p;x=t(n,f,F)}else[x]=p;let T=Ri(n,x),m=Sp(n,T);return n.logger.info("\uD83D\uDD0C","selector",i,`registers dependency ( "${x.key}" =`,m,")"),c.selectorGraph.set({upstreamSelectorKey:x.key,downstreamSelectorKey:i},{source:x.key}),ew(i,x,o,n),m},set:(...p)=>{let c,x;if(p.length===2)c=p[0],x=p[1];else{let f=p[0],F=p[1];x=p[2],c=t(n,f,F)}let T=I(n),m=Ri(T,c);am(T,m,x)},find:(...p)=>t(n,...p),json:(p)=>Jo(n,p)});var RT=(i,o,n)=>{let p=I(i),c=new $i,x=new Set,{get:T,find:m,json:f}=gm(o.key,x,p),F=()=>{let X=o.get({get:T,find:m,json:f});return Wn(I(i),o.key,X,c),x.clear(),X},$={...o,subject:c,install:(X)=>RT(X,o,n),get:F,type:"readonly_selector",...n&&{family:n}};p.readonlySelectors.set(o.key,$);let J=F();i.logger.info("\u2728",$.type,$.key,"=",J);let A={key:o.key,type:"readonly_selector"};if(n)A.family=n;return A};var KT=(i,o,n)=>{let p=I(i),c=new $i,x=new Set,T=gm(o.key,x,p),{find:m,get:f,json:F}=T,$={find:m,get:f,json:F},J=(K=o.get,H=I(i))=>{let z=K($);return Wn(H,o.key,z,c),x.clear(),z},X={...o,subject:c,install:(K)=>KT(K,o,n),get:J,set:(K)=>{let H=I(i),z=J(o.get,H),b=Pm(K)(z);if(i.logger.info("\uD83D\uDCDD","selector",o.key,"set (",z,"->",b,")"),Wn(H,o.key,b,c),dc(H,o.key),Ho(H))c.next({newValue:b,oldValue:z});o.set(T,b)},type:"selector",...n&&{family:n}};p.selectors.set(o.key,X);let Y=J();i.logger.info("\u2728",X.type,X.key,"=",Y);let R={key:o.key,type:"selector"};if(n)R.family=n;return R};function rf(i,o){if("set"in o){let c=KT(i,o,void 0);return i.on.selectorCreation.next(c),c}let p=RT(i,o,void 0);return i.on.selectorCreation.next(p),p}function tw(i,o){let n=I(i),{key:p}=o,c=Ri(n,o);if(!c.family)i.logger.error("\u274C","selector",p,"Standalone selectors cannot be disposed.");else{if(n.molecules.get(c.family.subKey))n.moleculeData.delete(c.family.subKey,c.family.key);let T;switch(o.type){case"selector":n.selectors.delete(p),T={key:c.family.key,type:"selector_family"},Ri(i,T).subject.next({type:"state_disposal",subType:"selector",token:o});break;case"readonly_selector":n.readonlySelectors.delete(p),T={key:c.family.key,type:"readonly_selector_family"},Ri(i,T).subject.next({type:"state_disposal",subType:"selector",token:o});break}if(n.valueMap.delete(p),n.selectorAtoms.delete(p),n.selectorGraph.delete(p),i.logger.info("\uD83D\uDD25",o.type,p,"deleted"),zi(n)&&n.transactionMeta.phase==="building")n.transactionMeta.update.updates.push({type:"state_disposal",subType:"selector",token:o});else i.on.selectorDisposal.next(o)}}function YT(i,o,n){let p={key:o.key,type:"selector_family"},c=i.families.get(o.key);if(c)i.logger.error("\u2757","selector_family",o.key,`Overwriting an existing ${hn(c)} "${c.key}" in store "${i.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let x=new $i,m=Object.assign((f)=>{let F=Ji(f),$={key:o.key,subKey:F},J=`${o.key}(${F})`,A=I(i),X=KT(A,{key:J,get:o.get(f),set:o.set(f)},$);return x.next({type:"state_creation",token:X}),X},p,{internalRoles:n,subject:x,install:(f)=>YT(f,o),default:(f)=>{return o.get(f)({get:(...$)=>Mi(i,...$),find:(...$)=>t(i,...$),json:($)=>Jo(i,$)})}});return i.families.set(o.key,m),p}function i8(i,o,n){return YT(i,{key:`${o.key}:JSON`,get:(c)=>({get:x})=>{let T=x(o,c);return n.toJson(T)},set:(c)=>({set:x},T)=>{x(o,c,n.fromJson(T))}},["mutable","json"])}var Wo=(i)=>JSON.parse(i),Ji=(i)=>JSON.stringify(i),Ek=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var o8=(i,o)=>{let n=I(i);if(n.operation.open)return n.operation.prev.get(o.key);return n.valueMap.get(o.key)};var FF=(i,o)=>{let n=I(i);return rw(o,i).map((c)=>{let x=n.atoms.get(c);if(x===void 0)throw new Error(`Atom "${c}", a dependency of selector "${o.key}", not found in store "${i.config.name}".`);return x.subject.subscribe(`${o.type}:${o.key}`,(T)=>{i.logger.info("\uD83D\uDCE2",o.type,o.key,"root",c,"went",T.oldValue,"->",T.newValue);let m=o8(n,o),f=Sp(n,o);i.logger.info("\u2728",o.type,o.key,"went",m,"->",f),o.subject.next({newValue:f,oldValue:m})})})};function Oo(i,o,n,p){function c(J){if(i.operation.open){let A=i.on.operationClose.subscribe(`state subscription ${n}`,()=>{A(),p(J)})}else p(J)}let x=Ri(i,o);i.logger.info("\uD83D\uDC40",x.type,x.key,`Adding subscription "${n}"`);let T=x.type==="selector"||x.type==="readonly_selector",m=null,f=c;if(T)m=FF(i,x),f=(J)=>{if(m)m.length=0,m.push(...FF(i,x));c(J)};let F=x.subject.subscribe(n,f);return()=>{if(i.logger.info("\uD83D\uDE48",x.type,x.key,`Removing subscription "${n}"`),F(),m)for(let J of m)J()}}var mF=(i,o,n,p)=>{let c=Ri(i,o);i.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${n}"`);let x=c.subject.subscribe(n,p);return()=>{i.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${n}" from timeline`),x()}};var fF=(i,o,n,p)=>{let c=Ri(i,o);i.logger.info("\uD83D\uDC40","transaction",o.key,`Adding subscription "${n}"`);let x=c.subject.subscribe(n,p);return()=>{i.logger.info("\uD83D\uDE48","transaction",o.key,`Removing subscription "${n}"`),x()}};class cc{Update;initializeState(i,o){let n=`*${i.key}`;o.atoms.delete(n),o.valueMap.delete(n);let p=i.family?{key:`*${i.family.key}`,subKey:i.family.subKey}:void 0,c=rp(o,{key:n,default:null},p);if(o.parent?.valueMap.has(n)){let x=o.parent.valueMap.get(n);o.valueMap.set(n,x)}return c}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(i,o,n){let p=`tracker:${n.config.name}:${zi(n)?n.transactionMeta.update.key:"main"}:${i.key}`,c=Mi(n,i);this.unsubscribeFromInnerValue=c.subscribe(p,(x)=>{_i(n,o,x)}),this.unsubscribeFromState=Oo(n,i,p,(x)=>{if(x.newValue!==x.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=x.newValue.subscribe(p,(T)=>{_i(n,o,T)})})}updateCore(i,o,n){let p=`tracker:${n.config.name}:${zi(n)?n.transactionMeta.update.key:"main"}:${i.key}`;Oo(n,o,p,({newValue:c,oldValue:x})=>{let T=n.timelineTopics.getRelatedKey(o.key);if(T){if(n.timelines.get(T)?.timeTraveling){let F=mF(n,{key:T,type:"timeline"},p,($)=>{F(),_i(n,i,(J)=>{if($==="redo"&&c)J.do(c);else if($==="undo"&&x)J.undo(x);return J})});return}}let m=n.on.operationClose.subscribe(p,()=>{m();let f=Mi(n,i),F=c===null?-1:f.getUpdateNumber(c),$=F-f.cacheUpdateNumber;if(c&&$===1)_i(n,i,(J)=>(J.do(c),J));else n.logger.info("\u274C","mutable_atom",i.key,`could not be updated. Expected update number ${f.cacheUpdateNumber+1}, but got ${F}`)})})}mutableState;latestUpdateState;[Symbol.dispose];constructor(i,o){this.mutableState=i;let n=I(o);this.latestUpdateState=this.initializeState(i,n),this.observeCore(i,this.latestUpdateState,n),this.updateCore(i,this.latestUpdateState,n),n.trackers.set(i.key,this),this[Symbol.dispose]=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),n.trackers.delete(i.key)}}}function HT(i,o,n){i.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${i.config.name}"`);let p=I(i),c=p.atoms.get(o.key);if(c&&c.type==="mutable_atom")return i.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),gn(c);let x=new $i,T={...o,type:"mutable_atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${F.config.name}"`),HT(F,o,n)},subject:x};if(n)T.family=n;let m=o.default();p.atoms.set(T.key,T),sm(i,o.key),Wn(p,o.key,m,x);let f=gn(T);if(o.effects){let F=0,$=[];for(let J of o.effects){let A=J({setSelf:(X)=>{_i(i,f,X)},onSet:(X)=>Oo(i,f,`effect[${F}]`,X)});if(A)$.push(A);++F}T.cleanup=()=>{for(let J of $)J()}}if(new cc(f,i),!n)Ww(f,o,i);return f}class $F{trackers=new Map;Update;latestUpdateAtoms;mutableAtoms;constructor(i,o){let n=dp(o,{key:`*${i.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=Ri(o,n),this.mutableAtoms=i,this.mutableAtoms.subject.subscribe(`store=${o.config.name}::tracker-atom-family`,(p)=>{let{type:c,token:x}=p;if(x.family){let T=Wo(x.family.subKey);switch(c){case"state_creation":this.trackers.set(T,new cc(x,o));break;case"state_disposal":{let m=this.trackers.get(T);if(m)m[Symbol.dispose](),this.trackers.delete(T)}break}}})}}function WT(i,o,n){let p={key:o.key,type:"mutable_atom_family"},c=i.families.get(o.key);if(c)i.logger.error("\u2757","mutable_atom_family",o.key,`Overwriting an existing ${hn(c)} "${c.key}" in store "${i.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);let x=new $i,m=Object.assign((f)=>{let F=Ji(f),$={key:o.key,subKey:F},J=`${o.key}(${F})`,A=I(i),X={key:J,default:()=>o.default(f),toJson:o.toJson,fromJson:o.fromJson,mutable:!0};if(o.effects)X.effects=o.effects(f);let Y=HT(A,X,$);return x.next({type:"state_creation",token:Y}),Y},p,{subject:x,install:(f)=>WT(f,o),toJson:o.toJson,fromJson:o.fromJson,internalRoles:n});return i.families.set(o.key,m),i8(i,m,o),new $F(m,i),p}var JF=(i,o)=>{let n=I(o),p=`${i.key}:JSON`;return n.families.get(p)};var Jo=(i,o)=>{if(o.family){let p=I(i),x={key:`${o.family.key}:JSON`,type:"selector_family"},T=Ri(p,x),m=JSON.parse(o.family.subKey);return t(i,T,m)}return{type:"selector",key:`${o.key}:JSON`}};var $p=(i)=>{let n={type:"atom",key:`*${i.key}`};if(i.family)n.family={key:`*${i.family.key}`,subKey:i.family.subKey};return n};function Vw(i){return typeof i==="object"&&i!==null&&"do"in i&&"undo"in i&&"subscribe"in i}function GT(i,o,n){let p=n.valueMap.get(o.key),c=i.valueMap.get(o.key);if(p!==c)return c;if(p===void 0)return o.default();n.logger.info("\uD83D\uDCC3","atom",o.key,"copying");let x=o.toJson(p),T=o.fromJson(x);return i.valueMap.set(o.key,T),new cc(o,n),T}function Wn(i,o,n,p){let c=i.valueMap.get(o);if(c instanceof XT)c.use(n);if(n instanceof Promise){let x=new XT(n);return i.valueMap.set(o,x),x.then((T)=>{Wn(i,o,T,p),p.next({newValue:T,oldValue:x})}).catch((T)=>{i.logger.error("\uD83D\uDCA5","state",o,"rejected:",T)}),x}return i.valueMap.set(o,n),n}var Hw=(i,o)=>{let n=o.valueMap.get(i.key);if(i.type==="mutable_atom"&&zi(o)){let{parent:p}=o;n=GT(o,i,p)}return n},uw=(i,o)=>{let n=o.valueMap.get(i);if(n instanceof XT){let p=n,c=o.selectors.get(i)??o.readonlySelectors.get(i);if(c)p.use(c.get());return}if(o.operation.open)o.operation.prev.set(i,n);o.valueMap.delete(i),o.logger.info("\uD83D\uDDD1","state",i,"evicted")};var Sw=(i,o)=>{return I(i).atomsThatAreDefault.has(o)},sm=(i,o)=>{let n=I(i);n.atomsThatAreDefault=new Set(n.atomsThatAreDefault).add(o)},Ew=(i,o)=>{let n=I(i);n.atomsThatAreDefault=new Set(I(i).atomsThatAreDefault),n.atomsThatAreDefault.delete(o)};function rp(i,o,n){i.logger.info("\uD83D\uDD28","atom",o.key,`creating in store "${i.config.name}"`);let p=I(i),c=p.atoms.get(o.key);if(c&&c.type==="atom")return i.logger.error("\u274C","atom",o.key,"Tried to create atom, but it already exists in the store."),gn(c);let x=new $i,T={...o,type:"atom",install:(F)=>{return F.logger.info("\uD83D\uDEE0\uFE0F","atom",o.key,`installing in store "${F.config.name}"`),rp(F,o,n)},subject:x};if(n)T.family=n;let m=o.default;if(o.default instanceof Function)m=o.default();p.atoms.set(T.key,T),sm(i,o.key),Wn(p,o.key,m,x);let f=gn(T);if(o.effects){let F=0,$=[];for(let J of o.effects){let A=J({setSelf:(X)=>{_i(i,f,X)},onSet:(X)=>Oo(i,f,`effect[${F}]`,X)});if(A)$.push(A);++F}T.cleanup=()=>{for(let J of $)J()}}return f}function n8(i,o){if("mutable"in o){let c=HT(i,o,void 0);return i.on.atomCreation.next(c),c}let p=rp(i,o,void 0);return i.on.atomCreation.next(p),p}function xF(i,o){let n=I(i),{key:p,family:c}=o,x=Ri(n,o);if(!c)i.logger.error("\u274C","atom",p,"Standalone atoms cannot be disposed.");else{x.cleanup?.();let T=i.valueMap.get(x.key),m=Ri(i,{key:c.key,type:"atom_family"}),f={type:"state_disposal",subType:"atom",token:o,value:T};m.subject.next(f);let F=zi(n);if(n.atoms.delete(p),n.valueMap.delete(p),n.selectorAtoms.delete(p),n.atomsThatAreDefault.delete(p),i.timelineTopics.delete(p),o.type==="mutable_atom"){let $=$p(o);xF(i,$),i.trackers.delete(p)}if(i.logger.info("\uD83D\uDD25","atom",p,"deleted"),F&&n.transactionMeta.phase==="building"){let $=n.transactionMeta.update.updates.at(-1);if(!($?.type==="molecule_disposal"&&$.values.some(([X])=>X===x.family?.key)))n.transactionMeta.update.updates.push(f)}else i.on.atomDisposal.next(o)}}class vo extends Set{mode="record";subject=new $i;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(i,o=0){super(i);if(i instanceof vo)this.parent=i,this.cacheUpdateNumber=i.cacheUpdateNumber;if(o)this.cacheLimit=o,this.cache=new Array(o),this.subscribe("auto cache",(n)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=n})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(i){let o=new vo(i.members,i.cacheLimit);return o.cache=i.cache,o.cacheIdx=i.cacheIdx,o.cacheUpdateNumber=i.cacheUpdateNumber,o}add(i){let o=super.add(i);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${Ji(i)}`);return o}clear(){let i=this.mode==="record"?[...this]:null;if(super.clear(),i)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(i)}`)}delete(i){let o=super.delete(i);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${Ji(i)}`);return o}parent;child=null;transactionUpdates=null;transaction(i){this.mode="transaction",this.transactionUpdates=[],this.child=new vo(this);let o=this.child._subscribe("transaction",(n)=>{this.transactionUpdates?.push(n)});try{if(i(this.child)){for(let p of this.transactionUpdates)this.doStep(p);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(n){throw console.warn("Did not apply transaction to SetRTX; this error was thrown:",n),n}finally{o(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(i,o){return this.subject.subscribe(i,o)}subscribe(i,o){return this.subject.subscribe(i,(n)=>{o(`${this.cacheUpdateNumber}=${n}`)})}emit(i){this.subject.next(i)}doStep(i){let o=i.indexOf(":"),n=i.substring(0,o),p=i.substring(o+1);switch(n){case"add":this.add(JSON.parse(p));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(p));break;case"tx":for(let c of p.split(";"))this.doStep(c)}}getUpdateNumber(i){let o=i.indexOf("=");return Number(i.substring(0,o))}do(i){let o=i.indexOf("="),n=Number(i.substring(0,o)),p=n-this.cacheUpdateNumber;if(p>0){if(p===1){this.mode="playback";let x=i.substring(o+1);return this.doStep(x),this.mode="record",this.cacheUpdateNumber=n,null}return this.cacheUpdateNumber+1}if(Math.abs(p)<this.cacheLimit){let x=this.cacheIdx+p;if(this.cache[x]===i)return null;this.mode="playback";let m=!1;while(!m){this.cacheIdx%=this.cacheLimit;let F=this.cache[this.cacheIdx];if(this.cacheIdx--,!F)return"OUT_OF_RANGE";this.undo(F),m=this.cacheIdx===x-1}let f=i.substring(o+1);return this.doStep(f),this.mode="record",this.cacheUpdateNumber=n,null}return"OUT_OF_RANGE"}undoStep(i){let o=i.indexOf(":"),n=i.substring(0,o),p=i.substring(o+1);switch(n){case"add":this.delete(JSON.parse(p));break;case"del":this.add(JSON.parse(p));break;case"clear":{let c=JSON.parse(p);for(let x of c)this.add(x);break}case"tx":{let c=p.split(";");for(let x=c.length-1;x>=0;x--)this.undoStep(c[x])}}}undo(i){let o=i.indexOf("=");if(Number(i.substring(0,o))===this.cacheUpdateNumber){this.mode="playback";let p=i.substring(o+1);return this.undoStep(p),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}class UT{toolkit;options;defaultContent;molecules=new Map;relations;states;core;transact(i,o){let n=this.toolkit;this.toolkit=i,o(this),this.toolkit=n}store;realm;[Symbol.dispose](){}constructor(i,o,n=d.STORE){this.store=n,this.realm=new AF(n),this.options=i,this.defaultContent=o,this.store.miscResources.set(`join:${i.key}`,this),this.realm.allocate("root",i.key),this.toolkit={get:(...M)=>Mi(n,...M),set:(...M)=>{_i(n,...M)},find:(...M)=>t(n,...M),json:(M)=>Jo(n,M)};let p=i.between[0],c=i.between[1],x=WT(n,{key:`${i.key}/relatedKeys`,default:()=>new vo,mutable:!0,fromJson:(M)=>vo.fromJSON(M),toJson:(M)=>M.toJSON()},["join","relations"]);this.core={relatedKeysAtoms:x};let T=({get:M},u)=>M(x,u),m=({set:M},u,E)=>{if(!this.store.molecules.has(Ji(u)))this.realm.allocate(i.key,u);M(x,u,(S)=>S.add(E)),M(x,E,(S)=>S.add(u))},f=({set:M},u,E)=>{M(x,u,(S)=>{return S.delete(E),S}),M(x,E,(S)=>{return S.delete(u),S})},F=(M,u,E)=>{let{find:S,get:y,set:l}=M,Q=S(x,u),Ti=y(Q);for(let q of Ti){if(E.includes(q))continue;l(x,q,(Ei)=>{return Ei.delete(u),Ei})}l(Q,(q)=>{return q.transaction((mi)=>{mi.clear();for(let Ei of E){let To=T(M,Ei),lo=To.has(u);if(this.relations.cardinality==="1:n"){let ip=[];for(let O of To){if(O===u)continue;let k=T(M,O);if(k.delete(Ei),k.size===0)ip.push(O)}if(!lo&&To.size>0)To.clear();for(let O of ip){let k=[Ei,O].sort(),Yi=`"${k[0]}:${k[1]}"`;this.molecules.delete(Yi)}}if(!lo)To.add(u);mi.add(Ei)}return!0}),q})},$=(M,u,E)=>{let{set:S}=M;S(x,u,(y)=>{return y.transaction((l)=>{for(let Q of E)l.add(Q);return!0}),y});for(let y of E)S(x,y,(l)=>{return l.add(u),l});return!0},J=(M,u,E)=>{let S=T(M,u);return E?S.has(E):S.size>0},A={getRelatedKeys:(M)=>T(this.toolkit,M),addRelation:(M,u)=>{this.store.moleculeJoins.set(M,i.key),this.store.moleculeJoins.set(u,i.key),m(this.toolkit,M,u)},deleteRelation:(M,u)=>{f(this.toolkit,M,u)},replaceRelationsSafely:(M,u)=>{F(this.toolkit,M,u)},replaceRelationsUnsafely:(M,u)=>{$(this.toolkit,M,u)},has:(M,u)=>J(this.toolkit,M,u)},X,Y;if(o){Y=dp(n,{key:`${i.key}/content`,default:o},["join","content"]);let M=({get:S},y)=>S(Y,y),u=({set:S},y,l)=>{S(Y,y,l)};X=Object.assign(A,{getContent:(S)=>{return M(this.toolkit,S)},setContent:(S,y)=>{u(this.toolkit,S,y)},deleteContent:(S)=>{this.realm.deallocate(S)}})}else X=A;let R=new Ao(i,{externalStore:X,isAType:i.isAType,isBType:i.isBType,makeContentKey:(...M)=>{let[u,E]=M,S=M.sort(),y=`${S[0]}:${S[1]}`,l=n.molecules.get(Ji(u)),Q=n.molecules.get(Ji(E));if(!l)this.realm.allocate(i.key,u);if(!Q)this.realm.allocate(i.key,E);return this.realm.allocate(u,y,"all"),this.realm.claim(E,y),this.store.moleculeJoins.set(y,i.key),y}}),K=()=>Vp(n,{key:`${i.key}/singleRelatedKey`,get:(M)=>({get:u})=>{let E=u(x,M);for(let S of E)return S;return null}},["join","keys"]),H=()=>{return Vp(n,{key:`${i.key}/multipleRelatedKeys`,get:(M)=>({get:u})=>{let E=JF(x,n);return u(E,M).members}},["join","keys"])},z=()=>Vp(n,{key:`${i.key}/singleRelatedEntry`,get:(M)=>({get:u})=>{let E=u(x,M);for(let S of E){let y=R.isAType?.(M)?M:void 0,l=y===void 0?M:void 0;y??=S,l??=S;let Q=R.makeContentKey(y,l),Ti=u(Y,Q);return[S,Ti]}return null}},["join","entries"]),b=()=>Vp(n,{key:`${i.key}/multipleRelatedEntries`,get:(M)=>({get:u})=>{let E=JF(x,n);return u(E,M).members.map((y)=>{let l=R.isAType?.(M)?M:void 0,Q=l===void 0?M:void 0;l??=y,Q??=y;let Ti=R.makeContentKey(l,Q),q=u(Y,Ti);return[y,q]})}},["join","entries"]);switch(i.cardinality){case"1:1":{let M=K(),u=`${p}KeyOf${ui(c)}`,E=`${c}KeyOf${ui(p)}`,S={[u]:M,[E]:M},y;if(o){let l=z(),Q=`${p}EntryOf${ui(c)}`,Ti=`${c}EntryOf${ui(p)}`,q={[Q]:l,[Ti]:l};y=Object.assign(S,q)}else y=S;this.relations=R,this.states=y;break}case"1:n":{let M=K(),u=H(),E=`${p}KeyOf${ui(c)}`,S=`${c}KeysOf${ui(p)}`,y={[E]:M,[S]:u},l;if(o){let Q=z(),Ti=b(),q=`${p}EntryOf${ui(c)}`,mi=`${c}EntriesOf${ui(p)}`,Ei={[q]:Q,[mi]:Ti};l=Object.assign(y,Ei)}else l=y;this.relations=R,this.states=l;break}case"n:n":{let M=H(),u=`${p}KeysOf${ui(c)}`,E=`${c}KeysOf${ui(p)}`,S={[u]:M,[E]:M},y;if(o){let l=b(),Q=`${p}EntriesOf${ui(c)}`,Ti=`${c}EntriesOf${ui(p)}`,q={[Q]:l,[Ti]:l};y=Object.assign(S,q)}else y=S;this.relations=R,this.states=y}}}}function ec(i,o){let n=o.joins.get(i.key);if(n===void 0){let c=d.STORE.joins.get(i.key);if(c===void 0)throw new Error(`Join "${i.key}" not found in store "${o.config.name}"`);n=new UT(c.options,c.defaultContent,o),o.joins.set(i.key,n)}return n}function Ep(i,o,n){let p=ec(i,n),c=I(n);if(zi(c)){let{toolkit:x}=c.transactionMeta;p.transact(x,({relations:T})=>{o(T)})}else o(p.relations)}function ix(i,o,n){let p=ec(i,n),c;switch(i.cardinality){case"1:1":{let x=`${i.a}KeyOf${ui(i.b)}`,T=`${i.b}KeyOf${ui(i.a)}`;c={get[x](){let f=p.states[x];return t(n,f,o)},get[T](){let f=p.states[T];return t(n,f,o)}};let m=`${i.a}EntryOf${ui(i.b)}`;if(m in p.states){let f=`${i.b}EntryOf${ui(i.a)}`;Object.assign(c,{get[m](){let F=p.states[m];return t(n,F,o)},get[f](){let F=p.states[f];return t(n,F,o)}})}break}case"1:n":{let x=`${i.a}KeyOf${ui(i.b)}`,T=`${i.b}KeysOf${ui(i.a)}`;c={get[x](){let f=p.states[x];return t(n,f,o)},get[T](){let f=p.states[T];return t(n,f,o)}};let m=`${i.a}EntryOf${ui(i.b)}`;if(m in p.states){let f=`${i.b}EntriesOf${ui(i.a)}`;Object.assign(c,{get[m](){let F=p.states[m];return t(n,F,o)},get[f](){let F=p.states[f];return t(n,F,o)}})}break}case"n:n":{let x=`${i.a}KeysOf${ui(i.b)}`,T=`${i.b}KeysOf${ui(i.a)}`;c={get[x](){let f=p.states[x];return t(n,f,o)},get[T](){let f=p.states[T];return t(n,f,o)}};let m=`${i.a}EntriesOf${ui(i.b)}`;if(m in p.states){let f=`${i.b}EntriesOf${ui(i.a)}`;Object.assign(c,{get[m](){let F=p.states[m];return t(n,F,o)},get[f](){let F=p.states[f];return t(n,F,o)}})}}}return c}function p8(i,o){return ec(i,o).core.relatedKeysAtoms}function hw(i){return i.startsWith("\uD83D\uDD0D ")}function Op(i){return n8(d.STORE,i)}function xc(i){return Rw(d.STORE,i)}function tm(i,o,n=d.STORE){return n.joins.set(i.key,new UT(i,o,n)),{key:i.key,type:"join",a:i.between[0],b:i.between[1],cardinality:i.cardinality}}function c8(i){return p8(i,d.STORE)}var vF=(i)=>(o,n,p,c,...x)=>{console[i](`${o} ${n} "${p}" ${c}`,...x)},SU={error:vF("error"),info:vF("info"),warn:vF("warn")};class pc{logLevel;filter;logger;constructor(i,o,n=SU){this.logLevel=i,this.filter=o,this.logger=n}error=(...i)=>{if((this.filter?.(...i)??!0)&&this.logLevel!==null)this.logger.error(...i)};info=(...i)=>{if((this.filter?.(...i)??!0)&&this.logLevel==="info")this.logger.info(...i)};warn=(...i)=>{if((this.filter?.(...i)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...i)}}var rs=Symbol("claim");class x8{store;constructor(i=d.STORE){this.store=i,Lw("root",i)}allocate(i,o,n){return ic(this.store,i,o,n)}fuse(i,o,n){return Cw(this.store,i,o,n)}deallocate(i){oc(this.store,i)}claim(i,o,n){return rc(this.store,i,o,n)}}class AF{store;realm;constructor(i=d.STORE){this.store=i,this.realm=new x8(i)}allocate(i,o,n){ic(this.store,i,o,n)}deallocate(i){oc(this.store,i)}claim(i,o,n){rc(this.store,i,o,n)}}function dm(i){return Yw(d.STORE,i)}function Tc(i){return cF(d.STORE,i)}class T8 extends Map{set(i,o){if(this.has(i))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:i,value:o}),this;return super.set(i,o)}clear(){throw new Error("Cannot clear an InvariantMap")}}class rm{type="continuity";globals=[];actions=[];perspectives=[];key;constructor(i){this.key=i}static existing=new T8;static create(i,o){let n=new rm(i),{type:p,globals:c,actions:x,perspectives:T}=o(n),m={type:p,key:i,globals:c,actions:x,perspectives:T};return rm.existing.set(i,m),m}add(...i){switch(i[0].type){case"atom":case"mutable_atom":this.globals.push(...i);break;case"transaction":this.actions.push(...i);break;case"atom_family":case"mutable_atom_family":{let[n,p]=i;this.perspectives.push({type:"realtime_perspective",resourceAtoms:n,viewAtoms:p})}break}return this}}function m8(i){let{key:o,config:n}=i,p=rm.create(o,n),{actions:c}=p;for(let x of c)aw(d.STORE,o,x.key);return bw(d.STORE,o,-1),p}var ft=Op({key:"usersInRoomIndex",mutable:!0,default:()=>new vo,toJson:(i)=>i.toJSON(),fromJson:(i)=>vo.fromJSON(i)}),wF=Op({key:"roomIndex",default:()=>new vo,mutable:!0,toJson:(i)=>i.toJSON(),fromJson:(i)=>vo.fromJSON(i)}),EU={enteredAtEpoch:0},ZT=tm({key:"usersInRooms",between:["room","user"],cardinality:"1:n",isAType:(i)=>typeof i==="string",isBType:(i)=>typeof i==="string"},EU),Ft=dm({key:"usersInMyRoomView",get:(i)=>({find:o})=>{let n=c8(ZT);return[o(n,i)]}});import{spawn as OU}from"child_process";class ox{listeners;globalListeners;handleEvent(i,...o){for(let p of this.globalListeners)p(i,...o);let n=this.listeners.get(i);if(n)for(let p of n)p(...o)}id="no_id_retrieved";emit;constructor(i){this.emit=i,this.listeners=new Map,this.globalListeners=new Set}on(i,o){let n=this.listeners.get(i);if(n)n.add(o);else this.listeners.set(i,new Set([o]));return this}onAny(i){return this.globalListeners.add(i),this}off(i,o){let n=this.listeners.get(i);if(n)if(o)n.delete(o);else this.listeners.delete(i);return this}offAny(i){return this.globalListeners.delete(i),this}}class MT extends ox{incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";process;key;logger;handleLog(i){if(Array.isArray(i)){let[o,...n]=i;switch(o){case"i":this.logger.info(...n);break;case"w":this.logger.warn(...n);break;case"e":this.logger.error(...n);break;default:return}}}constructor(i,o,n){super((p,...c)=>{let x=JSON.stringify([p,...c])+"\x03",T=(m)=>{if(m.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",T)};return this.process.stdin.once("error",T),this.process.stdin.write(x),this});if(this.process=i,this.key=o,this.logger=n??{info:(...p)=>{console.info(this.id,this.key,...p)},warn:(...p)=>{console.warn(this.id,this.key,...p)},error:(...p)=>{console.error(this.id,this.key,...p)}},this.process.stdout.on("data",(p)=>{let c=p.toString();if(c==="ALIVE")return;this.unprocessedEvents.push(...c.split("\x03"));let x=this.unprocessedEvents.shift();this.incompleteData+=x??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let T=Wo(this.incompleteData);this.handleEvent(...T);while(this.unprocessedEvents.length>0){let m=this.unprocessedEvents.shift();if(m){if(this.unprocessedEvents.length===0)this.incompleteData=m;T=Wo(m),this.handleEvent(...T)}}this.incompleteData=""}catch(T){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(T)}}),this.process.stderr.on("data",(p)=>{let c=p.toString();this.unprocessedLogs.push(...c.split("\x03"));let x=this.unprocessedLogs.shift();this.incompleteLog+=x??"";try{let T=Wo(this.incompleteLog);this.handleLog(T);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)T=Wo(this.incompleteLog),this.handleLog(T)}catch(T){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(T),console.error("\u274C\u274C\u274C\uFE0F")}}),i.pid)this.id=i.pid.toString()}}class f8 extends ox{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(i){super((...o)=>{return this.out.next(o),this});this.id=i,this.in=new $i,this.out=new $i,this.in.subscribe("socket",(o)=>{this.handleEvent(...o)})}dispose(){for(let i of this.disposalFunctions)i()}}class XF extends ox{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...i){this.process.stderr.write(Ji(i.map((o)=>o instanceof vo?`{ ${o.toJSON().members.join(" | ")} }`:o))+"\x03")}logger={info:(...i)=>{this.log("i",...i)},warn:(...i)=>{this.log("w",...i)},error:(...i)=>{this.log("e",...i)}};constructor(){super((i,...o)=>{let n=JSON.stringify([i,...o]);return this.process.stdout.write(n+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(i)=>{let o=i.toString();this.unprocessedEvents.push(...o.split("\x03"));let n=this.unprocessedEvents.shift();this.incompleteData+=n??"";try{let p=Wo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",p),this.handleEvent(...p);while(this.unprocessedEvents.length>0){let c=this.unprocessedEvents.shift();if(c){if(this.unprocessedEvents.length===0)this.incompleteData=c;let x=Wo(c);this.handleEvent(...x)}}this.incompleteData=""}catch(p){if(p instanceof Error)this.logger.error("\u2757",p.message,p.cause,p.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(i)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${i}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(i)=>{this.logger.info("\uD83D\uDC64","user",i,"joined");let o=new f8(`user:${i}`);this.relays.set(i,o),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let n of this.relayServices){let p=n(o);if(p)o.disposalFunctions.push(p)}this.on(`user:${i}`,(...n)=>{o.in.next(n)}),o.out.subscribe("socket",(n)=>{this.emit(...n)})}),this.on("user-leaves",(i)=>{let o=this.relays.get(i);if(this.off(`relay:${i}`),o)o.dispose(),this.relays.delete(i)}),process.stdout.write("ALIVE")}relay(i){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(i)}}var WF=xc({key:"roomArguments",default:["echo",["Hello World!"]]}),F8=dm({key:"room",get:(i)=>async({get:o,find:n})=>{let p=n(WF,i),c=o(p),[x,T]=c,m=await new Promise((f)=>{let F=OU(x,T,{env:process.env}),$=(J)=>{if(J.toString()==="ALIVE")F.stdout.off("data",$),f(F)};F.stdout.on("data",$)});return new MT(m,i)}});var Dt=Tc({key:"createRoom",do:({get:i,set:o,find:n},p,c,x)=>{let T=x?[c,x]:[c],m=n(WF,p);o(m,T),o(wF,($)=>$.add(p));let f=n(F8,p);return i(f)}}),It=Tc({key:"joinRoom",do:(i,o,n,p)=>{let c={enteredAtEpoch:p};return Ep(ZT,(x)=>{x.set({room:o,user:n},c)},i.env().store),c}}),Bt=Tc({key:"leaveRoom",do:(i,o,n)=>{Ep(ZT,(p)=>{p.delete({room:o,user:n})},i.env().store)}}),Nt=Tc({key:"destroyRoom",do:(i,o)=>{Ep(ZT,(n)=>{n.delete({room:o})},i.env().store),i.set(wF,(n)=>(n.delete(o),n))}});function RF(i,o){return o.map((n)=>{switch(n.type){case"transaction_update":{let p=RF(i,n.updates);return{...n,updates:p}}case"atom_update":case"selector_update":case"molecule_creation":case"molecule_disposal":case"molecule_transfer":case"state_creation":case"state_disposal":return n}}).filter((n)=>{switch(n.type){case"atom_update":case"selector_update":return i.includes(n.key);case"state_creation":case"state_disposal":return i.includes(n.token.key);case"molecule_creation":case"transaction_update":case"molecule_disposal":case"molecule_transfer":return!0}})}var Pt=xc({key:"redactor",default:{occlude:(i)=>i}}),nx=xc({key:"unacknowledgedUpdates",default:()=>[]});var em=xc({key:"sockets",default:null}),YF=Op({key:"socketsIndex",mutable:!0,default:()=>new vo,toJson:(i)=>i.toJSON(),fromJson:(i)=>vo.fromJSON(i)}),GF=Op({key:"usersIndex",mutable:!0,default:()=>new vo,toJson:(i)=>i.toJSON(),fromJson:(i)=>vo.fromJSON(i)}),mc=tm({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1",isAType:(i)=>i.startsWith("user::"),isBType:(i)=>i.startsWith("socket::")});function $8(i,o,n,p){let c=o.key;return function x(){let T=[];for(let f of o.globals){let F=f.type==="mutable_atom"?Jo(i,f):f,$=Mi(i,F);T.push(F,$)}for(let f of o.perspectives){let{viewAtoms:F,resourceAtoms:$}=f,J=t(i,F,n),A=Mi(i,J);i.logger.info("\uD83D\uDC41","atom",$.key,`${n} can see`,{viewAtoms:F,resourceAtoms:$,userView:A});for(let X of A){let Y=X.type==="mutable_atom"?Jo(i,X):X,R=Mi(i,Y);T.push(Y,R)}}let m=Ho(i)?i.transactionMeta.epoch.get(c)??null:null;p?.emit(`continuity-init:${c}`,m,T)}}function J8(i,o,n){let p=o.key;return function c(x){i.logger.info("\uD83D\uDECE\uFE0F","continuity",p,"received",x);let{key:T,id:m}=x,f=`tx-run:${T}:${m}`,F=`${f}:start`,$=`${f}:end`;performance.mark(F);try{tc(i,{type:"transaction",key:T},m)(...x.params)}catch(A){if(A instanceof Error)i.logger.error("\u274C","continuity",p,`failed to run transaction ${T} from ${n} with update ${m}`,A.message)}performance.mark($);let J=performance.measure(f,F,$);i?.logger.info("\uD83D\uDE80","transaction",T,m,n,J.duration)}}function A8(i,o,n,p){let c=o.key;return function x(T){if(i.logger.info("\uD83D\uDC4D","continuity",c,`${n} acknowledged epoch ${T}`),p[0]?.epoch===T)_i(i,nx,n,(f)=>{return f.shift(),i.logger.info("\uD83D\uDC4D","continuity",c,`${n} unacknowledged update queue now has`,f.length,"items"),f})}}function v8(i,o,n,p){let c=o.key,x=[];for(let T of o.actions){let m=fF(i,T,`sync-continuity:${c}:${n}`,(f)=>{try{let F=o.globals.map((A)=>{if(A.type==="atom")return A.key;return $p(A).key}).concat(o.perspectives.flatMap((A)=>{let{viewAtoms:X}=A,Y=t(i,X,n);return Mi(i,Y).map((K)=>{return K.type==="mutable_atom"?"*"+K.key:K.key})})),$=RF(F,f.updates),J={...f,updates:$};_i(i,nx,n,(A)=>{if(J)A.push(J),A.sort((X,Y)=>X.epoch-Y.epoch),i.logger.info("\uD83D\uDC4D","continuity",c,`${n} unacknowledged update queue now has`,A.length,"items");return A}),p?.emit(`tx-new:${c}`,J)}catch(F){if(F instanceof Error)i.logger.error("\u274C","continuity",c,`${n} failed to send update from transaction ${T.key} to ${n}`,F.message)}});x.push(m)}return x}function w8(i,o,n,p){let c=o.key,x=[];for(let T of o.perspectives){let{viewAtoms:m}=T,f=t(i,m,n),F=Oo(i,f,`sync-continuity:${c}:${n}:perspective:${T.resourceAtoms.key}`,({oldValue:$,newValue:J})=>{let A=$.map((K)=>K.key),X=J.map((K)=>K.key),Y=$.filter((K)=>!X.includes(K.key)),R=J.filter((K)=>!A.includes(K.key)).flatMap((K)=>{let H=K.type==="mutable_atom"?Jo(i,K):K,z=Mi(i,H);return[H,z]});if(i.logger.info("\uD83D\uDC41","atom",T.resourceAtoms.key,`${n} has a new perspective`,{oldKeys:A,newKeys:X,revealed:R,concealed:Y}),R.length>0)p?.emit(`reveal:${c}`,R);if(Y.length>0)p?.emit(`conceal:${c}`,Y)});x.push(F)}return x}function X8({socket:i,store:o=d.STORE}){return function n(p){let c=i,x=p.key,T=ix(mc,`socket::${c.id}`,o).userKeyOfSocket,m=Mi(o,T);if(!m)return o.logger.error("\u274C","continuity",x,`Tried to create a synchronizer for a socket (${c.id}) that is not connected to a user.`),()=>{};let f=ix(mc,m,o).socketKeyOfUser,F=Oo(o,f,`sync-continuity:${x}:${m}`,({newValue:H})=>{if(o.logger.info("\uD83D\uDC4B","continuity",x,`seeing ${m} on new socket ${H}`),H===null){o.logger.warn("\u274C","continuity",x,`User (${m}) is not connected to a socket, waiting for them to reappear.`);return}let z=t(o,em,H);c=Mi(o,z);for(let M of $)c?.emit(`tx-new:${x}`,M)}),$=Mi(o,nx,m),J=[],A=w8(o,p,m,c),X=v8(o,p,m,c);J.push(...A,...X);let Y=$8(o,p,m,i);c.off(`get:${x}`,Y),c.on(`get:${x}`,Y);let R=J8(o,p,m);c.off(`tx-run:${x}`,R),c.on(`tx-run:${x}`,R);let K=A8(o,p,m,$);return c?.on(`ack:${x}`,K),()=>{for(let H of J)H();c?.off(`ack:${x}`,K),c?.off(`get:${x}`,Y),c?.off(`tx-run:${x}`,R)}}}var IY=C1(n$(),1);var w=Symbol.for("drizzle:entityKind"),ed=Symbol.for("drizzle:hasOwnEntityKind");function Z(i,o){if(!i||typeof i!=="object")return!1;if(i instanceof o)return!0;if(!Object.prototype.hasOwnProperty.call(o,w))throw new Error(`Class "${o.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let n=Object.getPrototypeOf(i).constructor;if(n)while(n){if(w in n&&n[w]===o[w])return!0;n=Object.getPrototypeOf(n)}return!1}class Li{constructor(i,o){this.table=i,this.config=o,this.name=o.name,this.keyAsName=o.keyAsName,this.notNull=o.notNull,this.default=o.default,this.defaultFn=o.defaultFn,this.onUpdateFn=o.onUpdateFn,this.hasDefault=o.hasDefault,this.primary=o.primaryKey,this.isUnique=o.isUnique,this.uniqueName=o.uniqueName,this.uniqueType=o.uniqueType,this.dataType=o.dataType,this.columnType=o.columnType,this.generated=o.generated,this.generatedIdentity=o.generatedIdentity}static[w]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(i){return i}mapToDriverValue(i){return i}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class p${static[w]="ColumnBuilder";config;constructor(i,o,n){this.config={name:i,keyAsName:i==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:o,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(i){return this.config.default=i,this.config.hasDefault=!0,this}$defaultFn(i){return this.config.defaultFn=i,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(i){return this.config.onUpdateFn=i,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(i){if(this.config.name!=="")return;this.config.name=i}}var Dn=Symbol.for("drizzle:Name");class c${static[w]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(i,o){if(this.reference=()=>{let{name:n,columns:p,foreignColumns:c}=i();return{name:n,columns:p,foreignTable:c[0].table,foreignColumns:c}},o)this._onUpdate=o.onUpdate,this._onDelete=o.onDelete}onUpdate(i){return this._onUpdate=i===void 0?"no action":i,this}onDelete(i){return this._onDelete=i===void 0?"no action":i,this}build(i){return new A3(i,this)}}class A3{constructor(i,o){this.table=i,this.reference=o.reference,this.onUpdate=o._onUpdate,this.onDelete=o._onDelete}static[w]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:i,columns:o,foreignColumns:n}=this.reference(),p=o.map((T)=>T.name),c=n.map((T)=>T.name),x=[this.table[Dn],...p,n[0].table[Dn],...c];return i??`${x.join("_")}_fk`}}function R0(i,...o){return i(...o)}function v3(i,o){return`${i[Dn]}_${o.join("_")}_unique`}function w3(i,o,n){for(let p=o;p<i.length;p++){let c=i[p];if(c==="\\"){p++;continue}if(c==='"')return[i.slice(o,p).replace(/\\/g,""),p+1];if(n)continue;if(c===","||c==="}")return[i.slice(o,p).replace(/\\/g,""),p]}return[i.slice(o).replace(/\\/g,""),i.length]}function X3(i,o=0){let n=[],p=o,c=!1;while(p<i.length){let x=i[p];if(x===","){if(c||p===o)n.push("");c=!0,p++;continue}if(c=!1,x==="\\"){p+=2;continue}if(x==='"'){let[f,F]=w3(i,p+1,!0);n.push(f),p=F;continue}if(x==="}")return[n,p+1];if(x==="{"){let[f,F]=X3(i,p+1);n.push(f),p=F;continue}let[T,m]=w3(i,p,!1);n.push(T),p=m}return[n,p]}function W3(i){let[o]=X3(i,1);return o}function x$(i){return`{${i.map((o)=>{if(Array.isArray(o))return x$(o);if(typeof o==="string")return`"${o.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${o}`}).join(",")}}`}class j extends p${foreignKeyConfigs=[];static[w]="PgColumnBuilder";array(i){return new Y3(this.config.name,this,i)}references(i,o={}){return this.foreignKeyConfigs.push({ref:i,actions:o}),this}unique(i,o){return this.config.isUnique=!0,this.config.uniqueName=i,this.config.uniqueType=o?.nulls,this}generatedAlwaysAs(i){return this.config.generated={as:i,type:"always",mode:"stored"},this}buildForeignKeys(i,o){return this.foreignKeyConfigs.map(({ref:n,actions:p})=>{return R0((c,x)=>{let T=new c$(()=>{let m=c();return{columns:[i],foreignColumns:[m]}});if(x.onUpdate)T.onUpdate(x.onUpdate);if(x.onDelete)T.onDelete(x.onDelete);return T.build(o)},n,p)})}buildExtraConfigColumn(i){return new R3(i,this.config)}}class _ extends Li{constructor(i,o){if(!o.uniqueName)o.uniqueName=v3(i,[o.name]);super(i,o);this.table=i}static[w]="PgColumn"}class R3 extends _{static[w]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(i){return this.indexConfig.opClass=i,this}}class DT{static[w]="IndexedColumn";constructor(i,o,n,p){this.name=i,this.keyAsName=o,this.type=n,this.indexConfig=p}name;keyAsName;type;indexConfig}class Y3 extends j{static[w]="PgArrayBuilder";constructor(i,o,n){super(i,"array","PgArray");this.config.baseBuilder=o,this.config.size=n}build(i){let o=this.config.baseBuilder.build(i);return new T$(i,this.config,o)}}class T$ extends _{constructor(i,o,n,p){super(i,o);this.baseColumn=n,this.range=p,this.size=o.size}size;static[w]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(i){if(typeof i==="string")i=W3(i);return i.map((o)=>this.baseColumn.mapFromDriverValue(o))}mapToDriverValue(i,o=!1){let n=i.map((p)=>p===null?null:Z(this.baseColumn,T$)?this.baseColumn.mapToDriverValue(p,!0):this.baseColumn.mapToDriverValue(p));if(o)return n;return x$(n)}}var m$=Symbol.for("drizzle:isPgEnum");function G3(i){return!!i&&typeof i==="function"&&m$ in i&&i[m$]===!0}class K3 extends j{static[w]="PgEnumColumnBuilder";constructor(i,o){super(i,"string","PgEnumColumn");this.config.enum=o}build(i){return new H3(i,this.config)}}class H3 extends _{static[w]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(i,o){super(i,o);this.enum=o.enum}getSQLType(){return this.enum.enumName}}function Y0(i,o){return tM(i,o,void 0)}function tM(i,o,n){let p=Object.assign((c)=>new K3(c??"",p),{enumName:i,enumValues:o,schema:n,[m$]:!0});return p}class wo{static[w]="Subquery";constructor(i,o,n,p=!1){this._={brand:"Subquery",sql:i,selectedFields:o,alias:n,isWith:p}}}class IT extends wo{static[w]="WithSubquery"}var U3="0.41.0";var f$,F$,Ci={startActiveSpan(i,o){if(!f$)return o();if(!F$)F$=f$.trace.getTracer("drizzle-orm",U3);return R0((n,p)=>p.startActiveSpan(i,(c)=>{try{return o(c)}catch(x){throw c.setStatus({code:n.SpanStatusCode.ERROR,message:x instanceof Error?x.message:"Unknown error"}),x}finally{c.end()}}),f$,F$)}};var Ni=Symbol.for("drizzle:ViewBaseConfig");var G0=Symbol.for("drizzle:Schema"),K0=Symbol.for("drizzle:Columns"),Z3=Symbol.for("drizzle:ExtraConfigColumns"),$$=Symbol.for("drizzle:OriginalName"),J$=Symbol.for("drizzle:BaseName"),BT=Symbol.for("drizzle:IsAlias"),M3=Symbol.for("drizzle:ExtraConfigBuilder"),dM=Symbol.for("drizzle:IsDrizzleTable");class B{static[w]="Table";static Symbol={Name:Dn,Schema:G0,OriginalName:$$,Columns:K0,ExtraConfigColumns:Z3,BaseName:J$,IsAlias:BT,ExtraConfigBuilder:M3};[Dn];[$$];[G0];[K0];[Z3];[J$];[BT]=!1;[dM]=!0;[M3]=void 0;constructor(i,o,n){this[Dn]=this[$$]=i,this[G0]=o,this[J$]=n}}function Ro(i){return i[Dn]}function vc(i){return`${i[G0]??"public"}.${i[Dn]}`}function A$(i){return i!==null&&i!==void 0&&typeof i.getSQL==="function"}function rM(i){let o={sql:"",params:[]};for(let n of i)if(o.sql+=n.sql,o.params.push(...n.params),n.typings?.length){if(!o.typings)o.typings=[];o.typings.push(...n.typings)}return o}class Xo{static[w]="StringChunk";value;constructor(i){this.value=Array.isArray(i)?i:[i]}getSQL(){return new N([this])}}class N{constructor(i){this.queryChunks=i}static[w]="SQL";decoder=u3;shouldInlineParams=!1;append(i){return this.queryChunks.push(...i.queryChunks),this}toQuery(i){return Ci.startActiveSpan("drizzle.buildSQL",(o)=>{let n=this.buildQueryFromSourceParams(this.queryChunks,i);return o?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(i,o){let n=Object.assign({},o,{inlineParams:o.inlineParams||this.shouldInlineParams,paramStartIndex:o.paramStartIndex||{value:0}}),{casing:p,escapeName:c,escapeParam:x,prepareTyping:T,inlineParams:m,paramStartIndex:f}=n;return rM(i.map((F)=>{if(Z(F,Xo))return{sql:F.value.join(""),params:[]};if(Z(F,H0))return{sql:c(F.value),params:[]};if(F===void 0)return{sql:"",params:[]};if(Array.isArray(F)){let $=[new Xo("(")];for(let[J,A]of F.entries())if($.push(A),J<F.length-1)$.push(new Xo(", "));return $.push(new Xo(")")),this.buildQueryFromSourceParams($,n)}if(Z(F,N))return this.buildQueryFromSourceParams(F.queryChunks,{...n,inlineParams:m||F.shouldInlineParams});if(Z(F,B)){let $=F[B.Symbol.Schema],J=F[B.Symbol.Name];return{sql:$===void 0||F[BT]?c(J):c($)+"."+c(J),params:[]}}if(Z(F,Li)){let $=p.getColumnCasing(F);if(o.invokeSource==="indexes")return{sql:c($),params:[]};let J=F.table[B.Symbol.Schema];return{sql:F.table[BT]||J===void 0?c(F.table[B.Symbol.Name])+"."+c($):c(J)+"."+c(F.table[B.Symbol.Name])+"."+c($),params:[]}}if(Z(F,ro)){let $=F[Ni].schema,J=F[Ni].name;return{sql:$===void 0||F[Ni].isAlias?c(J):c($)+"."+c(J),params:[]}}if(Z(F,Tn)){if(Z(F.value,Ip))return{sql:x(f.value++,F),params:[F],typings:["none"]};let $=F.value===null?null:F.encoder.mapToDriverValue(F.value);if(Z($,N))return this.buildQueryFromSourceParams([$],n);if(m)return{sql:this.mapInlineParam($,n),params:[]};let J=["none"];if(T)J=[T(F.encoder)];return{sql:x(f.value++,$),params:[$],typings:J}}if(Z(F,Ip))return{sql:x(f.value++,F),params:[F],typings:["none"]};if(Z(F,N.Aliased)&&F.fieldAlias!==void 0)return{sql:c(F.fieldAlias),params:[]};if(Z(F,wo)){if(F._.isWith)return{sql:c(F._.alias),params:[]};return this.buildQueryFromSourceParams([new Xo("("),F._.sql,new Xo(") "),new H0(F._.alias)],n)}if(G3(F)){if(F.schema)return{sql:c(F.schema)+"."+c(F.enumName),params:[]};return{sql:c(F.enumName),params:[]}}if(A$(F)){if(F.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([F.getSQL()],n);return this.buildQueryFromSourceParams([new Xo("("),F.getSQL(),new Xo(")")],n)}if(m)return{sql:this.mapInlineParam(F,n),params:[]};return{sql:x(f.value++,F),params:[F],typings:["none"]}}))}mapInlineParam(i,{escapeString:o}){if(i===null)return"null";if(typeof i==="number"||typeof i==="boolean")return i.toString();if(typeof i==="string")return o(i);if(typeof i==="object"){let n=i.toString();if(n==="[object Object]")return o(JSON.stringify(i));return o(n)}throw new Error("Unexpected param value: "+i)}getSQL(){return this}as(i){if(i===void 0)return this;return new N.Aliased(this,i)}mapWith(i){return this.decoder=typeof i==="function"?{mapFromDriverValue:i}:i,this}inlineParams(){return this.shouldInlineParams=!0,this}if(i){return i?this:void 0}}class H0{constructor(i){this.value=i}static[w]="Name";brand;getSQL(){return new N([this])}}function z3(i){return typeof i==="object"&&i!==null&&"mapToDriverValue"in i&&typeof i.mapToDriverValue==="function"}var u3={mapFromDriverValue:(i)=>i},Q3={mapToDriverValue:(i)=>i},jr={...u3,...Q3};class Tn{constructor(i,o=Q3){this.value=i,this.encoder=o}static[w]="Param";brand;getSQL(){return new N([this])}}function W(i,...o){let n=[];if(o.length>0||i.length>0&&i[0]!=="")n.push(new Xo(i[0]));for(let[p,c]of o.entries())n.push(c,new Xo(i[p+1]));return new N(n)}((i)=>{function o(){return new N([])}i.empty=o;function n(f){return new N(f)}i.fromList=n;function p(f){return new N([new Xo(f)])}i.raw=p;function c(f,F){let $=[];for(let[J,A]of f.entries()){if(J>0&&F!==void 0)$.push(F);$.push(A)}return new N($)}i.join=c;function x(f){return new H0(f)}i.identifier=x;function T(f){return new Ip(f)}i.placeholder=T;function m(f,F){return new Tn(f,F)}i.param=m})(W||(W={}));((i)=>{class o{constructor(n,p){this.sql=n,this.fieldAlias=p}static[w]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new o(this.sql,this.fieldAlias)}}i.Aliased=o})(N||(N={}));class Ip{constructor(i){this.name=i}static[w]="Placeholder";getSQL(){return new N([this])}}function v$(i,o){return i.map((n)=>{if(Z(n,Ip)){if(!(n.name in o))throw new Error(`No value for placeholder "${n.name}" was provided`);return o[n.name]}if(Z(n,Tn)&&Z(n.value,Ip)){if(!(n.value.name in o))throw new Error(`No value for placeholder "${n.value.name}" was provided`);return n.encoder.mapToDriverValue(o[n.value.name])}return n})}var eM=Symbol.for("drizzle:IsDrizzleView");class ro{static[w]="View";[Ni];[eM]=!0;constructor({name:i,schema:o,selectedFields:n,query:p}){this[Ni]={name:i,originalName:i,schema:o,selectedFields:n,query:p,isExisting:!p,isAlias:!1}}getSQL(){return new N([this])}}Li.prototype.getSQL=function(){return new N([this])};B.prototype.getSQL=function(){return new N([this])};wo.prototype.getSQL=function(){return new N([this])};class Xx{constructor(i){this.table=i}static[w]="ColumnAliasProxyHandler";get(i,o){if(o==="table")return this.table;return i[o]}}class NT{constructor(i,o){this.alias=i,this.replaceOriginalName=o}static[w]="TableAliasProxyHandler";get(i,o){if(o===B.Symbol.IsAlias)return!0;if(o===B.Symbol.Name)return this.alias;if(this.replaceOriginalName&&o===B.Symbol.OriginalName)return this.alias;if(o===Ni)return{...i[Ni],name:this.alias,isAlias:!0};if(o===B.Symbol.Columns){let p=i[B.Symbol.Columns];if(!p)return p;let c={};return Object.keys(p).map((x)=>{c[x]=new Proxy(p[x],new Xx(new Proxy(i,this)))}),c}let n=i[o];if(Z(n,Li))return new Proxy(n,new Xx(new Proxy(i,this)));return n}}function U0(i,o){return new Proxy(i,new NT(o,!1))}function tn(i,o){return new Proxy(i,new Xx(new Proxy(i.table,new NT(o,!1))))}function w$(i,o){return new N.Aliased(bT(i.sql,o),i.fieldAlias)}function bT(i,o){return W.join(i.queryChunks.map((n)=>{if(Z(n,Li))return tn(n,o);if(Z(n,N))return bT(n,o);if(Z(n,N.Aliased))return w$(n,o);return n}))}class Z0 extends Error{static[w]="DrizzleError";constructor({message:i,cause:o}){super(i);this.name="DrizzleError",this.cause=o}}class X$ extends Z0{static[w]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function eo(i,o){if(z3(o)&&!A$(i)&&!Z(i,Tn)&&!Z(i,Ip)&&!Z(i,Li)&&!Z(i,B)&&!Z(i,ro))return new Tn(i,o);return i}var dn=(i,o)=>{return W`${i} = ${eo(o,i)}`},V3=(i,o)=>{return W`${i} <> ${eo(o,i)}`};function wc(...i){let o=i.filter((n)=>n!==void 0);if(o.length===0)return;if(o.length===1)return new N(o);return new N([new Xo("("),W.join(o,new Xo(" and ")),new Xo(")")])}function S3(...i){let o=i.filter((n)=>n!==void 0);if(o.length===0)return;if(o.length===1)return new N(o);return new N([new Xo("("),W.join(o,new Xo(" or ")),new Xo(")")])}function E3(i){return W`not ${i}`}var M0=(i,o)=>{return W`${i} > ${eo(o,i)}`},O3=(i,o)=>{return W`${i} >= ${eo(o,i)}`},_3=(i,o)=>{return W`${i} < ${eo(o,i)}`},L3=(i,o)=>{return W`${i} <= ${eo(o,i)}`};function C3(i,o){if(Array.isArray(o)){if(o.length===0)return W`false`;return W`${i} in ${o.map((n)=>eo(n,i))}`}return W`${i} in ${eo(o,i)}`}function y3(i,o){if(Array.isArray(o)){if(o.length===0)return W`true`;return W`${i} not in ${o.map((n)=>eo(n,i))}`}return W`${i} not in ${eo(o,i)}`}function D3(i){return W`${i} is null`}function I3(i){return W`${i} is not null`}function B3(i){return W`exists ${i}`}function N3(i){return W`not exists ${i}`}function b3(i,o,n){return W`${i} between ${eo(o,i)} and ${eo(n,i)}`}function j3(i,o,n){return W`${i} not between ${eo(o,i)} and ${eo(n,i)}`}function P3(i,o){return W`${i} like ${o}`}function a3(i,o){return W`${i} not like ${o}`}function l3(i,o){return W`${i} ilike ${o}`}function q3(i,o){return W`${i} not ilike ${o}`}function k3(i){return W`${i} asc`}function h3(i){return W`${i} desc`}class g3{static[w]="ConsoleLogWriter";write(i){console.log(i)}}class W${static[w]="DefaultLogger";writer;constructor(i){this.writer=i?.writer??new g3}logQuery(i,o){let n=o.map((c)=>{try{return JSON.stringify(c)}catch{return String(c)}}),p=n.length?` -- params: [${n.join(", ")}]`:"";this.writer.write(`Query: ${i}${p}`)}}class R${static[w]="NoopLogger";logQuery(){}}class jo{static[w]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(i){return this.then(void 0,i)}finally(i){return this.then((o)=>{return i?.(),o},(o)=>{throw i?.(),o})}then(i,o){return this.execute().then(i,o)}}function s3(i,o,n){let p={},c=i.reduce((x,{path:T,field:m},f)=>{let F;if(Z(m,Li))F=m;else if(Z(m,N))F=m.decoder;else F=m.sql.decoder;let $=x;for(let[J,A]of T.entries())if(J<T.length-1){if(!(A in $))$[A]={};$=$[A]}else{let X=o[f],Y=$[A]=X===null?null:F.mapFromDriverValue(X);if(n&&Z(m,Li)&&T.length===2){let R=T[0];if(!(R in p))p[R]=Y===null?Ro(m.table):!1;else if(typeof p[R]==="string"&&p[R]!==Ro(m.table))p[R]=!1}}return x},{});if(n&&Object.keys(p).length>0){for(let[x,T]of Object.entries(p))if(typeof T==="string"&&!n[T])c[x]=null}return c}function Un(i,o){return Object.entries(i).reduce((n,[p,c])=>{if(typeof p!=="string")return n;let x=o?[...o,p]:[p];if(Z(c,Li)||Z(c,N)||Z(c,N.Aliased))n.push({path:x,field:c});else if(Z(c,B))n.push(...Un(c[B.Symbol.Columns],x));else n.push(...Un(c,x));return n},[])}function jT(i,o){let n=Object.keys(i),p=Object.keys(o);if(n.length!==p.length)return!1;for(let[c,x]of n.entries())if(x!==p[c])return!1;return!0}function z0(i,o){let n=Object.entries(o).filter(([,p])=>p!==void 0).map(([p,c])=>{if(Z(c,N)||Z(c,Li))return[p,c];else return[p,new Tn(c,i[B.Symbol.Columns][p])]});if(n.length===0)throw new Error("No values to set");return Object.fromEntries(n)}function t3(i,o){for(let n of o)for(let p of Object.getOwnPropertyNames(n.prototype)){if(p==="constructor")continue;Object.defineProperty(i.prototype,p,Object.getOwnPropertyDescriptor(n.prototype,p)||Object.create(null))}}function d3(i){return i[B.Symbol.Columns]}function Ap(i){return Z(i,wo)?i._.alias:Z(i,ro)?i[Ni].name:Z(i,N)?void 0:i[B.Symbol.IsAlias]?i[B.Symbol.Name]:i[B.Symbol.BaseName]}function vi(i,o){return{name:typeof i==="string"&&i.length>0?i:"",config:typeof i==="object"?i:o}}function r3(i){if(typeof i!=="object"||i===null)return!1;if(i.constructor.name!=="Object")return!1;if("logger"in i){let o=typeof i.logger;if(o!=="boolean"&&(o!=="object"||typeof i.logger.logQuery!=="function")&&o!=="undefined")return!1;return!0}if("schema"in i){let o=typeof i.schema;if(o!=="object"&&o!=="undefined")return!1;return!0}if("casing"in i){let o=typeof i.casing;if(o!=="string"&&o!=="undefined")return!1;return!0}if("mode"in i){if(i.mode!=="default"||i.mode!=="planetscale"||i.mode!==void 0)return!1;return!0}if("connection"in i){let o=typeof i.connection;if(o!=="string"&&o!=="object"&&o!=="undefined")return!1;return!0}if("client"in i){let o=typeof i.client;if(o!=="object"&&o!=="function"&&o!=="undefined")return!1;return!0}if(Object.keys(i).length===0)return!0;return!1}class Bp extends j{static[w]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(i){if(i){let{name:o,...n}=i;this.config.generatedIdentity={type:"always",sequenceName:o,sequenceOptions:n}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(i){if(i){let{name:o,...n}=i;this.config.generatedIdentity={type:"byDefault",sequenceName:o,sequenceOptions:n}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}class e3 extends Bp{static[w]="PgBigInt53Builder";constructor(i){super(i,"number","PgBigInt53")}build(i){return new iX(i,this.config)}}class iX extends _{static[w]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(i){if(typeof i==="number")return i;return Number(i)}}class oX extends Bp{static[w]="PgBigInt64Builder";constructor(i){super(i,"bigint","PgBigInt64")}build(i){return new nX(i,this.config)}}class nX extends _{static[w]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(i){return BigInt(i)}}function pX(i,o){let{name:n,config:p}=vi(i,o);if(p.mode==="number")return new e3(n);return new oX(n)}class cX extends j{static[w]="PgBigSerial53Builder";constructor(i){super(i,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(i){return new xX(i,this.config)}}class xX extends _{static[w]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(i){if(typeof i==="number")return i;return Number(i)}}class TX extends j{static[w]="PgBigSerial64Builder";constructor(i){super(i,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(i){return new mX(i,this.config)}}class mX extends _{static[w]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(i){return BigInt(i)}}function fX(i,o){let{name:n,config:p}=vi(i,o);if(p.mode==="number")return new cX(n);return new TX(n)}class FX extends j{static[w]="PgBooleanBuilder";constructor(i){super(i,"boolean","PgBoolean")}build(i){return new $X(i,this.config)}}class $X extends _{static[w]="PgBoolean";getSQLType(){return"boolean"}}function PT(i){return new FX(i??"")}class JX extends j{static[w]="PgCharBuilder";constructor(i,o){super(i,"string","PgChar");this.config.length=o.length,this.config.enumValues=o.enum}build(i){return new AX(i,this.config)}}class AX extends _{static[w]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function vX(i,o={}){let{name:n,config:p}=vi(i,o);return new JX(n,p)}class wX extends j{static[w]="PgCidrBuilder";constructor(i){super(i,"string","PgCidr")}build(i){return new XX(i,this.config)}}class XX extends _{static[w]="PgCidr";getSQLType(){return"cidr"}}function WX(i){return new wX(i??"")}class RX extends j{static[w]="PgCustomColumnBuilder";constructor(i,o,n){super(i,"custom","PgCustomColumn");this.config.fieldConfig=o,this.config.customTypeParams=n}build(i){return new YX(i,this.config)}}class YX extends _{static[w]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(i,o){super(i,o);this.sqlName=o.customTypeParams.dataType(o.fieldConfig),this.mapTo=o.customTypeParams.toDriver,this.mapFrom=o.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(i){return typeof this.mapFrom==="function"?this.mapFrom(i):i}mapToDriverValue(i){return typeof this.mapTo==="function"?this.mapTo(i):i}}function GX(i){return(o,n)=>{let{name:p,config:c}=vi(o,n);return new RX(p,c,i)}}class vp extends j{static[w]="PgDateColumnBaseBuilder";defaultNow(){return this.default(W`now()`)}}class KX extends vp{static[w]="PgDateBuilder";constructor(i){super(i,"date","PgDate")}build(i){return new u0(i,this.config)}}class u0 extends _{static[w]="PgDate";getSQLType(){return"date"}mapFromDriverValue(i){return new Date(i)}mapToDriverValue(i){return i.toISOString()}}class HX extends vp{static[w]="PgDateStringBuilder";constructor(i){super(i,"string","PgDateString")}build(i){return new Q0(i,this.config)}}class Q0 extends _{static[w]="PgDateString";getSQLType(){return"date"}}function UX(i,o){let{name:n,config:p}=vi(i,o);if(p?.mode==="date")return new KX(n);return new HX(n)}class ZX extends j{static[w]="PgDoublePrecisionBuilder";constructor(i){super(i,"number","PgDoublePrecision")}build(i){return new MX(i,this.config)}}class MX extends _{static[w]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(i){if(typeof i==="string")return Number.parseFloat(i);return i}}function zX(i){return new ZX(i??"")}class uX extends j{static[w]="PgInetBuilder";constructor(i){super(i,"string","PgInet")}build(i){return new QX(i,this.config)}}class QX extends _{static[w]="PgInet";getSQLType(){return"inet"}}function VX(i){return new uX(i??"")}class SX extends Bp{static[w]="PgIntegerBuilder";constructor(i){super(i,"number","PgInteger")}build(i){return new EX(i,this.config)}}class EX extends _{static[w]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(i){if(typeof i==="string")return Number.parseInt(i);return i}}function V0(i){return new SX(i??"")}class OX extends j{static[w]="PgIntervalBuilder";constructor(i,o){super(i,"string","PgInterval");this.config.intervalConfig=o}build(i){return new _X(i,this.config)}}class _X extends _{static[w]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let i=this.fields?` ${this.fields}`:"",o=this.precision?`(${this.precision})`:"";return`interval${i}${o}`}}function LX(i,o={}){let{name:n,config:p}=vi(i,o);return new OX(n,p)}class CX extends j{static[w]="PgJsonBuilder";constructor(i){super(i,"json","PgJson")}build(i){return new S0(i,this.config)}}class S0 extends _{static[w]="PgJson";constructor(i,o){super(i,o)}getSQLType(){return"json"}mapToDriverValue(i){return JSON.stringify(i)}mapFromDriverValue(i){if(typeof i==="string")try{return JSON.parse(i)}catch{return i}return i}}function yX(i){return new CX(i??"")}class DX extends j{static[w]="PgJsonbBuilder";constructor(i){super(i,"json","PgJsonb")}build(i){return new E0(i,this.config)}}class E0 extends _{static[w]="PgJsonb";constructor(i,o){super(i,o)}getSQLType(){return"jsonb"}mapToDriverValue(i){return JSON.stringify(i)}mapFromDriverValue(i){if(typeof i==="string")try{return JSON.parse(i)}catch{return i}return i}}function IX(i){return new DX(i??"")}class BX extends j{static[w]="PgLineBuilder";constructor(i){super(i,"array","PgLine")}build(i){return new NX(i,this.config)}}class NX extends _{static[w]="PgLine";getSQLType(){return"line"}mapFromDriverValue(i){let[o,n,p]=i.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(n),Number.parseFloat(p)]}mapToDriverValue(i){return`{${i[0]},${i[1]},${i[2]}}`}}class bX extends j{static[w]="PgLineABCBuilder";constructor(i){super(i,"json","PgLineABC")}build(i){return new jX(i,this.config)}}class jX extends _{static[w]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(i){let[o,n,p]=i.slice(1,-1).split(",");return{a:Number.parseFloat(o),b:Number.parseFloat(n),c:Number.parseFloat(p)}}mapToDriverValue(i){return`{${i.a},${i.b},${i.c}}`}}function PX(i,o){let{name:n,config:p}=vi(i,o);if(!p?.mode||p.mode==="tuple")return new BX(n);return new bX(n)}class aX extends j{static[w]="PgMacaddrBuilder";constructor(i){super(i,"string","PgMacaddr")}build(i){return new lX(i,this.config)}}class lX extends _{static[w]="PgMacaddr";getSQLType(){return"macaddr"}}function qX(i){return new aX(i??"")}class kX extends j{static[w]="PgMacaddr8Builder";constructor(i){super(i,"string","PgMacaddr8")}build(i){return new hX(i,this.config)}}class hX extends _{static[w]="PgMacaddr8";getSQLType(){return"macaddr8"}}function gX(i){return new kX(i??"")}class sX extends j{static[w]="PgNumericBuilder";constructor(i,o,n){super(i,"string","PgNumeric");this.config.precision=o,this.config.scale=n}build(i){return new O0(i,this.config)}}class O0 extends _{static[w]="PgNumeric";precision;scale;constructor(i,o){super(i,o);this.precision=o.precision,this.scale=o.scale}mapFromDriverValue(i){if(typeof i==="string")return i;return String(i)}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class tX extends j{static[w]="PgNumericNumberBuilder";constructor(i,o,n){super(i,"number","PgNumericNumber");this.config.precision=o,this.config.scale=n}build(i){return new dX(i,this.config)}}class dX extends _{static[w]="PgNumericNumber";precision;scale;constructor(i,o){super(i,o);this.precision=o.precision,this.scale=o.scale}mapFromDriverValue(i){if(typeof i==="number")return i;return Number(i)}mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}class rX extends j{static[w]="PgNumericBigIntBuilder";constructor(i,o,n){super(i,"bigint","PgNumericBigInt");this.config.precision=o,this.config.scale=n}build(i){return new eX(i,this.config)}}class eX extends _{static[w]="PgNumericBigInt";precision;scale;constructor(i,o){super(i,o);this.precision=o.precision,this.scale=o.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function i7(i,o){let{name:n,config:p}=vi(i,o),c=p?.mode;return c==="number"?new tX(n,p?.precision,p?.scale):c==="bigint"?new rX(n,p?.precision,p?.scale):new sX(n,p?.precision,p?.scale)}class o7 extends j{static[w]="PgPointTupleBuilder";constructor(i){super(i,"array","PgPointTuple")}build(i){return new n7(i,this.config)}}class n7 extends _{static[w]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(i){if(typeof i==="string"){let[o,n]=i.slice(1,-1).split(",");return[Number.parseFloat(o),Number.parseFloat(n)]}return[i.x,i.y]}mapToDriverValue(i){return`(${i[0]},${i[1]})`}}class p7 extends j{static[w]="PgPointObjectBuilder";constructor(i){super(i,"json","PgPointObject")}build(i){return new c7(i,this.config)}}class c7 extends _{static[w]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(i){if(typeof i==="string"){let[o,n]=i.slice(1,-1).split(",");return{x:Number.parseFloat(o),y:Number.parseFloat(n)}}return i}mapToDriverValue(i){return`(${i.x},${i.y})`}}function x7(i,o){let{name:n,config:p}=vi(i,o);if(!p?.mode||p.mode==="tuple")return new o7(n);return new p7(n)}function iz(i){let o=[];for(let n=0;n<i.length;n+=2)o.push(Number.parseInt(i.slice(n,n+2),16));return new Uint8Array(o)}function T7(i,o){let n=new ArrayBuffer(8),p=new DataView(n);for(let c=0;c<8;c++)p.setUint8(c,i[o+c]);return p.getFloat64(0,!0)}function Y$(i){let o=iz(i),n=0,p=o[n];n+=1;let c=new DataView(o.buffer),x=c.getUint32(n,p===1);n+=4;let T;if(x&536870912)T=c.getUint32(n,p===1),n+=4;if((x&65535)===1){let m=T7(o,n);n+=8;let f=T7(o,n);return n+=8,[m,f]}throw new Error("Unsupported geometry type")}class m7 extends j{static[w]="PgGeometryBuilder";constructor(i){super(i,"array","PgGeometry")}build(i){return new f7(i,this.config)}}class f7 extends _{static[w]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(i){return Y$(i)}mapToDriverValue(i){return`point(${i[0]} ${i[1]})`}}class F7 extends j{static[w]="PgGeometryObjectBuilder";constructor(i){super(i,"json","PgGeometryObject")}build(i){return new $7(i,this.config)}}class $7 extends _{static[w]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(i){let o=Y$(i);return{x:o[0],y:o[1]}}mapToDriverValue(i){return`point(${i.x} ${i.y})`}}function J7(i,o){let{name:n,config:p}=vi(i,o);if(!p?.mode||p.mode==="tuple")return new m7(n);return new F7(n)}class A7 extends j{static[w]="PgRealBuilder";constructor(i,o){super(i,"number","PgReal");this.config.length=o}build(i){return new v7(i,this.config)}}class v7 extends _{static[w]="PgReal";constructor(i,o){super(i,o)}getSQLType(){return"real"}mapFromDriverValue=(i)=>{if(typeof i==="string")return Number.parseFloat(i);return i}}function w7(i){return new A7(i??"")}class X7 extends j{static[w]="PgSerialBuilder";constructor(i){super(i,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(i){return new W7(i,this.config)}}class W7 extends _{static[w]="PgSerial";getSQLType(){return"serial"}}function R7(i){return new X7(i??"")}class Y7 extends Bp{static[w]="PgSmallIntBuilder";constructor(i){super(i,"number","PgSmallInt")}build(i){return new G7(i,this.config)}}class G7 extends _{static[w]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(i)=>{if(typeof i==="string")return Number(i);return i}}function K7(i){return new Y7(i??"")}class H7 extends j{static[w]="PgSmallSerialBuilder";constructor(i){super(i,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(i){return new U7(i,this.config)}}class U7 extends _{static[w]="PgSmallSerial";getSQLType(){return"smallserial"}}function Z7(i){return new H7(i??"")}class M7 extends j{static[w]="PgTextBuilder";constructor(i,o){super(i,"string","PgText");this.config.enumValues=o.enum}build(i){return new z7(i,this.config)}}class z7 extends _{static[w]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function u7(i,o={}){let{name:n,config:p}=vi(i,o);return new M7(n,p)}class Q7 extends vp{constructor(i,o,n){super(i,"string","PgTime");this.withTimezone=o,this.precision=n,this.config.withTimezone=o,this.config.precision=n}static[w]="PgTimeBuilder";build(i){return new _0(i,this.config)}}class _0 extends _{static[w]="PgTime";withTimezone;precision;constructor(i,o){super(i,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function V7(i,o={}){let{name:n,config:p}=vi(i,o);return new Q7(n,p.withTimezone??!1,p.precision)}class S7 extends vp{static[w]="PgTimestampBuilder";constructor(i,o,n){super(i,"date","PgTimestamp");this.config.withTimezone=o,this.config.precision=n}build(i){return new L0(i,this.config)}}class L0 extends _{static[w]="PgTimestamp";withTimezone;precision;constructor(i,o){super(i,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(i)=>{return new Date(this.withTimezone?i:i+"+0000")};mapToDriverValue=(i)=>{return i.toISOString()}}class E7 extends vp{static[w]="PgTimestampStringBuilder";constructor(i,o,n){super(i,"string","PgTimestampString");this.config.withTimezone=o,this.config.precision=n}build(i){return new C0(i,this.config)}}class C0 extends _{static[w]="PgTimestampString";withTimezone;precision;constructor(i,o){super(i,o);this.withTimezone=o.withTimezone,this.precision=o.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function In(i,o={}){let{name:n,config:p}=vi(i,o);if(p?.mode==="string")return new E7(n,p.withTimezone??!1,p.precision);return new S7(n,p?.withTimezone??!1,p?.precision)}class O7 extends j{static[w]="PgUUIDBuilder";constructor(i){super(i,"string","PgUUID")}defaultRandom(){return this.default(W`gen_random_uuid()`)}build(i){return new y0(i,this.config)}}class y0 extends _{static[w]="PgUUID";getSQLType(){return"uuid"}}function mn(i){return new O7(i??"")}class _7 extends j{static[w]="PgVarcharBuilder";constructor(i,o){super(i,"string","PgVarchar");this.config.length=o.length,this.config.enumValues=o.enum}build(i){return new L7(i,this.config)}}class L7 extends _{static[w]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function Zo(i,o={}){let{name:n,config:p}=vi(i,o);return new _7(n,p)}class C7 extends j{static[w]="PgBinaryVectorBuilder";constructor(i,o){super(i,"string","PgBinaryVector");this.config.dimensions=o.dimensions}build(i){return new y7(i,this.config)}}class y7 extends _{static[w]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function D7(i,o){let{name:n,config:p}=vi(i,o);return new C7(n,p)}class I7 extends j{static[w]="PgHalfVectorBuilder";constructor(i,o){super(i,"array","PgHalfVector");this.config.dimensions=o.dimensions}build(i){return new B7(i,this.config)}}class B7 extends _{static[w]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(i){return JSON.stringify(i)}mapFromDriverValue(i){return i.slice(1,-1).split(",").map((o)=>Number.parseFloat(o))}}function N7(i,o){let{name:n,config:p}=vi(i,o);return new I7(n,p)}class b7 extends j{static[w]="PgSparseVectorBuilder";constructor(i,o){super(i,"string","PgSparseVector");this.config.dimensions=o.dimensions}build(i){return new j7(i,this.config)}}class j7 extends _{static[w]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function P7(i,o){let{name:n,config:p}=vi(i,o);return new b7(n,p)}class a7 extends j{static[w]="PgVectorBuilder";constructor(i,o){super(i,"array","PgVector");this.config.dimensions=o.dimensions}build(i){return new l7(i,this.config)}}class l7 extends _{static[w]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(i){return JSON.stringify(i)}mapFromDriverValue(i){return i.slice(1,-1).split(",").map((o)=>Number.parseFloat(o))}}function q7(i,o){let{name:n,config:p}=vi(i,o);return new a7(n,p)}function k7(){return{bigint:pX,bigserial:fX,boolean:PT,char:vX,cidr:WX,customType:GX,date:UX,doublePrecision:zX,inet:VX,integer:V0,interval:LX,json:yX,jsonb:IX,line:PX,macaddr:qX,macaddr8:gX,numeric:i7,point:x7,geometry:J7,real:w7,serial:R7,smallint:K7,smallserial:Z7,text:u7,time:V7,timestamp:In,uuid:mn,varchar:Zo,bit:D7,halfvec:N7,sparsevec:P7,vector:q7}}var G$=Symbol.for("drizzle:PgInlineForeignKeys"),h7=Symbol.for("drizzle:EnableRLS");class Mo extends B{static[w]="PgTable";static Symbol=Object.assign({},B.Symbol,{InlineForeignKeys:G$,EnableRLS:h7});[G$]=[];[h7]=!1;[B.Symbol.ExtraConfigBuilder]=void 0;[B.Symbol.ExtraConfigColumns]={}}function oz(i,o,n,p,c=i){let x=new Mo(i,p,c),T=typeof o==="function"?o(k7()):o,m=Object.fromEntries(Object.entries(T).map(([$,J])=>{let A=J;A.setName($);let X=A.build(x);return x[G$].push(...A.buildForeignKeys(X,x)),[$,X]})),f=Object.fromEntries(Object.entries(T).map(([$,J])=>{let A=J;A.setName($);let X=A.buildExtraConfigColumn(x);return[$,X]})),F=Object.assign(x,m);if(F[B.Symbol.Columns]=m,F[B.Symbol.ExtraConfigColumns]=f,n)F[Mo.Symbol.ExtraConfigBuilder]=n;return Object.assign(F,{enableRLS:()=>{return F[Mo.Symbol.EnableRLS]=!0,F}})}var Np=(i,o,n)=>{return oz(i,o,n,void 0)};function g7(...i){if(i[0].columns)return new aT(i[0].columns,i[0].name);return new aT(i)}class aT{static[w]="PgPrimaryKeyBuilder";columns;name;constructor(i,o){this.columns=i,this.name=o}build(i){return new s7(i,this.columns,this.name)}}class s7{constructor(i,o,n){this.table=i,this.columns=o,this.name=n}static[w]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Mo.Symbol.Name]}_${this.columns.map((i)=>i.name).join("_")}_pk`}}class K${constructor(i,o,n){this.sourceTable=i,this.referencedTable=o,this.relationName=n,this.referencedTableName=o[B.Symbol.Name]}static[w]="Relation";referencedTableName;fieldName}class t7{constructor(i,o){this.table=i,this.config=o}static[w]="Relations"}class bp extends K${constructor(i,o,n,p){super(i,o,n?.relationName);this.config=n,this.isNullable=p}static[w]="One";withFieldName(i){let o=new bp(this.sourceTable,this.referencedTable,this.config,this.isNullable);return o.fieldName=i,o}}class lT extends K${constructor(i,o,n){super(i,o,n?.relationName);this.config=n}static[w]="Many";withFieldName(i){let o=new lT(this.sourceTable,this.referencedTable,this.config);return o.fieldName=i,o}}function d7(){return{and:wc,between:b3,eq:dn,exists:B3,gt:M0,gte:O3,ilike:l3,inArray:C3,isNull:D3,isNotNull:I3,like:P3,lt:_3,lte:L3,ne:V3,not:E3,notBetween:j3,notExists:N3,notLike:a3,notIlike:q3,notInArray:y3,or:S3,sql:W}}function r7(){return{sql:W,asc:k3,desc:h3}}function e7(i,o){if(Object.keys(i).length===1&&"default"in i&&!Z(i.default,B))i=i.default;let n={},p={},c={};for(let[x,T]of Object.entries(i))if(Z(T,B)){let m=vc(T),f=p[m];n[m]=x,c[x]={tsName:x,dbName:T[B.Symbol.Name],schema:T[B.Symbol.Schema],columns:T[B.Symbol.Columns],relations:f?.relations??{},primaryKey:f?.primaryKey??[]};for(let $ of Object.values(T[B.Symbol.Columns]))if($.primary)c[x].primaryKey.push($);let F=T[B.Symbol.ExtraConfigBuilder]?.(T[B.Symbol.ExtraConfigColumns]);if(F){for(let $ of Object.values(F))if(Z($,aT))c[x].primaryKey.push(...$.columns)}}else if(Z(T,t7)){let m=vc(T.table),f=n[m],F=T.config(o(T.table)),$;for(let[J,A]of Object.entries(F))if(f){let X=c[f];if(X.relations[J]=A,$)X.primaryKey.push(...$)}else{if(!(m in p))p[m]={relations:{},primaryKey:$};p[m].relations[J]=A}}return{tables:c,tableNamesMap:n}}function nz(i){return function o(n,p){return new bp(i,n,p,p?.fields.reduce((c,x)=>c&&x.notNull,!0)??!1)}}function pz(i){return function o(n,p){return new lT(i,n,p)}}function iW(i,o,n){if(Z(n,bp)&&n.config)return{fields:n.config.fields,references:n.config.references};let p=o[vc(n.referencedTable)];if(!p)throw new Error(`Table "${n.referencedTable[B.Symbol.Name]}" not found in schema`);let c=i[p];if(!c)throw new Error(`Table "${p}" not found in schema`);let x=n.sourceTable,T=o[vc(x)];if(!T)throw new Error(`Table "${x[B.Symbol.Name]}" not found in schema`);let m=[];for(let f of Object.values(c.relations))if(n.relationName&&n!==f&&f.relationName===n.relationName||!n.relationName&&f.referencedTable===n.sourceTable)m.push(f);if(m.length>1)throw n.relationName?new Error(`There are multiple relations with name "${n.relationName}" in table "${p}"`):new Error(`There are multiple relations between "${p}" and "${n.sourceTable[B.Symbol.Name]}". Please specify relation name`);if(m[0]&&Z(m[0],bp)&&m[0].config)return{fields:m[0].config.references,references:m[0].config.fields};throw new Error(`There is not enough information to infer relation "${T}.${n.fieldName}"`)}function oW(i){return{one:nz(i),many:pz(i)}}function D0(i,o,n,p,c=(x)=>x){let x={};for(let[T,m]of p.entries())if(m.isJson){let f=o.relations[m.tsKey],F=n[T],$=typeof F==="string"?JSON.parse(F):F;x[m.tsKey]=Z(f,bp)?$&&D0(i,i[m.relationTableTsKey],$,m.selection,c):$.map((J)=>D0(i,i[m.relationTableTsKey],J,m.selection,c))}else{let f=c(n[T]),F=m.field,$;if(Z(F,Li))$=F;else if(Z(F,N))$=F.decoder;else $=F.sql.decoder;x[m.tsKey]=f===null?null:$.mapFromDriverValue(f)}return x}var aR=C1(PR(),1),{Server:lR,Namespace:Ppi,Socket:api}=aR.default;import{readFileSync as hR}from"fs";import{resolve as XJ}from"path";function eS(i,o){let n={},p=[];for(let c in i){let x=i[c],T=o[c],m=x["~standard"].validate(T);if(m instanceof Promise)throw new Error(`Validation must be synchronous, but ${c} returned a Promise.`);if(m.issues){p.push(...m.issues.map((f)=>({...f,path:[c,...f.path??[]]})));continue}n[c]=m.value}if(p.length)return{issues:p};return{value:n}}function qR(i){let o=i.runtimeEnvStrict??i.runtimeEnv??process.env;if(i.emptyStringAsUndefined??!1){for(let[z,b]of Object.entries(o))if(b==="")delete o[z]}if(!!i.skipValidation)return o;let c=typeof i.client==="object"?i.client:{},x=typeof i.server==="object"?i.server:{},T=typeof i.shared==="object"?i.shared:{},m=i.isServer??(typeof window==="undefined"||("Deno"in window)),f=m?{...x,...T,...c}:{...c,...T},F=eS(f,o),$=i.onValidationError??((z)=>{throw console.error("\u274C Invalid environment variables:",z),new Error("Invalid environment variables")}),J=i.onInvalidAccess??(()=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(F.issues)return $(F.issues);let A=(z)=>{if(!i.clientPrefix)return!0;return!z.startsWith(i.clientPrefix)&&!(z in T)},X=(z)=>{return m||!A(z)},Y=(z)=>{return z==="__esModule"||z==="$$typeof"},R=(i.extends??[]).reduce((z,b)=>{return Object.assign(z,b)},{}),K=Object.assign(F.value,R);return new Proxy(K,{get(z,b){if(typeof b!=="string")return;if(Y(b))return;if(!X(b))return J(b);return Reflect.get(z,b)}})}var iE="__vite_start_time"in globalThis,oE=typeof window!=="undefined",gpi="vitest"in globalThis,Rp=ri("string"),kR=ri('"true" | "false" | undefined'),oo=qR({isServer:!iE&&!oE,server:{CI:ri("string | undefined").pipe(Boolean),POSTGRES_USER:Rp,POSTGRES_PASSWORD:Rp,POSTGRES_DATABASE:Rp,POSTGRES_HOST:Rp,POSTGRES_PORT:Rp.pipe((i)=>Number.parseInt(i,10)),BACKEND_PORT:Rp.pipe((i)=>Number.parseInt(i,10)),RUN_WORKERS_FROM_SOURCE:kR.pipe((i)=>i==="true"),FRONTEND_PORT:Rp.pipe((i)=>Number.parseInt(i,10)),FRONTEND_ORIGINS:Rp.pipe.try((i)=>JSON.parse(i),ri("string[]")),OPENAI_API_KEY:ri("string | undefined")},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Rp,VITE_USE_SELF_SIGNED_CERTIFICATE:kR.pipe((i)=>i==="true")},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var gR=XJ(import.meta.dirname,"../dev"),WJ=oo.VITE_USE_SELF_SIGNED_CERTIFICATE?{cert:hR(XJ(gR,"./cert.pem"),"utf-8"),key:hR(XJ(gR,"./key.pem"),"utf-8")}:void 0;var qp=new XF,xi=oo.VITE_USE_SELF_SIGNED_CERTIFICATE?console:qp.logger;d.STORE.loggers[0]=new pc("warn",void 0,xi);if(xi!==console)Object.assign(console,xi,{log:xi.info});import{spawn as nE}from"child_process";import{resolve as pE}from"path";function RJ(i,o,n=i.logger){let p=oo.RUN_WORKERS_FROM_SOURCE?"ts":"js",c=o.endsWith(".bun")?"bun":"node",T=[pE(import.meta.dir,`${o}.${p}`)];if(c==="node"&&p==="ts")T.push("--experimental-strip-types");let m=nE(c,T);return new MT(m,o,n)}var sR=C1(n$(),1);var cE=604800000,F1=(()=>{let{__userSessionMap:i}=globalThis;if(!i){i=globalThis.__userSessionMap=new Map;let o=new sR.CronJob("00 00 03 * * *",()=>{for(let[n,p]of i.entries()){let c=Date.now();for(let[x,T]of p.entries())if(c-T>cE)p.delete(x);if(p.size===0)i.delete(n)}});o.start(),process.on("exit",()=>{o.stop(),xi.info("\uD83D\uDEEC autoExpiry stopped")})}return i})();import tE from"path";import VE from"os";import SE from"fs";var $1=new Map,YJ=new Map,GJ=Symbol("OriginError"),Ex={};class un extends Promise{constructor(i,o,n,p,c={}){let x,T;super((m,f)=>{x=m,T=f});this.tagged=Array.isArray(i.raw),this.strings=i,this.args=o,this.handler=n,this.canceller=p,this.options=c,this.state=null,this.statement=null,this.resolve=(m)=>(this.active=!1,x(m)),this.reject=(m)=>(this.active=!1,T(m)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[GJ]=this.handler.debug?new Error:this.tagged&&xE(this.strings)}get origin(){return(this.handler.debug?this[GJ].stack:this.tagged&&YJ.has(this.strings)?YJ.get(this.strings):YJ.set(this.strings,this[GJ].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(i=1,o){if(this.options.simple=!1,typeof i==="function")o=i,i=1;if(this.cursorRows=i,typeof o==="function")return this.cursorFn=o,this;let n;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};n&&n();let p=new Promise((c,x)=>{this.cursorFn=(T)=>{return c({value:T,done:!1}),new Promise((m)=>n=m)},this.resolve=()=>(this.active=!1,c({done:!0})),this.reject=(T)=>(this.active=!1,x(T))});return this.execute(),p},return(){return n&&n(Ex),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(i){return this.forEachFn=i,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function xE(i){if($1.has(i))return $1.get(i);let o=Error.stackTraceLimit;return Error.stackTraceLimit=4,$1.set(i,new Error),Error.stackTraceLimit=o,$1.get(i)}class Ox extends Error{constructor(i){super(i.message);this.name=this.constructor.name,Object.assign(this,i)}}var xo={connection:tR,postgres:dR,generic:rR,notSupported:eR};function tR(i,o,n){let{host:p,port:c}=n||o,x=Object.assign(new Error("write "+i+" "+(o.path||p+":"+c)),{code:i,errno:i,address:o.path||p},o.path?{}:{port:c});return Error.captureStackTrace(x,tR),x}function dR(i){let o=new Ox(i);return Error.captureStackTrace(o,dR),o}function rR(i,o){let n=Object.assign(new Error(i+": "+o),{code:i});return Error.captureStackTrace(n,rR),n}function eR(i){let o=Object.assign(new Error(i+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:i});return Error.captureStackTrace(o,eR),o}var TE={string:{to:25,from:null,serialize:(i)=>""+i},number:{to:0,from:[21,23,26,700,701],serialize:(i)=>""+i,parse:(i)=>+i},json:{to:114,from:[114,3802],serialize:(i)=>JSON.stringify(i),parse:(i)=>JSON.parse(i)},boolean:{to:16,from:16,serialize:(i)=>i===!0?"t":"f",parse:(i)=>i==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(i)=>(i instanceof Date?i:new Date(i)).toISOString(),parse:(i)=>new Date(i)},bytea:{to:17,from:17,serialize:(i)=>"\\x"+Buffer.from(i).toString("hex"),parse:(i)=>Buffer.from(i.slice(2),"hex")}};class v1{then(){KJ()}catch(){KJ()}finally(){KJ()}}class om extends v1{constructor(i){super();this.value=W1(i)}}class en extends v1{constructor(i,o,n){super();this.value=i,this.type=o,this.array=n}}class w1 extends v1{constructor(i,o){super();this.first=i,this.rest=o}build(i,o,n,p){let c=mE.map(([x,T])=>({fn:T,i:i.search(x)})).sort((x,T)=>x.i-T.i).pop();return c.i===-1?zJ(this.first,p):c.fn(this.first,this.rest,o,n,p)}}function X1(i,o,n,p){let c=i instanceof en?i.value:i;if(c===void 0){if(i instanceof en?i.value=p.transform.undefined:c=i=p.transform.undefined,c===void 0)throw xo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+n.push(i instanceof en?(o.push(i.value),i.array?i.array[i.type||A1(i.value)]||i.type||pY(i.value):i.type):(o.push(i),A1(i)))}var oY=xY(TE);function ZJ(i,o,n,p,c,x){for(let T=1;T<i.strings.length;T++)o+=MJ(o,n,p,c,x)+i.strings[T],n=i.args[T];return o}function MJ(i,o,n,p,c){return o instanceof w1?o.build(i,n,p,c):o instanceof un?UJ(o,n,p,c):o instanceof om?o.value:o&&o[0]instanceof un?o.reduce((x,T)=>x+" "+UJ(T,n,p,c),""):X1(o,n,p,c)}function UJ(i,o,n,p){return i.fragment=!0,ZJ(i,i.strings[0],i.args[0],o,n,p)}function nY(i,o,n,p,c){return i.map((x)=>"("+p.map((T)=>MJ("values",x[T],o,n,c)).join(",")+")").join(",")}function iY(i,o,n,p,c){let x=Array.isArray(i[0]),T=o.length?o.flat():Object.keys(x?i[0]:i);return nY(x?i:[i],n,p,T,c)}function J1(i,o,n,p,c){if(typeof i==="string"&&(i=[i].concat(o)),Array.isArray(i))return zJ(i,c);let x;return(o.length?o.flat():Object.keys(i)).map((m)=>{return x=i[m],(x instanceof un?UJ(x,n,p,c):x instanceof om?x.value:X1(x,n,p,c))+" as "+W1(c.transform.column.to?c.transform.column.to(m):m)}).join(",")}var mE=Object.entries({values:iY,in:(...i)=>{let o=iY(...i);return o==="()"?"(null)":o},select:J1,as:J1,returning:J1,"\\(":J1,update(i,o,n,p,c){return(o.length?o.flat():Object.keys(i)).map((x)=>W1(c.transform.column.to?c.transform.column.to(x):x)+"="+MJ("values",i[x],n,p,c))},insert(i,o,n,p,c){let x=o.length?o.flat():Object.keys(Array.isArray(i)?i[0]:i);return"("+zJ(x,c)+")values"+nY(Array.isArray(i)?i:[i],n,p,x,c)}}).map(([i,o])=>[new RegExp("((?:^|[\\s(])"+i+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),o]);function KJ(){throw xo.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}var{serializers:fE,parsers:FE}=oY;function pY(i){if(Array.isArray(i))return pY(i[0]);return typeof i==="string"?1009:0}var cY=function(i){let o=xY(i||{});return{serializers:Object.assign({},fE,o.serializers),parsers:Object.assign({},FE,o.parsers)}};function xY(i){return Object.keys(i).reduce((o,n)=>{if(i[n].from&&[].concat(i[n].from).forEach((p)=>o.parsers[p]=i[n].parse),i[n].serialize)o.serializers[i[n].to]=i[n].serialize,i[n].from&&[].concat(i[n].from).forEach((p)=>o.serializers[p]=i[n].serialize);return o},{parsers:{},serializers:{}})}function zJ(i,{transform:{column:o}}){return i.map((n)=>W1(o.to?o.to(n):n)).join(",")}var W1=function i(o){return'"'+o.replace(/"/g,'""').replace(/\./g,'"."')+'"'},A1=function i(o){return o instanceof en?o.type:o instanceof Date?1184:o instanceof Uint8Array?17:o===!0||o===!1?16:typeof o==="bigint"?20:Array.isArray(o)?i(o[0]):0},$E=/\\/g,JE=/"/g;function AE(i){return i.replace($E,"\\\\").replace(JE,"\\\"")}var TY=function i(o,n,p,c){if(Array.isArray(o)===!1)return o;if(!o.length)return"{}";let x=o[0],T=c===1020?";":",";if(Array.isArray(x)&&!x.type)return"{"+o.map((m)=>i(m,n,p,c)).join(T)+"}";return"{"+o.map((m)=>{if(m===void 0){if(m=p.transform.undefined,m===void 0)throw xo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return m===null?"null":'"'+AE(n?n(m.type?m.value:m):""+m)+'"'}).join(T)+"}"},HJ={i:0,char:null,str:"",quoted:!1,last:0},mY=function i(o,n,p){return HJ.i=HJ.last=0,fY(HJ,o,n,p)};function fY(i,o,n,p){let c=[],x=p===1020?";":",";for(;i.i<o.length;i.i++){if(i.char=o[i.i],i.quoted)if(i.char==="\\")i.str+=o[++i.i];else if(i.char==='"')c.push(n?n(i.str):i.str),i.str="",i.quoted=o[i.i+1]==='"',i.last=i.i+2;else i.str+=i.char;else if(i.char==='"')i.quoted=!0;else if(i.char==="{")i.last=++i.i,c.push(fY(i,o,n,p));else if(i.char==="}"){i.quoted=!1,i.last<i.i&&c.push(n?n(o.slice(i.last,i.i)):o.slice(i.last,i.i)),i.last=i.i+1;break}else if(i.char===x&&i.p!=="}"&&i.p!=='"')c.push(n?n(o.slice(i.last,i.i)):o.slice(i.last,i.i)),i.last=i.i+1;i.p=i.char}return i.last<i.i&&c.push(n?n(o.slice(i.last,i.i+1)):o.slice(i.last,i.i+1)),c}var Zc=(i)=>{let o=i[0];for(let n=1;n<i.length;n++)o+=i[n]==="_"?i[++n].toUpperCase():i[n];return o},Mc=(i)=>{let o=i[0].toUpperCase();for(let n=1;n<i.length;n++)o+=i[n]==="_"?i[++n].toUpperCase():i[n];return o},zc=(i)=>i.replace(/_/g,"-"),rT=(i)=>i.replace(/([A-Z])/g,"_$1").toLowerCase(),eT=(i)=>(i.slice(0,1)+i.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),im=(i)=>i.replace(/-/g,"_");function uJ(i){return function o(n,p){return typeof n==="object"&&n!==null&&(p.type===114||p.type===3802)?Array.isArray(n)?n.map((c)=>o(c,p)):Object.entries(n).reduce((c,[x,T])=>Object.assign(c,{[i(x)]:o(T,p)}),{}):n}}Zc.column={from:Zc};Zc.value={from:uJ(Zc)};rT.column={to:rT};var QJ={...Zc};QJ.column.to=rT;Mc.column={from:Mc};Mc.value={from:uJ(Mc)};eT.column={to:eT};var VJ={...Mc};VJ.column.to=eT;zc.column={from:zc};zc.value={from:uJ(zc)};im.column={to:im};var SJ={...zc};SJ.column.to=im;import FY from"net";import WE from"tls";import nm from"crypto";import EJ from"stream";import{performance as $Y}from"perf_hooks";class uc extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}var Jn=vE;function vE(i=[]){let o=i.slice(),n=0;return{get length(){return o.length-n},remove:(p)=>{let c=o.indexOf(p);return c===-1?null:(o.splice(c,1),p)},push:(p)=>(o.push(p),p),shift:()=>{let p=o[n++];if(n===o.length)n=0,o=[];else o[n-1]=void 0;return p}}}var Io=Buffer.allocUnsafe(256),wE="BCcDdEFfHPpQSX".split("").reduce((i,o)=>{let n=o.charCodeAt(0);return i[o]=()=>{return Io[0]=n,Si.i=5,Si},i},{}),Si=Object.assign(XE,wE,{N:String.fromCharCode(0),i:0,inc(i){return Si.i+=i,Si},str(i){let o=Buffer.byteLength(i);return R1(o),Si.i+=Io.write(i,Si.i,o,"utf8"),Si},i16(i){return R1(2),Io.writeUInt16BE(i,Si.i),Si.i+=2,Si},i32(i,o){if(o||o===0)return Io.writeUInt32BE(i,o),Si;return R1(4),Io.writeUInt32BE(i,Si.i),Si.i+=4,Si},z(i){return R1(i),Io.fill(0,Si.i,Si.i+i),Si.i+=i,Si},raw(i){return Io=Buffer.concat([Io.subarray(0,Si.i),i]),Si.i=Io.length,Si},end(i=1){Io.writeUInt32BE(Si.i-i,i);let o=Io.subarray(0,Si.i);return Si.i=0,Io=Buffer.allocUnsafe(256),o}}),g=Si;function R1(i){if(Io.length-Si.i<i){let o=Io,n=o.length;Io=Buffer.allocUnsafe(n+(n>>1)+i),o.copy(Io)}}function XE(){return Si.i=0,Si}var LJ=vY,RE=1,kp=g().S().end(),JY=g().H().end(),YE=g().i32(8).i32(80877103).end(8),GE=Buffer.concat([g().E().str(g.N).i32(0).end(),kp]),KE=g().D().str("S").str(g.N).end(),_x=()=>{},HE=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),UE={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function vY(i,o={},{onopen:n=_x,onend:p=_x,onclose:c=_x}={}){let{ssl:x,max:T,user:m,host:f,port:F,database:$,parsers:J,transform:A,onnotice:X,onnotify:Y,onparameter:R,max_pipeline:K,keep_alive:H,backoff:z,target_session_attrs:b}=i,M=Jn(),u=RE++,E={pid:null,secret:null},S=_J(O1,i.idle_timeout),y=_J(O1,i.max_lifetime),l=_J(lY,i.connect_timeout),Q=null,Ti,q=new uc,mi=Buffer.alloc(0),Ei=i.fetch_types,To={},lo={},ip=Math.random().toString(36).slice(2),O=1,k=0,Yi=0,ai=0,mo=0,Fi=0,yi=0,no=0,qi=null,bi=null,zo=!1,Di=null,Qn=null,uo=null,Yp=null,fo=null,ji=null,Vn=null,Pn=null,C=null,Ix=null,Qo={queue:o.closed,idleTimer:S,connect(v){uo=v||!0,xA()},terminate:Nx,execute:Bx,cancel:bY,end:O1,count:0,id:u};return o.closed&&o.closed.push(Qo),Qo;async function NY(){let v;try{v=i.socket?await Promise.resolve(i.socket(i)):new FY.Socket}catch(G){Ec(G);return}return v.on("error",Ec),v.on("close",TA),v.on("drain",pA),v}async function bY({pid:v,secret:G},s,Gi){try{Ti=g().i32(16).i32(80877102).i32(v).i32(G).end(16),await cA(),Q.once("error",Gi),Q.once("close",s)}catch(gi){Gi(gi)}}function Bx(v){if(zo)return Fm(v,xo.connection("CONNECTION_DESTROYED",i));if(v.cancelled)return;try{return v.state=E,C?M.push(v):(C=v,C.active=!0),aY(v),Ko(jY(v))&&!v.describeFirst&&!v.cursorFn&&M.length<K&&(!v.options.onexecute||v.options.onexecute(Qo))}catch(G){return M.length===0&&Ko(kp),an(G),!0}}function jY(v){if(v.parameters.length>=65534)throw xo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return v.options.simple?g().Q().str(v.statement.string+g.N).end():v.describeFirst?Buffer.concat([iA(v),JY]):v.prepare?v.prepared?fm(v):Buffer.concat([iA(v),fm(v)]):PY(v)}function iA(v){return Buffer.concat([fA(v.statement.string,v.parameters,v.statement.types,v.statement.name),VG("S",v.statement.name)])}function fm(v){return Buffer.concat([QG(v.parameters,v.statement.types,v.statement.name,v.cursorName),v.cursorFn?FA("",v.cursorRows):GE])}function PY(v){return Buffer.concat([fA(v.statement.string,v.parameters,v.statement.types),KE,fm(v)])}function aY(v){let G=[],s=[],Gi=ZJ(v,v.strings[0],v.args[0],G,s,i);!v.tagged&&v.args.forEach((gi)=>X1(gi,G,s,i)),v.prepare=i.prepare&&("prepare"in v.options?v.options.prepare:!0),v.string=Gi,v.signature=v.prepare&&s+Gi,v.onlyDescribe&&delete lo[v.signature],v.parameters=v.parameters||G,v.prepared=v.prepare&&v.signature in lo,v.describeFirst=v.onlyDescribe||G.length&&!v.prepared,v.statement=v.prepared?lo[v.signature]:{string:Gi,types:s,name:v.prepare?ip+O++:""},typeof i.debug==="function"&&i.debug(u,Gi,G,s)}function Ko(v,G){if(ji=ji?Buffer.concat([ji,v]):Buffer.from(v),G||ji.length>=1024)return oA(G);return bi===null&&(bi=setImmediate(oA)),!0}function oA(v){let G=Q.write(ji,v);return bi!==null&&clearImmediate(bi),ji=bi=null,G}function lY(){an(xo.connection("CONNECT_TIMEOUT",i,Q)),Q.destroy()}async function nA(){if(Ko(YE),!await new Promise((G)=>Q.once("data",(s)=>G(s[0]===83)))&&x==="prefer")return Sc();Q.removeAllListeners(),Q=WE.connect({socket:Q,servername:FY.isIP(Q.host)?void 0:Q.host,...x==="require"||x==="allow"||x==="prefer"?{rejectUnauthorized:!1}:x==="verify-full"?{}:typeof x==="object"?x:{}}),Q.on("secureConnect",Sc),Q.on("error",Ec),Q.on("close",TA),Q.on("drain",pA)}function pA(){!C&&n(Qo)}function E1(v){if(Di){if(Di.push(v),Yi-=v.length,Yi>=0)return}mi=Di?Buffer.concat(Di,Fi-Yi):mi.length===0?v:Buffer.concat([mi,v],mi.length+v.length);while(mi.length>4){if(Fi=mi.readUInt32BE(1),Fi>=mi.length){Yi=Fi-mi.length,Di=[mi];break}try{qY(mi.subarray(0,Fi+1))}catch(G){C&&(C.cursorFn||C.describeFirst)&&Ko(kp),an(G)}mi=mi.subarray(Fi+1),Yi=0,Di=null}}async function cA(){if(zo=!1,To={},Q||(Q=await NY()),!Q)return;if(l.start(),i.socket)return x?nA():Sc();if(Q.on("connect",x?nA:Sc),i.path)return Q.connect(i.path);Q.ssl=x,Q.connect(F[ai],f[ai]),Q.host=f[ai],Q.port=F[ai],ai=(ai+1)%F.length}function xA(){setTimeout(cA,k?k+yi-$Y.now():0)}function Sc(){try{lo={},Ei=i.fetch_types,ip=Math.random().toString(36).slice(2),O=1,y.start(),Q.on("data",E1),H&&Q.setKeepAlive&&Q.setKeepAlive(!0,1000*H);let v=EG();Ko(v)}catch(v){Ec(v)}}function Ec(v){if(Qo.queue===o.connecting&&i.host[mo+1])return;an(v);while(M.length)Fm(M.shift(),v)}function an(v){fo&&(fo.destroy(v),fo=null),C&&Fm(C,v),uo&&(Fm(uo,v),uo=null)}function Fm(v,G){"query"in G||"parameters"in G||Object.defineProperties(G,{stack:{value:G.stack+v.origin.replace(/.*\n/,`
|
|
99
|
+
`),enumerable:i.debug},query:{value:v.string,enumerable:i.debug},parameters:{value:v.parameters,enumerable:i.debug},args:{value:v.args,enumerable:i.debug},types:{value:v.statement&&v.statement.types,enumerable:i.debug}}),v.reject(G)}function O1(){return Yp||(!Qo.reserved&&p(Qo),!Qo.reserved&&!uo&&!C&&M.length===0?(Nx(),new Promise((v)=>Q&&Q.readyState!=="closed"?Q.once("close",v):v())):Yp=new Promise((v)=>Vn=v))}function Nx(){if(zo=!0,fo||C||uo||M.length)Ec(xo.connection("CONNECTION_DESTROYED",i));if(clearImmediate(bi),Q)Q.removeListener("data",E1),Q.removeListener("connect",Sc),Q.readyState==="open"&&Q.end(g().X().end());Vn&&(Vn(),Yp=Vn=null)}async function TA(v){if(mi=Buffer.alloc(0),Yi=0,Di=null,clearImmediate(bi),Q.removeListener("data",E1),Q.removeListener("connect",Sc),S.cancel(),y.cancel(),l.cancel(),Q.removeAllListeners(),Q=null,uo)return xA();!v&&(C||M.length)&&Ec(xo.connection("CONNECTION_CLOSED",i,Q)),k=$Y.now(),v&&i.shared.retries++,yi=(typeof z==="function"?z(i.shared.retries):z)*1000,c(Qo,xo.connection("CONNECTION_CLOSED",i,Q))}function qY(v,G=v[0]){(G===68?kY:G===100?GG:G===65?vG:G===83?hY:G===90?gY:G===67?sY:G===50?mA:G===49?tY:G===116?dY:G===84?rY:G===82?eY:G===110?xG:G===75?TG:G===69?JG:G===115?wG:G===51?XG:G===71?WG:G===78?HG:G===72?RG:G===99?KG:G===73?UG:G===86?ZG:G===118?MG:G===87?YG:zG)(v)}function kY(v){let G=7,s,Gi,gi,Vo=C.isRaw?new Array(C.statement.columns.length):{};for(let Bo=0;Bo<C.statement.columns.length;Bo++)Gi=C.statement.columns[Bo],s=v.readInt32BE(G),G+=4,gi=s===-1?null:C.isRaw===!0?v.subarray(G,G+=s):Gi.parser===void 0?v.toString("utf8",G,G+=s):Gi.parser.array===!0?Gi.parser(v.toString("utf8",G+1,G+=s)):Gi.parser(v.toString("utf8",G,G+=s)),C.isRaw?Vo[Bo]=C.isRaw===!0?gi:A.value.from?A.value.from(gi,Gi):gi:Vo[Gi.name]=A.value.from?A.value.from(gi,Gi):gi;C.forEachFn?C.forEachFn(A.row.from?A.row.from(Vo):Vo,q):q[no++]=A.row.from?A.row.from(Vo):Vo}function hY(v){let[G,s]=v.toString("utf8",5,v.length-1).split(g.N);if(To[G]=s,i.parameters[G]!==s)i.parameters[G]=s,R&&R(G,s)}function gY(v){if(C&&C.options.simple&&C.resolve(Qn||q),C=Qn=null,q=new uc,l.cancel(),uo){if(b){if(!To.in_hot_standby||!To.default_transaction_read_only)return $G();else if(FG(b,To))return Nx()}if(Ei)return uo===!0&&(uo=null),mG();uo!==!0&&Bx(uo),i.shared.retries=mo=0,uo=null;return}while(M.length&&(C=M.shift())&&(C.active=!0,C.cancelled))vY(i).cancel(C.state,C.cancelled.resolve,C.cancelled.reject);if(C)return;Qo.reserved?!Qo.reserved.release&&v[5]===73?Yp?Nx():(Qo.reserved=null,n(Qo)):Qo.reserved():Yp?Nx():n(Qo)}function sY(v){no=0;for(let G=v.length-1;G>0;G--){if(v[G]===32&&v[G+1]<58&&q.count===null)q.count=+v.toString("utf8",G+1,v.length-1);if(v[G-1]>=65){q.command=v.toString("utf8",5,G),q.state=E;break}}if(Ix&&(Ix(),Ix=null),q.command==="BEGIN"&&T!==1&&!Qo.reserved)return an(xo.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(C.options.simple)return mA();if(C.cursorFn)q.count&&C.cursorFn(q),Ko(kp);C.resolve(q)}function tY(){C.parsing=!1}function mA(){!q.statement&&(q.statement=C.statement),q.columns=C.statement.columns}function dY(v){let G=v.readUInt16BE(5);for(let s=0;s<G;++s)!C.statement.types[s]&&(C.statement.types[s]=v.readUInt32BE(7+s*4));C.prepare&&(lo[C.signature]=C.statement),C.describeFirst&&!C.onlyDescribe&&(Ko(fm(C)),C.describeFirst=!1)}function rY(v){if(q.command)Qn=Qn||[q],Qn.push(q=new uc),q.count=null,C.statement.columns=null;let G=v.readUInt16BE(5),s=7,Gi;C.statement.columns=Array(G);for(let gi=0;gi<G;++gi){Gi=s;while(v[s++]!==0);let Vo=v.readUInt32BE(s),Bo=v.readUInt16BE(s+4),Gp=v.readUInt32BE(s+6);C.statement.columns[gi]={name:A.column.from?A.column.from(v.toString("utf8",Gi,s-1)):v.toString("utf8",Gi,s-1),parser:J[Gp],table:Vo,number:Bo,type:Gp},s+=18}if(q.statement=C.statement,C.onlyDescribe)return C.resolve(C.statement),Ko(kp)}async function eY(v,G=v.readUInt32BE(5)){(G===3?iG:G===5?oG:G===10?nG:G===11?pG:G===12?cG:G!==0?uG:_x)(v,G)}async function iG(){let v=await _1();Ko(g().p().str(v).z(1).end())}async function oG(v){let G="md5"+await AY(Buffer.concat([Buffer.from(await AY(await _1()+m)),v.subarray(9)]));Ko(g().p().str(G).z(1).end())}async function nG(){Pn=(await nm.randomBytes(18)).toString("base64"),g().p().str("SCRAM-SHA-256"+g.N);let v=g.i;Ko(g.inc(4).str("n,,n=*,r="+Pn).i32(g.i-v-4,v).end())}async function pG(v){let G=v.toString("utf8",9).split(",").reduce((Bo,Gp)=>(Bo[Gp[0]]=Gp.slice(2),Bo),{}),s=await nm.pbkdf2Sync(await _1(),Buffer.from(G.s,"base64"),parseInt(G.i),32,"sha256"),Gi=await Y1(s,"Client Key"),gi="n=*,r="+Pn+",r="+G.r+",s="+G.s+",i="+G.i+",c=biws,r="+G.r;qi=(await Y1(await Y1(s,"Server Key"),gi)).toString("base64");let Vo="c=biws,r="+G.r+",p="+ME(Gi,Buffer.from(await Y1(await ZE(Gi),gi))).toString("base64");Ko(g().p().str(Vo).end())}function cG(v){if(v.toString("utf8",9).split(g.N,1)[0].slice(2)===qi)return;an(xo.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),Q.destroy()}function _1(){return Promise.resolve(typeof i.pass==="function"?i.pass():i.pass)}function xG(){if(q.statement=C.statement,q.statement.columns=[],C.onlyDescribe)return C.resolve(C.statement),Ko(kp)}function TG(v){E.pid=v.readUInt32BE(5),E.secret=v.readUInt32BE(9)}async function mG(){Ei=!1,(await new un([`
|
|
100
100
|
select b.oid, b.typarray
|
|
101
101
|
from pg_catalog.pg_type a
|
|
102
102
|
left join pg_catalog.pg_type b on b.oid = a.typelem
|
|
@@ -106,7 +106,7 @@ ${T.trace}`:"No previous disposal trace was found."),p.type){case"atom_family":c
|
|
|
106
106
|
`],[],Bx)).forEach(({oid:G,typarray:s})=>fG(G,s))}function fG(v,G){if(!!i.parsers[G]&&!!i.serializers[G])return;let s=i.parsers[v];i.shared.typeArrayMap[v]=G,i.parsers[G]=(Gi)=>mY(Gi,s,G),i.parsers[G].array=!0,i.serializers[G]=(Gi)=>TY(Gi,i.serializers[v],i,G)}function FG(v,G){return v==="read-write"&&G.default_transaction_read_only==="on"||v==="read-only"&&G.default_transaction_read_only==="off"||v==="primary"&&G.in_hot_standby==="on"||v==="standby"&&G.in_hot_standby==="off"||v==="prefer-standby"&&G.in_hot_standby==="off"&&i.host[mo]}function $G(){let v=new un([`
|
|
107
107
|
show transaction_read_only;
|
|
108
108
|
select pg_catalog.pg_is_in_recovery()
|
|
109
|
-
`],[],Bx,null,{simple:!0});v.resolve=([[G],[s]])=>{To.default_transaction_read_only=G.transaction_read_only,To.in_hot_standby=s.pg_is_in_recovery?"on":"off"},v.execute()}function JG(v){C&&(C.cursorFn||C.describeFirst)&&Ko(kp);let G=xo.postgres(OJ(v));C&&C.retried?an(C.retried):C&&C.prepared&&HE.has(G.routine)?AG(C,G):an(G)}function AG(v,G){delete lo[v.signature],v.retried=G,Bx(v)}function vG(v){if(!Y)return;let G=9;while(v[G++]!==0);Y(v.toString("utf8",9,G-1),v.toString("utf8",G,v.length-1))}async function wG(){try{let v=await Promise.resolve(C.cursorFn(q));
|
|
109
|
+
`],[],Bx,null,{simple:!0});v.resolve=([[G],[s]])=>{To.default_transaction_read_only=G.transaction_read_only,To.in_hot_standby=s.pg_is_in_recovery?"on":"off"},v.execute()}function JG(v){C&&(C.cursorFn||C.describeFirst)&&Ko(kp);let G=xo.postgres(OJ(v));C&&C.retried?an(C.retried):C&&C.prepared&&HE.has(G.routine)?AG(C,G):an(G)}function AG(v,G){delete lo[v.signature],v.retried=G,Bx(v)}function vG(v){if(!Y)return;let G=9;while(v[G++]!==0);Y(v.toString("utf8",9,G-1),v.toString("utf8",G,v.length-1))}async function wG(){try{let v=await Promise.resolve(C.cursorFn(q));no=0,v===Ex?Ko(SG(C.portal)):(q=new uc,Ko(FA("",C.cursorRows)))}catch(v){Ko(kp),C.reject(v)}}function XG(){q.count&&C.cursorFn(q),C.resolve(q)}function WG(){fo=new EJ.Writable({autoDestroy:!0,write(v,G,s){Q.write(g().d().raw(v).end(),s)},destroy(v,G){G(v),Q.write(g().f().str(v+g.N).end()),fo=null},final(v){Q.write(g().c().end()),Ix=v}}),C.resolve(fo)}function RG(){fo=new EJ.Readable({read(){Q.resume()}}),C.resolve(fo)}function YG(){fo=new EJ.Duplex({autoDestroy:!0,read(){Q.resume()},write(v,G,s){Q.write(g().d().raw(v).end(),s)},destroy(v,G){G(v),Q.write(g().f().str(v+g.N).end()),fo=null},final(v){Q.write(g().c().end()),Ix=v}}),C.resolve(fo)}function GG(v){fo&&(fo.push(v.subarray(5))||Q.pause())}function KG(){fo&&fo.push(null),fo=null}function HG(v){X?X(OJ(v)):console.log(OJ(v))}function UG(){}function ZG(){an(xo.notSupported("FunctionCallResponse"))}function MG(){an(xo.notSupported("NegotiateProtocolVersion"))}function zG(v){console.error("Postgres.js : Unknown Message:",v[0])}function uG(v,G){console.error("Postgres.js : Unknown Auth:",G)}function QG(v,G,s="",Gi=""){let gi,Vo;return g().B().str(Gi+g.N).str(s+g.N).i16(0).i16(v.length),v.forEach((Bo,Gp)=>{if(Bo===null)return g.i32(4294967295);Vo=G[Gp],v[Gp]=Bo=Vo in i.serializers?i.serializers[Vo](Bo):""+Bo,gi=g.i,g.inc(4).str(Bo).i32(g.i-gi-4,gi)}),g.i16(0),g.end()}function fA(v,G,s,Gi=""){return g().P().str(Gi+g.N).str(v+g.N).i16(G.length),G.forEach((gi,Vo)=>g.i32(s[Vo]||0)),g.end()}function VG(v,G=""){return g().D().str(v).str(G+g.N).end()}function FA(v="",G=0){return Buffer.concat([g().E().str(v+g.N).i32(G).end(),JY])}function SG(v=""){return Buffer.concat([g().C().str("P").str(v+g.N).end(),g().S().end()])}function EG(){return Ti||g().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:m,database:$,client_encoding:"UTF8"},i.connection)).filter(([,v])=>v).map(([v,G])=>v+g.N+G).join(g.N)).z(2).end(0)}}function OJ(i){let o={},n=5;for(let p=5;p<i.length-1;p++)if(i[p]===0)o[UE[i[n]]]=i.toString("utf8",n+1,p),n=p+1;return o}function AY(i){return nm.createHash("md5").update(i).digest("hex")}function Y1(i,o){return nm.createHmac("sha256",i).update(o).digest()}function ZE(i){return nm.createHash("sha256").update(i).digest()}function ME(i,o){let n=Math.max(i.length,o.length),p=Buffer.allocUnsafe(n);for(let c=0;c<n;c++)p[c]=i[c]^o[c];return p}function _J(i,o){if(o=typeof o==="function"?o():o,!o)return{cancel:_x,start:_x};let n;return{cancel(){n&&(clearTimeout(n),n=null)},start(){n&&clearTimeout(n),n=setTimeout(p,o*1000,arguments)}};function p(c){i.apply(null,c),n=null}}var wY=()=>{};function CJ(i,o){let n=new Map,p="postgresjs_"+Math.random().toString(36).slice(2),c={},x,T,m=!1,f=J.sql=i({...o,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...o.connection,replication:"database"},onclose:async function(){if(m)return;T=null,c.pid=c.secret=void 0,A(await X(f,p,o.publications)),n.forEach((R)=>R.forEach(({onsubscribe:K})=>K()))},no_subscribe:!0}),F=f.end,$=f.close;return f.end=async()=>{return m=!0,T&&await new Promise((R)=>(T.once("close",R),T.end())),F()},f.close=async()=>{return T&&await new Promise((R)=>(T.once("close",R),T.end())),$()},J;async function J(R,K,H=wY,z=wY){if(R=QE(R),!x)x=X(f,p,o.publications);let b={fn:K,onsubscribe:H},M=n.has(R)?n.get(R).add(b):n.set(R,new Set([b])).get(R),u=()=>{M.delete(b),M.size===0&&n.delete(R)};return x.then((E)=>{return A(E),H(),T&&T.on("error",z),{unsubscribe:u,state:c,sql:f}})}function A(R){T=R.stream,c.pid=R.state.pid,c.secret=R.state.secret}async function X(R,K,H){if(!H)throw new Error("Missing publication names");let z=await R.unsafe(`CREATE_REPLICATION_SLOT ${K} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[b]=z,M=await R.unsafe(`START_REPLICATION SLOT ${K} LOGICAL ${b.consistent_point} (proto_version '1', publication_names '${H}')`).writable(),u={lsn:Buffer.concat(b.consistent_point.split("/").map((Q)=>Buffer.from(("00000000"+Q).slice(-8),"hex")))};return M.on("data",S),M.on("error",E),M.on("close",R.close),{stream:M,state:z.state};function E(Q){console.error("Unexpected error during logical streaming - reconnecting",Q)}function S(Q){if(Q[0]===119)uE(Q.subarray(25),u,R.options.parsers,y,o.transform);else if(Q[0]===107&&Q[17])u.lsn=Q.subarray(1,9),l()}function y(Q,Ti){let q=Ti.relation.schema+"."+Ti.relation.table;Y("*",Q,Ti),Y("*:"+q,Q,Ti),Ti.relation.keys.length&&Y("*:"+q+"="+Ti.relation.keys.map((mi)=>Q[mi.name]),Q,Ti),Y(Ti.command,Q,Ti),Y(Ti.command+":"+q,Q,Ti),Ti.relation.keys.length&&Y(Ti.command+":"+q+"="+Ti.relation.keys.map((mi)=>Q[mi.name]),Q,Ti)}function l(){let Q=Buffer.alloc(34);Q[0]=114,Q.fill(u.lsn,1),Q.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),M.write(Q)}}function Y(R,K,H){n.has(R)&&n.get(R).forEach(({fn:z})=>z(K,H,R))}}function zE(i){return new Date(Date.UTC(2000,0,1)+Number(i/BigInt(1000)))}function uE(i,o,n,p,c){let x=(T,[m,f])=>(T[m.charCodeAt(0)]=f,T);Object.entries({R:(T)=>{let m=1,f=o[T.readUInt32BE(m)]={schema:T.toString("utf8",m+=4,m=T.indexOf(0,m))||"pg_catalog",table:T.toString("utf8",m+1,m=T.indexOf(0,m+1)),columns:Array(T.readUInt16BE(m+=2)),keys:[]};m+=2;let F=0,$;while(m<T.length)$=f.columns[F++]={key:T[m++],name:c.column.from?c.column.from(T.toString("utf8",m,m=T.indexOf(0,m))):T.toString("utf8",m,m=T.indexOf(0,m)),type:T.readUInt32BE(m+=1),parser:n[T.readUInt32BE(m)],atttypmod:T.readUInt32BE(m+=4)},$.key&&f.keys.push($),m+=4},Y:()=>{},O:()=>{},B:(T)=>{o.date=zE(T.readBigInt64BE(9)),o.lsn=T.subarray(1,9)},I:(T)=>{let m=1,f=o[T.readUInt32BE(m)],{row:F}=G1(T,f.columns,m+=7,c);p(F,{command:"insert",relation:f})},D:(T)=>{let m=1,f=o[T.readUInt32BE(m)];m+=4;let F=T[m]===75;p(F||T[m]===79?G1(T,f.columns,m+=3,c).row:null,{command:"delete",relation:f,key:F})},U:(T)=>{let m=1,f=o[T.readUInt32BE(m)];m+=4;let F=T[m]===75,$=F||T[m]===79?G1(T,f.columns,m+=3,c):null;$&&(m=$.i);let{row:J}=G1(T,f.columns,m+3,c);p(J,{command:"update",relation:f,key:F,old:$&&$.row})},T:()=>{},C:()=>{}}).reduce(x,{})[i[0]](i)}function G1(i,o,n,p){let c,x,T,m=p.raw?new Array(o.length):{};for(let f=0;f<o.length;f++)c=i[n++],x=o[f],T=c===110?null:c===117?void 0:x.parser===void 0?i.toString("utf8",n+4,n+=4+i.readUInt32BE(n)):x.parser.array===!0?x.parser(i.toString("utf8",n+5,n+=4+i.readUInt32BE(n))):x.parser(i.toString("utf8",n+4,n+=4+i.readUInt32BE(n))),p.raw?m[f]=p.raw===!0?T:p.value.from?p.value.from(T,x):T:m[x.name]=p.value.from?p.value.from(T,x):T;return{i:n,row:p.row.from?p.row.from(m):m}}function QE(i){let o=i.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!o)throw new Error("Malformed subscribe pattern: "+i);let[,n,p,c]=o;return(n||"*")+(p?":"+(p.indexOf(".")===-1?"public."+p:p):"")+(c?"="+c:"")}import XY from"stream";function yJ(i,o,n=393216){return new Promise(async(p,c)=>{await i.begin(async(x)=>{let T;!o&&([{oid:o}]=await x`select lo_creat(-1) as oid`);let[{fd:m}]=await x`select lo_open(${o}, ${n}) as fd`,f={writable:$,readable:F,close:()=>x`select lo_close(${m})`.then(T),tell:()=>x`select lo_tell64(${m})`,read:(J)=>x`select loread(${m}, ${J}) as data`,write:(J)=>x`select lowrite(${m}, ${J})`,truncate:(J)=>x`select lo_truncate64(${m}, ${J})`,seek:(J,A=0)=>x`select lo_lseek64(${m}, ${J}, ${A})`,size:()=>x`
|
|
110
110
|
select
|
|
111
111
|
lo_lseek64(${m}, location, 0) as position,
|
|
112
112
|
seek.size
|
|
@@ -116,10 +116,10 @@ ${T.trace}`:"No previous disposal trace was found."),p.type){case"atom_family":c
|
|
|
116
116
|
tell.location
|
|
117
117
|
from (select lo_tell64($1) as location) tell
|
|
118
118
|
) seek
|
|
119
|
-
`};return p(f),new Promise(async(J)=>T=J);async function F({highWaterMark:J=16384,start:A=0,end:X=1/0}={}){let Y=X-A;return A&&await f.seek(A),new XY.Readable({highWaterMark:J,async read(R){let K=R>Y?R-Y:R;Y-=R;let[{data:H}]=await f.read(K);if(this.push(H),H.length<R)this.push(null)}})}async function $({highWaterMark:J=16384,start:A=0}={}){return A&&await f.seek(A),new XY.Writable({highWaterMark:J,write(X,Y,R){f.write(X).then(()=>R(),R)}})}}).catch(c)})}Object.assign(K1,{PostgresError:Ox,toPascal:Mc,pascal:VJ,toCamel:Zc,camel:QJ,toKebab:zc,kebab:SJ,fromPascal:eT,fromCamel:rT,fromKebab:im,BigInt:{to:20,from:[20],parse:(i)=>BigInt(i),serialize:(i)=>i.toString()}});var Lx=K1;function K1(i,o){let n=EE(i,o),p=n.no_subscribe||CJ(K1,{...n}),c=!1,x=Jn(),T=Jn(),m=Jn(),f=Jn(),F=Jn(),$=Jn(),J=Jn(),A=Jn(),X={connecting:T,reserved:m,closed:f,ended:F,open:$,busy:J,full:A},Y=[...Array(n.max)].map(()=>LJ(n,X,{onopen:lo,onend:To,onclose:ip})),R=K(y);return Object.assign(R,{get parameters(){return n.parameters},largeObject:yJ.bind(null,R),subscribe:p,CLOSE:Ex,END:Ex,PostgresError:Ox,options:n,reserve:b,listen:H,begin:M,close:q,end:Ti}),R;function K(O){return O.debug=n.debug,Object.entries(n.types).reduce((Fi,[yi,oo])=>{return Fi[yi]=(qi)=>new en(qi,oo.to),Fi},k),Object.assign(Yi,{types:k,typed:k,unsafe:ai,notify:z,array:S,json:E,file:mo}),Yi;function k(Fi,yi){return new en(Fi,yi)}function Yi(Fi,...yi){return Fi&&Array.isArray(Fi.raw)?new un(Fi,yi,O,Q):typeof Fi==="string"&&!yi.length?new om(n.transform.column.to?n.transform.column.to(Fi):Fi):new w1(Fi,yi)}function ai(Fi,yi=[],oo={}){return arguments.length===2&&!Array.isArray(yi)&&(oo=yi,yi=[]),new un([Fi],yi,O,Q,{prepare:!1,...oo,simple:"simple"in oo?oo.simple:yi.length===0})}function mo(Fi,yi=[],oo={}){return arguments.length===2&&!Array.isArray(yi)&&(oo=yi,yi=[]),new un([],yi,(bi)=>{SE.readFile(Fi,"utf8",(zo,Di)=>{if(zo)return bi.reject(zo);bi.strings=[Di],O(bi)})},Q,{...oo,simple:"simple"in oo?oo.simple:yi.length===0})}}async function H(O,k,Yi){let ai={fn:k,onlisten:Yi},mo=H.sql||(H.sql=K1({...n,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(H.channels).forEach(([bi,{listeners:zo}])=>{delete H.channels[bi],Promise.all(zo.map((Di)=>H(bi,Di.fn,Di.onlisten).catch(()=>{})))})},onnotify(bi,zo){bi in H.channels&&H.channels[bi].listeners.forEach((Di)=>Di.fn(zo))}})),Fi=H.channels||(H.channels={});if(O in Fi){Fi[O].listeners.push(ai);let bi=await Fi[O].result;return ai.onlisten&&ai.onlisten(),{state:bi.state,unlisten:qi}}Fi[O]={result:mo`listen ${mo.unsafe('"'+O.replace(/"/g,'""')+'"')}`,listeners:[ai]};let oo=await Fi[O].result;return ai.onlisten&&ai.onlisten(),{state:oo.state,unlisten:qi};async function qi(){if(O in Fi===!1)return;if(Fi[O].listeners=Fi[O].listeners.filter((bi)=>bi!==ai),Fi[O].listeners.length)return;return delete Fi[O],mo`unlisten ${mo.unsafe('"'+O.replace(/"/g,'""')+'"')}`}}async function z(O,k){return await R`select pg_notify(${O}, ${""+k})`}async function b(){let O=Jn(),k=$.length?$.shift():await new Promise((mo)=>{x.push({reserve:mo}),f.length&&Ei(f.shift())});u(k,m),k.reserved=()=>O.length?k.execute(O.shift()):u(k,m),k.reserved.release=!0;let Yi=K(ai);return Yi.release=()=>{k.reserved=null,lo(k)},Yi;function ai(mo){k.queue===A?O.push(mo):k.execute(mo)||u(k,A)}}async function M(O,k){!k&&(k=O,O="");let Yi=Jn(),ai=0,mo,Fi=null;try{return await R.unsafe("begin "+O.replace(/[^a-z ]/ig,""),[],{onexecute:oo}).execute(),await Promise.race([yi(mo,k),new Promise((qi,bi)=>mo.onclose=bi)])}catch(qi){throw qi}async function yi(qi,bi,zo){let Di=K(fo);Di.savepoint=Yp,Di.prepare=(ji)=>Fi=ji.replace(/[^a-z0-9$-_. ]/gi);let Qn,uo;zo&&await Di`savepoint ${Di(zo)}`;try{if(uo=await new Promise((ji,Vn)=>{let Pn=bi(Di);Promise.resolve(Array.isArray(Pn)?Promise.all(Pn):Pn).then(ji,Vn)}),Qn)throw Qn}catch(ji){throw await(zo?Di`rollback to ${Di(zo)}`:Di`rollback`),ji instanceof Ox&&ji.code==="25P02"&&Qn||ji}if(!zo)Fi?await Di`prepare transaction '${Di.unsafe(Fi)}'`:await Di`commit`;return uo;function Yp(ji,Vn){if(ji&&Array.isArray(ji.raw))return Yp((Pn)=>Pn.apply(Pn,arguments));return arguments.length===1&&(Vn=ji,ji=null),yi(qi,Vn,"s"+ai+++(ji?"_"+ji:""))}function fo(ji){ji.catch((Vn)=>Qn||(Qn=Vn)),qi.queue===A?Yi.push(ji):qi.execute(ji)||u(qi,A)}}function oo(qi){mo=qi,u(qi,m),qi.reserved=()=>Yi.length?qi.execute(Yi.shift()):u(qi,m)}}function u(O,k){return O.queue.remove(O),k.push(O),O.queue=k,k===$?O.idleTimer.start():O.idleTimer.cancel(),O}function E(O){return new en(O,3802)}function S(O,k){if(!Array.isArray(O))return S(Array.from(arguments));return new en(O,k||(O.length?A1(O)||25:0),n.shared.typeArrayMap)}function y(O){if(c)return O.reject(xo.connection("CONNECTION_ENDED",n,n));if($.length)return l($.shift(),O);if(f.length)return Ei(f.shift(),O);J.length?l(J.shift(),O):x.push(O)}function l(O,k){return O.execute(k)?u(O,J):u(O,A)}function Q(O){return new Promise((k,Yi)=>{O.state?O.active?LJ(n).cancel(O.state,k,Yi):O.cancelled={resolve:k,reject:Yi}:(x.remove(O),O.cancelled=!0,O.reject(xo.generic("57014","canceling statement due to user request")),k())})}async function Ti({timeout:O=null}={}){if(c)return c;await 1;let k;return c=Promise.race([new Promise((Yi)=>O!==null&&(k=setTimeout(mi,O*1000,Yi))),Promise.all(Y.map((Yi)=>Yi.end()).concat(H.sql?H.sql.end({timeout:0}):[],p.sql?p.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(k))}async function q(){await Promise.all(Y.map((O)=>O.end()))}async function mi(O){await Promise.all(Y.map((k)=>k.terminate()));while(x.length)x.shift().reject(xo.connection("CONNECTION_DESTROYED",n));O()}function Ei(O,k){return u(O,T),O.connect(k),O}function To(O){u(O,F)}function lo(O){if(x.length===0)return u(O,$);let k=Math.ceil(x.length/(T.length+1)),Yi=!0;while(Yi&&x.length&&k-- >0){let ai=x.shift();if(ai.reserve)return ai.reserve(O);Yi=O.execute(ai)}Yi?u(O,J):u(O,A)}function ip(O,k){u(O,f),O.reserved=null,O.onclose&&(O.onclose(k),O.onclose=null),n.onclose&&n.onclose(O.id),x.length&&Ei(O,x.shift())}}function EE(i,o){if(i&&i.shared)return i;let n=process.env,p=(!i||typeof i==="string"?o:i)||{},{url:c,multihost:x}=yE(i),T=[...c.searchParams].reduce((A,[X,Y])=>(A[X]=Y,A),{}),m=p.hostname||p.host||x||c.hostname||n.PGHOST||"localhost",f=p.port||c.port||n.PGPORT||5432,F=p.user||p.username||c.username||n.PGUSERNAME||n.PGUSER||DE();p.no_prepare&&(p.prepare=!1),T.sslmode&&(T.ssl=T.sslmode,delete T.sslmode),"timeout"in p&&(console.log("The timeout option is deprecated, use idle_timeout instead"),p.idle_timeout=p.timeout),T.sslrootcert==="system"&&(T.ssl="verify-full");let $=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],J={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:LE,max_pipeline:100,backoff:_E,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(m)?m:m.split(",").map((A)=>A.split(":")[0]),port:Array.isArray(f)?f:m.split(",").map((A)=>parseInt(A.split(":")[1]||f)),path:p.path||m.indexOf("/")>-1&&m+"/.s.PGSQL."+f,database:p.database||p.db||(c.pathname||"").slice(1)||n.PGDATABASE||F,user:F,pass:p.pass||p.password||c.password||n.PGPASSWORD||"",...Object.entries(J).reduce((A,[X,Y])=>{let R=X in p?p[X]:(X in T)?T[X]==="disable"||T[X]==="false"?!1:T[X]:n["PG"+X.toUpperCase()]||Y;return A[X]=typeof R==="string"&&$.includes(X)?+R:R,A},{}),connection:{application_name:"postgres.js",...p.connection,...Object.entries(T).reduce((A,[X,Y])=>((X in J)||(A[X]=Y),A),{})},types:p.types||{},target_session_attrs:OE(p,c,n),onnotice:p.onnotice,onnotify:p.onnotify,onclose:p.onclose,onparameter:p.onparameter,socket:p.socket,transform:CE(p.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...cY(p.types)}}function OE(i,o,n){let p=i.target_session_attrs||o.searchParams.get("target_session_attrs")||n.PGTARGETSESSIONATTRS;if(!p||["read-write","read-only","primary","standby","prefer-standby"].includes(p))return p;throw new Error("target_session_attrs "+p+" is not supported")}function _E(i){return(0.5+Math.random()/2)*Math.min(3**i/100,20)}function LE(){return 60*(30+Math.random()*30)}function CE(i){return{undefined:i.undefined,column:{from:typeof i.column==="function"?i.column:i.column&&i.column.from,to:i.column&&i.column.to},value:{from:typeof i.value==="function"?i.value:i.value&&i.value.from,to:i.value&&i.value.to},row:{from:typeof i.row==="function"?i.row:i.row&&i.row.from,to:i.row&&i.row.to}}}function yE(i){if(!i||typeof i!=="string")return{url:{searchParams:new Map}};let o=i;o=o.slice(o.indexOf("://")+3).split(/[?/]/)[0],o=decodeURIComponent(o.slice(o.indexOf("@")+1));let n=new URL(i.replace(o,o.split(",")[0]));return{url:{username:decodeURIComponent(n.username),password:decodeURIComponent(n.password),host:n.host,hostname:n.hostname,port:n.port,pathname:n.pathname,searchParams:n.searchParams},multihost:o.indexOf(",")>-1&&o}}function DE(){try{return VE.userInfo().username}catch(i){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class ti{static[w]="SelectionProxyHandler";config;constructor(i){this.config={...i}}get(i,o){if(o==="_")return{...i._,selectedFields:new Proxy(i._.selectedFields,this)};if(o===Ni)return{...i[Ni],selectedFields:new Proxy(i[Ni].selectedFields,this)};if(typeof o==="symbol")return i[o];let p=(Z(i,wo)?i._.selectedFields:Z(i,ro)?i[Ni].selectedFields:i)[o];if(Z(p,N.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!p.isSelectionField)return p.sql;let c=p.clone();return c.isSelectionField=!0,c}if(Z(p,N)){if(this.config.sqlBehavior==="sql")return p;throw new Error(`You tried to reference "${o}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(Z(p,Li)){if(this.config.alias)return new Proxy(p,new Xx(new Proxy(p.table,new NT(this.config.alias,this.config.replaceOriginalName??!1))));return p}if(typeof p!=="object"||p===null)return p;return new Proxy(p,new ti(this.config))}}class H1 extends jo{constructor(i,o,n,p){super();this.session=o,this.dialect=n,this.config={table:i,withList:p}}static[w]="PgDelete";config;where(i){return this.config.where=i,this}returning(i=this.config.table[B.Symbol.Columns]){return this.config.returningFields=i,this.config.returning=Un(i),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:i,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(i){return Ci.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,i,!0)})}prepare(i){return this._prepare(i)}authToken;setToken(i){return this.authToken=i,this}execute=(i)=>{return Ci.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(i,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new ti({alias:Ro(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function IE(i){return(i.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((n)=>n.toLowerCase()).join("_")}function BE(i){return(i.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((n,p,c)=>{let x=c===0?p.toLowerCase():`${p[0].toUpperCase()}${p.slice(1)}`;return n+x},"")}function NE(i){return i}class DJ{static[w]="CasingCache";cache={};cachedTables={};convert;constructor(i){this.convert=i==="snake_case"?IE:i==="camelCase"?BE:NE}getColumnCasing(i){if(!i.keyAsName)return i.name;let o=i.table[B.Symbol.Schema]??"public",n=i.table[B.Symbol.OriginalName],p=`${o}.${n}.${i.name}`;if(!this.cache[p])this.cacheTable(i.table);return this.cache[p]}cacheTable(i){let o=i[B.Symbol.Schema]??"public",n=i[B.Symbol.OriginalName],p=`${o}.${n}`;if(!this.cachedTables[p]){for(let c of Object.values(i[B.Symbol.Columns])){let x=`${p}.${c.name}`;this.cache[x]=this.convert(c.name)}this.cachedTables[p]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class pm extends ro{static[w]="PgViewBase"}class Qc{static[w]="PgDialect";casing;constructor(i){this.casing=new DJ(i?.casing)}async migrate(i,o,n){let p=typeof n==="string"?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",c=typeof n==="string"?"drizzle":n.migrationsSchema??"drizzle",x=W`
|
|
119
|
+
`};return p(f),new Promise(async(J)=>T=J);async function F({highWaterMark:J=16384,start:A=0,end:X=1/0}={}){let Y=X-A;return A&&await f.seek(A),new XY.Readable({highWaterMark:J,async read(R){let K=R>Y?R-Y:R;Y-=R;let[{data:H}]=await f.read(K);if(this.push(H),H.length<R)this.push(null)}})}async function $({highWaterMark:J=16384,start:A=0}={}){return A&&await f.seek(A),new XY.Writable({highWaterMark:J,write(X,Y,R){f.write(X).then(()=>R(),R)}})}}).catch(c)})}Object.assign(K1,{PostgresError:Ox,toPascal:Mc,pascal:VJ,toCamel:Zc,camel:QJ,toKebab:zc,kebab:SJ,fromPascal:eT,fromCamel:rT,fromKebab:im,BigInt:{to:20,from:[20],parse:(i)=>BigInt(i),serialize:(i)=>i.toString()}});var Lx=K1;function K1(i,o){let n=EE(i,o),p=n.no_subscribe||CJ(K1,{...n}),c=!1,x=Jn(),T=Jn(),m=Jn(),f=Jn(),F=Jn(),$=Jn(),J=Jn(),A=Jn(),X={connecting:T,reserved:m,closed:f,ended:F,open:$,busy:J,full:A},Y=[...Array(n.max)].map(()=>LJ(n,X,{onopen:lo,onend:To,onclose:ip})),R=K(y);return Object.assign(R,{get parameters(){return n.parameters},largeObject:yJ.bind(null,R),subscribe:p,CLOSE:Ex,END:Ex,PostgresError:Ox,options:n,reserve:b,listen:H,begin:M,close:q,end:Ti}),R;function K(O){return O.debug=n.debug,Object.entries(n.types).reduce((Fi,[yi,no])=>{return Fi[yi]=(qi)=>new en(qi,no.to),Fi},k),Object.assign(Yi,{types:k,typed:k,unsafe:ai,notify:z,array:S,json:E,file:mo}),Yi;function k(Fi,yi){return new en(Fi,yi)}function Yi(Fi,...yi){return Fi&&Array.isArray(Fi.raw)?new un(Fi,yi,O,Q):typeof Fi==="string"&&!yi.length?new om(n.transform.column.to?n.transform.column.to(Fi):Fi):new w1(Fi,yi)}function ai(Fi,yi=[],no={}){return arguments.length===2&&!Array.isArray(yi)&&(no=yi,yi=[]),new un([Fi],yi,O,Q,{prepare:!1,...no,simple:"simple"in no?no.simple:yi.length===0})}function mo(Fi,yi=[],no={}){return arguments.length===2&&!Array.isArray(yi)&&(no=yi,yi=[]),new un([],yi,(bi)=>{SE.readFile(Fi,"utf8",(zo,Di)=>{if(zo)return bi.reject(zo);bi.strings=[Di],O(bi)})},Q,{...no,simple:"simple"in no?no.simple:yi.length===0})}}async function H(O,k,Yi){let ai={fn:k,onlisten:Yi},mo=H.sql||(H.sql=K1({...n,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(H.channels).forEach(([bi,{listeners:zo}])=>{delete H.channels[bi],Promise.all(zo.map((Di)=>H(bi,Di.fn,Di.onlisten).catch(()=>{})))})},onnotify(bi,zo){bi in H.channels&&H.channels[bi].listeners.forEach((Di)=>Di.fn(zo))}})),Fi=H.channels||(H.channels={});if(O in Fi){Fi[O].listeners.push(ai);let bi=await Fi[O].result;return ai.onlisten&&ai.onlisten(),{state:bi.state,unlisten:qi}}Fi[O]={result:mo`listen ${mo.unsafe('"'+O.replace(/"/g,'""')+'"')}`,listeners:[ai]};let no=await Fi[O].result;return ai.onlisten&&ai.onlisten(),{state:no.state,unlisten:qi};async function qi(){if(O in Fi===!1)return;if(Fi[O].listeners=Fi[O].listeners.filter((bi)=>bi!==ai),Fi[O].listeners.length)return;return delete Fi[O],mo`unlisten ${mo.unsafe('"'+O.replace(/"/g,'""')+'"')}`}}async function z(O,k){return await R`select pg_notify(${O}, ${""+k})`}async function b(){let O=Jn(),k=$.length?$.shift():await new Promise((mo)=>{x.push({reserve:mo}),f.length&&Ei(f.shift())});u(k,m),k.reserved=()=>O.length?k.execute(O.shift()):u(k,m),k.reserved.release=!0;let Yi=K(ai);return Yi.release=()=>{k.reserved=null,lo(k)},Yi;function ai(mo){k.queue===A?O.push(mo):k.execute(mo)||u(k,A)}}async function M(O,k){!k&&(k=O,O="");let Yi=Jn(),ai=0,mo,Fi=null;try{return await R.unsafe("begin "+O.replace(/[^a-z ]/ig,""),[],{onexecute:no}).execute(),await Promise.race([yi(mo,k),new Promise((qi,bi)=>mo.onclose=bi)])}catch(qi){throw qi}async function yi(qi,bi,zo){let Di=K(fo);Di.savepoint=Yp,Di.prepare=(ji)=>Fi=ji.replace(/[^a-z0-9$-_. ]/gi);let Qn,uo;zo&&await Di`savepoint ${Di(zo)}`;try{if(uo=await new Promise((ji,Vn)=>{let Pn=bi(Di);Promise.resolve(Array.isArray(Pn)?Promise.all(Pn):Pn).then(ji,Vn)}),Qn)throw Qn}catch(ji){throw await(zo?Di`rollback to ${Di(zo)}`:Di`rollback`),ji instanceof Ox&&ji.code==="25P02"&&Qn||ji}if(!zo)Fi?await Di`prepare transaction '${Di.unsafe(Fi)}'`:await Di`commit`;return uo;function Yp(ji,Vn){if(ji&&Array.isArray(ji.raw))return Yp((Pn)=>Pn.apply(Pn,arguments));return arguments.length===1&&(Vn=ji,ji=null),yi(qi,Vn,"s"+ai+++(ji?"_"+ji:""))}function fo(ji){ji.catch((Vn)=>Qn||(Qn=Vn)),qi.queue===A?Yi.push(ji):qi.execute(ji)||u(qi,A)}}function no(qi){mo=qi,u(qi,m),qi.reserved=()=>Yi.length?qi.execute(Yi.shift()):u(qi,m)}}function u(O,k){return O.queue.remove(O),k.push(O),O.queue=k,k===$?O.idleTimer.start():O.idleTimer.cancel(),O}function E(O){return new en(O,3802)}function S(O,k){if(!Array.isArray(O))return S(Array.from(arguments));return new en(O,k||(O.length?A1(O)||25:0),n.shared.typeArrayMap)}function y(O){if(c)return O.reject(xo.connection("CONNECTION_ENDED",n,n));if($.length)return l($.shift(),O);if(f.length)return Ei(f.shift(),O);J.length?l(J.shift(),O):x.push(O)}function l(O,k){return O.execute(k)?u(O,J):u(O,A)}function Q(O){return new Promise((k,Yi)=>{O.state?O.active?LJ(n).cancel(O.state,k,Yi):O.cancelled={resolve:k,reject:Yi}:(x.remove(O),O.cancelled=!0,O.reject(xo.generic("57014","canceling statement due to user request")),k())})}async function Ti({timeout:O=null}={}){if(c)return c;await 1;let k;return c=Promise.race([new Promise((Yi)=>O!==null&&(k=setTimeout(mi,O*1000,Yi))),Promise.all(Y.map((Yi)=>Yi.end()).concat(H.sql?H.sql.end({timeout:0}):[],p.sql?p.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(k))}async function q(){await Promise.all(Y.map((O)=>O.end()))}async function mi(O){await Promise.all(Y.map((k)=>k.terminate()));while(x.length)x.shift().reject(xo.connection("CONNECTION_DESTROYED",n));O()}function Ei(O,k){return u(O,T),O.connect(k),O}function To(O){u(O,F)}function lo(O){if(x.length===0)return u(O,$);let k=Math.ceil(x.length/(T.length+1)),Yi=!0;while(Yi&&x.length&&k-- >0){let ai=x.shift();if(ai.reserve)return ai.reserve(O);Yi=O.execute(ai)}Yi?u(O,J):u(O,A)}function ip(O,k){u(O,f),O.reserved=null,O.onclose&&(O.onclose(k),O.onclose=null),n.onclose&&n.onclose(O.id),x.length&&Ei(O,x.shift())}}function EE(i,o){if(i&&i.shared)return i;let n=process.env,p=(!i||typeof i==="string"?o:i)||{},{url:c,multihost:x}=yE(i),T=[...c.searchParams].reduce((A,[X,Y])=>(A[X]=Y,A),{}),m=p.hostname||p.host||x||c.hostname||n.PGHOST||"localhost",f=p.port||c.port||n.PGPORT||5432,F=p.user||p.username||c.username||n.PGUSERNAME||n.PGUSER||DE();p.no_prepare&&(p.prepare=!1),T.sslmode&&(T.ssl=T.sslmode,delete T.sslmode),"timeout"in p&&(console.log("The timeout option is deprecated, use idle_timeout instead"),p.idle_timeout=p.timeout),T.sslrootcert==="system"&&(T.ssl="verify-full");let $=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],J={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:LE,max_pipeline:100,backoff:_E,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(m)?m:m.split(",").map((A)=>A.split(":")[0]),port:Array.isArray(f)?f:m.split(",").map((A)=>parseInt(A.split(":")[1]||f)),path:p.path||m.indexOf("/")>-1&&m+"/.s.PGSQL."+f,database:p.database||p.db||(c.pathname||"").slice(1)||n.PGDATABASE||F,user:F,pass:p.pass||p.password||c.password||n.PGPASSWORD||"",...Object.entries(J).reduce((A,[X,Y])=>{let R=X in p?p[X]:(X in T)?T[X]==="disable"||T[X]==="false"?!1:T[X]:n["PG"+X.toUpperCase()]||Y;return A[X]=typeof R==="string"&&$.includes(X)?+R:R,A},{}),connection:{application_name:"postgres.js",...p.connection,...Object.entries(T).reduce((A,[X,Y])=>((X in J)||(A[X]=Y),A),{})},types:p.types||{},target_session_attrs:OE(p,c,n),onnotice:p.onnotice,onnotify:p.onnotify,onclose:p.onclose,onparameter:p.onparameter,socket:p.socket,transform:CE(p.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...cY(p.types)}}function OE(i,o,n){let p=i.target_session_attrs||o.searchParams.get("target_session_attrs")||n.PGTARGETSESSIONATTRS;if(!p||["read-write","read-only","primary","standby","prefer-standby"].includes(p))return p;throw new Error("target_session_attrs "+p+" is not supported")}function _E(i){return(0.5+Math.random()/2)*Math.min(3**i/100,20)}function LE(){return 60*(30+Math.random()*30)}function CE(i){return{undefined:i.undefined,column:{from:typeof i.column==="function"?i.column:i.column&&i.column.from,to:i.column&&i.column.to},value:{from:typeof i.value==="function"?i.value:i.value&&i.value.from,to:i.value&&i.value.to},row:{from:typeof i.row==="function"?i.row:i.row&&i.row.from,to:i.row&&i.row.to}}}function yE(i){if(!i||typeof i!=="string")return{url:{searchParams:new Map}};let o=i;o=o.slice(o.indexOf("://")+3).split(/[?/]/)[0],o=decodeURIComponent(o.slice(o.indexOf("@")+1));let n=new URL(i.replace(o,o.split(",")[0]));return{url:{username:decodeURIComponent(n.username),password:decodeURIComponent(n.password),host:n.host,hostname:n.hostname,port:n.port,pathname:n.pathname,searchParams:n.searchParams},multihost:o.indexOf(",")>-1&&o}}function DE(){try{return VE.userInfo().username}catch(i){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}class ti{static[w]="SelectionProxyHandler";config;constructor(i){this.config={...i}}get(i,o){if(o==="_")return{...i._,selectedFields:new Proxy(i._.selectedFields,this)};if(o===Ni)return{...i[Ni],selectedFields:new Proxy(i[Ni].selectedFields,this)};if(typeof o==="symbol")return i[o];let p=(Z(i,wo)?i._.selectedFields:Z(i,ro)?i[Ni].selectedFields:i)[o];if(Z(p,N.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!p.isSelectionField)return p.sql;let c=p.clone();return c.isSelectionField=!0,c}if(Z(p,N)){if(this.config.sqlBehavior==="sql")return p;throw new Error(`You tried to reference "${o}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(Z(p,Li)){if(this.config.alias)return new Proxy(p,new Xx(new Proxy(p.table,new NT(this.config.alias,this.config.replaceOriginalName??!1))));return p}if(typeof p!=="object"||p===null)return p;return new Proxy(p,new ti(this.config))}}class H1 extends jo{constructor(i,o,n,p){super();this.session=o,this.dialect=n,this.config={table:i,withList:p}}static[w]="PgDelete";config;where(i){return this.config.where=i,this}returning(i=this.config.table[B.Symbol.Columns]){return this.config.returningFields=i,this.config.returning=Un(i),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:i,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(i){return Ci.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,i,!0)})}prepare(i){return this._prepare(i)}authToken;setToken(i){return this.authToken=i,this}execute=(i)=>{return Ci.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(i,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new ti({alias:Ro(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}function IE(i){return(i.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((n)=>n.toLowerCase()).join("_")}function BE(i){return(i.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((n,p,c)=>{let x=c===0?p.toLowerCase():`${p[0].toUpperCase()}${p.slice(1)}`;return n+x},"")}function NE(i){return i}class DJ{static[w]="CasingCache";cache={};cachedTables={};convert;constructor(i){this.convert=i==="snake_case"?IE:i==="camelCase"?BE:NE}getColumnCasing(i){if(!i.keyAsName)return i.name;let o=i.table[B.Symbol.Schema]??"public",n=i.table[B.Symbol.OriginalName],p=`${o}.${n}.${i.name}`;if(!this.cache[p])this.cacheTable(i.table);return this.cache[p]}cacheTable(i){let o=i[B.Symbol.Schema]??"public",n=i[B.Symbol.OriginalName],p=`${o}.${n}`;if(!this.cachedTables[p]){for(let c of Object.values(i[B.Symbol.Columns])){let x=`${p}.${c.name}`;this.cache[x]=this.convert(c.name)}this.cachedTables[p]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class pm extends ro{static[w]="PgViewBase"}class Qc{static[w]="PgDialect";casing;constructor(i){this.casing=new DJ(i?.casing)}async migrate(i,o,n){let p=typeof n==="string"?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",c=typeof n==="string"?"drizzle":n.migrationsSchema??"drizzle",x=W`
|
|
120
120
|
CREATE TABLE IF NOT EXISTS ${W.identifier(c)}.${W.identifier(p)} (
|
|
121
121
|
id SERIAL PRIMARY KEY,
|
|
122
122
|
hash text NOT NULL,
|
|
123
123
|
created_at bigint
|
|
124
124
|
)
|
|
125
|
-
`;await o.execute(W`CREATE SCHEMA IF NOT EXISTS ${W.identifier(c)}`),await o.execute(x);let m=(await o.all(W`select id, hash, created_at from ${W.identifier(c)}.${W.identifier(p)} order by created_at desc limit 1`))[0];await o.transaction(async(f)=>{for await(let F of i)if(!m||Number(m.created_at)<F.folderMillis){for(let $ of F.sql)await f.execute(W.raw($));await f.execute(W`insert into ${W.identifier(c)}.${W.identifier(p)} ("hash", "created_at") values(${F.hash}, ${F.folderMillis})`)}})}escapeName(i){return`"${i}"`}escapeParam(i){return`$${i+1}`}escapeString(i){return`'${i.replace(/'/g,"''")}'`}buildWithCTE(i){if(!i?.length)return;let o=[W`with `];for(let[n,p]of i.entries())if(o.push(W`${W.identifier(p._.alias)} as (${p._.sql})`),n<i.length-1)o.push(W`, `);return o.push(W` `),W.join(o)}buildDeleteQuery({table:i,where:o,returning:n,withList:p}){let c=this.buildWithCTE(p),x=n?W` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,T=o?W` where ${o}`:void 0;return W`${c}delete from ${i}${T}${x}`}buildUpdateSet(i,o){let n=i[B.Symbol.Columns],p=Object.keys(n).filter((x)=>o[x]!==void 0||n[x]?.onUpdateFn!==void 0),c=p.length;return W.join(p.flatMap((x,T)=>{let m=n[x],f=o[x]??W.param(m.onUpdateFn(),m),F=W`${W.identifier(this.casing.getColumnCasing(m))} = ${f}`;if(T<c-1)return[F,W.raw(", ")];return[F]}))}buildUpdateQuery({table:i,set:o,where:n,returning:p,withList:c,from:x,joins:T}){let m=this.buildWithCTE(c),f=i[Mo.Symbol.Name],F=i[Mo.Symbol.Schema],$=i[Mo.Symbol.OriginalName],J=f===$?void 0:f,A=W`${F?W`${W.identifier(F)}.`:void 0}${W.identifier($)}${J&&W` ${W.identifier(J)}`}`,X=this.buildUpdateSet(i,o),Y=x&&W.join([W.raw(" from "),this.buildFromTable(x)]),R=this.buildJoins(T),K=p?W` returning ${this.buildSelection(p,{isSingleTable:!x})}`:void 0,H=n?W` where ${n}`:void 0;return W`${m}update ${A} set ${X}${Y}${R}${H}${K}`}buildSelection(i,{isSingleTable:o=!1}={}){let n=i.length,p=i.flatMap(({field:c},x)=>{let T=[];if(Z(c,N.Aliased)&&c.isSelectionField)T.push(W.identifier(c.fieldAlias));else if(Z(c,N.Aliased)||Z(c,N)){let m=Z(c,N.Aliased)?c.sql:c;if(o)T.push(new N(m.queryChunks.map((f)=>{if(Z(f,_))return W.identifier(this.casing.getColumnCasing(f));return f})));else T.push(m);if(Z(c,N.Aliased))T.push(W` as ${W.identifier(c.fieldAlias)}`)}else if(Z(c,Li))if(o)T.push(W.identifier(this.casing.getColumnCasing(c)));else T.push(c);if(x<n-1)T.push(W`, `);return T});return W.join(p)}buildJoins(i){if(!i||i.length===0)return;let o=[];for(let[n,p]of i.entries()){if(n===0)o.push(W` `);let c=p.table,x=p.lateral?W` lateral`:void 0;if(Z(c,Mo)){let T=c[Mo.Symbol.Name],m=c[Mo.Symbol.Schema],f=c[Mo.Symbol.OriginalName],F=T===f?void 0:p.alias;o.push(W`${W.raw(p.joinType)} join${x} ${m?W`${W.identifier(m)}.`:void 0}${W.identifier(f)}${F&&W` ${W.identifier(F)}`} on ${p.on}`)}else if(Z(c,ro)){let T=c[Ni].name,m=c[Ni].schema,f=c[Ni].originalName,F=T===f?void 0:p.alias;o.push(W`${W.raw(p.joinType)} join${x} ${m?W`${W.identifier(m)}.`:void 0}${W.identifier(f)}${F&&W` ${W.identifier(F)}`} on ${p.on}`)}else o.push(W`${W.raw(p.joinType)} join${x} ${c} on ${p.on}`);if(n<i.length-1)o.push(W` `)}return W.join(o)}buildFromTable(i){if(Z(i,B)&&i[B.Symbol.IsAlias]){let o=W`${W.identifier(i[B.Symbol.OriginalName])}`;if(i[B.Symbol.Schema])o=W`${W.identifier(i[B.Symbol.Schema])}.${o}`;return W`${o} ${W.identifier(i[B.Symbol.Name])}`}return i}buildSelectQuery({withList:i,fields:o,fieldsFlat:n,where:p,having:c,table:x,joins:T,orderBy:m,groupBy:f,limit:F,offset:$,lockingClause:J,distinct:A,setOperators:X}){let Y=n??Un(o);for(let mi of Y)if(Z(mi.field,Li)&&Ro(mi.field.table)!==(Z(x,wo)?x._.alias:Z(x,pm)?x[Ni].name:Z(x,N)?void 0:Ro(x))&&!((Ei)=>T?.some(({alias:To})=>To===(Ei[B.Symbol.IsAlias]?Ro(Ei):Ei[B.Symbol.BaseName])))(mi.field.table)){let Ei=Ro(mi.field.table);throw new Error(`Your "${mi.path.join("->")}" field references a column "${Ei}"."${mi.field.name}", but the table "${Ei}" is not part of the query! Did you forget to join it?`)}let R=!T||T.length===0,K=this.buildWithCTE(i),H;if(A)H=A===!0?W` distinct`:W` distinct on (${W.join(A.on,W`, `)})`;let z=this.buildSelection(Y,{isSingleTable:R}),b=this.buildFromTable(x),M=this.buildJoins(T),u=p?W` where ${p}`:void 0,E=c?W` having ${c}`:void 0,S;if(m&&m.length>0)S=W` order by ${W.join(m,W`, `)}`;let y;if(f&&f.length>0)y=W` group by ${W.join(f,W`, `)}`;let l=typeof F==="object"||typeof F==="number"&&F>=0?W` limit ${F}`:void 0,Q=$?W` offset ${$}`:void 0,Ti=W.empty();if(J){let mi=W` for ${W.raw(J.strength)}`;if(J.config.of)mi.append(W` of ${W.join(Array.isArray(J.config.of)?J.config.of:[J.config.of],W`, `)}`);if(J.config.noWait)mi.append(W` no wait`);else if(J.config.skipLocked)mi.append(W` skip locked`);Ti.append(mi)}let q=W`${K}select${H} ${z} from ${b}${M}${u}${y}${E}${S}${l}${Q}${Ti}`;if(X.length>0)return this.buildSetOperations(q,X);return q}buildSetOperations(i,o){let[n,...p]=o;if(!n)throw new Error("Cannot pass undefined values to any set operator");if(p.length===0)return this.buildSetOperationQuery({leftSelect:i,setOperator:n});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:i,setOperator:n}),p)}buildSetOperationQuery({leftSelect:i,setOperator:{type:o,isAll:n,rightSelect:p,limit:c,orderBy:x,offset:T}}){let m=W`(${i.getSQL()}) `,f=W`(${p.getSQL()})`,F;if(x&&x.length>0){let X=[];for(let Y of x)if(Z(Y,_))X.push(W.identifier(Y.name));else if(Z(Y,N)){for(let R=0;R<Y.queryChunks.length;R++){let K=Y.queryChunks[R];if(Z(K,_))Y.queryChunks[R]=W.identifier(K.name)}X.push(W`${Y}`)}else X.push(W`${Y}`);F=W` order by ${W.join(X,W`, `)} `}let $=typeof c==="object"||typeof c==="number"&&c>=0?W` limit ${c}`:void 0,J=W.raw(`${o} ${n?"all ":""}`),A=T?W` offset ${T}`:void 0;return W`${m}${J}${f}${F}${$}${A}`}buildInsertQuery({table:i,values:o,onConflict:n,returning:p,withList:c,select:x,overridingSystemValue_:T}){let m=[],f=i[B.Symbol.Columns],F=Object.entries(f).filter(([K,H])=>!H.shouldDisableInsert()),$=F.map(([,K])=>W.identifier(this.casing.getColumnCasing(K)));if(x){let K=o;if(Z(K,N))m.push(K);else m.push(K.getSQL())}else{let K=o;m.push(W.raw("values "));for(let[H,z]of K.entries()){let b=[];for(let[M,u]of F){let E=z[M];if(E===void 0||Z(E,Tn)&&E.value===void 0)if(u.defaultFn!==void 0){let S=u.defaultFn(),y=Z(S,N)?S:W.param(S,u);b.push(y)}else if(!u.default&&u.onUpdateFn!==void 0){let S=u.onUpdateFn(),y=Z(S,N)?S:W.param(S,u);b.push(y)}else b.push(W`default`);else b.push(E)}if(m.push(b),H<K.length-1)m.push(W`, `)}}let J=this.buildWithCTE(c),A=W.join(m),X=p?W` returning ${this.buildSelection(p,{isSingleTable:!0})}`:void 0,Y=n?W` on conflict ${n}`:void 0,R=T===!0?W`overriding system value `:void 0;return W`${J}insert into ${i} ${$} ${R}${A}${Y}${X}`}buildRefreshMaterializedViewQuery({view:i,concurrently:o,withNoData:n}){let p=o?W` concurrently`:void 0,c=n?W` with no data`:void 0;return W`refresh materialized view${p} ${i}${c}`}prepareTyping(i){if(Z(i,E0)||Z(i,S0))return"json";else if(Z(i,O0))return"decimal";else if(Z(i,_0))return"time";else if(Z(i,L0)||Z(i,C0))return"timestamp";else if(Z(i,u0)||Z(i,Q0))return"date";else if(Z(i,y0))return"uuid";else return"none"}sqlToQuery(i,o){return i.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:o})}buildRelationalQueryWithoutPK({fullSchema:i,schema:o,tableNamesMap:n,table:p,tableConfig:c,queryConfig:x,tableAlias:T,nestedQueryRelation:m,joinOn:f}){let F=[],$,J,A=[],X,Y=[];if(x===!0)F=Object.entries(c.columns).map(([H,z])=>({dbKey:z.name,tsKey:H,field:tn(z,T),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let K=Object.fromEntries(Object.entries(c.columns).map(([E,S])=>[E,tn(S,T)]));if(x.where){let E=typeof x.where==="function"?x.where(K,d7()):x.where;X=E&&bT(E,T)}let H=[],z=[];if(x.columns){let E=!1;for(let[S,y]of Object.entries(x.columns)){if(y===void 0)continue;if(S in c.columns){if(!E&&y===!0)E=!0;z.push(S)}}if(z.length>0)z=E?z.filter((S)=>x.columns?.[S]===!0):Object.keys(c.columns).filter((S)=>!z.includes(S))}else z=Object.keys(c.columns);for(let E of z){let S=c.columns[E];H.push({tsKey:E,value:S})}let b=[];if(x.with)b=Object.entries(x.with).filter((E)=>!!E[1]).map(([E,S])=>({tsKey:E,queryConfig:S,relation:c.relations[E]}));let M;if(x.extras){M=typeof x.extras==="function"?x.extras(K,{sql:W}):x.extras;for(let[E,S]of Object.entries(M))H.push({tsKey:E,value:w$(S,T)})}for(let{tsKey:E,value:S}of H)F.push({dbKey:Z(S,N.Aliased)?S.fieldAlias:c.columns[E].name,tsKey:E,field:Z(S,Li)?tn(S,T):S,relationTableTsKey:void 0,isJson:!1,selection:[]});let u=typeof x.orderBy==="function"?x.orderBy(K,r7()):x.orderBy??[];if(!Array.isArray(u))u=[u];A=u.map((E)=>{if(Z(E,Li))return tn(E,T);return bT(E,T)}),$=x.limit,J=x.offset;for(let{tsKey:E,queryConfig:S,relation:y}of b){let l=iW(o,n,y),Q=vc(y.referencedTable),Ti=n[Q],q=`${T}_${E}`,mi=wc(...l.fields.map((lo,ip)=>dn(tn(l.references[ip],q),tn(lo,T)))),Ei=this.buildRelationalQueryWithoutPK({fullSchema:i,schema:o,tableNamesMap:n,table:i[Ti],tableConfig:o[Ti],queryConfig:Z(y,bp)?S===!0?{limit:1}:{...S,limit:1}:S,tableAlias:q,joinOn:mi,nestedQueryRelation:y}),To=W`${W.identifier(q)}.${W.identifier("data")}`.as(E);Y.push({on:W`true`,table:new wo(Ei.sql,{},q),alias:q,joinType:"left",lateral:!0}),F.push({dbKey:E,tsKey:E,field:To,relationTableTsKey:Ti,isJson:!0,selection:Ei.selection})}}if(F.length===0)throw new Z0({message:`No fields selected for table "${c.tsName}" ("${T}")`});let R;if(X=wc(f,X),m){let K=W`json_build_array(${W.join(F.map(({field:b,tsKey:M,isJson:u})=>u?W`${W.identifier(`${T}_${M}`)}.${W.identifier("data")}`:Z(b,N.Aliased)?b.sql:b),W`, `)})`;if(Z(m,lT))K=W`coalesce(json_agg(${K}${A.length>0?W` order by ${W.join(A,W`, `)}`:void 0}), '[]'::json)`;let H=[{dbKey:"data",tsKey:"data",field:K.as("data"),isJson:!0,relationTableTsKey:c.tsName,selection:F}];if($!==void 0||J!==void 0||A.length>0)R=this.buildSelectQuery({table:U0(p,T),fields:{},fieldsFlat:[{path:[],field:W.raw("*")}],where:X,limit:$,offset:J,orderBy:A,setOperators:[]}),X=void 0,$=void 0,J=void 0,A=[];else R=U0(p,T);R=this.buildSelectQuery({table:Z(R,Mo)?R:new wo(R,{},T),fields:{},fieldsFlat:H.map(({field:b})=>({path:[],field:Z(b,Li)?tn(b,T):b})),joins:Y,where:X,limit:$,offset:J,orderBy:A,setOperators:[]})}else R=this.buildSelectQuery({table:U0(p,T),fields:{},fieldsFlat:F.map(({field:K})=>({path:[],field:Z(K,Li)?tn(K,T):K})),joins:Y,where:X,limit:$,offset:J,orderBy:A,setOperators:[]});return{tableTsKey:c.tsName,sql:R,selection:F}}}class IJ{static[w]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class ao{static[w]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(i){if(this.fields=i.fields,this.session=i.session,this.dialect=i.dialect,i.withList)this.withList=i.withList;this.distinct=i.distinct}authToken;setToken(i){return this.authToken=i,this}from(i){let o=!!this.fields,n=i,p;if(this.fields)p=this.fields;else if(Z(n,wo))p=Object.fromEntries(Object.keys(n._.selectedFields).map((c)=>[c,n[c]]));else if(Z(n,pm))p=n[Ni].selectedFields;else if(Z(n,N))p={};else p=d3(n);return new BJ({table:n,fields:p,isPartialSelect:o,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class WY extends IJ{static[w]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:i,fields:o,isPartialSelect:n,session:p,dialect:c,withList:x,distinct:T}){super();this.config={withList:x,table:i,fields:{...o},distinct:T,setOperators:[]},this.isPartialSelect=n,this.session=p,this.dialect=c,this._={selectedFields:o},this.tableName=Ap(i),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(i){return(o,n)=>{let p=this.tableName,c=Ap(o);if(typeof c==="string"&&this.config.joins?.some((x)=>x.alias===c))throw new Error(`Alias "${c}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof p==="string")this.config.fields={[p]:this.config.fields};if(typeof c==="string"&&!Z(o,N)){let x=Z(o,wo)?o._.selectedFields:Z(o,ro)?o[Ni].selectedFields:o[B.Symbol.Columns];this.config.fields[c]=x}}if(typeof n==="function")n=n(new Proxy(this.config.fields,new ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:n,table:o,joinType:i,alias:c}),typeof c==="string")switch(i){case"left":{this.joinsNotNullableMap[c]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([x])=>[x,!1])),this.joinsNotNullableMap[c]=!0;break}case"inner":{this.joinsNotNullableMap[c]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([x])=>[x,!1])),this.joinsNotNullableMap[c]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(i,o){return(n)=>{let p=typeof n==="function"?n(bE()):n;if(!jT(this.getSelectedFields(),p.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:i,isAll:o,rightSelect:p}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(i){return this.config.setOperators.push(...i),this}where(i){if(typeof i==="function")i=i(new Proxy(this.config.fields,new ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=i,this}having(i){if(typeof i==="function")i=i(new Proxy(this.config.fields,new ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=i,this}groupBy(...i){if(typeof i[0]==="function"){let o=i[0](new Proxy(this.config.fields,new ti({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(o)?o:[o]}else this.config.groupBy=i;return this}orderBy(...i){if(typeof i[0]==="function"){let o=i[0](new Proxy(this.config.fields,new ti({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),n=Array.isArray(o)?o:[o];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=n;else this.config.orderBy=n}else{let o=i;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=o;else this.config.orderBy=o}return this}limit(i){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=i;else this.config.limit=i;return this}offset(i){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=i;else this.config.offset=i;return this}for(i,o={}){return this.config.lockingClause={strength:i,config:o},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:i,...o}=this.dialect.sqlToQuery(this.getSQL());return o}as(i){return new Proxy(new wo(this.getSQL(),this.config.fields,i),new ti({alias:i,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new ti({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class BJ extends WY{static[w]="PgSelect";_prepare(i){let{session:o,config:n,dialect:p,joinsNotNullableMap:c,authToken:x}=this;if(!o)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Ci.startActiveSpan("drizzle.prepareQuery",()=>{let T=Un(n.fields),m=o.prepareQuery(p.sqlToQuery(this.getSQL()),T,i,!0);return m.joinsNotNullableMap=c,m.setToken(x)})}prepare(i){return this._prepare(i)}authToken;setToken(i){return this.authToken=i,this}execute=(i)=>{return Ci.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(i,this.authToken)})}}t3(BJ,[jo]);function Cx(i,o){return(n,p,...c)=>{let x=[p,...c].map((T)=>({type:i,isAll:o,rightSelect:T}));for(let T of x)if(!jT(n.getSelectedFields(),T.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return n.addSetOperators(x)}}var bE=()=>({union:jE,unionAll:PE,intersect:aE,intersectAll:lE,except:qE,exceptAll:kE}),jE=Cx("union",!1),PE=Cx("union",!0),aE=Cx("intersect",!1),lE=Cx("intersect",!0),qE=Cx("except",!1),kE=Cx("except",!0);class cm{static[w]="PgQueryBuilder";dialect;dialectConfig;constructor(i){this.dialect=Z(i,Qc)?i:void 0,this.dialectConfig=Z(i,Qc)?void 0:i}$with=(i,o)=>{let n=this;return{as:(c)=>{if(typeof c==="function")c=c(n);return new Proxy(new IT(c.getSQL(),o??("getSelectedFields"in c?c.getSelectedFields()??{}:{}),i,!0),new ti({alias:i,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...i){let o=this;function n(x){return new ao({fields:x??void 0,session:void 0,dialect:o.getDialect(),withList:i})}function p(x){return new ao({fields:x??void 0,session:void 0,dialect:o.getDialect(),distinct:!0})}function c(x,T){return new ao({fields:T??void 0,session:void 0,dialect:o.getDialect(),distinct:{on:x}})}return{select:n,selectDistinct:p,selectDistinctOn:c}}select(i){return new ao({fields:i??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(i){return new ao({fields:i??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(i,o){return new ao({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:i}})}getDialect(){if(!this.dialect)this.dialect=new Qc(this.dialectConfig);return this.dialect}}class U1{constructor(i,o,n,p,c){this.table=i,this.session=o,this.dialect=n,this.withList=p,this.overridingSystemValue_=c}static[w]="PgInsertBuilder";authToken;setToken(i){return this.authToken=i,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(i){if(i=Array.isArray(i)?i:[i],i.length===0)throw new Error("values() must be called with at least one value");let o=i.map((n)=>{let p={},c=this.table[B.Symbol.Columns];for(let x of Object.keys(n)){let T=n[x];p[x]=Z(T,N)?T:new Tn(T,c[x])}return p});return new NJ(this.table,o,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(i){let o=typeof i==="function"?i(new cm):i;if(!Z(o,N)&&!jT(this.table[K0],o._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new NJ(this.table,o,this.session,this.dialect,this.withList,!0)}}class NJ extends jo{constructor(i,o,n,p,c,x,T){super();this.session=n,this.dialect=p,this.config={table:i,values:o,withList:c,select:x,overridingSystemValue_:T}}static[w]="PgInsert";config;returning(i=this.config.table[B.Symbol.Columns]){return this.config.returningFields=i,this.config.returning=Un(i),this}onConflictDoNothing(i={}){if(i.target===void 0)this.config.onConflict=W`do nothing`;else{let o="";o=Array.isArray(i.target)?i.target.map((p)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(p))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(i.target));let n=i.where?W` where ${i.where}`:void 0;this.config.onConflict=W`(${W.raw(o)})${n} do nothing`}return this}onConflictDoUpdate(i){if(i.where&&(i.targetWhere||i.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let o=i.where?W` where ${i.where}`:void 0,n=i.targetWhere?W` where ${i.targetWhere}`:void 0,p=i.setWhere?W` where ${i.setWhere}`:void 0,c=this.dialect.buildUpdateSet(this.config.table,z0(this.config.table,i.set)),x="";return x=Array.isArray(i.target)?i.target.map((T)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(T))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(i.target)),this.config.onConflict=W`(${W.raw(x)})${n} do update set ${c}${o}${p}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:i,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(i){return Ci.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,i,!0)})}prepare(i){return this._prepare(i)}authToken;setToken(i){return this.authToken=i,this}execute=(i)=>{return Ci.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(i,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new ti({alias:Ro(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class bJ extends jo{constructor(i,o,n){super();this.session=o,this.dialect=n,this.config={view:i}}static[w]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:i,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(i){return Ci.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,i,!0)})}prepare(i){return this._prepare(i)}authToken;setToken(i){return this.authToken=i,this}execute=(i)=>{return Ci.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(i,this.authToken)})}}class Z1{constructor(i,o,n,p){this.table=i,this.session=o,this.dialect=n,this.withList=p}static[w]="PgUpdateBuilder";authToken;setToken(i){return this.authToken=i,this}set(i){return new RY(this.table,z0(this.table,i),this.session,this.dialect,this.withList).setToken(this.authToken)}}class RY extends jo{constructor(i,o,n,p,c){super();this.session=n,this.dialect=p,this.config={set:o,table:i,withList:c,joins:[]},this.tableName=Ap(i),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[w]="PgUpdate";config;tableName;joinsNotNullableMap;from(i){let o=i,n=Ap(o);if(typeof n==="string")this.joinsNotNullableMap[n]=!0;return this.config.from=o,this}getTableLikeFields(i){if(Z(i,Mo))return i[B.Symbol.Columns];else if(Z(i,wo))return i._.selectedFields;return i[Ni].selectedFields}createJoin(i){return(o,n)=>{let p=Ap(o);if(typeof p==="string"&&this.config.joins.some((c)=>c.alias===p))throw new Error(`Alias "${p}" is already used in this query`);if(typeof n==="function"){let c=this.config.from&&!Z(this.config.from,N)?this.getTableLikeFields(this.config.from):void 0;n=n(new Proxy(this.config.table[B.Symbol.Columns],new ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),c&&new Proxy(c,new ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:n,table:o,joinType:i,alias:p}),typeof p==="string")switch(i){case"left":{this.joinsNotNullableMap[p]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([c])=>[c,!1])),this.joinsNotNullableMap[p]=!0;break}case"inner":{this.joinsNotNullableMap[p]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([c])=>[c,!1])),this.joinsNotNullableMap[p]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(i){return this.config.where=i,this}returning(i){if(!i){if(i=Object.assign({},this.config.table[B.Symbol.Columns]),this.config.from){let o=Ap(this.config.from);if(typeof o==="string"&&this.config.from&&!Z(this.config.from,N)){let n=this.getTableLikeFields(this.config.from);i[o]=n}for(let n of this.config.joins){let p=Ap(n.table);if(typeof p==="string"&&!Z(n.table,N)){let c=this.getTableLikeFields(n.table);i[p]=c}}}}return this.config.returningFields=i,this.config.returning=Un(i),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:i,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(i){let o=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,i,!0);return o.joinsNotNullableMap=this.joinsNotNullableMap,o}prepare(i){return this._prepare(i)}authToken;setToken(i){return this.authToken=i,this}execute=(i)=>{return this._prepare().execute(i,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new ti({alias:Ro(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class xm extends N{constructor(i){super(xm.buildEmbeddedCount(i.source,i.filters).queryChunks);this.params=i,this.mapWith(Number),this.session=i.session,this.sql=xm.buildCount(i.source,i.filters)}sql;token;static[w]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(i,o){return W`(select count(*) from ${i}${W.raw(" where ").if(o)}${o})`}static buildCount(i,o){return W`select count(*) as count from ${i}${W.raw(" where ").if(o)}${o};`}setToken(i){return this.token=i,this}then(i,o){return Promise.resolve(this.session.count(this.sql,this.token)).then(i,o)}catch(i){return this.then(void 0,i)}finally(i){return this.then((o)=>{return i?.(),o},(o)=>{throw i?.(),o})}}class PJ{constructor(i,o,n,p,c,x,T){this.fullSchema=i,this.schema=o,this.tableNamesMap=n,this.table=p,this.tableConfig=c,this.dialect=x,this.session=T}static[w]="PgRelationalQueryBuilder";findMany(i){return new jJ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,i?i:{},"many")}findFirst(i){return new jJ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,i?{...i,limit:1}:{limit:1},"first")}}class jJ extends jo{constructor(i,o,n,p,c,x,T,m,f){super();this.fullSchema=i,this.schema=o,this.tableNamesMap=n,this.table=p,this.tableConfig=c,this.dialect=x,this.session=T,this.config=m,this.mode=f}static[w]="PgRelationalQuery";_prepare(i){return Ci.startActiveSpan("drizzle.prepareQuery",()=>{let{query:o,builtQuery:n}=this._toSQL();return this.session.prepareQuery(n,void 0,i,!0,(p,c)=>{let x=p.map((T)=>D0(this.schema,this.tableConfig,T,o.selection,c));if(this.mode==="first")return x[0];return x})})}prepare(i){return this._prepare(i)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let i=this._getQuery(),o=this.dialect.sqlToQuery(i.sql);return{query:i,builtQuery:o}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(i){return this.authToken=i,this}execute(){return Ci.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class aJ extends jo{constructor(i,o,n,p){super();this.execute=i,this.sql=o,this.query=n,this.mapBatchResult=p}static[w]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(i,o){return o?this.mapBatchResult(i):i}_prepare(){return this}isResponseInArrayMode(){return!1}}class Tm{constructor(i,o,n){if(this.dialect=i,this.session=o,this._=n?{schema:n.schema,fullSchema:n.fullSchema,tableNamesMap:n.tableNamesMap,session:o}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:o},this.query={},this._.schema)for(let[p,c]of Object.entries(this._.schema))this.query[p]=new PJ(n.fullSchema,this._.schema,this._.tableNamesMap,n.fullSchema[p],c,i,o)}static[w]="PgDatabase";query;$with=(i,o)=>{let n=this;return{as:(c)=>{if(typeof c==="function")c=c(new cm(n.dialect));return new Proxy(new IT(c.getSQL(),o??("getSelectedFields"in c?c.getSelectedFields()??{}:{}),i,!0),new ti({alias:i,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(i,o){return new xm({source:i,filters:o,session:this.session})}with(...i){let o=this;function n(f){return new ao({fields:f??void 0,session:o.session,dialect:o.dialect,withList:i})}function p(f){return new ao({fields:f??void 0,session:o.session,dialect:o.dialect,withList:i,distinct:!0})}function c(f,F){return new ao({fields:F??void 0,session:o.session,dialect:o.dialect,withList:i,distinct:{on:f}})}function x(f){return new Z1(f,o.session,o.dialect,i)}function T(f){return new U1(f,o.session,o.dialect,i)}function m(f){return new H1(f,o.session,o.dialect,i)}return{select:n,selectDistinct:p,selectDistinctOn:c,update:x,insert:T,delete:m}}select(i){return new ao({fields:i??void 0,session:this.session,dialect:this.dialect})}selectDistinct(i){return new ao({fields:i??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(i,o){return new ao({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:{on:i}})}update(i){return new Z1(i,this.session,this.dialect)}insert(i){return new U1(i,this.session,this.dialect)}delete(i){return new H1(i,this.session,this.dialect)}refreshMaterializedView(i){return new bJ(i,this.session,this.dialect)}authToken;execute(i){let o=typeof i==="string"?W.raw(i):i.getSQL(),n=this.dialect.sqlToQuery(o),p=this.session.prepareQuery(n,void 0,void 0,!1);return new aJ(()=>p.execute(void 0,this.authToken),o,n,(c)=>p.mapResult(c,!0))}transaction(i,o){return this.session.transaction(i,o)}}class YY{constructor(i,o){this.unique=i,this.name=o}static[w]="PgIndexBuilderOn";on(...i){return new M1(i.map((o)=>{if(Z(o,N))return o;o=o;let n=new DT(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=JSON.parse(JSON.stringify(o.defaultConfig)),n}),this.unique,!1,this.name)}onOnly(...i){return new M1(i.map((o)=>{if(Z(o,N))return o;o=o;let n=new DT(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=o.defaultConfig,n}),this.unique,!0,this.name)}using(i,...o){return new M1(o.map((n)=>{if(Z(n,N))return n;n=n;let p=new DT(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=JSON.parse(JSON.stringify(n.defaultConfig)),p}),this.unique,!0,this.name,i)}}class M1{static[w]="PgIndexBuilder";config;constructor(i,o,n,p,c="btree"){this.config={name:p,columns:i,unique:o,only:n,method:c}}concurrently(){return this.config.concurrently=!0,this}with(i){return this.config.with=i,this}where(i){return this.config.where=i,this}build(i){return new GY(this.config,i)}}class GY{static[w]="PgIndex";config;constructor(i,o){this.config={...i,table:o}}}function lJ(i){return new YY(!0,i)}class qJ{constructor(i){this.query=i}authToken;getQuery(){return this.query}mapResult(i,o){return i}setToken(i){return this.authToken=i,this}static[w]="PgPreparedQuery";joinsNotNullableMap}class kJ{constructor(i){this.dialect=i}static[w]="PgSession";execute(i,o){return Ci.startActiveSpan("drizzle.operation",()=>{return Ci.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(i),void 0,void 0,!1)}).setToken(o).execute(void 0,o)})}all(i){return this.prepareQuery(this.dialect.sqlToQuery(i),void 0,void 0,!1).all()}async count(i,o){let n=await this.execute(i,o);return Number(n[0].count)}}class hJ extends Tm{constructor(i,o,n,p=0){super(i,o,n);this.schema=n,this.nestedIndex=p}static[w]="PgTransaction";rollback(){throw new X$}getTransactionConfigSQL(i){let o=[];if(i.isolationLevel)o.push(`isolation level ${i.isolationLevel}`);if(i.accessMode)o.push(i.accessMode);if(typeof i.deferrable==="boolean")o.push(i.deferrable?"deferrable":"not deferrable");return W.raw(o.join(" "))}setTransaction(i){return this.session.execute(W`set transaction ${this.getTransactionConfigSQL(i)}`)}}class KY extends qJ{constructor(i,o,n,p,c,x,T){super({sql:o,params:n});this.client=i,this.queryString=o,this.params=n,this.logger=p,this.fields=c,this._isResponseInArrayMode=x,this.customResultMapper=T}static[w]="PostgresJsPreparedQuery";async execute(i={}){return Ci.startActiveSpan("drizzle.execute",async(o)=>{let n=v$(this.params,i);o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(n)}),this.logger.logQuery(this.queryString,n);let{fields:p,queryString:c,client:x,joinsNotNullableMap:T,customResultMapper:m}=this;if(!p&&!m)return Ci.startActiveSpan("drizzle.driver.execute",()=>{return x.unsafe(c,n)});let f=await Ci.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":c,"drizzle.query.params":JSON.stringify(n)}),x.unsafe(c,n).values()});return Ci.startActiveSpan("drizzle.mapResponse",()=>{return m?m(f):f.map((F)=>s3(p,F,T))})})}all(i={}){return Ci.startActiveSpan("drizzle.execute",async(o)=>{let n=v$(this.params,i);return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(n)}),this.logger.logQuery(this.queryString,n),Ci.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(n)}),this.client.unsafe(this.queryString,n)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class mm extends kJ{constructor(i,o,n,p={}){super(o);this.client=i,this.schema=n,this.options=p,this.logger=p.logger??new R$}static[w]="PostgresJsSession";logger;prepareQuery(i,o,n,p,c){return new KY(this.client,i.sql,i.params,this.logger,o,p,c)}query(i,o){return this.logger.logQuery(i,o),this.client.unsafe(i,o).values()}queryObjects(i,o){return this.client.unsafe(i,o)}transaction(i,o){return this.client.begin(async(n)=>{let p=new mm(n,this.dialect,this.schema,this.options),c=new gJ(this.dialect,p,this.schema);if(o)await c.setTransaction(o);return i(c)})}}class gJ extends hJ{constructor(i,o,n,p=0){super(i,o,n,p);this.session=o}static[w]="PostgresJsTransaction";transaction(i){return this.session.client.savepoint((o)=>{let n=new mm(o,this.dialect,this.schema,this.session.options),p=new gJ(this.dialect,n,this.schema);return i(p)})}}class HY extends Tm{static[w]="PostgresJsDatabase"}function yx(i,o={}){let n=(f)=>f;for(let f of["1184","1082","1083","1114","1182","1185","1115","1231"])i.options.parsers[f]=n,i.options.serializers[f]=n;i.options.serializers["114"]=n,i.options.serializers["3802"]=n;let p=new Qc({casing:o.casing}),c;if(o.logger===!0)c=new W$;else if(o.logger!==!1)c=o.logger;let x;if(o.schema){let f=e7(o.schema,oW);x={fullSchema:o.schema,schema:f.tables,tableNamesMap:f.tableNamesMap}}let T=new mm(i,p,x,{logger:c}),m=new HY(p,T,x);return m.$client=i,m}function z1(...i){if(typeof i[0]==="string"){let o=Lx(i[0]);return yx(o,i[1])}if(r3(i[0])){let{connection:o,client:n,...p}=i[0];if(n)return yx(n,p);if(typeof o==="object"&&o.url!==void 0){let{url:x,...T}=o,m=Lx(x,T);return yx(m,p)}let c=Lx(o);return yx(c,p)}return yx(i[0],i[1])}((i)=>{function o(n){return yx({options:{parsers:{},serializers:{}}},n)}i.mock=o})(z1||(z1={}));var tJ={};yG(tJ,{users:()=>jn,userChanges:()=>gE,untrackedUserColumnNames:()=>hE,twoFactorMethod:()=>uY,trackedUserColumnName:()=>zY,trackableUserColumnNames:()=>MY,role:()=>ZY,players:()=>sJ,passwordResetAttempts:()=>sE,loginHistory:()=>Dx,games:()=>u1,banishedIps:()=>Q1});function UY(i){return W`lower(${i})`}var ZY=Y0("role",["admin","user"]),jn=Np("users",{id:mn().primaryKey().defaultRandom(),username:Zo({length:16}).notNull(),email:Zo({length:254}).notNull(),hash:Zo({length:64}).notNull(),salt:Zo({length:36}).notNull(),createdAt:In({withTimezone:!0}).notNull().defaultNow(),createdIp:Zo({length:45}).notNull(),isActive:PT().notNull().default(!1),verifiedAt:In({withTimezone:!0}),userRole:ZY().default("user")},(i)=>[lJ("usernameUniqueIndex").on(UY(i.username)),lJ("emailUniqueIndex").on(UY(i.email))]),hE=["id","createdAt","createdIp","isActive","salt","verifiedAt"],MY=["username","email","hash","userRole"],zY=Y0("trackedUserColumnName",MY),gE=Np("userChanges",{id:mn().primaryKey().defaultRandom(),userId:mn().notNull().references(()=>jn.id),changedAt:In({withTimezone:!0}).notNull().defaultNow(),changedIp:Zo({length:45}).notNull(),changedColumn:zY().notNull(),oldValue:Zo({length:255}),newValue:Zo({length:255})}),u1=Np("games",{id:mn().primaryKey().defaultRandom()}),sJ=Np("players",{userId:mn().notNull().references(()=>jn.id),gameId:mn().notNull().references(()=>u1.id),score:V0().notNull()},(i)=>[g7({name:"players_userId_gameId_pk",columns:[i.userId,i.gameId]})]),Dx=Np("loginHistory",{id:mn().primaryKey().defaultRandom(),userId:mn().references(()=>jn.id),loginTime:In({withTimezone:!0}).notNull().defaultNow(),ipAddress:Zo({length:45}).notNull(),userAgent:Zo({length:1024}),successful:PT().notNull().default(!1)}),uY=Y0("twoFactorMethod",["email","phone"]),sE=Np("passwordResetAttempts",{id:mn().primaryKey().defaultRandom(),userId:mn().notNull().references(()=>jn.id),requestedIp:Zo({length:45}).notNull(),requestedAt:In({withTimezone:!0}).notNull().defaultNow(),succeededIp:Zo({length:45}),succeededAt:In({withTimezone:!0}),verificationMethod:uY().notNull()}),Q1=Np("banishedIps",{ip:Zo({length:45}).primaryKey(),reason:Zo({length:2048}).notNull(),banishedAt:In({withTimezone:!0}).notNull().defaultNow(),banishedUntil:In({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class dJ{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(tE.resolve(__dirname,"notify_update.sql"));let i=[Ro(jn),Ro(u1),Ro(sJ)];await this.sql`SELECT create_notify_triggers(${this.sql.array(i)})`,await this.sql.listen("table_update",(o)=>{let n=o.split(","),p=n[0],c=n[1],x=`${p}("${c}")`;if(this.observers.has(x))this.observers.get(x).next(x)})}constructor(i=!1,o={host:io.POSTGRES_HOST,port:io.POSTGRES_PORT,user:io.POSTGRES_USER,password:io.POSTGRES_PASSWORD,database:io.POSTGRES_DATABASE}){this.options=o,this.sql=Lx(o),this.drizzle=z1(this.sql,{schema:tJ,logger:i})}observe(i,o){if(!this.observers.has(i))this.observers.set(i,new $i);this.observers.get(i).subscribe("SINGLETON",o)}}import{createHash as dE}from"crypto";function rJ(i){let o=dE("sha256").update(i).digest("hex");return`${o.substring(0,8)}-${o.substring(8,12)}-${o.substring(12,16)}-${o.substring(16,20)}-${o.substring(20,32)}`}var QY=["123","321","abc","admin","adobe","alexander","amanda","andrea","andrew","angel","apple","asdf","ashley","baby","banana","baseball","batman","bear","biteme","blazer","blonde","boston","buster","butterfly","cameron","charlie","cheese","chelsea","chicken","chocolate","chris","compaq","computer","cookie","corvette","cowboys","dakota","dallas","daniel","david","diamond","dolphin","donald","dragon","eagle","flower","football","frank","freedom","friend","gateway","george","ginger","god","golf","hannah","hardcore","harley","heather","hello","hottie","hunter","internet","jasmine","jennifer","jessica","jesus","johnny","jordan","joshua","justin","justme","killer","knight","lakers","letmein","liverpool","login","london","love","lucky","mackenzie","maggie","master","matrix","matthew","maverick","melissa","mercedes","michael","michelle","mickey","miller","money","monkey","morgan","mother","muffin","mustang","natasha","nathan","nicole","ninja","orange","pass","password","patrick","peanut","pepper","phoenix","photoshop","pokemon","princess","purple","qazwsx","qwerty","rainbow","ranger","root","samantha","samsung","scooter","secret","shadow","simpson","smile","soccer","sparkle","starwars","summer","sunflower","sunshine","superman","taylor","temp","test","thomas","tigers","tigger","tinkerbell","trust","turtle","victoria","welcome","whatever","william","winter","yellow","zaq12wsx","zxcvbn"];var rE=3,eE=15,iO=/^[a-zA-Z0-9_-]+$/,umi=po(iO).and(`string > ${rE} & string < ${eE}`).brand("username"),VY=20,SY={"0":"o","1":"l","3":"e","4":"a","5":"s","7":"t","@":"a",$:"s","!":"i"};function oO(i){let o="";for(let n of i)if(n in SY)o+=SY[n];else o+=n;return o}function nO(i){let o=i.toLocaleLowerCase(),n=oO(o);for(let p of QY){if(n.includes(p))return!0;if(o.includes(p))return!0}return!1}function pO(i){let o=new Set(i).size;return i.length*Math.log2(o)}function cO(i){let o=0,n=100;if(nO(i))o-=n;return o+=pO(i)*0.5,Math.max(o,0)}var Qmi=po("string").narrow((i,o)=>{let n=cO(i);return n>=VY?!0:o.mustBe(`Of complexity ${VY} or more. Was ${n}.`)}).brand("password"),EY=po({"+":"delete",username:"string",password:"string"}),Vmi=po("string").brand("email"),OY=po({"+":"delete",username:"string",password:"string",email:"string"});var V1={100:'"Continue"',101:'"Switching Protocols"',102:'"Processing"',103:'"Early Hints"',200:'"OK"',201:'"Created"',202:'"Accepted"',203:'"Non-Authoritative Information"',204:'"No Content"',205:'"Reset Content"',206:'"Partial Content"',207:'"Multi-Status"',208:'"Already Reported"',226:'"IM Used"',300:'"Multiple Choices"',301:'"Moved Permanently"',302:'"Found"',303:'"See Other"',304:'"Not Modified"',305:'"Use Proxy"',306:'"Switch Proxy"',307:'"Temporary Redirect"',308:'"Permanent Redirect"',400:'"Bad Request"',401:'"Unauthorized"',402:'"Payment Required"',403:'"Forbidden"',404:'"Not Found"',405:'"Method Not Allowed"',406:'"Not Acceptable"',407:'"Proxy Authentication Required"',408:'"Request Timeout"',409:'"Conflict"',410:'"Gone"',411:'"Length Required"',412:'"Precondition Failed"',413:'"Payload Too Large"',414:'"URI Too Long"',415:'"Unsupported Media Type"',416:'"Range Not Satisfiable"',417:'"Expectation Failed"',418:`"I'm a teapot"`,421:'"Misdirected Request"',422:'"Unprocessable Entity"',423:'"Locked"',424:'"Failed Dependency"',425:'"Too Early"',426:'"Upgrade Required"',428:'"Precondition Required"',429:'"Too Many Requests"',431:'"Request Header Fields Too Large"',451:'"Unavailable For Legal Reasons"',500:'"Internal Server Error"',501:'"Not Implemented"',502:'"Bad Gateway"',503:'"Service Unavailable"',504:'"Gateway Timeout"',505:'"HTTP Version Not Supported"',506:'"Variant Also Negotiates"',507:'"Insufficient Storage"',508:'"Loop Detected"',510:'"Not Extended"',511:'"Network Authentication Required"'};function xO(i){return Number.parseInt(i,10)}var TO=po(V1),mO=TO.keyof().pipe((i)=>xO(i)),_Y=po([mO,"string"]);var LY=Op({key:"count",default:0}),fO=Tc({key:"incrementTX",do:({set:i})=>{i(LY,(o)=>o+1)}}),CY=m8({key:"countContinuity",config:(i)=>i.add(LY).add(fO)});var DY=RJ(qp,"backend.worker.game.bun",xi),Vc=new dJ({logQuery(i,o){xi.info("\uD83D\uDCDD query",i,o)}});d.STORE.loggers[0]=new pc("info",void 0,xi);var o0i=(()=>{let{__tribunalDaily:i}=globalThis;if(!i)i=new IY.CronJob("00 15 * * * *",()=>{RJ(qp,"backend.worker.tribunal.bun",xi)}),i.start(),process.on("exit",()=>{i.stop(),xi.info("\u231B tribunal daily cronjob stopped")}),xi.info("\u23F3 tribunal daily cronjob started");return i})();function JO(i){if(WJ)return $O(WJ,i);return FO({},i)}var BY=JO((i,o)=>{let n;i.on("data",(p)=>(n??=[]).push(p)).on("end",async()=>{let p=i.headers.authorization;try{if(typeof i.url==="undefined")throw[400,"No URL"];let c=i.socket.remoteAddress;if(!c)throw[400,"No IP address"];let x=new Date,T=new URL(i.url,io.VITE_BACKEND_ORIGIN);xi.info(x,c,i.method,T.pathname);let m=await Vc.drizzle.query.banishedIps.findFirst({columns:{banishedUntil:!0},where:dn(Q1.ip,c)}),f=m?.banishedUntil===null,F=m?.banishedUntil&&m.banishedUntil>x;if(f||F){xi.info(`\uD83D\uDE45 request from banned ip ${c}`);return}switch(i.method){case"POST":if(!n)throw[400,"No data received"];switch(T.pathname){case`/sign-up-${rJ("sign-up")}`:{let $=Buffer.concat(n).toString(),J=JSON.parse($),A=OY(J);if(A instanceof po.errors)throw xi.warn("signup parsed",A),[400,"Signup failed"];let{username:X,password:Y,email:R}=A;if(xi.info(`\uD83D\uDD11 attempting to sign up: ${X}`),await Vc.drizzle.query.users.findFirst({columns:{id:!0},where:dn(jn.email,R)}))throw[400,"User already exists"];let H=crypto.randomUUID(),z=yY("sha256").update(Y+H).digest("hex");await Vc.drizzle.insert(jn).values({username:X,email:R,hash:z,salt:H,createdIp:c}),xi.info(`\uD83D\uDD11 user created: ${X}`),o.writeHead(201,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${io.FRONTEND_ORIGINS[0]}`}),o.end(V1[201])}break;case`/login-${rJ("login")}`:{let $=!1,J=null;try{let A=new Date(+x-600000);xi.info("\uD83D\uDD11 ten minutes ago",{tenMinutesAgo:A,now:x});let X=await Vc.drizzle.query.loginHistory.findMany({columns:{userId:!0,successful:!0},where:wc(dn(Dx.ipAddress,c),dn(Dx.successful,!1),M0(Dx.loginTime,A)),limit:10});xi.info(`\uD83D\uDD11 ${X.length}/10 recent failed logins from ${c}`);let Y=10-X.length;if(Y<1)throw xi.info(`\uD83D\uDD11 too many recent failed logins from ${c}`),await Vc.drizzle.insert(Q1).values({ip:c,reason:"Too many recent login attempts.",banishedAt:x,banishedUntil:new Date(+x+86400000)}),[429,"Too many recent login attempts."];let R=Buffer.concat(n).toString(),K=JSON.parse(R),H=EY(K);if(H instanceof po.errors)throw xi.warn("login parsed",H),[400,`${Y} attempts remaining.`];let{username:z,password:b}=H,M=await Vc.drizzle.query.users.findFirst({columns:{id:!0,hash:!0,salt:!0},where:dn(jn.username,z)});if(xi.info("\uD83D\uDD11 login attempt as user",z),!M)throw xi.info(`\uD83D\uDD11 user ${z} does not exist`),[400,`${Y} attempts remaining.`];let{hash:u,salt:E}=M;if(J=M.id,yY("sha256").update(b+E).digest("hex")===u){let y=crypto.randomUUID(),l=F1.get(z);if(!l)l=new Map,F1.set(z,l);l.set(y,Number(x)),$=!0,xi.info("\uD83D\uDD11 login successful as",z),o.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${io.FRONTEND_ORIGINS[0]}`}),o.end(`${z} ${y}`)}}finally{await Vc.drizzle.insert(Dx).values({userId:J,successful:$,ipAddress:c,userAgent:i.headers["user-agent"]??"Withheld"}),xi.info(`\uD83D\uDD11 recorded login attempt from ${c}`)}}break;default:throw[404,"Not found"]}break;case void 0:throw[400,"No Method"];default:throw[405,"Method not allowed"]}}catch(c){let x=_Y(c);if(x instanceof po.errors)xi.error(c),o.writeHead(500,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${io.FRONTEND_ORIGINS[0]}`}),o.end("Internal Server Error");else{let[T,m]=x,F=`${V1[T]}. ${m}`;xi.info(`\u274C ${T}: ${F}`),o.writeHead(T,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${io.FRONTEND_ORIGINS[0]}`}),o.end(F)}}})}),eJ=BY.listen(io.BACKEND_PORT).address(),AO=typeof eJ==="string"?null:eJ===null?null:eJ.port;if(AO===null)throw new Error("Could not determine port for test server");new lR(BY,{cors:{origin:io.FRONTEND_ORIGINS,methods:["GET","POST"]}}).use((i,o)=>{let{username:n,sessionKey:p}=i.handshake.auth;if(!(n&&p)){o(new Error("No auth header provided"));return}let c=`user::${n}`,x=`socket::${i.id}`;if(F1.get(n)?.has(p)){let m=t(d.STORE,em,x);_i(d.STORE,m,i),Ep(mc,(f)=>{f.set(c,x)},d.STORE),_i(d.STORE,GF,(f)=>f.add(c)),_i(d.STORE,YF,(f)=>f.add(x)),xi.info(`${n} connected on ${i.id}`),o()}else xi.info(`${n} couldn't authenticate`),o(new Error("Authentication error"))}).on("connection",(i)=>{let n=X8({socket:i,store:d.STORE})(CY);i.on("disconnect",()=>{let p=`socket::${i.id}`,c=ix(mc,p,d.STORE).userKeyOfSocket,x=Mi(d.STORE,c);if(Ep(mc,(T)=>{T.delete(p)},d.STORE),x)_i(d.STORE,GF,(T)=>(T.delete(x),T));_i(d.STORE,YF,(T)=>(T.delete(p),T)),xi.info(`${i.id} disconnected`),n()})});async function S1(){xi.info("\uD83E\uDDF9 closing workers");let i=new Promise((o)=>DY.process.once("close",o));DY.emit("timeToStop"),await i,xi.info("\uD83D\uDEEC backend server exiting"),process.exit(0)}process.on("SIGINT",async()=>{xi.info("\u2757 received SIGINT; exiting gracefully"),await S1()});process.on("SIGTERM",async()=>{xi.info("\u2757 received SIGTERM; exiting gracefully"),await S1()});process.on("exit",async()=>{xi.info("\u2757 received exit; exiting gracefully"),await S1()});qp.on("updatesReady",()=>{xi.info('\u2757 backend server received signal "updatesReady"'),qp.emit("readyToUpdate"),xi.info('\u2757 backend server has sent signal "readyToUpdate"; now awaits signal "timeToStop"'),qp.on("timeToStop",async()=>{xi.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),await S1()})});xi.info(`\uD83D\uDEEB backend server ready on port ${io.BACKEND_PORT}`);qp.emit("alive");export{o0i as tribunalDaily};
|
|
125
|
+
`;await o.execute(W`CREATE SCHEMA IF NOT EXISTS ${W.identifier(c)}`),await o.execute(x);let m=(await o.all(W`select id, hash, created_at from ${W.identifier(c)}.${W.identifier(p)} order by created_at desc limit 1`))[0];await o.transaction(async(f)=>{for await(let F of i)if(!m||Number(m.created_at)<F.folderMillis){for(let $ of F.sql)await f.execute(W.raw($));await f.execute(W`insert into ${W.identifier(c)}.${W.identifier(p)} ("hash", "created_at") values(${F.hash}, ${F.folderMillis})`)}})}escapeName(i){return`"${i}"`}escapeParam(i){return`$${i+1}`}escapeString(i){return`'${i.replace(/'/g,"''")}'`}buildWithCTE(i){if(!i?.length)return;let o=[W`with `];for(let[n,p]of i.entries())if(o.push(W`${W.identifier(p._.alias)} as (${p._.sql})`),n<i.length-1)o.push(W`, `);return o.push(W` `),W.join(o)}buildDeleteQuery({table:i,where:o,returning:n,withList:p}){let c=this.buildWithCTE(p),x=n?W` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0,T=o?W` where ${o}`:void 0;return W`${c}delete from ${i}${T}${x}`}buildUpdateSet(i,o){let n=i[B.Symbol.Columns],p=Object.keys(n).filter((x)=>o[x]!==void 0||n[x]?.onUpdateFn!==void 0),c=p.length;return W.join(p.flatMap((x,T)=>{let m=n[x],f=o[x]??W.param(m.onUpdateFn(),m),F=W`${W.identifier(this.casing.getColumnCasing(m))} = ${f}`;if(T<c-1)return[F,W.raw(", ")];return[F]}))}buildUpdateQuery({table:i,set:o,where:n,returning:p,withList:c,from:x,joins:T}){let m=this.buildWithCTE(c),f=i[Mo.Symbol.Name],F=i[Mo.Symbol.Schema],$=i[Mo.Symbol.OriginalName],J=f===$?void 0:f,A=W`${F?W`${W.identifier(F)}.`:void 0}${W.identifier($)}${J&&W` ${W.identifier(J)}`}`,X=this.buildUpdateSet(i,o),Y=x&&W.join([W.raw(" from "),this.buildFromTable(x)]),R=this.buildJoins(T),K=p?W` returning ${this.buildSelection(p,{isSingleTable:!x})}`:void 0,H=n?W` where ${n}`:void 0;return W`${m}update ${A} set ${X}${Y}${R}${H}${K}`}buildSelection(i,{isSingleTable:o=!1}={}){let n=i.length,p=i.flatMap(({field:c},x)=>{let T=[];if(Z(c,N.Aliased)&&c.isSelectionField)T.push(W.identifier(c.fieldAlias));else if(Z(c,N.Aliased)||Z(c,N)){let m=Z(c,N.Aliased)?c.sql:c;if(o)T.push(new N(m.queryChunks.map((f)=>{if(Z(f,_))return W.identifier(this.casing.getColumnCasing(f));return f})));else T.push(m);if(Z(c,N.Aliased))T.push(W` as ${W.identifier(c.fieldAlias)}`)}else if(Z(c,Li))if(o)T.push(W.identifier(this.casing.getColumnCasing(c)));else T.push(c);if(x<n-1)T.push(W`, `);return T});return W.join(p)}buildJoins(i){if(!i||i.length===0)return;let o=[];for(let[n,p]of i.entries()){if(n===0)o.push(W` `);let c=p.table,x=p.lateral?W` lateral`:void 0;if(Z(c,Mo)){let T=c[Mo.Symbol.Name],m=c[Mo.Symbol.Schema],f=c[Mo.Symbol.OriginalName],F=T===f?void 0:p.alias;o.push(W`${W.raw(p.joinType)} join${x} ${m?W`${W.identifier(m)}.`:void 0}${W.identifier(f)}${F&&W` ${W.identifier(F)}`} on ${p.on}`)}else if(Z(c,ro)){let T=c[Ni].name,m=c[Ni].schema,f=c[Ni].originalName,F=T===f?void 0:p.alias;o.push(W`${W.raw(p.joinType)} join${x} ${m?W`${W.identifier(m)}.`:void 0}${W.identifier(f)}${F&&W` ${W.identifier(F)}`} on ${p.on}`)}else o.push(W`${W.raw(p.joinType)} join${x} ${c} on ${p.on}`);if(n<i.length-1)o.push(W` `)}return W.join(o)}buildFromTable(i){if(Z(i,B)&&i[B.Symbol.IsAlias]){let o=W`${W.identifier(i[B.Symbol.OriginalName])}`;if(i[B.Symbol.Schema])o=W`${W.identifier(i[B.Symbol.Schema])}.${o}`;return W`${o} ${W.identifier(i[B.Symbol.Name])}`}return i}buildSelectQuery({withList:i,fields:o,fieldsFlat:n,where:p,having:c,table:x,joins:T,orderBy:m,groupBy:f,limit:F,offset:$,lockingClause:J,distinct:A,setOperators:X}){let Y=n??Un(o);for(let mi of Y)if(Z(mi.field,Li)&&Ro(mi.field.table)!==(Z(x,wo)?x._.alias:Z(x,pm)?x[Ni].name:Z(x,N)?void 0:Ro(x))&&!((Ei)=>T?.some(({alias:To})=>To===(Ei[B.Symbol.IsAlias]?Ro(Ei):Ei[B.Symbol.BaseName])))(mi.field.table)){let Ei=Ro(mi.field.table);throw new Error(`Your "${mi.path.join("->")}" field references a column "${Ei}"."${mi.field.name}", but the table "${Ei}" is not part of the query! Did you forget to join it?`)}let R=!T||T.length===0,K=this.buildWithCTE(i),H;if(A)H=A===!0?W` distinct`:W` distinct on (${W.join(A.on,W`, `)})`;let z=this.buildSelection(Y,{isSingleTable:R}),b=this.buildFromTable(x),M=this.buildJoins(T),u=p?W` where ${p}`:void 0,E=c?W` having ${c}`:void 0,S;if(m&&m.length>0)S=W` order by ${W.join(m,W`, `)}`;let y;if(f&&f.length>0)y=W` group by ${W.join(f,W`, `)}`;let l=typeof F==="object"||typeof F==="number"&&F>=0?W` limit ${F}`:void 0,Q=$?W` offset ${$}`:void 0,Ti=W.empty();if(J){let mi=W` for ${W.raw(J.strength)}`;if(J.config.of)mi.append(W` of ${W.join(Array.isArray(J.config.of)?J.config.of:[J.config.of],W`, `)}`);if(J.config.noWait)mi.append(W` no wait`);else if(J.config.skipLocked)mi.append(W` skip locked`);Ti.append(mi)}let q=W`${K}select${H} ${z} from ${b}${M}${u}${y}${E}${S}${l}${Q}${Ti}`;if(X.length>0)return this.buildSetOperations(q,X);return q}buildSetOperations(i,o){let[n,...p]=o;if(!n)throw new Error("Cannot pass undefined values to any set operator");if(p.length===0)return this.buildSetOperationQuery({leftSelect:i,setOperator:n});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:i,setOperator:n}),p)}buildSetOperationQuery({leftSelect:i,setOperator:{type:o,isAll:n,rightSelect:p,limit:c,orderBy:x,offset:T}}){let m=W`(${i.getSQL()}) `,f=W`(${p.getSQL()})`,F;if(x&&x.length>0){let X=[];for(let Y of x)if(Z(Y,_))X.push(W.identifier(Y.name));else if(Z(Y,N)){for(let R=0;R<Y.queryChunks.length;R++){let K=Y.queryChunks[R];if(Z(K,_))Y.queryChunks[R]=W.identifier(K.name)}X.push(W`${Y}`)}else X.push(W`${Y}`);F=W` order by ${W.join(X,W`, `)} `}let $=typeof c==="object"||typeof c==="number"&&c>=0?W` limit ${c}`:void 0,J=W.raw(`${o} ${n?"all ":""}`),A=T?W` offset ${T}`:void 0;return W`${m}${J}${f}${F}${$}${A}`}buildInsertQuery({table:i,values:o,onConflict:n,returning:p,withList:c,select:x,overridingSystemValue_:T}){let m=[],f=i[B.Symbol.Columns],F=Object.entries(f).filter(([K,H])=>!H.shouldDisableInsert()),$=F.map(([,K])=>W.identifier(this.casing.getColumnCasing(K)));if(x){let K=o;if(Z(K,N))m.push(K);else m.push(K.getSQL())}else{let K=o;m.push(W.raw("values "));for(let[H,z]of K.entries()){let b=[];for(let[M,u]of F){let E=z[M];if(E===void 0||Z(E,Tn)&&E.value===void 0)if(u.defaultFn!==void 0){let S=u.defaultFn(),y=Z(S,N)?S:W.param(S,u);b.push(y)}else if(!u.default&&u.onUpdateFn!==void 0){let S=u.onUpdateFn(),y=Z(S,N)?S:W.param(S,u);b.push(y)}else b.push(W`default`);else b.push(E)}if(m.push(b),H<K.length-1)m.push(W`, `)}}let J=this.buildWithCTE(c),A=W.join(m),X=p?W` returning ${this.buildSelection(p,{isSingleTable:!0})}`:void 0,Y=n?W` on conflict ${n}`:void 0,R=T===!0?W`overriding system value `:void 0;return W`${J}insert into ${i} ${$} ${R}${A}${Y}${X}`}buildRefreshMaterializedViewQuery({view:i,concurrently:o,withNoData:n}){let p=o?W` concurrently`:void 0,c=n?W` with no data`:void 0;return W`refresh materialized view${p} ${i}${c}`}prepareTyping(i){if(Z(i,E0)||Z(i,S0))return"json";else if(Z(i,O0))return"decimal";else if(Z(i,_0))return"time";else if(Z(i,L0)||Z(i,C0))return"timestamp";else if(Z(i,u0)||Z(i,Q0))return"date";else if(Z(i,y0))return"uuid";else return"none"}sqlToQuery(i,o){return i.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:o})}buildRelationalQueryWithoutPK({fullSchema:i,schema:o,tableNamesMap:n,table:p,tableConfig:c,queryConfig:x,tableAlias:T,nestedQueryRelation:m,joinOn:f}){let F=[],$,J,A=[],X,Y=[];if(x===!0)F=Object.entries(c.columns).map(([H,z])=>({dbKey:z.name,tsKey:H,field:tn(z,T),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let K=Object.fromEntries(Object.entries(c.columns).map(([E,S])=>[E,tn(S,T)]));if(x.where){let E=typeof x.where==="function"?x.where(K,d7()):x.where;X=E&&bT(E,T)}let H=[],z=[];if(x.columns){let E=!1;for(let[S,y]of Object.entries(x.columns)){if(y===void 0)continue;if(S in c.columns){if(!E&&y===!0)E=!0;z.push(S)}}if(z.length>0)z=E?z.filter((S)=>x.columns?.[S]===!0):Object.keys(c.columns).filter((S)=>!z.includes(S))}else z=Object.keys(c.columns);for(let E of z){let S=c.columns[E];H.push({tsKey:E,value:S})}let b=[];if(x.with)b=Object.entries(x.with).filter((E)=>!!E[1]).map(([E,S])=>({tsKey:E,queryConfig:S,relation:c.relations[E]}));let M;if(x.extras){M=typeof x.extras==="function"?x.extras(K,{sql:W}):x.extras;for(let[E,S]of Object.entries(M))H.push({tsKey:E,value:w$(S,T)})}for(let{tsKey:E,value:S}of H)F.push({dbKey:Z(S,N.Aliased)?S.fieldAlias:c.columns[E].name,tsKey:E,field:Z(S,Li)?tn(S,T):S,relationTableTsKey:void 0,isJson:!1,selection:[]});let u=typeof x.orderBy==="function"?x.orderBy(K,r7()):x.orderBy??[];if(!Array.isArray(u))u=[u];A=u.map((E)=>{if(Z(E,Li))return tn(E,T);return bT(E,T)}),$=x.limit,J=x.offset;for(let{tsKey:E,queryConfig:S,relation:y}of b){let l=iW(o,n,y),Q=vc(y.referencedTable),Ti=n[Q],q=`${T}_${E}`,mi=wc(...l.fields.map((lo,ip)=>dn(tn(l.references[ip],q),tn(lo,T)))),Ei=this.buildRelationalQueryWithoutPK({fullSchema:i,schema:o,tableNamesMap:n,table:i[Ti],tableConfig:o[Ti],queryConfig:Z(y,bp)?S===!0?{limit:1}:{...S,limit:1}:S,tableAlias:q,joinOn:mi,nestedQueryRelation:y}),To=W`${W.identifier(q)}.${W.identifier("data")}`.as(E);Y.push({on:W`true`,table:new wo(Ei.sql,{},q),alias:q,joinType:"left",lateral:!0}),F.push({dbKey:E,tsKey:E,field:To,relationTableTsKey:Ti,isJson:!0,selection:Ei.selection})}}if(F.length===0)throw new Z0({message:`No fields selected for table "${c.tsName}" ("${T}")`});let R;if(X=wc(f,X),m){let K=W`json_build_array(${W.join(F.map(({field:b,tsKey:M,isJson:u})=>u?W`${W.identifier(`${T}_${M}`)}.${W.identifier("data")}`:Z(b,N.Aliased)?b.sql:b),W`, `)})`;if(Z(m,lT))K=W`coalesce(json_agg(${K}${A.length>0?W` order by ${W.join(A,W`, `)}`:void 0}), '[]'::json)`;let H=[{dbKey:"data",tsKey:"data",field:K.as("data"),isJson:!0,relationTableTsKey:c.tsName,selection:F}];if($!==void 0||J!==void 0||A.length>0)R=this.buildSelectQuery({table:U0(p,T),fields:{},fieldsFlat:[{path:[],field:W.raw("*")}],where:X,limit:$,offset:J,orderBy:A,setOperators:[]}),X=void 0,$=void 0,J=void 0,A=[];else R=U0(p,T);R=this.buildSelectQuery({table:Z(R,Mo)?R:new wo(R,{},T),fields:{},fieldsFlat:H.map(({field:b})=>({path:[],field:Z(b,Li)?tn(b,T):b})),joins:Y,where:X,limit:$,offset:J,orderBy:A,setOperators:[]})}else R=this.buildSelectQuery({table:U0(p,T),fields:{},fieldsFlat:F.map(({field:K})=>({path:[],field:Z(K,Li)?tn(K,T):K})),joins:Y,where:X,limit:$,offset:J,orderBy:A,setOperators:[]});return{tableTsKey:c.tsName,sql:R,selection:F}}}class IJ{static[w]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class ao{static[w]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(i){if(this.fields=i.fields,this.session=i.session,this.dialect=i.dialect,i.withList)this.withList=i.withList;this.distinct=i.distinct}authToken;setToken(i){return this.authToken=i,this}from(i){let o=!!this.fields,n=i,p;if(this.fields)p=this.fields;else if(Z(n,wo))p=Object.fromEntries(Object.keys(n._.selectedFields).map((c)=>[c,n[c]]));else if(Z(n,pm))p=n[Ni].selectedFields;else if(Z(n,N))p={};else p=d3(n);return new BJ({table:n,fields:p,isPartialSelect:o,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}class WY extends IJ{static[w]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:i,fields:o,isPartialSelect:n,session:p,dialect:c,withList:x,distinct:T}){super();this.config={withList:x,table:i,fields:{...o},distinct:T,setOperators:[]},this.isPartialSelect=n,this.session=p,this.dialect=c,this._={selectedFields:o},this.tableName=Ap(i),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(i){return(o,n)=>{let p=this.tableName,c=Ap(o);if(typeof c==="string"&&this.config.joins?.some((x)=>x.alias===c))throw new Error(`Alias "${c}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof p==="string")this.config.fields={[p]:this.config.fields};if(typeof c==="string"&&!Z(o,N)){let x=Z(o,wo)?o._.selectedFields:Z(o,ro)?o[Ni].selectedFields:o[B.Symbol.Columns];this.config.fields[c]=x}}if(typeof n==="function")n=n(new Proxy(this.config.fields,new ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:n,table:o,joinType:i,alias:c}),typeof c==="string")switch(i){case"left":{this.joinsNotNullableMap[c]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([x])=>[x,!1])),this.joinsNotNullableMap[c]=!0;break}case"inner":{this.joinsNotNullableMap[c]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([x])=>[x,!1])),this.joinsNotNullableMap[c]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(i,o){return(n)=>{let p=typeof n==="function"?n(bE()):n;if(!jT(this.getSelectedFields(),p.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:i,isAll:o,rightSelect:p}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(i){return this.config.setOperators.push(...i),this}where(i){if(typeof i==="function")i=i(new Proxy(this.config.fields,new ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=i,this}having(i){if(typeof i==="function")i=i(new Proxy(this.config.fields,new ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=i,this}groupBy(...i){if(typeof i[0]==="function"){let o=i[0](new Proxy(this.config.fields,new ti({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(o)?o:[o]}else this.config.groupBy=i;return this}orderBy(...i){if(typeof i[0]==="function"){let o=i[0](new Proxy(this.config.fields,new ti({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),n=Array.isArray(o)?o:[o];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=n;else this.config.orderBy=n}else{let o=i;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=o;else this.config.orderBy=o}return this}limit(i){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=i;else this.config.limit=i;return this}offset(i){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=i;else this.config.offset=i;return this}for(i,o={}){return this.config.lockingClause={strength:i,config:o},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:i,...o}=this.dialect.sqlToQuery(this.getSQL());return o}as(i){return new Proxy(new wo(this.getSQL(),this.config.fields,i),new ti({alias:i,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new ti({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class BJ extends WY{static[w]="PgSelect";_prepare(i){let{session:o,config:n,dialect:p,joinsNotNullableMap:c,authToken:x}=this;if(!o)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Ci.startActiveSpan("drizzle.prepareQuery",()=>{let T=Un(n.fields),m=o.prepareQuery(p.sqlToQuery(this.getSQL()),T,i,!0);return m.joinsNotNullableMap=c,m.setToken(x)})}prepare(i){return this._prepare(i)}authToken;setToken(i){return this.authToken=i,this}execute=(i)=>{return Ci.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(i,this.authToken)})}}t3(BJ,[jo]);function Cx(i,o){return(n,p,...c)=>{let x=[p,...c].map((T)=>({type:i,isAll:o,rightSelect:T}));for(let T of x)if(!jT(n.getSelectedFields(),T.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return n.addSetOperators(x)}}var bE=()=>({union:jE,unionAll:PE,intersect:aE,intersectAll:lE,except:qE,exceptAll:kE}),jE=Cx("union",!1),PE=Cx("union",!0),aE=Cx("intersect",!1),lE=Cx("intersect",!0),qE=Cx("except",!1),kE=Cx("except",!0);class cm{static[w]="PgQueryBuilder";dialect;dialectConfig;constructor(i){this.dialect=Z(i,Qc)?i:void 0,this.dialectConfig=Z(i,Qc)?void 0:i}$with=(i,o)=>{let n=this;return{as:(c)=>{if(typeof c==="function")c=c(n);return new Proxy(new IT(c.getSQL(),o??("getSelectedFields"in c?c.getSelectedFields()??{}:{}),i,!0),new ti({alias:i,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...i){let o=this;function n(x){return new ao({fields:x??void 0,session:void 0,dialect:o.getDialect(),withList:i})}function p(x){return new ao({fields:x??void 0,session:void 0,dialect:o.getDialect(),distinct:!0})}function c(x,T){return new ao({fields:T??void 0,session:void 0,dialect:o.getDialect(),distinct:{on:x}})}return{select:n,selectDistinct:p,selectDistinctOn:c}}select(i){return new ao({fields:i??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(i){return new ao({fields:i??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(i,o){return new ao({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:i}})}getDialect(){if(!this.dialect)this.dialect=new Qc(this.dialectConfig);return this.dialect}}class U1{constructor(i,o,n,p,c){this.table=i,this.session=o,this.dialect=n,this.withList=p,this.overridingSystemValue_=c}static[w]="PgInsertBuilder";authToken;setToken(i){return this.authToken=i,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(i){if(i=Array.isArray(i)?i:[i],i.length===0)throw new Error("values() must be called with at least one value");let o=i.map((n)=>{let p={},c=this.table[B.Symbol.Columns];for(let x of Object.keys(n)){let T=n[x];p[x]=Z(T,N)?T:new Tn(T,c[x])}return p});return new NJ(this.table,o,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(i){let o=typeof i==="function"?i(new cm):i;if(!Z(o,N)&&!jT(this.table[K0],o._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new NJ(this.table,o,this.session,this.dialect,this.withList,!0)}}class NJ extends jo{constructor(i,o,n,p,c,x,T){super();this.session=n,this.dialect=p,this.config={table:i,values:o,withList:c,select:x,overridingSystemValue_:T}}static[w]="PgInsert";config;returning(i=this.config.table[B.Symbol.Columns]){return this.config.returningFields=i,this.config.returning=Un(i),this}onConflictDoNothing(i={}){if(i.target===void 0)this.config.onConflict=W`do nothing`;else{let o="";o=Array.isArray(i.target)?i.target.map((p)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(p))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(i.target));let n=i.where?W` where ${i.where}`:void 0;this.config.onConflict=W`(${W.raw(o)})${n} do nothing`}return this}onConflictDoUpdate(i){if(i.where&&(i.targetWhere||i.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let o=i.where?W` where ${i.where}`:void 0,n=i.targetWhere?W` where ${i.targetWhere}`:void 0,p=i.setWhere?W` where ${i.setWhere}`:void 0,c=this.dialect.buildUpdateSet(this.config.table,z0(this.config.table,i.set)),x="";return x=Array.isArray(i.target)?i.target.map((T)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(T))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(i.target)),this.config.onConflict=W`(${W.raw(x)})${n} do update set ${c}${o}${p}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:i,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(i){return Ci.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,i,!0)})}prepare(i){return this._prepare(i)}authToken;setToken(i){return this.authToken=i,this}execute=(i)=>{return Ci.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(i,this.authToken)})};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new ti({alias:Ro(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class bJ extends jo{constructor(i,o,n){super();this.session=o,this.dialect=n,this.config={view:i}}static[w]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:i,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(i){return Ci.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,i,!0)})}prepare(i){return this._prepare(i)}authToken;setToken(i){return this.authToken=i,this}execute=(i)=>{return Ci.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(i,this.authToken)})}}class Z1{constructor(i,o,n,p){this.table=i,this.session=o,this.dialect=n,this.withList=p}static[w]="PgUpdateBuilder";authToken;setToken(i){return this.authToken=i,this}set(i){return new RY(this.table,z0(this.table,i),this.session,this.dialect,this.withList).setToken(this.authToken)}}class RY extends jo{constructor(i,o,n,p,c){super();this.session=n,this.dialect=p,this.config={set:o,table:i,withList:c,joins:[]},this.tableName=Ap(i),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}static[w]="PgUpdate";config;tableName;joinsNotNullableMap;from(i){let o=i,n=Ap(o);if(typeof n==="string")this.joinsNotNullableMap[n]=!0;return this.config.from=o,this}getTableLikeFields(i){if(Z(i,Mo))return i[B.Symbol.Columns];else if(Z(i,wo))return i._.selectedFields;return i[Ni].selectedFields}createJoin(i){return(o,n)=>{let p=Ap(o);if(typeof p==="string"&&this.config.joins.some((c)=>c.alias===p))throw new Error(`Alias "${p}" is already used in this query`);if(typeof n==="function"){let c=this.config.from&&!Z(this.config.from,N)?this.getTableLikeFields(this.config.from):void 0;n=n(new Proxy(this.config.table[B.Symbol.Columns],new ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),c&&new Proxy(c,new ti({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:n,table:o,joinType:i,alias:p}),typeof p==="string")switch(i){case"left":{this.joinsNotNullableMap[p]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([c])=>[c,!1])),this.joinsNotNullableMap[p]=!0;break}case"inner":{this.joinsNotNullableMap[p]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([c])=>[c,!1])),this.joinsNotNullableMap[p]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(i){return this.config.where=i,this}returning(i){if(!i){if(i=Object.assign({},this.config.table[B.Symbol.Columns]),this.config.from){let o=Ap(this.config.from);if(typeof o==="string"&&this.config.from&&!Z(this.config.from,N)){let n=this.getTableLikeFields(this.config.from);i[o]=n}for(let n of this.config.joins){let p=Ap(n.table);if(typeof p==="string"&&!Z(n.table,N)){let c=this.getTableLikeFields(n.table);i[p]=c}}}}return this.config.returningFields=i,this.config.returning=Un(i),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:i,...o}=this.dialect.sqlToQuery(this.getSQL());return o}_prepare(i){let o=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,i,!0);return o.joinsNotNullableMap=this.joinsNotNullableMap,o}prepare(i){return this._prepare(i)}authToken;setToken(i){return this.authToken=i,this}execute=(i)=>{return this._prepare().execute(i,this.authToken)};getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new ti({alias:Ro(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}class xm extends N{constructor(i){super(xm.buildEmbeddedCount(i.source,i.filters).queryChunks);this.params=i,this.mapWith(Number),this.session=i.session,this.sql=xm.buildCount(i.source,i.filters)}sql;token;static[w]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(i,o){return W`(select count(*) from ${i}${W.raw(" where ").if(o)}${o})`}static buildCount(i,o){return W`select count(*) as count from ${i}${W.raw(" where ").if(o)}${o};`}setToken(i){return this.token=i,this}then(i,o){return Promise.resolve(this.session.count(this.sql,this.token)).then(i,o)}catch(i){return this.then(void 0,i)}finally(i){return this.then((o)=>{return i?.(),o},(o)=>{throw i?.(),o})}}class PJ{constructor(i,o,n,p,c,x,T){this.fullSchema=i,this.schema=o,this.tableNamesMap=n,this.table=p,this.tableConfig=c,this.dialect=x,this.session=T}static[w]="PgRelationalQueryBuilder";findMany(i){return new jJ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,i?i:{},"many")}findFirst(i){return new jJ(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,i?{...i,limit:1}:{limit:1},"first")}}class jJ extends jo{constructor(i,o,n,p,c,x,T,m,f){super();this.fullSchema=i,this.schema=o,this.tableNamesMap=n,this.table=p,this.tableConfig=c,this.dialect=x,this.session=T,this.config=m,this.mode=f}static[w]="PgRelationalQuery";_prepare(i){return Ci.startActiveSpan("drizzle.prepareQuery",()=>{let{query:o,builtQuery:n}=this._toSQL();return this.session.prepareQuery(n,void 0,i,!0,(p,c)=>{let x=p.map((T)=>D0(this.schema,this.tableConfig,T,o.selection,c));if(this.mode==="first")return x[0];return x})})}prepare(i){return this._prepare(i)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let i=this._getQuery(),o=this.dialect.sqlToQuery(i.sql);return{query:i,builtQuery:o}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(i){return this.authToken=i,this}execute(){return Ci.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(void 0,this.authToken)})}}class aJ extends jo{constructor(i,o,n,p){super();this.execute=i,this.sql=o,this.query=n,this.mapBatchResult=p}static[w]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(i,o){return o?this.mapBatchResult(i):i}_prepare(){return this}isResponseInArrayMode(){return!1}}class Tm{constructor(i,o,n){if(this.dialect=i,this.session=o,this._=n?{schema:n.schema,fullSchema:n.fullSchema,tableNamesMap:n.tableNamesMap,session:o}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:o},this.query={},this._.schema)for(let[p,c]of Object.entries(this._.schema))this.query[p]=new PJ(n.fullSchema,this._.schema,this._.tableNamesMap,n.fullSchema[p],c,i,o)}static[w]="PgDatabase";query;$with=(i,o)=>{let n=this;return{as:(c)=>{if(typeof c==="function")c=c(new cm(n.dialect));return new Proxy(new IT(c.getSQL(),o??("getSelectedFields"in c?c.getSelectedFields()??{}:{}),i,!0),new ti({alias:i,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(i,o){return new xm({source:i,filters:o,session:this.session})}with(...i){let o=this;function n(f){return new ao({fields:f??void 0,session:o.session,dialect:o.dialect,withList:i})}function p(f){return new ao({fields:f??void 0,session:o.session,dialect:o.dialect,withList:i,distinct:!0})}function c(f,F){return new ao({fields:F??void 0,session:o.session,dialect:o.dialect,withList:i,distinct:{on:f}})}function x(f){return new Z1(f,o.session,o.dialect,i)}function T(f){return new U1(f,o.session,o.dialect,i)}function m(f){return new H1(f,o.session,o.dialect,i)}return{select:n,selectDistinct:p,selectDistinctOn:c,update:x,insert:T,delete:m}}select(i){return new ao({fields:i??void 0,session:this.session,dialect:this.dialect})}selectDistinct(i){return new ao({fields:i??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(i,o){return new ao({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:{on:i}})}update(i){return new Z1(i,this.session,this.dialect)}insert(i){return new U1(i,this.session,this.dialect)}delete(i){return new H1(i,this.session,this.dialect)}refreshMaterializedView(i){return new bJ(i,this.session,this.dialect)}authToken;execute(i){let o=typeof i==="string"?W.raw(i):i.getSQL(),n=this.dialect.sqlToQuery(o),p=this.session.prepareQuery(n,void 0,void 0,!1);return new aJ(()=>p.execute(void 0,this.authToken),o,n,(c)=>p.mapResult(c,!0))}transaction(i,o){return this.session.transaction(i,o)}}class YY{constructor(i,o){this.unique=i,this.name=o}static[w]="PgIndexBuilderOn";on(...i){return new M1(i.map((o)=>{if(Z(o,N))return o;o=o;let n=new DT(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=JSON.parse(JSON.stringify(o.defaultConfig)),n}),this.unique,!1,this.name)}onOnly(...i){return new M1(i.map((o)=>{if(Z(o,N))return o;o=o;let n=new DT(o.name,!!o.keyAsName,o.columnType,o.indexConfig);return o.indexConfig=o.defaultConfig,n}),this.unique,!0,this.name)}using(i,...o){return new M1(o.map((n)=>{if(Z(n,N))return n;n=n;let p=new DT(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=JSON.parse(JSON.stringify(n.defaultConfig)),p}),this.unique,!0,this.name,i)}}class M1{static[w]="PgIndexBuilder";config;constructor(i,o,n,p,c="btree"){this.config={name:p,columns:i,unique:o,only:n,method:c}}concurrently(){return this.config.concurrently=!0,this}with(i){return this.config.with=i,this}where(i){return this.config.where=i,this}build(i){return new GY(this.config,i)}}class GY{static[w]="PgIndex";config;constructor(i,o){this.config={...i,table:o}}}function lJ(i){return new YY(!0,i)}class qJ{constructor(i){this.query=i}authToken;getQuery(){return this.query}mapResult(i,o){return i}setToken(i){return this.authToken=i,this}static[w]="PgPreparedQuery";joinsNotNullableMap}class kJ{constructor(i){this.dialect=i}static[w]="PgSession";execute(i,o){return Ci.startActiveSpan("drizzle.operation",()=>{return Ci.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(i),void 0,void 0,!1)}).setToken(o).execute(void 0,o)})}all(i){return this.prepareQuery(this.dialect.sqlToQuery(i),void 0,void 0,!1).all()}async count(i,o){let n=await this.execute(i,o);return Number(n[0].count)}}class hJ extends Tm{constructor(i,o,n,p=0){super(i,o,n);this.schema=n,this.nestedIndex=p}static[w]="PgTransaction";rollback(){throw new X$}getTransactionConfigSQL(i){let o=[];if(i.isolationLevel)o.push(`isolation level ${i.isolationLevel}`);if(i.accessMode)o.push(i.accessMode);if(typeof i.deferrable==="boolean")o.push(i.deferrable?"deferrable":"not deferrable");return W.raw(o.join(" "))}setTransaction(i){return this.session.execute(W`set transaction ${this.getTransactionConfigSQL(i)}`)}}class KY extends qJ{constructor(i,o,n,p,c,x,T){super({sql:o,params:n});this.client=i,this.queryString=o,this.params=n,this.logger=p,this.fields=c,this._isResponseInArrayMode=x,this.customResultMapper=T}static[w]="PostgresJsPreparedQuery";async execute(i={}){return Ci.startActiveSpan("drizzle.execute",async(o)=>{let n=v$(this.params,i);o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(n)}),this.logger.logQuery(this.queryString,n);let{fields:p,queryString:c,client:x,joinsNotNullableMap:T,customResultMapper:m}=this;if(!p&&!m)return Ci.startActiveSpan("drizzle.driver.execute",()=>{return x.unsafe(c,n)});let f=await Ci.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":c,"drizzle.query.params":JSON.stringify(n)}),x.unsafe(c,n).values()});return Ci.startActiveSpan("drizzle.mapResponse",()=>{return m?m(f):f.map((F)=>s3(p,F,T))})})}all(i={}){return Ci.startActiveSpan("drizzle.execute",async(o)=>{let n=v$(this.params,i);return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(n)}),this.logger.logQuery(this.queryString,n),Ci.startActiveSpan("drizzle.driver.execute",()=>{return o?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(n)}),this.client.unsafe(this.queryString,n)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class mm extends kJ{constructor(i,o,n,p={}){super(o);this.client=i,this.schema=n,this.options=p,this.logger=p.logger??new R$}static[w]="PostgresJsSession";logger;prepareQuery(i,o,n,p,c){return new KY(this.client,i.sql,i.params,this.logger,o,p,c)}query(i,o){return this.logger.logQuery(i,o),this.client.unsafe(i,o).values()}queryObjects(i,o){return this.client.unsafe(i,o)}transaction(i,o){return this.client.begin(async(n)=>{let p=new mm(n,this.dialect,this.schema,this.options),c=new gJ(this.dialect,p,this.schema);if(o)await c.setTransaction(o);return i(c)})}}class gJ extends hJ{constructor(i,o,n,p=0){super(i,o,n,p);this.session=o}static[w]="PostgresJsTransaction";transaction(i){return this.session.client.savepoint((o)=>{let n=new mm(o,this.dialect,this.schema,this.session.options),p=new gJ(this.dialect,n,this.schema);return i(p)})}}class HY extends Tm{static[w]="PostgresJsDatabase"}function yx(i,o={}){let n=(f)=>f;for(let f of["1184","1082","1083","1114","1182","1185","1115","1231"])i.options.parsers[f]=n,i.options.serializers[f]=n;i.options.serializers["114"]=n,i.options.serializers["3802"]=n;let p=new Qc({casing:o.casing}),c;if(o.logger===!0)c=new W$;else if(o.logger!==!1)c=o.logger;let x;if(o.schema){let f=e7(o.schema,oW);x={fullSchema:o.schema,schema:f.tables,tableNamesMap:f.tableNamesMap}}let T=new mm(i,p,x,{logger:c}),m=new HY(p,T,x);return m.$client=i,m}function z1(...i){if(typeof i[0]==="string"){let o=Lx(i[0]);return yx(o,i[1])}if(r3(i[0])){let{connection:o,client:n,...p}=i[0];if(n)return yx(n,p);if(typeof o==="object"&&o.url!==void 0){let{url:x,...T}=o,m=Lx(x,T);return yx(m,p)}let c=Lx(o);return yx(c,p)}return yx(i[0],i[1])}((i)=>{function o(n){return yx({options:{parsers:{},serializers:{}}},n)}i.mock=o})(z1||(z1={}));var tJ={};yG(tJ,{users:()=>jn,userChanges:()=>gE,untrackedUserColumnNames:()=>hE,twoFactorMethod:()=>uY,trackedUserColumnName:()=>zY,trackableUserColumnNames:()=>MY,role:()=>ZY,players:()=>sJ,passwordResetAttempts:()=>sE,loginHistory:()=>Dx,games:()=>u1,banishedIps:()=>Q1});function UY(i){return W`lower(${i})`}var ZY=Y0("role",["admin","user"]),jn=Np("users",{id:mn().primaryKey().defaultRandom(),username:Zo({length:16}).notNull(),email:Zo({length:254}).notNull(),hash:Zo({length:64}).notNull(),salt:Zo({length:36}).notNull(),createdAt:In({withTimezone:!0}).notNull().defaultNow(),createdIp:Zo({length:45}).notNull(),isActive:PT().notNull().default(!1),verifiedAt:In({withTimezone:!0}),userRole:ZY().default("user")},(i)=>[lJ("usernameUniqueIndex").on(UY(i.username)),lJ("emailUniqueIndex").on(UY(i.email))]),hE=["id","createdAt","createdIp","isActive","salt","verifiedAt"],MY=["username","email","hash","userRole"],zY=Y0("trackedUserColumnName",MY),gE=Np("userChanges",{id:mn().primaryKey().defaultRandom(),userId:mn().notNull().references(()=>jn.id),changedAt:In({withTimezone:!0}).notNull().defaultNow(),changedIp:Zo({length:45}).notNull(),changedColumn:zY().notNull(),oldValue:Zo({length:255}),newValue:Zo({length:255})}),u1=Np("games",{id:mn().primaryKey().defaultRandom()}),sJ=Np("players",{userId:mn().notNull().references(()=>jn.id),gameId:mn().notNull().references(()=>u1.id),score:V0().notNull()},(i)=>[g7({name:"players_userId_gameId_pk",columns:[i.userId,i.gameId]})]),Dx=Np("loginHistory",{id:mn().primaryKey().defaultRandom(),userId:mn().references(()=>jn.id),loginTime:In({withTimezone:!0}).notNull().defaultNow(),ipAddress:Zo({length:45}).notNull(),userAgent:Zo({length:1024}),successful:PT().notNull().default(!1)}),uY=Y0("twoFactorMethod",["email","phone"]),sE=Np("passwordResetAttempts",{id:mn().primaryKey().defaultRandom(),userId:mn().notNull().references(()=>jn.id),requestedIp:Zo({length:45}).notNull(),requestedAt:In({withTimezone:!0}).notNull().defaultNow(),succeededIp:Zo({length:45}),succeededAt:In({withTimezone:!0}),verificationMethod:uY().notNull()}),Q1=Np("banishedIps",{ip:Zo({length:45}).primaryKey(),reason:Zo({length:2048}).notNull(),banishedAt:In({withTimezone:!0}).notNull().defaultNow(),banishedUntil:In({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class dJ{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(tE.resolve(__dirname,"notify_update.sql"));let i=[Ro(jn),Ro(u1),Ro(sJ)];await this.sql`SELECT create_notify_triggers(${this.sql.array(i)})`,await this.sql.listen("table_update",(o)=>{let n=o.split(","),p=n[0],c=n[1],x=`${p}("${c}")`;if(this.observers.has(x))this.observers.get(x).next(x)})}constructor(i=!1,o={host:oo.POSTGRES_HOST,port:oo.POSTGRES_PORT,user:oo.POSTGRES_USER,password:oo.POSTGRES_PASSWORD,database:oo.POSTGRES_DATABASE}){this.options=o,this.sql=Lx(o),this.drizzle=z1(this.sql,{schema:tJ,logger:i})}observe(i,o){if(!this.observers.has(i))this.observers.set(i,new $i);this.observers.get(i).subscribe("SINGLETON",o)}}import{createHash as dE}from"crypto";function rJ(i){let o=dE("sha256").update(i).digest("hex");return`${o.substring(0,8)}-${o.substring(8,12)}-${o.substring(12,16)}-${o.substring(16,20)}-${o.substring(20,32)}`}var QY=["123","321","abc","admin","adobe","alexander","amanda","andrea","andrew","angel","apple","asdf","ashley","baby","banana","baseball","batman","bear","biteme","blazer","blonde","boston","buster","butterfly","cameron","charlie","cheese","chelsea","chicken","chocolate","chris","compaq","computer","cookie","corvette","cowboys","dakota","dallas","daniel","david","diamond","dolphin","donald","dragon","eagle","flower","football","frank","freedom","friend","gateway","george","ginger","god","golf","hannah","hardcore","harley","heather","hello","hottie","hunter","internet","jasmine","jennifer","jessica","jesus","johnny","jordan","joshua","justin","justme","killer","knight","lakers","letmein","liverpool","login","london","love","lucky","mackenzie","maggie","master","matrix","matthew","maverick","melissa","mercedes","michael","michelle","mickey","miller","money","monkey","morgan","mother","muffin","mustang","natasha","nathan","nicole","ninja","orange","pass","password","patrick","peanut","pepper","phoenix","photoshop","pokemon","princess","purple","qazwsx","qwerty","rainbow","ranger","root","samantha","samsung","scooter","secret","shadow","simpson","smile","soccer","sparkle","starwars","summer","sunflower","sunshine","superman","taylor","temp","test","thomas","tigers","tigger","tinkerbell","trust","turtle","victoria","welcome","whatever","william","winter","yellow","zaq12wsx","zxcvbn"];var rE=3,eE=15,iO=/^[a-zA-Z0-9_-]+$/,umi=ri(iO).pipe(ri(`string > ${rE} & string < ${eE}`)).brand("username"),VY=20,SY={"0":"o","1":"l","3":"e","4":"a","5":"s","7":"t","@":"a",$:"s","!":"i"};function oO(i){let o="";for(let n of i)if(n in SY)o+=SY[n];else o+=n;return o}function nO(i){let o=i.toLocaleLowerCase(),n=oO(o);for(let p of QY){if(n.includes(p))return!0;if(o.includes(p))return!0}return!1}function pO(i){let o=new Set(i).size;return i.length*Math.log2(o)}function cO(i){let o=0,n=100;if(nO(i))o-=n;return o+=pO(i)*0.5,Math.max(o,0)}var Qmi=ri("string").narrow((i,o)=>{let n=cO(i);return n>=VY?!0:o.mustBe(`Of complexity ${VY} or more. Was ${n}.`)}).brand("password"),EY=ri({"+":"delete",username:"string",password:"string"}),Vmi=ri("string").brand("email"),OY=ri({"+":"delete",username:"string",password:"string",email:"string"});var V1={100:'"Continue"',101:'"Switching Protocols"',102:'"Processing"',103:'"Early Hints"',200:'"OK"',201:'"Created"',202:'"Accepted"',203:'"Non-Authoritative Information"',204:'"No Content"',205:'"Reset Content"',206:'"Partial Content"',207:'"Multi-Status"',208:'"Already Reported"',226:'"IM Used"',300:'"Multiple Choices"',301:'"Moved Permanently"',302:'"Found"',303:'"See Other"',304:'"Not Modified"',305:'"Use Proxy"',306:'"Switch Proxy"',307:'"Temporary Redirect"',308:'"Permanent Redirect"',400:'"Bad Request"',401:'"Unauthorized"',402:'"Payment Required"',403:'"Forbidden"',404:'"Not Found"',405:'"Method Not Allowed"',406:'"Not Acceptable"',407:'"Proxy Authentication Required"',408:'"Request Timeout"',409:'"Conflict"',410:'"Gone"',411:'"Length Required"',412:'"Precondition Failed"',413:'"Payload Too Large"',414:'"URI Too Long"',415:'"Unsupported Media Type"',416:'"Range Not Satisfiable"',417:'"Expectation Failed"',418:`"I'm a teapot"`,421:'"Misdirected Request"',422:'"Unprocessable Entity"',423:'"Locked"',424:'"Failed Dependency"',425:'"Too Early"',426:'"Upgrade Required"',428:'"Precondition Required"',429:'"Too Many Requests"',431:'"Request Header Fields Too Large"',451:'"Unavailable For Legal Reasons"',500:'"Internal Server Error"',501:'"Not Implemented"',502:'"Bad Gateway"',503:'"Service Unavailable"',504:'"Gateway Timeout"',505:'"HTTP Version Not Supported"',506:'"Variant Also Negotiates"',507:'"Insufficient Storage"',508:'"Loop Detected"',510:'"Not Extended"',511:'"Network Authentication Required"'};function xO(i){return Number.parseInt(i,10)}var TO=ri(V1),mO=TO.keyof().pipe((i)=>xO(i)),_Y=ri([mO,"string"]);var LY=Op({key:"count",default:0}),fO=Tc({key:"incrementTX",do:({set:i})=>{i(LY,(o)=>o+1)}}),CY=m8({key:"countContinuity",config:(i)=>i.add(LY).add(fO)});var DY=RJ(qp,"backend.worker.game.bun",xi),Vc=new dJ({logQuery(i,o){xi.info("\uD83D\uDCDD query",i,o)}});d.STORE.loggers[0]=new pc("info",void 0,xi);var o0i=(()=>{let{__tribunalDaily:i}=globalThis;if(!i)i=new IY.CronJob("00 15 * * * *",()=>{RJ(qp,"backend.worker.tribunal.bun",xi)}),i.start(),process.on("exit",()=>{i.stop(),xi.info("\u231B tribunal daily cronjob stopped")}),xi.info("\u23F3 tribunal daily cronjob started");return i})();function JO(i){if(WJ)return $O(WJ,i);return FO({},i)}var BY=JO((i,o)=>{let n;i.on("data",(p)=>(n??=[]).push(p)).on("end",async()=>{let p=i.headers.authorization;try{if(typeof i.url==="undefined")throw[400,"No URL"];let c=i.socket.remoteAddress;if(!c)throw[400,"No IP address"];let x=new Date,T=new URL(i.url,oo.VITE_BACKEND_ORIGIN);xi.info(x,c,i.method,T.pathname);let m=await Vc.drizzle.query.banishedIps.findFirst({columns:{banishedUntil:!0},where:dn(Q1.ip,c)}),f=m?.banishedUntil===null,F=m?.banishedUntil&&m.banishedUntil>x;if(f||F){xi.info(`\uD83D\uDE45 request from banned ip ${c}`);return}switch(i.method){case"POST":if(!n)throw[400,"No data received"];switch(T.pathname){case`/sign-up-${rJ("sign-up")}`:{let $=Buffer.concat(n).toString(),J=JSON.parse($),A=OY(J);if(A instanceof ri.errors)throw xi.warn("signup parsed",A),[400,"Signup failed"];let{username:X,password:Y,email:R}=A;if(xi.info(`\uD83D\uDD11 attempting to sign up: ${X}`),await Vc.drizzle.query.users.findFirst({columns:{id:!0},where:dn(jn.email,R)}))throw[400,"User already exists"];let H=crypto.randomUUID(),z=yY("sha256").update(Y+H).digest("hex");await Vc.drizzle.insert(jn).values({username:X,email:R,hash:z,salt:H,createdIp:c}),xi.info(`\uD83D\uDD11 user created: ${X}`),o.writeHead(201,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${oo.FRONTEND_ORIGINS[0]}`}),o.end(V1[201])}break;case`/login-${rJ("login")}`:{let $=!1,J=null;try{let A=new Date(+x-600000);xi.info("\uD83D\uDD11 ten minutes ago",{tenMinutesAgo:A,now:x});let X=await Vc.drizzle.query.loginHistory.findMany({columns:{userId:!0,successful:!0},where:wc(dn(Dx.ipAddress,c),dn(Dx.successful,!1),M0(Dx.loginTime,A)),limit:10});xi.info(`\uD83D\uDD11 ${X.length}/10 recent failed logins from ${c}`);let Y=10-X.length;if(Y<1)throw xi.info(`\uD83D\uDD11 too many recent failed logins from ${c}`),await Vc.drizzle.insert(Q1).values({ip:c,reason:"Too many recent login attempts.",banishedAt:x,banishedUntil:new Date(+x+86400000)}),[429,"Too many recent login attempts."];let R=Buffer.concat(n).toString(),K=JSON.parse(R),H=EY(K);if(H instanceof ri.errors)throw xi.warn("login parsed",H),[400,`${Y} attempts remaining.`];let{username:z,password:b}=H,M=await Vc.drizzle.query.users.findFirst({columns:{id:!0,hash:!0,salt:!0},where:dn(jn.username,z)});if(xi.info("\uD83D\uDD11 login attempt as user",z),!M)throw xi.info(`\uD83D\uDD11 user ${z} does not exist`),[400,`${Y} attempts remaining.`];let{hash:u,salt:E}=M;if(J=M.id,yY("sha256").update(b+E).digest("hex")===u){let y=crypto.randomUUID(),l=F1.get(z);if(!l)l=new Map,F1.set(z,l);l.set(y,Number(x)),$=!0,xi.info("\uD83D\uDD11 login successful as",z),o.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${oo.FRONTEND_ORIGINS[0]}`}),o.end(`${z} ${y}`)}}finally{await Vc.drizzle.insert(Dx).values({userId:J,successful:$,ipAddress:c,userAgent:i.headers["user-agent"]??"Withheld"}),xi.info(`\uD83D\uDD11 recorded login attempt from ${c}`)}}break;default:throw[404,"Not found"]}break;case void 0:throw[400,"No Method"];default:throw[405,"Method not allowed"]}}catch(c){let x=_Y(c);if(x instanceof ri.errors)xi.error(c),o.writeHead(500,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${oo.FRONTEND_ORIGINS[0]}`}),o.end("Internal Server Error");else{let[T,m]=x,F=`${V1[T]}. ${m}`;xi.info(`\u274C ${T}: ${F}`),o.writeHead(T,{"Content-Type":"text/plain","Access-Control-Allow-Origin":`${oo.FRONTEND_ORIGINS[0]}`}),o.end(F)}}})}),eJ=BY.listen(oo.BACKEND_PORT).address(),AO=typeof eJ==="string"?null:eJ===null?null:eJ.port;if(AO===null)throw new Error("Could not determine port for test server");new lR(BY,{cors:{origin:oo.FRONTEND_ORIGINS,methods:["GET","POST"]}}).use((i,o)=>{let{username:n,sessionKey:p}=i.handshake.auth;if(!(n&&p)){o(new Error("No auth header provided"));return}let c=`user::${n}`,x=`socket::${i.id}`;if(F1.get(n)?.has(p)){let m=t(d.STORE,em,x);_i(d.STORE,m,i),Ep(mc,(f)=>{f.set(c,x)},d.STORE),_i(d.STORE,GF,(f)=>f.add(c)),_i(d.STORE,YF,(f)=>f.add(x)),xi.info(`${n} connected on ${i.id}`),o()}else xi.info(`${n} couldn't authenticate`),o(new Error("Authentication error"))}).on("connection",(i)=>{let n=X8({socket:i,store:d.STORE})(CY);i.on("disconnect",()=>{let p=`socket::${i.id}`,c=ix(mc,p,d.STORE).userKeyOfSocket,x=Mi(d.STORE,c);if(Ep(mc,(T)=>{T.delete(p)},d.STORE),x)_i(d.STORE,GF,(T)=>(T.delete(x),T));_i(d.STORE,YF,(T)=>(T.delete(p),T)),xi.info(`${i.id} disconnected`),n()})});async function S1(){xi.info("\uD83E\uDDF9 closing workers");let i=new Promise((o)=>DY.process.once("close",o));DY.emit("timeToStop"),await i,xi.info("\uD83D\uDEEC backend server exiting"),process.exit(0)}process.on("SIGINT",async()=>{xi.info("\u2757 received SIGINT; exiting gracefully"),await S1()});process.on("SIGTERM",async()=>{xi.info("\u2757 received SIGTERM; exiting gracefully"),await S1()});process.on("exit",async()=>{xi.info("\u2757 received exit; exiting gracefully"),await S1()});qp.on("updatesReady",()=>{xi.info('\u2757 backend server received signal "updatesReady"'),qp.emit("readyToUpdate"),xi.info('\u2757 backend server has sent signal "readyToUpdate"; now awaits signal "timeToStop"'),qp.on("timeToStop",async()=>{xi.info('\u2757 backend server received signal "timeToStop"; exiting gracefully'),await S1()})});xi.info(`\uD83D\uDEEB backend server ready on port ${oo.BACKEND_PORT}`);qp.emit("alive");export{o0i as tribunalDaily};
|