insite-server 2.0.0 → 2.0.2

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/bun.lockb CHANGED
Binary file
package/dist/InSite.d.ts CHANGED
@@ -8,7 +8,6 @@ import { type AbilitiesSchema, Users } from "insite-users-server";
8
8
  import { UsersServer } from "insite-users-server-ws";
9
9
  import { Optional, Options } from "./types";
10
10
  export declare class InSite<AS extends AbilitiesSchema> {
11
- #private;
12
11
  constructor(options: Options<AS>);
13
12
  mongoClient: MongoClient;
14
13
  db: InSiteDB;
@@ -21,6 +20,7 @@ export declare class InSite<AS extends AbilitiesSchema> {
21
20
  cookie: CookieSetter<AS>;
22
21
  http: InSiteHTTPServer;
23
22
  private init?;
23
+ private initPromise;
24
24
  whenReady(): Promise<this>;
25
25
  static init<IAS extends AbilitiesSchema, IO extends Options<IAS>>(options: IO): Promise<Optional<InSite<IAS>, IO, IAS>>;
26
26
  }
@@ -1 +1 @@
1
- {"version":3,"file":"InSite.d.ts","sourceRoot":"","sources":["../src/InSite.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAA0B,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,mBAAmB,EAAY,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,qBAAqB,EAA+B,MAAM,kBAAkB,CAAC;AACtF,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAEN,KAAK,iBAAiB,EACtB,KAAK,QAAQ,EACb,WAAW,EACX,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,gBAAgB,EAIhB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,KAAK,eAAe,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAG5C,qBAAa,MAAM,CAAC,EAAE,SAAS,eAAe;;gBACjC,OAAO,EAAE,OAAO,CAAC,EAAE,CAAC;IAKhC,WAAW,EAAG,WAAW,CAAC;IAC1B,EAAE,EAAG,QAAQ,CAAC;IACd,WAAW,EAAG,iBAAiB,CAAC;IAChC,GAAG,EAAG,qBAAqB,CAAC;IAC5B,iBAAiB,EAAG,iBAAiB,CAAC;IACtC,mBAAmB,EAAG,mBAAmB,CAAC,EAAE,CAAC,CAAC;IAC9C,WAAW,EAAG,WAAW,CAAC,EAAE,CAAC,CAAC;IAC9B,KAAK,EAAG,KAAK,CAAC,EAAE,CAAC,CAAC;IAClB,MAAM,EAAG,YAAY,CAAC,EAAE,CAAC,CAAC;IAC1B,IAAI,EAAG,gBAAgB,CAAC;IAExB,OAAO,CAAC,IAAI,CAAC,CA+EX;IAIF,SAAS;IAKT,MAAM,CAAC,IAAI,CACV,GAAG,SAAS,eAAe,EAC3B,EAAE,SAAS,OAAO,CAAC,GAAG,CAAC,EACtB,OAAO,EAAE,EAAE,GACgC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,GAAG,CAAC,CAAC;CAGpF"}
1
+ {"version":3,"file":"InSite.d.ts","sourceRoot":"","sources":["../src/InSite.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAA0B,MAAM,sBAAsB,CAAC;AAC5E,OAAO,EAAE,mBAAmB,EAAY,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,qBAAqB,EAA+B,MAAM,kBAAkB,CAAC;AACtF,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAEN,KAAK,iBAAiB,EACtB,KAAK,QAAQ,EACb,WAAW,EACX,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,gBAAgB,EAIhB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,KAAK,eAAe,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAG5C,qBAAa,MAAM,CAAC,EAAE,SAAS,eAAe;gBACjC,OAAO,EAAE,OAAO,CAAC,EAAE,CAAC;IAKhC,WAAW,EAAG,WAAW,CAAC;IAC1B,EAAE,EAAG,QAAQ,CAAC;IACd,WAAW,EAAG,iBAAiB,CAAC;IAChC,GAAG,EAAG,qBAAqB,CAAC;IAC5B,iBAAiB,EAAG,iBAAiB,CAAC;IACtC,mBAAmB,EAAG,mBAAmB,CAAC,EAAE,CAAC,CAAC;IAC9C,WAAW,EAAG,WAAW,CAAC,EAAE,CAAC,CAAC;IAC9B,KAAK,EAAG,KAAK,CAAC,EAAE,CAAC,CAAC;IAClB,MAAM,EAAG,YAAY,CAAC,EAAE,CAAC,CAAC;IAC1B,IAAI,EAAG,gBAAgB,CAAC;IAExB,OAAO,CAAC,IAAI,CAAC,CA+EX;IAEF,OAAO,CAAC,WAAW,CAAC;IAEpB,SAAS;IAKT,MAAM,CAAC,IAAI,CACV,GAAG,SAAS,eAAe,EAC3B,EAAE,SAAS,OAAO,CAAC,GAAG,CAAC,EACtB,OAAO,EAAE,EAAE,GACgC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,GAAG,CAAC,CAAC;CAGpF"}
package/dist/index.js CHANGED
@@ -1,6 +1,12 @@
1
- var lt=Object.create;var he=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var ct=Object.getPrototypeOf,dt=Object.prototype.hasOwnProperty;var y=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof require<"u"?require:t)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var R=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var pt=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ut(t))!dt.call(e,r)&&r!==s&&he(e,r,{get:()=>t[r],enumerable:!(i=at(t,r))||i.enumerable});return e};var fe=(e,t,s)=>(s=e!=null?lt(ct(e)):{},pt(t||!e||!e.__esModule?he(s,"default",{value:e,enumerable:!0}):s,e));var ge=R((ls,we)=>{var W=/^[a-z0-9-]{1,32}$/,N=/^[a-z0-9-]{1,32}$/,K=/^[a-zA-Z0-9/+.-]+$/,me=/^([a-zA-Z0-9/+.-]+|)$/,ht=/^((-)?[1-9]\d*|0)$/,Z=/^v=(\d+)$/;function ft(e){return q(e).map(t=>[t,e[t]].join("=")).join(",")}function mt(e){let t={};return e.split(",").forEach(s=>{let i=s.split("=");if(i.length<2)throw new TypeError("params must be in the format name=value");t[i.shift()]=i.join("=")}),t}function q(e){return Object.keys(e)}function ve(e){return typeof Object.values=="function"?Object.values(e):q(e).map(t=>e[t])}function vt(e){let t=[""];if(typeof e!="object"||e===null)throw new TypeError("opts must be an object");if(typeof e.id!="string")throw new TypeError("id must be a string");if(!W.test(e.id))throw new TypeError(`id must satisfy ${W}`);if(t.push(e.id),typeof e.version<"u"){if(typeof e.version!="number"||e.version<0||!Number.isInteger(e.version))throw new TypeError("version must be a positive integer number");t.push(`v=${e.version}`)}if(typeof e.params<"u"){if(typeof e.params!="object"||e.params===null)throw new TypeError("params must be an object");let i=q(e.params);if(!i.every(o=>N.test(o)))throw new TypeError(`params names must satisfy ${N}`);i.forEach(o=>{typeof e.params[o]=="number"?e.params[o]=e.params[o].toString():Buffer.isBuffer(e.params[o])&&(e.params[o]=e.params[o].toString("base64").split("=")[0])});let r=ve(e.params);if(!r.every(o=>typeof o=="string"))throw new TypeError("params values must be strings");if(!r.every(o=>K.test(o)))throw new TypeError(`params values must satisfy ${K}`);let n=ft(e.params);t.push(n)}if(typeof e.salt<"u"){if(!Buffer.isBuffer(e.salt))throw new TypeError("salt must be a Buffer");if(t.push(e.salt.toString("base64").split("=")[0]),typeof e.hash<"u"){if(!Buffer.isBuffer(e.hash))throw new TypeError("hash must be a Buffer");t.push(e.hash.toString("base64").split("=")[0])}}return t.join("$")}function wt(e){if(typeof e!="string"||e==="")throw new TypeError("pchstr must be a non-empty string");if(e[0]!=="$")throw new TypeError("pchstr must contain a $ as first char");let t=e.split("$");t.shift();let s=5;if(Z.test(t[1])||s--,t.length>s)throw new TypeError(`pchstr contains too many fileds: ${t.length}/${s}`);let i=t.shift();if(!W.test(i))throw new TypeError(`id must satisfy ${W}`);let r;Z.test(t[0])&&(r=parseInt(t.shift().match(Z)[1],10));let n,o;me.test(t[t.length-1])&&(t.length>1&&me.test(t[t.length-2])&&(n=Buffer.from(t.pop(),"base64")),o=Buffer.from(t.pop(),"base64"));let a;if(t.length>0){let d=t.pop();if(a=mt(d),!q(a).every(c=>N.test(c)))throw new TypeError(`params names must satisfy ${N}`);if(!ve(a).every(c=>K.test(c)))throw new TypeError(`params values must satisfy ${K}`);q(a).forEach(c=>{a[c]=ht.test(a[c])?parseInt(a[c],10):a[c]})}if(t.length>0)throw new TypeError(`pchstr contains unrecognized fileds: ${t}`);let l={id:i};return r&&(l.version=r),a&&(l.params=a),o&&(l.salt=o),n&&(l.hash=n),l}we.exports={serialize:vt,deserialize:wt}});var Le=R((as,qe)=>{var xe=y("fs"),O=y("path"),Oe=y("os"),Se=typeof __webpack_require__=="function"?__non_webpack_require__:y,gt=process.config&&process.config.variables||{},bt=!!process.env.PREBUILDS_ONLY,be=process.versions.modules,G=xt()?"electron":_t()?"node-webkit":"node",X=process.env.npm_config_arch||Oe.arch(),Y=process.env.npm_config_platform||Oe.platform(),Ie=process.env.LIBC||(Ot(Y)?"musl":"glibc"),Q=process.env.ARM_VERSION||(X==="arm64"?"8":gt.arm_version)||"",Te=(process.versions.uv||"").split(".")[0];qe.exports=_;function _(e){return Se(_.resolve(e))}_.resolve=_.path=function(e){e=O.resolve(e||".");try{var t=Se(O.join(e,"package.json")).name.toUpperCase().replace(/-/g,"_");process.env[t+"_PREBUILD"]&&(e=process.env[t+"_PREBUILD"])}catch{}if(!bt){var s=ye(O.join(e,"build/Release"),_e);if(s)return s;var i=ye(O.join(e,"build/Debug"),_e);if(i)return i}var r=a(e);if(r)return r;var n=a(O.dirname(process.execPath));if(n)return n;var o=["platform="+Y,"arch="+X,"runtime="+G,"abi="+be,"uv="+Te,Q?"armv="+Q:"","libc="+Ie,"node="+process.versions.node,process.versions.electron?"electron="+process.versions.electron:"",typeof __webpack_require__=="function"?"webpack=true":""].filter(Boolean).join(" ");throw new Error("No native build was found for "+o+`
2
- loaded from: `+e+`
3
- `);function a(l){var d=ee(O.join(l,"prebuilds")).map(Ae),p=d.filter(je(Y,X)).sort($e)[0];if(p){var u=O.join(l,"prebuilds",p.name),c=ee(u).map(Ee),m=c.filter(Me(G,be)),S=m.sort(Re(G))[0];if(S)return O.join(u,S.file)}}};function ee(e){try{return xe.readdirSync(e)}catch{return[]}}function ye(e,t){var s=ee(e).filter(t);return s[0]&&O.join(e,s[0])}function _e(e){return/\.node$/.test(e)}function Ae(e){var t=e.split("-");if(t.length===2){var s=t[0],i=t[1].split("+");if(s&&i.length&&i.every(Boolean))return{name:e,platform:s,architectures:i}}}function je(e,t){return function(s){return s==null||s.platform!==e?!1:s.architectures.includes(t)}}function $e(e,t){return e.architectures.length-t.architectures.length}function Ee(e){var t=e.split("."),s=t.pop(),i={file:e,specificity:0};if(s==="node"){for(var r=0;r<t.length;r++){var n=t[r];if(n==="node"||n==="electron"||n==="node-webkit")i.runtime=n;else if(n==="napi")i.napi=!0;else if(n.slice(0,3)==="abi")i.abi=n.slice(3);else if(n.slice(0,2)==="uv")i.uv=n.slice(2);else if(n.slice(0,4)==="armv")i.armv=n.slice(4);else if(n==="glibc"||n==="musl")i.libc=n;else continue;i.specificity++}return i}}function Me(e,t){return function(s){return!(s==null||s.runtime&&s.runtime!==e&&!yt(s)||s.abi&&s.abi!==t&&!s.napi||s.uv&&s.uv!==Te||s.armv&&s.armv!==Q||s.libc&&s.libc!==Ie)}}function yt(e){return e.runtime==="node"&&e.napi}function Re(e){return function(t,s){return t.runtime!==s.runtime?t.runtime===e?-1:1:t.abi!==s.abi?t.abi?-1:1:t.specificity!==s.specificity?t.specificity>s.specificity?-1:1:0}}function _t(){return!!(process.versions&&process.versions.nw)}function xt(){return process.versions&&process.versions.electron||process.env.ELECTRON_RUN_AS_NODE?!0:typeof window<"u"&&window.process&&window.process.type==="renderer"}function Ot(e){return e==="linux"&&xe.existsSync("/etc/alpine-release")}_.parseTags=Ee;_.matchTags=Me;_.compareTags=Re;_.parseTuple=Ae;_.matchTuple=je;_.compareTuples=$e});var De=R((cs,se)=>{var te=typeof __webpack_require__=="function"?__non_webpack_require__:y;typeof te.addon=="function"?se.exports=te.addon.bind(te):se.exports=Le()});var We=R((ps,I)=>{var St=y("node:assert"),{randomBytes:It,timingSafeEqual:Tt}=y("node:crypto"),{promisify:At}=y("node:util"),{deserialize:ke,serialize:jt}=ge(),$t=De(),{hash:Be}=$t(__dirname),Et=At(It),Pe=0,Ce=1,ie=2;I.exports.argon2d=Pe;I.exports.argon2i=Ce;I.exports.argon2id=ie;var L=Object.freeze({argon2d:Pe,argon2i:Ce,argon2id:ie}),Mt=Object.freeze({[L.argon2d]:"argon2d",[L.argon2i]:"argon2i",[L.argon2id]:"argon2id"}),Ue=Object.freeze({hashLength:32,timeCost:3,memoryCost:65536,parallelism:4,type:ie,version:19}),ze=Object.freeze({hashLength:{min:4,max:2**32-1},memoryCost:{min:1024,max:2**32-1},timeCost:{min:2,max:2**32-1},parallelism:{min:1,max:2**24-1}});I.exports.limits=ze;async function Rt(e,t){let{raw:s,salt:i,...r}={...Ue,...t};for(let[S,{min:A,max:b}]of Object.entries(ze)){let w=r[S];St(A<=w&&w<=b,`Invalid ${S}, must be between ${A} and ${b}.`)}i=i??await Et(16);let{hashLength:n,secret:o=Buffer.alloc(0),type:a,version:l,memoryCost:d,timeCost:p,parallelism:u,associatedData:c=Buffer.alloc(0)}=r,m=await Be({password:Buffer.from(e),salt:i,secret:o,data:c,hashLength:n,m:d,t:p,p:u,version:l,type:a});return s?m:jt({id:Mt[a],version:l,params:{m:d,t:p,p:u,...c.byteLength>0?{data:c}:{}},salt:i,hash:m})}I.exports.hash=Rt;function qt(e,t={}){let{memoryCost:s,timeCost:i,version:r}={...Ue,...t},{version:n,params:{m:o,t:a}}=ke(e);return+n!=+r||+o!=+s||+a!=+i}I.exports.needsRehash=qt;async function Lt(e,t,s={}){let{id:i,...r}=ke(e);if(!(i in L))return!1;let{version:n=16,params:{m:o,t:a,p:l,data:d=""},salt:p,hash:u}=r,{secret:c=Buffer.alloc(0)}=s;return Tt(await Be({password:Buffer.from(t),salt:p,secret:c,data:Buffer.from(d,"base64"),hashLength:u.byteLength,m:+o,t:+a,p:+l,version:+n,type:L[i]}),u)}I.exports.verify=Lt});var Ke=R((hs,re)=>{"use strict";var Dt=Object.prototype.hasOwnProperty,f="~";function D(){}Object.create&&(D.prototype=Object.create(null),new D().__proto__||(f=!1));function kt(e,t,s){this.fn=e,this.context=t,this.once=s||!1}function Ne(e,t,s,i,r){if(typeof s!="function")throw new TypeError("The listener must be a function");var n=new kt(s,i||e,r),o=f?f+t:t;return e._events[o]?e._events[o].fn?e._events[o]=[e._events[o],n]:e._events[o].push(n):(e._events[o]=n,e._eventsCount++),e}function F(e,t){--e._eventsCount===0?e._events=new D:delete e._events[t]}function h(){this._events=new D,this._eventsCount=0}h.prototype.eventNames=function(){var t=[],s,i;if(this._eventsCount===0)return t;for(i in s=this._events)Dt.call(s,i)&&t.push(f?i.slice(1):i);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(s)):t};h.prototype.listeners=function(t){var s=f?f+t:t,i=this._events[s];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,o=new Array(n);r<n;r++)o[r]=i[r].fn;return o};h.prototype.listenerCount=function(t){var s=f?f+t:t,i=this._events[s];return i?i.fn?1:i.length:0};h.prototype.emit=function(t,s,i,r,n,o){var a=f?f+t:t;if(!this._events[a])return!1;var l=this._events[a],d=arguments.length,p,u;if(l.fn){switch(l.once&&this.removeListener(t,l.fn,void 0,!0),d){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,s),!0;case 3:return l.fn.call(l.context,s,i),!0;case 4:return l.fn.call(l.context,s,i,r),!0;case 5:return l.fn.call(l.context,s,i,r,n),!0;case 6:return l.fn.call(l.context,s,i,r,n,o),!0}for(u=1,p=new Array(d-1);u<d;u++)p[u-1]=arguments[u];l.fn.apply(l.context,p)}else{var c=l.length,m;for(u=0;u<c;u++)switch(l[u].once&&this.removeListener(t,l[u].fn,void 0,!0),d){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,s);break;case 3:l[u].fn.call(l[u].context,s,i);break;case 4:l[u].fn.call(l[u].context,s,i,r);break;default:if(!p)for(m=1,p=new Array(d-1);m<d;m++)p[m-1]=arguments[m];l[u].fn.apply(l[u].context,p)}}return!0};h.prototype.on=function(t,s,i){return Ne(this,t,s,i,!1)};h.prototype.once=function(t,s,i){return Ne(this,t,s,i,!0)};h.prototype.removeListener=function(t,s,i,r){var n=f?f+t:t;if(!this._events[n])return this;if(!s)return F(this,n),this;var o=this._events[n];if(o.fn)o.fn===s&&(!r||o.once)&&(!i||o.context===i)&&F(this,n);else{for(var a=0,l=[],d=o.length;a<d;a++)(o[a].fn!==s||r&&!o[a].once||i&&o[a].context!==i)&&l.push(o[a]);l.length?this._events[n]=l.length===1?l[0]:l:F(this,n)}return this};h.prototype.removeAllListeners=function(t){var s;return t?(s=f?f+t:t,this._events[s]&&F(this,s)):(this._events=new D,this._eventsCount=0),this};h.prototype.off=h.prototype.removeListener;h.prototype.addListener=h.prototype.on;h.prefixed=f;h.EventEmitter=h;typeof re<"u"&&(re.exports=h)});import{CookieSetter as Gt,InSiteCookieMiddleware as Xt}from"insite-cookie/server";import{SubscriptionHandler as Yt}from"insite-subscriptions-server/ws";import{InSiteWebSocketServer as Qt}from"insite-ws/server";import{IncomingTransport as es}from"insite-ws-transfers/node";import{connect as ts}from"insite-db";import{InSiteHTTPServer as ss,InSiteStaticMiddleware as is,InSiteTemplateMiddleware as rs}from"insite-http";var z=fe(We(),1);var Fe=fe(Ke(),1);var He=Fe.default;function k(e){if(e instanceof Set){let t=[];for(let s of e)t.push(s._id);return t}return e.map(t=>t._id)}function $(){}function x(e,t=0,s={}){let{leading:i=!1,trailing:r=!0}=s,{maxWait:n=1/0}=s,o,a,l,d,p,u,c,m,S=async()=>{let j=Date.now();j>=l?(o=void 0,l=void 0,clearTimeout(a),typeof c=="function"&&await c(),w.resolve(m),w.promise.isResolved=!0,u=i):(clearTimeout(o),o=setTimeout(S,l-j))},A=Number.isFinite(n)?()=>{c===b&&(c=!1),b(),a=setTimeout(A,n)}:null;async function b(){return m=await e.apply(d,p)}i&&typeof i=="boolean"&&(i=b),u=i,r&&typeof r=="boolean"&&(r=b),c=r;let w=Object.assign(function(...j){return p=j,d=this,l=Date.now()+t,c=r,w.promise.isResolved&&(w.promise=Object.assign(new Promise(ot=>{w.resolve=ot,typeof u=="function"&&(u(),u=!1,c===b&&(c=!1)),o||(o=setTimeout(S,t),A&&(a=setTimeout(A,n)))}),{isResolved:!1})),w.promise},{callback:e,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:$,run:b,clear:async j=>{clearTimeout(o),o=void 0,clearTimeout(a),w.promise.isResolved=!0,w.resolve(j?await b():m)}});return w}x.noop=Object.assign(()=>{},{callback:$,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:$,run:$,clear:$});function g(e,t){if(e){for(let s of t)delete e[s];return e}return null}function Ve(e){for(let t in e)delete e[t];return e}var H=class extends Array{constructor(){super(),Object.freeze(this)}push(){return 0}unshift(){return 0}splice(){return[]}};var E=class extends Set{constructor(){super()}add(){return this}};function ne(e,t,s=!1){return s&&(t=t.filter(i=>e.has(i))),t.map(i=>e.get(i))}function Je(e,t){for(let s of t)if(e.has(s))return!0;return!1}function Ze(e,t,s,i,r=!0){return Array.isArray(e)&&(e=e.length),typeof i!="string"&&(r=i??!0,i=s),(r?`${e}\xA0`:"")+Ze.raw(e,t,s,i)}Ze.raw=(e,t,s,i=s)=>{e=Math.abs(e);let r=e%10,n=e%100;return r===1&&n!==11?t:r>=2&&r<=4&&!(n>=12&&n<=15)?s:i};function Ge(e,...t){let s=[];e:for(let i of e){for(let r of t)if(r instanceof Set?!r.has(i):!r.includes(i))continue e;s.push(i)}return s}function V(e,t){return Math.floor(Math.random()*(t-e+1)+e)}function Xe(e,t){return e.delete(t),e.add(t),e}function T(e,t){let s,i=0;for(let r of t)for(;(s=e.indexOf(r))>-1;)e.splice(s,1),i++;return i}function Ye(e,t){let s=e.indexOf(t);return s>-1?(e.splice(s,1),!0):!1}function Qe(e,t){for(let s of[...e].sort(t))e.delete(s),e.add(s);return e}import{newObjectIdString as Bt}from"insite-db";import{newObjectIdString as Ct}from"insite-db";import st from"node:crypto";var Pt=class extends Map{constructor(e){super(),this.schema=e,this.#e(this.schema)}schema;#e(e){for(let t of e)this.set(t._id,t),t.subAbilities&&this.#e(t.subAbilities)}merge(e,t){for(let[s,i]of Object.entries(t)){let r=this.get(s);if(r){if(r.isInheritable!==!1&&i){if(!(s in e))e[s]=structuredClone(i);else if(r.params){let n=e[s],o=i;for(let a of r.params)if(a.isInheritable!==!1&&a._id in o){if(!(a._id in n))n[a._id]=structuredClone(o[a._id]);else if(a.type==="number")n[a._id]<o[a._id]&&(n[a._id]=o[a._id]);else if(a.type==="items"){let l=n[a._id];for(let d of o[a._id])l.includes(d)||l.push(d)}}}}}else delete t[s]}return e}getMinimumOf(e){let t=this.get(e);if(t?.params){let s={};for(let i of t.params)i.type==="number"?s[i._id]=i.min??0:i.type==="items"&&(s[i._id]=[]);return s}return!0}getMaximum(){return[...this.values()].reduce((e,t)=>{if(t.params){let s={};for(let i of t.params)i.type==="number"?s[i._id]=i.max??0:i.type==="items"&&(s[i._id]=i.items.map(r=>r._id));e[t._id]=s}else e[t._id]=!0;return e},{})}getSchemeFor(e){return function t(s){for(let i=0;i<s.length;i++){let r=s[i],n=e.abilities[r._id];if(n){if(r.params)for(let o of r.params){let a=n[o._id];if(o.type==="number")"max"in o&&(o.max=a);else if(o.type==="items")for(let l=0;l<o.items.length;l++)a.includes(o.items[l]._id)||o.items.splice(l--,1)}r.subAbilities&&t(r.subAbilities)}else s.splice(i--,1)}return s}(structuredClone(this.schema))}},oe=new Map,M=class{constructor(e,t){this.orgs=e,this._id=t._id,e.set(this._id,this),this.update(t)}_id;title="";initials="";displayLabel="";_o=0;orgs;isOrg=!0;ownerOrgs=new Set;ownerUsers=new Set;users=new Set;slaveOrgs=new Set;ownerIds=[];update({_id:e,title:t,owners:s,...i},r){if(Object.assign(this,i),t!==void 0&&(this.title=t,this.initials=t?.[0]?.toUpperCase()??"",this.displayLabel=t),s){this.ownerIds=s;let n=this.ownerIds.join(",");n!==oe.get(this._id)&&(oe.set(this._id,n),this.orgs.users.isInited&&this.orgs.updateDebounced(),this.orgs.users.emit("orgs-org-update",this,r))}}delete(){this.orgs.delete(this._id),oe.delete(this._id),this.orgs.replace(this._id),this.orgs.updateDebounced()}},v={_id:/^[\dA-Fa-f]{24}$/,email:/^[^\s@]{1,63}@[^\s@]{1,63}\.[^\s@]{1,63}$/,argon2:/^\$argon2(?:i|d|id)\$v=\d+\$m=\d+,t=\d+,p=\d+(?:\$[\d+/A-Za-z]+){2}$/,sessionId:/^[\dA-Fa-f]{16,32}\$[\dA-Fa-f]{16,32}$/,role:/^[\d_a-z-]{1,64}$/,ip:/^(?:\d{1,3}\.){3}\d{1,3}$/},B={required:["_id","title","note","owners","createdAt"],properties:{_id:{bsonType:"string",pattern:v._id.source},title:{bsonType:"string",maxLength:512},note:{bsonType:"string",maxLength:131072},owners:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:v._id.source},additionalItems:!1},createdAt:{bsonType:"number"}},additionalProperties:!1},Ut=[[{owners:1}]];function et(){throw new Error("Direct usage of orgs collection.deleteOne or .deleteMany is forbidden. Use orgs.collectionDelete instead.")}var zt=class extends Map{constructor(e,t={}){super(),this.users=e,this.collections=e.collections,this.preinitOptions=t}users;collections;preinitOptions;collection;null;load(e){new M(this,e)}#e(e,t){t=[e,...t];for(let s of e.ownerOrgs){this.#e(s,t);for(let i of t)s.slaveOrgs.add(i)}}sorted=[];update(){let e=[...this.values()],t=[];for(let s of e){s.ownerOrgs.clear(),s.ownerUsers.clear(),s.slaveOrgs.clear();for(let i of s.ownerIds){let r=this.get(i);if(r)s.ownerOrgs.add(r);else{let n=this.users.get(i);n&&s.ownerUsers.add(n)}}!s.ownerOrgs.size&&s._id&&t.push(s)}for(let s of e)e.some(i=>i.ownerOrgs.has(s))||this.#e(s,[]);t.sort(this.#t);for(let s of e)Qe(s.slaveOrgs,this.#t);for(let s=0;s<t.length;s++){let i=t[s];for(let r of[...i.slaveOrgs].reverse())if(r.ownerOrgs.has(i)){let n=t.indexOf(r);~n&&(t.splice(n,1),s--),t.splice(s+1,0,r)}}for(let{length:s}=t,i=0;i<s;)t[i]._o=i++;this.sorted=t,this.users.emit("orgs-update"),this.users.isInited&&(this.users.updateDebounced.clear(),this.users.update())}#t(e,t){return t.slaveOrgs.size-e.slaveOrgs.size||(e.title>t.title?1:e.title<t.title?-1:0)}updateDebounced=x(this.update,250);preinit=async()=>{let{schema:e,indexes:t,null:s}=this.preinitOptions;e&&(e.required&&T(e.required,B.required),e.properties&&g(e,Object.keys(B.properties)));let i={...B,...e,required:[...B.required,...e?.required??[]],properties:{...B.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("orgs",{jsonSchema:i}),{deleteOne:et,deleteMany:et}),this.collection.ensureIndexes([...Ut,...t??[]]),this.null=Object.assign(new M(this,{...s,_id:"",title:"",note:"",owners:[],createdAt:Date.now()}),{_id:null,ownerIds:new H,ownerOrgs:new E,ownerUsers:new E,slaveOrgs:new E});for(let r of await this.collection.find().toArray())this.load(r);delete this.preinitOptions,delete this.preinit};init=async()=>{await this.update(),this.collection.changeListeners.add(e=>{switch(e.operationType){case"insert":{let t=new M(this,e.fullDocument);this.users.emit("orgs-org-update",t,e);break}case"replace":this.get(e.documentKey._id)?.update(e.fullDocument,e);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields,e);break;case"delete":this.get(e.documentKey._id)?.delete(),this.users.emit("orgs-org-update",null,e)}}),delete this.init};new({title:e,note:t,...s},i){return this.collection.insertOne({_id:Ct(),title:e??"",note:t??"",owners:i?[i]:[],...g(s,["_id","owners"]),createdAt:Date.now()})}collectionDelete(e){let t=typeof e=="string"?e:e._id;return this.collection.bulkWrite([{updateMany:{filter:{owners:t},update:{$pullAll:{owners:[t]}}}},{deleteOne:{filter:{_id:t}}}])}replaceMap=new Map;replaceHandlers=new Set;async replace(e){let t=this.replaceMap.get(e)??null;t&&this.replaceMap.delete(e);for(let s of this.replaceHandlers)await s(e,t)}},le=new Map,ae=class{constructor(e,t){this.roles=e,this._id=t._id,e.set(this._id,this),this.update(t)}roles;_id;ownInvolveIds;ownAbilities;title="";displayTitle="";_o=0;ownInvolves=[];involves=new Set;abilities={};inheritedAbilities={};update({_id:e,involves:t,abilities:s,title:i,...r},n){if(Object.assign(this,r),t&&(this.ownInvolveIds=t),s&&(this.ownAbilities=s),i!==void 0&&(this.title=i,this.displayTitle=i||this._id),t||s){let o=[this.ownInvolveIds.join(","),JSON.stringify(this.ownAbilities)].join(`
4
- `);o!==le.get(this._id)&&(le.set(this._id,o),this.roles.users.isInited&&this.roles.updateDebounced(),this.roles.users.emit("roles-role-update",this,n))}}delete(){this.roles.delete(this._id),le.delete(this._id),this.roles.updateDebounced()}},P={required:["_id","involves","abilities","title","description","createdAt"],properties:{_id:{bsonType:"string",pattern:v.role.source,not:{enum:["root"]}},involves:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:v.role.source,not:{enum:["root"]}},additionalItems:!1},abilities:{bsonType:"object"},title:{bsonType:"string",maxLength:256},description:{bsonType:"string",maxLength:10240},createdAt:{bsonType:"number"}},additionalProperties:!1},Wt=[[{involves:1}]];function tt(){throw new Error("Direct usage of roles collection.deleteOne or .deleteMany is forbidden. Use roles.collectionDelete instead.")}var Nt=class extends Map{constructor(e,t={}){super();let{root:s,...i}=t;this.users=e,this.collections=e.collections,this.abilitiesMap=e.abilitiesMap,this.root=new ae(this,{...s,_id:"root",involves:[],abilities:this.abilitiesMap.getMaximum(),title:"Root",description:"Root",createdAt:Date.now()}),this.initOptions=i}users;collections;collection;abilitiesMap;root;initOptions;load(e){new ae(this,e)}resolve(e,t){t=[e,...t];for(let s of e.ownInvolveIds){let i=this.get(s);if(i){for(let r of t)Xe(r.involves,i),this.abilitiesMap.merge(r.inheritedAbilities,i.abilities);i!==e&&this.resolve(i,t)}}}sorted=[];#e(e,t){return t.involves.size-e.involves.size||(e.title&&t.title?e.title>t.title?1:e.title<t.title?-1:0:e.title?-1:t.title||e._id>t._id?1:e._id<t._id?-1:0)}update(){let e=[...this.values()];this.root.ownInvolveIds=[];for(let i of e)i!==this.root&&!e.some(r=>r.ownInvolveIds.includes(i._id))&&this.root.ownInvolveIds.push(i._id),i.involves.clear(),i.abilities=structuredClone(i.ownAbilities),i.inheritedAbilities={};this.root.involves.add(this.root),this.resolve(this.root,[]);for(let i of e)i.ownInvolves=ne(this,i.ownInvolveIds,!0).sort(this.#e).reverse();let t=[this.root];for(let i=0;i<t.length;i++){let r=t[i];for(let n of r.ownInvolves){let o=t.indexOf(n);~o&&(t.splice(o,1),i--),t.splice(i+1,0,n)}}let s=0;for(let i of t)this.abilitiesMap.merge(i.abilities,i.inheritedAbilities),i._o=s++;this.sorted=t,this.users.emit("roles-update"),this.users.isInited&&(this.users.updateDebounced.clear(),this.users.update(!0))}updateDebounced=x(this.update,250);init=async()=>{let{schema:e,indexes:t}=this.initOptions;e&&(e.required&&T(e.required,P.required),e.properties&&g(e,Object.keys(P.properties)));let s={...P,...e,required:[...P.required,...e?.required??[]],properties:{...P.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("roles",{jsonSchema:s}),{deleteOne:tt,deleteMany:tt}),this.collection.ensureIndexes([...Wt,...t??[]]);for(let i of await this.collection.find().toArray())this.load(i);await this.update(),this.collection.changeListeners.add(i=>{switch(i.operationType){case"insert":{let r=new ae(this,i.fullDocument);this.users.emit("roles-role-update",r,i);break}case"replace":this.get(i.documentKey._id)?.update(i.fullDocument,i);break;case"update":this.get(i.documentKey._id)?.update(i.updateDescription.updatedFields,i);break;case"delete":this.get(i.documentKey._id)?.delete(),this.users.emit("roles-role-update",null,i)}}),delete this.initOptions,delete this.init};new({_id:e,involves:t,title:s,description:i,...r}){return this.collection.insertOne({_id:e,involves:t||[],abilities:{},title:s??"",description:i??"",...g(r,["abilities"]),createdAt:Date.now()})}collectionDelete(e){let t=typeof e=="string"?e:e._id;return this.collection.bulkWrite([{updateMany:{filter:{involves:t},update:{$pullAll:{involves:[t]}}}},{deleteOne:{filter:{_id:t}}}])}cleanUpIds(e){let t=Ge(this.sorted,ne(this,e,!0)),s=[];for(let i of t)t.every(r=>r===i||!r.involves.has(i))&&s.push(i._id);return s}},C={required:["_id","user","remoteAddress","isOnline","createdAt","prolongedAt","expiresAt"],properties:{_id:{bsonType:"string",pattern:v.sessionId.source},user:{bsonType:"string",pattern:v._id.source},userAgent:{bsonType:"string",maxLength:4096},remoteAddress:{bsonType:"string",pattern:v.ip.source},isOnline:{bsonType:"bool"},createdAt:{bsonType:"number"},prolongedAt:{bsonType:"number"},expiresAt:{bsonType:"date"}},additionalProperties:!1},ue=class{constructor(e,t){let s=e.users.get(t.user);s?(this.sessions=e,this._id=t._id,this.sessions.set(this._id,this),this.user=s,this.user.sessions.add(this),this.sessions.users.bySessionId.set(this._id,this.user),this.update(t)):e.collection.deleteOne({_id:t._id})}_id;user;isOnline=!1;userAgent;remoteAddress;createdAt;prolongedAt;expiresAt;sessions;update({_id:e,user:t,isOnline:s,...i}){s!==void 0&&this.isOnline!==s&&(this.isOnline=s,this.sessions.isInited&&this.user.isOnline!==this.isOnline&&this.user.updateIsOnline()),Object.assign(this,i)}prolong({_id:e,user:t,...s}){let i=Date.now();return s.prolongedAt=i,s.expiresAt=new Date(i+this.sessions.collection.expireAfterSeconds*1e3),this.update(s),this.sessions.collection.updateOne({_id:this._id},{$set:s})}offline(){let e={isOnline:!1};return this.update(e),this.sessions.collection.updateOne({_id:this._id},{$set:e})}delete(){this.sessions.delete(this._id),this.user.sessions.delete(this),this.sessions.users.bySessionId.delete(this._id),this.sessions.users.emit("session-delete",this),this.isOnline&&this.user.updateIsOnline()}},pe=3600*24*7,Kt=[[{user:1}],[{expiresAt:1},{expireAfterSeconds:pe}]],Ft=class extends Map{constructor(e,t={}){super(),this.users=e,this.collections=e.collections,this.initOptions=t}users;collections;initOptions;collection;isInited=!1;uid(){let e;do e=`${st.randomBytes(V(8,16)).toString("hex")}$${st.randomBytes(V(8,16)).toString("hex")}`;while(this.has(e));return e}load(e){new ue(this,e)}init=async()=>{let{schema:e,indexes:t}=this.initOptions;e&&(e.required&&T(e.required,C.required),e.properties&&g(e,Object.keys(C.properties)));let s={...C,...e,required:[...C.required,...e?.required??[]],properties:{...C.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("sessions",{jsonSchema:s}),{expireAfterSeconds:pe}),this.collection.ensureIndexes([...Kt,...t??[]]),await this.collection.updateMany({isOnline:!0},{$set:{isOnline:!1}});for(let i of await this.collection.find().toArray())this.load(i);this.collection.changeListeners.add(i=>{switch(i.operationType){case"insert":this.has(i.documentKey._id)||new ue(this,i.fullDocument),this.users.get(i.fullDocument.user)?.trimSessions();break;case"replace":this.get(i.documentKey._id)?.update(i.fullDocument);break;case"update":this.get(i.documentKey._id)?.update(i.updateDescription.updatedFields);break;case"delete":this.get(i.documentKey._id)?.delete()}}),this.isInited=!0,delete this.initOptions,delete this.init};async new(e,t){let s=Date.now(),i={userAgent:"",remoteAddress:"127.0.0.1",isOnline:!0,...t,_id:this.uid(),user:e._id,createdAt:s,prolongedAt:s,expiresAt:new Date(s+pe*1e3)},r=new ue(this,i);return await this.collection.insertOne(i),r}},Ht={required:["_id","type","size","ts","data"],properties:{_id:{bsonType:"string",pattern:v._id.source},type:{bsonType:"string",maxLength:256},size:{bsonType:"number"},ts:{bsonType:"string",maxLength:10},data:{bsonType:"binData"}},additionalProperties:!1},Vt=class{constructor(e){this.users=e,this.collections=e.collections}users;collections;collection;init=async()=>{this.collection=await this.collections.ensure("users.avatars",{jsonSchema:Ht}),delete this.init}},U={required:["_id","email","password","roles","name","org","job","createdAt"],properties:{_id:{bsonType:"string",pattern:v._id.source},email:{bsonType:"string",pattern:v.email.source},password:{bsonType:"string",pattern:v.argon2.source},roles:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:v.role.source},additionalItems:!1},name:{bsonType:"object",required:["first","middle","last"],properties:{first:{bsonType:"string",maxLength:512},middle:{bsonType:"string",maxLength:512},last:{bsonType:"string",maxLength:512}},additionalProperties:!1},org:{oneOf:[{bsonType:"string",pattern:v._id.source},{bsonType:"null"}]},job:{bsonType:"string",maxLength:512},avatar:{oneOf:[{bsonType:"string",maxLength:10},{bsonType:"null"}]},createdAt:{bsonType:"number"}},additionalProperties:!1},ce=new Map,de=new Map,Jt=process.env.INSITE_STATIC_URL??"http://localhost:8080",J=class{constructor(e,t){this.users=e,this._id=t._id,e.set(this._id,this),this.update(t),e.isInited&&e.emit("user-create",this)}_id;email;name={first:"",middle:"",last:""};initials="";displayLabel="";org;job="";avatar=null;avatarUrl=null;users;isUser=!0;isRoot;roles=new Set;ownRoles=[];ownRoleIds=[];slaveRoles=new Set;slaveRoleIds=[];abilities={};slaveOrgs=new Set;slaveUsers=new Set;slaves=new Set;slaveIds=[];permissiveIds=[];sessions=new Set;isOnline=!1;update({_id:e,name:t,email:s,roles:i,org:r,avatar:n,...o}){Object.assign(this,o);let a;s&&this.email!==s&&(this.users.byEmail.delete(this.email),this.email=s,this.users.byEmail.set(s,this),a=!0);let l,d;t&&(this.name.first!==t.first||this.name.middle!==t.middle||this.name.last!==t.last)&&(d=this.name.last!==t.last,this.name={first:t.first??"",middle:t.middle??"",last:t.last??""},this.initials=((t.first?.[0]??"")+(t.last?.[0]??"")||this.email[0]).toUpperCase(),l=!0),(a||l)&&(this.displayLabel=`${this.name.first} ${this.name.last}`.trim()||this.name.middle||this.email);let p;if(i){this.ownRoleIds=i;let c=this.ownRoleIds.join(",");c!==ce.get(this._id)&&(ce.set(this._id,c),this.updateRoles(),p=!0)}let u;r!==void 0&&this.org?._id!==r&&(this.org?.users.delete(this),this.org=r&&this.users.orgs.get(r)||this.users.orgs.null,this.org.users.add(this),u=!0),n!==void 0&&this.avatar!==n&&(this.avatar=n,this.avatarUrl=n&&`${Jt}/avatars/${this._id}-${n}.webp`),p||u?(this.updatePermissions(),d&&(this.users.isSortRequired=!0),this.users.isInited&&this.users.updateDebounced()):d&&this.users.sortDebounced()}updateRoles(){if(this.users.isInited){this.ownRoles=[],this.roles.clear(),this.slaveRoles.clear(),Ve(this.abilities);for(let e of this.ownRoleIds){let t=this.users.roles.get(e);if(t){this.ownRoles.push(t),this.roles.add(t);for(let s of t.involves)this.roles.add(s),this.slaveRoles.add(s);this.slaveRoleIds=k(this.slaveRoles),this.users.abilitiesMap.merge(this.abilities,t.abilities)}}this.roles.has(this.users.roles.root)&&(this.isRoot=!0),this.trimSessions()}}updatePermissions(){if(this.users.isInited){this.slaveOrgs.clear(),this.slaveUsers.clear(),this.slaves.clear();let e=new Set;for(let i of this.users.orgs.sorted)if((i.ownerUsers.has(this)||this.isRoot)&&!this.slaveOrgs.has(i)){this.slaveOrgs.add(i),this.slaves.add(i),e.add(i._id);for(let r of i.slaveOrgs)this.slaveOrgs.add(r),this.slaves.add(r),e.add(r._id)}for(let i of new Set([this.org,...this.slaveOrgs,this.users.orgs.null]))for(let r of i.users)r!==this&&(Je(this.slaveRoles,r.ownRoles)||!r.ownRoles.length)&&(this.slaveUsers.add(r),this.slaves.add(r),e.add(r._id));this.slaveIds=[...e];let t=[];if(this.org._id){t.push(this.org._id);for(let i of this.org.slaveOrgs)this.slaveOrgs.has(i)||t.push(i._id)}this.permissiveIds=[...t,this._id,...e];let s=[this.permissiveIds.join(","),this.ownRoleIds.join(","),JSON.stringify(this.abilities),this.slaveRoleIds.join(",")].join(`
5
- `);s!==de.get(this._id)&&(de.set(this._id,s),this.users.emit("user-permissions-change",this))}}trimSessions(){let e=this.abilities.login?.sessionsLimit??0;return this.sessions.size>e?this.users.sessions.collection.deleteMany({_id:{$in:k([...this.sessions].sort((t,s)=>t.expiresAt.valueOf()-s.expiresAt.valueOf()).slice(0,this.sessions.size-e))}}):null}updateIsOnline=x(()=>{let e=!1;for(let t of this.sessions)if(t.isOnline){e=!0;break}this.isOnline!==e&&(this.isOnline=e,this.users.emit("user-is-online",this))},500);delete(){this.org.users.delete(this),this.users.delete(this._id),this.users.byEmail.delete(this.email),Ye(this.users.sorted,this),ce.delete(this._id),de.delete(this._id),this.users.replace(this._id),this.users.updateDebounced()}},Zt=[[{email:1},{unique:!0}],[{org:1}]],it=class rt extends Map{constructor(t,s){super();let i=new He;this._events=i._events,this._eventsCount=i._eventsCount,this.emit=i.emit,this.on=i.on,this.once=i.once,this.addListener=i.addListener,this.off=i.off,this.removeListener=i.removeListener,this.collections=t,this.abilitiesMap=new Pt(s.abilities),this.initOptions=s,this.#e=this.init()}_events;_eventsCount;emit;on;once;addListener;off;removeListener;initOptions;collections;abilitiesMap;collection;roles;sessions;orgs;avatars;isInited=!1;byEmail=new Map;bySessionId=new Map;sorted=[];isSortRequired=!1;load(t){new J(this,t)}sort(t){return this.isSortRequired=!1,this.sorted=[...this.values()].sort((s,i)=>s.name.last>i.name.last?1:s.name.last<i.name.last?-1:0),this}sortDebounced=x(()=>this.sort(),250);update(t){if(t)for(let s of this.values())s.updateRoles();for(let s of this.values())s.updatePermissions();this.isSortRequired&&this.sort()}updateDebounced=x(()=>this.update(),250);preinit=async()=>{let{indexes:t,schema:s,initialRoot:i}=this.initOptions;s&&(s.required&&T(s.required,U.required),s.properties&&g(s,Object.keys(U.properties)));let r={...U,...s,required:[...U.required,...s?.required??[]],properties:{...U.properties,...s?.properties}};this.collection=await this.collections.ensure("users",{jsonSchema:r}),this.collection.ensureIndexes([...Zt,...t??[]]),await this.collection.countDocuments({roles:"root"})||await this.new({email:process.env.INSITE_ROOT_EMAIL??"insite@root.email",password:process.env.INSITE_ROOT_PASSWORD??"inSiteRootPassword",roles:["root"],name:{first:"Root"},org:null,job:"Root",...i&&g(i,["roles","org"])});for(let n of await this.collection.find().toArray())this.load(n);delete this.preinit};#e;init=async()=>{this.isInited=!0;let{roles:t,orgs:s,sessions:i}=this.initOptions;return this.roles=new Nt(this,t),this.orgs=new zt(this,s),this.sessions=new Ft(this,i),this.avatars=new Vt(this),await this.roles.init(),await this.orgs.preinit(),await this.preinit(),await this.orgs.init(),await this.avatars.init(),this.update(!0),this.collection.changeListeners.add(r=>{switch(r.operationType){case"insert":new J(this,r.fullDocument);break;case"replace":this.get(r.documentKey._id)?.update(r.fullDocument);break;case"update":this.get(r.documentKey._id)?.update(r.updateDescription.updatedFields);break;case"delete":this.get(r.documentKey._id)?.delete()}}),await this.sessions.init(),delete this.initOptions,delete this.init,this};whenReady(){return this.#e}async new({email:t,password:s,roles:i,name:r,org:n,job:o,...a}){if(this.byEmail.has(t))throw new Error("User exists");return await this.collection.insertOne({_id:Bt(),email:t,password:await z.hash(s),roles:this.isInited?this.roles.cleanUpIds(i):i,name:{first:r.first??"",middle:r.middle??"",last:r.last??""},org:n??null,job:o??"",...g(a,["_id"]),createdAt:Date.now()}),!0}async changePassword(t,s){if(!this.has(t))throw new Error("usernotfound");if(!s)throw new Error("emptypasswordisnotallowed");await Promise.all([this.collection.updateOne({_id:t},{$set:{password:await z.hash(s)}}),this.sessions.collection.deleteMany({user:t})])}async login(t,s,i){let r=this.byEmail.get(t);if(!r)throw new Error("usernotfound");if(!await z.verify(r.password,s))throw new Error("incorrectpassword");if(!r.abilities.login)throw new Error("userisnotabletologin");return this.sessions.new(r,i)}logout(t){return t.delete(),this.sessions.collection.deleteOne({_id:t._id})}#t(t,s){return t instanceof J&&s instanceof J?t.name.last&&s.name.last?t.name.last>s.name.last?1:t.name.last<s.name.last?-1:0:!t.name.last&&!s.name.last?t.displayLabel>s.displayLabel?1:t.displayLabel<s.displayLabel?-1:0:t.name.last?-1:1:t instanceof M&&s instanceof M?t.title>s.title?1:t.title<s.title?-1:0:t instanceof M?-1:1}sortIds(t){return k(t.map(s=>this.get(s)||this.orgs.get(s)).filter(Boolean).sort(this.#t))}replaceMap=new Map;replaceHandlers=new Set;async replace(t){let s=this.replaceMap.get(t)??null;s&&this.replaceMap.delete(t);for(let i of this.replaceHandlers)await i(t,s)}static init(t,s){return new rt(t,s).whenReady()}};import{UsersServer as ns}from"insite-users-server-ws";var nt=class e{constructor(t){this.#e=this.init(t)}mongoClient;db;collections;wss;incomingTransport;subscriptionHandler;usersServer;users;cookie;http;init=async t=>{let{db:s,wss:i,users:r,cookie:n,http:o}=t;if(s&&({client:this.mongoClient,db:this.db,collections:this.collections}=await ts(s)),i&&(this.wss=new Qt(i),process.env.NODE_ENV==="development"&&this.wss.on("client-connect",a=>console.info(`\u{1F50C} WebSocket connected with ${a.session?.user.email}`)),this.wss.on("error",a=>console.error("\u{1F50C}\u2757\uFE0F WebSocket Server:",a)),this.wss.on("close",()=>console.error("\u{1F50C}\u2757\uFE0F WebSocket Server closed")),this.incomingTransport=new es(this.wss),this.subscriptionHandler=new Yt(this.wss)),r&&this.collections){let{server:a,...l}=r;a&&this.wss?(this.usersServer=await ns.init({...a,users:l,wss:this.wss,collections:this.collections,incomingTransport:this.incomingTransport}),this.users=this.usersServer.users):this.users=await it.init(this.collections,l)}if(o){let{static:a=void 0,template:l=void 0,middlewares:d=void 0,...p}=typeof o=="object"?o:{};this.http=new ss(p,[a!==null&&new is(a??{}),n!==null&&new Xt(n?.middleware??{}),l!==null&&new rs(l??{}),...d??[]].filter(Boolean))}if(n!==null&&this.usersServer&&this.http){let{middleware:a,...l}=n??{};this.cookie=new Gt({...l,usersServer:this.usersServer})}return delete this.init,this};#e;whenReady(){return this.#e}static init(t){return new e(t).whenReady()}};export{nt as InSite};
1
+ var zr=Object.create;var Vt=Object.defineProperty;var Hr=Object.getOwnPropertyDescriptor;var Kr=Object.getOwnPropertyNames;var Yr=Object.getPrototypeOf,Xr=Object.prototype.hasOwnProperty;var g=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,s)=>(typeof require<"u"?require:e)[s]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var b=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Zr=(t,e,s,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Kr(e))!Xr.call(t,i)&&i!==s&&Vt(t,i,{get:()=>e[i],enumerable:!(r=Hr(e,i))||r.enumerable});return t};var G=(t,e,s)=>(s=t!=null?zr(Yr(t)):{},Zr(e||!t||!t.__esModule?Vt(s,"default",{value:t,enumerable:!0}):s,t));var Yt=b((_o,Kt)=>{"use strict";var{Duplex:Jr}=g("stream");function zt(t){t.emit("close")}function Qr(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ht(t){this.removeListener("error",Ht),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function ei(t,e){let s=!0,r=new Jr({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(n,o){let a=!o&&r._readableState.objectMode?n.toString():n;r.push(a)||t.pause()}),t.once("error",function(n){r.destroyed||(s=!1,r.destroy(n))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,n){if(t.readyState===t.CLOSED){n(i),process.nextTick(zt,r);return}let o=!1;t.once("error",function(l){o=!0,n(l)}),t.once("close",function(){o||n(i),process.nextTick(zt,r)}),s&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,n,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,n,o)});return}t.send(i,o)},r.on("end",Qr),r.on("error",Ht),r}Kt.exports=ei});var M=b((go,Jt)=>{"use strict";var Xt=["nodebuffer","arraybuffer","fragments"],Zt=typeof Blob<"u";Zt&&Xt.push("blob");Jt.exports={BINARY_TYPES:Xt,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Zt,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ce=b((yo,Le)=>{"use strict";var{EMPTY_BUFFER:ti}=M(),Je=Buffer[Symbol.species];function si(t,e){if(t.length===0)return ti;if(t.length===1)return t[0];let s=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let n=t[i];s.set(n,r),r+=n.length}return r<e?new Je(s.buffer,s.byteOffset,r):s}function Qt(t,e,s,r,i){for(let n=0;n<i;n++)s[r+n]=t[n]^e[n&3]}function es(t,e){for(let s=0;s<t.length;s++)t[s]^=e[s&3]}function ri(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Qe(t){if(Qe.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Je(t):ArrayBuffer.isView(t)?e=new Je(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Qe.readOnly=!1),e}Le.exports={concat:si,mask:Qt,toArrayBuffer:ri,toBuffer:Qe,unmask:es};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=g("bufferutil");Le.exports.mask=function(e,s,r,i,n){n<48?Qt(e,s,r,i,n):t.mask(e,s,r,i,n)},Le.exports.unmask=function(e,s){e.length<32?es(e,s):t.unmask(e,s)}}catch{}});var rs=b((xo,ss)=>{"use strict";var ts=Symbol("kDone"),et=Symbol("kRun"),tt=class{constructor(e){this[ts]=()=>{this.pending--,this[et]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[et]()}[et](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[ts])}}};ss.exports=tt});var he=b((vo,as)=>{"use strict";var fe=g("zlib"),is=ce(),ii=rs(),{kStatusCode:ns}=M(),ni=Buffer[Symbol.species],oi=Buffer.from([0,0,255,255]),Re=Symbol("permessage-deflate"),B=Symbol("total-length"),ue=Symbol("callback"),U=Symbol("buffers"),Pe=Symbol("error"),Ae,st=class{constructor(e,s,r){if(this._maxPayload=r|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!s,this._deflate=null,this._inflate=null,this.params=null,!Ae){let i=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ae=new ii(i)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ue];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let s=this._options,r=e.find(i=>!(s.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(s.serverMaxWindowBits===!1||typeof s.serverMaxWindowBits=="number"&&s.serverMaxWindowBits>i.server_max_window_bits)||typeof s.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return s.serverNoContextTakeover&&(r.server_no_context_takeover=!0),s.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof s.serverMaxWindowBits=="number"&&(r.server_max_window_bits=s.serverMaxWindowBits),typeof s.clientMaxWindowBits=="number"?r.client_max_window_bits=s.clientMaxWindowBits:(r.client_max_window_bits===!0||s.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let s=e[0];if(this._options.clientNoContextTakeover===!1&&s.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!s.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(s.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&s.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return s}normalizeParams(e){return e.forEach(s=>{Object.keys(s).forEach(r=>{let i=s[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=n}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=n}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);s[r]=i})}),e}decompress(e,s,r){Ae.add(i=>{this._decompress(e,s,(n,o)=>{i(),r(n,o)})})}compress(e,s,r){Ae.add(i=>{this._compress(e,s,(n,o)=>{i(),r(n,o)})})}_decompress(e,s,r){let i=this._isServer?"client":"server";if(!this._inflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?fe.Z_DEFAULT_WINDOWBITS:this.params[n];this._inflate=fe.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Re]=this,this._inflate[B]=0,this._inflate[U]=[],this._inflate.on("error",li),this._inflate.on("data",os)}this._inflate[ue]=r,this._inflate.write(e),s&&this._inflate.write(oi),this._inflate.flush(()=>{let n=this._inflate[Pe];if(n){this._inflate.close(),this._inflate=null,r(n);return}let o=is.concat(this._inflate[U],this._inflate[B]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[B]=0,this._inflate[U]=[],s&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,s,r){let i=this._isServer?"server":"client";if(!this._deflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?fe.Z_DEFAULT_WINDOWBITS:this.params[n];this._deflate=fe.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[B]=0,this._deflate[U]=[],this._deflate.on("data",ai)}this._deflate[ue]=r,this._deflate.write(e),this._deflate.flush(fe.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let n=is.concat(this._deflate[U],this._deflate[B]);s&&(n=new ni(n.buffer,n.byteOffset,n.length-4)),this._deflate[ue]=null,this._deflate[B]=0,this._deflate[U]=[],s&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,n)})}};as.exports=st;function ai(t){this[U].push(t),this[B]+=t.length}function os(t){if(this[B]+=t.length,this[Re]._maxPayload<1||this[B]<=this[Re]._maxPayload){this[U].push(t);return}this[Pe]=new RangeError("Max payload size exceeded"),this[Pe].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Pe][ns]=1009,this.removeListener("data",os),this.reset()}function li(t){this[Re]._inflate=null,t[ns]=1007,this[ue](t)}});var J=b((bo,Ne)=>{"use strict";var{isUtf8:ls}=g("buffer"),{hasBlob:ci}=M(),fi=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,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,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,0,1,0,1,0];function ui(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function rt(t){let e=t.length,s=0;for(;s<e;)if(!(t[s]&128))s++;else if((t[s]&224)===192){if(s+1===e||(t[s+1]&192)!==128||(t[s]&254)===192)return!1;s+=2}else if((t[s]&240)===224){if(s+2>=e||(t[s+1]&192)!==128||(t[s+2]&192)!==128||t[s]===224&&(t[s+1]&224)===128||t[s]===237&&(t[s+1]&224)===160)return!1;s+=3}else if((t[s]&248)===240){if(s+3>=e||(t[s+1]&192)!==128||(t[s+2]&192)!==128||(t[s+3]&192)!==128||t[s]===240&&(t[s+1]&240)===128||t[s]===244&&t[s+1]>143||t[s]>244)return!1;s+=4}else return!1;return!0}function hi(t){return ci&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ne.exports={isBlob:hi,isValidStatusCode:ui,isValidUTF8:rt,tokenChars:fi};if(ls)Ne.exports.isValidUTF8=function(t){return t.length<24?rt(t):ls(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=g("utf-8-validate");Ne.exports.isValidUTF8=function(e){return e.length<32?rt(e):t(e)}}catch{}});var lt=b((wo,ms)=>{"use strict";var{Writable:di}=g("stream"),cs=he(),{BINARY_TYPES:pi,EMPTY_BUFFER:fs,kStatusCode:mi,kWebSocket:_i}=M(),{concat:it,toArrayBuffer:gi,unmask:yi}=ce(),{isValidStatusCode:xi,isValidUTF8:us}=J(),Me=Buffer[Symbol.species],I=0,hs=1,ds=2,ps=3,nt=4,ot=5,Be=6,at=class extends di{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||pi[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[_i]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=I}_write(e,s,r){if(this._opcode===8&&this._state==I)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Me(r.buffer,r.byteOffset+e,r.length-e),new Me(r.buffer,r.byteOffset,e)}let s=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=s.length-e;e>=r.length?s.set(this._buffers.shift(),i):(s.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new Me(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return s}startLoop(e){this._loop=!0;do switch(this._state){case I:this.getInfo(e);break;case hs:this.getPayloadLength16(e);break;case ds:this.getPayloadLength64(e);break;case ps:this.getMask();break;case nt:this.getData(e);break;case ot:case Be:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let s=this.consume(2);if(s[0]&48){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(s[0]&64)===64;if(r&&!this._extensions[cs.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(s[0]&128)===128,this._opcode=s[0]&15,this._payloadLength=s[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(s[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=hs:this._payloadLength===127?this._state=ds:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let s=this.consume(8),r=s.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+s.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(s);return}this._masked?this._state=ps:this._state=nt}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=nt}getData(e){let s=fs;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}s=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&yi(s,this._mask)}if(this._opcode>7){this.controlMessage(s,e);return}if(this._compressed){this._state=ot,this.decompress(s,e);return}s.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(s)),this.dataMessage(e)}decompress(e,s){this._extensions[cs.extensionName].decompress(e,this._fin,(i,n)=>{if(i)return s(i);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");s(o);return}this._fragments.push(n)}this.dataMessage(s),this._state===I&&this.startLoop(s)})}dataMessage(e){if(!this._fin){this._state=I;return}let s=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=it(r,s):this._binaryType==="arraybuffer"?i=gi(it(r,s)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=I):(this._state=Be,setImmediate(()=>{this.emit("message",i,!0),this._state=I,this.startLoop(e)}))}else{let i=it(r,s);if(!this._skipUTF8Validation&&!us(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(n);return}this._state===ot||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=I):(this._state=Be,setImmediate(()=>{this.emit("message",i,!1),this._state=I,this.startLoop(e)}))}}controlMessage(e,s){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,fs),this.end();else{let r=e.readUInt16BE(0);if(!xi(r)){let n=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");s(n);return}let i=new Me(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!us(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");s(n);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=I;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=I):(this._state=Be,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=I,this.startLoop(s)}))}createError(e,s,r,i,n){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${s}`:s);return Error.captureStackTrace(o,this.createError),o.code=n,o[mi]=i,o}};ms.exports=at});var ut=b((Oo,ys)=>{"use strict";var{Duplex:So}=g("stream"),{randomFillSync:vi}=g("crypto"),_s=he(),{EMPTY_BUFFER:bi,kWebSocket:wi,NOOP:Si}=M(),{isBlob:Q,isValidStatusCode:Oi}=J(),{mask:gs,toBuffer:V}=ce(),k=Symbol("kByteLength"),Ei=Buffer.alloc(4),De=8*1024,z,ee=De,L=0,Ti=1,Ii=2,ct=class t{constructor(e,s,r){this._extensions=s||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=L,this.onerror=Si,this[wi]=void 0}static frame(e,s){let r,i=!1,n=2,o=!1;s.mask&&(r=s.maskBuffer||Ei,s.generateMask?s.generateMask(r):(ee===De&&(z===void 0&&(z=Buffer.alloc(De)),vi(z,0,De),ee=0),r[0]=z[ee++],r[1]=z[ee++],r[2]=z[ee++],r[3]=z[ee++]),o=(r[0]|r[1]|r[2]|r[3])===0,n=6);let a;typeof e=="string"?(!s.mask||o)&&s[k]!==void 0?a=s[k]:(e=Buffer.from(e),a=e.length):(a=e.length,i=s.mask&&s.readOnly&&!o);let l=a;a>=65536?(n+=8,l=127):a>125&&(n+=2,l=126);let c=Buffer.allocUnsafe(i?a+n:n);return c[0]=s.fin?s.opcode|128:s.opcode,s.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),s.mask?(c[1]|=128,c[n-4]=r[0],c[n-3]=r[1],c[n-2]=r[2],c[n-1]=r[3],o?[c,e]:i?(gs(e,r,c,n,a),[c]):(gs(e,r,e,0,a),[c,e])):[c,e]}close(e,s,r,i){let n;if(e===void 0)n=bi;else{if(typeof e!="number"||!Oi(e))throw new TypeError("First argument must be a valid error code number");if(s===void 0||!s.length)n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0);else{let a=Buffer.byteLength(s);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");n=Buffer.allocUnsafe(2+a),n.writeUInt16BE(e,0),typeof s=="string"?n.write(s,2):n.set(s,2)}}let o={[k]:n.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==L?this.enqueue([this.dispatch,n,!1,o,i]):this.sendFrame(t.frame(n,o),i)}ping(e,s,r){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):Q(e)?(i=e.size,n=!1):(e=V(e),i=e.length,n=V.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[k]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};Q(e)?this._state!==L?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==L?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,s,r){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):Q(e)?(i=e.size,n=!1):(e=V(e),i=e.length,n=V.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[k]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};Q(e)?this._state!==L?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==L?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,s,r){let i=this._extensions[_s.extensionName],n=s.binary?2:1,o=s.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):Q(e)?(a=e.size,l=!1):(e=V(e),a=e.length,l=V.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=i._threshold),this._compress=o):(o=!1,n=0),s.fin&&(this._firstFragment=!0);let c={[k]:a,fin:s.fin,generateMask:this._generateMask,mask:s.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:l,rsv1:o};Q(e)?this._state!==L?this.enqueue([this.getBlobData,e,this._compress,c,r]):this.getBlobData(e,this._compress,c,r):this._state!==L?this.enqueue([this.dispatch,e,this._compress,c,r]):this.dispatch(e,this._compress,c,r)}getBlobData(e,s,r,i){this._bufferedBytes+=r[k],this._state=Ii,e.arrayBuffer().then(n=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(ft,this,a,i);return}this._bufferedBytes-=r[k];let o=V(n);s?this.dispatch(o,s,r,i):(this._state=L,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(n=>{process.nextTick(ki,this,n,i)})}dispatch(e,s,r,i){if(!s){this.sendFrame(t.frame(e,r),i);return}let n=this._extensions[_s.extensionName];this._bufferedBytes+=r[k],this._state=Ti,n.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");ft(this,l,i);return}this._bufferedBytes-=r[k],this._state=L,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===L&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][k],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][k],this._queue.push(e)}sendFrame(e,s){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],s),this._socket.uncork()):this._socket.write(e[0],s)}};ys.exports=ct;function ft(t,e,s){typeof s=="function"&&s(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],n=i[i.length-1];typeof n=="function"&&n(e)}}function ki(t,e,s){ft(t,e,s),t.onerror(e)}});var Is=b((Eo,Ts)=>{"use strict";var{kForOnEventAttribute:de,kListener:ht}=M(),xs=Symbol("kCode"),vs=Symbol("kData"),bs=Symbol("kError"),ws=Symbol("kMessage"),Ss=Symbol("kReason"),te=Symbol("kTarget"),Os=Symbol("kType"),Es=Symbol("kWasClean"),D=class{constructor(e){this[te]=null,this[Os]=e}get target(){return this[te]}get type(){return this[Os]}};Object.defineProperty(D.prototype,"target",{enumerable:!0});Object.defineProperty(D.prototype,"type",{enumerable:!0});var H=class extends D{constructor(e,s={}){super(e),this[xs]=s.code===void 0?0:s.code,this[Ss]=s.reason===void 0?"":s.reason,this[Es]=s.wasClean===void 0?!1:s.wasClean}get code(){return this[xs]}get reason(){return this[Ss]}get wasClean(){return this[Es]}};Object.defineProperty(H.prototype,"code",{enumerable:!0});Object.defineProperty(H.prototype,"reason",{enumerable:!0});Object.defineProperty(H.prototype,"wasClean",{enumerable:!0});var se=class extends D{constructor(e,s={}){super(e),this[bs]=s.error===void 0?null:s.error,this[ws]=s.message===void 0?"":s.message}get error(){return this[bs]}get message(){return this[ws]}};Object.defineProperty(se.prototype,"error",{enumerable:!0});Object.defineProperty(se.prototype,"message",{enumerable:!0});var pe=class extends D{constructor(e,s={}){super(e),this[vs]=s.data===void 0?null:s.data}get data(){return this[vs]}};Object.defineProperty(pe.prototype,"data",{enumerable:!0});var Ci={addEventListener(t,e,s={}){for(let i of this.listeners(t))if(!s[de]&&i[ht]===e&&!i[de])return;let r;if(t==="message")r=function(n,o){let a=new pe("message",{data:o?n:n.toString()});a[te]=this,$e(e,this,a)};else if(t==="close")r=function(n,o){let a=new H("close",{code:n,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[te]=this,$e(e,this,a)};else if(t==="error")r=function(n){let o=new se("error",{error:n,message:n.message});o[te]=this,$e(e,this,o)};else if(t==="open")r=function(){let n=new D("open");n[te]=this,$e(e,this,n)};else return;r[de]=!!s[de],r[ht]=e,s.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let s of this.listeners(t))if(s[ht]===e&&!s[de]){this.removeListener(t,s);break}}};Ts.exports={CloseEvent:H,ErrorEvent:se,Event:D,EventTarget:Ci,MessageEvent:pe};function $e(t,e,s){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,s):t.call(e,s)}});var dt=b((To,ks)=>{"use strict";var{tokenChars:me}=J();function A(t,e,s){t[e]===void 0?t[e]=[s]:t[e].push(s)}function Li(t){let e=Object.create(null),s=Object.create(null),r=!1,i=!1,n=!1,o,a,l=-1,c=-1,u=-1,f=0;for(;f<t.length;f++)if(c=t.charCodeAt(f),o===void 0)if(u===-1&&me[c]===1)l===-1&&(l=f);else if(f!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=f);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1&&(u=f);let p=t.slice(l,u);c===44?(A(e,p,s),s=Object.create(null)):o=p,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(a===void 0)if(u===-1&&me[c]===1)l===-1&&(l=f);else if(c===32||c===9)u===-1&&l!==-1&&(u=f);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1&&(u=f),A(s,t.slice(l,u),!0),c===44&&(A(e,o,s),s=Object.create(null),o=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=t.slice(l,f),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(i){if(me[c]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);l===-1?l=f:r||(r=!0),i=!1}else if(n)if(me[c]===1)l===-1&&(l=f);else if(c===34&&l!==-1)n=!1,u=f;else if(c===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(c===34&&t.charCodeAt(f-1)===61)n=!0;else if(u===-1&&me[c]===1)l===-1&&(l=f);else if(l!==-1&&(c===32||c===9))u===-1&&(u=f);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1&&(u=f);let p=t.slice(l,u);r&&(p=p.replace(/\\/g,""),r=!1),A(s,a,p),c===44&&(A(e,o,s),s=Object.create(null),o=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(l===-1||n||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=f);let h=t.slice(l,u);return o===void 0?A(e,h,s):(a===void 0?A(s,h,!0):r?A(s,a,h.replace(/\\/g,"")):A(s,a,h),A(e,o,s)),e}function Ai(t){return Object.keys(t).map(e=>{let s=t[e];return Array.isArray(s)||(s=[s]),s.map(r=>[e].concat(Object.keys(r).map(i=>{let n=r[i];return Array.isArray(n)||(n=[n]),n.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ks.exports={format:Ai,parse:Li}});var yt=b((Co,Us)=>{"use strict";var Pi=g("events"),Ri=g("https"),Ni=g("http"),As=g("net"),Mi=g("tls"),{randomBytes:Bi,createHash:Di}=g("crypto"),{Duplex:Io,Readable:ko}=g("stream"),{URL:pt}=g("url"),q=he(),$i=lt(),ji=ut(),{isBlob:Ui}=J(),{BINARY_TYPES:Cs,EMPTY_BUFFER:je,GUID:qi,kForOnEventAttribute:mt,kListener:Wi,kStatusCode:Fi,kWebSocket:w,NOOP:Ps}=M(),{EventTarget:{addEventListener:Gi,removeEventListener:Vi}}=Is(),{format:zi,parse:Hi}=dt(),{toBuffer:Ki}=ce(),Yi=30*1e3,Rs=Symbol("kAborted"),_t=[8,13],$=["CONNECTING","OPEN","CLOSING","CLOSED"],Xi=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,x=class t extends Pi{constructor(e,s,r){super(),this._binaryType=Cs[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=je,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,s===void 0?s=[]:Array.isArray(s)||(typeof s=="object"&&s!==null?(r=s,s=[]):s=[s]),Ns(this,e,s,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Cs.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,s,r){let i=new $i({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),n=new ji(e,this._extensions,r.generateMask);this._receiver=i,this._sender=n,this._socket=e,i[w]=this,n[w]=this,e[w]=this,i.on("conclude",Qi),i.on("drain",en),i.on("error",tn),i.on("message",sn),i.on("ping",rn),i.on("pong",nn),n.onerror=on,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),s.length>0&&e.unshift(s),e.on("close",Ds),e.on("data",qe),e.on("end",$s),e.on("error",js),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[q.extensionName]&&this._extensions[q.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,s){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){E(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,s,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Bs(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=s=void 0):typeof s=="function"&&(r=s,s=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){gt(this,e,r);return}s===void 0&&(s=!this._isServer),this._sender.ping(e||je,s,r)}pong(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=s=void 0):typeof s=="function"&&(r=s,s=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){gt(this,e,r);return}s===void 0&&(s=!this._isServer),this._sender.pong(e||je,s,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof s=="function"&&(r=s,s={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){gt(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...s};this._extensions[q.extensionName]||(i.compress=!1),this._sender.send(e||je,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){E(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(x,"CONNECTING",{enumerable:!0,value:$.indexOf("CONNECTING")});Object.defineProperty(x.prototype,"CONNECTING",{enumerable:!0,value:$.indexOf("CONNECTING")});Object.defineProperty(x,"OPEN",{enumerable:!0,value:$.indexOf("OPEN")});Object.defineProperty(x.prototype,"OPEN",{enumerable:!0,value:$.indexOf("OPEN")});Object.defineProperty(x,"CLOSING",{enumerable:!0,value:$.indexOf("CLOSING")});Object.defineProperty(x.prototype,"CLOSING",{enumerable:!0,value:$.indexOf("CLOSING")});Object.defineProperty(x,"CLOSED",{enumerable:!0,value:$.indexOf("CLOSED")});Object.defineProperty(x.prototype,"CLOSED",{enumerable:!0,value:$.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(x.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(x.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[mt])return e[Wi];return null},set(e){for(let s of this.listeners(t))if(s[mt]){this.removeListener(t,s);break}typeof e=="function"&&this.addEventListener(t,e,{[mt]:!0})}})});x.prototype.addEventListener=Gi;x.prototype.removeEventListener=Vi;Us.exports=x;function Ns(t,e,s,r){let i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:_t[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,!_t.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${_t.join(", ")})`);let n;if(e instanceof pt)n=e;else try{n=new pt(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),t._url=n.href;let o=n.protocol==="wss:",a=n.protocol==="ws+unix:",l;if(n.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`:a&&!n.pathname?l="The URL's pathname is empty":n.hash&&(l="The URL contains a fragment identifier"),l){let d=new SyntaxError(l);if(t._redirects===0)throw d;Ue(t,d);return}let c=o?443:80,u=Bi(16).toString("base64"),f=o?Ri.request:Ni.request,h=new Set,p;if(i.createConnection=i.createConnection||(o?Ji:Zi),i.defaultPort=i.defaultPort||c,i.port=n.port||c,i.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=n.pathname+n.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(p=new q(i.perMessageDeflate!==!0?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=zi({[q.extensionName]:p.offer()})),s.length){for(let d of s){if(typeof d!="string"||!Xi.test(d)||h.has(d))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(d)}i.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(n.username||n.password)&&(i.auth=`${n.username}:${n.password}`),a){let d=i.path.split(":");i.socketPath=d[0],i.path=d[1]}let _;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?i.socketPath:n.host;let d=r&&r.headers;if(r={...r,headers:{}},d)for(let[m,y]of Object.entries(d))r.headers[m.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let d=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:n.host===t._originalHostOrSocketPath;(!d||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,d||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),_=t._req=f(i),t._redirects&&t.emit("redirect",t.url,_)}else _=t._req=f(i);i.timeout&&_.on("timeout",()=>{E(t,_,"Opening handshake has timed out")}),_.on("error",d=>{_===null||_[Rs]||(_=t._req=null,Ue(t,d))}),_.on("response",d=>{let m=d.headers.location,y=d.statusCode;if(m&&i.followRedirects&&y>=300&&y<400){if(++t._redirects>i.maxRedirects){E(t,_,"Maximum redirects exceeded");return}_.abort();let v;try{v=new pt(m,e)}catch{let Z=new SyntaxError(`Invalid URL: ${m}`);Ue(t,Z);return}Ns(t,v,s,r)}else t.emit("unexpected-response",_,d)||E(t,_,`Unexpected server response: ${d.statusCode}`)}),_.on("upgrade",(d,m,y)=>{if(t.emit("upgrade",d),t.readyState!==x.CONNECTING)return;_=t._req=null;let v=d.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){E(t,m,"Invalid Upgrade header");return}let X=Di("sha1").update(u+qi).digest("base64");if(d.headers["sec-websocket-accept"]!==X){E(t,m,"Invalid Sec-WebSocket-Accept header");return}let Z=d.headers["sec-websocket-protocol"],le;if(Z!==void 0?h.size?h.has(Z)||(le="Server sent an invalid subprotocol"):le="Server sent a subprotocol but none was requested":h.size&&(le="Server sent no subprotocol"),le){E(t,m,le);return}Z&&(t._protocol=Z);let Ft=d.headers["sec-websocket-extensions"];if(Ft!==void 0){if(!p){E(t,m,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Xe;try{Xe=Hi(Ft)}catch{E(t,m,"Invalid Sec-WebSocket-Extensions header");return}let Gt=Object.keys(Xe);if(Gt.length!==1||Gt[0]!==q.extensionName){E(t,m,"Server indicated an extension that was not requested");return}try{p.accept(Xe[q.extensionName])}catch{E(t,m,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[q.extensionName]=p}t.setSocket(m,y,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(_,t):_.end()}function Ue(t,e){t._readyState=x.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Zi(t){return t.path=t.socketPath,As.connect(t)}function Ji(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=As.isIP(t.host)?"":t.host),Mi.connect(t)}function E(t,e,s){t._readyState=x.CLOSING;let r=new Error(s);Error.captureStackTrace(r,E),e.setHeader?(e[Rs]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ue,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function gt(t,e,s){if(e){let r=Ui(e)?e.size:Ki(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(s){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${$[t.readyState]})`);process.nextTick(s,r)}}function Qi(t,e){let s=this[w];s._closeFrameReceived=!0,s._closeMessage=e,s._closeCode=t,s._socket[w]!==void 0&&(s._socket.removeListener("data",qe),process.nextTick(Ms,s._socket),t===1005?s.close():s.close(t,e))}function en(){let t=this[w];t.isPaused||t._socket.resume()}function tn(t){let e=this[w];e._socket[w]!==void 0&&(e._socket.removeListener("data",qe),process.nextTick(Ms,e._socket),e.close(t[Fi])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Ls(){this[w].emitClose()}function sn(t,e){this[w].emit("message",t,e)}function rn(t){let e=this[w];e._autoPong&&e.pong(t,!this._isServer,Ps),e.emit("ping",t)}function nn(t){this[w].emit("pong",t)}function Ms(t){t.resume()}function on(t){let e=this[w];e.readyState!==x.CLOSED&&(e.readyState===x.OPEN&&(e._readyState=x.CLOSING,Bs(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Bs(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),Yi)}function Ds(){let t=this[w];this.removeListener("close",Ds),this.removeListener("data",qe),this.removeListener("end",$s),t._readyState=x.CLOSING;let e;!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&(e=t._socket.read())!==null&&t._receiver.write(e),t._receiver.end(),this[w]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Ls),t._receiver.on("finish",Ls))}function qe(t){this[w]._receiver.write(t)||this.pause()}function $s(){let t=this[w];t._readyState=x.CLOSING,t._receiver.end(),this.end()}function js(){let t=this[w];this.removeListener("error",js),this.on("error",Ps),t&&(t._readyState=x.CLOSING,this.destroy())}});var Ws=b((Lo,qs)=>{"use strict";var{tokenChars:an}=J();function ln(t){let e=new Set,s=-1,r=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(r===-1&&an[o]===1)s===-1&&(s=i);else if(i!==0&&(o===32||o===9))r===-1&&s!==-1&&(r=i);else if(o===44){if(s===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let a=t.slice(s,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),s=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(s===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let n=t.slice(s,i);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return e.add(n),e}qs.exports={parse:ln}});var Ys=b((Po,Ks)=>{"use strict";var cn=g("events"),We=g("http"),{Duplex:Ao}=g("stream"),{createHash:fn}=g("crypto"),Fs=dt(),K=he(),un=Ws(),hn=yt(),{GUID:dn,kWebSocket:pn}=M(),mn=/^[+/0-9A-Za-z]{22}==$/,Gs=0,Vs=1,Hs=2,xt=class extends cn{constructor(e,s){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:hn,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=We.createServer((r,i)=>{let n=We.STATUS_CODES[426];i.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),i.end(n)}),this._server.listen(e.port,e.host,e.backlog,s)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=_n(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,n,o)=>{this.handleUpgrade(i,n,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Gs}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Hs){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(_e,this);return}if(e&&this.once("close",e),this._state!==Vs)if(this._state=Vs,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(_e,this):process.nextTick(_e,this);else{let s=this._server;this._removeListeners(),this._removeListeners=this._server=null,s.close(()=>{_e(this)})}}shouldHandle(e){if(this.options.path){let s=e.url.indexOf("?");if((s!==-1?e.url.slice(0,s):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,s,r,i){s.on("error",zs);let n=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Y(this,e,s,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Y(this,e,s,400,"Invalid Upgrade header");return}if(n===void 0||!mn.test(n)){Y(this,e,s,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==8&&a!==13){Y(this,e,s,400,"Missing or invalid Sec-WebSocket-Version header");return}if(!this.shouldHandle(e)){ge(s,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=un.parse(l)}catch{Y(this,e,s,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&u!==void 0){let h=new K(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let p=Fs.parse(u);p[K.extensionName]&&(h.accept(p[K.extensionName]),f[K.extensionName]=h)}catch{Y(this,e,s,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(p,_,d,m)=>{if(!p)return ge(s,_||401,d,m);this.completeUpgrade(f,n,c,e,s,r,i)});return}if(!this.options.verifyClient(h))return ge(s,401)}this.completeUpgrade(f,n,c,e,s,r,i)}completeUpgrade(e,s,r,i,n,o,a){if(!n.readable||!n.writable)return n.destroy();if(n[pn])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Gs)return ge(n,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${fn("sha1").update(s+dn).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(r.size){let f=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;f&&(c.push(`Sec-WebSocket-Protocol: ${f}`),u._protocol=f)}if(e[K.extensionName]){let f=e[K.extensionName].params,h=Fs.format({[K.extensionName]:[f]});c.push(`Sec-WebSocket-Extensions: ${h}`),u._extensions=e}this.emit("headers",c,i),n.write(c.concat(`\r
2
+ `).join(`\r
3
+ `)),n.removeListener("error",zs),u.setSocket(n,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(_e,this)})),a(u,i)}};Ks.exports=xt;function _n(t,e){for(let s of Object.keys(e))t.on(s,e[s]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function _e(t){t._state=Hs,t.emit("close")}function zs(){this.destroy()}function ge(t,e,s,r){s=s||We.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(s),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${We.STATUS_CODES[e]}\r
4
+ `+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
5
+ `)+`\r
6
+ \r
7
+ `+s)}function Y(t,e,s,r,i){if(t.listenerCount("wsClientError")){let n=new Error(i);Error.captureStackTrace(n,Y),t.emit("wsClientError",n,s,e)}else ge(s,r,i)}});var rr=b((Dl,sr)=>{var Fe=/^[a-z0-9-]{1,32}$/,Ge=/^[a-z0-9-]{1,32}$/,Ve=/^[a-zA-Z0-9/+.-]+$/,er=/^([a-zA-Z0-9/+.-]+|)$/,wn=/^((-)?[1-9]\d*|0)$/,Et=/^v=(\d+)$/;function Sn(t){return be(t).map(e=>[e,t[e]].join("=")).join(",")}function On(t){let e={};return t.split(",").forEach(s=>{let r=s.split("=");if(r.length<2)throw new TypeError("params must be in the format name=value");e[r.shift()]=r.join("=")}),e}function be(t){return Object.keys(t)}function tr(t){return typeof Object.values=="function"?Object.values(t):be(t).map(e=>t[e])}function En(t){let e=[""];if(typeof t!="object"||t===null)throw new TypeError("opts must be an object");if(typeof t.id!="string")throw new TypeError("id must be a string");if(!Fe.test(t.id))throw new TypeError(`id must satisfy ${Fe}`);if(e.push(t.id),typeof t.version<"u"){if(typeof t.version!="number"||t.version<0||!Number.isInteger(t.version))throw new TypeError("version must be a positive integer number");e.push(`v=${t.version}`)}if(typeof t.params<"u"){if(typeof t.params!="object"||t.params===null)throw new TypeError("params must be an object");let r=be(t.params);if(!r.every(o=>Ge.test(o)))throw new TypeError(`params names must satisfy ${Ge}`);r.forEach(o=>{typeof t.params[o]=="number"?t.params[o]=t.params[o].toString():Buffer.isBuffer(t.params[o])&&(t.params[o]=t.params[o].toString("base64").split("=")[0])});let i=tr(t.params);if(!i.every(o=>typeof o=="string"))throw new TypeError("params values must be strings");if(!i.every(o=>Ve.test(o)))throw new TypeError(`params values must satisfy ${Ve}`);let n=Sn(t.params);e.push(n)}if(typeof t.salt<"u"){if(!Buffer.isBuffer(t.salt))throw new TypeError("salt must be a Buffer");if(e.push(t.salt.toString("base64").split("=")[0]),typeof t.hash<"u"){if(!Buffer.isBuffer(t.hash))throw new TypeError("hash must be a Buffer");e.push(t.hash.toString("base64").split("=")[0])}}return e.join("$")}function Tn(t){if(typeof t!="string"||t==="")throw new TypeError("pchstr must be a non-empty string");if(t[0]!=="$")throw new TypeError("pchstr must contain a $ as first char");let e=t.split("$");e.shift();let s=5;if(Et.test(e[1])||s--,e.length>s)throw new TypeError(`pchstr contains too many fileds: ${e.length}/${s}`);let r=e.shift();if(!Fe.test(r))throw new TypeError(`id must satisfy ${Fe}`);let i;Et.test(e[0])&&(i=parseInt(e.shift().match(Et)[1],10));let n,o;er.test(e[e.length-1])&&(e.length>1&&er.test(e[e.length-2])&&(n=Buffer.from(e.pop(),"base64")),o=Buffer.from(e.pop(),"base64"));let a;if(e.length>0){let c=e.pop();if(a=On(c),!be(a).every(h=>Ge.test(h)))throw new TypeError(`params names must satisfy ${Ge}`);if(!tr(a).every(h=>Ve.test(h)))throw new TypeError(`params values must satisfy ${Ve}`);be(a).forEach(h=>{a[h]=wn.test(a[h])?parseInt(a[h],10):a[h]})}if(e.length>0)throw new TypeError(`pchstr contains unrecognized fileds: ${e}`);let l={id:r};return i&&(l.version=i),a&&(l.params=a),o&&(l.salt=o),n&&(l.hash=n),l}sr.exports={serialize:En,deserialize:Tn}});var xr=b(($l,yr)=>{var ar=g("fs"),j=g("path"),lr=g("os"),cr=typeof __webpack_require__=="function"?__non_webpack_require__:g,In=process.config&&process.config.variables||{},kn=!!process.env.PREBUILDS_ONLY,ir=process.versions.modules,Tt=An()?"electron":Ln()?"node-webkit":"node",It=process.env.npm_config_arch||lr.arch(),kt=process.env.npm_config_platform||lr.platform(),fr=process.env.LIBC||(Pn(kt)?"musl":"glibc"),Ct=process.env.ARM_VERSION||(It==="arm64"?"8":In.arm_version)||"",ur=(process.versions.uv||"").split(".")[0];yr.exports=R;function R(t){return cr(R.resolve(t))}R.resolve=R.path=function(t){t=j.resolve(t||".");try{var e=cr(j.join(t,"package.json")).name.toUpperCase().replace(/-/g,"_");process.env[e+"_PREBUILD"]&&(t=process.env[e+"_PREBUILD"])}catch{}if(!kn){var s=nr(j.join(t,"build/Release"),or);if(s)return s;var r=nr(j.join(t,"build/Debug"),or);if(r)return r}var i=a(t);if(i)return i;var n=a(j.dirname(process.execPath));if(n)return n;var o=["platform="+kt,"arch="+It,"runtime="+Tt,"abi="+ir,"uv="+ur,Ct?"armv="+Ct:"","libc="+fr,"node="+process.versions.node,process.versions.electron?"electron="+process.versions.electron:"",typeof __webpack_require__=="function"?"webpack=true":""].filter(Boolean).join(" ");throw new Error("No native build was found for "+o+`
8
+ loaded from: `+t+`
9
+ `);function a(l){var c=Lt(j.join(l,"prebuilds")).map(hr),u=c.filter(dr(kt,It)).sort(pr)[0];if(u){var f=j.join(l,"prebuilds",u.name),h=Lt(f).map(mr),p=h.filter(_r(Tt,ir)),_=p.sort(gr(Tt))[0];if(_)return j.join(f,_.file)}}};function Lt(t){try{return ar.readdirSync(t)}catch{return[]}}function nr(t,e){var s=Lt(t).filter(e);return s[0]&&j.join(t,s[0])}function or(t){return/\.node$/.test(t)}function hr(t){var e=t.split("-");if(e.length===2){var s=e[0],r=e[1].split("+");if(s&&r.length&&r.every(Boolean))return{name:t,platform:s,architectures:r}}}function dr(t,e){return function(s){return s==null||s.platform!==t?!1:s.architectures.includes(e)}}function pr(t,e){return t.architectures.length-e.architectures.length}function mr(t){var e=t.split("."),s=e.pop(),r={file:t,specificity:0};if(s==="node"){for(var i=0;i<e.length;i++){var n=e[i];if(n==="node"||n==="electron"||n==="node-webkit")r.runtime=n;else if(n==="napi")r.napi=!0;else if(n.slice(0,3)==="abi")r.abi=n.slice(3);else if(n.slice(0,2)==="uv")r.uv=n.slice(2);else if(n.slice(0,4)==="armv")r.armv=n.slice(4);else if(n==="glibc"||n==="musl")r.libc=n;else continue;r.specificity++}return r}}function _r(t,e){return function(s){return!(s==null||s.runtime&&s.runtime!==t&&!Cn(s)||s.abi&&s.abi!==e&&!s.napi||s.uv&&s.uv!==ur||s.armv&&s.armv!==Ct||s.libc&&s.libc!==fr)}}function Cn(t){return t.runtime==="node"&&t.napi}function gr(t){return function(e,s){return e.runtime!==s.runtime?e.runtime===t?-1:1:e.abi!==s.abi?e.abi?-1:1:e.specificity!==s.specificity?e.specificity>s.specificity?-1:1:0}}function Ln(){return!!(process.versions&&process.versions.nw)}function An(){return process.versions&&process.versions.electron||process.env.ELECTRON_RUN_AS_NODE?!0:typeof window<"u"&&window.process&&window.process.type==="renderer"}function Pn(t){return t==="linux"&&ar.existsSync("/etc/alpine-release")}R.parseTags=mr;R.matchTags=_r;R.compareTags=gr;R.parseTuple=hr;R.matchTuple=dr;R.compareTuples=pr});var vr=b((Ul,Pt)=>{var At=typeof __webpack_require__=="function"?__non_webpack_require__:g;typeof At.addon=="function"?Pt.exports=At.addon.bind(At):Pt.exports=xr()});var Ir=b((Wl,W)=>{var Rn=g("node:assert"),{randomBytes:Nn,timingSafeEqual:Mn}=g("node:crypto"),{promisify:Bn}=g("node:util"),{deserialize:br,serialize:Dn}=rr(),$n=vr(),{hash:wr}=$n(__dirname),jn=Bn(Nn),Sr=0,Or=1,Rt=2;W.exports.argon2d=Sr;W.exports.argon2i=Or;W.exports.argon2id=Rt;var we=Object.freeze({argon2d:Sr,argon2i:Or,argon2id:Rt}),Un=Object.freeze({[we.argon2d]:"argon2d",[we.argon2i]:"argon2i",[we.argon2id]:"argon2id"}),Er=Object.freeze({hashLength:32,timeCost:3,memoryCost:65536,parallelism:4,type:Rt,version:19}),Tr=Object.freeze({hashLength:{min:4,max:2**32-1},memoryCost:{min:1024,max:2**32-1},timeCost:{min:2,max:2**32-1},parallelism:{min:1,max:2**24-1}});W.exports.limits=Tr;async function qn(t,e){let{raw:s,salt:r,...i}={...Er,...e};for(let[_,{min:d,max:m}]of Object.entries(Tr)){let y=i[_];Rn(d<=y&&y<=m,`Invalid ${_}, must be between ${d} and ${m}.`)}r=r??await jn(16);let{hashLength:n,secret:o=Buffer.alloc(0),type:a,version:l,memoryCost:c,timeCost:u,parallelism:f,associatedData:h=Buffer.alloc(0)}=i,p=await wr({password:Buffer.from(t),salt:r,secret:o,data:h,hashLength:n,m:c,t:u,p:f,version:l,type:a});return s?p:Dn({id:Un[a],version:l,params:{m:c,t:u,p:f,...h.byteLength>0?{data:h}:{}},salt:r,hash:p})}W.exports.hash=qn;function Wn(t,e={}){let{memoryCost:s,timeCost:r,version:i}={...Er,...e},{version:n,params:{m:o,t:a}}=br(t);return+n!=+i||+o!=+s||+a!=+r}W.exports.needsRehash=Wn;async function Fn(t,e,s={}){let{id:r,...i}=br(t);if(!(r in we))return!1;let{version:n=16,params:{m:o,t:a,p:l,data:c=""},salt:u,hash:f}=i,{secret:h=Buffer.alloc(0)}=s;return Mn(await wr({password:Buffer.from(e),salt:u,secret:h,data:Buffer.from(c,"base64"),hashLength:f.byteLength,m:+o,t:+a,p:+l,version:+n,type:we[r]}),f)}W.exports.verify=Fn});var Cr=b((Fl,Nt)=>{"use strict";var Gn=Object.prototype.hasOwnProperty,O="~";function Se(){}Object.create&&(Se.prototype=Object.create(null),new Se().__proto__||(O=!1));function Vn(t,e,s){this.fn=t,this.context=e,this.once=s||!1}function kr(t,e,s,r,i){if(typeof s!="function")throw new TypeError("The listener must be a function");var n=new Vn(s,r||t,i),o=O?O+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],n]:t._events[o].push(n):(t._events[o]=n,t._eventsCount++),t}function ze(t,e){--t._eventsCount===0?t._events=new Se:delete t._events[e]}function S(){this._events=new Se,this._eventsCount=0}S.prototype.eventNames=function(){var e=[],s,r;if(this._eventsCount===0)return e;for(r in s=this._events)Gn.call(s,r)&&e.push(O?r.slice(1):r);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(s)):e};S.prototype.listeners=function(e){var s=O?O+e:e,r=this._events[s];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,n=r.length,o=new Array(n);i<n;i++)o[i]=r[i].fn;return o};S.prototype.listenerCount=function(e){var s=O?O+e:e,r=this._events[s];return r?r.fn?1:r.length:0};S.prototype.emit=function(e,s,r,i,n,o){var a=O?O+e:e;if(!this._events[a])return!1;var l=this._events[a],c=arguments.length,u,f;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),c){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,s),!0;case 3:return l.fn.call(l.context,s,r),!0;case 4:return l.fn.call(l.context,s,r,i),!0;case 5:return l.fn.call(l.context,s,r,i,n),!0;case 6:return l.fn.call(l.context,s,r,i,n,o),!0}for(f=1,u=new Array(c-1);f<c;f++)u[f-1]=arguments[f];l.fn.apply(l.context,u)}else{var h=l.length,p;for(f=0;f<h;f++)switch(l[f].once&&this.removeListener(e,l[f].fn,void 0,!0),c){case 1:l[f].fn.call(l[f].context);break;case 2:l[f].fn.call(l[f].context,s);break;case 3:l[f].fn.call(l[f].context,s,r);break;case 4:l[f].fn.call(l[f].context,s,r,i);break;default:if(!u)for(p=1,u=new Array(c-1);p<c;p++)u[p-1]=arguments[p];l[f].fn.apply(l[f].context,u)}}return!0};S.prototype.on=function(e,s,r){return kr(this,e,s,r,!1)};S.prototype.once=function(e,s,r){return kr(this,e,s,r,!0)};S.prototype.removeListener=function(e,s,r,i){var n=O?O+e:e;if(!this._events[n])return this;if(!s)return ze(this,n),this;var o=this._events[n];if(o.fn)o.fn===s&&(!i||o.once)&&(!r||o.context===r)&&ze(this,n);else{for(var a=0,l=[],c=o.length;a<c;a++)(o[a].fn!==s||i&&!o[a].once||r&&o[a].context!==r)&&l.push(o[a]);l.length?this._events[n]=l.length===1?l[0]:l:ze(this,n)}return this};S.prototype.removeAllListeners=function(e){var s;return e?(s=O?O+e:e,this._events[s]&&ze(this,s)):(this._events=new Se,this._eventsCount=0),this};S.prototype.off=S.prototype.removeListener;S.prototype.addListener=S.prototype.on;S.prefixed=O;S.EventEmitter=S;typeof Nt<"u"&&(Nt.exports=S)});import{CookieSetter as no,InSiteCookieMiddleware as oo}from"insite-cookie/server";import{SubscriptionHandler as ao}from"insite-subscriptions-server/ws";import Js from"node:fs";import vn from"node:http";import bn from"node:https";var gn=G(Yt(),1),yn=G(lt(),1),xn=G(ut(),1),vt=G(yt(),1),bt=G(Ys(),1);function re(){}function wt(t,e=0,s={}){let{leading:r=!1,trailing:i=!0}=s,{maxWait:n=1/0}=s,o,a,l,c,u,f,h,p,_=async()=>{let v=Date.now();v>=l?(o=void 0,l=void 0,clearTimeout(a),typeof h=="function"&&await h(),y.resolve(p),y.promise.isResolved=!0,f=r):(clearTimeout(o),o=setTimeout(_,l-v))},d=Number.isFinite(n)?()=>{h===m&&(h=!1),m(),a=setTimeout(d,n)}:null;async function m(){return p=await t.apply(c,u)}r&&typeof r=="boolean"&&(r=m),f=r,i&&typeof i=="boolean"&&(i=m),h=i;let y=Object.assign(function(...v){return u=v,c=this,l=Date.now()+e,h=i,y.promise.isResolved&&(y.promise=Object.assign(new Promise(X=>{y.resolve=X,typeof f=="function"&&(f(),f=!1,h===m&&(h=!1)),o||(o=setTimeout(_,e),d&&(a=setTimeout(d,n)))}),{isResolved:!1})),y.promise},{callback:t,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:re,run:m,clear:async v=>{clearTimeout(o),o=void 0,clearTimeout(a),y.promise.isResolved=!0,y.resolve(v?await m():p)}});return y}wt.noop=Object.assign(()=>{},{callback:re,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:re,run:re,clear:re});function Xs(t,e,s,r,i=!0){return Array.isArray(t)&&(t=t.length),typeof r!="string"&&(i=r??!0,r=s),(i?`${t}\xA0`:"")+Xs.raw(t,e,s,r)}Xs.raw=(t,e,s,r=s)=>{t=Math.abs(t);let i=t%10,n=t%100;return i===1&&n!==11?e:i>=2&&i<=4&&!(n>=12&&n<=15)?s:r};function Zs(t="",e=""){return`${t}${Date.now().toString(36)}${Math.round(Math.random()*Number.MAX_SAFE_INTEGER).toString(36)}${e}`}var xe={request:"~r-q",response:"~r-s"},St=Symbol("heartbeatInterval"),ye=Symbol("defib"),ve=Symbol("pingTs"),P=class Ot extends vt.default{get isConnecting(){return this.readyState===this.CONNECTING}get isOpen(){return this.readyState===this.OPEN}get isClosing(){return this.readyState===this.CLOSING}get isClosed(){return this.readyState===this.CLOSED}isWebSocketServerClient=!0;isWebSocketServer=!1;isWebSocket=!1;wss;userAgent="";remoteAddress="";[ye]=Ot.makeDefib.call(this);latency=0;[ve];[St]=Ot.makeHeartbeatInterval.call(this);sendMessage(...e){return this.send(JSON.stringify(e))}sendRequest(...e){let s=Zs(),r=`message:${xe.response}-${s}`;return typeof e.at(-1)=="function"?(this.once(r,e.splice(-1,1)[0]),this.sendMessage(xe.request,s,...e),this):new Promise((i,n)=>{this.once(r,(o,a)=>{if(o){let{message:l,...c}=o;n(Object.assign(new Error(l),c))}else i(a)}),this.sendMessage(xe.request,s,...e)})}static makeDefib(){return wt(()=>this.terminate(),65e3)}static makeHeartbeatInterval(){return setInterval(()=>{this[ve]=Date.now(),this.send("")},5e3)}},Qs=class ie extends bt.default{constructor(e,s,r){let{ssl:i,port:n,...o}=e;if(i){if(typeof i.cert=="string"&&!/^-{3,}BEGIN/.test(i.cert))try{i.cert=Js.readFileSync(i.cert)}catch{}if(typeof i.key=="string"&&!/^-{3,}BEGIN/.test(i.key))try{i.key=Js.readFileSync(i.key)}catch{}}let{server:a=i?bn.createServer({...i}):vn.createServer()}=o;super({...o,server:a,WebSocket:P}),this.port=typeof n=="string"?Number.parseInt(n):n,s&&(typeof s=="function"?r=s:Object.assign(this,s)),this.on("connection",ie.handleConnection),this.on(`client-message:${xe.request}`,this.handleRequest),a.listen(this.port,r)}isWebSocketServer=!0;isWebSocketServerClient=!1;isWebSocket=!1;port;requestListeners=new Map;addRequestListener(e,s){return this.requestListeners.set(e,s),this}onRequest=this.addRequestListener;removeRequestListener(e){return this.requestListeners.delete(e),this}offRequest=this.removeRequestListener;handleRequest=async(e,s,r,...i)=>{let n=this.requestListeners.get(r),o,a=null;if(n)try{o=await n.call(this,e,...i)}catch(l){if(l instanceof Error){let{message:c,...u}=l;a={message:c,...u}}}else a={message:`Unknown request kind "${r}"`};e.sendMessage(`${xe.response}-${s}`,a,o)};static handleConnection(e,s){if(!(e instanceof P)){Object.defineProperties(e,{isConnecting:{get:Object.getOwnPropertyDescriptor(P.prototype,"isConnecting").get},isOpen:{get:Object.getOwnPropertyDescriptor(P.prototype,"isOpen").get},isClosing:{get:Object.getOwnPropertyDescriptor(P.prototype,"isClosing").get},isClosed:{get:Object.getOwnPropertyDescriptor(P.prototype,"isClosed").get}});let{terminate:r}=e;Object.assign(e,{isWebSocketServerClient:!0,isWebSocketServer:!1,isWebSocket:!1,[ye]:P.makeDefib.call(e),latency:0,[St]:P.makeHeartbeatInterval.call(e),sendMessage:P.prototype.sendMessage,sendRequest:P.prototype.sendRequest,terminate(){try{r.call(e)}catch(i){console.error(i)}}})}Object.assign(e,{wss:this,userAgent:s.headers["user-agent"]??"",remoteAddress:s.headers["x-real-ip"]??s.headers["x-forwarded-for"]??""}),e[ye](),e.on("message",ie.handleClientMessage),e.on("error",ie.handleClientError),e.on("close",ie.handleClientClose),this.emit("client-connect",e,s)}static handleClientMessage(e){let s=e.toString();if(this[ye](),s)try{let[r,...i]=JSON.parse(s);this.emit(`message:${r}`,...i),this.wss.emit("client-message",this,r,...i),this.wss.emit(`client-message:${r}`,this,...i)}catch(r){ie.handleClientError.call(this,r)}else this[ve]&&(this.latency=Date.now()-this[ve],delete this[ve])}static handleClientError(e){e instanceof Event&&(e=void 0),process.env.NODE_ENV==="development"&&console.error("WebSocketServer Client error",e),this.wss.emit("client-error",this,e)}static handleClientClose(...e){process.env.NODE_ENV==="development"&&console.info("WebSocketServer Client closed",...e),this[ye].clear(),clearInterval(this[St]),this.wss.emit("client-close",this),this.wss.emit("client-closed",this)}};import{IncomingTransport as lo}from"insite-ws-transfers/node";import{connect as co}from"insite-db";import{InSiteHTTPServer as fo,InSiteStaticMiddleware as uo,InSiteTemplateMiddleware as ho}from"insite-http";var Ce=G(Ir(),1);var Lr=G(Cr(),1);var Ar=Lr.default;function Oe(t){if(t instanceof Set){let e=[];for(let s of t)e.push(s._id);return e}return t.map(e=>e._id)}function ne(){}function N(t,e=0,s={}){let{leading:r=!1,trailing:i=!0}=s,{maxWait:n=1/0}=s,o,a,l,c,u,f,h,p,_=async()=>{let v=Date.now();v>=l?(o=void 0,l=void 0,clearTimeout(a),typeof h=="function"&&await h(),y.resolve(p),y.promise.isResolved=!0,f=r):(clearTimeout(o),o=setTimeout(_,l-v))},d=Number.isFinite(n)?()=>{h===m&&(h=!1),m(),a=setTimeout(d,n)}:null;async function m(){return p=await t.apply(c,u)}r&&typeof r=="boolean"&&(r=m),f=r,i&&typeof i=="boolean"&&(i=m),h=i;let y=Object.assign(function(...v){return u=v,c=this,l=Date.now()+e,h=i,y.promise.isResolved&&(y.promise=Object.assign(new Promise(X=>{y.resolve=X,typeof f=="function"&&(f(),f=!1,h===m&&(h=!1)),o||(o=setTimeout(_,e),d&&(a=setTimeout(d,n)))}),{isResolved:!1})),y.promise},{callback:t,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:ne,run:m,clear:async v=>{clearTimeout(o),o=void 0,clearTimeout(a),y.promise.isResolved=!0,y.resolve(v?await m():p)}});return y}N.noop=Object.assign(()=>{},{callback:ne,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:ne,run:ne,clear:ne});function C(t,e){if(t){for(let s of e)delete t[s];return t}return null}function Pr(t){for(let e in t)delete t[e];return t}var He=class extends Array{constructor(){super(),Object.freeze(this)}push(){return 0}unshift(){return 0}splice(){return[]}};var oe=class extends Set{constructor(){super()}add(){return this}};function Mt(t,e,s=!1){return s&&(e=e.filter(r=>t.has(r))),e.map(r=>t.get(r))}function Rr(t,e){for(let s of e)if(t.has(s))return!0;return!1}function Nr(t,e,s,r,i=!0){return Array.isArray(t)&&(t=t.length),typeof r!="string"&&(i=r??!0,r=s),(i?`${t}\xA0`:"")+Nr.raw(t,e,s,r)}Nr.raw=(t,e,s,r=s)=>{t=Math.abs(t);let i=t%10,n=t%100;return i===1&&n!==11?e:i>=2&&i<=4&&!(n>=12&&n<=15)?s:r};function Mr(t,...e){let s=[];e:for(let r of t){for(let i of e)if(i instanceof Set?!i.has(r):!i.includes(r))continue e;s.push(r)}return s}function Ke(t,e){return Math.floor(Math.random()*(e-t+1)+t)}function Br(t,e){return t.delete(e),t.add(e),t}function F(t,e){let s,r=0;for(let i of e)for(;(s=t.indexOf(i))>-1;)t.splice(s,1),r++;return r}function Dr(t,e){let s=t.indexOf(e);return s>-1?(t.splice(s,1),!0):!1}function $r(t,e){for(let s of[...t].sort(e))t.delete(s),t.add(s);return t}import{newObjectIdString as zn}from"insite-db";import{newObjectIdString as Kn}from"insite-db";import qr from"node:crypto";var Hn=class extends Map{constructor(t){super(),this.schema=t,this.parse(this.schema)}schema;parse(t){for(let e of t)this.set(e._id,e),e.subAbilities&&this.parse(e.subAbilities)}merge(t,e){for(let[s,r]of Object.entries(e)){let i=this.get(s);if(i){if(i.isInheritable!==!1&&r){if(!(s in t))t[s]=structuredClone(r);else if(i.params){let n=t[s],o=r;for(let a of i.params)if(a.isInheritable!==!1&&a._id in o){if(!(a._id in n))n[a._id]=structuredClone(o[a._id]);else if(a.type==="number")n[a._id]<o[a._id]&&(n[a._id]=o[a._id]);else if(a.type==="items"){let l=n[a._id];for(let c of o[a._id])l.includes(c)||l.push(c)}}}}}else delete e[s]}return t}getMinimumOf(t){let e=this.get(t);if(e?.params){let s={};for(let r of e.params)r.type==="number"?s[r._id]=r.min??0:r.type==="items"&&(s[r._id]=[]);return s}return!0}getMaximum(){return[...this.values()].reduce((t,e)=>{if(e.params){let s={};for(let r of e.params)r.type==="number"?s[r._id]=r.max??0:r.type==="items"&&(s[r._id]=r.items.map(i=>i._id));t[e._id]=s}else t[e._id]=!0;return t},{})}getSchemeFor(t){return function e(s){for(let r=0;r<s.length;r++){let i=s[r],n=t.abilities[i._id];if(n){if(i.params)for(let o of i.params){let a=n[o._id];if(o.type==="number")"max"in o&&(o.max=a);else if(o.type==="items")for(let l=0;l<o.items.length;l++)a.includes(o.items[l]._id)||o.items.splice(l--,1)}i.subAbilities&&e(i.subAbilities)}else s.splice(r--,1)}return s}(structuredClone(this.schema))}},Bt=new Map,ae=class{constructor(t,e){this.orgs=t,this._id=e._id,t.set(this._id,this),this.update(e)}_id;title="";initials="";displayLabel="";_o=0;orgs;isOrg=!0;ownerOrgs=new Set;ownerUsers=new Set;users=new Set;slaveOrgs=new Set;ownerIds=[];update({_id:t,title:e,owners:s,...r},i){if(Object.assign(this,r),e!==void 0&&(this.title=e,this.initials=e?.[0]?.toUpperCase()??"",this.displayLabel=e),s){this.ownerIds=s;let n=this.ownerIds.join(",");n!==Bt.get(this._id)&&(Bt.set(this._id,n),this.orgs.users.isInited&&this.orgs.updateDebounced(),this.orgs.users.emit("orgs-org-update",this,i))}}delete(){this.orgs.delete(this._id),Bt.delete(this._id),this.orgs.replace(this._id),this.orgs.updateDebounced()}},T={_id:/^[\dA-Fa-f]{24}$/,email:/^[^\s@]{1,63}@[^\s@]{1,63}\.[^\s@]{1,63}$/,argon2:/^\$argon2(?:i|d|id)\$v=\d+\$m=\d+,t=\d+,p=\d+(?:\$[\d+/A-Za-z]+){2}$/,sessionId:/^[\dA-Fa-f]{16,32}\$[\dA-Fa-f]{16,32}$/,role:/^[\d_a-z-]{1,64}$/,ip:/^(?:\d{1,3}\.){3}\d{1,3}$/},Ee={required:["_id","title","note","owners","createdAt"],properties:{_id:{bsonType:"string",pattern:T._id.source},title:{bsonType:"string",maxLength:512},note:{bsonType:"string",maxLength:131072},owners:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:T._id.source},additionalItems:!1},createdAt:{bsonType:"number"}},additionalProperties:!1},Yn=[[{owners:1}]];function jr(){throw new Error("Direct usage of orgs collection.deleteOne or .deleteMany is forbidden. Use orgs.collectionDelete instead.")}var Xn=class extends Map{constructor(t,e={}){super(),this.users=t,this.collections=t.collections,this.preinitOptions=e}users;collections;preinitOptions;collection;null;load(t){new ae(this,t)}resolve(t,e){e=[t,...e];for(let s of t.ownerOrgs){this.resolve(s,e);for(let r of e)s.slaveOrgs.add(r)}}sorted=[];update(){let t=[...this.values()],e=[];for(let s of t){s.ownerOrgs.clear(),s.ownerUsers.clear(),s.slaveOrgs.clear();for(let r of s.ownerIds){let i=this.get(r);if(i)s.ownerOrgs.add(i);else{let n=this.users.get(r);n&&s.ownerUsers.add(n)}}!s.ownerOrgs.size&&s._id&&e.push(s)}for(let s of t)t.some(r=>r.ownerOrgs.has(s))||this.resolve(s,[]);e.sort(this.sortOrgs);for(let s of t)$r(s.slaveOrgs,this.sortOrgs);for(let s=0;s<e.length;s++){let r=e[s];for(let i of[...r.slaveOrgs].reverse())if(i.ownerOrgs.has(r)){let n=e.indexOf(i);~n&&(e.splice(n,1),s--),e.splice(s+1,0,i)}}for(let{length:s}=e,r=0;r<s;)e[r]._o=r++;this.sorted=e,this.users.emit("orgs-update"),this.users.isInited&&(this.users.updateDebounced.clear(),this.users.update())}sortOrgs(t,e){return e.slaveOrgs.size-t.slaveOrgs.size||(t.title>e.title?1:t.title<e.title?-1:0)}updateDebounced=N(this.update,250);preinit=async()=>{let{schema:t,indexes:e,null:s}=this.preinitOptions;t&&(t.required&&F(t.required,Ee.required),t.properties&&C(t,Object.keys(Ee.properties)));let r={...Ee,...t,required:[...Ee.required,...t?.required??[]],properties:{...Ee.properties,...t?.properties}};this.collection=Object.assign(await this.collections.ensure("orgs",{jsonSchema:r}),{deleteOne:jr,deleteMany:jr}),this.collection.ensureIndexes([...Yn,...e??[]]),this.null=Object.assign(new ae(this,{...s,_id:"",title:"",note:"",owners:[],createdAt:Date.now()}),{_id:null,ownerIds:new He,ownerOrgs:new oe,ownerUsers:new oe,slaveOrgs:new oe});for(let i of await this.collection.find().toArray())this.load(i);delete this.preinitOptions,delete this.preinit};init=async()=>{await this.update(),this.collection.changeListeners.add(t=>{switch(t.operationType){case"insert":{let e=new ae(this,t.fullDocument);this.users.emit("orgs-org-update",e,t);break}case"replace":this.get(t.documentKey._id)?.update(t.fullDocument,t);break;case"update":this.get(t.documentKey._id)?.update(t.updateDescription.updatedFields,t);break;case"delete":this.get(t.documentKey._id)?.delete(),this.users.emit("orgs-org-update",null,t)}}),delete this.init};new({title:t,note:e,...s},r){return this.collection.insertOne({_id:Kn(),title:t??"",note:e??"",owners:r?[r]:[],...C(s,["_id","owners"]),createdAt:Date.now()})}collectionDelete(t){let e=typeof t=="string"?t:t._id;return this.collection.bulkWrite([{updateMany:{filter:{owners:e},update:{$pullAll:{owners:[e]}}}},{deleteOne:{filter:{_id:e}}}])}replaceMap=new Map;replaceHandlers=new Set;async replace(t){let e=this.replaceMap.get(t)??null;e&&this.replaceMap.delete(t);for(let s of this.replaceHandlers)await s(t,e)}},Dt=new Map,$t=class{constructor(t,e){this.roles=t,this._id=e._id,t.set(this._id,this),this.update(e)}roles;_id;ownInvolveIds;ownAbilities;title="";displayTitle="";_o=0;ownInvolves=[];involves=new Set;abilities={};inheritedAbilities={};update({_id:t,involves:e,abilities:s,title:r,...i},n){if(Object.assign(this,i),e&&(this.ownInvolveIds=e),s&&(this.ownAbilities=s),r!==void 0&&(this.title=r,this.displayTitle=r||this._id),e||s){let o=[this.ownInvolveIds.join(","),JSON.stringify(this.ownAbilities)].join(`
10
+ `);o!==Dt.get(this._id)&&(Dt.set(this._id,o),this.roles.users.isInited&&this.roles.updateDebounced(),this.roles.users.emit("roles-role-update",this,n))}}delete(){this.roles.delete(this._id),Dt.delete(this._id),this.roles.updateDebounced()}},Te={required:["_id","involves","abilities","title","description","createdAt"],properties:{_id:{bsonType:"string",pattern:T.role.source,not:{enum:["root"]}},involves:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:T.role.source,not:{enum:["root"]}},additionalItems:!1},abilities:{bsonType:"object"},title:{bsonType:"string",maxLength:256},description:{bsonType:"string",maxLength:10240},createdAt:{bsonType:"number"}},additionalProperties:!1},Zn=[[{involves:1}]];function Ur(){throw new Error("Direct usage of roles collection.deleteOne or .deleteMany is forbidden. Use roles.collectionDelete instead.")}var Jn=class extends Map{constructor(t,e={}){super();let{root:s,...r}=e;this.users=t,this.collections=t.collections,this.abilitiesMap=t.abilitiesMap,this.root=new $t(this,{...s,_id:"root",involves:[],abilities:this.abilitiesMap.getMaximum(),title:"Root",description:"Root",createdAt:Date.now()}),this.initOptions=r}users;collections;collection;abilitiesMap;root;initOptions;load(t){new $t(this,t)}resolve(t,e){e=[t,...e];for(let s of t.ownInvolveIds){let r=this.get(s);if(r){for(let i of e)Br(i.involves,r),this.abilitiesMap.merge(i.inheritedAbilities,r.abilities);r!==t&&this.resolve(r,e)}}}sorted=[];sortRoles(t,e){return e.involves.size-t.involves.size||(t.title&&e.title?t.title>e.title?1:t.title<e.title?-1:0:t.title?-1:e.title||t._id>e._id?1:t._id<e._id?-1:0)}update(){let t=[...this.values()];this.root.ownInvolveIds=[];for(let r of t)r!==this.root&&!t.some(i=>i.ownInvolveIds.includes(r._id))&&this.root.ownInvolveIds.push(r._id),r.involves.clear(),r.abilities=structuredClone(r.ownAbilities),r.inheritedAbilities={};this.root.involves.add(this.root),this.resolve(this.root,[]);for(let r of t)r.ownInvolves=Mt(this,r.ownInvolveIds,!0).sort(this.sortRoles).reverse();let e=[this.root];for(let r=0;r<e.length;r++){let i=e[r];for(let n of i.ownInvolves){let o=e.indexOf(n);~o&&(e.splice(o,1),r--),e.splice(r+1,0,n)}}let s=0;for(let r of e)this.abilitiesMap.merge(r.abilities,r.inheritedAbilities),r._o=s++;this.sorted=e,this.users.emit("roles-update"),this.users.isInited&&(this.users.updateDebounced.clear(),this.users.update(!0))}updateDebounced=N(this.update,250);init=async()=>{let{schema:t,indexes:e}=this.initOptions;t&&(t.required&&F(t.required,Te.required),t.properties&&C(t,Object.keys(Te.properties)));let s={...Te,...t,required:[...Te.required,...t?.required??[]],properties:{...Te.properties,...t?.properties}};this.collection=Object.assign(await this.collections.ensure("roles",{jsonSchema:s}),{deleteOne:Ur,deleteMany:Ur}),this.collection.ensureIndexes([...Zn,...e??[]]);for(let r of await this.collection.find().toArray())this.load(r);await this.update(),this.collection.changeListeners.add(r=>{switch(r.operationType){case"insert":{let i=new $t(this,r.fullDocument);this.users.emit("roles-role-update",i,r);break}case"replace":this.get(r.documentKey._id)?.update(r.fullDocument,r);break;case"update":this.get(r.documentKey._id)?.update(r.updateDescription.updatedFields,r);break;case"delete":this.get(r.documentKey._id)?.delete(),this.users.emit("roles-role-update",null,r)}}),delete this.initOptions,delete this.init};new({_id:t,involves:e,title:s,description:r,...i}){return this.collection.insertOne({_id:t,involves:e||[],abilities:{},title:s??"",description:r??"",...C(i,["abilities"]),createdAt:Date.now()})}collectionDelete(t){let e=typeof t=="string"?t:t._id;return this.collection.bulkWrite([{updateMany:{filter:{involves:e},update:{$pullAll:{involves:[e]}}}},{deleteOne:{filter:{_id:e}}}])}cleanUpIds(t){let e=Mr(this.sorted,Mt(this,t,!0)),s=[];for(let r of e)e.every(i=>i===r||!i.involves.has(r))&&s.push(r._id);return s}},Ie={required:["_id","user","remoteAddress","isOnline","createdAt","prolongedAt","expiresAt"],properties:{_id:{bsonType:"string",pattern:T.sessionId.source},user:{bsonType:"string",pattern:T._id.source},userAgent:{bsonType:"string",maxLength:4096},remoteAddress:{bsonType:"string",pattern:T.ip.source},isOnline:{bsonType:"bool"},createdAt:{bsonType:"number"},prolongedAt:{bsonType:"number"},expiresAt:{bsonType:"date"}},additionalProperties:!1},jt=class{constructor(t,e){let s=t.users.get(e.user);s?(this.sessions=t,this._id=e._id,this.sessions.set(this._id,this),this.user=s,this.user.sessions.add(this),this.sessions.users.bySessionId.set(this._id,this.user),this.update(e)):t.collection.deleteOne({_id:e._id})}_id;user;isOnline=!1;userAgent;remoteAddress;createdAt;prolongedAt;expiresAt;sessions;update({_id:t,user:e,isOnline:s,...r}){s!==void 0&&this.isOnline!==s&&(this.isOnline=s,this.sessions.isInited&&this.user.isOnline!==this.isOnline&&this.user.updateIsOnline()),Object.assign(this,r)}prolong({_id:t,user:e,...s}){let r=Date.now();return s.prolongedAt=r,s.expiresAt=new Date(r+this.sessions.collection.expireAfterSeconds*1e3),this.update(s),this.sessions.collection.updateOne({_id:this._id},{$set:s})}offline(){let t={isOnline:!1};return this.update(t),this.sessions.collection.updateOne({_id:this._id},{$set:t})}delete(){this.sessions.delete(this._id),this.user.sessions.delete(this),this.sessions.users.bySessionId.delete(this._id),this.sessions.users.emit("session-delete",this),this.isOnline&&this.user.updateIsOnline()}},Wt=3600*24*7,Qn=[[{user:1}],[{expiresAt:1},{expireAfterSeconds:Wt}]],eo=class extends Map{constructor(t,e={}){super(),this.users=t,this.collections=t.collections,this.initOptions=e}users;collections;initOptions;collection;isInited=!1;uid(){let t;do t=`${qr.randomBytes(Ke(8,16)).toString("hex")}$${qr.randomBytes(Ke(8,16)).toString("hex")}`;while(this.has(t));return t}load(t){new jt(this,t)}init=async()=>{let{schema:t,indexes:e}=this.initOptions;t&&(t.required&&F(t.required,Ie.required),t.properties&&C(t,Object.keys(Ie.properties)));let s={...Ie,...t,required:[...Ie.required,...t?.required??[]],properties:{...Ie.properties,...t?.properties}};this.collection=Object.assign(await this.collections.ensure("sessions",{jsonSchema:s}),{expireAfterSeconds:Wt}),this.collection.ensureIndexes([...Qn,...e??[]]),await this.collection.updateMany({isOnline:!0},{$set:{isOnline:!1}});for(let r of await this.collection.find().toArray())this.load(r);this.collection.changeListeners.add(r=>{switch(r.operationType){case"insert":this.has(r.documentKey._id)||new jt(this,r.fullDocument),this.users.get(r.fullDocument.user)?.trimSessions();break;case"replace":this.get(r.documentKey._id)?.update(r.fullDocument);break;case"update":this.get(r.documentKey._id)?.update(r.updateDescription.updatedFields);break;case"delete":this.get(r.documentKey._id)?.delete()}}),this.isInited=!0,delete this.initOptions,delete this.init};async new(t,e){let s=Date.now(),r={userAgent:"",remoteAddress:"127.0.0.1",isOnline:!0,...e,_id:this.uid(),user:t._id,createdAt:s,prolongedAt:s,expiresAt:new Date(s+Wt*1e3)},i=new jt(this,r);return await this.collection.insertOne(r),i}},to={required:["_id","type","size","ts","data"],properties:{_id:{bsonType:"string",pattern:T._id.source},type:{bsonType:"string",maxLength:256},size:{bsonType:"number"},ts:{bsonType:"string",maxLength:10},data:{bsonType:"binData"}},additionalProperties:!1},so=class{constructor(t){this.users=t,this.collections=t.collections}users;collections;collection;init=async()=>{this.collection=await this.collections.ensure("users.avatars",{jsonSchema:to}),delete this.init}},ke={required:["_id","email","password","roles","name","org","job","createdAt"],properties:{_id:{bsonType:"string",pattern:T._id.source},email:{bsonType:"string",pattern:T.email.source},password:{bsonType:"string",pattern:T.argon2.source},roles:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:T.role.source},additionalItems:!1},name:{bsonType:"object",required:["first","middle","last"],properties:{first:{bsonType:"string",maxLength:512},middle:{bsonType:"string",maxLength:512},last:{bsonType:"string",maxLength:512}},additionalProperties:!1},org:{oneOf:[{bsonType:"string",pattern:T._id.source},{bsonType:"null"}]},job:{bsonType:"string",maxLength:512},avatar:{oneOf:[{bsonType:"string",maxLength:10},{bsonType:"null"}]},createdAt:{bsonType:"number"}},additionalProperties:!1},Ut=new Map,qt=new Map,ro=process.env.INSITE_STATIC_URL??"http://localhost:8080",Ye=class{constructor(t,e){this.users=t,this._id=e._id,t.set(this._id,this),this.update(e),t.isInited&&t.emit("user-create",this)}_id;email;name={first:"",middle:"",last:""};initials="";displayLabel="";org;job="";avatar=null;avatarUrl=null;users;isUser=!0;isRoot;roles=new Set;ownRoles=[];ownRoleIds=[];slaveRoles=new Set;slaveRoleIds=[];abilities={};slaveOrgs=new Set;slaveUsers=new Set;slaves=new Set;slaveIds=[];permissiveIds=[];sessions=new Set;isOnline=!1;update({_id:t,name:e,email:s,roles:r,org:i,avatar:n,...o}){Object.assign(this,o);let a;s&&this.email!==s&&(this.users.byEmail.delete(this.email),this.email=s,this.users.byEmail.set(s,this),a=!0);let l,c;e&&(this.name.first!==e.first||this.name.middle!==e.middle||this.name.last!==e.last)&&(c=this.name.last!==e.last,this.name={first:e.first??"",middle:e.middle??"",last:e.last??""},this.initials=((e.first?.[0]??"")+(e.last?.[0]??"")||this.email[0]).toUpperCase(),l=!0),(a||l)&&(this.displayLabel=`${this.name.first} ${this.name.last}`.trim()||this.name.middle||this.email);let u;if(r){this.ownRoleIds=r;let h=this.ownRoleIds.join(",");h!==Ut.get(this._id)&&(Ut.set(this._id,h),this.updateRoles(),u=!0)}let f;i!==void 0&&this.org?._id!==i&&(this.org?.users.delete(this),this.org=i&&this.users.orgs.get(i)||this.users.orgs.null,this.org.users.add(this),f=!0),n!==void 0&&this.avatar!==n&&(this.avatar=n,this.avatarUrl=n&&`${ro}/avatars/${this._id}-${n}.webp`),u||f?(this.updatePermissions(),c&&(this.users.isSortRequired=!0),this.users.isInited&&this.users.updateDebounced()):c&&this.users.sortDebounced()}updateRoles(){if(this.users.isInited){this.ownRoles=[],this.roles.clear(),this.slaveRoles.clear(),Pr(this.abilities);for(let t of this.ownRoleIds){let e=this.users.roles.get(t);if(e){this.ownRoles.push(e),this.roles.add(e);for(let s of e.involves)this.roles.add(s),this.slaveRoles.add(s);this.slaveRoleIds=Oe(this.slaveRoles),this.users.abilitiesMap.merge(this.abilities,e.abilities)}}this.roles.has(this.users.roles.root)&&(this.isRoot=!0),this.trimSessions()}}updatePermissions(){if(this.users.isInited){this.slaveOrgs.clear(),this.slaveUsers.clear(),this.slaves.clear();let t=new Set;for(let r of this.users.orgs.sorted)if((r.ownerUsers.has(this)||this.isRoot)&&!this.slaveOrgs.has(r)){this.slaveOrgs.add(r),this.slaves.add(r),t.add(r._id);for(let i of r.slaveOrgs)this.slaveOrgs.add(i),this.slaves.add(i),t.add(i._id)}for(let r of new Set([this.org,...this.slaveOrgs,this.users.orgs.null]))for(let i of r.users)i!==this&&(Rr(this.slaveRoles,i.ownRoles)||!i.ownRoles.length)&&(this.slaveUsers.add(i),this.slaves.add(i),t.add(i._id));this.slaveIds=[...t];let e=[];if(this.org._id){e.push(this.org._id);for(let r of this.org.slaveOrgs)this.slaveOrgs.has(r)||e.push(r._id)}this.permissiveIds=[...e,this._id,...t];let s=[this.permissiveIds.join(","),this.ownRoleIds.join(","),JSON.stringify(this.abilities),this.slaveRoleIds.join(",")].join(`
11
+ `);s!==qt.get(this._id)&&(qt.set(this._id,s),this.users.emit("user-permissions-change",this))}}trimSessions(){let t=this.abilities.login?.sessionsLimit??0;return this.sessions.size>t?this.users.sessions.collection.deleteMany({_id:{$in:Oe([...this.sessions].sort((e,s)=>e.expiresAt.valueOf()-s.expiresAt.valueOf()).slice(0,this.sessions.size-t))}}):null}updateIsOnline=N(()=>{let t=!1;for(let e of this.sessions)if(e.isOnline){t=!0;break}this.isOnline!==t&&(this.isOnline=t,this.users.emit("user-is-online",this))},500);delete(){this.org.users.delete(this),this.users.delete(this._id),this.users.byEmail.delete(this.email),Dr(this.users.sorted,this),Ut.delete(this._id),qt.delete(this._id),this.users.replace(this._id),this.users.updateDebounced()}},io=[[{email:1},{unique:!0}],[{org:1}]],Wr=class Fr extends Map{constructor(e,s){super();let r=new Ar;this._events=r._events,this._eventsCount=r._eventsCount,this.emit=r.emit,this.on=r.on,this.once=r.once,this.addListener=r.addListener,this.off=r.off,this.removeListener=r.removeListener,this.collections=e,this.abilitiesMap=new Hn(s.abilities),this.initOptions=s,this.initPromise=this.init()}_events;_eventsCount;emit;on;once;addListener;off;removeListener;initOptions;collections;abilitiesMap;collection;roles;sessions;orgs;avatars;isInited=!1;byEmail=new Map;bySessionId=new Map;sorted=[];isSortRequired=!1;load(e){new Ye(this,e)}sort(){this.isSortRequired=!1,this.sorted=[...this.values()].sort((e,s)=>e.name.last>s.name.last?1:e.name.last<s.name.last?-1:0)}sortDebounced=N(()=>this.sort(),250);update(e){if(e)for(let s of this.values())s.updateRoles();for(let s of this.values())s.updatePermissions();this.isSortRequired&&this.sort()}updateDebounced=N(()=>this.update(),250);preinit=async()=>{let{indexes:e,schema:s,initialRoot:r}=this.initOptions;s&&(s.required&&F(s.required,ke.required),s.properties&&C(s,Object.keys(ke.properties)));let i={...ke,...s,required:[...ke.required,...s?.required??[]],properties:{...ke.properties,...s?.properties}};this.collection=await this.collections.ensure("users",{jsonSchema:i}),this.collection.ensureIndexes([...io,...e??[]]),await this.collection.countDocuments({roles:"root"})||await this.new({email:process.env.INSITE_ROOT_EMAIL??"insite@root.email",password:process.env.INSITE_ROOT_PASSWORD??"inSiteRootPassword",roles:["root"],name:{first:"Root"},org:null,job:"Root",...r&&C(r,["roles","org"])});for(let n of await this.collection.find().toArray())this.load(n);delete this.preinit};initPromise;init=async()=>{this.isInited=!0;let{roles:e,orgs:s,sessions:r}=this.initOptions;return this.roles=new Jn(this,e),this.orgs=new Xn(this,s),this.sessions=new eo(this,r),this.avatars=new so(this),await this.roles.init(),await this.orgs.preinit(),await this.preinit(),await this.orgs.init(),await this.avatars.init(),this.update(!0),this.collection.changeListeners.add(i=>{switch(i.operationType){case"insert":new Ye(this,i.fullDocument);break;case"replace":this.get(i.documentKey._id)?.update(i.fullDocument);break;case"update":this.get(i.documentKey._id)?.update(i.updateDescription.updatedFields);break;case"delete":this.get(i.documentKey._id)?.delete()}}),await this.sessions.init(),delete this.initOptions,delete this.init,this};whenReady(){return this.initPromise}async new({email:e,password:s,roles:r,name:i,org:n,job:o,...a}){if(this.byEmail.has(e))throw new Error("User exists");return await this.collection.insertOne({_id:zn(),email:e,password:await Ce.hash(s),roles:this.isInited?this.roles.cleanUpIds(r):r,name:{first:i.first??"",middle:i.middle??"",last:i.last??""},org:n??null,job:o??"",...C(a,["_id"]),createdAt:Date.now()}),!0}async changePassword(e,s){if(!this.has(e))throw new Error("usernotfound");if(!s)throw new Error("emptypasswordisnotallowed");await Promise.all([this.collection.updateOne({_id:e},{$set:{password:await Ce.hash(s)}}),this.sessions.collection.deleteMany({user:e})])}async login(e,s,r){let i=this.byEmail.get(e);if(!i)throw new Error("usernotfound");if(!await Ce.verify(i.password,s))throw new Error("incorrectpassword");if(!i.abilities.login)throw new Error("userisnotabletologin");return this.sessions.new(i,r)}logout(e){return e.delete(),this.sessions.collection.deleteOne({_id:e._id})}sortUsersAndOrgs(e,s){return e instanceof Ye&&s instanceof Ye?e.name.last&&s.name.last?e.name.last>s.name.last?1:e.name.last<s.name.last?-1:0:!e.name.last&&!s.name.last?e.displayLabel>s.displayLabel?1:e.displayLabel<s.displayLabel?-1:0:e.name.last?-1:1:e instanceof ae&&s instanceof ae?e.title>s.title?1:e.title<s.title?-1:0:e instanceof ae?-1:1}sortIds(e){return Oe(e.map(s=>this.get(s)||this.orgs.get(s)).filter(Boolean).sort(this.sortUsersAndOrgs))}replaceMap=new Map;replaceHandlers=new Set;async replace(e){let s=this.replaceMap.get(e)??null;s&&this.replaceMap.delete(e);for(let r of this.replaceHandlers)await r(e,s)}static init(e,s){return new Fr(e,s).whenReady()}};import{UsersServer as po}from"insite-users-server-ws";var Gr=class t{constructor(e){this.initPromise=this.init(e)}mongoClient;db;collections;wss;incomingTransport;subscriptionHandler;usersServer;users;cookie;http;init=async e=>{let{db:s,wss:r,users:i,cookie:n,http:o}=e;if(s&&({client:this.mongoClient,db:this.db,collections:this.collections}=await co(s)),r&&(this.wss=new Qs(r),process.env.NODE_ENV==="development"&&this.wss.on("client-connect",a=>console.info(`\u{1F50C} WebSocket connected with ${a.session?.user.email}`)),this.wss.on("error",a=>console.error("\u{1F50C}\u2757\uFE0F WebSocket Server:",a)),this.wss.on("close",()=>console.error("\u{1F50C}\u2757\uFE0F WebSocket Server closed")),this.incomingTransport=new lo(this.wss),this.subscriptionHandler=new ao(this.wss)),i&&this.collections){let{server:a,...l}=i;a&&this.wss?(this.usersServer=await po.init({...a,users:l,wss:this.wss,collections:this.collections,incomingTransport:this.incomingTransport}),this.users=this.usersServer.users):this.users=await Wr.init(this.collections,l)}if(o){let{static:a=void 0,template:l=void 0,middlewares:c=void 0,...u}=typeof o=="object"?o:{};this.http=new fo(u,[a!==null&&new uo(a??{}),n!==null&&new oo(n?.middleware??{}),l!==null&&new ho(l??{}),...c??[]].filter(Boolean))}if(n!==null&&this.usersServer&&this.http){let{middleware:a,...l}=n??{};this.cookie=new no({...l,usersServer:this.usersServer})}return delete this.init,this};initPromise;whenReady(){return this.initPromise}static init(e){return new t(e).whenReady()}};export{Gr as InSite};
6
12
  //# sourceMappingURL=index.js.map