@prestizni-software/server-dem 0.2.60 → 0.2.62

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.
@@ -1,673 +0,0 @@
1
- import "reflect-metadata";
2
- import {
3
- Constructor,
4
- EventEmitter3,
5
- InstanceOf,
6
- IsData,
7
- LoggersType,
8
- LoggersTypeInternal,
9
- Paths,
10
- PathValueOf,
11
- ServerResponse,
12
- ServerUpdateRequest,
13
- } from "./CommonTypes.js";
14
- import { AutoUpdateManager } from "./AutoUpdateManagerClass.js";
15
- import { ObjectId } from "bson";
16
- import { Socket } from "socket.io-client";
17
- type SocketType = Socket<any, any>;
18
- export type AutoUpdated<T extends Constructor<any>> =
19
- AutoUpdatedClientObject<T> & InstanceOf<T>;
20
- export async function createAutoUpdatedClass<C extends Constructor<any>>(
21
- classParam: C,
22
- socket: SocketType,
23
- data: IsData<InstanceType<C>> | string,
24
- loggers: LoggersType,
25
- autoClassers: AutoUpdateManager<any>,
26
- emitter: EventEmitter3,
27
- token: string
28
- ): Promise<AutoUpdated<C>> {
29
- if (typeof data !== "string") {
30
- checkForMissingRefs<C>(data as any, [], classParam, autoClassers);
31
- processIsRefProperties(data, classParam.prototype, undefined, [], loggers);
32
- }
33
- const props = Reflect.getMetadata("props", classParam.prototype);
34
- const instance = new (class extends AutoUpdatedClientObject<C> {})(
35
- socket,
36
- data,
37
- loggers,
38
- props,
39
- classParam.name,
40
- classParam,
41
- autoClassers,
42
- emitter,
43
- token
44
- );
45
-
46
- await instance.isLoadedAsync();
47
-
48
- return instance as any;
49
- }
50
-
51
- export abstract class AutoUpdatedClientObject<T extends Constructor<any>> {
52
- protected readonly socket: SocketType;
53
- //protected updates: string[] = [];
54
- protected data: IsData<T>;
55
- protected readonly isServer: boolean = false;
56
- protected readonly loggers: LoggersTypeInternal = {
57
- info: () => {},
58
- debug: () => {},
59
- error: () => {},
60
- warn: () => {},
61
- };
62
- protected isLoading = false;
63
- protected readonly emitter: EventEmitter3;
64
- protected readonly properties: (keyof T)[];
65
- protected readonly className: string;
66
- protected autoClasser: AutoUpdateManager<any>;
67
- protected isLoadingReferences = false;
68
- public readonly classProp: Constructor<T>;
69
- private readonly EmitterID = new ObjectId().toHexString();
70
- private readonly token: string;
71
- private readonly loadShit = async () => {
72
- if (this.isLoaded()) {
73
- try {
74
- await this.loadForceReferences();
75
- } catch (error) {
76
- this.loggers.error(error);
77
- }
78
- this.isLoadingReferences = false;
79
-
80
- return;
81
- }
82
- this.emitter.on("loaded" + this.EmitterID, async () => {
83
- try {
84
- await this.loadForceReferences();
85
- } catch (error) {
86
- this.loggers.error(error);
87
- }
88
- this.isLoadingReferences = false;
89
- });
90
- };
91
- constructor(
92
- socket: SocketType,
93
- data: string | IsData<T>,
94
- loggers: LoggersType,
95
- properties: (keyof T)[],
96
- className: string,
97
- classProperty: Constructor<T>,
98
- autoClasser: AutoUpdateManager<any>,
99
- emitter: EventEmitter3,
100
- token: string = ""
101
- ) {
102
- this.token = token;
103
- this.emitter = emitter;
104
- this.classProp = classProperty;
105
- this.isLoadingReferences = true;
106
- this.isLoading = true;
107
- this.autoClasser = autoClasser;
108
- this.className = className;
109
- this.properties = properties;
110
- this.loggers.debug = loggers.debug;
111
- this.loggers.info = loggers.info;
112
- this.loggers.error = loggers.error;
113
- this.loggers.warn = loggers.warn ?? loggers.info;
114
- this.socket = socket;
115
- if (typeof data === "string") {
116
- if (data === "")
117
- throw new Error(
118
- "Cannot create a new AutoUpdatedClientClass with an empty string for ID."
119
- );
120
- this.socket.emit(
121
- "get" + this.className + data,
122
- null,
123
- (res: ServerResponse<T>) => {
124
- if (!res.success) {
125
- this.isLoading = false;
126
- this.loggers.error("Could not load data from server:", res.message);
127
- this.emitter.emit("loaded" + this.EmitterID);
128
- return;
129
- }
130
- checkForMissingRefs<T>(
131
- res.data as any,
132
- properties,
133
- classProperty as any,
134
- autoClasser
135
- );
136
- this.data = res.data as IsData<T>;
137
- this.isLoading = false;
138
- this.emitter.emit("loaded" + this.EmitterID);
139
- }
140
- );
141
- this.data = { _id: data } as IsData<T>;
142
- } else {
143
- this.isLoading = true;
144
- checkForMissingRefs<T>(
145
- data as any,
146
- properties,
147
- classProperty as any,
148
- autoClasser
149
- );
150
- this.data = data as any;
151
-
152
- if (!this.data._id || this.data._id === "") this.handleNewObject(data as any);
153
- else {
154
- this.isLoading = false;
155
- }
156
- }
157
- if (!this.isServer) this.openSockets();
158
- this.generateSettersAndGetters();
159
- }
160
-
161
- protected handleNewObject(data: IsData<T>) {
162
- this.isLoading = true;
163
- if (!this.className)
164
- throw new Error(
165
- "Cannot create a new AutoUpdatedClientClass without a class name."
166
- );
167
- this.socket.emit("new" + this.className, data, (res: ServerResponse<T>) => {
168
- if (!res.success) {
169
- this.isLoading = false;
170
- this.loggers.error("Could not create data on server:", res.message);
171
- this.emitter.emit("loaded" + this.EmitterID);
172
- throw new Error("Error creating new object: " + res.message);
173
- }
174
- checkForMissingRefs<T>(
175
- res.data as any,
176
- this.properties,
177
- this.classProp as any,
178
- this.autoClasser
179
- );
180
- this.data = res.data as IsData<T>;
181
- this.isLoading = false;
182
- this.emitter.emit("loaded" + this.EmitterID);
183
- });
184
- }
185
-
186
- public get extractedData(): {
187
- [K in keyof InstanceType<T>]: InstanceOf<InstanceType<T>>[K];
188
- } {
189
- const extracted = processIsRefProperties(
190
- this.data,
191
- this.classProp.prototype,
192
- null,
193
- [],
194
- {},
195
- this.loggers
196
- ).newData;
197
-
198
- return structuredClone(extracted) as {
199
- [K in keyof InstanceType<T>]: InstanceOf<InstanceType<T>>[K];
200
- };
201
- }
202
-
203
- public isLoaded(): boolean {
204
- return !this.isLoading;
205
- }
206
-
207
- public async isLoadedAsync(): Promise<boolean> {
208
- await this.loadShit();
209
- return this.isLoading
210
- ? new Promise((resolve) => {
211
- this.emitter.on("loaded" + this.EmitterID, async () => {
212
- resolve(this.isLoading === false);
213
- });
214
- })
215
- : true;
216
- }
217
-
218
- private openSockets() {
219
- this.loggers.debug(`[${this.data._id}] Opening socket listeners`);
220
-
221
- this.socket.on(
222
- "update" + this.className + this.data._id.toString(),
223
- async (update: ServerUpdateRequest<T>) => {
224
- await this.handleUpdateRequest(update);
225
- }
226
- );
227
- }
228
-
229
- private async handleUpdateRequest(
230
- update: ServerUpdateRequest<T>
231
- ): Promise<ServerResponse<undefined>> {
232
- try {
233
- const path = update.key.split(".");
234
- let dataRef: any = this.data;
235
- for (let i = 0; i < path.length - 1; i++) {
236
- if (!dataRef[path[i]]) dataRef[path[i]] = {};
237
- dataRef = dataRef[path[i]];
238
- }
239
- dataRef[path.at(-1)!] = update.value;
240
-
241
- this.loggers.debug(
242
- `[${this.data._id}] Applied patch ${update.key} set to ${update.value}`
243
- );
244
-
245
- // Return success with the applied patch
246
- return { success: true, data: undefined, message: "" };
247
- } catch (error) {
248
- this.loggers.error(`[${this.data._id}] Error applying patch:`, error);
249
- return {
250
- success: false,
251
- message: "Error applying update: " + (error as Error).message,
252
- };
253
- }
254
- }
255
-
256
- private generateSettersAndGetters() {
257
- for (const key of this.properties) {
258
- if (typeof key !== "string") return;
259
-
260
- const k = key as keyof IsData<T>;
261
- const isRef = getMetadataRecursive(
262
- "isRef",
263
- this.classProp.prototype,
264
- key
265
- );
266
-
267
- Object.defineProperty(this, key, {
268
- get: () => {
269
- if (isRef)
270
- return typeof this.data[k] === "string"
271
- ? this.findReference(this.data[k] as string)
272
- : this.data[k];
273
- else return this.data[k];
274
- },
275
- set: () => {
276
- throw new Error(
277
- `Cannot set ${key} this way, use "setValue" function.`
278
- );
279
- },
280
- enumerable: true,
281
- configurable: true,
282
- });
283
- }
284
- }
285
-
286
- protected findReference(id: string): AutoUpdated<any> | undefined {
287
- for (const classer of Object.values(this.autoClasser.classers)) {
288
- const result = classer.getObject(id);
289
- if (result) return result;
290
- }
291
- }
292
-
293
- public setValue<K extends Paths<InstanceOf<T>>>(
294
- key: K,
295
- val: PathValueOf<T, K>
296
- ): Promise<{ success: boolean; msg: string }> {
297
- return this.setValue__(key, val);
298
- }
299
-
300
- protected async setValue__(
301
- key: any,
302
- val: any
303
- ): Promise<{ success: boolean; msg: string }> {
304
- let message = "Setting value " + key + " of " + this.className;
305
- let value = val;
306
- this.loggers.debug(
307
- `[${(this.data as any)._id}] Setting ${key} to ${value}`
308
- );
309
- try {
310
- if (value instanceof AutoUpdatedClientObject)
311
- value = (value as any).extractedData._id;
312
- const path = key.split(".");
313
- let obj = this.data as any;
314
- let lastClass = this as any;
315
- let lastPath = key as string;
316
- for (let i = 0; i < path.length - 1; i++) {
317
- if (
318
- typeof obj[path[i]] !== "object" ||
319
- obj[path[i]] instanceof ObjectId
320
- ) {
321
- let temp;
322
- try {
323
- temp = this.resolveReference(
324
- obj[path[i]]?.toString()
325
- ) as AutoUpdated<any>;
326
- } catch (error: any) {
327
- message +=
328
- "\n Error: likely undefined property on path: " +
329
- path +
330
- " on index: " +
331
- i +
332
- " with error: " +
333
- error.message;
334
- }
335
- if (!temp) {
336
- message +=
337
- "\nLikely undefined property " +
338
- path[i] +
339
- " on path: " +
340
- path +
341
- " at index: " +
342
- i;
343
- this.loggers.warn(
344
- "Failed to set value for " + this.className + "\n" + message
345
- );
346
- return {
347
- success: false,
348
- msg: message,
349
- };
350
- }
351
- lastClass = temp;
352
- lastPath = path.slice(i + 1).join(".");
353
- return await lastClass.setValue(lastPath, value);
354
- } else obj = obj[path[i]];
355
- }
356
-
357
- if (lastClass !== this || lastPath !== (key as any)) {
358
- message +=
359
- "\n What the actual fuckity fuck error on path: " +
360
- path +
361
- " on index: " +
362
- (path.length - 1);
363
- this.loggers.error(
364
- "Failed to set value for " + this.className + "\n" + message
365
- );
366
- return {
367
- success: false,
368
- msg: message,
369
- };
370
- }
371
-
372
- let success;
373
- try {
374
- const res = await this.setValueInternal(lastPath, value);
375
- success = res.success;
376
- message += "\nReport from inner setValue function: \n " + res.message;
377
- } catch (error: any) {
378
- success = false;
379
- message += "\nError from inner setValue function: \n " + error.message;
380
- }
381
-
382
- if (!success) {
383
- this.loggers.warn(
384
- "Failed to set value for " + this.className + "\n" + message
385
- );
386
- return { success: false, msg: message };
387
- }
388
- const pathArr = lastPath.split(".");
389
- if (pathArr.length === 1) {
390
- (this.data as any)[key as any] = value;
391
- await this.checkAutoStatusChange();
392
- return {
393
- success: true,
394
- msg: "Successfully set " + key + " to " + value,
395
- };
396
- }
397
- const pathMinusLast = pathArr.splice(0, 1);
398
- let ref = this as any;
399
- for (const p of pathMinusLast) {
400
- ref = ref[p];
401
- }
402
- ref[pathArr.at(-1)!] = value;
403
- await this.checkAutoStatusChange();
404
- return {
405
- success: true,
406
- msg: "Successfully set " + key + " to " + value,
407
- };
408
- } catch (error: any) {
409
- this.loggers.error(
410
- "An error occurred setting value for " +
411
- this.className +
412
- "\n" +
413
- message +
414
- "\n Random error here: " +
415
- error.message +
416
- "\n" +
417
- error.stack
418
- );
419
- this.loggers.error(error);
420
- return {
421
- success: false,
422
- msg:
423
- message +
424
- "\n Random error here: " +
425
- error.message +
426
- "\n" +
427
- error.stack,
428
- };
429
- }
430
- }
431
-
432
- public getValue(key: Paths<T>) {
433
- let value: any;
434
-
435
- for (const part of key.split(".")) {
436
- try {
437
- if (value) value = value[part];
438
- else value = (this.data as any)[part];
439
- } catch (error: any) {
440
- this.loggers.error(
441
- "Error getting value for " +
442
- this.className +
443
- " on key " +
444
- key +
445
- " on index " +
446
- part +
447
- ":",
448
- error.message
449
- );
450
- }
451
- }
452
- return value;
453
- }
454
-
455
- protected async setValueInternal(
456
- key: string,
457
- value: any
458
- ): Promise<{ success: boolean; message: string }> {
459
- const update: ServerUpdateRequest<T> = this.makeUpdate(key, value);
460
- const promise = new Promise<{ success: boolean; message: string }>(
461
- (resolve) => {
462
- try {
463
- this.socket.emit(
464
- "update" + this.className + this.data._id,
465
- update,
466
- (res: ServerResponse<T>) => {
467
- resolve({ success: res.success, message: res.message });
468
- }
469
- );
470
- } catch (error: any) {
471
- this.loggers.error("Error sending update:", error);
472
- resolve({ success: false, message: error.message });
473
- }
474
- }
475
- );
476
- return promise;
477
- }
478
-
479
- protected makeUpdate(key: string, value: any): any {
480
- try {
481
- const id = this.data._id.toString();
482
- return { _id: id, key, value } as any;
483
- } catch (error: any) {
484
- this.loggers.error(
485
- "Probably missing the fucking identifier ['_id'] again " + error.message
486
- );
487
- throw error;
488
- }
489
- }
490
-
491
- protected async checkAutoStatusChange() {
492
- return;
493
- }
494
-
495
- // return a properly typed AutoUpdatedClientClass (or null)
496
- // inside AutoUpdatedClientClass
497
- protected resolveReference(id: string): AutoUpdatedClientObject<any> | null {
498
- if (!this.autoClasser) throw new Error("No autoClasser");
499
- for (const autoClasser of Object.values(this.autoClasser.classers)) {
500
- const data = autoClasser.getObject(id);
501
- if (data) return data;
502
- }
503
- return null;
504
- }
505
-
506
- private async loadForceReferences(
507
- obj: any = this.data,
508
- proto: any = this.classProp.prototype
509
- ) {
510
- const props: string[] = Reflect.getMetadata("props", proto) || [];
511
-
512
- for (const key of props) {
513
- const isRef = Reflect.getMetadata("isRef", proto, key);
514
-
515
- if (isRef) {
516
- await this.handleLoadOnForced(obj, key);
517
- }
518
-
519
- // If the property itself is a nested object, check deeper
520
- if (obj[key] && typeof obj[key] === "object") {
521
- const nestedProto = Object.getPrototypeOf(obj[key]);
522
- if (nestedProto) {
523
- await this.loadForceReferences(obj[key], nestedProto);
524
- }
525
- }
526
- }
527
- }
528
-
529
- private async handleLoadOnForced(obj: any, key: string) {
530
- if (!this.autoClasser) throw new Error("No autoClassers");
531
- const refId = obj[key];
532
- if (refId) {
533
- for (const classer of Object.values(this.autoClasser.classers)) {
534
- const result = classer.getObject(refId);
535
- if (result) {
536
- obj[key] = result;
537
-
538
- // Recursively load refs inside the resolved object
539
- if (typeof result.loadForceReferences === "function") {
540
- await result.loadForceReferences();
541
- }
542
- break;
543
- }
544
- }
545
- }
546
- }
547
- public async destroy(): Promise<void> {
548
- this.socket.emit("delete" + this.className, this.data._id);
549
-
550
- this.socket.removeAllListeners("update" + this.className + this.data._id);
551
- this.socket.removeAllListeners("delete" + this.className + this.data._id);
552
- this.wipeSelf();
553
- }
554
-
555
- protected wipeSelf() {
556
- for (const key of Object.keys(this.data)) {
557
- delete (this.data as any)[key];
558
- }
559
- this.loggers.info(`[${this.data._id}] ${this.className} object wiped`);
560
- }
561
- }
562
-
563
- export function processIsRefProperties(
564
- instance: any,
565
- target: any,
566
- prefix: string | null = null,
567
- allProps: string[] = [],
568
- newData = {} as any,
569
- loggers = console as LoggersType
570
- ) {
571
- const props: string[] = Reflect.getMetadata("props", target) || [];
572
-
573
- for (const prop of props) {
574
- const path = prefix ? `${prefix}.${prop}` : prop;
575
- allProps.push(path);
576
- newData[prop] = ObjectId.isValid(instance[prop])
577
- ? instance[prop]?.toString()
578
- : instance[prop];
579
- if (Reflect.getMetadata("isRef", target, prop)) {
580
- if (Array.isArray(instance[prop]))
581
- newData[prop] = instance[prop].map((item: any) =>
582
- typeof item === "string"
583
- ? item
584
- : ObjectId.isValid(item)
585
- ? item?.toString()
586
- : item?._id
587
- );
588
- else
589
- newData[prop] =
590
- typeof instance[prop] === "string"
591
- ? instance[prop]
592
- : ObjectId.isValid(instance[prop])
593
- ? instance[prop]?.toString()
594
- : instance[prop]?._id;
595
- }
596
-
597
- const type = Reflect.getMetadata("design:type", target, prop);
598
- if (type?.prototype) {
599
- const nestedProps = Reflect.getMetadata("props", type.prototype);
600
- if (nestedProps && instance[prop]) {
601
- newData[prop] = processIsRefProperties(
602
- instance[prop],
603
- type.prototype,
604
- path,
605
- allProps,
606
- undefined,
607
- loggers
608
- ).newData;
609
- }
610
- }
611
- }
612
- return { allProps, newData };
613
- }
614
-
615
- export function getMetadataRecursive(
616
- metaKey: string,
617
- proto: any,
618
- prop: string
619
- ) {
620
- while (proto) {
621
- const meta = Reflect.getMetadata(metaKey, proto, prop);
622
- if (meta) return meta;
623
- proto = Object.getPrototypeOf(proto);
624
- }
625
- return undefined;
626
- }
627
-
628
- function checkForMissingRefs<C extends Constructor<any>>(
629
- data: IsData<InstanceType<C>>,
630
- props: any,
631
- classParam: C,
632
- autoClassers: AutoUpdateManager<any>
633
- ) {
634
- if (typeof data !== "string") {
635
- const entryKeys = Object.keys(data);
636
- for (const prop of props) {
637
- const pointer = getMetadataRecursive(
638
- "isRef",
639
- classParam.prototype,
640
- prop.toString()
641
- );
642
- if (!entryKeys.includes(prop.toString()) && pointer) {
643
- findMissingObjectReference(data, prop, autoClassers.classers, pointer);
644
- }
645
- }
646
- }
647
- }
648
- function findMissingObjectReference(
649
- data: any,
650
- prop: any,
651
- autoClassers: { [key: string]: AutoUpdateManager<any> },
652
- acName: string
653
- ) {
654
- let foundAnAC = false;
655
- for (const ac of Object.values(autoClassers)) {
656
- if (ac.className !== acName) {
657
- continue;
658
- }
659
- foundAnAC = true;
660
- for (const obj of ac.objectsAsArray) {
661
- const found = Object.values(obj.extractedData).find((value) =>
662
- Array.isArray(value) ? value.includes(data._id) : value === data._id
663
- );
664
- if (found) {
665
- data[prop] = obj._id;
666
- return;
667
- }
668
- }
669
- }
670
- if (!foundAnAC) {
671
- throw new Error(`No AutoUpdateManager found for class ${acName}`);
672
- }
673
- }