insite-users-server 2.3.0 → 2.3.3

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.
@@ -3,8 +3,28 @@ import { type Ability, type AbilityParam, type AbilityParamItems, type AbilitySc
3
3
  export declare class AbilitiesMap<AS extends AbilitiesSchema> extends Map<string, AbilitySchema> {
4
4
  #private;
5
5
  constructor(abilitiesSchema: AS);
6
- get(longId: string, parent?: AbilitySchema | null): AbilitySchema | undefined;
7
- getSchema: (longId: string, parent?: AbilitySchema | null) => AbilitySchema | undefined;
6
+ get(longId: string, parent?: AbilitySchema | null): {
7
+ _id: string;
8
+ title?: string | undefined;
9
+ description?: string | undefined;
10
+ params?: readonly AbilityParamSchema[] | undefined;
11
+ isInheritable?: boolean | undefined;
12
+ top?: boolean | undefined;
13
+ level: number;
14
+ longId: string;
15
+ abilities?: AbilitySchema[] | undefined;
16
+ } | undefined;
17
+ getSchema: (longId: string, parent?: AbilitySchema | null) => {
18
+ _id: string;
19
+ title?: string | undefined;
20
+ description?: string | undefined;
21
+ params?: readonly AbilityParamSchema[] | undefined;
22
+ isInheritable?: boolean | undefined;
23
+ top?: boolean | undefined;
24
+ level: number;
25
+ longId: string;
26
+ abilities?: AbilitySchema[] | undefined;
27
+ } | undefined;
8
28
  getParamSchema(longId: string, paramId: string): AbilityParamSchema | undefined;
9
29
  getDefaultParam(longId: string, paramId: string, max?: boolean): AbilityParam | undefined;
10
30
  getDefaultParam(schema: AbilityParamSchema, max?: boolean): AbilityParam;
@@ -15,7 +35,17 @@ export declare class AbilitiesMap<AS extends AbilitiesSchema> extends Map<string
15
35
  getDefaultAbilities(schema: AbilitySchema, max?: boolean): Abilities<AS>;
16
36
  getDefaultAbilities(longIds: string[], max?: boolean): Abilities<AS>;
17
37
  getDefaultAbilities(longId: string, max?: boolean): Abilities<AS>;
18
- getSchemeFor(abilities: GenericAbilities): AbilitySchema[];
38
+ getSchemeFor(abilities: GenericAbilities): {
39
+ _id: string;
40
+ title?: string | undefined;
41
+ description?: string | undefined;
42
+ params?: readonly AbilityParamSchema[] | undefined;
43
+ isInheritable?: boolean | undefined;
44
+ top?: boolean | undefined;
45
+ level: number;
46
+ longId: string;
47
+ abilities?: AbilitySchema[] | undefined;
48
+ }[];
19
49
  getParam(abilities: GenericAbilities, longId: string, paramId: string): AbilityParam | undefined;
20
50
  setParam(abilities: GenericAbilities, longId: string, paramId: string, value: AbilityParam): Abilities<AS>;
21
51
  isParamFits(longId: string, paramId: string, value: AbilityParam, referenceValue?: AbilityParam): boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"Map.d.ts","sourceRoot":"","sources":["../../src/abilities/Map.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACpF,OAAO,EAIN,KAAK,OAAO,EAEZ,KAAK,YAAY,EACjB,KAAK,iBAAiB,EAEtB,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,MAAM,SAAS,CAAC;AAMjB,qBAAa,YAAY,CAAC,EAAE,SAAS,eAAe,CAAE,SAAQ,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC;;gBAC3E,eAAe,EAAE,EAAE;IAmC/B,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,aAAa,GAAG,IAAI;IAcjD,SAAS,WAdG,MAAM,WAAW,aAAa,GAAG,IAAI,+BAc5B;IAErB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;IAI9C,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,OAAO,GAAG,YAAY,GAAG,SAAS;IACzF,eAAe,CAAC,MAAM,EAAE,kBAAkB,EAAE,GAAG,CAAC,EAAE,OAAO,GAAG,YAAY;IAuBxE,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,O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CAAC,EAAE,aAAa,GAAG,IAAI,GAAG,SAAS,CAAC,EAAE,CAAC;IAwCjF,KAAK,CAAC,MAAM,EAAE,gBAAgB,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,CAAC,EAAE,aAAa,GAAG,IAAI,GAAG,SAAS,CAAC,EAAE,CAAC;IA0CvG,UAAU,CAAC,SAAS,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM;IAItD,UAAU,CAAC,MAAM,EAAE,gBAAgB,EAAE,MAAM,EAAE,aAAa,GAAG,SAAS,CAAC,EAAE,CAAC;IAC1E,UAAU,CAAC,MAAM,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,EAAE,CAAC;IAYnE,YAAY,CAAC,MAAM,EAAE,gBAAgB,EAAE,MAAM,EAAE,aAAa,GAAG,SAAS,CAAC,EAAE,CAAC;IAC5E,YAAY,CAAC,MAAM,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,EAAE,CAAC;CAmBrE"}
@@ -1,3 +1,4 @@
1
+ import type { Prettify } from "@nesvet/n";
1
2
  import type { AbilitySchema as OriginalAbilitySchema } from "insite-common";
2
3
  type AbilityParamItem = string;
3
4
  export type AbilityParamItems = AbilityParamItem[];
@@ -9,11 +10,11 @@ export type AbilityBoolean = true;
9
10
  export type Ability = AbilityBoolean | {
10
11
  [key: string]: Ability | AbilityParam;
11
12
  };
12
- export type AbilitySchema = Omit<OriginalAbilitySchema, "abilities"> & {
13
+ export type AbilitySchema = Prettify<Omit<OriginalAbilitySchema, "abilities"> & {
13
14
  level: number;
14
15
  longId: string;
15
16
  abilities?: AbilitySchema[];
16
- };
17
+ }>;
17
18
  export type GenericAbilities = Record<string, Ability>;
18
19
  export declare function isAbilityObject(value: Ability): value is AbilityObject;
19
20
  export declare function isAbilityParamNumber(value: AbilityParam): value is AbilityParamNumber;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["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of e)r.includes(i)||(r.push(i),t++);return t}function E(r,e,t){if(r&&e){if(e.includes(".")){let i=e.split("."),s=r;for(let o=0;o<i.length-1;o++){let n=i[o],a=s[n];s=a&&typeof a=="object"?a:s[n]={}}return s[i.at(-1)]=t}return r[e]=t}return null}function pe(r,...e){for(let t of e)for(let i in t)Object.hasOwn(t,i)&&E(r,i,t[i]);return r}function S(){}var U=new WeakMap,x=class r extends Promise{constructor(e,t){let i,s;if(super((o,n)=>{i=o,s=n}),U.set(this,{resolve:i,reject:s}),t?.signal)if(t.signal.aborted)this.reject(new DOMException("Aborted","AbortError"));else{let o=()=>this.reject(new DOMException("Aborted","AbortError"));t.signal.addEventListener("abort",o),this.finally(()=>t.signal?.removeEventListener("abort",o))}if(typeof t?.timeout=="number"&&Number.isFinite(t.timeout)){let o=setTimeout(()=>this.reject(new DOMException("Timeout exceeded","TimeoutError")),t.timeout);this.finally(()=>clearTimeout(o))}e?.(this.resolve,this.reject)}isPending=!0;isFulfilled=!1;isRejected=!1;state="pending";result;resolve=e=>{if(this.isPending){this.isPending=!1,this.isFulfilled=!0,this.state="fulfilled",this.result=e;let t=U.get(this);t&&(t.resolve.call(this,e),U.delete(this))}};reject=e=>{if(this.isPending){this.isPending=!1,this.isRejected=!0,this.state="rejected",this.result=e;let t=U.get(this);t&&(t.reject.call(this,e),U.delete(this))}};static resolved(e){return new r(t=>t(e))}static rejected(e){return new r((t,i)=>i(e))}};function J(r,e=0,t={}){let{leading:i=!1,trailing:s=!0}=t,{maxWait:o=1/0}=t,n,a,l,d,y,A,p,w,ce=async()=>{let g=Date.now();g>=l?(n=void 0,l=void 0,clearTimeout(a),a=void 0,typeof p=="function"&&await p(),b.resolve(w),A=i):(clearTimeout(n),n=setTimeout(ce,l-g))},K=Number.isFinite(o)?()=>{p===v&&(p=!1),v(),a=setTimeout(K,o)}:null;async function v(){try{return w=await r.apply(d,y),w}catch(g){throw b.reject(g),g}}i&&typeof i=="boolean"&&(i=v),A=i,s&&typeof s=="boolean"&&(s=v),p=s;let b=Object.assign(function(...g){return y=g,d=this,l=Date.now()+e,p=s,b.promise.isPending||(b.promise=new x((Oe,Pe)=>{b.resolve=Oe,b.reject=Pe,typeof A=="function"&&(A(),A=!1,p===v&&(p=!1)),n||(n=setTimeout(ce,e),K&&(a=setTimeout(K,o)))})),b.promise},{callback:r,promise:x.resolved(void 0),resolve:S,reject:S,run:v,clear:async g=>{clearTimeout(n),n=void 0,clearTimeout(a),a=void 0,b.resolve(g?await v():w)}});return b}J.noop=Object.assign(()=>{},{callback:S,promise:x.resolved(void 0),resolve:S,reject:S,run:S,clear:S});function ue(r,e){if(r&&e){if(e.includes(".")){let t=e.split("."),i=r;for(let o=0;o<t.length-1;o++){let n=t[o],a=i[n];if(a&&typeof a=="object")i=a;else return!1}let s=t.at(-1);return s in i&&delete i[s]}return e in r&&delete r[e]}return!1}function u(r,e){if(r){for(let t of e)delete r[t];return r}return null}function k(r){for(let e in r)delete r[e];return r}var q=class extends Array{constructor(){super(),Object.freeze(this)}push(){return 0}unshift(){return 0}splice(){return[]}};var _=class extends Set{constructor(){super()}add(){return this}};var m=class extends Error{constructor(e,t=null,i){typeof e=="object"?(i=e,e=i.message,delete i.message,t=null):t&&typeof t=="object"&&(i=t,t=null),super(e),this.tag=t,i&&Object.assign(this,i)}name="Err-or";tag};function H(r,e,t=!1){let i=[];if(t)for(let s of e){let o=r.get(s);o!==void 0&&i.push(o)}else for(let s of e)i.push(r.get(s));return i}function N(r,e){if(e){if(e.includes(".")){let t=r;for(let i of e.split("."))if(t=t?.[i],t===void 0)break;return t}return r[e]}return r}function me(r,e){for(let t of e)if(r.has(t))return!0;return!1}function fe(r,e,t,i,s=!0){return Array.isArray(r)&&(r=r.length),typeof i!="string"&&(s=i??!0,i=t),(s?`${r}\xA0`:"")+fe.raw(r,e,t,i)}fe.raw=(r,e,t,i=t)=>{r=Math.abs(r);let s=r%10,o=r%100;return s===1&&o!==11?e:s>=2&&s<=4&&!(o>=12&&o<=15)?t:i};function G(...r){let e=[];if(r.length){let[t,...i]=r;e:for(let s of t){for(let o of i)if(o instanceof Set?!o.has(s):!o.includes(s))continue e;e.push(s)}}return e}function he(r,e){let t={};for(let i of e)i in r&&(t[i]=r[i]);return t}function be(r,e){return r.delete(e),r.add(e),r}function f(r,e){let t,i=0;for(let s of e)for(;(t=r.indexOf(s))>-1;)r.splice(t,1),i++;return i}function ge(r,e){let t=r.indexOf(e);return t>-1?(r.splice(t,1),!0):!1}function ye(r,e){for(let t of[...r].sort(e))r.delete(t),r.add(t);return r}function Ae(...r){return[...new Set(r.flat())]}function C(r,e){return r.filter(t=>!e.includes(t))}var Z=class extends m{constructor(e,t){typeof e=="object"&&(t=e,e=void 0),super("User lacks ability","lacksability",{...e&&{ability:e},...t})}name="AbilityError"};function X(r){return typeof r=="object"}function Y(r){return typeof r=="number"}function Q(r){return Array.isArray(r)}var Se=new Map,W=class extends Map{constructor(e){super();for(let t of e)delete t.top,this.#e.push(t);(function t(i,s,o){for(let n of i){if(Se.set(n,s),n.level=o,!s||n.top){if(n.longId=n._id,this.has(n._id))throw new Error(`Top-level ability duplicate: ${n._id}`);this.set(n._id,n)}else n.longId=s?`${s.longId}.${n._id}`:n._id;n.abilities&&t.call(this,n.abilities,n,o+1)}}).call(this,e,null,0)}#e=[];get(e,t){let i=e.split("."),s=t??super.get(i.shift());if(s&&i.length){for(let o of i)if(s=s?.abilities?.find(({_id:n,top:a})=>!a&&n===o),!s)break}return s}getSchema=this.get;getParamSchema(e,t){return this.get(e)?.params?.find(({_id:i})=>i===t)}getDefaultParam(e,t,i){(t===void 0||typeof t=="boolean")&&(i=t);let s=typeof e=="string"?this.getParamSchema(e,t):e;if(s)switch(s.type){case"number":return i?s.max??1/0:s.min??0;case"items":return i?s.items.map(({_id:o})=>o):[]}}getDefaultAbility(e,t=!e){if(typeof e=="string"&&(e=this.get(e)),e){if(e.abilities||e.params){let i={};if(e.params)for(let s of e.params)i[s._id]=this.getDefaultParam(s,t);if(t&&e.abilities)for(let s of e.abilities)s.top||(i[s._id]=this.getDefaultAbility(s,t));return i}return!0}}getDefaultAbilities(e,t=!e){let i=(e?(Array.isArray(e)?e:[e]).map(o=>typeof o=="string"?this.get(o):o).filter(Boolean):[...this.values()]).sort((o,n)=>o.level-n.level),s=new Map;for(let o of i)(function n(a){let l=Se.get(a);l&&(n(l),s.has(l)||s.set(l,!1))})(o),t?function n(a){if(s.has(a)||s.set(a,!0),a.abilities)for(let l of a.abilities)l.top&&n(l)}(o):s.has(o)||s.set(o,!1);return pe({},Object.fromEntries([...s].map(([o,n])=>[o.longId,this.getDefaultAbility(o,n)])))}getSchemeFor(e){return e=this.adjust(structuredClone(e)),function t(i,s){for(let o=0;o<i.length;o++){let n=i[o],a=n.top?e[n._id]:s[n._id];if(a){if(n.params)for(let l of n.params){let d=a[l._id];switch(l.type){case"number":l.max=d;break;case"items":l.items=l.items.filter(({_id:y})=>d.includes(y))}}n.abilities&&(t(n.abilities,a),n.abilities.length||delete n.abilities)}else i.splice(o--,1)}return i}(structuredClone(this.#e),e)}getParam(e,t,i){if(this.getParamSchema(t,i)){let s=N(e,`${t}.${i}`);return this.isParamFits(t,i,s)?s:this.getDefaultParam(t,i)}}setParam(e,t,i,s){let o=this.getParamSchema(t,i);if(!o)throw new Error(`No such ability param: ${t}.${i}`);return E(e,`${t}.${i}`,this.adjustParam(o,s)),e}isParamFits(e,t,i,s){if(i!==void 0){let o=this.getParamSchema(e,t);if(o)switch(o.type){case"number":return Y(i)&&(o.min===void 0||i>=o.min)&&(s===void 0?o.max===void 0||i<=o.max:i<=s);case"items":return Q(i)&&i.length===new Set(i).size&&(s===void 0?i.every(n=>o.items.find(({_id:a})=>a===n)):i.every(n=>s.includes(n)))}}return!1}adjustParam(e,t){switch(e.type){case"number":return Y(t)?Math.max(Math.min(t,e.max??1/0),e.min??0):e.min??0;default:return Q(t)?G(e.items.map(i=>i._id),t):[]}}adjust(e,t){let i={};for(let[s,o]of Object.entries(e)){let n=this.get(s,t);if(n)if(n.params||n.abilities){let a={};if(n.params)if(X(o))for(let l of n.params)a[l._id]=this.adjustParam(l,o[l._id]);else for(let l of n.params)a[l._id]=this.getDefaultParam(l);n.abilities&&X(o)&&Object.assign(a,this.adjust(he(o,n.abilities.filter(l=>!l.top).map(l=>l._id)),n)),i[s]=a}else i[s]=!0}return Object.assign(k(e),i)}merge(e,t,i){i||(this.adjust(e),t=this.adjust(structuredClone(t)));for(let[s,o]of Object.entries(t)){let n=this.get(s,i);if(n&&n.isInheritable!==!1)if(s in e&&(n.params||n.abilities)){let a=e[s],l=o;if(n.params){for(let d of n.params)if(d.isInheritable!==!1)switch(d.type){case"number":a[d._id]=Math.max(a[d._id],l[d._id]);break;case"items":de(a[d._id],...l[d._id])}}n.abilities&&this.merge(a,l,n)}else e[s]=o}return e}hasAbility(e,t){return!!N(e,t)}setAbility(e,t){let i=typeof t=="string"?this.get(t):t;if(!i)throw new Error(`No such ability: ${t}`);return this.merge(e,this.getDefaultAbilities(i)),e}unsetAbility(e,t){let i=typeof t=="string"?this.get(t):t;if(!i)throw new Error(`No such ability: ${t}`);return function s(o){if(ue(e,o.longId),o.abilities)for(let n of o.abilities)s(n)}(i),e}};var V=class extends m{constructor(e,t){super(`User lacks role${Array.isArray(e)?"s":""}`,"lacksroles",{roles:Array.isArray(e)?e:[e],...t})}name="RolesError"};var ee=new WeakMap,D=class{constructor(e,t){this.#e=e,this._id=t._id,e.set(this._id,this),this.update(t)}#e;_id;ownInvolveIds;ownAbilities;title="";displayTitle="";_o=0;ownInvolves=[];involves=new Set;abilities={};inheritedAbilities={};update({_id:e,involves:t,abilities:i,title:s,...o}){if(Object.assign(this,o),t&&(this.ownInvolveIds=t),i&&(this.ownAbilities=i),s!==void 0&&(this.title=s,this.displayTitle=s||this._id),t||i){let n=[this.ownInvolveIds.join(","),JSON.stringify(this.ownAbilities)].join(`
2
- `);n!==ee.get(this)&&(ee.set(this,n),this.#e.users.isInited&&this.#e.update())}}delete(){this.#e.delete(this._id),ee.delete(this),this.#e.update()}};var c={_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}|[0-9a-f]{24}~[A-Za-z0-9_-]{43})$/,role:/^[\d_a-z-]{1,64}$/,ip:/^(?:\d{1,3}\.){3}\d{1,3}$/};var I={required:["_id","involves","abilities","title","description","meta","createdAt"],properties:{_id:{bsonType:"string",pattern:c.role.source,not:{enum:["root"]}},involves:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c.role.source,not:{enum:["root"]}},additionalItems:!1},abilities:{bsonType:"object"},title:{bsonType:"string",maxLength:256},description:{bsonType:"string",maxLength:10240},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var _e=[[{involves:1}]];function xe(){throw new Error("Direct usage of roles collection.deleteOne or .deleteMany is forbidden. Use roles.deleteRole instead.")}var L=class extends Map{constructor(e,t={}){super();let{root:i,...s}=t;this.users=e,this.collections=e.collections,this.abilities=e.abilities,this.root=new D(this,{...i,_id:"root",involves:[],abilities:this.abilities.getDefaultAbilities(),title:"Root",description:"Root",meta:{},createdAt:Date.now()}),this.initOptions=s}users;collections;collection;abilities;root;initOptions;async init(){if(!this.users.isInited){let{schema:e,indexes:t,collection:i}=this.initOptions;e&&(e.required&&f(e.required,I.required),e.properties&&u(e,Object.keys(I.properties)));let s={...I,...e,required:[...I.required,...e?.required??[]],properties:{...I.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("roles",{...i,schema:s}),{deleteOne:xe,deleteMany:xe}),await this.collection.ensureIndexes([..._e,...t??[]]),await this.#e();for await(let o of this.collection.find())this.abilities.adjust(o.abilities)&&await this.collection.updateOne({_id:o._id},{$set:{abilities:o.abilities}}),this.load(o);this.update(),this.collection.onChange(this.#t),delete this.initOptions}}async#e(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}#t=e=>{switch(e.operationType){case"insert":{new D(this,e.fullDocument);break}case"replace":this.get(e.documentKey._id)?.update(e.fullDocument);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields);break;case"delete":this.get(e.documentKey._id)?.delete()}};load(e){new D(this,e)}resolve(e,t){t=[e,...t];for(let i of e.ownInvolveIds){let s=this.get(i);if(s){for(let o of t)be(o.involves,s),this.abilities.merge(o.inheritedAbilities,s.abilities);s!==e&&this.resolve(s,t)}}}sorted=[];#i(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 s of e)s!==this.root&&!e.some(o=>o.ownInvolveIds.includes(s._id))&&this.root.ownInvolveIds.push(s._id),s.involves.clear(),s.abilities=structuredClone(s.ownAbilities),s.inheritedAbilities={};this.root.involves.add(this.root),this.resolve(this.root,[]);for(let s of e)s.ownInvolves=H(this,s.ownInvolveIds,!0).sort(this.#i).reverse();let t=[this.root];for(let s=0;s<t.length;s++){let o=t[s];for(let n of o.ownInvolves){let a=t.indexOf(n);~a&&(t.splice(a,1),s--),t.splice(s+1,0,n)}}let i=0;for(let s of t)this.abilities.merge(s.abilities,s.inheritedAbilities),s._o=i++;this.sorted=t,this.users.isInited&&this.users.update(!0)}async create({_id:e,involves:t,title:i,description:s,...o}){return await this.collection.insertOne({_id:e,involves:t||[],abilities:{},title:i??"",description:s??"",meta:{},...u(o,["abilities"]),createdAt:Date.now()}),e}async updateRole(e,t){let i=this.get(e);if(!i)return!1;if(t.involves){f(t.involves,[e]);for(let s of t.involves)this.get(s)?.involves.has(i)&&f(t.involves,[s]);t.involves=this.cleanUpIds(t.involves)}return await this.collection.updateOne({_id:e},{$set:t}),!0}deleteRole(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=G(this.sorted,H(this,e,!0)),i=[];for(let s of t)t.every(o=>o===s||!o.involves.has(s))&&i.push(s._id);return i}async setAbility(e,t,i){let s=this.get(e);return s?(await this.collection.updateOne({_id:e},{$set:{abilities:i?this.abilities.setAbility(s.ownAbilities,t):this.abilities.unsetAbility(s.ownAbilities,t)}}),!0):!1}async setAbilityParam(e,t,i,s){let o=this.get(e);return o?(await this.collection.updateOne({_id:e},{$set:{abilities:this.abilities.setParam(o.ownAbilities,t,i,s)}}),!0):!1}};var te=class extends m{constructor(e){super("Unauthorized","unauthorized",e)}name="UnauthorizedError"},ie=class extends m{constructor(e,t,i){switch(arguments.length){case 1:i=e,e=void 0;break;case 2:i=t,t=void 0}super("Insubordination attempt","subordination",{...e&&{type:e},...t&&{ids:Array.isArray(t)?t:[t]},...i})}name="SubordinationError"},se=class extends m{constructor(e){super("Insufficient permissions","permissions",e)}name="PermissionError"};import*as M from"argon2";import Ce from"eventemitter3";import{newObjectIdString as Me}from"insite-db";import{newObjectIdString as De}from"insite-db";var oe=new WeakMap,h=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:i,...s}){if(Object.assign(this,s),t!==void 0&&(this.title=t,this.initials=t?.[0]?.toUpperCase()??"",this.displayLabel=t),i){this.ownerIds=i;let o=this.ownerIds.join(",");o!==oe.get(this)&&(oe.set(this,o),this.orgs.users.isInited&&this.orgs.update())}}async delete(){this.orgs.delete(this._id),oe.delete(this),await this.orgs.replace(this._id),this.orgs.update()}};var R={required:["_id","title","note","owners","meta","createdAt"],properties:{_id:{bsonType:"string",pattern:c._id.source},title:{bsonType:"string",maxLength:512},note:{bsonType:"string",maxLength:131072},owners:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c._id.source},additionalItems:!1},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var Ie=[[{owners:1}]];function we(){throw new Error("Direct usage of orgs collection.deleteOne or .deleteMany is forbidden. Use orgs.deleteOrg instead.")}var B=class extends Map{constructor(e,t={}){super(),this.users=e,this.collections=e.collections,this.preinitOptions=t}users;collections;preinitOptions;collection;null;#e=!1;async preinit(){if(!this.#e){this.#e=!0;let{schema:e,indexes:t,null:i,collection:s}=this.preinitOptions;e&&(e.required&&f(e.required,R.required),e.properties&&u(e,Object.keys(R.properties)));let o={...R,...e,required:[...R.required,...e?.required??[]],properties:{...R.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("orgs",{...s,schema:o}),{deleteOne:we,deleteMany:we}),await this.collection.ensureIndexes([...Ie,...t??[]]),this.null=Object.assign(new h(this,{...i,_id:"",title:"",note:"",owners:[],meta:{},createdAt:Date.now()}),{_id:null,ownerIds:new q,ownerOrgs:new _,ownerUsers:new _,slaveOrgs:new _}),await this.#t();for await(let n of this.collection.find())this.load(n);delete this.preinitOptions}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}init(){this.users.isInited||(this.update(),this.collection.onChange(this.#i))}#i=e=>{switch(e.operationType){case"insert":{new h(this,e.fullDocument);break}case"replace":this.get(e.documentKey._id)?.update(e.fullDocument);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields);break;case"delete":this.get(e.documentKey._id)?.delete()}};load(e){new h(this,e)}#o(e,t){t=[e,...t];for(let i of e.ownerOrgs){this.#o(i,t);for(let s of t)i.slaveOrgs.add(s)}}sorted=[];update(){let e=[...this.values()],t=[];for(let i of e){i.ownerOrgs.clear(),i.ownerUsers.clear(),i.slaveOrgs.clear();for(let s of i.ownerIds){let o=this.get(s);if(o)i.ownerOrgs.add(o);else{let n=this.users.get(s);n&&i.ownerUsers.add(n)}}!i.ownerOrgs.size&&i._id&&t.push(i)}for(let i of e)e.some(s=>s.ownerOrgs.has(i))||this.#o(i,[]);t.sort(this.#s);for(let i of e)ye(i.slaveOrgs,this.#s);for(let i=0;i<t.length;i++){let s=t[i];for(let o of[...s.slaveOrgs].reverse())if(o.ownerOrgs.has(s)){let n=t.indexOf(o);~n&&(t.splice(n,1),i--),t.splice(i+1,0,o)}}for(let i=0,{length:s}=t;i<s;)t[i]._o=i++;this.sorted=t,this.users.isInited&&this.users.update()}#s(e,t){return t.slaveOrgs.size-e.slaveOrgs.size||(e.title>t.title?1:e.title<t.title?-1:0)}async create({title:e,note:t,...i}){let s=De();return await this.collection.insertOne({_id:s,title:e??"",note:t??"",meta:{},...u(i,["_id"]),createdAt:Date.now()}),s}async updateOrg(e,t,i){let s=this.get(e);return s?(t.owners&&(t.owners=this.users.sortIds(Ae(i?C(s.ownerIds,i.slaveIds):[],C(t.owners,[e,...O(s.slaveOrgs)])))),await this.collection.updateOne({_id:e},{$set:t}),!0):!1}deleteOrg(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 i of this.replaceHandlers)await i(e,t)}};import{randomBytes as Re}from"node:crypto";import{newObjectIdString as Te}from"insite-db";var T={required:["_id","user","remoteAddress","isOnline","meta","createdAt","prolongedAt","expiresAt"],properties:{_id:{bsonType:"string",pattern:c.sessionId.source},user:{bsonType:"string",pattern:c._id.source},userAgent:{bsonType:"string",maxLength:4096},remoteAddress:{bsonType:"string",pattern:c.ip.source},isOnline:{bsonType:"bool"},meta:{bsonType:"object"},createdAt:{bsonType:"number"},prolongedAt:{bsonType:"number"},expiresAt:{bsonType:"date"}}};var j=class{constructor(e,t){let i=e.users.get(t.user);i?(this.#e=e,this._id=t._id,this.#e.set(this._id,this),this.user=i,this.user.sessions.add(this),this.#e.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;#e;update({_id:e,user:t,isOnline:i,...s}){i!==void 0&&this.isOnline!==i&&(this.isOnline=i,this.#e.users.isInited&&this.user.isOnline!==this.isOnline&&this.user.updateIsOnlineDebounced()),Object.assign(this,s)}prolong({_id:e,user:t,...i}){let s=Date.now();return i.prolongedAt=s,i.expiresAt=new Date(s+this.#e.collection.expireAfterSeconds*1e3),this.update(i),this.#e.collection.updateOne({_id:this._id},{$set:i})}async online(){if(!this.isOnline){let e={isOnline:!0};this.update(e),await this.#e.collection.updateOne({_id:this._id},{$set:e})}}async offline(){if(this.isOnline){let e={isOnline:!1};this.update(e),await this.#e.collection.updateOne({_id:this._id},{$set:e})}}delete(){this.#e.delete(this._id),this.user.sessions.delete(this),this.#e.users.bySessionId.delete(this._id),this.#e.users.emit("session-delete",this),this.isOnline&&this.user.updateIsOnline()}};var re=3600*24*7,je=[[{user:1}],[{expiresAt:1},{expireAfterSeconds:re}]],F=class extends Map{constructor(e,t={}){super(),this.users=e,this.collections=e.collections,this.initOptions=t}users;collections;initOptions;collection;async init(){if(!this.users.isInited){let{schema:e,indexes:t,collection:i}=this.initOptions;e&&(e.required&&f(e.required,T.required),e.properties&&u(e,Object.keys(T.properties)));let s={...T,...e,required:[...T.required,...e?.required??[]],properties:{...T.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("sessions",{...i,schema:s}),{expireAfterSeconds:re}),await this.collection.ensureIndexes([...je,...t??[]]),await this.#e();for await(let o of this.collection.find())this.load(o);this.collection.onChange(this.#t),delete this.initOptions}}async#e(){await this.collection.bulkWrite([{updateMany:{filter:{meta:{$exists:!1}},update:{$set:{meta:{}}}}},{updateMany:{filter:{isOnline:!0},update:{$set:{isOnline:!1}}}}])}#t=e=>{switch(e.operationType){case"insert":this.has(e.documentKey._id)||new j(this,e.fullDocument),this.users.get(e.fullDocument.user)?.trimSessions();break;case"replace":this.get(e.documentKey._id)?.update(e.fullDocument);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields);break;case"delete":this.get(e.documentKey._id)?.delete()}};uid(){return`${Te()}~${Re(32).toString("base64url")}`}load(e){new j(this,e)}async create(e,t){let i=Date.now(),s={userAgent:"",remoteAddress:"127.0.0.1",isOnline:!0,...t,_id:this.uid(),user:e._id,meta:{},createdAt:i,prolongedAt:i,expiresAt:new Date(i+re*1e3)},o=new j(this,s);return await this.collection.insertOne(s),o}async destroySession(e){let{deletedCount:t}=await this.collection.deleteOne({_id:e});return!!t}};import{Binary as $e}from"insite-db";var ve={required:["_id","type","size","ts","data","meta"],properties:{_id:{bsonType:"string",pattern:c._id.source},type:{bsonType:"string",maxLength:256},size:{bsonType:"number"},ts:{bsonType:"string",maxLength:10},data:{bsonType:"binData"},meta:{bsonType:"object"}},additionalProperties:!1};var z=class{constructor(e,t={}){this.users=e,this.collections=e.collections,this.initOptions=t}TYPES_ACCEPTED=["image/webp"];MAX_SIZE=1024*512;users;collections;collection;initOptions;async init(){if(!this.users.isInited){let{collection:e}=this.initOptions;this.collection=await this.collections.ensure("users.avatars",{...e,schema:ve}),await this.#e()}}async#e(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}async save(e,t,i){let s=$e.createFromBase64(i.slice(i.indexOf(","))),o=Date.now().toString(36);await Promise.all([this.collection.replaceOne({_id:e},{type:t,size:s.length(),ts:o,data:s,meta:{}},{upsert:!0}),this.users.collection.updateOne({_id:e},{$set:{avatar:o}})])}async deleteAvatar(e){let[{deletedCount:t}]=await Promise.all([this.collection.deleteOne({_id:e}),this.users.collection.updateOne({_id:e},{$set:{avatar:null}})]);return!!t}};var $={required:["_id","email","password","roles","name","org","job","meta","createdAt"],properties:{_id:{bsonType:"string",pattern:c._id.source},email:{bsonType:"string",pattern:c.email.source},password:{bsonType:"string",pattern:c.argon2.source},roles:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c.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:c._id.source},{bsonType:"null"}]},job:{bsonType:"string",maxLength:512},avatar:{oneOf:[{bsonType:"string",maxLength:10},{bsonType:"null"}]},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var ne=new WeakMap,ae=new WeakMap,Ue=process.env.INSITE_STATIC_URL??"http://localhost:8080",P=class{constructor(e,t){this.#e=e,this._id=t._id,e.set(this._id,this),e.isSortRequired=!0,this.update(t),e.isInited&&e.emit("user-create",this)}_id;email;name={first:"",middle:"",last:""};initials="";displayLabel="";org;job="";avatar=null;avatarUrl=null;#e;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:i,roles:s,org:o,avatar:n,...a}){Object.assign(this,a);let l;i&&this.email!==i&&(this.#e.byEmail.delete(this.email),this.email=i,this.#e.byEmail.set(i,this),l=!0);let d,y;t&&(this.name.first!==t.first||this.name.middle!==t.middle||this.name.last!==t.last)&&(y=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(),d=!0),(l||d)&&(this.displayLabel=`${this.name.first} ${this.name.last}`.trim()||this.name.middle||this.email);let A;if(s){this.ownRoleIds=s;let w=this.ownRoleIds.join(",");w!==ne.get(this)&&(ne.set(this,w),this.#e.isInited&&(this.updateRoles(),A=!0))}let p;o!==void 0&&this.org?._id!==o&&(this.org?.users.delete(this),this.org=o&&this.#e.orgs.get(o)||this.#e.orgs.null,this.org.users.add(this),p=!0),n!==void 0&&this.avatar!==n&&(this.avatar=n,this.avatarUrl=n&&`${Ue}/avatars/${this._id}-${n}.webp`),this.#e.isInited&&(A||p?(this.updatePermissions(),y&&(this.#e.isSortRequired=!0),this.#e.update()):y&&this.#e.sort())}updateRoles(){this.ownRoles=[],this.roles.clear(),this.slaveRoles.clear(),k(this.abilities);for(let e of this.ownRoleIds){let t=this.#e.roles.get(e);if(t){this.ownRoles.push(t),this.roles.add(t);for(let i of t.involves)this.roles.add(i),this.slaveRoles.add(i);this.slaveRoleIds=O(this.slaveRoles),this.#e.abilities.merge(this.abilities,t.abilities)}}this.roles.has(this.#e.roles.root)&&(this.isRoot=!0),this.trimSessions()}updatePermissions(){this.slaveOrgs.clear(),this.slaveUsers.clear(),this.slaves.clear();let e=new Set;for(let s of this.#e.orgs.sorted)if((s.ownerUsers.has(this)||this.isRoot)&&!this.slaveOrgs.has(s)){this.slaveOrgs.add(s),this.slaves.add(s),e.add(s._id);for(let o of s.slaveOrgs)this.slaveOrgs.add(o),this.slaves.add(o),e.add(o._id)}for(let s of new Set([this.org,...this.slaveOrgs,this.#e.orgs.null]))for(let o of s.users)o!==this&&(me(this.slaveRoles,o.ownRoles)||!o.ownRoles.length)&&(this.slaveUsers.add(o),this.slaves.add(o),e.add(o._id));this.slaveIds=[...e];let t=[];if(this.org._id){t.push(this.org._id);for(let s of this.org.slaveOrgs)this.slaveOrgs.has(s)||t.push(s._id)}this.permissiveIds=[...t,this._id,...e];let i=[this.permissiveIds.join(","),this.ownRoleIds.join(","),JSON.stringify(this.abilities),this.slaveRoleIds.join(",")].join(`
3
- `);i!==ae.get(this)&&(ae.set(this,i),this.#e.isInited&&this.#e.emit("user-permissions-change",this))}trimSessions(){let e=this.abilities.login?.sessionsLimit??0;if(this.sessions.size>e)return this.#e.sessions.collection.deleteMany({_id:{$in:O([...this.sessions].sort((t,i)=>t.expiresAt.valueOf()-i.expiresAt.valueOf()).slice(0,this.sessions.size-e))}})}updateIsOnline(){let e=!1;for(let t of this.sessions)if(t.isOnline){e=!0;break}this.isOnline!==e&&(this.isOnline=e,this.#e.emit("user-is-online",this))}updateIsOnlineDebounced=J(()=>this.updateIsOnline(),500);async delete(){this.org.users.delete(this),this.#e.delete(this._id),this.#e.byEmail.delete(this.email),ge(this.#e.sorted,this),ne.delete(this),ae.delete(this),await this.#e.replace(this._id),this.#e.update()}};var Ee=[[{email:1},{unique:!0}],[{org:1}]],le=class r extends Map{constructor(e,t){super();let i=new Ce;this.#e=i,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=e,this.abilities=new W(t.abilities),this.initOptions=t,this.init()}#e;_events;_eventsCount;emit;on(e,t,i){return this.#e.on(e,t,i),this}once;addListener;off;removeListener;initOptions;collections;abilities;collection;roles;sessions;orgs;avatars;byEmail=new Map;bySessionId=new Map;sorted=[];isSortRequired=!1;#t=!1;async preinit(){if(!this.#t){this.#t=!0;let{indexes:e,schema:t,initialRoot:i,collection:s}=this.initOptions;t&&(t.required&&f(t.required,$.required),t.properties&&u(t,Object.keys($.properties)));let o={...$,...t,required:[...$.required,...t?.required??[]],properties:{...$.properties,...t?.properties}};this.collection=await this.collections.ensure("users",{...s,schema:o}),await this.collection.ensureIndexes([...Ee,...e??[]]),await this.collection.countDocuments({roles:"root"})||await this.create({email:process.env.INSITE_ROOT_EMAIL??"insite@root.email",password:process.env.INSITE_ROOT_PASSWORD??"inSiteRootPassword",name:{first:"Root"},job:"Root",...i,roles:["root"],org:null,meta:{}}),await this.#i();for await(let n of this.collection.find())this.load(n)}}async#i(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}isInited=!1;async init(){if(!this.isInited){let{roles:e,orgs:t,sessions:i,avatars:s,collection:{quiet:o}={}}=this.initOptions;this.roles=new L(this,{...e,collection:{quiet:o,...e?.collection}}),this.orgs=new B(this,{...t,collection:{quiet:o,...t?.collection}}),this.sessions=new F(this,{...i,collection:{quiet:o,...i?.collection}}),this.avatars=new z(this,{...s,collection:{quiet:o,...s?.collection}}),await this.roles.init(),await this.orgs.preinit(),await this.preinit(),this.orgs.init(),await this.avatars.init(),this.update(!0),this.collection.onChange(this.#o),await this.sessions.init(),delete this.initOptions,this.isInited=!0,this.#s.resolve(this)}}#o=e=>{switch(e.operationType){case"insert":new P(this,e.fullDocument);break;case"replace":this.get(e.documentKey._id)?.update(e.fullDocument);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields);break;case"delete":this.get(e.documentKey._id)?.delete()}};load(e){new P(this,e)}sort(){this.isSortRequired=!1,this.sorted=[...this.values()].sort((e,t)=>e.name.last>t.name.last?1:e.name.last<t.name.last?-1:0)}update(e){if(e)for(let t of this.values())t.updateRoles();for(let t of this.values())t.updatePermissions();this.isSortRequired&&this.sort()}#s=new x;whenReady(){return this.#s}async create({email:e,password:t,roles:i,name:s,org:o,job:n,...a}){if(this.byEmail.has(e))throw new Error("User exists");let l=Me();return await this.collection.insertOne({_id:l,email:e,password:await M.hash(t),roles:this.isInited?this.roles.cleanUpIds(i):i,name:{first:s.first??"",middle:s.middle??"",last:s.last??""},org:o??null,job:n??"",meta:{},...u(a,["_id"]),createdAt:Date.now()}),l}async updateUser(e,t,i){let s=this.get(e);return s?(t.roles&&(t.roles=s.isRoot?["root"]:this.roles.cleanUpIds(i?C(s.ownRoleIds,i.slaveRoleIds).concat(t.roles):t.roles)),await this.collection.updateOne({_id:e},{$set:t}),!0):!1}async changePassword(e,t){if(!this.has(e))throw new Error("usernotfound");if(!t)throw new Error("emptypasswordisnotallowed");await Promise.all([this.collection.updateOne({_id:e},{$set:{password:await M.hash(t)}}),this.sessions.collection.deleteMany({user:e})])}async login(e,t,i){let s=this.byEmail.get(e);if(!s)throw new Error("usernotfound");if(!await M.verify(s.password,t))throw new Error("incorrectpassword");if(!s.abilities.login)throw new Error("userisnotabletologin");return this.sessions.create(s,i)}logout(e){return e.delete(),this.sessions.collection.deleteOne({_id:e._id})}#r(e,t){return e instanceof P&&t instanceof P?e.name.last&&t.name.last?e.name.last>t.name.last?1:e.name.last<t.name.last?-1:0:!e.name.last&&!t.name.last?e.displayLabel>t.displayLabel?1:e.displayLabel<t.displayLabel?-1:0:e.name.last?-1:1:e instanceof h&&t instanceof h?e.title>t.title?1:e.title<t.title?-1:0:e instanceof h?-1:1}sortIds(e){return O(e.map(t=>this.get(t)||this.orgs.get(t)).filter(Boolean).sort(this.#r))}replaceMap=new Map;replaceHandlers=new Set;async replace(e){let t=this.replaceMap.get(e)??null;t&&this.replaceMap.delete(e);for(let i of this.replaceHandlers)await i(e,t)}async deleteUser(e){let{deletedCount:t}=await this.collection.deleteOne({_id:e});return!!t}static init(e,t){return new r(e,t).whenReady()}};export{Z as AbilityError,se as PermissionError,V as RolesError,ie as SubordinationError,te as UnauthorizedError,le as Users};
1
+ function O(r){if(r instanceof Set){let e=[];for(let t of r)e.push(t._id);return e}return r.map(e=>e._id)}function ce(r,...e){let t=0;for(let i of e)r.includes(i)||(r.push(i),t++);return t}function M(r,e,t){if(r&&e){if(e.includes(".")){let i=e.split("."),s=r;for(let o=0;o<i.length-1;o++){let n=i[o],l=s[n];s=l&&typeof l=="object"?l:s[n]={}}return s[i.at(-1)]=t}return r[e]=t}return null}function de(r,...e){for(let t of e)for(let i in t)Object.hasOwn(t,i)&&M(r,i,t[i]);return r}function S(){}var E=new WeakMap,x=class r extends Promise{constructor(e,t){let i,s;if(super((o,n)=>{i=o,s=n}),E.set(this,{resolve:i,reject:s}),t?.signal)if(t.signal.aborted)this.reject(new DOMException("Aborted","AbortError"));else{let o=()=>this.reject(new DOMException("Aborted","AbortError"));t.signal.addEventListener("abort",o),this.finally(()=>t.signal?.removeEventListener("abort",o))}if(typeof t?.timeout=="number"&&Number.isFinite(t.timeout)){let o=setTimeout(()=>this.reject(new DOMException("Timeout exceeded","TimeoutError")),t.timeout);this.finally(()=>clearTimeout(o))}e?.(this.resolve,this.reject)}isPending=!0;isFulfilled=!1;isRejected=!1;state="pending";result;resolve=e=>{if(this.isPending){this.isPending=!1,this.isFulfilled=!0,this.state="fulfilled",this.result=e;let t=E.get(this);t&&(t.resolve.call(this,e),E.delete(this))}};reject=e=>{if(this.isPending){this.isPending=!1,this.isRejected=!0,this.state="rejected",this.result=e;let t=E.get(this);t&&(t.reject.call(this,e),E.delete(this))}};static resolved(e){return new r(t=>t(e))}static rejected(e){return new r((t,i)=>i(e))}};function K(r,e=0,t={}){let{leading:i=!1,trailing:s=!0}=t,{maxWait:o=1/0}=t,n,l,a,d,g,A,p,w,ae=async()=>{let b=Date.now();b>=a?(n=void 0,a=void 0,clearTimeout(l),l=void 0,typeof p=="function"&&await p(),y.resolve(w),A=i):(clearTimeout(n),n=setTimeout(ae,a-b))},F=Number.isFinite(o)?()=>{p===v&&(p=!1),v(),l=setTimeout(F,o)}:null;async function v(){try{return w=await r.apply(d,g),w}catch(b){throw y.reject(b),b}}i&&typeof i=="boolean"&&(i=v),A=i,s&&typeof s=="boolean"&&(s=v),p=s;let y=Object.assign(function(...b){return g=b,d=this,a=Date.now()+e,p=s,y.promise.isPending||(y.promise=new x((Oe,Pe)=>{y.resolve=Oe,y.reject=Pe,typeof A=="function"&&(A(),A=!1,p===v&&(p=!1)),n||(n=setTimeout(ae,e),F&&(l=setTimeout(F,o)))})),y.promise},{callback:r,promise:x.resolved(void 0),resolve:S,reject:S,run:v,clear:async b=>{clearTimeout(n),n=void 0,clearTimeout(l),l=void 0,y.resolve(b?await v():w)}});return y}K.noop=Object.assign(()=>{},{callback:S,promise:x.resolved(void 0),resolve:S,reject:S,run:S,clear:S});function pe(r,e){if(r&&e){if(e.includes(".")){let t=e.split("."),i=r;for(let o=0;o<t.length-1;o++){let n=t[o],l=i[n];if(l&&typeof l=="object")i=l;else return!1}let s=t.at(-1);return s in i&&delete i[s]}return e in r&&delete r[e]}return!1}function u(r,e){if(r){for(let t of e)delete r[t];return r}return null}function U(r){for(let e in r)delete r[e];return r}var C=class extends Array{constructor(){super(),Object.freeze(this)}push(){return 0}unshift(){return 0}splice(){return[]}};var _=class extends Set{constructor(){super()}add(){return this}};var f=class extends Error{constructor(e,t=null,i){typeof e=="object"?(i=e,e=i.message,delete i.message,t=null):t&&typeof t=="object"&&(i=t,t=null),super(e),this.tag=t,i&&Object.assign(this,i)}name="Err-or";tag};function J(r,e,t=!1){let i=[];if(t)for(let s of e){let o=r.get(s);o!==void 0&&i.push(o)}else for(let s of e)i.push(r.get(s));return i}function N(r,e){if(e){if(e.includes(".")){let t=r;for(let i of e.split("."))if(t=t?.[i],t===void 0)break;return t}return r[e]}return r}function ue(r,e){for(let t of e)if(r.has(t))return!0;return!1}function fe(r,e,t,i,s=!0){return Array.isArray(r)&&(r=r.length),typeof i!="string"&&(s=i??!0,i=t),(s?`${r}\xA0`:"")+fe.raw(r,e,t,i)}fe.raw=(r,e,t,i=t)=>{r=Math.abs(r);let s=r%10,o=r%100;return s===1&&o!==11?e:s>=2&&s<=4&&!(o>=12&&o<=15)?t:i};function q(...r){let e=[];if(r.length){let[t,...i]=r;e:for(let s of t){for(let o of i)if(o instanceof Set?!o.has(s):!o.includes(s))continue e;e.push(s)}}return e}function he(r,e){let t={};for(let i of e)i in r&&(t[i]=r[i]);return t}function me(r,e){return r.delete(e),r.add(e),r}function h(r,e){let t,i=0;for(let s of e)for(;(t=r.indexOf(s))>-1;)r.splice(t,1),i++;return i}function ye(r,e){let t=r.indexOf(e);return t>-1?(r.splice(t,1),!0):!1}function be(r,e){for(let t of[...r].sort(e))r.delete(t),r.add(t);return r}function ge(...r){return[...new Set(r.flat())]}function k(r,e){return r.filter(t=>!e.includes(t))}var H=class extends f{constructor(e,t){typeof e=="object"&&(t=e,e=void 0),super("User lacks ability","lacksability",{...e&&{ability:e},...t})}name="AbilityError"};function V(r){return typeof r=="object"}function Z(r){return typeof r=="number"}function X(r){return Array.isArray(r)}var Ae=new Map,W=class extends Map{constructor(e){super();for(let t of e)delete t.top,this.#e.push(t);(function t(i,s,o){for(let n of i){if(Ae.set(n,s),n.level=o,!s||n.top){if(n.longId=n._id,this.has(n._id))throw new Error(`Top-level ability duplicate: ${n._id}`);this.set(n._id,n)}else n.longId=s?`${s.longId}.${n._id}`:n._id;n.abilities&&t.call(this,n.abilities,n,o+1)}}).call(this,e,null,0)}#e=[];get(e,t){let i=e.split("."),s=t??super.get(i.shift());if(s&&i.length){for(let o of i)if(s=s?.abilities?.find(({_id:n,top:l})=>!l&&n===o),!s)break}return s}getSchema=this.get;getParamSchema(e,t){return this.get(e)?.params?.find(({_id:i})=>i===t)}getDefaultParam(e,t,i){(t===void 0||typeof t=="boolean")&&(i=t);let s=typeof e=="string"?this.getParamSchema(e,t):e;if(s)switch(s.type){case"number":return i?s.max??1/0:s.min??0;case"items":return i?s.items.map(({_id:o})=>o):[]}}getDefaultAbility(e,t=!e){if(typeof e=="string"&&(e=this.get(e)),e){if(e.abilities||e.params){let i={};if(e.params)for(let s of e.params)i[s._id]=this.getDefaultParam(s,t);if(t&&e.abilities)for(let s of e.abilities)s.top||(i[s._id]=this.getDefaultAbility(s,t));return i}return!0}}getDefaultAbilities(e,t=!e){let i=(e?(Array.isArray(e)?e:[e]).map(o=>typeof o=="string"?this.get(o):o).filter(Boolean):[...this.values()]).sort((o,n)=>o.level-n.level),s=new Map;for(let o of i)(function n(l){let a=Ae.get(l);a&&(n(a),s.has(a)||s.set(a,!1))})(o),t?function n(l){if(s.has(l)||s.set(l,!0),l.abilities)for(let a of l.abilities)a.top&&n(a)}(o):s.has(o)||s.set(o,!1);return de({},Object.fromEntries([...s].map(([o,n])=>[o.longId,this.getDefaultAbility(o,n)])))}getSchemeFor(e){return e=this.adjust(structuredClone(e)),function t(i,s){for(let o=0;o<i.length;o++){let n=i[o],l=n.top?e[n._id]:s[n._id];if(l){if(n.params)for(let a of n.params){let d=l[a._id];switch(a.type){case"number":a.max=d;break;case"items":a.items=a.items.filter(({_id:g})=>d.includes(g))}}n.abilities&&(t(n.abilities,l),n.abilities.length||delete n.abilities)}else i.splice(o--,1)}return i}(structuredClone(this.#e),e)}getParam(e,t,i){if(this.getParamSchema(t,i)){let s=N(e,`${t}.${i}`);return this.isParamFits(t,i,s)?s:this.getDefaultParam(t,i)}}setParam(e,t,i,s){let o=this.getParamSchema(t,i);if(!o)throw new Error(`No such ability param: ${t}.${i}`);return M(e,`${t}.${i}`,this.adjustParam(o,s)),e}isParamFits(e,t,i,s){if(i!==void 0){let o=this.getParamSchema(e,t);if(o)switch(o.type){case"number":return Z(i)&&(o.min===void 0||i>=o.min)&&(s===void 0?o.max===void 0||i<=o.max:i<=s);case"items":return X(i)&&i.length===new Set(i).size&&(s===void 0?i.every(n=>o.items.find(({_id:l})=>l===n)):i.every(n=>s.includes(n)))}}return!1}adjustParam(e,t){switch(e.type){case"number":return Z(t)?Math.max(Math.min(t,e.max??1/0),e.min??0):e.min??0;default:return X(t)?q(e.items.map(i=>i._id),t):[]}}adjust(e,t){let i={};for(let[s,o]of Object.entries(e)){let n=this.get(s,t);if(n)if(n.params||n.abilities){let l={};if(n.params)if(V(o))for(let a of n.params)l[a._id]=this.adjustParam(a,o[a._id]);else for(let a of n.params)l[a._id]=this.getDefaultParam(a);n.abilities&&V(o)&&Object.assign(l,this.adjust(he(o,n.abilities.filter(a=>!a.top).map(a=>a._id)),n)),i[s]=l}else i[s]=!0}return Object.assign(U(e),i)}merge(e,t,i){i||(this.adjust(e),t=this.adjust(structuredClone(t)));for(let[s,o]of Object.entries(t)){let n=this.get(s,i);if(n&&n.isInheritable!==!1)if(s in e&&(n.params||n.abilities)){let l=e[s],a=o;if(n.params){for(let d of n.params)if(d.isInheritable!==!1)switch(d.type){case"number":l[d._id]=Math.max(l[d._id],a[d._id]);break;case"items":ce(l[d._id],...a[d._id])}}n.abilities&&this.merge(l,a,n)}else e[s]=o}return e}hasAbility(e,t){return!!N(e,t)}setAbility(e,t){let i=typeof t=="string"?this.get(t):t;if(!i)throw new Error(`No such ability: ${t}`);return this.merge(e,this.getDefaultAbilities(i)),e}unsetAbility(e,t){let i=typeof t=="string"?this.get(t):t;if(!i)throw new Error(`No such ability: ${t}`);return function s(o){if(pe(e,o.longId),o.abilities)for(let n of o.abilities)s(n)}(i),e}};var Y=class extends f{constructor(e,t){super(`User lacks role${Array.isArray(e)?"s":""}`,"lacksroles",{roles:Array.isArray(e)?e:[e],...t})}name="RolesError"};var Q=new WeakMap,D=class{constructor(e,t){this.#e=e,this._id=t._id,e.set(this._id,this),this.update(t)}#e;_id;ownInvolveIds;ownAbilities;title="";displayTitle="";_o=0;ownInvolves=[];involves=new Set;abilities={};inheritedAbilities={};update({_id:e,involves:t,abilities:i,title:s,...o}){if(Object.assign(this,o),t&&(this.ownInvolveIds=t),i&&(this.ownAbilities=i),s!==void 0&&(this.title=s,this.displayTitle=s||this._id),t||i){let n=[this.ownInvolveIds.join(","),JSON.stringify(this.ownAbilities)].join(`
2
+ `);n!==Q.get(this)&&(Q.set(this,n),this.#e.users.isInited&&this.#e.update())}}delete(){this.#e.delete(this._id),Q.delete(this),this.#e.update()}};var c={_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}|[0-9a-f]{24}~[A-Za-z0-9_-]{43})$/,role:/^[\d_a-z-]{1,64}$/,ip:/^(?:\d{1,3}\.){3}\d{1,3}$/};var I={required:["_id","involves","abilities","title","description","meta","createdAt"],properties:{_id:{bsonType:"string",pattern:c.role.source,not:{enum:["root"]}},involves:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c.role.source,not:{enum:["root"]}},additionalItems:!1},abilities:{bsonType:"object"},title:{bsonType:"string",maxLength:256},description:{bsonType:"string",maxLength:10240},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var _e=[[{involves:1}]];function Se(){throw new Error("Direct usage of roles collection.deleteOne or .deleteMany is forbidden. Use roles.deleteRole instead.")}var G=class extends Map{constructor(e,t={}){super();let{root:i,...s}=t;this.users=e,this.collections=e.collections,this.abilities=e.abilities,this.root=new D(this,{...i,_id:"root",involves:[],abilities:this.abilities.getDefaultAbilities(),title:"Root",description:"Root",meta:{},createdAt:Date.now()}),this.initOptions=s}users;collections;collection;abilities;root;initOptions;async init(){if(!this.users.isInited){let{schema:e,indexes:t,collection:i}=this.initOptions;e&&(e.required&&h(e.required,I.required),e.properties&&u(e,Object.keys(I.properties)));let s={...I,...e,required:[...I.required,...e?.required??[]],properties:{...I.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("roles",{...i,schema:s}),{deleteOne:Se,deleteMany:Se}),await this.collection.ensureIndexes([..._e,...t??[]]),await this.#e();for await(let o of this.collection.find())this.abilities.adjust(o.abilities)&&await this.collection.updateOne({_id:o._id},{$set:{abilities:o.abilities}}),this.load(o);this.update(),this.collection.onChange(this.#t),delete this.initOptions}}async#e(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}#t=e=>{switch(e.operationType){case"insert":{new D(this,e.fullDocument);break}case"replace":this.get(e.documentKey._id)?.update(e.fullDocument);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields);break;case"delete":this.get(e.documentKey._id)?.delete()}};load(e){new D(this,e)}resolve(e,t){t=[e,...t];for(let i of e.ownInvolveIds){let s=this.get(i);if(s){for(let o of t)me(o.involves,s),this.abilities.merge(o.inheritedAbilities,s.abilities);s!==e&&this.resolve(s,t)}}}sorted=[];#i(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 s of e)s!==this.root&&!e.some(o=>o.ownInvolveIds.includes(s._id))&&this.root.ownInvolveIds.push(s._id),s.involves.clear(),s.abilities=structuredClone(s.ownAbilities),s.inheritedAbilities={};this.root.involves.add(this.root),this.resolve(this.root,[]);for(let s of e)s.ownInvolves=J(this,s.ownInvolveIds,!0).sort(this.#i).reverse();let t=[this.root];for(let s=0;s<t.length;s++){let o=t[s];for(let n of o.ownInvolves){let l=t.indexOf(n);~l&&(t.splice(l,1),s--),t.splice(s+1,0,n)}}let i=0;for(let s of t)this.abilities.merge(s.abilities,s.inheritedAbilities),s._o=i++;this.sorted=t,this.users.isInited&&this.users.update(!0)}async create({_id:e,involves:t,title:i,description:s,...o}){return await this.collection.insertOne({_id:e,involves:t||[],abilities:{},title:i??"",description:s??"",meta:{},...u(o,["abilities"]),createdAt:Date.now()}),e}async updateRole(e,t){let i=this.get(e);if(!i)return!1;if(t.involves){h(t.involves,[e]);for(let s of t.involves)this.get(s)?.involves.has(i)&&h(t.involves,[s]);t.involves=this.cleanUpIds(t.involves)}return await this.collection.updateOne({_id:e},{$set:t}),!0}deleteRole(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=q(this.sorted,J(this,e,!0)),i=[];for(let s of t)t.every(o=>o===s||!o.involves.has(s))&&i.push(s._id);return i}async setAbility(e,t,i){let s=this.get(e);return s?(await this.collection.updateOne({_id:e},{$set:{abilities:i?this.abilities.setAbility(s.ownAbilities,t):this.abilities.unsetAbility(s.ownAbilities,t)}}),!0):!1}async setAbilityParam(e,t,i,s){let o=this.get(e);return o?(await this.collection.updateOne({_id:e},{$set:{abilities:this.abilities.setParam(o.ownAbilities,t,i,s)}}),!0):!1}};var ee=class extends f{constructor(e){super("Unauthorized","unauthorized",e)}name="UnauthorizedError"},te=class extends f{constructor(e,t,i){switch(arguments.length){case 1:i=e,e=void 0;break;case 2:i=t,t=void 0}super("Insubordination attempt","subordination",{...e&&{type:e},...t&&{ids:Array.isArray(t)?t:[t]},...i})}name="SubordinationError"},ie=class extends f{constructor(e){super("Insufficient permissions","permissions",e)}name="PermissionError"};import{hash as ve,verify as ke}from"@node-rs/argon2";import Me from"eventemitter3";import{newObjectIdString as Ue}from"insite-db";import{newObjectIdString as De}from"insite-db";var se=new WeakMap,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:i,...s}){if(Object.assign(this,s),t!==void 0&&(this.title=t,this.initials=t?.[0]?.toUpperCase()??"",this.displayLabel=t),i){this.ownerIds=i;let o=this.ownerIds.join(",");o!==se.get(this)&&(se.set(this,o),this.orgs.users.isInited&&this.orgs.update())}}async delete(){this.orgs.delete(this._id),se.delete(this),await this.orgs.replace(this._id),this.orgs.update()}};var j={required:["_id","title","note","owners","meta","createdAt"],properties:{_id:{bsonType:"string",pattern:c._id.source},title:{bsonType:"string",maxLength:512},note:{bsonType:"string",maxLength:131072},owners:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c._id.source},additionalItems:!1},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var Ie=[[{owners:1}]];function xe(){throw new Error("Direct usage of orgs collection.deleteOne or .deleteMany is forbidden. Use orgs.deleteOrg instead.")}var L=class extends Map{constructor(e,t={}){super(),this.users=e,this.collections=e.collections,this.preinitOptions=t}users;collections;preinitOptions;collection;null;#e=!1;async preinit(){if(!this.#e){this.#e=!0;let{schema:e,indexes:t,null:i,collection:s}=this.preinitOptions;e&&(e.required&&h(e.required,j.required),e.properties&&u(e,Object.keys(j.properties)));let o={...j,...e,required:[...j.required,...e?.required??[]],properties:{...j.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("orgs",{...s,schema:o}),{deleteOne:xe,deleteMany:xe}),await this.collection.ensureIndexes([...Ie,...t??[]]),this.null=Object.assign(new m(this,{...i,_id:"",title:"",note:"",owners:[],meta:{},createdAt:Date.now()}),{_id:null,ownerIds:new C,ownerOrgs:new _,ownerUsers:new _,slaveOrgs:new _}),await this.#t();for await(let n of this.collection.find())this.load(n);delete this.preinitOptions}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}init(){this.users.isInited||(this.update(),this.collection.onChange(this.#i))}#i=e=>{switch(e.operationType){case"insert":{new m(this,e.fullDocument);break}case"replace":this.get(e.documentKey._id)?.update(e.fullDocument);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields);break;case"delete":this.get(e.documentKey._id)?.delete()}};load(e){new m(this,e)}#o(e,t){t=[e,...t];for(let i of e.ownerOrgs){this.#o(i,t);for(let s of t)i.slaveOrgs.add(s)}}sorted=[];update(){let e=[...this.values()],t=[];for(let i of e){i.ownerOrgs.clear(),i.ownerUsers.clear(),i.slaveOrgs.clear();for(let s of i.ownerIds){let o=this.get(s);if(o)i.ownerOrgs.add(o);else{let n=this.users.get(s);n&&i.ownerUsers.add(n)}}!i.ownerOrgs.size&&i._id&&t.push(i)}for(let i of e)e.some(s=>s.ownerOrgs.has(i))||this.#o(i,[]);t.sort(this.#s);for(let i of e)be(i.slaveOrgs,this.#s);for(let i=0;i<t.length;i++){let s=t[i];for(let o of[...s.slaveOrgs].reverse())if(o.ownerOrgs.has(s)){let n=t.indexOf(o);~n&&(t.splice(n,1),i--),t.splice(i+1,0,o)}}for(let i=0,{length:s}=t;i<s;)t[i]._o=i++;this.sorted=t,this.users.isInited&&this.users.update()}#s(e,t){return t.slaveOrgs.size-e.slaveOrgs.size||(e.title>t.title?1:e.title<t.title?-1:0)}async create({title:e,note:t,...i}){let s=De();return await this.collection.insertOne({_id:s,title:e??"",note:t??"",meta:{},...u(i,["_id"]),createdAt:Date.now()}),s}async updateOrg(e,t,i){let s=this.get(e);return s?(t.owners&&(t.owners=this.users.sortIds(ge(i?k(s.ownerIds,i.slaveIds):[],k(t.owners,[e,...O(s.slaveOrgs)])))),await this.collection.updateOne({_id:e},{$set:t}),!0):!1}deleteOrg(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 i of this.replaceHandlers)await i(e,t)}};import{randomBytes as je}from"node:crypto";import{newObjectIdString as Re}from"insite-db";var R={required:["_id","user","remoteAddress","isOnline","meta","createdAt","prolongedAt","expiresAt"],properties:{_id:{bsonType:"string",pattern:c.sessionId.source},user:{bsonType:"string",pattern:c._id.source},userAgent:{bsonType:"string",maxLength:4096},remoteAddress:{bsonType:"string",pattern:c.ip.source},isOnline:{bsonType:"bool"},meta:{bsonType:"object"},createdAt:{bsonType:"number"},prolongedAt:{bsonType:"number"},expiresAt:{bsonType:"date"}}};var $=class{constructor(e,t){let i=e.users.get(t.user);i?(this.#e=e,this._id=t._id,this.#e.set(this._id,this),this.user=i,this.user.sessions.add(this),this.#e.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;#e;update({_id:e,user:t,isOnline:i,...s}){i!==void 0&&this.isOnline!==i&&(this.isOnline=i,this.#e.users.isInited&&this.user.isOnline!==this.isOnline&&this.user.updateIsOnlineDebounced()),Object.assign(this,s)}prolong({_id:e,user:t,...i}){let s=Date.now();return i.prolongedAt=s,i.expiresAt=new Date(s+this.#e.collection.expireAfterSeconds*1e3),this.update(i),this.#e.collection.updateOne({_id:this._id},{$set:i})}async online(){if(!this.isOnline){let e={isOnline:!0};this.update(e),await this.#e.collection.updateOne({_id:this._id},{$set:e})}}async offline(){if(this.isOnline){let e={isOnline:!1};this.update(e),await this.#e.collection.updateOne({_id:this._id},{$set:e})}}delete(){this.#e.delete(this._id),this.user.sessions.delete(this),this.#e.users.bySessionId.delete(this._id),this.#e.users.emit("session-delete",this),this.isOnline&&this.user.updateIsOnline()}};var oe=3600*24*7,$e=[[{user:1}],[{expiresAt:1},{expireAfterSeconds:oe}]],B=class extends Map{constructor(e,t={}){super(),this.users=e,this.collections=e.collections,this.initOptions=t}users;collections;initOptions;collection;async init(){if(!this.users.isInited){let{schema:e,indexes:t,collection:i}=this.initOptions;e&&(e.required&&h(e.required,R.required),e.properties&&u(e,Object.keys(R.properties)));let s={...R,...e,required:[...R.required,...e?.required??[]],properties:{...R.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("sessions",{...i,schema:s}),{expireAfterSeconds:oe}),await this.collection.ensureIndexes([...$e,...t??[]]),await this.#e();for await(let o of this.collection.find())this.load(o);this.collection.onChange(this.#t),delete this.initOptions}}async#e(){await this.collection.bulkWrite([{updateMany:{filter:{meta:{$exists:!1}},update:{$set:{meta:{}}}}},{updateMany:{filter:{isOnline:!0},update:{$set:{isOnline:!1}}}}])}#t=e=>{switch(e.operationType){case"insert":this.has(e.documentKey._id)||new $(this,e.fullDocument),this.users.get(e.fullDocument.user)?.trimSessions();break;case"replace":this.get(e.documentKey._id)?.update(e.fullDocument);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields);break;case"delete":this.get(e.documentKey._id)?.delete()}};uid(){return`${Re()}~${je(32).toString("base64url")}`}load(e){new $(this,e)}async create(e,t){let i=Date.now(),s={userAgent:"",remoteAddress:"127.0.0.1",isOnline:!0,...t,_id:this.uid(),user:e._id,meta:{},createdAt:i,prolongedAt:i,expiresAt:new Date(i+oe*1e3)},o=new $(this,s);return await this.collection.insertOne(s),o}async destroySession(e){let{deletedCount:t}=await this.collection.deleteOne({_id:e});return!!t}};import{Binary as Te}from"insite-db";var we={required:["_id","type","size","ts","data","meta"],properties:{_id:{bsonType:"string",pattern:c._id.source},type:{bsonType:"string",maxLength:256},size:{bsonType:"number"},ts:{bsonType:"string",maxLength:10},data:{bsonType:"binData"},meta:{bsonType:"object"}},additionalProperties:!1};var z=class{constructor(e,t={}){this.users=e,this.collections=e.collections,this.initOptions=t}TYPES_ACCEPTED=["image/webp"];MAX_SIZE=1024*512;users;collections;collection;initOptions;async init(){if(!this.users.isInited){let{collection:e}=this.initOptions;this.collection=await this.collections.ensure("users.avatars",{...e,schema:we}),await this.#e()}}async#e(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}async save(e,t,i){let s=Te.createFromBase64(i.slice(i.indexOf(","))),o=Date.now().toString(36);await Promise.all([this.collection.replaceOne({_id:e},{type:t,size:s.length(),ts:o,data:s,meta:{}},{upsert:!0}),this.users.collection.updateOne({_id:e},{$set:{avatar:o}})])}async deleteAvatar(e){let[{deletedCount:t}]=await Promise.all([this.collection.deleteOne({_id:e}),this.users.collection.updateOne({_id:e},{$set:{avatar:null}})]);return!!t}};var T={required:["_id","email","password","roles","name","org","job","meta","createdAt"],properties:{_id:{bsonType:"string",pattern:c._id.source},email:{bsonType:"string",pattern:c.email.source},password:{bsonType:"string",pattern:c.argon2.source},roles:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c.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:c._id.source},{bsonType:"null"}]},job:{bsonType:"string",maxLength:512},avatar:{oneOf:[{bsonType:"string",maxLength:10},{bsonType:"null"}]},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var re=new WeakMap,ne=new WeakMap,Ee=process.env.INSITE_STATIC_URL??"",P=class{constructor(e,t){this.#e=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;#e;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:i,roles:s,org:o,avatar:n,...l}){Object.assign(this,l);let a;i&&this.email!==i&&(this.#e.byEmail.delete(this.email),this.email=i,this.#e.byEmail.set(i,this),a=!0);let d,g;t&&(this.name.first!==t.first||this.name.middle!==t.middle||this.name.last!==t.last)&&(g=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(),d=!0),(a||d)&&(this.displayLabel=`${this.name.first} ${this.name.last}`.trim()||this.name.middle||this.email);let A;if(s){this.ownRoleIds=s;let w=this.ownRoleIds.join(",");w!==re.get(this)&&(re.set(this,w),this.#e.isInited&&(this.updateRoles(),A=!0))}let p;o!==void 0&&this.org?._id!==o&&(this.org?.users.delete(this),this.org=o&&this.#e.orgs.get(o)||this.#e.orgs.null,this.org.users.add(this),p=!0),n!==void 0&&this.avatar!==n&&(this.avatar=n,this.avatarUrl=n&&`${Ee}/avatars/${this._id}-${n}.webp`),this.#e.isInited&&(A||p?(this.updatePermissions(),g&&(this.#e.isSortRequired=!0),this.#e.update()):g&&this.#e.sort())}updateRoles(){this.ownRoles=[],this.roles.clear(),this.slaveRoles.clear(),U(this.abilities);for(let e of this.ownRoleIds){let t=this.#e.roles.get(e);if(t){this.ownRoles.push(t),this.roles.add(t);for(let i of t.involves)this.roles.add(i),this.slaveRoles.add(i);this.slaveRoleIds=O(this.slaveRoles),this.#e.abilities.merge(this.abilities,t.abilities)}}this.roles.has(this.#e.roles.root)&&(this.isRoot=!0),this.trimSessions()}updatePermissions(){this.slaveOrgs.clear(),this.slaveUsers.clear(),this.slaves.clear();let e=new Set;for(let s of this.#e.orgs.sorted)if((s.ownerUsers.has(this)||this.isRoot)&&!this.slaveOrgs.has(s)){this.slaveOrgs.add(s),this.slaves.add(s),e.add(s._id);for(let o of s.slaveOrgs)this.slaveOrgs.add(o),this.slaves.add(o),e.add(o._id)}for(let s of new Set([this.org,...this.slaveOrgs,this.#e.orgs.null]))for(let o of s.users)o!==this&&(ue(this.slaveRoles,o.ownRoles)||!o.ownRoles.length)&&(this.slaveUsers.add(o),this.slaves.add(o),e.add(o._id));this.slaveIds=[...e];let t=[];if(this.org._id){t.push(this.org._id);for(let s of this.org.slaveOrgs)this.slaveOrgs.has(s)||t.push(s._id)}this.permissiveIds=[...t,this._id,...e];let i=[this.permissiveIds.join(","),this.ownRoleIds.join(","),JSON.stringify(this.abilities),this.slaveRoleIds.join(",")].join(`
3
+ `);i!==ne.get(this)&&(ne.set(this,i),this.#e.isInited&&this.#e.emit("user-permissions-change",this))}trimSessions(){let e=this.abilities.login?.sessionsLimit??0;if(this.sessions.size>e)return this.#e.sessions.collection.deleteMany({_id:{$in:O([...this.sessions].sort((t,i)=>t.expiresAt.valueOf()-i.expiresAt.valueOf()).slice(0,this.sessions.size-e))}})}updateIsOnline(){let e=!1;for(let t of this.sessions)if(t.isOnline){e=!0;break}this.isOnline!==e&&(this.isOnline=e,this.#e.emit("user-is-online",this))}updateIsOnlineDebounced=K(()=>this.updateIsOnline(),500);async delete(){this.org.users.delete(this),this.#e.delete(this._id),this.#e.byEmail.delete(this.email),ye(this.#e.sorted,this),re.delete(this),ne.delete(this),await this.#e.replace(this._id),this.#e.update()}};var Ce=[[{email:1},{unique:!0}],[{org:1}]],le=class r extends Map{constructor(e,t){super();let i=new Me;this.#e=i,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=e,this.abilities=new W(t.abilities),this.initOptions=t,this.init()}#e;_events;_eventsCount;emit;on(e,t,i){return this.#e.on(e,t,i),this}once;addListener;off;removeListener;initOptions;collections;abilities;collection;roles;sessions;orgs;avatars;byEmail=new Map;bySessionId=new Map;sorted=[];isSortRequired=!0;#t=!1;async preinit(){if(!this.#t){this.#t=!0;let{indexes:e,schema:t,initialRoot:i,collection:s}=this.initOptions;t&&(t.required&&h(t.required,T.required),t.properties&&u(t,Object.keys(T.properties)));let o={...T,...t,required:[...T.required,...t?.required??[]],properties:{...T.properties,...t?.properties}};this.collection=await this.collections.ensure("users",{...s,schema:o}),await this.collection.ensureIndexes([...Ce,...e??[]]),await this.collection.countDocuments({roles:"root"})||await this.create({email:process.env.INSITE_ROOT_EMAIL??"insite@root.email",password:process.env.INSITE_ROOT_PASSWORD??"inSiteRootPassword",name:{first:"Root"},job:"Root",...i,roles:["root"],org:null,meta:{}}),await this.#i();for await(let n of this.collection.find())this.load(n)}}async#i(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}isInited=!1;async init(){if(!this.isInited){let{roles:e,orgs:t,sessions:i,avatars:s,collection:{quiet:o}={}}=this.initOptions;this.roles=new G(this,{...e,collection:{quiet:o,...e?.collection}}),this.orgs=new L(this,{...t,collection:{quiet:o,...t?.collection}}),this.sessions=new B(this,{...i,collection:{quiet:o,...i?.collection}}),this.avatars=new z(this,{...s,collection:{quiet:o,...s?.collection}}),await this.roles.init(),await this.orgs.preinit(),await this.preinit(),this.orgs.init(),await this.avatars.init(),this.update(!0),this.collection.onChange(this.#o),await this.sessions.init(),delete this.initOptions,this.isInited=!0,this.#s.resolve(this)}}#o=e=>{switch(e.operationType){case"insert":new P(this,e.fullDocument);break;case"replace":this.get(e.documentKey._id)?.update(e.fullDocument);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields);break;case"delete":this.get(e.documentKey._id)?.delete()}};load(e){new P(this,e)}sort(){this.isSortRequired=!1,this.sorted=[...this.values()].sort((e,t)=>e.name.last>t.name.last?1:e.name.last<t.name.last?-1:0)}update(e){if(e)for(let t of this.values())t.updateRoles();for(let t of this.values())t.updatePermissions();this.isSortRequired&&this.sort()}#s=new x;whenReady(){return this.#s}async create({email:e,password:t,roles:i,name:s,org:o,job:n,...l}){if(this.byEmail.has(e))throw new Error("User exists");let a=Ue();return await this.collection.insertOne({_id:a,email:e,password:await ve(t),roles:this.isInited?this.roles.cleanUpIds(i):i,name:{first:s.first??"",middle:s.middle??"",last:s.last??""},org:o??null,job:n??"",meta:{},...u(l,["_id"]),createdAt:Date.now()}),a}async updateUser(e,t,i){let s=this.get(e);return s?(t.roles&&(t.roles=s.isRoot?["root"]:this.roles.cleanUpIds(i?k(s.ownRoleIds,i.slaveRoleIds).concat(t.roles):t.roles)),await this.collection.updateOne({_id:e},{$set:t}),!0):!1}async changePassword(e,t){if(!this.has(e))throw new Error("usernotfound");if(!t)throw new Error("emptypasswordisnotallowed");await Promise.all([this.collection.updateOne({_id:e},{$set:{password:await ve(t)}}),this.sessions.collection.deleteMany({user:e})])}async login(e,t,i){let s=this.byEmail.get(e);if(!s)throw new Error("usernotfound");if(!await ke(s.password,t))throw new Error("incorrectpassword");if(!s.abilities.login)throw new Error("userisnotabletologin");return this.sessions.create(s,i)}logout(e){return e.delete(),this.sessions.collection.deleteOne({_id:e._id})}#r(e,t){return e instanceof P&&t instanceof P?e.name.last&&t.name.last?e.name.last>t.name.last?1:e.name.last<t.name.last?-1:0:!e.name.last&&!t.name.last?e.displayLabel>t.displayLabel?1:e.displayLabel<t.displayLabel?-1:0:e.name.last?-1:1:e instanceof m&&t instanceof m?e.title>t.title?1:e.title<t.title?-1:0:e instanceof m?-1:1}sortIds(e){return O(e.map(t=>this.get(t)||this.orgs.get(t)).filter(Boolean).sort(this.#r))}replaceMap=new Map;replaceHandlers=new Set;async replace(e){let t=this.replaceMap.get(e)??null;t&&this.replaceMap.delete(e);for(let i of this.replaceHandlers)await i(e,t)}async deleteUser(e){let{deletedCount:t}=await this.collection.deleteOne({_id:e});return!!t}static init(e,t){return new r(e,t).whenReady()}};export{H as AbilityError,ie as PermissionError,Y as RolesError,te as SubordinationError,ee as UnauthorizedError,le as Users};
4
4
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../@nesvet/npm/n/src/_ids.ts", "../../../../@nesvet/npm/n/src/add.ts", "../../../../@nesvet/npm/n/src/setPath.ts", "../../../../@nesvet/npm/n/src/assignPath.ts", "../../../../@nesvet/npm/n/src/noop.ts", "../../../../@nesvet/npm/n/src/StatefulPromise.ts", "../../../../@nesvet/npm/n/src/debounce.ts", "../../../../@nesvet/npm/n/src/deletePath.ts", "../../../../@nesvet/npm/n/src/deleteProps.ts", "../../../../@nesvet/npm/n/src/empty.ts", "../../../../@nesvet/npm/n/src/EmptyArray.ts", "../../../../@nesvet/npm/n/src/EmptySet.ts", "../../../../@nesvet/npm/n/src/Err.ts", "../../../../@nesvet/npm/n/src/getAll.ts", "../../../../@nesvet/npm/n/src/getPath.ts", "../../../../@nesvet/npm/n/src/hasAny.ts", "../../../../@nesvet/npm/n/src/howmuch.ts", "../../../../@nesvet/npm/n/src/intersection.ts", "../../../../@nesvet/npm/n/src/pick.ts", "../../../../@nesvet/npm/n/src/reAdd.ts", "../../../../@nesvet/npm/n/src/removeAll.ts", "../../../../@nesvet/npm/n/src/removeOne.ts", "../../../../@nesvet/npm/n/src/sort.ts", "../../../../@nesvet/npm/n/src/union.ts", "../../../../@nesvet/npm/n/src/without.ts", "../src/abilities/Error.ts", "../src/abilities/types.ts", "../src/abilities/Map.ts", "../src/roles/Error.ts", "../src/roles/Role.ts", "../src/lib/regexps.ts", "../src/roles/schema.ts", "../src/roles/Roles.ts", "../src/users/errors.ts", "../src/users/Users.ts", "../src/orgs/Orgs.ts", "../src/orgs/Org.ts", "../src/orgs/schema.ts", "../src/sessions/Sessions.ts", "../src/sessions/schema.ts", "../src/sessions/Session.ts", "../src/users/avatars/Avatars.ts", "../src/users/avatars/schema.ts", "../src/users/schema.ts", "../src/users/User.ts"],
4
- "sourcesContent": ["export function _ids<T extends { _id: string }>(iterable: Set<T> | T[]): string[] {\n\tif (iterable instanceof Set) {\n\t\tconst ids = [];\n\t\t\n\t\tfor (const object of iterable)\n\t\t\tids.push(object._id);\n\t\t\n\t\treturn ids;\n\t}\n\t\n\treturn iterable.map(object => object._id);\n}\n", "export function add<T>(array: T[], ...items: T[]): number {\n\t\n\tlet added = 0;\n\t\n\tfor (const item of items)\n\t\tif (!array.includes(item)) {\n\t\t\tarray.push(item);\n\t\t\tadded++;\n\t\t}\n\t\n\treturn added;\n}\n", "export function setPath<V>(object: Record<string, unknown>, path: string, value: V): null | V {\n\tif (object && path) {\n\t\tif (path.includes(\".\")) {\n\t\t\tconst keys = path.split(\".\");\n\t\t\tlet subObject: any = object;// eslint-disable-line @typescript-eslint/no-explicit-any\n\t\t\t\n\t\t\tfor (let i = 0; i < keys.length - 1; i++) {\n\t\t\t\tconst key = keys[i];\n\t\t\t\tconst subObjectValue = subObject[key];\n\t\t\t\t\n\t\t\t\tsubObject =\n\t\t\t\t\t(subObjectValue && typeof subObjectValue == \"object\") ?\n\t\t\t\t\t\tsubObjectValue :\n\t\t\t\t\t\t(subObject[key] = {});\n\t\t\t}\n\t\t\t\n\t\t\treturn (subObject[keys.at(-1)!] = value);\n\t\t}\n\t\t\n\t\treturn (object[path] = value) as V;\n\t}\n\t\n\treturn null;\n}\n", "import { setPath } from \"./setPath.js\";\n\n\nexport function assignPath<T extends Record<string, unknown>>(target: T, ...sources: Record<string, unknown>[]): T {\n\tfor (const source of sources)\n\t\tfor (const path in source)\n\t\t\tif (Object.hasOwn(source, path))\n\t\t\t\tsetPath(target, path, source[path]);\n\t\n\treturn target;\n}\n", "export function noop() { /**/ }\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n\ntype Value<T> = PromiseLike<T> | T;\ntype Resolve<T> = (value: Value<T>) => void;\ntype Reject = (reason?: any) => void;\n\ntype Options = {\n\tsignal?: AbortSignal;\n\ttimeout?: number;\n};\n\nconst nativesMap = new WeakMap<StatefulPromise<any>, { resolve: Resolve<any>; reject: Reject }>();\n\n\nexport class StatefulPromise<T> extends Promise<T> {\n\tconstructor(\n\t\texecutor?: (resolve: Resolve<T>, reject: Reject) => void,\n\t\toptions?: Options\n\t) {\n\t\tlet nativeResolve: Resolve<T>;\n\t\tlet nativeReject: Reject;\n\t\t\n\t\tsuper((resolve, reject) => {\n\t\t\tnativeResolve = resolve;\n\t\t\tnativeReject = reject;\n\t\t\t\n\t\t});\n\t\t\n\t\tnativesMap.set(this, { resolve: nativeResolve!, reject: nativeReject! });\n\t\t\n\t\tif (options?.signal)\n\t\t\tif (options.signal.aborted)\n\t\t\t\tthis.reject(new DOMException(\"Aborted\", \"AbortError\"));\n\t\t\telse {\n\t\t\t\tconst abortListener = () => this.reject(new DOMException(\"Aborted\", \"AbortError\"));\n\t\t\t\t\n\t\t\t\toptions.signal.addEventListener(\"abort\", abortListener);\n\t\t\t\t\n\t\t\t\tthis.finally(() => options.signal?.removeEventListener(\"abort\", abortListener));\n\t\t\t}\n\t\t\n\t\tif (typeof options?.timeout === \"number\" && Number.isFinite(options.timeout)) {\n\t\t\tconst timeout = setTimeout(() => this.reject(new DOMException(\"Timeout exceeded\", \"TimeoutError\")), options.timeout);\n\t\t\t\n\t\t\tthis.finally(() => clearTimeout(timeout));\n\t\t}\n\t\t\n\t\texecutor?.(this.resolve, this.reject);\n\t\t\n\t}\n\t\n\tisPending = true;\n\tisFulfilled = false;\n\tisRejected = false;\n\t\n\tstate: \"fulfilled\" | \"pending\" | \"rejected\" = \"pending\";\n\t\n\tresult?: T | unknown;\n\t\n\treadonly resolve = (value: Value<T>) => {\n\t\t\n\t\tif (this.isPending) {\n\t\t\tthis.isPending = false;\n\t\t\tthis.isFulfilled = true;\n\t\t\tthis.state = \"fulfilled\";\n\t\t\tthis.result = value;\n\t\t\t\n\t\t\tconst native = nativesMap.get(this);\n\t\t\t\n\t\t\tif (native) {\n\t\t\t\tnative.resolve.call(this, value);\n\t\t\t\tnativesMap.delete(this);\n\t\t\t}\n\t\t}\n\t\t\n\t};\n\t\n\treadonly reject = (reason?: any) => {\n\t\t\n\t\tif (this.isPending) {\n\t\t\tthis.isPending = false;\n\t\t\tthis.isRejected = true;\n\t\t\tthis.state = \"rejected\";\n\t\t\tthis.result = reason;\n\t\t\t\n\t\t\tconst native = nativesMap.get(this);\n\t\t\t\n\t\t\tif (native) {\n\t\t\t\tnative.reject.call(this, reason);\n\t\t\t\tnativesMap.delete(this);\n\t\t\t}\n\t\t}\n\t\t\n\t};\n\t\n\t\n\tstatic resolved<U>(value: U): StatefulPromise<U> {\n\t\treturn new StatefulPromise<U>(resolve => resolve(value));\n\t}\n\t\n\tstatic rejected(reason: unknown): StatefulPromise<never> {\n\t\treturn new StatefulPromise((_, reject) => reject(reason));\n\t}\n\t\n}\n", "import { noop } from \"./noop.js\";\nimport { StatefulPromise } from \"./StatefulPromise.js\";\n\n\ntype Callback = (...args: any[]) => unknown;// eslint-disable-line @typescript-eslint/no-explicit-any\ntype FunctionOrBoolean = (() => unknown) | boolean;\ntype Options = { leading?: FunctionOrBoolean; maxWait?: number; trailing?: FunctionOrBoolean };\n\ntype DebouncedFunction<C extends Callback> = {\n\t(this: ThisParameterType<C>, ...args: Parameters<C>): Promise<Awaited<ReturnType<C>>>;\n};\n\nexport type Debounced<C extends Callback, R extends ReturnType<C>> = DebouncedFunction<C> & {\n\tcallback: C;\n\tpromise: StatefulPromise<R>;\n\tresolve: (value: R) => void;\n\treject: (reason?: unknown) => void;\n\trun(): Promise<R>;\n\tclear(shouldRun?: boolean): Promise<void>;\n};\n\n\nexport function debounce<C extends Callback, R extends ReturnType<C>>(callback: C, limit = 0, options: Options = {}) {\n\tlet { leading = false, trailing = true } = options;\n\tconst { maxWait = Infinity } = options;\n\t\n\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\tlet maxWaitTimeout: ReturnType<typeof setTimeout> | undefined;\n\tlet end: number | undefined;\n\tlet context: ThisParameterType<C>;\n\tlet args: unknown[];\n\tlet initial: FunctionOrBoolean;\n\tlet final: FunctionOrBoolean;\n\tlet result: R;\n\t\n\tconst expired = async () => {\n\t\t\n\t\tconst n = Date.now();\n\t\t\n\t\tif (n >= end!) {\n\t\t\ttimeout = undefined;\n\t\t\tend = undefined;\n\t\t\t\n\t\t\tclearTimeout(maxWaitTimeout);\n\t\t\tmaxWaitTimeout = undefined;\n\t\t\t\n\t\t\tif (typeof final == \"function\")\n\t\t\t\tawait final();\n\t\t\t\n\t\t\tdebounced.resolve(result);\n\t\t\t\n\t\t\tinitial = leading;\n\t\t} else {\n\t\t\tclearTimeout(timeout);\n\t\t\ttimeout = setTimeout(expired, end! - n);\n\t\t}\n\t\t\n\t};\n\t\n\tconst maxWaitExpired = Number.isFinite(maxWait) ? () => {\n\t\t\n\t\tif (final === run)\n\t\t\tfinal = false;\n\t\t\n\t\trun();\n\t\t\n\t\tmaxWaitTimeout = setTimeout(maxWaitExpired as TimerHandler, maxWait);\n\t\t\n\t} : null;\n\t\n\tasync function run() {\n\t\ttry {\n\t\t\tresult = await callback.apply(context, args) as R;\n\t\t\t\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tdebounced.reject(error);\n\t\t\t\n\t\t\tthrow error;\n\t\t}\n\t}\n\t\n\tif (leading && typeof leading == \"boolean\")\n\t\tleading = run;\n\tinitial = leading;\n\t\n\tif (trailing && typeof trailing == \"boolean\")\n\t\ttrailing = run;\n\tfinal = trailing;\n\t\n\tconst debounced: Debounced<C, R> = Object.assign(function (..._args) {\n\t\targs = _args;\n\t\tcontext = this;// eslint-disable-line no-invalid-this\n\t\t\n\t\tend = Date.now() + limit;\n\t\tfinal = trailing;\n\t\t\n\t\tif (!debounced.promise.isPending)\n\t\t\tdebounced.promise = new StatefulPromise<R>((resolve, reject) => {\n\t\t\t\tdebounced.resolve = resolve;\n\t\t\t\tdebounced.reject = reject;\n\t\t\t\t\n\t\t\t\tif (typeof initial == \"function\") {\n\t\t\t\t\tinitial();\n\t\t\t\t\t\n\t\t\t\t\tinitial = false;\n\t\t\t\t\t\n\t\t\t\t\tif (final === run)\n\t\t\t\t\t\tfinal = false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (!timeout) {\n\t\t\t\t\ttimeout = setTimeout(expired, limit);\n\t\t\t\t\t\n\t\t\t\t\tif (maxWaitExpired)\n\t\t\t\t\t\tmaxWaitTimeout = setTimeout(maxWaitExpired, maxWait);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});\n\t\t\n\t\treturn debounced.promise;\n\t} as DebouncedFunction<C>, {\n\t\tcallback,\n\t\tpromise: StatefulPromise.resolved(undefined as unknown as R),\n\t\tresolve: noop,\n\t\treject: noop,\n\t\trun,\n\t\tclear: async (shouldRun?: boolean) => {\n\t\t\t\n\t\t\tclearTimeout(timeout);\n\t\t\ttimeout = undefined;\n\t\t\t\n\t\t\tclearTimeout(maxWaitTimeout);\n\t\t\tmaxWaitTimeout = undefined;\n\t\t\t\n\t\t\tdebounced.resolve(shouldRun ? await run() : result);\n\t\t\t\n\t\t}\n\t});\n\t\n\treturn debounced;\n}\n\n\ndebounce.noop = Object.assign(() => { /**/ }, {\n\tcallback: noop,\n\tpromise: StatefulPromise.resolved(undefined), // eslint-disable-line unicorn/no-useless-undefined\n\tresolve: noop,\n\treject: noop,\n\trun: noop,\n\tclear: noop\n}) as Debounced<() => void, void>;\n\n\nexport function throttle(callback: Callback, limit?: number, options?: Options) {\n\treturn debounce(callback, limit, {\n\t\tmaxWait: limit,\n\t\tleading: true,\n\t\ttrailing: true,\n\t\t...options\n\t});\n}\n", "export function deletePath(object: Record<string, unknown>, path: string): boolean {\n\tif (object && path) {\n\t\tif (path.includes(\".\")) {\n\t\t\tconst keys = path.split(\".\");\n\t\t\tlet subObject: any = object; // eslint-disable-line @typescript-eslint/no-explicit-any\n\t\t\t\n\t\t\tfor (let i = 0; i < keys.length - 1; i++) {\n\t\t\t\tconst key = keys[i];\n\t\t\t\tconst subObjectValue = subObject[key];\n\t\t\t\t\n\t\t\t\tif (subObjectValue && typeof subObjectValue === \"object\")\n\t\t\t\t\tsubObject = subObjectValue;\n\t\t\t\telse\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tconst lastKey = keys.at(-1)!;\n\t\t\t\n\t\t\treturn lastKey in subObject && delete subObject[lastKey];\n\t\t}\n\t\t\n\t\treturn path in object && delete object[path];\n\t}\n\t\n\treturn false;\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n\n\nexport function deleteProps(object: null | undefined, keys: any): null;\nexport function deleteProps<O extends object, K extends readonly (keyof O | number | string | symbol)[]>(object: O, keys: K): Omit<O, K[number]>;\nexport function deleteProps<O extends object, K extends readonly (keyof O | number | string | symbol)[]>(object: O, keys: K) {\n\tif (object) {\n\t\tfor (const key of keys)\n\t\t\tdelete object[key as keyof O];\n\t\t\n\t\treturn object as Omit<O, K[number]>;\n\t}\n\t\n\treturn null;\n}\n", "export function empty<O extends object>(object: O) {\n\t// eslint-disable-next-line guard-for-in\n\tfor (const key in object)\n\t\tdelete object[key as keyof O];\n\t\n\treturn object;\n}\n", "export class EmptyArray extends Array {\n\tconstructor() {\n\t\tsuper();\n\t\t\n\t\tObject.freeze(this);\n\t\t\n\t}\n\t\n\tpush() {\n\t\treturn 0;\n\t}\n\t\n\tunshift() {\n\t\treturn 0;\n\t}\n\t\n\tsplice() {\n\t\treturn [];\n\t}\n\t\n}\n", "export class EmptySet extends Set {\n\t// eslint-disable-next-line no-useless-constructor\n\tconstructor() {\n\t\tsuper();\n\t\t\n\t}\n\t\n\tadd() {\n\t\treturn this;\n\t}\n\t\n}\n", "/* eslint-disable unicorn/prevent-abbreviations, unicorn/custom-error-definition */\n\n\ntype Payload = Record<string, unknown>;\n\ntype PayloadWithMessage = Payload & {\n\tmessage: string;\n};\n\n\nexport class Err extends Error {\n\tconstructor(payload: PayloadWithMessage);\n\tconstructor(message: string, tag: string | null, payload?: Payload);\n\tconstructor(message: string, payload?: Payload);\n\tconstructor(message: PayloadWithMessage | string, tag: Payload | string | null = null, payload?: Payload) {\n\t\tif (typeof message == \"object\") {\n\t\t\tpayload = message;\n\t\t\tmessage = payload.message as string;\n\t\t\tdelete payload.message;\n\t\t\ttag = null;\n\t\t} else if (tag && typeof tag == \"object\") {\n\t\t\tpayload = tag;\n\t\t\ttag = null;\n\t\t}\n\t\t\n\t\tsuper(message);\n\t\t\n\t\tthis.tag = tag;\n\t\t\n\t\tif (payload)\n\t\t\tObject.assign(this, payload);\n\t\t\n\t}\n\t\n\tname = \"Err-or\";\n\t\n\ttag: string | null;\n\t\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n\n\nexport function getAll<V>(map: Map<any, V>, keys: any[], onlyExisting: true): V[];\nexport function getAll<V>(map: Map<any, V>, keys: any[], onlyExisting?: false): (V | undefined)[];\nexport function getAll<V>(map: Map<any, V>, keys: any[], onlyExisting = false) {\n\t\n\tconst items = [];\n\t\n\tif (onlyExisting)\n\t\tfor (const key of keys) {\n\t\t\tconst item = map.get(key);\n\t\t\tif (item !== undefined)\n\t\t\t\titems.push(item);\n\t\t}\n\telse\n\t\tfor (const key of keys)\n\t\t\titems.push(map.get(key));\n\t\n\treturn items;\n}\n", "export function getPath(object: Record<string, unknown>, path: string): unknown {\n\tif (path) {\n\t\tif (path.includes(\".\")) {\n\t\t\tlet subObject: any = object;// eslint-disable-line @typescript-eslint/no-explicit-any\n\t\t\t\n\t\t\tfor (const key of path.split(\".\")) {\n\t\t\t\tsubObject = subObject?.[key];\n\t\t\t\t\n\t\t\t\tif (subObject === undefined)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\treturn subObject;\n\t\t}\n\t\t\n\t\treturn object[path];\n\t}\n\t\n\treturn object;\n}\n", "export function hasAny<K, V>(mapOrSet: Map<K, V> | Set<K>, items: K[] | Set<K>) {\n\tfor (const item of items)\n\t\tif (mapOrSet.has(item))\n\t\t\treturn true;\n\t\n\treturn false;\n}\n", "export function howmuch(number: [] | number, one: string, two: string, five: boolean | string, shouldPrintNumber = true) {\n\tif (Array.isArray(number))\n\t\tnumber = number.length;\n\t\n\tif (typeof five != \"string\") {\n\t\tshouldPrintNumber = five ?? true;\n\t\tfive = two;\n\t}\n\t\n\t\n\treturn (shouldPrintNumber ? `${number}\u00A0` : \"\") + howmuch.raw(number, one, two, five);\n}\n\nhowmuch.raw = (number: number, one: string, two: string, five = two) => {\n\tnumber = Math.abs(number);\n\tconst u = number % 10;\n\tconst d = number % 100;\n\t\n\treturn (\n\t\t(u === 1 && d !== 11) ?\n\t\t\tone :\n\t\t\t((u >= 2 && u <= 4) && !(d >= 12 && d <= 15)) ?\n\t\t\t\ttwo :\n\t\t\t\tfive\n\t);\n};\n", "export function intersection<I>(...iterables: (I[] | Set<I>)[]): I[] {\n\t\n\tconst intersectionArray = [];\n\t\n\tif (iterables.length) {\n\t\tconst [ firstIterable, ...otherIterables ] = iterables;\n\t\t\n\t\tmainLoop: for (const item of firstIterable) {\n\t\t\tfor (const otherIterable of otherIterables)\n\t\t\t\tif (otherIterable instanceof Set ? !otherIterable.has(item) : !otherIterable.includes(item))\n\t\t\t\t\tcontinue mainLoop;\n\t\t\tintersectionArray.push(item);\n\t\t}\n\t}\n\t\n\treturn intersectionArray;\n}\n", "export function pick<O extends object, K extends keyof O>(object: O, keys: K[]) {\n\t\n\tconst picked: Partial<Pick<O, K>> = {};\n\t\n\tfor (const key of keys)\n\t\tif (key in object)\n\t\t\tpicked[key] = object[key];\n\t\n\treturn picked as Pick<O, K>;\n}\n", "export function reAdd<S extends Set<I>, I>(set: S, item: I) {\n\tset.delete(item);\n\tset.add(item);\n\t\n\treturn set;\n}\n", "export function removeAll<T>(array: T[], items: T[]): number {\n\t\n\tlet i,\n\t\tremoved = 0;\n\t\n\tfor (const item of items)\n\t\twhile ((i = array.indexOf(item)) > -1) {\n\t\t\tarray.splice(i, 1);\n\t\t\tremoved++;\n\t\t}\n\t\n\treturn removed;\n}\n", "export function removeOne<T>(array: T[], item: T): boolean {\n\tconst i = array.indexOf(item);\n\tif (i > -1) {\n\t\tarray.splice(i, 1);\n\t\t\n\t\treturn true;\n\t}\n\t\n\treturn false;\n}\n", "export function sort<I>(set: Set<I>, compareFn?: ((a: I, b: I) => number)) {\n\tfor (const item of [ ...set ].sort(compareFn)) {\n\t\tset.delete(item);\n\t\tset.add(item);\n\t}\n\t\n\treturn set;\n}\n", "export function union<I>(...iterables: I[][]): I[] {\n\treturn [ ...new Set(iterables.flat()) ];\n}\n", "export function without<I>(array: I[], arrayToExclude: I[]): I[] {\n\treturn array.filter(item => !arrayToExclude.includes(item));\n}\n", "import { Err } from \"@nesvet/n\";\n\n\ntype Payload = Record<string, unknown>;\n\n\nexport class AbilityError extends Err {\n\tconstructor(payload?: Payload);\n\tconstructor(longId: string, payload?: Payload);\n\tconstructor(longId?: Payload | string, payload?: Payload) {\n\t\tif (typeof longId == \"object\") {\n\t\t\tpayload = longId;\n\t\t\tlongId = undefined;\n\t\t}\n\t\t\n\t\tsuper(\"User lacks ability\", \"lacksability\", {\n\t\t\t...longId && { ability: longId },\n\t\t\t...payload\n\t\t});\n\t\t\n\t}\n\t\n\tname = \"AbilityError\";\n\t\n}\n", "import type { AbilitySchema as OriginalAbilitySchema } from \"insite-common\";\n\n\ntype AbilityParamItem = string;\nexport type AbilityParamItems = AbilityParamItem[];\nexport type AbilityParamNumber = number;\nexport type AbilityParam = AbilityParamItems | AbilityParamNumber;\n\nexport type AbilityWithParams = Record<string, AbilityParam>;\nexport type AbilityObject = Record<string, Ability | AbilityParam>;\nexport type AbilityBoolean = true;\nexport type Ability = AbilityBoolean | { [key: string]: Ability | AbilityParam };\n\nexport type AbilitySchema = Omit<OriginalAbilitySchema, \"abilities\"> & {\n\tlevel: number;\n\tlongId: string;\n\tabilities?: AbilitySchema[];\n};\n\nexport type GenericAbilities = Record<string, Ability>;\n\nexport function isAbilityObject(value: Ability): value is AbilityObject {\n\treturn typeof value == \"object\";\n}\n\nexport function isAbilityParamNumber(value: AbilityParam): value is AbilityParamNumber {\n\treturn typeof value == \"number\";\n}\n\nexport function isAbilityParamItems(value: AbilityParam): value is AbilityParamItems {\n\treturn Array.isArray(value);\n}\n", "import {\n\tadd,\n\tassignPath,\n\tdeletePath,\n\tempty,\n\tgetPath,\n\tintersection,\n\tpick,\n\tsetPath\n} from \"@nesvet/n\";\nimport type { Abilities, AbilitiesSchema, AbilityParamSchema } from \"insite-common\";\nimport {\n\tisAbilityObject,\n\tisAbilityParamItems,\n\tisAbilityParamNumber,\n\ttype Ability,\n\ttype AbilityObject,\n\ttype AbilityParam,\n\ttype AbilityParamItems,\n\ttype AbilityParamNumber,\n\ttype AbilitySchema,\n\ttype GenericAbilities\n} from \"./types\";\n\n\nconst schemaParentMap = new Map<AbilitySchema, AbilitySchema | null>();\n\n\nexport class AbilitiesMap<AS extends AbilitiesSchema> extends Map<string, AbilitySchema> {\n\tconstructor(abilitiesSchema: AS) {\n\t\tsuper();\n\t\t\n\t\tfor (const subSchema of abilitiesSchema) {\n\t\t\tdelete subSchema.top;/* The first level is always top */\n\t\t\t\n\t\t\tthis.#hierarchical.push(subSchema as AbilitySchema);\n\t\t}\n\t\t\n\t\t(function parse(this: AbilitiesMap<AS>, schemas: AbilitiesSchema, parent: AbilitySchema | null, level: number) {\n\t\t\tfor (const schema of schemas as AbilitySchema[]) {\n\t\t\t\tschemaParentMap.set(schema, parent);\n\t\t\t\t\n\t\t\t\tschema.level = level;\n\t\t\t\t\n\t\t\t\tif (!parent || schema.top) {\n\t\t\t\t\tschema.longId = schema._id;\n\t\t\t\t\t\n\t\t\t\t\tif (this.has(schema._id))\n\t\t\t\t\t\tthrow new Error(`Top-level ability duplicate: ${schema._id}`);\n\t\t\t\t\t\n\t\t\t\t\tthis.set(schema._id, schema);\n\t\t\t\t} else\n\t\t\t\t\tschema.longId = parent ? `${parent.longId}.${schema._id}` : schema._id;\n\t\t\t\t\n\t\t\t\tif (schema.abilities)\n\t\t\t\t\tparse.call(this, schema.abilities, schema, level + 1);\n\t\t\t}\n\t\t\t\n\t\t}).call(this, abilitiesSchema, null, 0);\n\t\t\n\t}\n\t\n\t#hierarchical: AbilitySchema[] = [];\n\t\n\tget(longId: string, parent?: AbilitySchema | null) {\n\t\tconst subIds = longId.split(\".\");\n\t\tlet schema = parent ?? super.get(subIds.shift()!);\n\t\t\n\t\tif (schema && subIds.length)\n\t\t\tfor (const subId of subIds) {\n\t\t\t\tschema = schema?.abilities?.find(({ _id, top }) => !top && _id === subId);\n\t\t\t\tif (!schema)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\n\t\treturn schema;\n\t}\n\t\n\tgetSchema = this.get;\n\t\n\tgetParamSchema(longId: string, paramId: string) {\n\t\treturn this.get(longId)?.params?.find(({ _id }) => _id === paramId);\n\t}\n\t\n\tgetDefaultParam(longId: string, paramId: string, max?: boolean): AbilityParam | undefined;\n\tgetDefaultParam(schema: AbilityParamSchema, max?: boolean): AbilityParam;\n\tgetDefaultParam(schemaOrLongId: AbilityParamSchema | string, paramIdOrMax?: boolean | string, max?: boolean) {\n\t\tif (paramIdOrMax === undefined || typeof paramIdOrMax == \"boolean\")\n\t\t\tmax = paramIdOrMax;\n\t\t\n\t\tconst schema = typeof schemaOrLongId == \"string\" ? this.getParamSchema(schemaOrLongId, paramIdOrMax as string) : schemaOrLongId;\n\t\t\n\t\tif (schema)\n\t\t\tswitch (schema.type) {\n\t\t\t\tcase \"number\":\n\t\t\t\t\treturn max ?\n\t\t\t\t\t\t(schema.max ?? Infinity) :\n\t\t\t\t\t\t(schema.min ?? 0);\n\t\t\t\t\n\t\t\t\tcase \"items\":\n\t\t\t\t\treturn max ?\n\t\t\t\t\t\tschema.items.map(({ _id }) => _id) :\n\t\t\t\t\t\t[];\n\t\t\t}\n\t\t\n\t\treturn undefined;// eslint-disable-line unicorn/no-useless-undefined\n\t}\n\t\n\tgetDefaultAbility(schema: string, max?: boolean): Ability | undefined;\n\tgetDefaultAbility(schema: AbilitySchema, max?: boolean): Ability;\n\tgetDefaultAbility(schema: AbilitySchema | string, max: boolean = !schema): Ability | undefined {\n\t\tif (typeof schema == \"string\")\n\t\t\tschema = this.get(schema)!;\n\t\t\n\t\tif (schema) {\n\t\t\tif (schema.abilities || schema.params) {\n\t\t\t\tconst ability = {} as AbilityObject;\n\t\t\t\t\n\t\t\t\tif (schema.params)\n\t\t\t\t\tfor (const paramSchema of schema.params)\n\t\t\t\t\t\tability[paramSchema._id] = this.getDefaultParam(paramSchema, max);\n\t\t\t\t\n\t\t\t\tif (max && schema.abilities)\n\t\t\t\t\tfor (const subSchema of schema.abilities)\n\t\t\t\t\t\tif (!subSchema.top)\n\t\t\t\t\t\t\tability[subSchema._id] = this.getDefaultAbility(subSchema, max);\n\t\t\t\t\n\t\t\t\treturn ability;\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn undefined;\n\t}\n\t\n\tgetDefaultAbilities(): Abilities<AS>;\n\tgetDefaultAbilities(schemas: AbilitySchema[], max?: boolean): Abilities<AS>;\n\tgetDefaultAbilities(schema: AbilitySchema, max?: boolean): Abilities<AS>;\n\tgetDefaultAbilities(longIds: string[], max?: boolean): Abilities<AS>;\n\tgetDefaultAbilities(longId: string, max?: boolean): Abilities<AS>;\n\tgetDefaultAbilities(schemasOrIds?: (AbilitySchema | string)[] | AbilitySchema | string, max: boolean = !schemasOrIds) {\n\t\t\n\t\tconst schemas = (\n\t\t\tschemasOrIds ?\n\t\t\t\t(Array.isArray(schemasOrIds) ? schemasOrIds : [ schemasOrIds ])\n\t\t\t\t\t.map(schema => (typeof schema == \"string\" ? this.get(schema) : schema))\n\t\t\t\t\t.filter(Boolean) as AbilitySchema[] :\n\t\t\t\t[ ...this.values() ]\n\t\t).sort((a, b) => a.level - b.level);\n\t\t\n\t\tconst schemaMaxMap = new Map<AbilitySchema, boolean>();\n\t\t\n\t\tfor (const schema of schemas) {\n\t\t\t(function resolve(_schema) {\n\t\t\t\tconst parentSchema = schemaParentMap.get(_schema);\n\t\t\t\t\n\t\t\t\tif (parentSchema) {\n\t\t\t\t\tresolve(parentSchema);\n\t\t\t\t\t\n\t\t\t\t\tif (!schemaMaxMap.has(parentSchema))\n\t\t\t\t\t\tschemaMaxMap.set(parentSchema, false);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t})(schema);\n\t\t\t\n\t\t\tif (max)\n\t\t\t\t(function resolve(_schema) {\n\t\t\t\t\tif (!schemaMaxMap.has(_schema))\n\t\t\t\t\t\tschemaMaxMap.set(_schema, true);\n\t\t\t\t\t\n\t\t\t\t\tif (_schema.abilities)\n\t\t\t\t\t\tfor (const subSchema of _schema.abilities)\n\t\t\t\t\t\t\tif (subSchema.top)\n\t\t\t\t\t\t\t\tresolve(subSchema);\n\t\t\t\t\t\n\t\t\t\t})(schema);\n\t\t\telse\n\t\t\t\tif (!schemaMaxMap.has(schema))\n\t\t\t\t\tschemaMaxMap.set(schema, false);\n\t\t}\n\t\t\n\t\treturn assignPath(\n\t\t\t{},\n\t\t\tObject.fromEntries(\n\t\t\t\t[ ...schemaMaxMap ]\n\t\t\t\t\t.map(([ schema, _max ]) => [ schema.longId, this.getDefaultAbility(schema, _max) ])\n\t\t\t)\n\t\t);\n\t}\n\t\n\tgetSchemeFor(abilities: GenericAbilities) {\n\t\tabilities = this.adjust(structuredClone(abilities));\n\t\t\n\t\treturn (function resolve(subSchemas: AbilitySchema[], subAbilities: GenericAbilities) {\n\t\t\tfor (let i = 0; i < subSchemas.length; i++) {\n\t\t\t\tconst schema = subSchemas[i];\n\t\t\t\tconst ability = schema.top ? abilities[schema._id] : subAbilities[schema._id];\n\t\t\t\t\n\t\t\t\tif (ability) {\n\t\t\t\t\tif (schema.params)\n\t\t\t\t\t\tfor (const paramSchema of schema.params) {\n\t\t\t\t\t\t\tconst abilityParam = (ability as AbilityObject)[paramSchema._id];\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tswitch (paramSchema.type) {\n\t\t\t\t\t\t\t\tcase \"number\":\n\t\t\t\t\t\t\t\t\tparamSchema.max = abilityParam as AbilityParamNumber;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tcase \"items\":\n\t\t\t\t\t\t\t\t\tparamSchema.items = paramSchema.items.filter(({ _id }) => (abilityParam as AbilityParamItems).includes(_id));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (schema.abilities) {\n\t\t\t\t\t\tresolve(schema.abilities, ability as GenericAbilities);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!schema.abilities.length)\n\t\t\t\t\t\t\tdelete schema.abilities;\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t\tsubSchemas.splice(i--, 1);\n\t\t\t}\n\t\t\t\n\t\t\treturn subSchemas;\n\t\t})(structuredClone(this.#hierarchical), abilities);\n\t}\n\t\n\tgetParam(abilities: GenericAbilities, longId: string, paramId: string) {\n\t\tif (this.getParamSchema(longId, paramId)) {\n\t\t\tconst value = getPath(abilities, `${longId}.${paramId}`) as AbilityParam;\n\t\t\t\n\t\t\tif (this.isParamFits(longId, paramId, value))\n\t\t\t\treturn value;\n\t\t\t\n\t\t\treturn this.getDefaultParam(longId, paramId)!;\n\t\t}\n\t\t\n\t\treturn undefined;// eslint-disable-line unicorn/no-useless-undefined\n\t}\n\t\n\tsetParam(abilities: GenericAbilities, longId: string, paramId: string, value: AbilityParam): Abilities<AS> {\n\t\tconst schema = this.getParamSchema(longId, paramId);\n\t\t\n\t\tif (!schema)\n\t\t\tthrow new Error(`No such ability param: ${longId}.${paramId}`);\n\t\t\n\t\tsetPath(abilities, `${longId}.${paramId}`, this.adjustParam(schema, value));\n\t\t\n\t\treturn abilities as Abilities<AS>;\n\t}\n\t\n\tisParamFits(longId: string, paramId: string, value: AbilityParam, referenceValue?: AbilityParam) {\n\t\tif (value !== undefined) {\n\t\t\tconst paramSchema = this.getParamSchema(longId, paramId);\n\t\t\t\n\t\t\tif (paramSchema)\n\t\t\t\tswitch (paramSchema.type) {\n\t\t\t\t\tcase \"number\":\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tisAbilityParamNumber(value) &&\n\t\t\t\t\t\t\t(paramSchema.min === undefined || value >= paramSchema.min) && (\n\t\t\t\t\t\t\t\treferenceValue === undefined ?\n\t\t\t\t\t\t\t\t\t(paramSchema.max === undefined || value <= paramSchema.max) :\n\t\t\t\t\t\t\t\t\tvalue <= (referenceValue as AbilityParamNumber)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t\t\n\t\t\t\t\tcase \"items\":\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tisAbilityParamItems(value) &&\n\t\t\t\t\t\t\tvalue.length === new Set(value).size && (\n\t\t\t\t\t\t\t\treferenceValue === undefined ?\n\t\t\t\t\t\t\t\t\tvalue.every(itemId => paramSchema.items.find(({ _id }) => _id === itemId)) :\n\t\t\t\t\t\t\t\t\tvalue.every(itemId => (referenceValue as AbilityParamItems).includes(itemId))\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tadjustParam(paramSchema: AbilityParamSchema, value: AbilityParam) {\n\t\tswitch (paramSchema.type) {\n\t\t\tcase \"number\":\n\t\t\t\treturn (\n\t\t\t\t\tisAbilityParamNumber(value) ?\n\t\t\t\t\t\tMath.max(\n\t\t\t\t\t\t\tMath.min(\n\t\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\t\tparamSchema.max ?? Infinity\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tparamSchema.min ?? 0\n\t\t\t\t\t\t) :\n\t\t\t\t\t\tparamSchema.min ?? 0\n\t\t\t\t);\n\t\t\t\n\t\t\tdefault/* paramSchema.type === \"items\" */:\n\t\t\t\treturn (\n\t\t\t\t\tisAbilityParamItems(value) ?\n\t\t\t\t\t\tintersection(paramSchema.items.map(item => item._id), value) :\n\t\t\t\t\t\t[]\n\t\t\t\t) as AbilityParamItems;\n\t\t}\n\t\t\n\t}\n\t\n\tadjust(abilities: GenericAbilities, parent?: AbilitySchema | null): Abilities<AS> {\n\t\tconst adjustedAbilities: GenericAbilities = {};\n\t\t\n\t\tfor (const [ _id, ability ] of Object.entries(abilities)) {\n\t\t\tconst schema = this.get(_id, parent);\n\t\t\t\n\t\t\tif (schema)\n\t\t\t\tif (schema.params || schema.abilities) {\n\t\t\t\t\tconst adjustedAbility: AbilityObject = {};\n\t\t\t\t\t\n\t\t\t\t\tif (schema.params)\n\t\t\t\t\t\tif (isAbilityObject(ability))\n\t\t\t\t\t\t\tfor (const paramSchema of schema.params)\n\t\t\t\t\t\t\t\tadjustedAbility[paramSchema._id] = this.adjustParam(paramSchema, ability[paramSchema._id] as AbilityParam);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tfor (const paramSchema of schema.params)\n\t\t\t\t\t\t\t\tadjustedAbility[paramSchema._id] = this.getDefaultParam(paramSchema);\n\t\t\t\t\t\n\t\t\t\t\tif (schema.abilities && isAbilityObject(ability))\n\t\t\t\t\t\tObject.assign(\n\t\t\t\t\t\t\tadjustedAbility,\n\t\t\t\t\t\t\tthis.adjust(\n\t\t\t\t\t\t\t\tpick(\n\t\t\t\t\t\t\t\t\tability,\n\t\t\t\t\t\t\t\t\tschema.abilities\n\t\t\t\t\t\t\t\t\t\t.filter(subSchema => !subSchema.top)\n\t\t\t\t\t\t\t\t\t\t.map(subSchema => subSchema._id)\n\t\t\t\t\t\t\t\t) as GenericAbilities,\n\t\t\t\t\t\t\t\tschema\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t\t\n\t\t\t\t\tadjustedAbilities[_id] = adjustedAbility;\n\t\t\t\t} else\n\t\t\t\t\tadjustedAbilities[_id] = true;\n\t\t}\n\t\t\n\t\treturn Object.assign(empty(abilities), adjustedAbilities) as Abilities<AS>;\n\t}\n\t\n\tmerge(target: GenericAbilities, source: GenericAbilities, parent?: AbilitySchema | null): Abilities<AS> {\n\t\tif (!parent) {\n\t\t\tthis.adjust(target);\n\t\t\tsource = this.adjust(structuredClone(source));\n\t\t}\n\t\t\n\t\tfor (const [ _id, ability ] of Object.entries(source)) {\n\t\t\tconst schema = this.get(_id, parent);\n\t\t\t\n\t\t\tif (schema && schema.isInheritable !== false)\n\t\t\t\tif (_id in target && (schema.params || schema.abilities)) {\n\t\t\t\t\tconst targetAbility = target[_id] as AbilityObject;\n\t\t\t\t\tconst sourceAbility = ability as AbilityObject;\n\t\t\t\t\t\n\t\t\t\t\tif (schema.params)\n\t\t\t\t\t\tfor (const paramSchema of schema.params)\n\t\t\t\t\t\t\tif (paramSchema.isInheritable !== false)\n\t\t\t\t\t\t\t\tswitch (paramSchema.type) {\n\t\t\t\t\t\t\t\t\tcase \"number\":\n\t\t\t\t\t\t\t\t\t\ttargetAbility[paramSchema._id] =\n\t\t\t\t\t\t\t\t\t\t\tMath.max(\n\t\t\t\t\t\t\t\t\t\t\t\ttargetAbility[paramSchema._id] as AbilityParamNumber,\n\t\t\t\t\t\t\t\t\t\t\t\tsourceAbility[paramSchema._id] as AbilityParamNumber\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tcase \"items\":\n\t\t\t\t\t\t\t\t\t\tadd(\n\t\t\t\t\t\t\t\t\t\t\ttargetAbility[paramSchema._id] as AbilityParamItems,\n\t\t\t\t\t\t\t\t\t\t\t...sourceAbility[paramSchema._id] as AbilityParamItems\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (schema.abilities)\n\t\t\t\t\t\tthis.merge(targetAbility as GenericAbilities, sourceAbility as GenericAbilities, schema);\n\t\t\t\t} else\n\t\t\t\t\ttarget[_id] = ability;\n\t\t}\n\t\t\n\t\treturn target as Abilities<AS>;\n\t}\n\t\n\thasAbility(abilities: GenericAbilities, longId: string) {\n\t\treturn Boolean(getPath(abilities, longId));\n\t}\n\t\n\tsetAbility(target: GenericAbilities, schema: AbilitySchema): Abilities<AS>;\n\tsetAbility(target: GenericAbilities, longId: string): Abilities<AS>;\n\tsetAbility(target: GenericAbilities, schemaOrLongId: AbilitySchema | string) {\n\t\tconst schema = typeof schemaOrLongId == \"string\" ? this.get(schemaOrLongId) : schemaOrLongId;\n\t\t\n\t\tif (!schema)\n\t\t\tthrow new Error(`No such ability: ${schemaOrLongId as string}`);\n\t\t\n\t\tthis.merge(target, this.getDefaultAbilities(schema));\n\t\t\n\t\treturn target as Abilities<AS>;\n\t}\n\t\n\tunsetAbility(target: GenericAbilities, schema: AbilitySchema): Abilities<AS>;\n\tunsetAbility(target: GenericAbilities, longId: string): Abilities<AS>;\n\tunsetAbility(target: GenericAbilities, schemaOrLongId: AbilitySchema | string) {\n\t\tconst schema = typeof schemaOrLongId == \"string\" ? this.get(schemaOrLongId) : schemaOrLongId;\n\t\t\n\t\tif (!schema)\n\t\t\tthrow new Error(`No such ability: ${schemaOrLongId as string}`);\n\t\t\n\t\t(function resolve(_schema) {\n\t\t\tdeletePath(target, _schema.longId);\n\t\t\t\n\t\t\tif (_schema.abilities)\n\t\t\t\tfor (const subSchema of _schema.abilities)\n\t\t\t\t\tresolve(subSchema);\n\t\t\t\n\t\t})(schema);\n\t\t\n\t\treturn target;\n\t}\n\t\n}\n", "import { Err } from \"@nesvet/n\";\n\n\ntype Payload = Record<string, unknown>;\n\n\nexport class RolesError extends Err {\n\tconstructor(roleId: string, payload?: Payload);\n\tconstructor(roleIds: string[], payload?: Payload);\n\tconstructor(stringOrArray: Payload | string[] | string, payload?: Payload) {\n\t\tsuper(`User lacks role${Array.isArray(stringOrArray) ? \"s\" : \"\"}`, \"lacksroles\", {\n\t\t\troles: Array.isArray(stringOrArray) ? stringOrArray : [ stringOrArray ],\n\t\t\t...payload\n\t\t});\n\t\t\n\t}\n\t\n\tname = \"RolesError\";\n\t\n}\n", "import type { Abilities, AbilitiesSchema } from \"insite-common\";\nimport { Roles } from \"./Roles\";\nimport { RoleDoc } from \"./types\";\n\n\nconst snapshots = new WeakMap();\n\n\nexport class Role<AS extends AbilitiesSchema> {\n\tconstructor(roles: Roles<AS>, roleDoc: RoleDoc) {\n\t\tthis.#roles = roles;\n\t\t\n\t\tthis._id = roleDoc._id;\n\t\troles.set(this._id, this);\n\t\t\n\t\tvoid this.update(roleDoc);\n\t\t\n\t}\n\t\n\t#roles;\n\t\n\t_id;\n\townInvolveIds!: string[];\n\townAbilities!: Abilities<AS>;\n\ttitle = \"\";\n\tdisplayTitle = \"\";\n\t_o = 0;\n\t\n\townInvolves: Role<AS>[] = [];\n\tinvolves = new Set<Role<AS>>();\n\tabilities: Abilities<AS> = {};\n\tinheritedAbilities: Abilities<AS> = {};\n\t\n\tupdate({ _id, involves: ownInvolveIds, abilities: ownAbilities, title, ...restProps }: Partial<RoleDoc>) {\n\t\tObject.assign(this, restProps);\n\t\t\n\t\tif (ownInvolveIds)\n\t\t\tthis.ownInvolveIds = ownInvolveIds;\n\t\t\n\t\tif (ownAbilities)\n\t\t\tthis.ownAbilities = ownAbilities as Abilities<AS>;\n\t\t\n\t\tif (title !== undefined) {\n\t\t\tthis.title = title;\n\t\t\tthis.displayTitle = title || this._id;\n\t\t}\n\t\t\n\t\tif (ownInvolveIds || ownAbilities) {\n\t\t\tconst snapshot = [\n\t\t\t\tthis.ownInvolveIds.join(\",\"),\n\t\t\t\tJSON.stringify(this.ownAbilities)\n\t\t\t].join(\"\\n\");\n\t\t\t\n\t\t\tif (snapshot !== snapshots.get(this)) {\n\t\t\t\tsnapshots.set(this, snapshot);\n\t\t\t\t\n\t\t\t\tif (this.#roles.users.isInited)\n\t\t\t\t\tthis.#roles.update();\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tdelete() {\n\t\t\n\t\tthis.#roles.delete(this._id);\n\t\t\n\t\tsnapshots.delete(this);\n\t\t\n\t\tthis.#roles.update();\n\t\t\n\t}\n\t\n}\n", "export const regexps = {\n\t_id: /^[\\dA-Fa-f]{24}$/,\n\temail: /^[^\\s@]{1,63}@[^\\s@]{1,63}\\.[^\\s@]{1,63}$/,\n\targon2: /^\\$argon2(?:i|d|id)\\$v=\\d+\\$m=\\d+,t=\\d+,p=\\d+(?:\\$[\\d+/A-Za-z]+){2}$/,\n\t// eslint-disable-next-line unicorn/better-regex\n\tsessionId: /^(?:[\\dA-Fa-f]{16,32}\\$[\\dA-Fa-f]{16,32}|[0-9a-f]{24}~[A-Za-z0-9_-]{43})$/, // (?:old_format|new_format) - leave just the new after some time\n\trole: /^[\\d_a-z-]{1,64}$/,\n\tip: /^(?:\\d{1,3}\\.){3}\\d{1,3}$/\n};\n", "import { CollectionSchema } from \"insite-db\";\nimport { regexps } from \"../lib\";\n\n\nexport const basisSchema: CollectionSchema = {\n\trequired: [\n\t\t\"_id\",\n\t\t\"involves\",\n\t\t\"abilities\",\n\t\t\"title\",\n\t\t\"description\",\n\t\t\"meta\",\n\t\t\"createdAt\"\n\t],\n\tproperties: {\n\t\t_id: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps.role.source,\n\t\t\tnot: { enum: [ \"root\" ] }\n\t\t},\n\t\tinvolves: {\n\t\t\tbsonType: \"array\",\n\t\t\tuniqueItems: true,\n\t\t\titems: {\n\t\t\t\tbsonType: \"string\",\n\t\t\t\tpattern: regexps.role.source,\n\t\t\t\tnot: { enum: [ \"root\" ] }\n\t\t\t},\n\t\t\tadditionalItems: false\n\t\t},\n\t\tabilities: {\n\t\t\tbsonType: \"object\"\n\t\t},\n\t\ttitle: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 256\n\t\t},\n\t\tdescription: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 10240\n\t\t},\n\t\tmeta: {\n\t\t\tbsonType: \"object\"\n\t\t},\n\t\tcreatedAt: {\n\t\t\tbsonType: \"number\"\n\t\t}\n\t},\n\tadditionalProperties: false\n};\n", "import {\n\tdeleteProps,\n\tgetAll,\n\tintersection,\n\treAdd,\n\tremoveAll\n} from \"@nesvet/n\";\nimport type { AbilitiesSchema } from \"insite-common\";\nimport type { ChangeStreamDocument, CollectionIndexes, WatchedCollection } from \"insite-db\";\nimport type { AbilityParam, GenericAbilities } from \"../abilities/types\";\nimport type { Users } from \"../users\";\nimport { Role } from \"./Role\";\nimport { basisSchema } from \"./schema\";\nimport type { NewRole, RoleDoc, RolesOptions } from \"./types\";\n\n\nconst indexes: CollectionIndexes = [\n\t[ { involves: 1 } ]\n];\n\nfunction preventDirectDelete() {\n\tthrow new Error(\"Direct usage of roles collection.deleteOne or .deleteMany is forbidden. Use roles.deleteRole instead.\");\n}\n\n\nexport class Roles<AS extends AbilitiesSchema> extends Map<string, Role<AS>> {\n\tconstructor(users: Users<AS>, options: RolesOptions = {}) {\n\t\tsuper();\n\t\t\n\t\tconst {\n\t\t\troot: rootProps,\n\t\t\t...initOptions\n\t\t} = options;\n\t\t\n\t\tthis.users = users;\n\t\tthis.collections = users.collections;\n\t\tthis.abilities = users.abilities;\n\t\t\n\t\tthis.root = new Role<AS>(this, {\n\t\t\t...rootProps,\n\t\t\t_id: \"root\",\n\t\t\tinvolves: [],\n\t\t\tabilities: this.abilities.getDefaultAbilities(),\n\t\t\ttitle: \"Root\",\n\t\t\tdescription: \"Root\",\n\t\t\tmeta: {},\n\t\t\tcreatedAt: Date.now()\n\t\t});\n\t\t\n\t\tthis.initOptions = initOptions;\n\t\t\n\t}\n\t\n\tusers;\n\tcollections;\n\tcollection!: WatchedCollection<RoleDoc> & {\n\t\t/** @deprecated Direct usage of roles collection.deleteOne is forbidden. Use roles.deleteRole instead. */\n\t\tdeleteOne: typeof preventDirectDelete;\n\t\t\n\t\t/** @deprecated Direct usage of roles collection.deleteMany is forbidden. Use roles.deleteRole instead. */\n\t\tdeleteMany: typeof preventDirectDelete;\n\t};\n\t\n\tabilities;\n\troot;\n\tprivate initOptions?;\n\t\n\tasync init() {\n\t\t\n\t\tif (!this.users.isInited) {\n\t\t\tconst {\n\t\t\t\tschema: customSchema,\n\t\t\t\tindexes: customIndexes,\n\t\t\t\tcollection: collectionOptions\n\t\t\t} = this.initOptions!;\n\t\t\t\n\t\t\tif (customSchema) {\n\t\t\t\tif (customSchema.required)\n\t\t\t\t\tremoveAll(customSchema.required as string[], basisSchema.required as string[]);\n\t\t\t\tif (customSchema.properties)\n\t\t\t\t\tdeleteProps(customSchema, Object.keys(basisSchema.properties!));\n\t\t\t}\n\t\t\t\n\t\t\tconst schema = {\n\t\t\t\t...basisSchema,\n\t\t\t\t...customSchema,\n\t\t\t\trequired: [ ...basisSchema.required as string[], ...customSchema?.required as string[] ?? [] ],\n\t\t\t\tproperties: { ...basisSchema.properties, ...customSchema?.properties }\n\t\t\t};\n\t\t\t\n\t\t\tthis.collection = Object.assign(\n\t\t\t\tawait this.collections.ensure<RoleDoc>(\"roles\", { ...collectionOptions, schema }),\n\t\t\t\t{\n\t\t\t\t\tdeleteOne: preventDirectDelete,\n\t\t\t\t\tdeleteMany: preventDirectDelete\n\t\t\t\t}\n\t\t\t);\n\t\t\t\n\t\t\tawait this.collection.ensureIndexes([ ...indexes, ...customIndexes ?? [] ]);\n\t\t\t\n\t\t\tawait this.#maintain();\n\t\t\t\n\t\t\tfor await (const roleDoc of this.collection.find()) {\n\t\t\t\tif (this.abilities.adjust(roleDoc.abilities))\n\t\t\t\t\tawait this.collection.updateOne({ _id: roleDoc._id }, { $set: { abilities: roleDoc.abilities } });\n\t\t\t\t\n\t\t\t\tthis.load(roleDoc);\n\t\t\t}\n\t\t\t\n\t\t\tthis.update();\n\t\t\t\n\t\t\tthis.collection.onChange(this.#handleCollectionChange);\n\t\t\t\n\t\t\tdelete this.initOptions;\n\t\t}\n\t\t\n\t}\n\t\n\tasync #maintain() {\n\t\t\n\t\tawait this.collection.updateMany({ meta: { $exists: false } }, { $set: { meta: {} } });\n\t\t\n\t}\n\t\n\t#handleCollectionChange = (next: ChangeStreamDocument<RoleDoc>) => {\n\t\tswitch (next.operationType) {\n\t\t\tcase \"insert\": {\n\t\t\t\tnew Role<AS>(this, next.fullDocument);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tcase \"replace\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.update(next.fullDocument);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"update\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.update(next.updateDescription.updatedFields!);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"delete\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.delete();\n\t\t}\n\t\t\n\t};\n\t\n\tload(roleDoc: RoleDoc) {\n\t\tnew Role<AS>(this, roleDoc);\n\t\t\n\t}\n\t\n\tresolve(role: Role<AS>, involvedBy: Role<AS>[]) {\n\t\tinvolvedBy = [ role, ...involvedBy ];\n\t\t\n\t\tfor (const involvedRoleId of role.ownInvolveIds) {\n\t\t\tconst involvedRole = this.get(involvedRoleId);\n\t\t\tif (involvedRole) {\n\t\t\t\tfor (const involvedByRole of involvedBy) {\n\t\t\t\t\treAdd(involvedByRole.involves, involvedRole);\n\t\t\t\t\tthis.abilities.merge(involvedByRole.inheritedAbilities as GenericAbilities, involvedRole.abilities as GenericAbilities);\n\t\t\t\t}\n\t\t\t\tif (involvedRole !== role)\n\t\t\t\t\tthis.resolve(involvedRole, involvedBy);\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tsorted: Role<AS>[] = [];\n\t\n\t#sortRoles(a: Role<AS>, b: Role<AS>) {\n\t\treturn (\n\t\t\t(b.involves.size - a.involves.size) || (\n\t\t\t\t(a.title && b.title) ?\n\t\t\t\t\ta.title > b.title ? 1 : a.title < b.title ? -1 : 0 :\n\t\t\t\t\ta.title ?\n\t\t\t\t\t\t-1 :\n\t\t\t\t\t\tb.title ?\n\t\t\t\t\t\t\t1 :\n\t\t\t\t\t\t\ta._id > b._id ?\n\t\t\t\t\t\t\t\t1 :\n\t\t\t\t\t\t\t\ta._id < b._id ?\n\t\t\t\t\t\t\t\t\t-1 :\n\t\t\t\t\t\t\t\t\t0\n\t\t\t)\n\t\t);\n\t}\n\t\n\tupdate() {\n\t\t\n\t\tconst array = [ ...this.values() ];\n\t\t\n\t\tthis.root.ownInvolveIds = [];\n\t\tfor (const role of array) {\n\t\t\tif (role !== this.root && !array.some(anotherRole => anotherRole.ownInvolveIds.includes(role._id)))\n\t\t\t\tthis.root.ownInvolveIds.push(role._id);\n\t\t\trole.involves.clear();\n\t\t\trole.abilities = structuredClone(role.ownAbilities);\n\t\t\trole.inheritedAbilities = {};\n\t\t}\n\t\t\n\t\tthis.root.involves.add(this.root);\n\t\tthis.resolve(this.root, []);\n\t\t\n\t\tfor (const role of array)\n\t\t\trole.ownInvolves = getAll(this, role.ownInvolveIds, true).sort(this.#sortRoles).reverse();\n\t\t\n\t\tconst sorted = [ this.root ];\n\t\t\n\t\tfor (let i = 0; i < sorted.length; i++) {\n\t\t\tconst role = sorted[i];\n\t\t\tfor (const involvedRole of role.ownInvolves) {\n\t\t\t\tconst involvedRoleIndex = sorted.indexOf(involvedRole);\n\t\t\t\tif (~involvedRoleIndex) {\n\t\t\t\t\tsorted.splice(involvedRoleIndex, 1);\n\t\t\t\t\ti--;\n\t\t\t\t}\n\t\t\t\tsorted.splice(i + 1, 0, involvedRole);\n\t\t\t}\n\t\t}\n\t\t\n\t\tlet _o = 0;\n\t\tfor (const role of sorted) {\n\t\t\tthis.abilities.merge(role.abilities as GenericAbilities, role.inheritedAbilities as GenericAbilities);\n\t\t\trole._o = _o++;\n\t\t}\n\t\t\n\t\tthis.sorted = sorted;\n\t\t\n\t\tif (this.users.isInited)\n\t\t\tthis.users.update(true);\n\t\t\n\t}\n\t\n\tasync create({ _id, involves, title, description, ...restProps }: NewRole) {\n\t\t\n\t\tawait this.collection.insertOne({\n\t\t\t_id,\n\t\t\tinvolves: involves || [],\n\t\t\tabilities: {},\n\t\t\ttitle: title ?? \"\",\n\t\t\tdescription: description ?? \"\",\n\t\t\tmeta: {},\n\t\t\t...deleteProps(restProps, [ \"abilities\" ]),\n\t\t\tcreatedAt: Date.now()\n\t\t});\n\t\t\n\t\treturn _id;\n\t}\n\t\n\tasync updateRole(roleId: string, updates: Omit<RoleDoc, \"abilities\" | \"createdAt\">) {\n\t\tconst role = this.get(roleId);\n\t\t\n\t\tif (!role)\n\t\t\treturn false;\n\t\t\n\t\tif (updates.involves) {\n\t\t\tremoveAll(updates.involves, [ roleId ]);\n\t\t\t\n\t\t\tfor (const involvedRoleId of updates.involves)\n\t\t\t\tif (this.get(involvedRoleId)?.involves.has(role))\n\t\t\t\t\tremoveAll(updates.involves, [ involvedRoleId ]);\n\t\t\t\n\t\t\tupdates.involves = this.cleanUpIds(updates.involves);\n\t\t}\n\t\t\n\t\tawait this.collection.updateOne({ _id: roleId }, { $set: updates });\n\t\t\n\t\treturn true;\n\t}\n\t\n\tdeleteRole(role: Role<AS> | string) {\n\t\tconst _id = typeof role == \"string\" ? role : role._id;\n\t\t\n\t\treturn this.collection.bulkWrite([\n\t\t\t{ updateMany: { filter: { involves: _id }, update: { $pullAll: { involves: [ _id ] } } } },\n\t\t\t{ deleteOne: { filter: { _id } } }\n\t\t]);\n\t}\n\t\n\tcleanUpIds(ids: string[]) {\n\t\tconst roles = intersection(this.sorted, getAll(this, ids, true));\n\t\t\n\t\tconst cleanedUpIds = [];\n\t\t\n\t\tfor (const role of roles)\n\t\t\tif (roles.every(anotherRole => anotherRole === role || !anotherRole.involves.has(role)))\n\t\t\t\tcleanedUpIds.push(role._id);\n\t\t\n\t\treturn cleanedUpIds;\n\t}\n\t\n\tasync setAbility(roleId: string, abilityLongId: string, set: boolean) {\n\t\tconst role = this.get(roleId);\n\t\t\n\t\tif (!role)\n\t\t\treturn false;\n\t\t\n\t\tawait this.collection.updateOne({ _id: roleId }, { $set: {\n\t\t\tabilities:\n\t\t\t\tset ?\n\t\t\t\t\tthis.abilities.setAbility(role.ownAbilities, abilityLongId) :\n\t\t\t\t\tthis.abilities.unsetAbility(role.ownAbilities, abilityLongId)\n\t\t} });\n\t\t\n\t\treturn true;\n\t}\n\t\n\tasync setAbilityParam(roleId: string, abilityLongId: string, paramId: string, value: AbilityParam) {\n\t\tconst role = this.get(roleId);\n\t\t\n\t\tif (!role)\n\t\t\treturn false;\n\t\t\n\t\tawait this.collection.updateOne({ _id: roleId }, { $set: {\n\t\t\tabilities: this.abilities.setParam(role.ownAbilities, abilityLongId, paramId, value)\n\t\t} });\n\t\t\n\t\treturn true;\n\t}\n\t\n}\n", "import { Err } from \"@nesvet/n\";\n\n\ntype Payload = Record<string, unknown>;\n\n\nexport class UnauthorizedError extends Err {\n\tconstructor(payload?: Payload) {\n\t\tsuper(\"Unauthorized\", \"unauthorized\", payload);\n\t\t\n\t}\n\t\n\tname = \"UnauthorizedError\";\n\t\n}\n\n\ntype SubordinationType = \"_id\" | \"permissiveIds\" | \"slaveIds\";\n\nexport class SubordinationError extends Err {\n\tconstructor(payload?: Payload);\n\tconstructor(type: SubordinationType, payload?: Payload);\n\tconstructor(type: SubordinationType, ids: string[] | string, payload?: Payload);\n\tconstructor(type?: Payload | SubordinationType, ids?: Payload | string[] | string, payload?: Payload) {\n\t\tswitch (arguments.length) {\n\t\t\tcase 1:\n\t\t\t\tpayload = type as Payload;\n\t\t\t\ttype = undefined;\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 2:\n\t\t\t\tpayload = ids as Payload;\n\t\t\t\tids = undefined;\n\t\t}\n\t\t\n\t\tsuper(\"Insubordination attempt\", \"subordination\", {\n\t\t\t...type && { type },\n\t\t\t...ids && { ids: Array.isArray(ids) ? ids : [ ids ] },\n\t\t\t...payload\n\t\t});\n\t\t\n\t}\n\t\n\tname = \"SubordinationError\";\n\t\n}\n\n\nexport class PermissionError extends Err {\n\tconstructor(payload?: Payload) {\n\t\tsuper(\"Insufficient permissions\", \"permissions\", payload);\n\t\t\n\t}\n\t\n\tname = \"PermissionError\";\n\t\n}\n", "import * as argon2 from \"argon2\";\nimport EventEmitter from \"eventemitter3\";\nimport {\n\t_ids,\n\tdeleteProps,\n\tremoveAll,\n\tStatefulPromise,\n\twithout\n} from \"@nesvet/n\";\nimport type { AbilitiesSchema } from \"insite-common\";\nimport {\n\tChangeStreamDocument,\n\tCollectionIndexes,\n\tCollections,\n\tnewObjectIdString,\n\tWatchedCollection\n} from \"insite-db\";\nimport { AbilitiesMap } from \"../abilities\";\nimport { Orgs } from \"../orgs\";\nimport { Org } from \"../orgs/Org\";\nimport { Roles } from \"../roles\";\nimport { Sessions } from \"../sessions\";\nimport { Session } from \"../sessions/Session\";\nimport type { SessionDoc } from \"../sessions/types\";\nimport { Avatars } from \"./avatars\";\nimport { basisSchema } from \"./schema\";\nimport { User } from \"./User\";\nimport type { NewUser, Options, UserDoc } from \"./types\";\n\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n\nconst indexes: CollectionIndexes = [\n\t[ { email: 1 }, { unique: true } ],\n\t[ { org: 1 } ]\n];\n\n\nexport class Users<AS extends AbilitiesSchema> extends Map<string, User<AS>> {\n\tconstructor(collections: Collections, options: Options<AS>) {\n\t\tsuper();\n\t\t\n\t\tconst eventEmitter = new EventEmitter() as EventEmitter & {\n\t\t\t_events: Record<string, object>;\n\t\t\t_eventsCount: number;\n\t\t};\n\t\tthis.#eventEmitter = eventEmitter;\n\t\tthis._events = eventEmitter._events;\n\t\tthis._eventsCount = eventEmitter._eventsCount;\n\t\tthis.emit = eventEmitter.emit;\n\t\tthis.on = eventEmitter.on as unknown as (...args: any[]) => this;\n\t\tthis.once = eventEmitter.once;\n\t\tthis.addListener = eventEmitter.addListener;\n\t\tthis.off = eventEmitter.off;\n\t\tthis.removeListener = eventEmitter.removeListener;\n\t\t\n\t\tthis.collections = collections;\n\t\t\n\t\tthis.abilities = new AbilitiesMap<AS>(options.abilities);\n\t\t\n\t\tthis.initOptions = options;\n\t\t\n\t\tvoid this.init();\n\t\t\n\t}\n\t\n\t#eventEmitter;\n\t_events;\n\t_eventsCount;\n\temit;\n\t\n\ton(event: \"user-create\" | \"user-is-online\" | \"user-permissions-change\", callback: (user: User<AS>) => void): this;\n\ton(event: \"session-delete\", callback: (session: Session<AS>) => void): this;\n\ton<T extends string | symbol>(event: T, callback: (...args: any[]) => void, context?: any) {\n\t\tthis.#eventEmitter.on(event, callback, context);\n\t\t\n\t\treturn this;\n\t}\n\t\n\tonce;\n\taddListener;\n\toff;\n\tremoveListener;\n\t\n\tprivate initOptions?;\n\t\n\tcollections;\n\tabilities;\n\t\n\tcollection!: WatchedCollection<UserDoc>;\n\troles!: Roles<AS>;\n\tsessions!: Sessions<AS>;\n\torgs!: Orgs<AS>;\n\tavatars!: Avatars<AS>;\n\t\n\tbyEmail = new Map();\n\tbySessionId = new Map();\n\tsorted: User<AS>[] = [];\n\t\n\tisSortRequired = false;\n\t\n\t#isPreinited = false;\n\t\n\tasync preinit() {\n\t\t\n\t\tif (!this.#isPreinited) {\n\t\t\tthis.#isPreinited = true;\n\t\t\t\n\t\t\tconst {\n\t\t\t\tindexes: customIndexes,\n\t\t\t\tschema: customSchema,\n\t\t\t\tinitialRoot: initialRootProps,\n\t\t\t\tcollection: collectionOptions\n\t\t\t} = this.initOptions!;\n\t\t\t\n\t\t\tif (customSchema) {\n\t\t\t\tif (customSchema.required)\n\t\t\t\t\tremoveAll(customSchema.required as string[], basisSchema.required as string[]);\n\t\t\t\tif (customSchema.properties)\n\t\t\t\t\tdeleteProps(customSchema, Object.keys(basisSchema.properties!));\n\t\t\t}\n\t\t\t\n\t\t\tconst schema = {\n\t\t\t\t...basisSchema,\n\t\t\t\t...customSchema,\n\t\t\t\trequired: [ ...basisSchema.required as string [], ...customSchema?.required as string[] ?? [] ],\n\t\t\t\tproperties: { ...basisSchema.properties, ...customSchema?.properties }\n\t\t\t};\n\t\t\t\n\t\t\tthis.collection = await this.collections.ensure<UserDoc>(\"users\", { ...collectionOptions, schema });\n\t\t\t\n\t\t\tawait this.collection.ensureIndexes([ ...indexes, ...customIndexes ?? [] ]);\n\t\t\t\n\t\t\tif (!await this.collection.countDocuments({ roles: \"root\" }))\n\t\t\t\tawait this.create({\n\t\t\t\t\temail: process.env.INSITE_ROOT_EMAIL ?? \"insite@root.email\",\n\t\t\t\t\tpassword: process.env.INSITE_ROOT_PASSWORD ?? \"inSiteRootPassword\",\n\t\t\t\t\tname: { first: \"Root\" },\n\t\t\t\t\tjob: \"Root\",\n\t\t\t\t\t...initialRootProps,\n\t\t\t\t\troles: [ \"root\" ],\n\t\t\t\t\torg: null,\n\t\t\t\t\tmeta: {}\n\t\t\t\t});\n\t\t\t\n\t\t\tawait this.#maintain();\n\t\t\t\n\t\t\tfor await (const userDoc of this.collection.find())\n\t\t\t\tthis.load(userDoc);\n\t\t}\n\t\t\n\t}\n\t\n\tasync #maintain() {\n\t\t\n\t\tawait this.collection.updateMany({ meta: { $exists: false } }, { $set: { meta: {} } });\n\t\t\n\t}\n\t\n\tisInited = false;\n\t\n\tprotected async init() {\n\t\t\n\t\tif (!this.isInited) {\n\t\t\tconst {\n\t\t\t\troles: rolesOptions,\n\t\t\t\torgs: orgsOptions,\n\t\t\t\tsessions: sessionsOptions,\n\t\t\t\tavatars: avatarsOptions,\n\t\t\t\tcollection: { quiet } = {}\n\t\t\t} = this.initOptions!;\n\t\t\t\n\t\t\tthis.roles = new Roles<AS>(this, { ...rolesOptions, collection: { quiet, ...rolesOptions?.collection } });\n\t\t\tthis.orgs = new Orgs<AS>(this, { ...orgsOptions, collection: { quiet, ...orgsOptions?.collection } });\n\t\t\tthis.sessions = new Sessions<AS>(this, { ...sessionsOptions, collection: { quiet, ...sessionsOptions?.collection } });\n\t\t\tthis.avatars = new Avatars<AS>(this, { ...avatarsOptions, collection: { quiet, ...avatarsOptions?.collection } });\n\t\t\t\n\t\t\tawait this.roles.init();\n\t\t\tawait this.orgs.preinit();\n\t\t\tawait this.preinit();\n\t\t\tthis.orgs.init();\n\t\t\tawait this.avatars.init();\n\t\t\t\n\t\t\tthis.update(true);\n\t\t\t\n\t\t\tthis.collection.onChange(this.#handleCollectionChange);\n\t\t\t\n\t\t\tawait this.sessions.init();\n\t\t\t\n\t\t\tdelete this.initOptions;\n\t\t\t\n\t\t\tthis.isInited = true;\n\t\t\t\n\t\t\tthis.#initPromise.resolve(this);\n\t\t}\n\t\t\n\t}\n\t\n\t#handleCollectionChange = (next: ChangeStreamDocument<UserDoc>) => {\n\t\tswitch (next.operationType) {\n\t\t\tcase \"insert\":\n\t\t\t\tnew User<AS>(this, next.fullDocument);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"replace\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.update(next.fullDocument);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"update\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.update(next.updateDescription.updatedFields!);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"delete\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.delete();\n\t\t}\n\t\t\n\t};\n\t\n\t\n\tload(userDoc: UserDoc) {\n\t\tnew User<AS>(this, userDoc);\n\t\t\n\t}\n\t\n\tsort() {\n\t\t\n\t\tthis.isSortRequired = false;\n\t\t\n\t\tthis.sorted = [ ...this.values() ].sort((a, b) => a.name.last > b.name.last ? 1 : a.name.last < b.name.last ? -1 : 0);\n\t\t\n\t}\n\t\n\tupdate(shouldUpdateRoles?: boolean) {\n\t\tif (shouldUpdateRoles)\n\t\t\tfor (const user of this.values())\n\t\t\t\tuser.updateRoles();\n\t\t\n\t\tfor (const user of this.values())\n\t\t\tuser.updatePermissions();\n\t\t\n\t\tif (this.isSortRequired)\n\t\t\tthis.sort();\n\t\t\n\t}\n\t\n\t#initPromise = new StatefulPromise<this>();\n\t\n\twhenReady() {\n\t\treturn this.#initPromise;\n\t}\n\t\n\tasync create({ email, password, roles, name, org, job, ...restProps }: NewUser) {\n\t\tif (this.byEmail.has(email))\n\t\t\tthrow new Error(\"User exists\");\n\t\t\n\t\tconst _id = newObjectIdString();\n\t\t\n\t\tawait this.collection.insertOne({\n\t\t\t_id,\n\t\t\temail,\n\t\t\tpassword: await argon2.hash(password),\n\t\t\troles: this.isInited ? this.roles.cleanUpIds(roles) : roles,\n\t\t\tname: {\n\t\t\t\tfirst: name.first ?? \"\",\n\t\t\t\tmiddle: name.middle ?? \"\",\n\t\t\t\tlast: name.last ?? \"\"\n\t\t\t},\n\t\t\torg: org ?? null,\n\t\t\tjob: job ?? \"\",\n\t\t\tmeta: {},\n\t\t\t...deleteProps(restProps, [ \"_id\" ]),\n\t\t\tcreatedAt: Date.now()\n\t\t});\n\t\t\n\t\treturn _id;\n\t}\n\t\n\tasync updateUser(_id: string, updates: Omit<UserDoc, \"_id\" | \"createdAt\">, byUser?: User<AS>) {\n\t\tconst user = this.get(_id)!;\n\t\t\n\t\tif (!user)\n\t\t\treturn false;\n\t\t\n\t\tif (updates.roles)\n\t\t\tupdates.roles =\n\t\t\t\tuser.isRoot ?\n\t\t\t\t\t[ \"root\" ] :\n\t\t\t\t\tthis.roles.cleanUpIds(\n\t\t\t\t\t\tbyUser ?\n\t\t\t\t\t\t\twithout(user.ownRoleIds, byUser.slaveRoleIds).concat(updates.roles) :\n\t\t\t\t\t\t\tupdates.roles\n\t\t\t\t\t);\n\t\t\n\t\tawait this.collection.updateOne({ _id }, { $set: updates });\n\t\t\n\t\treturn true;\n\t}\n\t\n\tasync changePassword(_id: string, newPassword: string) {\n\t\tif (!this.has(_id))\n\t\t\tthrow new Error(\"usernotfound\");\n\t\t\n\t\tif (!newPassword)\n\t\t\tthrow new Error(\"emptypasswordisnotallowed\");\n\t\t\n\t\tawait Promise.all([\n\t\t\tthis.collection.updateOne({ _id }, { $set: { password: await argon2.hash(newPassword) } }),\n\t\t\tthis.sessions.collection.deleteMany({ user: _id })\n\t\t]);\n\t\t\n\t}\n\t\n\tasync login(email: string, password: string, sessionProps: Partial<SessionDoc>) {\n\t\tconst user = this.byEmail.get(email);\n\t\t\n\t\tif (!user)\n\t\t\tthrow new Error(\"usernotfound\");\n\t\t\n\t\tif (!await argon2.verify(user.password, password))\n\t\t\tthrow new Error(\"incorrectpassword\");\n\t\t\n\t\tif (!user.abilities.login)\n\t\t\tthrow new Error(\"userisnotabletologin\");\n\t\t\n\t\treturn this.sessions.create(user, sessionProps);\n\t}\n\t\n\tlogout(session: Session<AS>) {\n\t\tsession.delete();\n\t\t\n\t\treturn this.sessions.collection.deleteOne({ _id: session._id });\n\t}\n\t\n\t#sortUsersAndOrgs(a: Org<AS> | User<AS>, b: Org<AS> | User<AS>) {\n\t\treturn (\n\t\t\t(a instanceof User && b instanceof User) ?\n\t\t\t\t(a.name.last && b.name.last) ?\n\t\t\t\t\ta.name.last > b.name.last ?\n\t\t\t\t\t\t1 :\n\t\t\t\t\t\ta.name.last < b.name.last ? -1 : 0 :\n\t\t\t\t\t(!a.name.last && !b.name.last) ?\n\t\t\t\t\t\ta.displayLabel > b.displayLabel ?\n\t\t\t\t\t\t\t1 :\n\t\t\t\t\t\t\ta.displayLabel < b.displayLabel ? -1 : 0 :\n\t\t\t\t\t\ta.name.last ? -1 : 1 :\n\t\t\t\t(a instanceof Org && b instanceof Org) ?\n\t\t\t\t\ta.title > b.title ?\n\t\t\t\t\t\t1 :\n\t\t\t\t\t\ta.title < b.title ? -1 : 0 :\n\t\t\t\t\ta instanceof Org ? -1 : 1\n\t\t);\n\t}\n\t\n\tsortIds(ids: string[]) {\n\t\treturn _ids((\n\t\t\tids\n\t\t\t\t.map(_id => this.get(_id) || this.orgs.get(_id))\n\t\t\t\t.filter(Boolean) as (Org<AS> | User<AS>)[]\n\t\t).sort(this.#sortUsersAndOrgs));\n\t}\n\t\n\treplaceMap = new Map<string, string>();\n\t\n\treplaceHandlers = new Set<(fromId: string, toId: string | null) => Promise<void> | void>();\n\t\n\tasync replace(fromId: string) {\n\t\tconst toId = this.replaceMap.get(fromId) ?? null;\n\t\tif (toId)\n\t\t\tthis.replaceMap.delete(fromId);\n\t\t\n\t\tfor (const handler of this.replaceHandlers)\n\t\t\tawait handler(fromId, toId);\n\t\t\n\t}\n\t\n\tasync deleteUser(_id: string) {\n\t\tconst { deletedCount } = await this.collection.deleteOne({ _id });\n\t\t\n\t\treturn Boolean(deletedCount);\n\t}\n\t\n\t\n\tstatic init<IAS extends AbilitiesSchema>(collections: Collections, options: Options<IAS>) {\n\t\tconst users = new Users(collections, options);\n\t\t\n\t\treturn users.whenReady();\n\t}\n\t\n}\n", "import {\n\t_ids,\n\tdeleteProps,\n\tEmptyArray,\n\tEmptySet,\n\tremoveAll,\n\tsort,\n\tunion,\n\twithout\n} from \"@nesvet/n\";\nimport type { AbilitiesSchema } from \"insite-common\";\nimport {\n\tChangeStreamDocument,\n\tCollectionIndexes,\n\tnewObjectIdString,\n\tWatchedCollection\n} from \"insite-db\";\nimport type { User, Users } from \"../users\";\nimport { Org } from \"./Org\";\nimport { basisSchema } from \"./schema\";\nimport type { NewOrg, OrgDoc, OrgsOptions } from \"./types\";\n\n\nconst indexes: CollectionIndexes = [\n\t[ { owners: 1 } ]\n];\n\nfunction preventDirectDelete() {\n\tthrow new Error(\"Direct usage of orgs collection.deleteOne or .deleteMany is forbidden. Use orgs.deleteOrg instead.\");\n}\n\n\nexport class Orgs<AS extends AbilitiesSchema> extends Map<string, Org<AS>> {\n\tconstructor(users: Users<AS>, options: OrgsOptions = {}) {\n\t\tsuper();\n\t\t\n\t\tthis.users = users;\n\t\tthis.collections = users.collections;\n\t\t\n\t\tthis.preinitOptions = options;\n\t\t\n\t}\n\t\n\tusers;\n\tcollections;\n\tprivate preinitOptions?;\n\t\n\tcollection!: WatchedCollection<OrgDoc> & {\n\t\t/** @deprecated Direct usage of roles collection.deleteOne is forbidden. Use orgs.deleteOrg instead. */\n\t\tdeleteOne: typeof preventDirectDelete;\n\t\t\n\t\t/** @deprecated Direct usage of roles collection.deleteMany is forbidden. Use orgs.deleteOrg instead. */\n\t\tdeleteMany: typeof preventDirectDelete;\n\t};\n\t\n\tnull!: Org<AS> & { _id: null };\n\t\n\t#isPreinited = false;\n\t\n\tasync preinit() {\n\t\t\n\t\tif (!this.#isPreinited) {\n\t\t\tthis.#isPreinited = true;\n\t\t\t\n\t\t\tconst {\n\t\t\t\tschema: customSchema,\n\t\t\t\tindexes: customIndexes,\n\t\t\t\tnull: nullProps,\n\t\t\t\tcollection: collectionOptions\n\t\t\t} = this.preinitOptions!;\n\t\t\t\n\t\t\tif (customSchema) {\n\t\t\t\tif (customSchema.required)\n\t\t\t\t\tremoveAll(customSchema.required as string [], basisSchema.required as string[]);\n\t\t\t\tif (customSchema.properties)\n\t\t\t\t\tdeleteProps(customSchema, Object.keys(basisSchema.properties!));\n\t\t\t}\n\t\t\t\n\t\t\tconst schema = {\n\t\t\t\t...basisSchema,\n\t\t\t\t...customSchema,\n\t\t\t\trequired: [ ...basisSchema.required as string[], ...customSchema?.required as string[] ?? [] ],\n\t\t\t\tproperties: { ...basisSchema.properties, ...customSchema?.properties }\n\t\t\t};\n\t\t\t\n\t\t\tthis.collection = Object.assign(\n\t\t\t\tawait this.collections.ensure<OrgDoc>(\"orgs\", { ...collectionOptions, schema }),\n\t\t\t\t{\n\t\t\t\t\tdeleteOne: preventDirectDelete,\n\t\t\t\t\tdeleteMany: preventDirectDelete\n\t\t\t\t}\n\t\t\t);\n\t\t\t\n\t\t\t// TODO: customIndexes should be moved to collectionOptions\n\t\t\tawait this.collection.ensureIndexes([ ...indexes, ...customIndexes ?? [] ]);\n\t\t\t\n\t\t\tthis.null = Object.assign(\n\t\t\t\tnew Org<AS>(this, {\n\t\t\t\t\t...nullProps,\n\t\t\t\t\t_id: \"\",\n\t\t\t\t\ttitle: \"\",\n\t\t\t\t\tnote: \"\",\n\t\t\t\t\towners: [],\n\t\t\t\t\tmeta: {},\n\t\t\t\t\tcreatedAt: Date.now()\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\t_id: null,\n\t\t\t\t\townerIds: new EmptyArray(),\n\t\t\t\t\townerOrgs: new EmptySet(),\n\t\t\t\t\townerUsers: new EmptySet(),\n\t\t\t\t\tslaveOrgs: new EmptySet()\n\t\t\t\t}\n\t\t\t);\n\t\t\t\n\t\t\tawait this.#maintain();\n\t\t\t\n\t\t\tfor await (const orgDoc of this.collection.find())\n\t\t\t\tthis.load(orgDoc);\n\t\t\t\n\t\t\tdelete this.preinitOptions;\n\t\t}\n\t\t\n\t}\n\t\n\tasync #maintain() {\n\t\t\n\t\tawait this.collection.updateMany({ meta: { $exists: false } }, { $set: { meta: {} } });\n\t\t\n\t}\n\t\n\tinit() {\n\t\t\n\t\tif (!this.users.isInited) {\n\t\t\tthis.update();\n\t\t\t\n\t\t\tthis.collection.onChange(this.#handleCollectionChange);\n\t\t}\n\t\t\n\t}\n\t\n\t#handleCollectionChange = (next: ChangeStreamDocument<OrgDoc>) => {\n\t\tswitch (next.operationType) {\n\t\t\tcase \"insert\": {\n\t\t\t\tnew Org<AS>(this, next.fullDocument);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tcase \"replace\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.update(next.fullDocument);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"update\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.update(next.updateDescription.updatedFields!);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"delete\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.delete();\n\t\t}\n\t\t\n\t};\n\t\n\tload(orgDoc: OrgDoc) {\n\t\tnew Org<AS>(this, orgDoc);\n\t\t\n\t}\n\t\n\t#resolve(org: Org<AS>, slaveOrgs: Org<AS>[]) {\n\t\tslaveOrgs = [ org, ...slaveOrgs ];\n\t\t\n\t\tfor (const ownerOrg of org.ownerOrgs) {\n\t\t\tthis.#resolve(ownerOrg, slaveOrgs);\n\t\t\tfor (const slaveOrg of slaveOrgs)\n\t\t\t\townerOrg.slaveOrgs.add(slaveOrg);\n\t\t}\n\t\t\n\t}\n\t\n\tsorted: Org<AS>[] = [];\n\t\n\tupdate() {\n\t\t\n\t\tconst array = [ ...this.values() ];\n\t\tconst sorted = [];\n\t\t\n\t\tfor (const org of array) {\n\t\t\torg.ownerOrgs.clear();\n\t\t\torg.ownerUsers.clear();\n\t\t\torg.slaveOrgs.clear();\n\t\t\t\n\t\t\tfor (const ownerId of org.ownerIds) {\n\t\t\t\tconst ownerOrg = this.get(ownerId);\n\t\t\t\tif (ownerOrg)\n\t\t\t\t\torg.ownerOrgs.add(ownerOrg);\n\t\t\t\telse {\n\t\t\t\t\tconst ownerUser = this.users.get(ownerId);\n\t\t\t\t\tif (ownerUser)\n\t\t\t\t\t\torg.ownerUsers.add(ownerUser);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (!org.ownerOrgs.size && org._id)\n\t\t\t\tsorted.push(org);\n\t\t}\n\t\t\n\t\tfor (const org of array)\n\t\t\tif (!array.some(anotherOrg => anotherOrg.ownerOrgs.has(org)))\n\t\t\t\tthis.#resolve(org, []);\n\t\t\n\t\tsorted.sort(this.#sortOrgs);\n\t\tfor (const org of array)\n\t\t\tsort(org.slaveOrgs, this.#sortOrgs);\n\t\t\n\t\tfor (let i = 0; i < sorted.length; i++) {\n\t\t\tconst org = sorted[i];\n\t\t\tfor (const slaveOrg of [ ...org.slaveOrgs ].reverse())\n\t\t\t\tif (slaveOrg.ownerOrgs.has(org)) {\n\t\t\t\t\tconst slaveOrgIndex = sorted.indexOf(slaveOrg);\n\t\t\t\t\tif (~slaveOrgIndex) {\n\t\t\t\t\t\tsorted.splice(slaveOrgIndex, 1);\n\t\t\t\t\t\ti--;\n\t\t\t\t\t}\n\t\t\t\t\tsorted.splice(i + 1, 0, slaveOrg);\n\t\t\t\t}\n\t\t}\n\t\tfor (let o = 0, { length } = sorted; o < length;)\n\t\t\tsorted[o]._o = o++;\n\t\t\n\t\tthis.sorted = sorted;\n\t\t\n\t\tif (this.users.isInited)\n\t\t\tthis.users.update();\n\t\t\n\t}\n\t\n\t#sortOrgs(a: Org<AS>, b: Org<AS>) {\n\t\treturn (\n\t\t\t(b.slaveOrgs.size - a.slaveOrgs.size) || (\n\t\t\t\ta.title > b.title ?\n\t\t\t\t\t1 :\n\t\t\t\t\ta.title < b.title ?\n\t\t\t\t\t\t-1 :\n\t\t\t\t\t\t0\n\t\t\t)\n\t\t);\n\t}\n\t\n\tasync create({ title, note, ...restProps }: NewOrg) {\n\t\t\n\t\tconst _id = newObjectIdString();\n\t\t\n\t\tawait this.collection.insertOne({\n\t\t\t_id,\n\t\t\ttitle: title ?? \"\",\n\t\t\tnote: note ?? \"\",\n\t\t\tmeta: {},\n\t\t\t...deleteProps(restProps, [ \"_id\" ]),\n\t\t\tcreatedAt: Date.now()\n\t\t});\n\t\t\n\t\treturn _id;\n\t}\n\t\n\tasync updateOrg(_id: string, updates: Omit<OrgDoc, \"_id\" | \"createdAt\">, byUser?: User<AS>) {\n\t\tconst org = this.get(_id)!;\n\t\t\n\t\tif (!org)\n\t\t\treturn false;\n\t\t\n\t\tif (updates.owners)\n\t\t\tupdates.owners =\n\t\t\t\tthis.users.sortIds(\n\t\t\t\t\tunion(\n\t\t\t\t\t\tbyUser ?\n\t\t\t\t\t\t\twithout(org.ownerIds, byUser.slaveIds) :\n\t\t\t\t\t\t\t[],\n\t\t\t\t\t\twithout(updates.owners, [ _id, ..._ids(org.slaveOrgs) ])\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\n\t\tawait this.collection.updateOne({ _id }, { $set: updates });\n\t\t\n\t\treturn true;\n\t}\n\t\n\tdeleteOrg(org: Org<AS> | string) {\n\t\tconst _id = typeof org == \"string\" ? org : org._id;\n\t\t\n\t\treturn this.collection.bulkWrite([\n\t\t\t{ updateMany: { filter: { owners: _id }, update: { $pullAll: { owners: [ _id ] } } } },\n\t\t\t{ deleteOne: { filter: { _id } } }\n\t\t]);\n\t}\n\t\n\treplaceMap = new Map<string, string>();\n\t\n\treplaceHandlers = new Set<(fromId: string, toId: string | null) => Promise<void> | void>();\n\t\n\tasync replace(fromId: string) {\n\t\tconst toId = this.replaceMap.get(fromId) ?? null;\n\t\tif (toId)\n\t\t\tthis.replaceMap.delete(fromId);\n\t\t\n\t\tfor (const handler of this.replaceHandlers)\n\t\t\tawait handler(fromId, toId);\n\t\t\n\t}\n\t\n}\n", "import type { AbilitiesSchema } from \"insite-common\";\nimport { User } from \"../users/User\";\nimport type { Orgs } from \"./Orgs\";\nimport type { OrgDoc } from \"./types\";\n\n\nconst snapshots = new WeakMap();\n\n\nexport class Org<AS extends AbilitiesSchema> {\n\tconstructor(orgs: Orgs<AS>, orgDoc: OrgDoc) {\n\t\tthis.orgs = orgs;\n\t\t\n\t\tthis._id = orgDoc._id;\n\t\torgs.set(this._id, this);\n\t\t\n\t\tvoid this.update(orgDoc);\n\t\t\n\t}\n\t\n\t_id;\n\ttitle = \"\";\n\tinitials = \"\";\n\tdisplayLabel = \"\";\n\t\n\t_o = 0;\n\t\n\torgs;\n\t\n\tisOrg = true;\n\t\n\townerOrgs = new Set<Org<AS>>();\n\townerUsers = new Set<User<AS>>();\n\t\n\tusers = new Set<User<AS>>();\n\t\n\tslaveOrgs = new Set<Org<AS>>();\n\t\n\townerIds: string[] = [];\n\t\n\tupdate({ _id, title, owners: ownerIds, ...restProps }: Partial<OrgDoc>) {\n\t\t\n\t\tObject.assign(this, restProps);\n\t\t\n\t\tif (title !== undefined) {\n\t\t\tthis.title = title;\n\t\t\tthis.initials = title?.[0]?.toUpperCase() ?? \"\";\n\t\t\tthis.displayLabel = title;\n\t\t}\n\t\t\n\t\tif (ownerIds) {\n\t\t\tthis.ownerIds = ownerIds;\n\t\t\t\n\t\t\tconst snapshot = this.ownerIds.join(\",\");\n\t\t\t\n\t\t\tif (snapshot !== snapshots.get(this)) {\n\t\t\t\tsnapshots.set(this, snapshot);\n\t\t\t\t\n\t\t\t\tif (this.orgs.users.isInited)\n\t\t\t\t\tthis.orgs.update();\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tasync delete() {\n\t\t\n\t\tthis.orgs.delete(this._id);\n\t\t\n\t\tsnapshots.delete(this);\n\t\t\n\t\tawait this.orgs.replace(this._id);\n\t\t\n\t\tthis.orgs.update();\n\t\t\n\t}\n\t\n}\n", "import { CollectionSchema } from \"insite-db\";\nimport { regexps } from \"../lib\";\n\n\nexport const basisSchema: CollectionSchema = {\n\trequired: [\n\t\t\"_id\",\n\t\t\"title\",\n\t\t\"note\",\n\t\t\"owners\",\n\t\t\"meta\",\n\t\t\"createdAt\"\n\t],\n\tproperties: {\n\t\t_id: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps._id.source\n\t\t},\n\t\ttitle: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 512\n\t\t},\n\t\tnote: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 131072\n\t\t},\n\t\towners: {\n\t\t\tbsonType: \"array\",\n\t\t\tuniqueItems: true,\n\t\t\titems: {\n\t\t\t\tbsonType: \"string\",\n\t\t\t\tpattern: regexps._id.source\n\t\t\t},\n\t\t\tadditionalItems: false\n\t\t},\n\t\tmeta: {\n\t\t\tbsonType: \"object\"\n\t\t},\n\t\tcreatedAt: {\n\t\t\tbsonType: \"number\"\n\t\t}\n\t},\n\tadditionalProperties: false\n};\n", "import { randomBytes } from \"node:crypto\";\nimport { deleteProps, removeAll } from \"@nesvet/n\";\nimport type { AbilitiesSchema } from \"insite-common\";\nimport {\n\tChangeStreamDocument,\n\tCollectionIndexes,\n\tnewObjectIdString,\n\tWatchedCollection\n} from \"insite-db\";\nimport { User } from \"../users/User\";\nimport type { Users } from \"../users\";\nimport { basisSchema } from \"./schema\";\nimport { Session } from \"./Session\";\nimport { SessionDoc, SessionsOptions } from \"./types\";\n\n\nconst expireAfterSeconds = 3600 * 24 * 7;\n\nconst indexes: CollectionIndexes = [\n\t[ { user: 1 } ],\n\t[ { expiresAt: 1 }, { expireAfterSeconds } ]\n];\n\n\nexport class Sessions<AS extends AbilitiesSchema> extends Map<string, Session<AS>> {\n\tconstructor(users: Users<AS>, options: SessionsOptions = {}) {\n\t\tsuper();\n\t\t\n\t\tthis.users = users;\n\t\tthis.collections = users.collections;\n\t\t\n\t\tthis.initOptions = options;\n\t}\n\t\n\tusers;\n\tcollections;\n\t\n\tprivate initOptions?;\n\t\n\tcollection!: WatchedCollection<SessionDoc> & {\n\t\texpireAfterSeconds: number;\n\t};\n\t\n\tasync init() {\n\t\t\n\t\tif (!this.users.isInited) {\n\t\t\tconst {\n\t\t\t\tschema: customSchema,\n\t\t\t\tindexes: customIndexes,\n\t\t\t\tcollection: collectionOptions\n\t\t\t} = this.initOptions!;\n\t\t\t\n\t\t\tif (customSchema) {\n\t\t\t\tif (customSchema.required)\n\t\t\t\t\tremoveAll(customSchema.required as string[], basisSchema.required as string[]);\n\t\t\t\tif (customSchema.properties)\n\t\t\t\t\tdeleteProps(customSchema, Object.keys(basisSchema.properties!));\n\t\t\t}\n\t\t\t\n\t\t\tconst schema = {\n\t\t\t\t...basisSchema,\n\t\t\t\t...customSchema,\n\t\t\t\trequired: [ ...basisSchema.required as string[], ...customSchema?.required as string[] ?? [] ],\n\t\t\t\tproperties: { ...basisSchema.properties, ...customSchema?.properties }\n\t\t\t};\n\t\t\t\n\t\t\tthis.collection = Object.assign(\n\t\t\t\tawait this.collections.ensure<SessionDoc>(\"sessions\", { ...collectionOptions, schema }),\n\t\t\t\t{\n\t\t\t\t\texpireAfterSeconds\n\t\t\t\t}\n\t\t\t);\n\t\t\t\n\t\t\tawait this.collection.ensureIndexes([ ...indexes, ...customIndexes ?? [] ]);\n\t\t\t\n\t\t\tawait this.#maintain();\n\t\t\t\n\t\t\tfor await (const sessionDoc of this.collection.find())\n\t\t\t\tthis.load(sessionDoc);\n\t\t\t\n\t\t\tthis.collection.onChange(this.#handleCollectionChange);\n\t\t\t\n\t\t\tdelete this.initOptions;\n\t\t}\n\t\t\n\t}\n\t\n\tasync #maintain() {\n\t\t\n\t\tawait this.collection.bulkWrite([\n\t\t\t{ updateMany: { filter: { meta: { $exists: false } }, update: { $set: { meta: {} } } } },\n\t\t\t{ updateMany: { filter: { isOnline: true }, update: { $set: { isOnline: false } } } }\n\t\t]);\n\t\t\n\t}\n\t\n\t#handleCollectionChange = (next: ChangeStreamDocument<SessionDoc>) => {\n\t\tswitch (next.operationType) {\n\t\t\tcase \"insert\":\n\t\t\t\tif (!this.has(next.documentKey._id))\n\t\t\t\t\tnew Session<AS>(this, next.fullDocument);\n\t\t\t\t\n\t\t\t\tvoid this.users.get(next.fullDocument.user)?.trimSessions();\n\t\t\t\t\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"replace\":\n\t\t\t\tthis.get(next.documentKey._id)?.update(next.fullDocument);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"update\":\n\t\t\t\tthis.get(next.documentKey._id)?.update(next.updateDescription.updatedFields!);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"delete\":\n\t\t\t\tthis.get(next.documentKey._id)?.delete();\n\t\t}\n\t\t\n\t};\n\t\n\tuid() {\n\t\treturn `${newObjectIdString()}~${randomBytes(32).toString(\"base64url\")}`;\n\t}\n\t\n\tload(sessionDoc: SessionDoc) {\n\t\tnew Session<AS>(this, sessionDoc);\n\t\t\n\t}\n\t\n\tasync create(user: User<AS>, props: Partial<SessionDoc>) {\n\t\t\n\t\tconst ts = Date.now();\n\t\t\n\t\tconst sessionDoc: SessionDoc = {\n\t\t\tuserAgent: \"\",\n\t\t\tremoteAddress: \"127.0.0.1\",\n\t\t\tisOnline: true,\n\t\t\t...props,\n\t\t\t_id: this.uid(),\n\t\t\tuser: user._id,\n\t\t\tmeta: {},\n\t\t\tcreatedAt: ts,\n\t\t\tprolongedAt: ts,\n\t\t\texpiresAt: new Date(ts + (expireAfterSeconds * 1000))\n\t\t};\n\t\t\n\t\t/* new Session(\u2026) before await insertOne(\u2026) for avoid changeStream insert event to come earlier and create the session duplicate */\n\t\tconst session = new Session<AS>(this, sessionDoc);\n\t\t\n\t\tawait this.collection.insertOne(sessionDoc);\n\t\t\n\t\treturn session;\n\t}\n\t\n\tasync destroySession(_id: string) {\n\t\tconst { deletedCount } = await this.collection.deleteOne({ _id });\n\t\t\n\t\treturn Boolean(deletedCount);\n\t}\n\t\n}\n", "import { CollectionSchema } from \"insite-db\";\nimport { regexps } from \"../lib\";\n\n\nexport const basisSchema: CollectionSchema = {\n\trequired: [\n\t\t\"_id\",\n\t\t\"user\",\n\t\t\"remoteAddress\",\n\t\t\"isOnline\",\n\t\t\"meta\",\n\t\t\"createdAt\",\n\t\t\"prolongedAt\",\n\t\t\"expiresAt\"\n\t],\n\tproperties: {\n\t\t_id: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps.sessionId.source\n\t\t},\n\t\tuser: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps._id.source\n\t\t},\n\t\tuserAgent: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 4096\n\t\t},\n\t\tremoteAddress: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps.ip.source\n\t\t},\n\t\tisOnline: {\n\t\t\tbsonType: \"bool\"\n\t\t},\n\t\tmeta: {\n\t\t\tbsonType: \"object\"\n\t\t},\n\t\tcreatedAt: {\n\t\t\tbsonType: \"number\"\n\t\t},\n\t\tprolongedAt: {\n\t\t\tbsonType: \"number\"\n\t\t},\n\t\texpiresAt: {\n\t\t\tbsonType: \"date\"\n\t\t}\n\t}\n\t// TODO: Restrict additional properties (not needed with meta)\n};\n", "import type { AbilitiesSchema } from \"insite-common\";\nimport type { User } from \"../users/User\";\nimport type { Sessions } from \"./Sessions\";\nimport type { SessionDoc } from \"./types\";\n\n\nexport class Session<AS extends AbilitiesSchema> {\n\tconstructor(sessions: Sessions<AS>, sessionDoc: SessionDoc) {\n\t\tconst user = sessions.users.get(sessionDoc.user);\n\t\t\n\t\tif (user) {\n\t\t\tthis.#sessions = sessions;\n\t\t\t\n\t\t\tthis._id = sessionDoc._id;\n\t\t\tthis.#sessions.set(this._id, this);\n\t\t\t\n\t\t\tthis.user = user;\n\t\t\tthis.user.sessions.add(this);\n\t\t\t\n\t\t\tthis.#sessions.users.bySessionId.set(this._id, this.user);\n\t\t\t\n\t\t\tthis.update(sessionDoc);\n\t\t} else\n\t\t\tvoid sessions.collection.deleteOne({ _id: sessionDoc._id });\n\t\t\n\t}\n\t\n\t_id!: string;\n\tuser!: User<AS>;\n\tisOnline = false;\n\t\n\tuserAgent!: string;\n\tremoteAddress!: string;\n\tcreatedAt!: number;\n\tprolongedAt!: number;\n\texpiresAt!: Date;\n\t\n\t#sessions!: Sessions<AS>;\n\t\n\tupdate({ _id, user, isOnline, ...restProps }: Partial<SessionDoc>) {\n\t\t\n\t\tif (isOnline !== undefined && this.isOnline !== isOnline) {\n\t\t\tthis.isOnline = isOnline;\n\t\t\t\n\t\t\tif (this.#sessions.users.isInited && this.user.isOnline !== this.isOnline)\n\t\t\t\tvoid this.user.updateIsOnlineDebounced();\n\t\t}\n\t\t\n\t\tObject.assign(this, restProps);\n\t\t\n\t}\n\t\n\tprolong({ _id, user, ...updates }: Partial<SessionDoc>) {\n\t\t\n\t\tconst ts = Date.now();\n\t\t\n\t\tupdates.prolongedAt = ts;\n\t\tupdates.expiresAt = new Date(ts + (this.#sessions.collection.expireAfterSeconds * 1000));\n\t\t\n\t\tthis.update(updates);\n\t\t\n\t\treturn this.#sessions.collection.updateOne({ _id: this._id }, { $set: updates });\n\t}\n\t\n\tasync online() {\n\t\t\n\t\tif (!this.isOnline) {\n\t\t\tconst updates = { isOnline: true };\n\t\t\t\n\t\t\tthis.update(updates);\n\t\t\t\n\t\t\tawait this.#sessions.collection.updateOne({ _id: this._id }, { $set: updates });\n\t\t}\n\t\t\n\t}\n\t\n\tasync offline() {\n\t\t\n\t\tif (this.isOnline) {\n\t\t\tconst updates = { isOnline: false };\n\t\t\t\n\t\t\tthis.update(updates);\n\t\t\t\n\t\t\tawait this.#sessions.collection.updateOne({ _id: this._id }, { $set: updates });\n\t\t}\n\t\t\n\t}\n\t\n\tdelete() {\n\t\t\n\t\tthis.#sessions.delete(this._id);\n\t\tthis.user.sessions.delete(this);\n\t\tthis.#sessions.users.bySessionId.delete(this._id);\n\t\t\n\t\tthis.#sessions.users.emit(\"session-delete\", this);\n\t\t\n\t\tif (this.isOnline)\n\t\t\tthis.user.updateIsOnline();\n\t\t\n\t}\n\t\n}\n", "import type { AbilitiesSchema } from \"insite-common\";\nimport { Binary, type WatchedCollection } from \"insite-db\";\nimport type { Users } from \"../Users\";\nimport { schema } from \"./schema\";\nimport type { AvatarDoc, AvatarsOptions } from \"./types\";\n\n\nexport class Avatars<AS extends AbilitiesSchema> {\n\tconstructor(users: Users<AS>, options: AvatarsOptions = {}) {\n\t\tthis.users = users;\n\t\tthis.collections = users.collections;\n\t\t\n\t\tthis.initOptions = options;\n\t\t\n\t}\n\t\n\treadonly TYPES_ACCEPTED = [ \"image/webp\" ];\n\treadonly MAX_SIZE = 1024 * 512;\n\t\n\tusers;\n\tcollections;\n\t\n\tcollection!: WatchedCollection<AvatarDoc>;\n\t\n\tprivate initOptions?;\n\t\n\tasync init() {\n\t\t\n\t\tif (!this.users.isInited) {\n\t\t\tconst {\n\t\t\t\tcollection: collectionOptions\n\t\t\t} = this.initOptions!;\n\t\t\t\n\t\t\tthis.collection = await this.collections.ensure<AvatarDoc>(\"users.avatars\", { ...collectionOptions, schema });\n\t\t\t\n\t\t\tawait this.#maintain();\n\t\t}\n\t\t\n\t}\n\t\n\tasync #maintain() {\n\t\t\n\t\tawait this.collection.updateMany({ meta: { $exists: false } }, { $set: { meta: {} } });\n\t\t\n\t}\n\t\n\tasync save(_id: string, type: string, data: string) {\n\t\tconst binaryData = Binary.createFromBase64(data.slice(data.indexOf(\",\")));\n\t\t\n\t\tconst ts = Date.now().toString(36);\n\t\t\n\t\tawait Promise.all([\n\t\t\tthis.collection.replaceOne({ _id }, {\n\t\t\t\ttype,\n\t\t\t\tsize: binaryData.length(),\n\t\t\t\tts,\n\t\t\t\tdata: binaryData,\n\t\t\t\tmeta: {}\n\t\t\t}, { upsert: true }),\n\t\t\tthis.users.collection.updateOne({ _id }, { $set: { avatar: ts } })\n\t\t]);\n\t\t\n\t}\n\t\n\tasync deleteAvatar(_id: string) {\n\t\t\n\t\tconst [ { deletedCount } ] = await Promise.all([\n\t\t\tthis.collection.deleteOne({ _id }),\n\t\t\tthis.users.collection.updateOne({ _id }, { $set: { avatar: null } })\n\t\t]);\n\t\t\n\t\treturn Boolean(deletedCount);\n\t}\n\t\n}\n", "import { CollectionSchema } from \"insite-db\";\nimport { regexps } from \"../../lib\";\n\n\nexport const schema: CollectionSchema = {\n\trequired: [\n\t\t\"_id\",\n\t\t\"type\",\n\t\t\"size\",\n\t\t\"ts\",\n\t\t\"data\",\n\t\t\"meta\"\n\t],\n\tproperties: {\n\t\t_id: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps._id.source\n\t\t},\n\t\ttype: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 256\n\t\t},\n\t\tsize: {\n\t\t\tbsonType: \"number\"\n\t\t},\n\t\tts: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 10\n\t\t},\n\t\tdata: {\n\t\t\tbsonType: \"binData\"\n\t\t},\n\t\tmeta: {\n\t\t\tbsonType: \"object\"\n\t\t}\n\t},\n\tadditionalProperties: false\n};\n", "import { CollectionSchema } from \"insite-db\";\nimport { regexps } from \"../lib\";\n\n\nexport const basisSchema: CollectionSchema = {\n\trequired: [\n\t\t\"_id\",\n\t\t\"email\",\n\t\t\"password\",\n\t\t\"roles\",\n\t\t\"name\",\n\t\t\"org\",\n\t\t\"job\",\n\t\t\"meta\",\n\t\t\"createdAt\"\n\t],\n\tproperties: {\n\t\t_id: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps._id.source\n\t\t},\n\t\temail: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps.email.source\n\t\t},\n\t\tpassword: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps.argon2.source\n\t\t},\n\t\troles: {\n\t\t\tbsonType: \"array\",\n\t\t\tuniqueItems: true,\n\t\t\titems: {\n\t\t\t\tbsonType: \"string\",\n\t\t\t\tpattern: regexps.role.source\n\t\t\t},\n\t\t\tadditionalItems: false\n\t\t},\n\t\tname: {\n\t\t\tbsonType: \"object\",\n\t\t\trequired: [\n\t\t\t\t\"first\",\n\t\t\t\t\"middle\",\n\t\t\t\t\"last\"\n\t\t\t],\n\t\t\tproperties: {\n\t\t\t\tfirst: {\n\t\t\t\t\tbsonType: \"string\",\n\t\t\t\t\tmaxLength: 512\n\t\t\t\t},\n\t\t\t\tmiddle: {\n\t\t\t\t\tbsonType: \"string\",\n\t\t\t\t\tmaxLength: 512\n\t\t\t\t},\n\t\t\t\tlast: {\n\t\t\t\t\tbsonType: \"string\",\n\t\t\t\t\tmaxLength: 512\n\t\t\t\t}\n\t\t\t},\n\t\t\tadditionalProperties: false\n\t\t},\n\t\torg: {\n\t\t\toneOf: [\n\t\t\t\t{\n\t\t\t\t\tbsonType: \"string\",\n\t\t\t\t\tpattern: regexps._id.source\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbsonType: \"null\"\n\t\t\t\t}\n\t\t\t]\n\t\t},\n\t\tjob: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 512\n\t\t},\n\t\tavatar: {\n\t\t\toneOf: [\n\t\t\t\t{\n\t\t\t\t\tbsonType: \"string\",\n\t\t\t\t\tmaxLength: 10\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbsonType: \"null\"\n\t\t\t\t}\n\t\t\t]\n\t\t},\n\t\tmeta: {\n\t\t\tbsonType: \"object\"\n\t\t},\n\t\tcreatedAt: {\n\t\t\tbsonType: \"number\"\n\t\t}\n\t},\n\tadditionalProperties: false\n};\n", "import {\n\t_ids,\n\tdebounce,\n\tempty,\n\thasAny,\n\tremoveOne\n} from \"@nesvet/n\";\nimport type { Abilities, AbilitiesSchema } from \"insite-common\";\nimport type { GenericAbilities } from \"../abilities/types\";\nimport type { Org } from \"../orgs/Org\";\nimport type { Role } from \"../roles/Role\";\nimport type { Session } from \"../sessions/Session\";\nimport type { UserDoc } from \"./types\";\nimport type { Users } from \"./Users\";\n\n\nconst rolesSnapshots = new WeakMap();\nconst permissionsSnapshots = new WeakMap();\n\nconst staticUrl = process.env.INSITE_STATIC_URL ?? \"http://localhost:8080\";\n\n\nexport class User<AS extends AbilitiesSchema> {\n\tconstructor(users: Users<AS>, userDoc: UserDoc) {\n\t\tthis.#users = users;\n\t\t\n\t\tthis._id = userDoc._id;\n\t\tusers.set(this._id, this);\n\t\t\n\t\tusers.isSortRequired = true;\n\t\t\n\t\tvoid this.update(userDoc);\n\t\t\n\t\tif (users.isInited)\n\t\t\tusers.emit(\"user-create\", this);\n\t\t\n\t}\n\t\n\t_id;\n\temail!: string;\n\tname = {\n\t\tfirst: \"\",\n\t\tmiddle: \"\",\n\t\tlast: \"\"\n\t};\n\t\n\tinitials = \"\";\n\tdisplayLabel = \"\";\n\torg!: Org<AS>;\n\tjob: string = \"\";\n\tavatar: string | null = null;\n\tavatarUrl: string | null = null;\n\t\n\t#users;\n\t\n\tisUser = true;\n\tisRoot?: boolean;\n\t\n\troles = new Set<Role<AS>>();\n\townRoles: Role<AS>[] = [];\n\townRoleIds: string[] = [];\n\tslaveRoles = new Set<Role<AS>>();\n\tslaveRoleIds: string[] = [];\n\tabilities: Abilities<AS> = {};\n\t\n\tslaveOrgs = new Set<Org<AS>>();\n\tslaveUsers = new Set<User<AS>>();\n\tslaves = new Set<Org<AS> | User<AS>>();\n\t\n\tslaveIds: string[] = [];\n\tpermissiveIds: string[] = [];\n\t\n\tsessions = new Set<Session<AS>>();\n\t\n\tisOnline = false;\n\t\n\tupdate({ _id, name, email, roles: ownRoleIds, org: orgId, avatar, ...restProps }: Partial<UserDoc>) {\n\t\t\n\t\tObject.assign(this, restProps);\n\t\t\n\t\tlet isEmailUpdated;\n\t\tif (email && this.email !== email) {\n\t\t\tthis.#users.byEmail.delete(this.email);\n\t\t\tthis.email = email;\n\t\t\tthis.#users.byEmail.set(email, this);\n\t\t\tisEmailUpdated = true;\n\t\t}\n\t\t\n\t\tlet isNameUpdated;\n\t\tlet isLastNameUpdated;\n\t\tif (name && (this.name.first !== name.first || this.name.middle !== name.middle || this.name.last !== name.last)) {\n\t\t\tisLastNameUpdated = this.name.last !== name.last;\n\t\t\tthis.name = {\n\t\t\t\tfirst: name.first ?? \"\",\n\t\t\t\tmiddle: name.middle ?? \"\",\n\t\t\t\tlast: name.last ?? \"\"\n\t\t\t};\n\t\t\tthis.initials = (((name.first?.[0] ?? \"\") + (name.last?.[0] ?? \"\")) || this.email[0]).toUpperCase();\n\t\t\tisNameUpdated = true;\n\t\t}\n\t\t\n\t\tif (isEmailUpdated || isNameUpdated)\n\t\t\tthis.displayLabel = `${this.name.first} ${this.name.last}`.trim() || this.name.middle || this.email;\n\t\t\n\t\tlet isRolesUpdated;\n\t\tif (ownRoleIds) {\n\t\t\tthis.ownRoleIds = ownRoleIds;\n\t\t\t\n\t\t\tconst snapshot = this.ownRoleIds.join(\",\");\n\t\t\t\n\t\t\tif (snapshot !== rolesSnapshots.get(this)) {\n\t\t\t\trolesSnapshots.set(this, snapshot);\n\t\t\t\t\n\t\t\t\tif (this.#users.isInited) {\n\t\t\t\t\tthis.updateRoles();\n\t\t\t\t\tisRolesUpdated = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tlet isOrgUpdated;\n\t\tif (orgId !== undefined && this.org?._id !== orgId) {\n\t\t\tthis.org?.users.delete(this);\n\t\t\tthis.org = orgId && this.#users.orgs.get(orgId) || this.#users.orgs.null;// eslint-disable-line @stylistic/no-mixed-operators\n\t\t\tthis.org.users.add(this);\n\t\t\tisOrgUpdated = true;\n\t\t}\n\t\t\n\t\tif (avatar !== undefined && this.avatar !== avatar) {\n\t\t\tthis.avatar = avatar;\n\t\t\tthis.avatarUrl = avatar && `${staticUrl}/avatars/${this._id}-${avatar}.webp`;\n\t\t}\n\t\t\n\t\tif (this.#users.isInited)\n\t\t\tif (isRolesUpdated || isOrgUpdated) {\n\t\t\t\tthis.updatePermissions();\n\t\t\t\t\n\t\t\t\tif (isLastNameUpdated)\n\t\t\t\t\tthis.#users.isSortRequired = true;\n\t\t\t\t\n\t\t\t\tthis.#users.update();\n\t\t\t} else if (isLastNameUpdated)\n\t\t\t\tthis.#users.sort();\n\t\t\n\t}\n\t\n\tupdateRoles() {\n\t\t\n\t\tthis.ownRoles = [];\n\t\tthis.roles.clear();\n\t\tthis.slaveRoles.clear();\n\t\tempty(this.abilities);\n\t\t\n\t\tfor (const roleId of this.ownRoleIds) {\n\t\t\tconst role = this.#users.roles.get(roleId);\n\t\t\tif (role) {\n\t\t\t\t\n\t\t\t\tthis.ownRoles.push(role);\n\t\t\t\tthis.roles.add(role);\n\t\t\t\tfor (const involvedRole of role.involves) {\n\t\t\t\t\tthis.roles.add(involvedRole);\n\t\t\t\t\tthis.slaveRoles.add(involvedRole);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tthis.slaveRoleIds = _ids(this.slaveRoles);\n\t\t\t\t\n\t\t\t\tthis.#users.abilities.merge(this.abilities as GenericAbilities, role.abilities as GenericAbilities);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (this.roles.has(this.#users.roles.root))\n\t\t\tthis.isRoot = true;\n\t\t\n\t\tvoid this.trimSessions();\n\t\t\n\t}\n\t\n\tupdatePermissions() {\n\t\t\n\t\tthis.slaveOrgs.clear();\n\t\tthis.slaveUsers.clear();\n\t\tthis.slaves.clear();\n\t\tconst slaveIds = new Set<string>();\n\t\t\n\t\tfor (const org of this.#users.orgs.sorted)\n\t\t\tif ((org.ownerUsers.has(this) || this.isRoot) && !this.slaveOrgs.has(org)) {\n\t\t\t\tthis.slaveOrgs.add(org);\n\t\t\t\tthis.slaves.add(org);\n\t\t\t\tslaveIds.add(org._id);\n\t\t\t\tfor (const slaveOrg of org.slaveOrgs) {\n\t\t\t\t\tthis.slaveOrgs.add(slaveOrg);\n\t\t\t\t\tthis.slaves.add(slaveOrg);\n\t\t\t\t\tslaveIds.add(slaveOrg._id);\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\tfor (const org of new Set([ this.org, ...this.slaveOrgs, this.#users.orgs.null ]))\n\t\t\tfor (const user of org.users)\n\t\t\t\tif (user !== this && (hasAny(this.slaveRoles, user.ownRoles) || !user.ownRoles.length)) {\n\t\t\t\t\tthis.slaveUsers.add(user);\n\t\t\t\t\tthis.slaves.add(user);\n\t\t\t\t\tslaveIds.add(user._id);\n\t\t\t\t}\n\t\t\n\t\tthis.slaveIds = [ ...slaveIds ];\n\t\t\n\t\tconst permissiveOrgIds = [];\n\t\tif (this.org._id) {\n\t\t\tpermissiveOrgIds.push(this.org._id);\n\t\t\tfor (const slaveOrg of this.org.slaveOrgs)\n\t\t\t\tif (!this.slaveOrgs.has(slaveOrg))\n\t\t\t\t\tpermissiveOrgIds.push(slaveOrg._id);\n\t\t}\n\t\t\n\t\tthis.permissiveIds = [ ...permissiveOrgIds, this._id, ...slaveIds ];\n\t\t\n\t\t\n\t\tconst snapshot = [\n\t\t\tthis.permissiveIds.join(\",\"),\n\t\t\tthis.ownRoleIds.join(\",\"),\n\t\t\tJSON.stringify(this.abilities),\n\t\t\tthis.slaveRoleIds.join(\",\")\n\t\t].join(\"\\n\");\n\t\t\n\t\tif (snapshot !== permissionsSnapshots.get(this)) {\n\t\t\tpermissionsSnapshots.set(this, snapshot);\n\t\t\t\n\t\t\tif (this.#users.isInited)\n\t\t\t\tthis.#users.emit(\"user-permissions-change\", this);\n\t\t}\n\t\t\n\t}\n\t\n\ttrimSessions() {\n\t\t\n\t\tconst sessionsLimit = this.abilities.login?.sessionsLimit ?? 0;\n\t\t\n\t\tif (this.sessions.size > sessionsLimit)\n\t\t\treturn this.#users.sessions.collection.deleteMany({\n\t\t\t\t_id: {\n\t\t\t\t\t$in: _ids(\n\t\t\t\t\t\t[ ...this.sessions ]\n\t\t\t\t\t\t\t.sort((a, b) => a.expiresAt.valueOf() - b.expiresAt.valueOf())\n\t\t\t\t\t\t\t.slice(0, this.sessions.size - sessionsLimit)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t});\n\t\t\n\t}\n\t\n\tupdateIsOnline() {\n\t\t\n\t\tlet isOnline = false;\n\t\t\n\t\tfor (const session of this.sessions)\n\t\t\tif (session.isOnline) {\n\t\t\t\tisOnline = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\n\t\tif (this.isOnline !== isOnline) {\n\t\t\tthis.isOnline = isOnline;\n\t\t\tthis.#users.emit(\"user-is-online\", this);\n\t\t}\n\t\t\n\t}\n\t\n\tupdateIsOnlineDebounced = debounce(() => this.updateIsOnline(), 500);\n\t\n\tasync delete() {\n\t\t\n\t\tthis.org.users.delete(this);\n\t\t\n\t\tthis.#users.delete(this._id);\n\t\tthis.#users.byEmail.delete(this.email);\n\t\tremoveOne(this.#users.sorted, this);\n\t\t\n\t\trolesSnapshots.delete(this);\n\t\tpermissionsSnapshots.delete(this);\n\t\t\n\t\tawait this.#users.replace(this._id);\n\t\t\n\t\tthis.#users.update();\n\t\t\n\t}\n\t\n}\n"],
5
- "mappings": "AAAM,SAAUA,EAAgCC,EAAsB,CACrE,GAAIA,aAAoB,IAAK,CAC5B,IAAMC,EAAM,CAAA,EAEZ,QAAWC,KAAUF,EACpBC,EAAI,KAAKC,EAAO,GAAG,EAEpB,OAAOD,CACR,CAEA,OAAOD,EAAS,IAAIE,GAAUA,EAAO,GAAG,CACzC,CCXM,SAAUC,GAAOC,KAAeC,EAAU,CAE/C,IAAIC,EAAQ,EAEZ,QAAWC,KAAQF,EACbD,EAAM,SAASG,CAAI,IACvBH,EAAM,KAAKG,CAAI,EACfD,KAGF,OAAOA,CACR,CCXM,SAAUE,EAAWC,EAAiCC,EAAcC,EAAQ,CACjF,GAAIF,GAAUC,EAAM,CACnB,GAAIA,EAAK,SAAS,GAAG,EAAG,CACvB,I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AAE,KAAK,KAAOC,EAAE,KAAK,KACpB,EACAD,EAAE,KAAK,KAAOC,EAAE,KAAK,KAAO,GAAK,EACjC,CAACD,EAAE,KAAK,MAAQ,CAACC,EAAE,KAAK,KACxBD,EAAE,aAAeC,EAAE,aAClB,EACAD,EAAE,aAAeC,EAAE,aAAe,GAAK,EACxCD,EAAE,KAAK,KAAO,GAAK,EACpBA,aAAaqB,GAAOpB,aAAaoB,EACjCrB,EAAE,MAAQC,EAAE,MACX,EACAD,EAAE,MAAQC,EAAE,MAAQ,GAAK,EAC1BD,aAAaqB,EAAM,GAAK,CAE5B,CAEA,QAAQC,EAAe,CACtB,OAAOC,EACND,EACE,IAAIV,GAAO,KAAK,IAAIA,CAAG,GAAK,KAAK,KAAK,IAAIA,CAAG,CAAC,EAC9C,OAAO,OAAO,EACf,KAAK,KAAKQ,EAAiB,CAAC,CAC/B,CAEA,WAAa,IAAI,IAEjB,gBAAkB,IAAI,IAEtB,MAAM,QAAQI,EAAgB,CAC7B,IAAMC,EAAO,KAAK,WAAW,IAAID,CAAM,GAAK,KACxCC,GACH,KAAK,WAAW,OAAOD,CAAM,EAE9B,QAAWE,KAAW,KAAK,gBAC1B,MAAMA,EAAQF,EAAQC,CAAI,CAE5B,CAEA,MAAM,WAAWb,EAAa,CAC7B,GAAM,CAAE,aAAAe,CAAa,EAAI,MAAM,KAAK,WAAW,UAAU,CAAE,IAAAf,CAAI,CAAC,EAEhE,MAAO,EAAQe,CAChB,CAGA,OAAO,KAAkC5D,EAA0BC,EAAuB,CAGzF,OAFc,IAAIF,EAAMC,EAAaC,CAAO,EAE/B,UAAU,CACxB,CAED",
6
- "names": ["_ids", "iterable", "ids", "object", "add", "array", "items", "added", "item", "setPath", "object", "path", "value", "keys", "subObject", "i", "key", "subObjectValue", "assignPath", "target", "sources", "source", "path", "setPath", "noop", "nativesMap", "StatefulPromise", "_StatefulPromise", "executor", "options", "nativeResolve", "nativeReject", "resolve", "reject", "abortListener", "timeout", "value", "native", "reason", "_", "debounce", "callback", "limit", "options", "leading", "trailing", "maxWait", "timeout", "maxWaitTimeout", "end", "context", "args", "initial", "final", "result", "expired", "n", "debounced", "maxWaitExpired", "run", "error", "_args", "StatefulPromise", "resolve", "reject", "noop", "shouldRun", "deletePath", "object", "path", "keys", "subObject", "i", "key", "subObjectValue", "lastKey", "deleteProps", "object", "keys", "key", "empty", "object", "key", "EmptyArray", "EmptySet", "Err", "message", "tag", "payload", "getAll", "map", "keys", "onlyExisting", "items", "key", "item", "getPath", "object", "path", "subObject", "key", "hasAny", "mapOrSet", "items", "item", "howmuch", "number", "one", "two", "five", "shouldPrintNumber", "u", "d", "intersection", "iterables", "intersectionArray", "firstIterable", "otherIterables", "mainLoop", "item", "otherIterable", "pick", "object", "keys", "picked", "key", "reAdd", "set", "item", "removeAll", "array", "items", "i", "removed", "item", "removeOne", "array", "item", "i", "sort", "set", "compareFn", "item", "union", "iterables", "without", "array", "arrayToExclude", "item", "AbilityError", "Err", "longId", "payload", "isAbilityObject", "value", "isAbilityParamNumber", "isAbilityParamItems", "schemaParentMap", "AbilitiesMap", "abilitiesSchema", "subSchema", "#hierarchical", "parse", "schemas", "parent", "level", "schema", "longId", "subIds", "subId", "_id", "top", "paramId", "schemaOrLongId", "paramIdOrMax", "max", "ability", "paramSchema", "schemasOrIds", "a", "b", "schemaMaxMap", "resolve", "_schema", "parentSchema", "assignPath", "_max", "abilities", "subSchemas", "subAbilities", "i", "abilityParam", "value", "getPath", "setPath", "referenceValue", "isAbilityParamNumber", "isAbilityParamItems", "itemId", "intersection", "item", "adjustedAbilities", "adjustedAbility", "isAbilityObject", "pick", "empty", "target", "source", "targetAbility", "sourceAbility", "add", "deletePath", "RolesError", "Err", "stringOrArray", "payload", "snapshots", "Role", "roles", "roleDoc", "#roles", "_id", "ownInvolveIds", "ownAbilities", "title", "restProps", "snapshot", "regexps", "basisSchema", "regexps", "indexes", "preventDirectDelete", "Roles", "users", "options", "rootProps", "initOptions", "Role", "customSchema", "customIndexes", "collectionOptions", "removeAll", "basisSchema", "deleteProps", "schema", "#maintain", "roleDoc", "#handleCollectionChange", "next", "role", "involvedBy", "involvedRoleId", "involvedRole", "involvedByRole", "reAdd", "#sortRoles", "a", "b", "array", "anotherRole", "getAll", "sorted", "i", "involvedRoleIndex", "_o", "_id", "involves", "title", "description", "restProps", "roleId", "updates", "ids", "roles", "intersection", "cleanedUpIds", "abilityLongId", "set", "paramId", "value", "UnauthorizedError", "Err", "payload", "SubordinationError", "type", "ids", "PermissionError", "argon2", "EventEmitter", "newObjectIdString", "newObjectIdString", "snapshots", "Org", "orgs", "orgDoc", "_id", "title", "ownerIds", "restProps", "snapshot", "basisSchema", "regexps", "indexes", "preventDirectDelete", "Orgs", "users", "options", "#isPreinited", "customSchema", "customIndexes", "nullProps", "collectionOptions", "removeAll", "basisSchema", "deleteProps", "schema", "Org", "EmptyArray", "EmptySet", "#maintain", "orgDoc", "#handleCollectionChange", "next", "#resolve", "org", "slaveOrgs", "ownerOrg", "slaveOrg", "array", "sorted", "ownerId", "ownerUser", "anotherOrg", "#sortOrgs", "sort", "slaveOrgIndex", "o", "length", "a", "b", "title", "note", "restProps", "_id", "newObjectIdString", "updates", "byUser", "union", "without", "_ids", "fromId", "toId", "handler", "randomBytes", "newObjectIdString", "basisSchema", "regexps", "Session", "sessions", "sessionDoc", "user", "#sessions", "_id", "isOnline", "restProps", "updates", "ts", "expireAfterSeconds", "indexes", "Sessions", "users", "options", "customSchema", "customIndexes", "collectionOptions", "removeAll", "basisSchema", "deleteProps", "schema", "#maintain", "sessionDoc", "#handleCollectionChange", "next", "Session", "newObjectIdString", "randomBytes", "user", "props", "ts", "session", "_id", "deletedCount", "Binary", "schema", "regexps", "Avatars", "users", "options", "collectionOptions", "schema", "#maintain", "_id", "type", "data", "binaryData", "Binary", "ts", "deletedCount", "basisSchema", "regexps", "rolesSnapshots", "permissionsSnapshots", "staticUrl", "User", "users", "userDoc", "#users", "_id", "name", "email", "ownRoleIds", "orgId", "avatar", "restProps", "isEmailUpdated", "isNameUpdated", "isLastNameUpdated", "isRolesUpdated", "snapshot", "isOrgUpdated", "empty", "roleId", "role", "involvedRole", "_ids", "slaveIds", "org", "slaveOrg", "user", "hasAny", "permissiveOrgIds", "sessionsLimit", "a", "b", "isOnline", "session", "debounce", "removeOne", "indexes", "Users", "_Users", "collections", "options", "eventEmitter", "EventEmitter", "#eventEmitter", "AbilitiesMap", "event", "callback", "context", "#isPreinited", "customIndexes", "customSchema", "initialRootProps", "collectionOptions", "removeAll", "basisSchema", "deleteProps", "schema", "#maintain", "userDoc", "rolesOptions", "orgsOptions", "sessionsOptions", "avatarsOptions", "quiet", "Roles", "Orgs", "Sessions", "Avatars", "#handleCollectionChange", "#initPromise", "next", "User", "a", "b", "shouldUpdateRoles", "user", "StatefulPromise", "email", "password", "roles", "name", "org", "job", "restProps", "_id", "newObjectIdString", "updates", "byUser", "without", "newPassword", "sessionProps", "session", "#sortUsersAndOrgs", "Org", "ids", "_ids", "fromId", "toId", "handler", "deletedCount"]
4
+ "sourcesContent": ["export function _ids<T extends { _id: string }>(iterable: Set<T> | T[]): string[] {\n\tif (iterable instanceof Set) {\n\t\tconst ids = [];\n\t\t\n\t\tfor (const object of iterable)\n\t\t\tids.push(object._id);\n\t\t\n\t\treturn ids;\n\t}\n\t\n\treturn iterable.map(object => object._id);\n}\n", "export function add<T>(array: T[], ...items: T[]): number {\n\t\n\tlet added = 0;\n\t\n\tfor (const item of items)\n\t\tif (!array.includes(item)) {\n\t\t\tarray.push(item);\n\t\t\tadded++;\n\t\t}\n\t\n\treturn added;\n}\n", "export function setPath<V>(object: Record<string, unknown>, path: string, value: V): null | V {\n\tif (object && path) {\n\t\tif (path.includes(\".\")) {\n\t\t\tconst keys = path.split(\".\");\n\t\t\tlet subObject: any = object;// eslint-disable-line @typescript-eslint/no-explicit-any\n\t\t\t\n\t\t\tfor (let i = 0; i < keys.length - 1; i++) {\n\t\t\t\tconst key = keys[i];\n\t\t\t\tconst subObjectValue = subObject[key];\n\t\t\t\t\n\t\t\t\tsubObject =\n\t\t\t\t\t(subObjectValue && typeof subObjectValue == \"object\") ?\n\t\t\t\t\t\tsubObjectValue :\n\t\t\t\t\t\t(subObject[key] = {});\n\t\t\t}\n\t\t\t\n\t\t\treturn (subObject[keys.at(-1)!] = value);\n\t\t}\n\t\t\n\t\treturn (object[path] = value) as V;\n\t}\n\t\n\treturn null;\n}\n", "import { setPath } from \"./setPath.js\";\n\n\nexport function assignPath<T extends Record<string, unknown>>(target: T, ...sources: Record<string, unknown>[]): T {\n\tfor (const source of sources)\n\t\tfor (const path in source)\n\t\t\tif (Object.hasOwn(source, path))\n\t\t\t\tsetPath(target, path, source[path]);\n\t\n\treturn target;\n}\n", "export function noop() { /**/ }\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n\ntype Value<T> = PromiseLike<T> | T;\ntype Resolve<T> = (value: Value<T>) => void;\ntype Reject = (reason?: any) => void;\n\ntype Options = {\n\tsignal?: AbortSignal;\n\ttimeout?: number;\n};\n\nconst nativesMap = new WeakMap<StatefulPromise<any>, { resolve: Resolve<any>; reject: Reject }>();\n\n\nexport class StatefulPromise<T> extends Promise<T> {\n\tconstructor(\n\t\texecutor?: (resolve: Resolve<T>, reject: Reject) => void,\n\t\toptions?: Options\n\t) {\n\t\tlet nativeResolve: Resolve<T>;\n\t\tlet nativeReject: Reject;\n\t\t\n\t\tsuper((resolve, reject) => {\n\t\t\tnativeResolve = resolve;\n\t\t\tnativeReject = reject;\n\t\t\t\n\t\t});\n\t\t\n\t\tnativesMap.set(this, { resolve: nativeResolve!, reject: nativeReject! });\n\t\t\n\t\tif (options?.signal)\n\t\t\tif (options.signal.aborted)\n\t\t\t\tthis.reject(new DOMException(\"Aborted\", \"AbortError\"));\n\t\t\telse {\n\t\t\t\tconst abortListener = () => this.reject(new DOMException(\"Aborted\", \"AbortError\"));\n\t\t\t\t\n\t\t\t\toptions.signal.addEventListener(\"abort\", abortListener);\n\t\t\t\t\n\t\t\t\tthis.finally(() => options.signal?.removeEventListener(\"abort\", abortListener));\n\t\t\t}\n\t\t\n\t\tif (typeof options?.timeout === \"number\" && Number.isFinite(options.timeout)) {\n\t\t\tconst timeout = setTimeout(() => this.reject(new DOMException(\"Timeout exceeded\", \"TimeoutError\")), options.timeout);\n\t\t\t\n\t\t\tthis.finally(() => clearTimeout(timeout));\n\t\t}\n\t\t\n\t\texecutor?.(this.resolve, this.reject);\n\t\t\n\t}\n\t\n\tisPending = true;\n\tisFulfilled = false;\n\tisRejected = false;\n\t\n\tstate: \"fulfilled\" | \"pending\" | \"rejected\" = \"pending\";\n\t\n\tresult?: T | unknown;\n\t\n\treadonly resolve = (value: Value<T>) => {\n\t\t\n\t\tif (this.isPending) {\n\t\t\tthis.isPending = false;\n\t\t\tthis.isFulfilled = true;\n\t\t\tthis.state = \"fulfilled\";\n\t\t\tthis.result = value;\n\t\t\t\n\t\t\tconst native = nativesMap.get(this);\n\t\t\t\n\t\t\tif (native) {\n\t\t\t\tnative.resolve.call(this, value);\n\t\t\t\tnativesMap.delete(this);\n\t\t\t}\n\t\t}\n\t\t\n\t};\n\t\n\treadonly reject = (reason?: any) => {\n\t\t\n\t\tif (this.isPending) {\n\t\t\tthis.isPending = false;\n\t\t\tthis.isRejected = true;\n\t\t\tthis.state = \"rejected\";\n\t\t\tthis.result = reason;\n\t\t\t\n\t\t\tconst native = nativesMap.get(this);\n\t\t\t\n\t\t\tif (native) {\n\t\t\t\tnative.reject.call(this, reason);\n\t\t\t\tnativesMap.delete(this);\n\t\t\t}\n\t\t}\n\t\t\n\t};\n\t\n\t\n\tstatic resolved<U>(value: U): StatefulPromise<U> {\n\t\treturn new StatefulPromise<U>(resolve => resolve(value));\n\t}\n\t\n\tstatic rejected(reason: unknown): StatefulPromise<never> {\n\t\treturn new StatefulPromise((_, reject) => reject(reason));\n\t}\n\t\n}\n", "import { noop } from \"./noop.js\";\nimport { StatefulPromise } from \"./StatefulPromise.js\";\n\n\ntype Callback = (...args: any[]) => unknown;// eslint-disable-line @typescript-eslint/no-explicit-any\ntype FunctionOrBoolean = (() => unknown) | boolean;\ntype Options = { leading?: FunctionOrBoolean; maxWait?: number; trailing?: FunctionOrBoolean };\n\ntype DebouncedFunction<C extends Callback> = {\n\t(this: ThisParameterType<C>, ...args: Parameters<C>): Promise<Awaited<ReturnType<C>>>;\n};\n\nexport type Debounced<C extends Callback, R extends ReturnType<C>> = DebouncedFunction<C> & {\n\tcallback: C;\n\tpromise: StatefulPromise<R>;\n\tresolve: (value: R) => void;\n\treject: (reason?: unknown) => void;\n\trun(): Promise<R>;\n\tclear(shouldRun?: boolean): Promise<void>;\n};\n\n\nexport function debounce<C extends Callback, R extends ReturnType<C>>(callback: C, limit = 0, options: Options = {}) {\n\tlet { leading = false, trailing = true } = options;\n\tconst { maxWait = Infinity } = options;\n\t\n\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\tlet maxWaitTimeout: ReturnType<typeof setTimeout> | undefined;\n\tlet end: number | undefined;\n\tlet context: ThisParameterType<C>;\n\tlet args: unknown[];\n\tlet initial: FunctionOrBoolean;\n\tlet final: FunctionOrBoolean;\n\tlet result: R;\n\t\n\tconst expired = async () => {\n\t\t\n\t\tconst n = Date.now();\n\t\t\n\t\tif (n >= end!) {\n\t\t\ttimeout = undefined;\n\t\t\tend = undefined;\n\t\t\t\n\t\t\tclearTimeout(maxWaitTimeout);\n\t\t\tmaxWaitTimeout = undefined;\n\t\t\t\n\t\t\tif (typeof final == \"function\")\n\t\t\t\tawait final();\n\t\t\t\n\t\t\tdebounced.resolve(result);\n\t\t\t\n\t\t\tinitial = leading;\n\t\t} else {\n\t\t\tclearTimeout(timeout);\n\t\t\ttimeout = setTimeout(expired, end! - n);\n\t\t}\n\t\t\n\t};\n\t\n\tconst maxWaitExpired = Number.isFinite(maxWait) ? () => {\n\t\t\n\t\tif (final === run)\n\t\t\tfinal = false;\n\t\t\n\t\trun();\n\t\t\n\t\tmaxWaitTimeout = setTimeout(maxWaitExpired as TimerHandler, maxWait);\n\t\t\n\t} : null;\n\t\n\tasync function run() {\n\t\ttry {\n\t\t\tresult = await callback.apply(context, args) as R;\n\t\t\t\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tdebounced.reject(error);\n\t\t\t\n\t\t\tthrow error;\n\t\t}\n\t}\n\t\n\tif (leading && typeof leading == \"boolean\")\n\t\tleading = run;\n\tinitial = leading;\n\t\n\tif (trailing && typeof trailing == \"boolean\")\n\t\ttrailing = run;\n\tfinal = trailing;\n\t\n\tconst debounced: Debounced<C, R> = Object.assign(function (..._args) {\n\t\targs = _args;\n\t\tcontext = this;// eslint-disable-line no-invalid-this\n\t\t\n\t\tend = Date.now() + limit;\n\t\tfinal = trailing;\n\t\t\n\t\tif (!debounced.promise.isPending)\n\t\t\tdebounced.promise = new StatefulPromise<R>((resolve, reject) => {\n\t\t\t\tdebounced.resolve = resolve;\n\t\t\t\tdebounced.reject = reject;\n\t\t\t\t\n\t\t\t\tif (typeof initial == \"function\") {\n\t\t\t\t\tinitial();\n\t\t\t\t\t\n\t\t\t\t\tinitial = false;\n\t\t\t\t\t\n\t\t\t\t\tif (final === run)\n\t\t\t\t\t\tfinal = false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (!timeout) {\n\t\t\t\t\ttimeout = setTimeout(expired, limit);\n\t\t\t\t\t\n\t\t\t\t\tif (maxWaitExpired)\n\t\t\t\t\t\tmaxWaitTimeout = setTimeout(maxWaitExpired, maxWait);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});\n\t\t\n\t\treturn debounced.promise;\n\t} as DebouncedFunction<C>, {\n\t\tcallback,\n\t\tpromise: StatefulPromise.resolved(undefined as unknown as R),\n\t\tresolve: noop,\n\t\treject: noop,\n\t\trun,\n\t\tclear: async (shouldRun?: boolean) => {\n\t\t\t\n\t\t\tclearTimeout(timeout);\n\t\t\ttimeout = undefined;\n\t\t\t\n\t\t\tclearTimeout(maxWaitTimeout);\n\t\t\tmaxWaitTimeout = undefined;\n\t\t\t\n\t\t\tdebounced.resolve(shouldRun ? await run() : result);\n\t\t\t\n\t\t}\n\t});\n\t\n\treturn debounced;\n}\n\n\ndebounce.noop = Object.assign(() => { /**/ }, {\n\tcallback: noop,\n\tpromise: StatefulPromise.resolved(undefined), // eslint-disable-line unicorn/no-useless-undefined\n\tresolve: noop,\n\treject: noop,\n\trun: noop,\n\tclear: noop\n}) as Debounced<() => void, void>;\n\n\nexport function throttle(callback: Callback, limit?: number, options?: Options) {\n\treturn debounce(callback, limit, {\n\t\tmaxWait: limit,\n\t\tleading: true,\n\t\ttrailing: true,\n\t\t...options\n\t});\n}\n", "export function deletePath(object: Record<string, unknown>, path: string): boolean {\n\tif (object && path) {\n\t\tif (path.includes(\".\")) {\n\t\t\tconst keys = path.split(\".\");\n\t\t\tlet subObject: any = object; // eslint-disable-line @typescript-eslint/no-explicit-any\n\t\t\t\n\t\t\tfor (let i = 0; i < keys.length - 1; i++) {\n\t\t\t\tconst key = keys[i];\n\t\t\t\tconst subObjectValue = subObject[key];\n\t\t\t\t\n\t\t\t\tif (subObjectValue && typeof subObjectValue === \"object\")\n\t\t\t\t\tsubObject = subObjectValue;\n\t\t\t\telse\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tconst lastKey = keys.at(-1)!;\n\t\t\t\n\t\t\treturn lastKey in subObject && delete subObject[lastKey];\n\t\t}\n\t\t\n\t\treturn path in object && delete object[path];\n\t}\n\t\n\treturn false;\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n\n\nexport function deleteProps(object: null | undefined, keys: any): null;\nexport function deleteProps<O extends object, K extends readonly (keyof O | number | string | symbol)[]>(object: O, keys: K): Omit<O, K[number]>;\nexport function deleteProps<O extends object, K extends readonly (keyof O | number | string | symbol)[]>(object: O, keys: K) {\n\tif (object) {\n\t\tfor (const key of keys)\n\t\t\tdelete object[key as keyof O];\n\t\t\n\t\treturn object as Omit<O, K[number]>;\n\t}\n\t\n\treturn null;\n}\n", "export function empty<O extends object>(object: O) {\n\t// eslint-disable-next-line guard-for-in\n\tfor (const key in object)\n\t\tdelete object[key as keyof O];\n\t\n\treturn object;\n}\n", "export class EmptyArray extends Array {\n\tconstructor() {\n\t\tsuper();\n\t\t\n\t\tObject.freeze(this);\n\t\t\n\t}\n\t\n\tpush() {\n\t\treturn 0;\n\t}\n\t\n\tunshift() {\n\t\treturn 0;\n\t}\n\t\n\tsplice() {\n\t\treturn [];\n\t}\n\t\n}\n", "export class EmptySet extends Set {\n\t// eslint-disable-next-line no-useless-constructor\n\tconstructor() {\n\t\tsuper();\n\t\t\n\t}\n\t\n\tadd() {\n\t\treturn this;\n\t}\n\t\n}\n", "/* eslint-disable unicorn/prevent-abbreviations, unicorn/custom-error-definition */\n\n\ntype Payload = Record<string, unknown>;\n\ntype PayloadWithMessage = Payload & {\n\tmessage: string;\n};\n\n\nexport class Err extends Error {\n\tconstructor(payload: PayloadWithMessage);\n\tconstructor(message: string, tag: string | null, payload?: Payload);\n\tconstructor(message: string, payload?: Payload);\n\tconstructor(message: PayloadWithMessage | string, tag: Payload | string | null = null, payload?: Payload) {\n\t\tif (typeof message == \"object\") {\n\t\t\tpayload = message;\n\t\t\tmessage = payload.message as string;\n\t\t\tdelete payload.message;\n\t\t\ttag = null;\n\t\t} else if (tag && typeof tag == \"object\") {\n\t\t\tpayload = tag;\n\t\t\ttag = null;\n\t\t}\n\t\t\n\t\tsuper(message);\n\t\t\n\t\tthis.tag = tag;\n\t\t\n\t\tif (payload)\n\t\t\tObject.assign(this, payload);\n\t\t\n\t}\n\t\n\tname = \"Err-or\";\n\t\n\ttag: string | null;\n\t\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n\n\nexport function getAll<V>(map: Map<any, V>, keys: any[], onlyExisting: true): V[];\nexport function getAll<V>(map: Map<any, V>, keys: any[], onlyExisting?: false): (V | undefined)[];\nexport function getAll<V>(map: Map<any, V>, keys: any[], onlyExisting = false) {\n\t\n\tconst items = [];\n\t\n\tif (onlyExisting)\n\t\tfor (const key of keys) {\n\t\t\tconst item = map.get(key);\n\t\t\tif (item !== undefined)\n\t\t\t\titems.push(item);\n\t\t}\n\telse\n\t\tfor (const key of keys)\n\t\t\titems.push(map.get(key));\n\t\n\treturn items;\n}\n", "export function getPath(object: Record<string, unknown>, path: string): unknown {\n\tif (path) {\n\t\tif (path.includes(\".\")) {\n\t\t\tlet subObject: any = object;// eslint-disable-line @typescript-eslint/no-explicit-any\n\t\t\t\n\t\t\tfor (const key of path.split(\".\")) {\n\t\t\t\tsubObject = subObject?.[key];\n\t\t\t\t\n\t\t\t\tif (subObject === undefined)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\treturn subObject;\n\t\t}\n\t\t\n\t\treturn object[path];\n\t}\n\t\n\treturn object;\n}\n", "export function hasAny<K, V>(mapOrSet: Map<K, V> | Set<K>, items: K[] | Set<K>) {\n\tfor (const item of items)\n\t\tif (mapOrSet.has(item))\n\t\t\treturn true;\n\t\n\treturn false;\n}\n", "export function howmuch(number: [] | number, one: string, two: string, five: boolean | string, shouldPrintNumber = true) {\n\tif (Array.isArray(number))\n\t\tnumber = number.length;\n\t\n\tif (typeof five != \"string\") {\n\t\tshouldPrintNumber = five ?? true;\n\t\tfive = two;\n\t}\n\t\n\t\n\treturn (shouldPrintNumber ? `${number}\u00A0` : \"\") + howmuch.raw(number, one, two, five);\n}\n\nhowmuch.raw = (number: number, one: string, two: string, five = two) => {\n\tnumber = Math.abs(number);\n\tconst u = number % 10;\n\tconst d = number % 100;\n\t\n\treturn (\n\t\t(u === 1 && d !== 11) ?\n\t\t\tone :\n\t\t\t((u >= 2 && u <= 4) && !(d >= 12 && d <= 15)) ?\n\t\t\t\ttwo :\n\t\t\t\tfive\n\t);\n};\n", "export function intersection<I>(...iterables: (I[] | Set<I>)[]): I[] {\n\t\n\tconst intersectionArray = [];\n\t\n\tif (iterables.length) {\n\t\tconst [ firstIterable, ...otherIterables ] = iterables;\n\t\t\n\t\tmainLoop: for (const item of firstIterable) {\n\t\t\tfor (const otherIterable of otherIterables)\n\t\t\t\tif (otherIterable instanceof Set ? !otherIterable.has(item) : !otherIterable.includes(item))\n\t\t\t\t\tcontinue mainLoop;\n\t\t\tintersectionArray.push(item);\n\t\t}\n\t}\n\t\n\treturn intersectionArray;\n}\n", "export function pick<O extends object, K extends keyof O>(object: O, keys: K[]) {\n\t\n\tconst picked: Partial<Pick<O, K>> = {};\n\t\n\tfor (const key of keys)\n\t\tif (key in object)\n\t\t\tpicked[key] = object[key];\n\t\n\treturn picked as Pick<O, K>;\n}\n", "export function reAdd<S extends Set<I>, I>(set: S, item: I) {\n\tset.delete(item);\n\tset.add(item);\n\t\n\treturn set;\n}\n", "export function removeAll<T>(array: T[], items: T[]): number {\n\t\n\tlet i,\n\t\tremoved = 0;\n\t\n\tfor (const item of items)\n\t\twhile ((i = array.indexOf(item)) > -1) {\n\t\t\tarray.splice(i, 1);\n\t\t\tremoved++;\n\t\t}\n\t\n\treturn removed;\n}\n", "export function removeOne<T>(array: T[], item: T): boolean {\n\tconst i = array.indexOf(item);\n\tif (i > -1) {\n\t\tarray.splice(i, 1);\n\t\t\n\t\treturn true;\n\t}\n\t\n\treturn false;\n}\n", "export function sort<I>(set: Set<I>, compareFn?: ((a: I, b: I) => number)) {\n\tfor (const item of [ ...set ].sort(compareFn)) {\n\t\tset.delete(item);\n\t\tset.add(item);\n\t}\n\t\n\treturn set;\n}\n", "export function union<I>(...iterables: I[][]): I[] {\n\treturn [ ...new Set(iterables.flat()) ];\n}\n", "export function without<I>(array: I[], arrayToExclude: I[]): I[] {\n\treturn array.filter(item => !arrayToExclude.includes(item));\n}\n", "import { Err } from \"@nesvet/n\";\n\n\ntype Payload = Record<string, unknown>;\n\n\nexport class AbilityError extends Err {\n\tconstructor(payload?: Payload);\n\tconstructor(longId: string, payload?: Payload);\n\tconstructor(longId?: Payload | string, payload?: Payload) {\n\t\tif (typeof longId == \"object\") {\n\t\t\tpayload = longId;\n\t\t\tlongId = undefined;\n\t\t}\n\t\t\n\t\tsuper(\"User lacks ability\", \"lacksability\", {\n\t\t\t...longId && { ability: longId },\n\t\t\t...payload\n\t\t});\n\t\t\n\t}\n\t\n\tname = \"AbilityError\";\n\t\n}\n", "import type { Prettify } from \"@nesvet/n\";\nimport type { AbilitySchema as OriginalAbilitySchema } from \"insite-common\";\n\n\ntype AbilityParamItem = string;\nexport type AbilityParamItems = AbilityParamItem[];\nexport type AbilityParamNumber = number;\nexport type AbilityParam = AbilityParamItems | AbilityParamNumber;\n\nexport type AbilityWithParams = Record<string, AbilityParam>;\nexport type AbilityObject = Record<string, Ability | AbilityParam>;\nexport type AbilityBoolean = true;\nexport type Ability = AbilityBoolean | { [key: string]: Ability | AbilityParam };\n\nexport type AbilitySchema = Prettify<\n\tOmit<OriginalAbilitySchema, \"abilities\"> & {\n\t\tlevel: number;\n\t\tlongId: string;\n\t\tabilities?: AbilitySchema[];\n\t}\n>;\n\nexport type GenericAbilities = Record<string, Ability>;\n\nexport function isAbilityObject(value: Ability): value is AbilityObject {\n\treturn typeof value == \"object\";\n}\n\nexport function isAbilityParamNumber(value: AbilityParam): value is AbilityParamNumber {\n\treturn typeof value == \"number\";\n}\n\nexport function isAbilityParamItems(value: AbilityParam): value is AbilityParamItems {\n\treturn Array.isArray(value);\n}\n", "import {\n\tadd,\n\tassignPath,\n\tdeletePath,\n\tempty,\n\tgetPath,\n\tintersection,\n\tpick,\n\tsetPath\n} from \"@nesvet/n\";\nimport type { Abilities, AbilitiesSchema, AbilityParamSchema } from \"insite-common\";\nimport {\n\tisAbilityObject,\n\tisAbilityParamItems,\n\tisAbilityParamNumber,\n\ttype Ability,\n\ttype AbilityObject,\n\ttype AbilityParam,\n\ttype AbilityParamItems,\n\ttype AbilityParamNumber,\n\ttype AbilitySchema,\n\ttype GenericAbilities\n} from \"./types\";\n\n\nconst schemaParentMap = new Map<AbilitySchema, AbilitySchema | null>();\n\n\nexport class AbilitiesMap<AS extends AbilitiesSchema> extends Map<string, AbilitySchema> {\n\tconstructor(abilitiesSchema: AS) {\n\t\tsuper();\n\t\t\n\t\tfor (const subSchema of abilitiesSchema) {\n\t\t\tdelete subSchema.top;/* The first level is always top */\n\t\t\t\n\t\t\tthis.#hierarchical.push(subSchema as AbilitySchema);\n\t\t}\n\t\t\n\t\t(function parse(this: AbilitiesMap<AS>, schemas: AbilitiesSchema, parent: AbilitySchema | null, level: number) {\n\t\t\tfor (const schema of schemas as AbilitySchema[]) {\n\t\t\t\tschemaParentMap.set(schema, parent);\n\t\t\t\t\n\t\t\t\tschema.level = level;\n\t\t\t\t\n\t\t\t\tif (!parent || schema.top) {\n\t\t\t\t\tschema.longId = schema._id;\n\t\t\t\t\t\n\t\t\t\t\tif (this.has(schema._id))\n\t\t\t\t\t\tthrow new Error(`Top-level ability duplicate: ${schema._id}`);\n\t\t\t\t\t\n\t\t\t\t\tthis.set(schema._id, schema);\n\t\t\t\t} else\n\t\t\t\t\tschema.longId = parent ? `${parent.longId}.${schema._id}` : schema._id;\n\t\t\t\t\n\t\t\t\tif (schema.abilities)\n\t\t\t\t\tparse.call(this, schema.abilities, schema, level + 1);\n\t\t\t}\n\t\t\t\n\t\t}).call(this, abilitiesSchema, null, 0);\n\t\t\n\t}\n\t\n\t#hierarchical: AbilitySchema[] = [];\n\t\n\tget(longId: string, parent?: AbilitySchema | null) {\n\t\tconst subIds = longId.split(\".\");\n\t\tlet schema = parent ?? super.get(subIds.shift()!);\n\t\t\n\t\tif (schema && subIds.length)\n\t\t\tfor (const subId of subIds) {\n\t\t\t\tschema = schema?.abilities?.find(({ _id, top }) => !top && _id === subId);\n\t\t\t\tif (!schema)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\n\t\treturn schema;\n\t}\n\t\n\tgetSchema = this.get;\n\t\n\tgetParamSchema(longId: string, paramId: string) {\n\t\treturn this.get(longId)?.params?.find(({ _id }) => _id === paramId);\n\t}\n\t\n\tgetDefaultParam(longId: string, paramId: string, max?: boolean): AbilityParam | undefined;\n\tgetDefaultParam(schema: AbilityParamSchema, max?: boolean): AbilityParam;\n\tgetDefaultParam(schemaOrLongId: AbilityParamSchema | string, paramIdOrMax?: boolean | string, max?: boolean) {\n\t\tif (paramIdOrMax === undefined || typeof paramIdOrMax == \"boolean\")\n\t\t\tmax = paramIdOrMax;\n\t\t\n\t\tconst schema = typeof schemaOrLongId == \"string\" ? this.getParamSchema(schemaOrLongId, paramIdOrMax as string) : schemaOrLongId;\n\t\t\n\t\tif (schema)\n\t\t\tswitch (schema.type) {\n\t\t\t\tcase \"number\":\n\t\t\t\t\treturn max ?\n\t\t\t\t\t\t(schema.max ?? Infinity) :\n\t\t\t\t\t\t(schema.min ?? 0);\n\t\t\t\t\n\t\t\t\tcase \"items\":\n\t\t\t\t\treturn max ?\n\t\t\t\t\t\tschema.items.map(({ _id }) => _id) :\n\t\t\t\t\t\t[];\n\t\t\t}\n\t\t\n\t\treturn undefined;// eslint-disable-line unicorn/no-useless-undefined\n\t}\n\t\n\tgetDefaultAbility(schema: string, max?: boolean): Ability | undefined;\n\tgetDefaultAbility(schema: AbilitySchema, max?: boolean): Ability;\n\tgetDefaultAbility(schema: AbilitySchema | string, max: boolean = !schema): Ability | undefined {\n\t\tif (typeof schema == \"string\")\n\t\t\tschema = this.get(schema)!;\n\t\t\n\t\tif (schema) {\n\t\t\tif (schema.abilities || schema.params) {\n\t\t\t\tconst ability = {} as AbilityObject;\n\t\t\t\t\n\t\t\t\tif (schema.params)\n\t\t\t\t\tfor (const paramSchema of schema.params)\n\t\t\t\t\t\tability[paramSchema._id] = this.getDefaultParam(paramSchema, max);\n\t\t\t\t\n\t\t\t\tif (max && schema.abilities)\n\t\t\t\t\tfor (const subSchema of schema.abilities)\n\t\t\t\t\t\tif (!subSchema.top)\n\t\t\t\t\t\t\tability[subSchema._id] = this.getDefaultAbility(subSchema, max);\n\t\t\t\t\n\t\t\t\treturn ability;\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn undefined;\n\t}\n\t\n\tgetDefaultAbilities(): Abilities<AS>;\n\tgetDefaultAbilities(schemas: AbilitySchema[], max?: boolean): Abilities<AS>;\n\tgetDefaultAbilities(schema: AbilitySchema, max?: boolean): Abilities<AS>;\n\tgetDefaultAbilities(longIds: string[], max?: boolean): Abilities<AS>;\n\tgetDefaultAbilities(longId: string, max?: boolean): Abilities<AS>;\n\tgetDefaultAbilities(schemasOrIds?: (AbilitySchema | string)[] | AbilitySchema | string, max: boolean = !schemasOrIds) {\n\t\t\n\t\tconst schemas = (\n\t\t\tschemasOrIds ?\n\t\t\t\t(Array.isArray(schemasOrIds) ? schemasOrIds : [ schemasOrIds ])\n\t\t\t\t\t.map(schema => (typeof schema == \"string\" ? this.get(schema) : schema))\n\t\t\t\t\t.filter(Boolean) as AbilitySchema[] :\n\t\t\t\t[ ...this.values() ]\n\t\t).sort((a, b) => a.level - b.level);\n\t\t\n\t\tconst schemaMaxMap = new Map<AbilitySchema, boolean>();\n\t\t\n\t\tfor (const schema of schemas) {\n\t\t\t(function resolve(_schema) {\n\t\t\t\tconst parentSchema = schemaParentMap.get(_schema);\n\t\t\t\t\n\t\t\t\tif (parentSchema) {\n\t\t\t\t\tresolve(parentSchema);\n\t\t\t\t\t\n\t\t\t\t\tif (!schemaMaxMap.has(parentSchema))\n\t\t\t\t\t\tschemaMaxMap.set(parentSchema, false);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t})(schema);\n\t\t\t\n\t\t\tif (max)\n\t\t\t\t(function resolve(_schema) {\n\t\t\t\t\tif (!schemaMaxMap.has(_schema))\n\t\t\t\t\t\tschemaMaxMap.set(_schema, true);\n\t\t\t\t\t\n\t\t\t\t\tif (_schema.abilities)\n\t\t\t\t\t\tfor (const subSchema of _schema.abilities)\n\t\t\t\t\t\t\tif (subSchema.top)\n\t\t\t\t\t\t\t\tresolve(subSchema);\n\t\t\t\t\t\n\t\t\t\t})(schema);\n\t\t\telse\n\t\t\t\tif (!schemaMaxMap.has(schema))\n\t\t\t\t\tschemaMaxMap.set(schema, false);\n\t\t}\n\t\t\n\t\treturn assignPath(\n\t\t\t{},\n\t\t\tObject.fromEntries(\n\t\t\t\t[ ...schemaMaxMap ]\n\t\t\t\t\t.map(([ schema, _max ]) => [ schema.longId, this.getDefaultAbility(schema, _max) ])\n\t\t\t)\n\t\t);\n\t}\n\t\n\tgetSchemeFor(abilities: GenericAbilities) {\n\t\tabilities = this.adjust(structuredClone(abilities));\n\t\t\n\t\treturn (function resolve(subSchemas: AbilitySchema[], subAbilities: GenericAbilities) {\n\t\t\tfor (let i = 0; i < subSchemas.length; i++) {\n\t\t\t\tconst schema = subSchemas[i];\n\t\t\t\tconst ability = schema.top ? abilities[schema._id] : subAbilities[schema._id];\n\t\t\t\t\n\t\t\t\tif (ability) {\n\t\t\t\t\tif (schema.params)\n\t\t\t\t\t\tfor (const paramSchema of schema.params) {\n\t\t\t\t\t\t\tconst abilityParam = (ability as AbilityObject)[paramSchema._id];\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tswitch (paramSchema.type) {\n\t\t\t\t\t\t\t\tcase \"number\":\n\t\t\t\t\t\t\t\t\tparamSchema.max = abilityParam as AbilityParamNumber;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tcase \"items\":\n\t\t\t\t\t\t\t\t\tparamSchema.items = paramSchema.items.filter(({ _id }) => (abilityParam as AbilityParamItems).includes(_id));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (schema.abilities) {\n\t\t\t\t\t\tresolve(schema.abilities, ability as GenericAbilities);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!schema.abilities.length)\n\t\t\t\t\t\t\tdelete schema.abilities;\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t\tsubSchemas.splice(i--, 1);\n\t\t\t}\n\t\t\t\n\t\t\treturn subSchemas;\n\t\t})(structuredClone(this.#hierarchical), abilities);\n\t}\n\t\n\tgetParam(abilities: GenericAbilities, longId: string, paramId: string) {\n\t\tif (this.getParamSchema(longId, paramId)) {\n\t\t\tconst value = getPath(abilities, `${longId}.${paramId}`) as AbilityParam;\n\t\t\t\n\t\t\tif (this.isParamFits(longId, paramId, value))\n\t\t\t\treturn value;\n\t\t\t\n\t\t\treturn this.getDefaultParam(longId, paramId)!;\n\t\t}\n\t\t\n\t\treturn undefined;// eslint-disable-line unicorn/no-useless-undefined\n\t}\n\t\n\tsetParam(abilities: GenericAbilities, longId: string, paramId: string, value: AbilityParam): Abilities<AS> {\n\t\tconst schema = this.getParamSchema(longId, paramId);\n\t\t\n\t\tif (!schema)\n\t\t\tthrow new Error(`No such ability param: ${longId}.${paramId}`);\n\t\t\n\t\tsetPath(abilities, `${longId}.${paramId}`, this.adjustParam(schema, value));\n\t\t\n\t\treturn abilities as Abilities<AS>;\n\t}\n\t\n\tisParamFits(longId: string, paramId: string, value: AbilityParam, referenceValue?: AbilityParam) {\n\t\tif (value !== undefined) {\n\t\t\tconst paramSchema = this.getParamSchema(longId, paramId);\n\t\t\t\n\t\t\tif (paramSchema)\n\t\t\t\tswitch (paramSchema.type) {\n\t\t\t\t\tcase \"number\":\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tisAbilityParamNumber(value) &&\n\t\t\t\t\t\t\t(paramSchema.min === undefined || value >= paramSchema.min) && (\n\t\t\t\t\t\t\t\treferenceValue === undefined ?\n\t\t\t\t\t\t\t\t\t(paramSchema.max === undefined || value <= paramSchema.max) :\n\t\t\t\t\t\t\t\t\tvalue <= (referenceValue as AbilityParamNumber)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t\t\n\t\t\t\t\tcase \"items\":\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\tisAbilityParamItems(value) &&\n\t\t\t\t\t\t\tvalue.length === new Set(value).size && (\n\t\t\t\t\t\t\t\treferenceValue === undefined ?\n\t\t\t\t\t\t\t\t\tvalue.every(itemId => paramSchema.items.find(({ _id }) => _id === itemId)) :\n\t\t\t\t\t\t\t\t\tvalue.every(itemId => (referenceValue as AbilityParamItems).includes(itemId))\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tadjustParam(paramSchema: AbilityParamSchema, value: AbilityParam) {\n\t\tswitch (paramSchema.type) {\n\t\t\tcase \"number\":\n\t\t\t\treturn (\n\t\t\t\t\tisAbilityParamNumber(value) ?\n\t\t\t\t\t\tMath.max(\n\t\t\t\t\t\t\tMath.min(\n\t\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\t\tparamSchema.max ?? Infinity\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tparamSchema.min ?? 0\n\t\t\t\t\t\t) :\n\t\t\t\t\t\tparamSchema.min ?? 0\n\t\t\t\t);\n\t\t\t\n\t\t\tdefault/* paramSchema.type === \"items\" */:\n\t\t\t\treturn (\n\t\t\t\t\tisAbilityParamItems(value) ?\n\t\t\t\t\t\tintersection(paramSchema.items.map(item => item._id), value) :\n\t\t\t\t\t\t[]\n\t\t\t\t) as AbilityParamItems;\n\t\t}\n\t\t\n\t}\n\t\n\tadjust(abilities: GenericAbilities, parent?: AbilitySchema | null): Abilities<AS> {\n\t\tconst adjustedAbilities: GenericAbilities = {};\n\t\t\n\t\tfor (const [ _id, ability ] of Object.entries(abilities)) {\n\t\t\tconst schema = this.get(_id, parent);\n\t\t\t\n\t\t\tif (schema)\n\t\t\t\tif (schema.params || schema.abilities) {\n\t\t\t\t\tconst adjustedAbility: AbilityObject = {};\n\t\t\t\t\t\n\t\t\t\t\tif (schema.params)\n\t\t\t\t\t\tif (isAbilityObject(ability))\n\t\t\t\t\t\t\tfor (const paramSchema of schema.params)\n\t\t\t\t\t\t\t\tadjustedAbility[paramSchema._id] = this.adjustParam(paramSchema, ability[paramSchema._id] as AbilityParam);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tfor (const paramSchema of schema.params)\n\t\t\t\t\t\t\t\tadjustedAbility[paramSchema._id] = this.getDefaultParam(paramSchema);\n\t\t\t\t\t\n\t\t\t\t\tif (schema.abilities && isAbilityObject(ability))\n\t\t\t\t\t\tObject.assign(\n\t\t\t\t\t\t\tadjustedAbility,\n\t\t\t\t\t\t\tthis.adjust(\n\t\t\t\t\t\t\t\tpick(\n\t\t\t\t\t\t\t\t\tability,\n\t\t\t\t\t\t\t\t\tschema.abilities\n\t\t\t\t\t\t\t\t\t\t.filter(subSchema => !subSchema.top)\n\t\t\t\t\t\t\t\t\t\t.map(subSchema => subSchema._id)\n\t\t\t\t\t\t\t\t) as GenericAbilities,\n\t\t\t\t\t\t\t\tschema\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t);\n\t\t\t\t\t\n\t\t\t\t\tadjustedAbilities[_id] = adjustedAbility;\n\t\t\t\t} else\n\t\t\t\t\tadjustedAbilities[_id] = true;\n\t\t}\n\t\t\n\t\treturn Object.assign(empty(abilities), adjustedAbilities) as Abilities<AS>;\n\t}\n\t\n\tmerge(target: GenericAbilities, source: GenericAbilities, parent?: AbilitySchema | null): Abilities<AS> {\n\t\tif (!parent) {\n\t\t\tthis.adjust(target);\n\t\t\tsource = this.adjust(structuredClone(source));\n\t\t}\n\t\t\n\t\tfor (const [ _id, ability ] of Object.entries(source)) {\n\t\t\tconst schema = this.get(_id, parent);\n\t\t\t\n\t\t\tif (schema && schema.isInheritable !== false)\n\t\t\t\tif (_id in target && (schema.params || schema.abilities)) {\n\t\t\t\t\tconst targetAbility = target[_id] as AbilityObject;\n\t\t\t\t\tconst sourceAbility = ability as AbilityObject;\n\t\t\t\t\t\n\t\t\t\t\tif (schema.params)\n\t\t\t\t\t\tfor (const paramSchema of schema.params)\n\t\t\t\t\t\t\tif (paramSchema.isInheritable !== false)\n\t\t\t\t\t\t\t\tswitch (paramSchema.type) {\n\t\t\t\t\t\t\t\t\tcase \"number\":\n\t\t\t\t\t\t\t\t\t\ttargetAbility[paramSchema._id] =\n\t\t\t\t\t\t\t\t\t\t\tMath.max(\n\t\t\t\t\t\t\t\t\t\t\t\ttargetAbility[paramSchema._id] as AbilityParamNumber,\n\t\t\t\t\t\t\t\t\t\t\t\tsourceAbility[paramSchema._id] as AbilityParamNumber\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tcase \"items\":\n\t\t\t\t\t\t\t\t\t\tadd(\n\t\t\t\t\t\t\t\t\t\t\ttargetAbility[paramSchema._id] as AbilityParamItems,\n\t\t\t\t\t\t\t\t\t\t\t...sourceAbility[paramSchema._id] as AbilityParamItems\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (schema.abilities)\n\t\t\t\t\t\tthis.merge(targetAbility as GenericAbilities, sourceAbility as GenericAbilities, schema);\n\t\t\t\t} else\n\t\t\t\t\ttarget[_id] = ability;\n\t\t}\n\t\t\n\t\treturn target as Abilities<AS>;\n\t}\n\t\n\thasAbility(abilities: GenericAbilities, longId: string) {\n\t\treturn Boolean(getPath(abilities, longId));\n\t}\n\t\n\tsetAbility(target: GenericAbilities, schema: AbilitySchema): Abilities<AS>;\n\tsetAbility(target: GenericAbilities, longId: string): Abilities<AS>;\n\tsetAbility(target: GenericAbilities, schemaOrLongId: AbilitySchema | string) {\n\t\tconst schema = typeof schemaOrLongId == \"string\" ? this.get(schemaOrLongId) : schemaOrLongId;\n\t\t\n\t\tif (!schema)\n\t\t\tthrow new Error(`No such ability: ${schemaOrLongId as string}`);\n\t\t\n\t\tthis.merge(target, this.getDefaultAbilities(schema));\n\t\t\n\t\treturn target as Abilities<AS>;\n\t}\n\t\n\tunsetAbility(target: GenericAbilities, schema: AbilitySchema): Abilities<AS>;\n\tunsetAbility(target: GenericAbilities, longId: string): Abilities<AS>;\n\tunsetAbility(target: GenericAbilities, schemaOrLongId: AbilitySchema | string) {\n\t\tconst schema = typeof schemaOrLongId == \"string\" ? this.get(schemaOrLongId) : schemaOrLongId;\n\t\t\n\t\tif (!schema)\n\t\t\tthrow new Error(`No such ability: ${schemaOrLongId as string}`);\n\t\t\n\t\t(function resolve(_schema) {\n\t\t\tdeletePath(target, _schema.longId);\n\t\t\t\n\t\t\tif (_schema.abilities)\n\t\t\t\tfor (const subSchema of _schema.abilities)\n\t\t\t\t\tresolve(subSchema);\n\t\t\t\n\t\t})(schema);\n\t\t\n\t\treturn target;\n\t}\n\t\n}\n", "import { Err } from \"@nesvet/n\";\n\n\ntype Payload = Record<string, unknown>;\n\n\nexport class RolesError extends Err {\n\tconstructor(roleId: string, payload?: Payload);\n\tconstructor(roleIds: string[], payload?: Payload);\n\tconstructor(stringOrArray: Payload | string[] | string, payload?: Payload) {\n\t\tsuper(`User lacks role${Array.isArray(stringOrArray) ? \"s\" : \"\"}`, \"lacksroles\", {\n\t\t\troles: Array.isArray(stringOrArray) ? stringOrArray : [ stringOrArray ],\n\t\t\t...payload\n\t\t});\n\t\t\n\t}\n\t\n\tname = \"RolesError\";\n\t\n}\n", "import type { Abilities, AbilitiesSchema } from \"insite-common\";\nimport { Roles } from \"./Roles\";\nimport { RoleDoc } from \"./types\";\n\n\nconst snapshots = new WeakMap();\n\n\nexport class Role<AS extends AbilitiesSchema> {\n\tconstructor(roles: Roles<AS>, roleDoc: RoleDoc) {\n\t\tthis.#roles = roles;\n\t\t\n\t\tthis._id = roleDoc._id;\n\t\troles.set(this._id, this);\n\t\t\n\t\tvoid this.update(roleDoc);\n\t\t\n\t}\n\t\n\t#roles;\n\t\n\t_id;\n\townInvolveIds!: string[];\n\townAbilities!: Abilities<AS>;\n\ttitle = \"\";\n\tdisplayTitle = \"\";\n\t_o = 0;\n\t\n\townInvolves: Role<AS>[] = [];\n\tinvolves = new Set<Role<AS>>();\n\tabilities: Abilities<AS> = {};\n\tinheritedAbilities: Abilities<AS> = {};\n\t\n\tupdate({ _id, involves: ownInvolveIds, abilities: ownAbilities, title, ...restProps }: Partial<RoleDoc>) {\n\t\tObject.assign(this, restProps);\n\t\t\n\t\tif (ownInvolveIds)\n\t\t\tthis.ownInvolveIds = ownInvolveIds;\n\t\t\n\t\tif (ownAbilities)\n\t\t\tthis.ownAbilities = ownAbilities as Abilities<AS>;\n\t\t\n\t\tif (title !== undefined) {\n\t\t\tthis.title = title;\n\t\t\tthis.displayTitle = title || this._id;\n\t\t}\n\t\t\n\t\tif (ownInvolveIds || ownAbilities) {\n\t\t\tconst snapshot = [\n\t\t\t\tthis.ownInvolveIds.join(\",\"),\n\t\t\t\tJSON.stringify(this.ownAbilities)\n\t\t\t].join(\"\\n\");\n\t\t\t\n\t\t\tif (snapshot !== snapshots.get(this)) {\n\t\t\t\tsnapshots.set(this, snapshot);\n\t\t\t\t\n\t\t\t\tif (this.#roles.users.isInited)\n\t\t\t\t\tthis.#roles.update();\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tdelete() {\n\t\t\n\t\tthis.#roles.delete(this._id);\n\t\t\n\t\tsnapshots.delete(this);\n\t\t\n\t\tthis.#roles.update();\n\t\t\n\t}\n\t\n}\n", "export const regexps = {\n\t_id: /^[\\dA-Fa-f]{24}$/,\n\temail: /^[^\\s@]{1,63}@[^\\s@]{1,63}\\.[^\\s@]{1,63}$/,\n\targon2: /^\\$argon2(?:i|d|id)\\$v=\\d+\\$m=\\d+,t=\\d+,p=\\d+(?:\\$[\\d+/A-Za-z]+){2}$/,\n\t// eslint-disable-next-line unicorn/better-regex\n\tsessionId: /^(?:[\\dA-Fa-f]{16,32}\\$[\\dA-Fa-f]{16,32}|[0-9a-f]{24}~[A-Za-z0-9_-]{43})$/, // (?:old_format|new_format) - leave just the new after some time\n\trole: /^[\\d_a-z-]{1,64}$/,\n\tip: /^(?:\\d{1,3}\\.){3}\\d{1,3}$/\n};\n", "import { CollectionSchema } from \"insite-db\";\nimport { regexps } from \"../lib\";\n\n\nexport const basisSchema: CollectionSchema = {\n\trequired: [\n\t\t\"_id\",\n\t\t\"involves\",\n\t\t\"abilities\",\n\t\t\"title\",\n\t\t\"description\",\n\t\t\"meta\",\n\t\t\"createdAt\"\n\t],\n\tproperties: {\n\t\t_id: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps.role.source,\n\t\t\tnot: { enum: [ \"root\" ] }\n\t\t},\n\t\tinvolves: {\n\t\t\tbsonType: \"array\",\n\t\t\tuniqueItems: true,\n\t\t\titems: {\n\t\t\t\tbsonType: \"string\",\n\t\t\t\tpattern: regexps.role.source,\n\t\t\t\tnot: { enum: [ \"root\" ] }\n\t\t\t},\n\t\t\tadditionalItems: false\n\t\t},\n\t\tabilities: {\n\t\t\tbsonType: \"object\"\n\t\t},\n\t\ttitle: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 256\n\t\t},\n\t\tdescription: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 10240\n\t\t},\n\t\tmeta: {\n\t\t\tbsonType: \"object\"\n\t\t},\n\t\tcreatedAt: {\n\t\t\tbsonType: \"number\"\n\t\t}\n\t},\n\tadditionalProperties: false\n};\n", "import {\n\tdeleteProps,\n\tgetAll,\n\tintersection,\n\treAdd,\n\tremoveAll\n} from \"@nesvet/n\";\nimport type { AbilitiesSchema } from \"insite-common\";\nimport type { ChangeStreamDocument, CollectionIndexes, WatchedCollection } from \"insite-db\";\nimport type { AbilityParam, GenericAbilities } from \"../abilities/types\";\nimport type { Users } from \"../users\";\nimport { Role } from \"./Role\";\nimport { basisSchema } from \"./schema\";\nimport type { NewRole, RoleDoc, RolesOptions } from \"./types\";\n\n\nconst indexes: CollectionIndexes = [\n\t[ { involves: 1 } ]\n];\n\nfunction preventDirectDelete() {\n\tthrow new Error(\"Direct usage of roles collection.deleteOne or .deleteMany is forbidden. Use roles.deleteRole instead.\");\n}\n\n\nexport class Roles<AS extends AbilitiesSchema> extends Map<string, Role<AS>> {\n\tconstructor(users: Users<AS>, options: RolesOptions = {}) {\n\t\tsuper();\n\t\t\n\t\tconst {\n\t\t\troot: rootProps,\n\t\t\t...initOptions\n\t\t} = options;\n\t\t\n\t\tthis.users = users;\n\t\tthis.collections = users.collections;\n\t\tthis.abilities = users.abilities;\n\t\t\n\t\tthis.root = new Role<AS>(this, {\n\t\t\t...rootProps,\n\t\t\t_id: \"root\",\n\t\t\tinvolves: [],\n\t\t\tabilities: this.abilities.getDefaultAbilities(),\n\t\t\ttitle: \"Root\",\n\t\t\tdescription: \"Root\",\n\t\t\tmeta: {},\n\t\t\tcreatedAt: Date.now()\n\t\t});\n\t\t\n\t\tthis.initOptions = initOptions;\n\t\t\n\t}\n\t\n\tusers;\n\tcollections;\n\tcollection!: WatchedCollection<RoleDoc> & {\n\t\t/** @deprecated Direct usage of roles collection.deleteOne is forbidden. Use roles.deleteRole instead. */\n\t\tdeleteOne: typeof preventDirectDelete;\n\t\t\n\t\t/** @deprecated Direct usage of roles collection.deleteMany is forbidden. Use roles.deleteRole instead. */\n\t\tdeleteMany: typeof preventDirectDelete;\n\t};\n\t\n\tabilities;\n\troot;\n\tprivate initOptions?;\n\t\n\tasync init() {\n\t\t\n\t\tif (!this.users.isInited) {\n\t\t\tconst {\n\t\t\t\tschema: customSchema,\n\t\t\t\tindexes: customIndexes,\n\t\t\t\tcollection: collectionOptions\n\t\t\t} = this.initOptions!;\n\t\t\t\n\t\t\tif (customSchema) {\n\t\t\t\tif (customSchema.required)\n\t\t\t\t\tremoveAll(customSchema.required as string[], basisSchema.required as string[]);\n\t\t\t\tif (customSchema.properties)\n\t\t\t\t\tdeleteProps(customSchema, Object.keys(basisSchema.properties!));\n\t\t\t}\n\t\t\t\n\t\t\tconst schema = {\n\t\t\t\t...basisSchema,\n\t\t\t\t...customSchema,\n\t\t\t\trequired: [ ...basisSchema.required as string[], ...customSchema?.required as string[] ?? [] ],\n\t\t\t\tproperties: { ...basisSchema.properties, ...customSchema?.properties }\n\t\t\t};\n\t\t\t\n\t\t\tthis.collection = Object.assign(\n\t\t\t\tawait this.collections.ensure<RoleDoc>(\"roles\", { ...collectionOptions, schema }),\n\t\t\t\t{\n\t\t\t\t\tdeleteOne: preventDirectDelete,\n\t\t\t\t\tdeleteMany: preventDirectDelete\n\t\t\t\t}\n\t\t\t);\n\t\t\t\n\t\t\tawait this.collection.ensureIndexes([ ...indexes, ...customIndexes ?? [] ]);\n\t\t\t\n\t\t\tawait this.#maintain();\n\t\t\t\n\t\t\tfor await (const roleDoc of this.collection.find()) {\n\t\t\t\tif (this.abilities.adjust(roleDoc.abilities))\n\t\t\t\t\tawait this.collection.updateOne({ _id: roleDoc._id }, { $set: { abilities: roleDoc.abilities } });\n\t\t\t\t\n\t\t\t\tthis.load(roleDoc);\n\t\t\t}\n\t\t\t\n\t\t\tthis.update();\n\t\t\t\n\t\t\tthis.collection.onChange(this.#handleCollectionChange);\n\t\t\t\n\t\t\tdelete this.initOptions;\n\t\t}\n\t\t\n\t}\n\t\n\tasync #maintain() {\n\t\t\n\t\tawait this.collection.updateMany({ meta: { $exists: false } }, { $set: { meta: {} } });\n\t\t\n\t}\n\t\n\t#handleCollectionChange = (next: ChangeStreamDocument<RoleDoc>) => {\n\t\tswitch (next.operationType) {\n\t\t\tcase \"insert\": {\n\t\t\t\tnew Role<AS>(this, next.fullDocument);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tcase \"replace\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.update(next.fullDocument);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"update\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.update(next.updateDescription.updatedFields!);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"delete\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.delete();\n\t\t}\n\t\t\n\t};\n\t\n\tload(roleDoc: RoleDoc) {\n\t\tnew Role<AS>(this, roleDoc);\n\t\t\n\t}\n\t\n\tresolve(role: Role<AS>, involvedBy: Role<AS>[]) {\n\t\tinvolvedBy = [ role, ...involvedBy ];\n\t\t\n\t\tfor (const involvedRoleId of role.ownInvolveIds) {\n\t\t\tconst involvedRole = this.get(involvedRoleId);\n\t\t\tif (involvedRole) {\n\t\t\t\tfor (const involvedByRole of involvedBy) {\n\t\t\t\t\treAdd(involvedByRole.involves, involvedRole);\n\t\t\t\t\tthis.abilities.merge(involvedByRole.inheritedAbilities as GenericAbilities, involvedRole.abilities as GenericAbilities);\n\t\t\t\t}\n\t\t\t\tif (involvedRole !== role)\n\t\t\t\t\tthis.resolve(involvedRole, involvedBy);\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tsorted: Role<AS>[] = [];\n\t\n\t#sortRoles(a: Role<AS>, b: Role<AS>) {\n\t\treturn (\n\t\t\t(b.involves.size - a.involves.size) || (\n\t\t\t\t(a.title && b.title) ?\n\t\t\t\t\ta.title > b.title ? 1 : a.title < b.title ? -1 : 0 :\n\t\t\t\t\ta.title ?\n\t\t\t\t\t\t-1 :\n\t\t\t\t\t\tb.title ?\n\t\t\t\t\t\t\t1 :\n\t\t\t\t\t\t\ta._id > b._id ?\n\t\t\t\t\t\t\t\t1 :\n\t\t\t\t\t\t\t\ta._id < b._id ?\n\t\t\t\t\t\t\t\t\t-1 :\n\t\t\t\t\t\t\t\t\t0\n\t\t\t)\n\t\t);\n\t}\n\t\n\tupdate() {\n\t\t\n\t\tconst array = [ ...this.values() ];\n\t\t\n\t\tthis.root.ownInvolveIds = [];\n\t\tfor (const role of array) {\n\t\t\tif (role !== this.root && !array.some(anotherRole => anotherRole.ownInvolveIds.includes(role._id)))\n\t\t\t\tthis.root.ownInvolveIds.push(role._id);\n\t\t\trole.involves.clear();\n\t\t\trole.abilities = structuredClone(role.ownAbilities);\n\t\t\trole.inheritedAbilities = {};\n\t\t}\n\t\t\n\t\tthis.root.involves.add(this.root);\n\t\tthis.resolve(this.root, []);\n\t\t\n\t\tfor (const role of array)\n\t\t\trole.ownInvolves = getAll(this, role.ownInvolveIds, true).sort(this.#sortRoles).reverse();\n\t\t\n\t\tconst sorted = [ this.root ];\n\t\t\n\t\tfor (let i = 0; i < sorted.length; i++) {\n\t\t\tconst role = sorted[i];\n\t\t\tfor (const involvedRole of role.ownInvolves) {\n\t\t\t\tconst involvedRoleIndex = sorted.indexOf(involvedRole);\n\t\t\t\tif (~involvedRoleIndex) {\n\t\t\t\t\tsorted.splice(involvedRoleIndex, 1);\n\t\t\t\t\ti--;\n\t\t\t\t}\n\t\t\t\tsorted.splice(i + 1, 0, involvedRole);\n\t\t\t}\n\t\t}\n\t\t\n\t\tlet _o = 0;\n\t\tfor (const role of sorted) {\n\t\t\tthis.abilities.merge(role.abilities as GenericAbilities, role.inheritedAbilities as GenericAbilities);\n\t\t\trole._o = _o++;\n\t\t}\n\t\t\n\t\tthis.sorted = sorted;\n\t\t\n\t\tif (this.users.isInited)\n\t\t\tthis.users.update(true);\n\t\t\n\t}\n\t\n\tasync create({ _id, involves, title, description, ...restProps }: NewRole) {\n\t\t\n\t\tawait this.collection.insertOne({\n\t\t\t_id,\n\t\t\tinvolves: involves || [],\n\t\t\tabilities: {},\n\t\t\ttitle: title ?? \"\",\n\t\t\tdescription: description ?? \"\",\n\t\t\tmeta: {},\n\t\t\t...deleteProps(restProps, [ \"abilities\" ]),\n\t\t\tcreatedAt: Date.now()\n\t\t});\n\t\t\n\t\treturn _id;\n\t}\n\t\n\tasync updateRole(roleId: string, updates: Omit<RoleDoc, \"abilities\" | \"createdAt\">) {\n\t\tconst role = this.get(roleId);\n\t\t\n\t\tif (!role)\n\t\t\treturn false;\n\t\t\n\t\tif (updates.involves) {\n\t\t\tremoveAll(updates.involves, [ roleId ]);\n\t\t\t\n\t\t\tfor (const involvedRoleId of updates.involves)\n\t\t\t\tif (this.get(involvedRoleId)?.involves.has(role))\n\t\t\t\t\tremoveAll(updates.involves, [ involvedRoleId ]);\n\t\t\t\n\t\t\tupdates.involves = this.cleanUpIds(updates.involves);\n\t\t}\n\t\t\n\t\tawait this.collection.updateOne({ _id: roleId }, { $set: updates });\n\t\t\n\t\treturn true;\n\t}\n\t\n\tdeleteRole(role: Role<AS> | string) {\n\t\tconst _id = typeof role == \"string\" ? role : role._id;\n\t\t\n\t\treturn this.collection.bulkWrite([\n\t\t\t{ updateMany: { filter: { involves: _id }, update: { $pullAll: { involves: [ _id ] } } } },\n\t\t\t{ deleteOne: { filter: { _id } } }\n\t\t]);\n\t}\n\t\n\tcleanUpIds(ids: string[]) {\n\t\tconst roles = intersection(this.sorted, getAll(this, ids, true));\n\t\t\n\t\tconst cleanedUpIds = [];\n\t\t\n\t\tfor (const role of roles)\n\t\t\tif (roles.every(anotherRole => anotherRole === role || !anotherRole.involves.has(role)))\n\t\t\t\tcleanedUpIds.push(role._id);\n\t\t\n\t\treturn cleanedUpIds;\n\t}\n\t\n\tasync setAbility(roleId: string, abilityLongId: string, set: boolean) {\n\t\tconst role = this.get(roleId);\n\t\t\n\t\tif (!role)\n\t\t\treturn false;\n\t\t\n\t\tawait this.collection.updateOne({ _id: roleId }, { $set: {\n\t\t\tabilities:\n\t\t\t\tset ?\n\t\t\t\t\tthis.abilities.setAbility(role.ownAbilities, abilityLongId) :\n\t\t\t\t\tthis.abilities.unsetAbility(role.ownAbilities, abilityLongId)\n\t\t} });\n\t\t\n\t\treturn true;\n\t}\n\t\n\tasync setAbilityParam(roleId: string, abilityLongId: string, paramId: string, value: AbilityParam) {\n\t\tconst role = this.get(roleId);\n\t\t\n\t\tif (!role)\n\t\t\treturn false;\n\t\t\n\t\tawait this.collection.updateOne({ _id: roleId }, { $set: {\n\t\t\tabilities: this.abilities.setParam(role.ownAbilities, abilityLongId, paramId, value)\n\t\t} });\n\t\t\n\t\treturn true;\n\t}\n\t\n}\n", "import { Err } from \"@nesvet/n\";\n\n\ntype Payload = Record<string, unknown>;\n\n\nexport class UnauthorizedError extends Err {\n\tconstructor(payload?: Payload) {\n\t\tsuper(\"Unauthorized\", \"unauthorized\", payload);\n\t\t\n\t}\n\t\n\tname = \"UnauthorizedError\";\n\t\n}\n\n\ntype SubordinationType = \"_id\" | \"permissiveIds\" | \"slaveIds\";\n\nexport class SubordinationError extends Err {\n\tconstructor(payload?: Payload);\n\tconstructor(type: SubordinationType, payload?: Payload);\n\tconstructor(type: SubordinationType, ids: string[] | string, payload?: Payload);\n\tconstructor(type?: Payload | SubordinationType, ids?: Payload | string[] | string, payload?: Payload) {\n\t\tswitch (arguments.length) {\n\t\t\tcase 1:\n\t\t\t\tpayload = type as Payload;\n\t\t\t\ttype = undefined;\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 2:\n\t\t\t\tpayload = ids as Payload;\n\t\t\t\tids = undefined;\n\t\t}\n\t\t\n\t\tsuper(\"Insubordination attempt\", \"subordination\", {\n\t\t\t...type && { type },\n\t\t\t...ids && { ids: Array.isArray(ids) ? ids : [ ids ] },\n\t\t\t...payload\n\t\t});\n\t\t\n\t}\n\t\n\tname = \"SubordinationError\";\n\t\n}\n\n\nexport class PermissionError extends Err {\n\tconstructor(payload?: Payload) {\n\t\tsuper(\"Insufficient permissions\", \"permissions\", payload);\n\t\t\n\t}\n\t\n\tname = \"PermissionError\";\n\t\n}\n", "import { hash, verify } from \"@node-rs/argon2\";\nimport EventEmitter from \"eventemitter3\";\nimport {\n\t_ids,\n\tdeleteProps,\n\tremoveAll,\n\tStatefulPromise,\n\twithout\n} from \"@nesvet/n\";\nimport type { AbilitiesSchema } from \"insite-common\";\nimport {\n\tChangeStreamDocument,\n\tCollectionIndexes,\n\tCollections,\n\tnewObjectIdString,\n\tWatchedCollection\n} from \"insite-db\";\nimport { AbilitiesMap } from \"../abilities\";\nimport { Orgs } from \"../orgs\";\nimport { Org } from \"../orgs/Org\";\nimport { Roles } from \"../roles\";\nimport { Sessions } from \"../sessions\";\nimport { Session } from \"../sessions/Session\";\nimport type { SessionDoc } from \"../sessions/types\";\nimport { Avatars } from \"./avatars\";\nimport { basisSchema } from \"./schema\";\nimport { User } from \"./User\";\nimport type { NewUser, Options, UserDoc } from \"./types\";\n\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n\nconst indexes: CollectionIndexes = [\n\t[ { email: 1 }, { unique: true } ],\n\t[ { org: 1 } ]\n];\n\n\nexport class Users<AS extends AbilitiesSchema> extends Map<string, User<AS>> {\n\tconstructor(collections: Collections, options: Options<AS>) {\n\t\tsuper();\n\t\t\n\t\tconst eventEmitter = new EventEmitter() as EventEmitter & {\n\t\t\t_events: Record<string, object>;\n\t\t\t_eventsCount: number;\n\t\t};\n\t\tthis.#eventEmitter = eventEmitter;\n\t\tthis._events = eventEmitter._events;\n\t\tthis._eventsCount = eventEmitter._eventsCount;\n\t\tthis.emit = eventEmitter.emit;\n\t\tthis.on = eventEmitter.on as unknown as (...args: any[]) => this;\n\t\tthis.once = eventEmitter.once;\n\t\tthis.addListener = eventEmitter.addListener;\n\t\tthis.off = eventEmitter.off;\n\t\tthis.removeListener = eventEmitter.removeListener;\n\t\t\n\t\tthis.collections = collections;\n\t\t\n\t\tthis.abilities = new AbilitiesMap<AS>(options.abilities);\n\t\t\n\t\tthis.initOptions = options;\n\t\t\n\t\tvoid this.init();\n\t\t\n\t}\n\t\n\t#eventEmitter;\n\t_events;\n\t_eventsCount;\n\temit;\n\t\n\ton(event: \"user-create\" | \"user-is-online\" | \"user-permissions-change\", callback: (user: User<AS>) => void): this;\n\ton(event: \"session-delete\", callback: (session: Session<AS>) => void): this;\n\ton<T extends string | symbol>(event: T, callback: (...args: any[]) => void, context?: any) {\n\t\tthis.#eventEmitter.on(event, callback, context);\n\t\t\n\t\treturn this;\n\t}\n\t\n\tonce;\n\taddListener;\n\toff;\n\tremoveListener;\n\t\n\tprivate initOptions?;\n\t\n\tcollections;\n\tabilities;\n\t\n\tcollection!: WatchedCollection<UserDoc>;\n\troles!: Roles<AS>;\n\tsessions!: Sessions<AS>;\n\torgs!: Orgs<AS>;\n\tavatars!: Avatars<AS>;\n\t\n\tbyEmail = new Map();\n\tbySessionId = new Map();\n\tsorted: User<AS>[] = [];\n\t\n\tisSortRequired = true;\n\t\n\t#isPreinited = false;\n\t\n\tasync preinit() {\n\t\t\n\t\tif (!this.#isPreinited) {\n\t\t\tthis.#isPreinited = true;\n\t\t\t\n\t\t\tconst {\n\t\t\t\tindexes: customIndexes,\n\t\t\t\tschema: customSchema,\n\t\t\t\tinitialRoot: initialRootProps,\n\t\t\t\tcollection: collectionOptions\n\t\t\t} = this.initOptions!;\n\t\t\t\n\t\t\tif (customSchema) {\n\t\t\t\tif (customSchema.required)\n\t\t\t\t\tremoveAll(customSchema.required as string[], basisSchema.required as string[]);\n\t\t\t\tif (customSchema.properties)\n\t\t\t\t\tdeleteProps(customSchema, Object.keys(basisSchema.properties!));\n\t\t\t}\n\t\t\t\n\t\t\tconst schema = {\n\t\t\t\t...basisSchema,\n\t\t\t\t...customSchema,\n\t\t\t\trequired: [ ...basisSchema.required as string [], ...customSchema?.required as string[] ?? [] ],\n\t\t\t\tproperties: { ...basisSchema.properties, ...customSchema?.properties }\n\t\t\t};\n\t\t\t\n\t\t\tthis.collection = await this.collections.ensure<UserDoc>(\"users\", { ...collectionOptions, schema });\n\t\t\t\n\t\t\tawait this.collection.ensureIndexes([ ...indexes, ...customIndexes ?? [] ]);\n\t\t\t\n\t\t\tif (!await this.collection.countDocuments({ roles: \"root\" }))\n\t\t\t\tawait this.create({\n\t\t\t\t\temail: process.env.INSITE_ROOT_EMAIL ?? \"insite@root.email\",\n\t\t\t\t\tpassword: process.env.INSITE_ROOT_PASSWORD ?? \"inSiteRootPassword\",\n\t\t\t\t\tname: { first: \"Root\" },\n\t\t\t\t\tjob: \"Root\",\n\t\t\t\t\t...initialRootProps,\n\t\t\t\t\troles: [ \"root\" ],\n\t\t\t\t\torg: null,\n\t\t\t\t\tmeta: {}\n\t\t\t\t});\n\t\t\t\n\t\t\tawait this.#maintain();\n\t\t\t\n\t\t\tfor await (const userDoc of this.collection.find())\n\t\t\t\tthis.load(userDoc);\n\t\t}\n\t\t\n\t}\n\t\n\tasync #maintain() {\n\t\t\n\t\tawait this.collection.updateMany({ meta: { $exists: false } }, { $set: { meta: {} } });\n\t\t\n\t}\n\t\n\tisInited = false;\n\t\n\tprotected async init() {\n\t\t\n\t\tif (!this.isInited) {\n\t\t\tconst {\n\t\t\t\troles: rolesOptions,\n\t\t\t\torgs: orgsOptions,\n\t\t\t\tsessions: sessionsOptions,\n\t\t\t\tavatars: avatarsOptions,\n\t\t\t\tcollection: { quiet } = {}\n\t\t\t} = this.initOptions!;\n\t\t\t\n\t\t\tthis.roles = new Roles<AS>(this, { ...rolesOptions, collection: { quiet, ...rolesOptions?.collection } });\n\t\t\tthis.orgs = new Orgs<AS>(this, { ...orgsOptions, collection: { quiet, ...orgsOptions?.collection } });\n\t\t\tthis.sessions = new Sessions<AS>(this, { ...sessionsOptions, collection: { quiet, ...sessionsOptions?.collection } });\n\t\t\tthis.avatars = new Avatars<AS>(this, { ...avatarsOptions, collection: { quiet, ...avatarsOptions?.collection } });\n\t\t\t\n\t\t\tawait this.roles.init();\n\t\t\tawait this.orgs.preinit();\n\t\t\tawait this.preinit();\n\t\t\tthis.orgs.init();\n\t\t\tawait this.avatars.init();\n\t\t\t\n\t\t\tthis.update(true);\n\t\t\t\n\t\t\tthis.collection.onChange(this.#handleCollectionChange);\n\t\t\t\n\t\t\tawait this.sessions.init();\n\t\t\t\n\t\t\tdelete this.initOptions;\n\t\t\t\n\t\t\tthis.isInited = true;\n\t\t\t\n\t\t\tthis.#initPromise.resolve(this);\n\t\t}\n\t\t\n\t}\n\t\n\t#handleCollectionChange = (next: ChangeStreamDocument<UserDoc>) => {\n\t\tswitch (next.operationType) {\n\t\t\tcase \"insert\":\n\t\t\t\tnew User<AS>(this, next.fullDocument);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"replace\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.update(next.fullDocument);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"update\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.update(next.updateDescription.updatedFields!);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"delete\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.delete();\n\t\t}\n\t\t\n\t};\n\t\n\t\n\tload(userDoc: UserDoc) {\n\t\tnew User<AS>(this, userDoc);\n\t\t\n\t}\n\t\n\tsort() {\n\t\t\n\t\tthis.isSortRequired = false;\n\t\t\n\t\tthis.sorted = [ ...this.values() ].sort((a, b) => a.name.last > b.name.last ? 1 : a.name.last < b.name.last ? -1 : 0);\n\t\t\n\t}\n\t\n\tupdate(shouldUpdateRoles?: boolean) {\n\t\tif (shouldUpdateRoles)\n\t\t\tfor (const user of this.values())\n\t\t\t\tuser.updateRoles();\n\t\t\n\t\tfor (const user of this.values())\n\t\t\tuser.updatePermissions();\n\t\t\n\t\tif (this.isSortRequired)\n\t\t\tthis.sort();\n\t\t\n\t}\n\t\n\t#initPromise = new StatefulPromise<this>();\n\t\n\twhenReady() {\n\t\treturn this.#initPromise;\n\t}\n\t\n\tasync create({ email, password, roles, name, org, job, ...restProps }: NewUser) {\n\t\tif (this.byEmail.has(email))\n\t\t\tthrow new Error(\"User exists\");\n\t\t\n\t\tconst _id = newObjectIdString();\n\t\t\n\t\tawait this.collection.insertOne({\n\t\t\t_id,\n\t\t\temail,\n\t\t\tpassword: await hash(password),\n\t\t\troles: this.isInited ? this.roles.cleanUpIds(roles) : roles,\n\t\t\tname: {\n\t\t\t\tfirst: name.first ?? \"\",\n\t\t\t\tmiddle: name.middle ?? \"\",\n\t\t\t\tlast: name.last ?? \"\"\n\t\t\t},\n\t\t\torg: org ?? null,\n\t\t\tjob: job ?? \"\",\n\t\t\tmeta: {},\n\t\t\t...deleteProps(restProps, [ \"_id\" ]),\n\t\t\tcreatedAt: Date.now()\n\t\t});\n\t\t\n\t\treturn _id;\n\t}\n\t\n\tasync updateUser(_id: string, updates: Omit<UserDoc, \"_id\" | \"createdAt\">, byUser?: User<AS>) {\n\t\tconst user = this.get(_id)!;\n\t\t\n\t\tif (!user)\n\t\t\treturn false;\n\t\t\n\t\tif (updates.roles)\n\t\t\tupdates.roles =\n\t\t\t\tuser.isRoot ?\n\t\t\t\t\t[ \"root\" ] :\n\t\t\t\t\tthis.roles.cleanUpIds(\n\t\t\t\t\t\tbyUser ?\n\t\t\t\t\t\t\twithout(user.ownRoleIds, byUser.slaveRoleIds).concat(updates.roles) :\n\t\t\t\t\t\t\tupdates.roles\n\t\t\t\t\t);\n\t\t\n\t\tawait this.collection.updateOne({ _id }, { $set: updates });\n\t\t\n\t\treturn true;\n\t}\n\t\n\tasync changePassword(_id: string, newPassword: string) {\n\t\tif (!this.has(_id))\n\t\t\tthrow new Error(\"usernotfound\");\n\t\t\n\t\tif (!newPassword)\n\t\t\tthrow new Error(\"emptypasswordisnotallowed\");\n\t\t\n\t\tawait Promise.all([\n\t\t\tthis.collection.updateOne({ _id }, { $set: { password: await hash(newPassword) } }),\n\t\t\tthis.sessions.collection.deleteMany({ user: _id })\n\t\t]);\n\t\t\n\t}\n\t\n\tasync login(email: string, password: string, sessionProps: Partial<SessionDoc>) {\n\t\tconst user = this.byEmail.get(email);\n\t\t\n\t\tif (!user)\n\t\t\tthrow new Error(\"usernotfound\");\n\t\t\n\t\tif (!await verify(user.password, password))\n\t\t\tthrow new Error(\"incorrectpassword\");\n\t\t\n\t\tif (!user.abilities.login)\n\t\t\tthrow new Error(\"userisnotabletologin\");\n\t\t\n\t\treturn this.sessions.create(user, sessionProps);\n\t}\n\t\n\tlogout(session: Session<AS>) {\n\t\tsession.delete();\n\t\t\n\t\treturn this.sessions.collection.deleteOne({ _id: session._id });\n\t}\n\t\n\t#sortUsersAndOrgs(a: Org<AS> | User<AS>, b: Org<AS> | User<AS>) {\n\t\treturn (\n\t\t\t(a instanceof User && b instanceof User) ?\n\t\t\t\t(a.name.last && b.name.last) ?\n\t\t\t\t\ta.name.last > b.name.last ?\n\t\t\t\t\t\t1 :\n\t\t\t\t\t\ta.name.last < b.name.last ? -1 : 0 :\n\t\t\t\t\t(!a.name.last && !b.name.last) ?\n\t\t\t\t\t\ta.displayLabel > b.displayLabel ?\n\t\t\t\t\t\t\t1 :\n\t\t\t\t\t\t\ta.displayLabel < b.displayLabel ? -1 : 0 :\n\t\t\t\t\t\ta.name.last ? -1 : 1 :\n\t\t\t\t(a instanceof Org && b instanceof Org) ?\n\t\t\t\t\ta.title > b.title ?\n\t\t\t\t\t\t1 :\n\t\t\t\t\t\ta.title < b.title ? -1 : 0 :\n\t\t\t\t\ta instanceof Org ? -1 : 1\n\t\t);\n\t}\n\t\n\tsortIds(ids: string[]) {\n\t\treturn _ids((\n\t\t\tids\n\t\t\t\t.map(_id => this.get(_id) || this.orgs.get(_id))\n\t\t\t\t.filter(Boolean) as (Org<AS> | User<AS>)[]\n\t\t).sort(this.#sortUsersAndOrgs));\n\t}\n\t\n\treplaceMap = new Map<string, string>();\n\t\n\treplaceHandlers = new Set<(fromId: string, toId: string | null) => Promise<void> | void>();\n\t\n\tasync replace(fromId: string) {\n\t\tconst toId = this.replaceMap.get(fromId) ?? null;\n\t\tif (toId)\n\t\t\tthis.replaceMap.delete(fromId);\n\t\t\n\t\tfor (const handler of this.replaceHandlers)\n\t\t\tawait handler(fromId, toId);\n\t\t\n\t}\n\t\n\tasync deleteUser(_id: string) {\n\t\tconst { deletedCount } = await this.collection.deleteOne({ _id });\n\t\t\n\t\treturn Boolean(deletedCount);\n\t}\n\t\n\t\n\tstatic init<IAS extends AbilitiesSchema>(collections: Collections, options: Options<IAS>) {\n\t\tconst users = new Users(collections, options);\n\t\t\n\t\treturn users.whenReady();\n\t}\n\t\n}\n", "import {\n\t_ids,\n\tdeleteProps,\n\tEmptyArray,\n\tEmptySet,\n\tremoveAll,\n\tsort,\n\tunion,\n\twithout\n} from \"@nesvet/n\";\nimport type { AbilitiesSchema } from \"insite-common\";\nimport {\n\tChangeStreamDocument,\n\tCollectionIndexes,\n\tnewObjectIdString,\n\tWatchedCollection\n} from \"insite-db\";\nimport type { User, Users } from \"../users\";\nimport { Org } from \"./Org\";\nimport { basisSchema } from \"./schema\";\nimport type { NewOrg, OrgDoc, OrgsOptions } from \"./types\";\n\n\nconst indexes: CollectionIndexes = [\n\t[ { owners: 1 } ]\n];\n\nfunction preventDirectDelete() {\n\tthrow new Error(\"Direct usage of orgs collection.deleteOne or .deleteMany is forbidden. Use orgs.deleteOrg instead.\");\n}\n\n\nexport class Orgs<AS extends AbilitiesSchema> extends Map<string, Org<AS>> {\n\tconstructor(users: Users<AS>, options: OrgsOptions = {}) {\n\t\tsuper();\n\t\t\n\t\tthis.users = users;\n\t\tthis.collections = users.collections;\n\t\t\n\t\tthis.preinitOptions = options;\n\t\t\n\t}\n\t\n\tusers;\n\tcollections;\n\tprivate preinitOptions?;\n\t\n\tcollection!: WatchedCollection<OrgDoc> & {\n\t\t/** @deprecated Direct usage of roles collection.deleteOne is forbidden. Use orgs.deleteOrg instead. */\n\t\tdeleteOne: typeof preventDirectDelete;\n\t\t\n\t\t/** @deprecated Direct usage of roles collection.deleteMany is forbidden. Use orgs.deleteOrg instead. */\n\t\tdeleteMany: typeof preventDirectDelete;\n\t};\n\t\n\tnull!: Org<AS> & { _id: null };\n\t\n\t#isPreinited = false;\n\t\n\tasync preinit() {\n\t\t\n\t\tif (!this.#isPreinited) {\n\t\t\tthis.#isPreinited = true;\n\t\t\t\n\t\t\tconst {\n\t\t\t\tschema: customSchema,\n\t\t\t\tindexes: customIndexes,\n\t\t\t\tnull: nullProps,\n\t\t\t\tcollection: collectionOptions\n\t\t\t} = this.preinitOptions!;\n\t\t\t\n\t\t\tif (customSchema) {\n\t\t\t\tif (customSchema.required)\n\t\t\t\t\tremoveAll(customSchema.required as string [], basisSchema.required as string[]);\n\t\t\t\tif (customSchema.properties)\n\t\t\t\t\tdeleteProps(customSchema, Object.keys(basisSchema.properties!));\n\t\t\t}\n\t\t\t\n\t\t\tconst schema = {\n\t\t\t\t...basisSchema,\n\t\t\t\t...customSchema,\n\t\t\t\trequired: [ ...basisSchema.required as string[], ...customSchema?.required as string[] ?? [] ],\n\t\t\t\tproperties: { ...basisSchema.properties, ...customSchema?.properties }\n\t\t\t};\n\t\t\t\n\t\t\tthis.collection = Object.assign(\n\t\t\t\tawait this.collections.ensure<OrgDoc>(\"orgs\", { ...collectionOptions, schema }),\n\t\t\t\t{\n\t\t\t\t\tdeleteOne: preventDirectDelete,\n\t\t\t\t\tdeleteMany: preventDirectDelete\n\t\t\t\t}\n\t\t\t);\n\t\t\t\n\t\t\t// TODO: customIndexes should be moved to collectionOptions\n\t\t\tawait this.collection.ensureIndexes([ ...indexes, ...customIndexes ?? [] ]);\n\t\t\t\n\t\t\tthis.null = Object.assign(\n\t\t\t\tnew Org<AS>(this, {\n\t\t\t\t\t...nullProps,\n\t\t\t\t\t_id: \"\",\n\t\t\t\t\ttitle: \"\",\n\t\t\t\t\tnote: \"\",\n\t\t\t\t\towners: [],\n\t\t\t\t\tmeta: {},\n\t\t\t\t\tcreatedAt: Date.now()\n\t\t\t\t}),\n\t\t\t\t{\n\t\t\t\t\t_id: null,\n\t\t\t\t\townerIds: new EmptyArray(),\n\t\t\t\t\townerOrgs: new EmptySet(),\n\t\t\t\t\townerUsers: new EmptySet(),\n\t\t\t\t\tslaveOrgs: new EmptySet()\n\t\t\t\t}\n\t\t\t);\n\t\t\t\n\t\t\tawait this.#maintain();\n\t\t\t\n\t\t\tfor await (const orgDoc of this.collection.find())\n\t\t\t\tthis.load(orgDoc);\n\t\t\t\n\t\t\tdelete this.preinitOptions;\n\t\t}\n\t\t\n\t}\n\t\n\tasync #maintain() {\n\t\t\n\t\tawait this.collection.updateMany({ meta: { $exists: false } }, { $set: { meta: {} } });\n\t\t\n\t}\n\t\n\tinit() {\n\t\t\n\t\tif (!this.users.isInited) {\n\t\t\tthis.update();\n\t\t\t\n\t\t\tthis.collection.onChange(this.#handleCollectionChange);\n\t\t}\n\t\t\n\t}\n\t\n\t#handleCollectionChange = (next: ChangeStreamDocument<OrgDoc>) => {\n\t\tswitch (next.operationType) {\n\t\t\tcase \"insert\": {\n\t\t\t\tnew Org<AS>(this, next.fullDocument);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tcase \"replace\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.update(next.fullDocument);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"update\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.update(next.updateDescription.updatedFields!);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"delete\":\n\t\t\t\tvoid this.get(next.documentKey._id)?.delete();\n\t\t}\n\t\t\n\t};\n\t\n\tload(orgDoc: OrgDoc) {\n\t\tnew Org<AS>(this, orgDoc);\n\t\t\n\t}\n\t\n\t#resolve(org: Org<AS>, slaveOrgs: Org<AS>[]) {\n\t\tslaveOrgs = [ org, ...slaveOrgs ];\n\t\t\n\t\tfor (const ownerOrg of org.ownerOrgs) {\n\t\t\tthis.#resolve(ownerOrg, slaveOrgs);\n\t\t\tfor (const slaveOrg of slaveOrgs)\n\t\t\t\townerOrg.slaveOrgs.add(slaveOrg);\n\t\t}\n\t\t\n\t}\n\t\n\tsorted: Org<AS>[] = [];\n\t\n\tupdate() {\n\t\t\n\t\tconst array = [ ...this.values() ];\n\t\tconst sorted = [];\n\t\t\n\t\tfor (const org of array) {\n\t\t\torg.ownerOrgs.clear();\n\t\t\torg.ownerUsers.clear();\n\t\t\torg.slaveOrgs.clear();\n\t\t\t\n\t\t\tfor (const ownerId of org.ownerIds) {\n\t\t\t\tconst ownerOrg = this.get(ownerId);\n\t\t\t\tif (ownerOrg)\n\t\t\t\t\torg.ownerOrgs.add(ownerOrg);\n\t\t\t\telse {\n\t\t\t\t\tconst ownerUser = this.users.get(ownerId);\n\t\t\t\t\tif (ownerUser)\n\t\t\t\t\t\torg.ownerUsers.add(ownerUser);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (!org.ownerOrgs.size && org._id)\n\t\t\t\tsorted.push(org);\n\t\t}\n\t\t\n\t\tfor (const org of array)\n\t\t\tif (!array.some(anotherOrg => anotherOrg.ownerOrgs.has(org)))\n\t\t\t\tthis.#resolve(org, []);\n\t\t\n\t\tsorted.sort(this.#sortOrgs);\n\t\tfor (const org of array)\n\t\t\tsort(org.slaveOrgs, this.#sortOrgs);\n\t\t\n\t\tfor (let i = 0; i < sorted.length; i++) {\n\t\t\tconst org = sorted[i];\n\t\t\tfor (const slaveOrg of [ ...org.slaveOrgs ].reverse())\n\t\t\t\tif (slaveOrg.ownerOrgs.has(org)) {\n\t\t\t\t\tconst slaveOrgIndex = sorted.indexOf(slaveOrg);\n\t\t\t\t\tif (~slaveOrgIndex) {\n\t\t\t\t\t\tsorted.splice(slaveOrgIndex, 1);\n\t\t\t\t\t\ti--;\n\t\t\t\t\t}\n\t\t\t\t\tsorted.splice(i + 1, 0, slaveOrg);\n\t\t\t\t}\n\t\t}\n\t\tfor (let o = 0, { length } = sorted; o < length;)\n\t\t\tsorted[o]._o = o++;\n\t\t\n\t\tthis.sorted = sorted;\n\t\t\n\t\tif (this.users.isInited)\n\t\t\tthis.users.update();\n\t\t\n\t}\n\t\n\t#sortOrgs(a: Org<AS>, b: Org<AS>) {\n\t\treturn (\n\t\t\t(b.slaveOrgs.size - a.slaveOrgs.size) || (\n\t\t\t\ta.title > b.title ?\n\t\t\t\t\t1 :\n\t\t\t\t\ta.title < b.title ?\n\t\t\t\t\t\t-1 :\n\t\t\t\t\t\t0\n\t\t\t)\n\t\t);\n\t}\n\t\n\tasync create({ title, note, ...restProps }: NewOrg) {\n\t\t\n\t\tconst _id = newObjectIdString();\n\t\t\n\t\tawait this.collection.insertOne({\n\t\t\t_id,\n\t\t\ttitle: title ?? \"\",\n\t\t\tnote: note ?? \"\",\n\t\t\tmeta: {},\n\t\t\t...deleteProps(restProps, [ \"_id\" ]),\n\t\t\tcreatedAt: Date.now()\n\t\t});\n\t\t\n\t\treturn _id;\n\t}\n\t\n\tasync updateOrg(_id: string, updates: Omit<OrgDoc, \"_id\" | \"createdAt\">, byUser?: User<AS>) {\n\t\tconst org = this.get(_id)!;\n\t\t\n\t\tif (!org)\n\t\t\treturn false;\n\t\t\n\t\tif (updates.owners)\n\t\t\tupdates.owners =\n\t\t\t\tthis.users.sortIds(\n\t\t\t\t\tunion(\n\t\t\t\t\t\tbyUser ?\n\t\t\t\t\t\t\twithout(org.ownerIds, byUser.slaveIds) :\n\t\t\t\t\t\t\t[],\n\t\t\t\t\t\twithout(updates.owners, [ _id, ..._ids(org.slaveOrgs) ])\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\n\t\tawait this.collection.updateOne({ _id }, { $set: updates });\n\t\t\n\t\treturn true;\n\t}\n\t\n\tdeleteOrg(org: Org<AS> | string) {\n\t\tconst _id = typeof org == \"string\" ? org : org._id;\n\t\t\n\t\treturn this.collection.bulkWrite([\n\t\t\t{ updateMany: { filter: { owners: _id }, update: { $pullAll: { owners: [ _id ] } } } },\n\t\t\t{ deleteOne: { filter: { _id } } }\n\t\t]);\n\t}\n\t\n\treplaceMap = new Map<string, string>();\n\t\n\treplaceHandlers = new Set<(fromId: string, toId: string | null) => Promise<void> | void>();\n\t\n\tasync replace(fromId: string) {\n\t\tconst toId = this.replaceMap.get(fromId) ?? null;\n\t\tif (toId)\n\t\t\tthis.replaceMap.delete(fromId);\n\t\t\n\t\tfor (const handler of this.replaceHandlers)\n\t\t\tawait handler(fromId, toId);\n\t\t\n\t}\n\t\n}\n", "import type { AbilitiesSchema } from \"insite-common\";\nimport { User } from \"../users/User\";\nimport type { Orgs } from \"./Orgs\";\nimport type { OrgDoc } from \"./types\";\n\n\nconst snapshots = new WeakMap();\n\n\nexport class Org<AS extends AbilitiesSchema> {\n\tconstructor(orgs: Orgs<AS>, orgDoc: OrgDoc) {\n\t\tthis.orgs = orgs;\n\t\t\n\t\tthis._id = orgDoc._id;\n\t\torgs.set(this._id, this);\n\t\t\n\t\tvoid this.update(orgDoc);\n\t\t\n\t}\n\t\n\t_id;\n\ttitle = \"\";\n\tinitials = \"\";\n\tdisplayLabel = \"\";\n\t\n\t_o = 0;\n\t\n\torgs;\n\t\n\tisOrg = true;\n\t\n\townerOrgs = new Set<Org<AS>>();\n\townerUsers = new Set<User<AS>>();\n\t\n\tusers = new Set<User<AS>>();\n\t\n\tslaveOrgs = new Set<Org<AS>>();\n\t\n\townerIds: string[] = [];\n\t\n\tupdate({ _id, title, owners: ownerIds, ...restProps }: Partial<OrgDoc>) {\n\t\t\n\t\tObject.assign(this, restProps);\n\t\t\n\t\tif (title !== undefined) {\n\t\t\tthis.title = title;\n\t\t\tthis.initials = title?.[0]?.toUpperCase() ?? \"\";\n\t\t\tthis.displayLabel = title;\n\t\t}\n\t\t\n\t\tif (ownerIds) {\n\t\t\tthis.ownerIds = ownerIds;\n\t\t\t\n\t\t\tconst snapshot = this.ownerIds.join(\",\");\n\t\t\t\n\t\t\tif (snapshot !== snapshots.get(this)) {\n\t\t\t\tsnapshots.set(this, snapshot);\n\t\t\t\t\n\t\t\t\tif (this.orgs.users.isInited)\n\t\t\t\t\tthis.orgs.update();\n\t\t\t}\n\t\t}\n\t\t\n\t}\n\t\n\tasync delete() {\n\t\t\n\t\tthis.orgs.delete(this._id);\n\t\t\n\t\tsnapshots.delete(this);\n\t\t\n\t\tawait this.orgs.replace(this._id);\n\t\t\n\t\tthis.orgs.update();\n\t\t\n\t}\n\t\n}\n", "import { CollectionSchema } from \"insite-db\";\nimport { regexps } from \"../lib\";\n\n\nexport const basisSchema: CollectionSchema = {\n\trequired: [\n\t\t\"_id\",\n\t\t\"title\",\n\t\t\"note\",\n\t\t\"owners\",\n\t\t\"meta\",\n\t\t\"createdAt\"\n\t],\n\tproperties: {\n\t\t_id: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps._id.source\n\t\t},\n\t\ttitle: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 512\n\t\t},\n\t\tnote: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 131072\n\t\t},\n\t\towners: {\n\t\t\tbsonType: \"array\",\n\t\t\tuniqueItems: true,\n\t\t\titems: {\n\t\t\t\tbsonType: \"string\",\n\t\t\t\tpattern: regexps._id.source\n\t\t\t},\n\t\t\tadditionalItems: false\n\t\t},\n\t\tmeta: {\n\t\t\tbsonType: \"object\"\n\t\t},\n\t\tcreatedAt: {\n\t\t\tbsonType: \"number\"\n\t\t}\n\t},\n\tadditionalProperties: false\n};\n", "import { randomBytes } from \"node:crypto\";\nimport { deleteProps, removeAll } from \"@nesvet/n\";\nimport type { AbilitiesSchema } from \"insite-common\";\nimport {\n\tChangeStreamDocument,\n\tCollectionIndexes,\n\tnewObjectIdString,\n\tWatchedCollection\n} from \"insite-db\";\nimport { User } from \"../users/User\";\nimport type { Users } from \"../users\";\nimport { basisSchema } from \"./schema\";\nimport { Session } from \"./Session\";\nimport { SessionDoc, SessionsOptions } from \"./types\";\n\n\nconst expireAfterSeconds = 3600 * 24 * 7;\n\nconst indexes: CollectionIndexes = [\n\t[ { user: 1 } ],\n\t[ { expiresAt: 1 }, { expireAfterSeconds } ]\n];\n\n\nexport class Sessions<AS extends AbilitiesSchema> extends Map<string, Session<AS>> {\n\tconstructor(users: Users<AS>, options: SessionsOptions = {}) {\n\t\tsuper();\n\t\t\n\t\tthis.users = users;\n\t\tthis.collections = users.collections;\n\t\t\n\t\tthis.initOptions = options;\n\t}\n\t\n\tusers;\n\tcollections;\n\t\n\tprivate initOptions?;\n\t\n\tcollection!: WatchedCollection<SessionDoc> & {\n\t\texpireAfterSeconds: number;\n\t};\n\t\n\tasync init() {\n\t\t\n\t\tif (!this.users.isInited) {\n\t\t\tconst {\n\t\t\t\tschema: customSchema,\n\t\t\t\tindexes: customIndexes,\n\t\t\t\tcollection: collectionOptions\n\t\t\t} = this.initOptions!;\n\t\t\t\n\t\t\tif (customSchema) {\n\t\t\t\tif (customSchema.required)\n\t\t\t\t\tremoveAll(customSchema.required as string[], basisSchema.required as string[]);\n\t\t\t\tif (customSchema.properties)\n\t\t\t\t\tdeleteProps(customSchema, Object.keys(basisSchema.properties!));\n\t\t\t}\n\t\t\t\n\t\t\tconst schema = {\n\t\t\t\t...basisSchema,\n\t\t\t\t...customSchema,\n\t\t\t\trequired: [ ...basisSchema.required as string[], ...customSchema?.required as string[] ?? [] ],\n\t\t\t\tproperties: { ...basisSchema.properties, ...customSchema?.properties }\n\t\t\t};\n\t\t\t\n\t\t\tthis.collection = Object.assign(\n\t\t\t\tawait this.collections.ensure<SessionDoc>(\"sessions\", { ...collectionOptions, schema }),\n\t\t\t\t{\n\t\t\t\t\texpireAfterSeconds\n\t\t\t\t}\n\t\t\t);\n\t\t\t\n\t\t\tawait this.collection.ensureIndexes([ ...indexes, ...customIndexes ?? [] ]);\n\t\t\t\n\t\t\tawait this.#maintain();\n\t\t\t\n\t\t\tfor await (const sessionDoc of this.collection.find())\n\t\t\t\tthis.load(sessionDoc);\n\t\t\t\n\t\t\tthis.collection.onChange(this.#handleCollectionChange);\n\t\t\t\n\t\t\tdelete this.initOptions;\n\t\t}\n\t\t\n\t}\n\t\n\tasync #maintain() {\n\t\t\n\t\tawait this.collection.bulkWrite([\n\t\t\t{ updateMany: { filter: { meta: { $exists: false } }, update: { $set: { meta: {} } } } },\n\t\t\t{ updateMany: { filter: { isOnline: true }, update: { $set: { isOnline: false } } } }\n\t\t]);\n\t\t\n\t}\n\t\n\t#handleCollectionChange = (next: ChangeStreamDocument<SessionDoc>) => {\n\t\tswitch (next.operationType) {\n\t\t\tcase \"insert\":\n\t\t\t\tif (!this.has(next.documentKey._id))\n\t\t\t\t\tnew Session<AS>(this, next.fullDocument);\n\t\t\t\t\n\t\t\t\tvoid this.users.get(next.fullDocument.user)?.trimSessions();\n\t\t\t\t\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"replace\":\n\t\t\t\tthis.get(next.documentKey._id)?.update(next.fullDocument);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"update\":\n\t\t\t\tthis.get(next.documentKey._id)?.update(next.updateDescription.updatedFields!);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"delete\":\n\t\t\t\tthis.get(next.documentKey._id)?.delete();\n\t\t}\n\t\t\n\t};\n\t\n\tuid() {\n\t\treturn `${newObjectIdString()}~${randomBytes(32).toString(\"base64url\")}`;\n\t}\n\t\n\tload(sessionDoc: SessionDoc) {\n\t\tnew Session<AS>(this, sessionDoc);\n\t\t\n\t}\n\t\n\tasync create(user: User<AS>, props: Partial<SessionDoc>) {\n\t\t\n\t\tconst ts = Date.now();\n\t\t\n\t\tconst sessionDoc: SessionDoc = {\n\t\t\tuserAgent: \"\",\n\t\t\tremoteAddress: \"127.0.0.1\",\n\t\t\tisOnline: true,\n\t\t\t...props,\n\t\t\t_id: this.uid(),\n\t\t\tuser: user._id,\n\t\t\tmeta: {},\n\t\t\tcreatedAt: ts,\n\t\t\tprolongedAt: ts,\n\t\t\texpiresAt: new Date(ts + (expireAfterSeconds * 1000))\n\t\t};\n\t\t\n\t\t/* new Session(\u2026) before await insertOne(\u2026) for avoid changeStream insert event to come earlier and create the session duplicate */\n\t\tconst session = new Session<AS>(this, sessionDoc);\n\t\t\n\t\tawait this.collection.insertOne(sessionDoc);\n\t\t\n\t\treturn session;\n\t}\n\t\n\tasync destroySession(_id: string) {\n\t\tconst { deletedCount } = await this.collection.deleteOne({ _id });\n\t\t\n\t\treturn Boolean(deletedCount);\n\t}\n\t\n}\n", "import { CollectionSchema } from \"insite-db\";\nimport { regexps } from \"../lib\";\n\n\nexport const basisSchema: CollectionSchema = {\n\trequired: [\n\t\t\"_id\",\n\t\t\"user\",\n\t\t\"remoteAddress\",\n\t\t\"isOnline\",\n\t\t\"meta\",\n\t\t\"createdAt\",\n\t\t\"prolongedAt\",\n\t\t\"expiresAt\"\n\t],\n\tproperties: {\n\t\t_id: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps.sessionId.source\n\t\t},\n\t\tuser: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps._id.source\n\t\t},\n\t\tuserAgent: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 4096\n\t\t},\n\t\tremoteAddress: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps.ip.source\n\t\t},\n\t\tisOnline: {\n\t\t\tbsonType: \"bool\"\n\t\t},\n\t\tmeta: {\n\t\t\tbsonType: \"object\"\n\t\t},\n\t\tcreatedAt: {\n\t\t\tbsonType: \"number\"\n\t\t},\n\t\tprolongedAt: {\n\t\t\tbsonType: \"number\"\n\t\t},\n\t\texpiresAt: {\n\t\t\tbsonType: \"date\"\n\t\t}\n\t}\n\t// TODO: Restrict additional properties (not needed with meta)\n};\n", "import type { AbilitiesSchema } from \"insite-common\";\nimport type { User } from \"../users/User\";\nimport type { Sessions } from \"./Sessions\";\nimport type { SessionDoc } from \"./types\";\n\n\nexport class Session<AS extends AbilitiesSchema> {\n\tconstructor(sessions: Sessions<AS>, sessionDoc: SessionDoc) {\n\t\tconst user = sessions.users.get(sessionDoc.user);\n\t\t\n\t\tif (user) {\n\t\t\tthis.#sessions = sessions;\n\t\t\t\n\t\t\tthis._id = sessionDoc._id;\n\t\t\tthis.#sessions.set(this._id, this);\n\t\t\t\n\t\t\tthis.user = user;\n\t\t\tthis.user.sessions.add(this);\n\t\t\t\n\t\t\tthis.#sessions.users.bySessionId.set(this._id, this.user);\n\t\t\t\n\t\t\tthis.update(sessionDoc);\n\t\t} else\n\t\t\tvoid sessions.collection.deleteOne({ _id: sessionDoc._id });\n\t\t\n\t}\n\t\n\t_id!: string;\n\tuser!: User<AS>;\n\tisOnline = false;\n\t\n\tuserAgent!: string;\n\tremoteAddress!: string;\n\tcreatedAt!: number;\n\tprolongedAt!: number;\n\texpiresAt!: Date;\n\t\n\t#sessions!: Sessions<AS>;\n\t\n\tupdate({ _id, user, isOnline, ...restProps }: Partial<SessionDoc>) {\n\t\t\n\t\tif (isOnline !== undefined && this.isOnline !== isOnline) {\n\t\t\tthis.isOnline = isOnline;\n\t\t\t\n\t\t\tif (this.#sessions.users.isInited && this.user.isOnline !== this.isOnline)\n\t\t\t\tvoid this.user.updateIsOnlineDebounced();\n\t\t}\n\t\t\n\t\tObject.assign(this, restProps);\n\t\t\n\t}\n\t\n\tprolong({ _id, user, ...updates }: Partial<SessionDoc>) {\n\t\t\n\t\tconst ts = Date.now();\n\t\t\n\t\tupdates.prolongedAt = ts;\n\t\tupdates.expiresAt = new Date(ts + (this.#sessions.collection.expireAfterSeconds * 1000));\n\t\t\n\t\tthis.update(updates);\n\t\t\n\t\treturn this.#sessions.collection.updateOne({ _id: this._id }, { $set: updates });\n\t}\n\t\n\tasync online() {\n\t\t\n\t\tif (!this.isOnline) {\n\t\t\tconst updates = { isOnline: true };\n\t\t\t\n\t\t\tthis.update(updates);\n\t\t\t\n\t\t\tawait this.#sessions.collection.updateOne({ _id: this._id }, { $set: updates });\n\t\t}\n\t\t\n\t}\n\t\n\tasync offline() {\n\t\t\n\t\tif (this.isOnline) {\n\t\t\tconst updates = { isOnline: false };\n\t\t\t\n\t\t\tthis.update(updates);\n\t\t\t\n\t\t\tawait this.#sessions.collection.updateOne({ _id: this._id }, { $set: updates });\n\t\t}\n\t\t\n\t}\n\t\n\tdelete() {\n\t\t\n\t\tthis.#sessions.delete(this._id);\n\t\tthis.user.sessions.delete(this);\n\t\tthis.#sessions.users.bySessionId.delete(this._id);\n\t\t\n\t\tthis.#sessions.users.emit(\"session-delete\", this);\n\t\t\n\t\tif (this.isOnline)\n\t\t\tthis.user.updateIsOnline();\n\t\t\n\t}\n\t\n}\n", "import type { AbilitiesSchema } from \"insite-common\";\nimport { Binary, type WatchedCollection } from \"insite-db\";\nimport type { Users } from \"../Users\";\nimport { schema } from \"./schema\";\nimport type { AvatarDoc, AvatarsOptions } from \"./types\";\n\n\nexport class Avatars<AS extends AbilitiesSchema> {\n\tconstructor(users: Users<AS>, options: AvatarsOptions = {}) {\n\t\tthis.users = users;\n\t\tthis.collections = users.collections;\n\t\t\n\t\tthis.initOptions = options;\n\t\t\n\t}\n\t\n\treadonly TYPES_ACCEPTED = [ \"image/webp\" ];\n\treadonly MAX_SIZE = 1024 * 512;\n\t\n\tusers;\n\tcollections;\n\t\n\tcollection!: WatchedCollection<AvatarDoc>;\n\t\n\tprivate initOptions?;\n\t\n\tasync init() {\n\t\t\n\t\tif (!this.users.isInited) {\n\t\t\tconst {\n\t\t\t\tcollection: collectionOptions\n\t\t\t} = this.initOptions!;\n\t\t\t\n\t\t\tthis.collection = await this.collections.ensure<AvatarDoc>(\"users.avatars\", { ...collectionOptions, schema });\n\t\t\t\n\t\t\tawait this.#maintain();\n\t\t}\n\t\t\n\t}\n\t\n\tasync #maintain() {\n\t\t\n\t\tawait this.collection.updateMany({ meta: { $exists: false } }, { $set: { meta: {} } });\n\t\t\n\t}\n\t\n\tasync save(_id: string, type: string, data: string) {\n\t\tconst binaryData = Binary.createFromBase64(data.slice(data.indexOf(\",\")));\n\t\t\n\t\tconst ts = Date.now().toString(36);\n\t\t\n\t\tawait Promise.all([\n\t\t\tthis.collection.replaceOne({ _id }, {\n\t\t\t\ttype,\n\t\t\t\tsize: binaryData.length(),\n\t\t\t\tts,\n\t\t\t\tdata: binaryData,\n\t\t\t\tmeta: {}\n\t\t\t}, { upsert: true }),\n\t\t\tthis.users.collection.updateOne({ _id }, { $set: { avatar: ts } })\n\t\t]);\n\t\t\n\t}\n\t\n\tasync deleteAvatar(_id: string) {\n\t\t\n\t\tconst [ { deletedCount } ] = await Promise.all([\n\t\t\tthis.collection.deleteOne({ _id }),\n\t\t\tthis.users.collection.updateOne({ _id }, { $set: { avatar: null } })\n\t\t]);\n\t\t\n\t\treturn Boolean(deletedCount);\n\t}\n\t\n}\n", "import { CollectionSchema } from \"insite-db\";\nimport { regexps } from \"../../lib\";\n\n\nexport const schema: CollectionSchema = {\n\trequired: [\n\t\t\"_id\",\n\t\t\"type\",\n\t\t\"size\",\n\t\t\"ts\",\n\t\t\"data\",\n\t\t\"meta\"\n\t],\n\tproperties: {\n\t\t_id: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps._id.source\n\t\t},\n\t\ttype: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 256\n\t\t},\n\t\tsize: {\n\t\t\tbsonType: \"number\"\n\t\t},\n\t\tts: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 10\n\t\t},\n\t\tdata: {\n\t\t\tbsonType: \"binData\"\n\t\t},\n\t\tmeta: {\n\t\t\tbsonType: \"object\"\n\t\t}\n\t},\n\tadditionalProperties: false\n};\n", "import { CollectionSchema } from \"insite-db\";\nimport { regexps } from \"../lib\";\n\n\nexport const basisSchema: CollectionSchema = {\n\trequired: [\n\t\t\"_id\",\n\t\t\"email\",\n\t\t\"password\",\n\t\t\"roles\",\n\t\t\"name\",\n\t\t\"org\",\n\t\t\"job\",\n\t\t\"meta\",\n\t\t\"createdAt\"\n\t],\n\tproperties: {\n\t\t_id: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps._id.source\n\t\t},\n\t\temail: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps.email.source\n\t\t},\n\t\tpassword: {\n\t\t\tbsonType: \"string\",\n\t\t\tpattern: regexps.argon2.source\n\t\t},\n\t\troles: {\n\t\t\tbsonType: \"array\",\n\t\t\tuniqueItems: true,\n\t\t\titems: {\n\t\t\t\tbsonType: \"string\",\n\t\t\t\tpattern: regexps.role.source\n\t\t\t},\n\t\t\tadditionalItems: false\n\t\t},\n\t\tname: {\n\t\t\tbsonType: \"object\",\n\t\t\trequired: [\n\t\t\t\t\"first\",\n\t\t\t\t\"middle\",\n\t\t\t\t\"last\"\n\t\t\t],\n\t\t\tproperties: {\n\t\t\t\tfirst: {\n\t\t\t\t\tbsonType: \"string\",\n\t\t\t\t\tmaxLength: 512\n\t\t\t\t},\n\t\t\t\tmiddle: {\n\t\t\t\t\tbsonType: \"string\",\n\t\t\t\t\tmaxLength: 512\n\t\t\t\t},\n\t\t\t\tlast: {\n\t\t\t\t\tbsonType: \"string\",\n\t\t\t\t\tmaxLength: 512\n\t\t\t\t}\n\t\t\t},\n\t\t\tadditionalProperties: false\n\t\t},\n\t\torg: {\n\t\t\toneOf: [\n\t\t\t\t{\n\t\t\t\t\tbsonType: \"string\",\n\t\t\t\t\tpattern: regexps._id.source\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbsonType: \"null\"\n\t\t\t\t}\n\t\t\t]\n\t\t},\n\t\tjob: {\n\t\t\tbsonType: \"string\",\n\t\t\tmaxLength: 512\n\t\t},\n\t\tavatar: {\n\t\t\toneOf: [\n\t\t\t\t{\n\t\t\t\t\tbsonType: \"string\",\n\t\t\t\t\tmaxLength: 10\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tbsonType: \"null\"\n\t\t\t\t}\n\t\t\t]\n\t\t},\n\t\tmeta: {\n\t\t\tbsonType: \"object\"\n\t\t},\n\t\tcreatedAt: {\n\t\t\tbsonType: \"number\"\n\t\t}\n\t},\n\tadditionalProperties: false\n};\n", "import {\n\t_ids,\n\tdebounce,\n\tempty,\n\thasAny,\n\tremoveOne\n} from \"@nesvet/n\";\nimport type { Abilities, AbilitiesSchema } from \"insite-common\";\nimport type { GenericAbilities } from \"../abilities/types\";\nimport type { Org } from \"../orgs/Org\";\nimport type { Role } from \"../roles/Role\";\nimport type { Session } from \"../sessions/Session\";\nimport type { UserDoc } from \"./types\";\nimport type { Users } from \"./Users\";\n\n\nconst rolesSnapshots = new WeakMap();\nconst permissionsSnapshots = new WeakMap();\n\nconst staticUrl = process.env.INSITE_STATIC_URL ?? \"\";\n\n\nexport class User<AS extends AbilitiesSchema> {\n\tconstructor(users: Users<AS>, userDoc: UserDoc) {\n\t\tthis.#users = users;\n\t\t\n\t\tthis._id = userDoc._id;\n\t\tusers.set(this._id, this);\n\t\t\n\t\tvoid this.update(userDoc);\n\t\t\n\t\tif (users.isInited)\n\t\t\tusers.emit(\"user-create\", this);\n\t\t\n\t}\n\t\n\t_id;\n\temail!: string;\n\tname = {\n\t\tfirst: \"\",\n\t\tmiddle: \"\",\n\t\tlast: \"\"\n\t};\n\t\n\tinitials = \"\";\n\tdisplayLabel = \"\";\n\torg!: Org<AS>;\n\tjob: string = \"\";\n\tavatar: string | null = null;\n\tavatarUrl: string | null = null;\n\t\n\t#users;\n\t\n\tisUser = true;\n\tisRoot?: boolean;\n\t\n\troles = new Set<Role<AS>>();\n\townRoles: Role<AS>[] = [];\n\townRoleIds: string[] = [];\n\tslaveRoles = new Set<Role<AS>>();\n\tslaveRoleIds: string[] = [];\n\tabilities: Abilities<AS> = {};\n\t\n\tslaveOrgs = new Set<Org<AS>>();\n\tslaveUsers = new Set<User<AS>>();\n\tslaves = new Set<Org<AS> | User<AS>>();\n\t\n\tslaveIds: string[] = [];\n\tpermissiveIds: string[] = [];\n\t\n\tsessions = new Set<Session<AS>>();\n\t\n\tisOnline = false;\n\t\n\tupdate({ _id, name, email, roles: ownRoleIds, org: orgId, avatar, ...restProps }: Partial<UserDoc>) {\n\t\t\n\t\tObject.assign(this, restProps);\n\t\t\n\t\tlet isEmailUpdated;\n\t\tif (email && this.email !== email) {\n\t\t\tthis.#users.byEmail.delete(this.email);\n\t\t\tthis.email = email;\n\t\t\tthis.#users.byEmail.set(email, this);\n\t\t\tisEmailUpdated = true;\n\t\t}\n\t\t\n\t\tlet isNameUpdated;\n\t\tlet isLastNameUpdated;\n\t\tif (name && (this.name.first !== name.first || this.name.middle !== name.middle || this.name.last !== name.last)) {\n\t\t\tisLastNameUpdated = this.name.last !== name.last;\n\t\t\tthis.name = {\n\t\t\t\tfirst: name.first ?? \"\",\n\t\t\t\tmiddle: name.middle ?? \"\",\n\t\t\t\tlast: name.last ?? \"\"\n\t\t\t};\n\t\t\tthis.initials = (((name.first?.[0] ?? \"\") + (name.last?.[0] ?? \"\")) || this.email[0]).toUpperCase();\n\t\t\tisNameUpdated = true;\n\t\t}\n\t\t\n\t\tif (isEmailUpdated || isNameUpdated)\n\t\t\tthis.displayLabel = `${this.name.first} ${this.name.last}`.trim() || this.name.middle || this.email;\n\t\t\n\t\tlet isRolesUpdated;\n\t\tif (ownRoleIds) {\n\t\t\tthis.ownRoleIds = ownRoleIds;\n\t\t\t\n\t\t\tconst snapshot = this.ownRoleIds.join(\",\");\n\t\t\t\n\t\t\tif (snapshot !== rolesSnapshots.get(this)) {\n\t\t\t\trolesSnapshots.set(this, snapshot);\n\t\t\t\t\n\t\t\t\tif (this.#users.isInited) {\n\t\t\t\t\tthis.updateRoles();\n\t\t\t\t\tisRolesUpdated = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tlet isOrgUpdated;\n\t\tif (orgId !== undefined && this.org?._id !== orgId) {\n\t\t\tthis.org?.users.delete(this);\n\t\t\tthis.org = orgId && this.#users.orgs.get(orgId) || this.#users.orgs.null;// eslint-disable-line @stylistic/no-mixed-operators\n\t\t\tthis.org.users.add(this);\n\t\t\tisOrgUpdated = true;\n\t\t}\n\t\t\n\t\tif (avatar !== undefined && this.avatar !== avatar) {\n\t\t\tthis.avatar = avatar;\n\t\t\tthis.avatarUrl = avatar && `${staticUrl}/avatars/${this._id}-${avatar}.webp`;\n\t\t}\n\t\t\n\t\tif (this.#users.isInited)\n\t\t\tif (isRolesUpdated || isOrgUpdated) {\n\t\t\t\tthis.updatePermissions();\n\t\t\t\t\n\t\t\t\tif (isLastNameUpdated)\n\t\t\t\t\tthis.#users.isSortRequired = true;\n\t\t\t\t\n\t\t\t\tthis.#users.update();\n\t\t\t} else if (isLastNameUpdated)\n\t\t\t\tthis.#users.sort();\n\t\t\n\t}\n\t\n\tupdateRoles() {\n\t\t\n\t\tthis.ownRoles = [];\n\t\tthis.roles.clear();\n\t\tthis.slaveRoles.clear();\n\t\tempty(this.abilities);\n\t\t\n\t\tfor (const roleId of this.ownRoleIds) {\n\t\t\tconst role = this.#users.roles.get(roleId);\n\t\t\tif (role) {\n\t\t\t\t\n\t\t\t\tthis.ownRoles.push(role);\n\t\t\t\tthis.roles.add(role);\n\t\t\t\tfor (const involvedRole of role.involves) {\n\t\t\t\t\tthis.roles.add(involvedRole);\n\t\t\t\t\tthis.slaveRoles.add(involvedRole);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tthis.slaveRoleIds = _ids(this.slaveRoles);\n\t\t\t\t\n\t\t\t\tthis.#users.abilities.merge(this.abilities as GenericAbilities, role.abilities as GenericAbilities);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (this.roles.has(this.#users.roles.root))\n\t\t\tthis.isRoot = true;\n\t\t\n\t\tvoid this.trimSessions();\n\t\t\n\t}\n\t\n\tupdatePermissions() {\n\t\t\n\t\tthis.slaveOrgs.clear();\n\t\tthis.slaveUsers.clear();\n\t\tthis.slaves.clear();\n\t\tconst slaveIds = new Set<string>();\n\t\t\n\t\tfor (const org of this.#users.orgs.sorted)\n\t\t\tif ((org.ownerUsers.has(this) || this.isRoot) && !this.slaveOrgs.has(org)) {\n\t\t\t\tthis.slaveOrgs.add(org);\n\t\t\t\tthis.slaves.add(org);\n\t\t\t\tslaveIds.add(org._id);\n\t\t\t\tfor (const slaveOrg of org.slaveOrgs) {\n\t\t\t\t\tthis.slaveOrgs.add(slaveOrg);\n\t\t\t\t\tthis.slaves.add(slaveOrg);\n\t\t\t\t\tslaveIds.add(slaveOrg._id);\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\tfor (const org of new Set([ this.org, ...this.slaveOrgs, this.#users.orgs.null ]))\n\t\t\tfor (const user of org.users)\n\t\t\t\tif (user !== this && (hasAny(this.slaveRoles, user.ownRoles) || !user.ownRoles.length)) {\n\t\t\t\t\tthis.slaveUsers.add(user);\n\t\t\t\t\tthis.slaves.add(user);\n\t\t\t\t\tslaveIds.add(user._id);\n\t\t\t\t}\n\t\t\n\t\tthis.slaveIds = [ ...slaveIds ];\n\t\t\n\t\tconst permissiveOrgIds = [];\n\t\tif (this.org._id) {\n\t\t\tpermissiveOrgIds.push(this.org._id);\n\t\t\tfor (const slaveOrg of this.org.slaveOrgs)\n\t\t\t\tif (!this.slaveOrgs.has(slaveOrg))\n\t\t\t\t\tpermissiveOrgIds.push(slaveOrg._id);\n\t\t}\n\t\t\n\t\tthis.permissiveIds = [ ...permissiveOrgIds, this._id, ...slaveIds ];\n\t\t\n\t\t\n\t\tconst snapshot = [\n\t\t\tthis.permissiveIds.join(\",\"),\n\t\t\tthis.ownRoleIds.join(\",\"),\n\t\t\tJSON.stringify(this.abilities),\n\t\t\tthis.slaveRoleIds.join(\",\")\n\t\t].join(\"\\n\");\n\t\t\n\t\tif (snapshot !== permissionsSnapshots.get(this)) {\n\t\t\tpermissionsSnapshots.set(this, snapshot);\n\t\t\t\n\t\t\tif (this.#users.isInited)\n\t\t\t\tthis.#users.emit(\"user-permissions-change\", this);\n\t\t}\n\t\t\n\t}\n\t\n\ttrimSessions() {\n\t\t\n\t\tconst sessionsLimit = this.abilities.login?.sessionsLimit ?? 0;\n\t\t\n\t\tif (this.sessions.size > sessionsLimit)\n\t\t\treturn this.#users.sessions.collection.deleteMany({\n\t\t\t\t_id: {\n\t\t\t\t\t$in: _ids(\n\t\t\t\t\t\t[ ...this.sessions ]\n\t\t\t\t\t\t\t.sort((a, b) => a.expiresAt.valueOf() - b.expiresAt.valueOf())\n\t\t\t\t\t\t\t.slice(0, this.sessions.size - sessionsLimit)\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t});\n\t\t\n\t}\n\t\n\tupdateIsOnline() {\n\t\t\n\t\tlet isOnline = false;\n\t\t\n\t\tfor (const session of this.sessions)\n\t\t\tif (session.isOnline) {\n\t\t\t\tisOnline = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\n\t\tif (this.isOnline !== isOnline) {\n\t\t\tthis.isOnline = isOnline;\n\t\t\tthis.#users.emit(\"user-is-online\", this);\n\t\t}\n\t\t\n\t}\n\t\n\tupdateIsOnlineDebounced = debounce(() => this.updateIsOnline(), 500);\n\t\n\tasync delete() {\n\t\t\n\t\tthis.org.users.delete(this);\n\t\t\n\t\tthis.#users.delete(this._id);\n\t\tthis.#users.byEmail.delete(this.email);\n\t\tremoveOne(this.#users.sorted, this);\n\t\t\n\t\trolesSnapshots.delete(this);\n\t\tpermissionsSnapshots.delete(this);\n\t\t\n\t\tawait this.#users.replace(this._id);\n\t\t\n\t\tthis.#users.update();\n\t\t\n\t}\n\t\n}\n"],
5
+ "mappings": "AAAM,SAAUA,EAAgCC,EAAsB,CACrE,GAAIA,aAAoB,IAAK,CAC5B,IAAMC,EAAM,CAAA,EAEZ,QAAWC,KAAUF,EACpBC,EAAI,KAAKC,EAAO,GAAG,EAEpB,OAAOD,CACR,CAEA,OAAOD,EAAS,IAAIE,GAAUA,EAAO,GAAG,CACzC,CCXM,SAAUC,GAAOC,KAAeC,EAAU,CAE/C,IAAIC,EAAQ,EAEZ,QAAWC,KAAQF,EACbD,EAAM,SAASG,CAAI,IACvBH,EAAM,KAAKG,CAAI,EACfD,KAGF,OAAOA,CACR,CCXM,SAAUE,EAAWC,EAAiCC,EAAcC,EAAQ,CACjF,GAAIF,GAAUC,EAAM,CACnB,GAAIA,EAAK,SAAS,GAAG,EAAG,CACvB,IAAME,EAAOF,EAAK,MAAM,GAAG,EACvBG,EAAiBJ,EAErB,QAASK,EAAI,EAAGA,EAAIF,EAAK,OAAS,EAAGE,IAAK,CACzC,IAAMC,EAAMH,EAAKE,CAAC,EACZE,EAAiBH,EAAUE,CAAG,EAEpCF,EACEG,GAAkB,OAAOA,GAAkB,SAC3CA,EACCH,EAAUE,CAAG,EAAI,CAAA,CACrB,CAEA,OAAQF,EAAUD,EAAK,GAAG,EAAE,CAAE,EAAID,CACnC,CAEA,OAAQF,EAAOC,CAAI,EAAIC,CACxB,CAEA,OAAO,IACR,CCpBM,SAAUM,GAA8CC,KAAcC,EAAkC,CAC7G,QAAWC,KAAUD,EACpB,QAAWE,KAAQD,EACd,OAAO,OAAOA,EAAQC,CAAI,GAC7BC,EAAQJ,EAAQG,EAAMD,EAAOC,CAAI,CAAC,EAErC,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AKU,EAAiB,CAAC,CAC/B,CAEA,WAAa,IAAI,IAEjB,gBAAkB,IAAI,IAEtB,MAAM,QAAQI,EAAgB,CAC7B,IAAMC,EAAO,KAAK,WAAW,IAAID,CAAM,GAAK,KACxCC,GACH,KAAK,WAAW,OAAOD,CAAM,EAE9B,QAAWE,KAAW,KAAK,gBAC1B,MAAMA,EAAQF,EAAQC,CAAI,CAE5B,CAEA,MAAM,WAAWf,EAAa,CAC7B,GAAM,CAAE,aAAAiB,CAAa,EAAI,MAAM,KAAK,WAAW,UAAU,CAAE,IAAAjB,CAAI,CAAC,EAEhE,MAAO,EAAQiB,CAChB,CAGA,OAAO,KAAkC9D,EAA0BC,EAAuB,CAGzF,OAFc,IAAIF,EAAMC,EAAaC,CAAO,EAE/B,UAAU,CACxB,CAED",
6
+ "names": ["_ids", "iterable", "ids", "object", "add", "array", "items", "added", "item", "setPath", "object", "path", "value", "keys", "subObject", "i", "key", "subObjectValue", "assignPath", "target", "sources", "source", "path", "setPath", "noop", "nativesMap", "StatefulPromise", "_StatefulPromise", "executor", "options", "nativeResolve", "nativeReject", "resolve", "reject", "abortListener", "timeout", "value", "native", "reason", "_", "debounce", "callback", "limit", "options", "leading", "trailing", "maxWait", "timeout", "maxWaitTimeout", "end", "context", "args", "initial", "final", "result", "expired", "n", "debounced", "maxWaitExpired", "run", "error", "_args", "StatefulPromise", "resolve", "reject", "noop", "shouldRun", "deletePath", "object", "path", "keys", "subObject", "i", "key", "subObjectValue", "lastKey", "deleteProps", "object", "keys", "key", "empty", "object", "key", "EmptyArray", "EmptySet", "Err", "message", "tag", "payload", "getAll", "map", "keys", "onlyExisting", "items", "key", "item", "getPath", "object", "path", "subObject", "key", "hasAny", "mapOrSet", "items", "item", "howmuch", "number", "one", "two", "five", "shouldPrintNumber", "u", "d", "intersection", "iterables", "intersectionArray", "firstIterable", "otherIterables", "mainLoop", "item", "otherIterable", "pick", "object", "keys", "picked", "key", "reAdd", "set", "item", "removeAll", "array", "items", "i", "removed", "item", "removeOne", "array", "item", "i", "sort", "set", "compareFn", "item", "union", "iterables", "without", "array", "arrayToExclude", "item", "AbilityError", "Err", "longId", "payload", "isAbilityObject", "value", "isAbilityParamNumber", "isAbilityParamItems", "schemaParentMap", "AbilitiesMap", "abilitiesSchema", "subSchema", "#hierarchical", "parse", "schemas", "parent", "level", "schema", "longId", "subIds", "subId", "_id", "top", "paramId", "schemaOrLongId", "paramIdOrMax", "max", "ability", "paramSchema", "schemasOrIds", "a", "b", "schemaMaxMap", "resolve", "_schema", "parentSchema", "assignPath", "_max", "abilities", "subSchemas", "subAbilities", "i", "abilityParam", "value", "getPath", "setPath", "referenceValue", "isAbilityParamNumber", "isAbilityParamItems", "itemId", "intersection", "item", "adjustedAbilities", "adjustedAbility", "isAbilityObject", "pick", "empty", "target", "source", "targetAbility", "sourceAbility", "add", "deletePath", "RolesError", "Err", "stringOrArray", "payload", "snapshots", "Role", "roles", "roleDoc", "#roles", "_id", "ownInvolveIds", "ownAbilities", "title", "restProps", "snapshot", "regexps", "basisSchema", "regexps", "indexes", "preventDirectDelete", "Roles", "users", "options", "rootProps", "initOptions", "Role", "customSchema", "customIndexes", "collectionOptions", "removeAll", "basisSchema", "deleteProps", "schema", "#maintain", "roleDoc", "#handleCollectionChange", "next", "role", "involvedBy", "involvedRoleId", "involvedRole", "involvedByRole", "reAdd", "#sortRoles", "a", "b", "array", "anotherRole", "getAll", "sorted", "i", "involvedRoleIndex", "_o", "_id", "involves", "title", "description", "restProps", "roleId", "updates", "ids", "roles", "intersection", "cleanedUpIds", "abilityLongId", "set", "paramId", "value", "UnauthorizedError", "Err", "payload", "SubordinationError", "type", "ids", "PermissionError", "hash", "verify", "EventEmitter", "newObjectIdString", "newObjectIdString", "snapshots", "Org", "orgs", "orgDoc", "_id", "title", "ownerIds", "restProps", "snapshot", "basisSchema", "regexps", "indexes", "preventDirectDelete", "Orgs", "users", "options", "#isPreinited", "customSchema", "customIndexes", "nullProps", "collectionOptions", "removeAll", "basisSchema", "deleteProps", "schema", "Org", "EmptyArray", "EmptySet", "#maintain", "orgDoc", "#handleCollectionChange", "next", "#resolve", "org", "slaveOrgs", "ownerOrg", "slaveOrg", "array", "sorted", "ownerId", "ownerUser", "anotherOrg", "#sortOrgs", "sort", "slaveOrgIndex", "o", "length", "a", "b", "title", "note", "restProps", "_id", "newObjectIdString", "updates", "byUser", "union", "without", "_ids", "fromId", "toId", "handler", "randomBytes", "newObjectIdString", "basisSchema", "regexps", "Session", "sessions", "sessionDoc", "user", "#sessions", "_id", "isOnline", "restProps", "updates", "ts", "expireAfterSeconds", "indexes", "Sessions", "users", "options", "customSchema", "customIndexes", "collectionOptions", "removeAll", "basisSchema", "deleteProps", "schema", "#maintain", "sessionDoc", "#handleCollectionChange", "next", "Session", "newObjectIdString", "randomBytes", "user", "props", "ts", "session", "_id", "deletedCount", "Binary", "schema", "regexps", "Avatars", "users", "options", "collectionOptions", "schema", "#maintain", "_id", "type", "data", "binaryData", "Binary", "ts", "deletedCount", "basisSchema", "regexps", "rolesSnapshots", "permissionsSnapshots", "staticUrl", "User", "users", "userDoc", "#users", "_id", "name", "email", "ownRoleIds", "orgId", "avatar", "restProps", "isEmailUpdated", "isNameUpdated", "isLastNameUpdated", "isRolesUpdated", "snapshot", "isOrgUpdated", "empty", "roleId", "role", "involvedRole", "_ids", "slaveIds", "org", "slaveOrg", "user", "hasAny", "permissiveOrgIds", "sessionsLimit", "a", "b", "isOnline", "session", "debounce", "removeOne", "indexes", "Users", "_Users", "collections", "options", "eventEmitter", "EventEmitter", "#eventEmitter", "AbilitiesMap", "event", "callback", "context", "#isPreinited", "customIndexes", "customSchema", "initialRootProps", "collectionOptions", "removeAll", "basisSchema", "deleteProps", "schema", "#maintain", "userDoc", "rolesOptions", "orgsOptions", "sessionsOptions", "avatarsOptions", "quiet", "Roles", "Orgs", "Sessions", "Avatars", "#handleCollectionChange", "#initPromise", "next", "User", "a", "b", "shouldUpdateRoles", "user", "StatefulPromise", "email", "password", "roles", "name", "org", "job", "restProps", "_id", "newObjectIdString", "hash", "updates", "byUser", "without", "newPassword", "sessionProps", "verify", "session", "#sortUsersAndOrgs", "Org", "ids", "_ids", "fromId", "toId", "handler", "deletedCount"]
7
7
  }
@@ -1,4 +1,5 @@
1
- import { CollectionIndexes, CollectionOptions, CollectionSchema } from "insite-db";
1
+ import type { Prettify } from "@nesvet/n";
2
+ import type { CollectionIndexes, CollectionOptions, CollectionSchema } from "insite-db";
2
3
  export type OrgDoc = {
3
4
  _id: string;
4
5
  title: string;
@@ -13,5 +14,5 @@ export type OrgsOptions = {
13
14
  null?: Partial<OrgDoc>;
14
15
  collection?: Omit<CollectionOptions, "fullDocument" | "watch">;
15
16
  };
16
- export type NewOrg = Omit<OrgDoc, "_id" | "createdAt" | "meta" | "note" | "title"> & Partial<Pick<OrgDoc, "meta" | "note" | "title">>;
17
+ export type NewOrg = Prettify<Omit<OrgDoc, "_id" | "createdAt" | "meta" | "note" | "title"> & Partial<Pick<OrgDoc, "meta" | "note" | "title">>>;
17
18
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/orgs/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAGnF,MAAM,MAAM,MAAM,GAAG;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC9B,SAAS,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,WAAW,GAAG;IACzB,MAAM,CAAC,EAAE,gBAAgB,CAAC;IAC1B,OAAO,CAAC,EAAE,iBAAiB,CAAC;IAC5B,IAAI,CAAC,EAAE,OAAO,CAAC,MAAM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M,GAAG,OAAO,CAAC,CAAC,CAChD,CAAC"}
@@ -1,5 +1,6 @@
1
- import { CollectionIndexes, CollectionOptions, CollectionSchema } from "insite-db";
2
- import { GenericAbilities } from "../abilities";
1
+ import type { Prettify } from "@nesvet/n";
2
+ import type { CollectionIndexes, CollectionOptions, CollectionSchema } from "insite-db";
3
+ import type { GenericAbilities } from "../abilities";
3
4
  export type RoleDoc = {
4
5
  _id: Exclude<string, "root">;
5
6
  involves: Exclude<string, "root">[];
@@ -15,5 +16,5 @@ export type RolesOptions = {
15
16
  root?: Partial<RoleDoc>;
16
17
  collection?: Omit<CollectionOptions, "fullDocument" | "watch">;
17
18
  };
18
- export type NewRole = Omit<RoleDoc, "abilities" | "createdAt" | "description" | "involves" | "meta" | "title"> & Partial<Pick<RoleDoc, "description" | "involves" | "meta" | "title">>;
19
+ export type NewRole = Prettify<Omit<RoleDoc, "abilities" | "createdAt" | "description" | "involves" | "meta" | "title"> & Partial<Pick<RoleDoc, "description" | "involves" | "meta" | "title">>>;
19
20
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/roles/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AACnF,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAGhD,MAAM,MAAM,OAAO,GAAG;IACrB,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,QAAQ,EAAE,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC;IACpC,SAAS,EAAE,gBAAgB,CAAC;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC9B,SAAS,EAAE,MAAM,CAAC;CAClB,CAAC;A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AI,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACxB,UAAU,CAAC,EAAE,IAAI,CAAC,iBAAiB,EAAE,cAAc,GAAG,OAAO,CAAC,CAAC;CAC/D,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG,QAAQ,CAC7B,IAAI,CAAC,OAAO,EAAE,WAAW,GAAG,WAAW,GAAG,aAAa,GAAG,UAAU,GAAG,MAAM,GAAG,OAAO,CAAC,GACxF,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,aAAa,GAAG,UAAU,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC,CACrE,CAAC"}
@@ -1,4 +1,4 @@
1
- import { CollectionIndexes, CollectionOptions, CollectionSchema } from "insite-db";
1
+ import type { CollectionIndexes, CollectionOptions, CollectionSchema } from "insite-db";
2
2
  export type SessionDoc = {
3
3
  _id: string;
4
4
  user: string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/sessions/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAGnF,MAAM,MAAM,UAAU,GAAG;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,OAAO,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,IAAI,CAAC;IAGhB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC7B,MAAM,CAAC,EAAE,gBAAgB,CAAC;IAC1B,OAAO,CAAC,EAAE,iBAAiB,CAAC;IAC5B,UAAU,CAAC,EAAE,IAAI,CAAC,iBAAiB,EAAE,cAAc,GAAG,OAAO,CAAC,CAAC;CAC/D,CAAC"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/sessions/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAGxF,MAAM,MAAM,UAAU,GAAG;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,OAAO,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,IAAI,CAAC;IAGhB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC7B,MAAM,CAAC,EAAE,gBAAgB,CAAC;IAC1B,OAAO,CAAC,EAAE,iBAAiB,CAAC;IAC5B,UAAU,CAAC,EAAE,IAAI,CAAC,iBAAiB,EAAE,cAAc,GAAG,OAAO,CAAC,CAAC;CAC/D,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"User.d.ts","sourceRoot":"","sources":["../../src/users/User.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEhE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,KAAK,EA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,MAAM,CAAC,IAAI,CAAC,GAAG,SAAS,eAAe,EAAE,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC;CAMxF"}
@@ -1,3 +1,4 @@
1
+ import type { Prettify } from "@nesvet/n";
1
2
  import type { CollectionIndexes, CollectionOptions, CollectionSchema } from "insite-db";
2
3
  import type { OrgsOptions } from "../orgs/types";
3
4
  import type { RolesOptions } from "../roles/types";
@@ -30,7 +31,7 @@ export type Options<AS> = {
30
31
  avatars?: AvatarsOptions;
31
32
  collection?: Omit<CollectionOptions, "fullDocument" | "watch">;
32
33
  };
33
- export type NewUser = Omit<UserDoc, "_id" | "createdAt" | "job" | "meta" | "name" | "org"> & Partial<Pick<UserDoc, "job" | "meta" | "org">> & {
34
+ export type NewUser = Prettify<Omit<UserDoc, "_id" | "createdAt" | "job" | "meta" | "name" | "org"> & Partial<Pick<UserDoc, "job" | "meta" | "org">> & {
34
35
  name: Partial<UserDoc["name"]>;
35
- };
36
+ }>;
36
37
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/users/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AACxF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAGhD,MAAM,MAAM,OAAO,GAAG;IACrB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,IAAI,EAAE;QACL,KAAK,C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;AAEF,MAAM,MAAM,OAAO,GAAG,QAAQ,CAC7B,IAAI,CAAC,OAAO,EAAE,KAAK,GAAG,WAAW,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,KAAK,CAAC,GACpE,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,GAAG,MAAM,GAAG,KAAK,CAAC,CAAC,GAC9C;IAAE,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAA;CAAE,CAClC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "insite-users-server",
3
- "version": "2.3.0",
3
+ "version": "2.3.3",
4
4
  "description": "inSite users server side",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -12,7 +12,7 @@
12
12
  ".": "./dist/index.js",
13
13
  "./ws": "./dist/ws.js"
14
14
  },
15
- "packageManager": "bun@1.2.11",
15
+ "packageManager": "bun@1.2.18",
16
16
  "scripts": {
17
17
  "test": "echo \"Error: no test specified\" && exit 1",
18
18
  "build": "bun .conveyer.js",
@@ -30,19 +30,19 @@
30
30
  "author": "Eugene Nesvetaev <dev@nesvet.dev> (https://nesvet.dev/)",
31
31
  "license": "MIT",
32
32
  "dependencies": {
33
- "@nesvet/n": "^1.2.0",
34
- "argon2": "^0.40.3",
33
+ "@nesvet/n": "^1.2.1",
34
+ "@node-rs/argon2": "^2.0.2",
35
35
  "eventemitter3": "^5.0.1",
36
- "insite-common": "^2.3.0",
37
- "insite-db": "^2.3.0",
38
- "insite-subscriptions-server": "^2.3.0",
39
- "insite-ws": "^2.3.0",
40
- "insite-ws-transfers": "^2.3.0"
36
+ "insite-common": "^2.3.3",
37
+ "insite-db": "^2.3.3",
38
+ "insite-subscriptions-server": "^2.3.3",
39
+ "insite-ws": "^2.3.3",
40
+ "insite-ws-transfers": "^2.3.3"
41
41
  },
42
42
  "devDependencies": {
43
- "@nesvet/conveyer": "^2.5.2",
44
- "@nesvet/eslint-config": "^2.1.1",
45
- "@types/node": "^22.15.3",
43
+ "@nesvet/conveyer": "^2.6.1",
44
+ "@nesvet/eslint-config": "^2.1.2",
45
+ "@types/node": "^24.0.13",
46
46
  "typescript": "^5.8.3"
47
47
  }
48
48
  }