@prestizni-software/client-dem 0.2.21 → 0.2.23

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,516 +0,0 @@
1
- import "reflect-metadata";
2
- import {
3
- Constructor,
4
- DeRef,
5
- InstanceOf,
6
- IsData,
7
- LoggersType,
8
- LoggersTypeInternal,
9
- Paths,
10
- PathValueOf,
11
- RefToId,
12
- ServerResponse,
13
- ServerUpdateRequest,
14
- SocketType,
15
- } from "./CommonTypes.ts";
16
- import { AutoUpdateManager } from "./AutoUpdateManagerClass.ts";
17
- import { ObjectId } from "bson";
18
-
19
- export type AutoUpdated<T extends Constructor<any>> =
20
- AutoUpdatedClientObject<T> & DeRef<InstanceOf<T>>;
21
- export async function createAutoUpdatedClass<C extends Constructor<any>>(
22
- classParam: C,
23
- socket: SocketType,
24
- data: RefToId<IsData<InstanceType<C>>> | string,
25
- loggers: LoggersType,
26
- autoClassers: { [key: string]: AutoUpdateManager<any> },
27
- emitter: EventTarget
28
- ): Promise<AutoUpdated<C>> {
29
- if (typeof data !== "string")
30
- processIsRefProperties(data, classParam.prototype, undefined, [], loggers);
31
- const props = Reflect.getMetadata("props", classParam.prototype);
32
- const instance = new (class extends AutoUpdatedClientObject<C> {})(
33
- socket,
34
- data,
35
- loggers,
36
- props,
37
- classParam.name,
38
- classParam,
39
- autoClassers,
40
- emitter
41
- );
42
-
43
- await instance.isLoadedAsync();
44
-
45
- return instance as any;
46
- }
47
-
48
- export abstract class AutoUpdatedClientObject<T extends Constructor<any>> {
49
- protected readonly socket: SocketType;
50
- //protected updates: string[] = [];
51
- protected data: IsData<T>;
52
- protected readonly isServer: boolean = false;
53
- protected readonly loggers: LoggersTypeInternal = {
54
- info: () => {},
55
- debug: () => {},
56
- error: () => {},
57
- warn: () => {},
58
- };
59
- protected isLoading = false;
60
- protected readonly emitter;
61
- protected readonly properties: (keyof T)[];
62
- protected readonly className: string;
63
- protected autoClassers: Record<string, AutoUpdateManager<any>>;
64
- protected isLoadingReferences = false;
65
- public readonly classProp: Constructor<T>;
66
- private readonly EmitterID = new ObjectId().toHexString();
67
- private readonly loadShit = async () => {
68
- if (this.isLoaded()) {
69
- try {
70
- await this.loadForceReferences();
71
- } catch (error) {
72
- this.loggers.error(error);
73
- }
74
- this.isLoadingReferences = false;
75
-
76
- return;
77
- }
78
- this.emitter.addEventListener("loaded" + this.EmitterID, async () => {
79
- try {
80
- await this.loadForceReferences();
81
- } catch (error) {
82
- this.loggers.error(error);
83
- }
84
- this.isLoadingReferences = false;
85
- });
86
- };
87
- constructor(
88
- socket: SocketType,
89
- data: string | RefToId<IsData<T>>,
90
- loggers: LoggersType,
91
- properties: (keyof T)[],
92
- className: string,
93
- classProperty: Constructor<T>,
94
- autoClassers: Record<string, AutoUpdateManager<any>>,
95
- emitter: EventTarget
96
- ) {
97
- this.emitter = emitter;
98
- this.classProp = classProperty;
99
- this.isLoadingReferences = true;
100
- this.isLoading = true;
101
- this.autoClassers = autoClassers;
102
- this.className = className;
103
- this.properties = properties;
104
- this.loggers.debug = loggers.debug;
105
- this.loggers.info = loggers.info;
106
- this.loggers.error = loggers.error;
107
- this.loggers.warn = loggers.warn ?? loggers.info;
108
- this.socket = socket;
109
- if (typeof data === "string") {
110
- if (data === "")
111
- throw new Error(
112
- "Cannot create a new AutoUpdatedClientClass with an empty string for ID."
113
- );
114
- this.socket.emit(
115
- "get" + this.className + data,
116
- null,
117
- (res: ServerResponse<T>) => {
118
- if (!res.success) {
119
- this.isLoading = false;
120
- this.loggers.error("Could not load data from server:", res.message);
121
- this.emitter.dispatchEvent(new Event("loaded" + this.EmitterID));
122
- return;
123
- }
124
- checkForMissingRefs<T>(
125
- res.data as any,
126
- properties,
127
- classProperty as any,
128
- autoClassers
129
- );
130
- this.data = res.data as IsData<T>;
131
- this.isLoading = false;
132
- this.emitter.dispatchEvent(new Event("loaded" + this.EmitterID));
133
- }
134
- );
135
- this.data = { _id: data } as IsData<T>;
136
- } else {
137
- this.isLoading = true;
138
- checkForMissingRefs<T>(
139
- data as any,
140
- properties,
141
- classProperty as any,
142
- autoClassers
143
- );
144
- this.data = data as any;
145
-
146
- if (this.data._id === "") this.handleNewObject(data as any);
147
- else this.isLoading = false;
148
- }
149
- if (!this.isServer) this.openSockets();
150
- this.generateSettersAndGetters();
151
- }
152
-
153
- protected handleNewObject(data: IsData<T>) {
154
- this.isLoading = true;
155
- if (!this.className)
156
- throw new Error(
157
- "Cannot create a new AutoUpdatedClientClass without a class name."
158
- );
159
- this.socket.emit("new" + this.className, data, (res: ServerResponse<T>) => {
160
- if (!res.success) {
161
- this.isLoading = false;
162
- this.loggers.error("Could not create data on server:", res.message);
163
- this.emitter.dispatchEvent(new Event("loaded" + this.EmitterID));
164
- return;
165
- }
166
- checkForMissingRefs<T>(
167
- res.data as any,
168
- this.properties,
169
- this.classProp as any,
170
- this.autoClassers
171
- );
172
- this.data = res.data as IsData<T>;
173
- this.isLoading = false;
174
- this.emitter.dispatchEvent(new Event("loaded" + this.EmitterID));
175
- });
176
- }
177
-
178
- public get extractedData(): {
179
- [K in keyof InstanceType<T>]: InstanceOf<InstanceType<T>>[K];
180
- } {
181
- const extracted = Object.fromEntries(
182
- Object.entries(
183
- processIsRefProperties(this.data, this.classProp.prototype).newData
184
- ).filter(([k, v]) => typeof v !== "function")
185
- );
186
- return structuredClone(extracted) as any as {
187
- [K in keyof InstanceType<T>]: InstanceOf<InstanceType<T>>[K];
188
- };
189
- }
190
-
191
- public isLoaded(): boolean {
192
- return !this.isLoading;
193
- }
194
-
195
- public async isLoadedAsync(): Promise<boolean> {
196
- await this.loadShit();
197
- return this.isLoading
198
- ? new Promise((resolve) => {
199
- this.emitter.addEventListener("loaded" + this.EmitterID, () => {
200
- resolve(this.isLoading === false);
201
- });
202
- })
203
- : true;
204
- }
205
-
206
- private openSockets() {
207
- this.loggers.debug(`[${this.data._id}] Opening socket listeners`);
208
-
209
- this.socket.on(
210
- "update" + this.className + this.data._id,
211
- async (update: ServerUpdateRequest<T>) => {
212
- await this.handleUpdateRequest(update);
213
- }
214
- );
215
- }
216
- // Example server-side handler
217
- private async handleUpdateRequest(
218
- update: ServerUpdateRequest<T>
219
- ): Promise<ServerResponse<undefined>> {
220
- try {
221
- const path = update.key.split(".");
222
- let dataRef: any = this.data;
223
- for (let i = 0; i < path.length - 1; i++) {
224
- if (!dataRef[path[i]]) dataRef[path[i]] = {};
225
- dataRef = dataRef[path[i]];
226
- }
227
- dataRef[path.at(-1)!] = update.value;
228
-
229
- this.loggers.debug(
230
- `[${this.data._id}] Applied patch ${update.key} set to ${update.value}`
231
- );
232
-
233
- // Return success with the applied patch
234
- return { success: true, data: undefined, message: "" };
235
- } catch (error) {
236
- this.loggers.error(`[${this.data._id}] Error applying patch:`, error);
237
- return {
238
- success: false,
239
- message: "Error applying update: " + (error as Error).message,
240
- };
241
- }
242
- }
243
-
244
- private generateSettersAndGetters() {
245
- for (const key of this.properties) {
246
- if (typeof key !== "string") return;
247
-
248
- const k = key as keyof IsData<T>;
249
- const isRef = getMetadataRecursive(
250
- "isRef",
251
- this.classProp.prototype,
252
- key
253
- );
254
-
255
- Object.defineProperty(this, key, {
256
- get: () => {
257
- if (isRef)
258
- return typeof this.data[k] === "string"
259
- ? this.findReference(this.data[k] as string)
260
- : this.data[k];
261
- else return this.data[k];
262
- },
263
- set: () => {
264
- throw new Error(
265
- `Cannot set ${key} this way, use "setValue" function.`
266
- );
267
- },
268
- enumerable: true,
269
- configurable: true,
270
- });
271
- }
272
- }
273
-
274
- protected findReference(id: string): AutoUpdated<any> | undefined {
275
- for (const classer of Object.values(this.autoClassers)) {
276
- const result = classer.getObject(id);
277
- if (result) return result;
278
- }
279
- }
280
-
281
- public async setValue<K extends Paths<InstanceOf<T>>>(
282
- key: K,
283
- val: PathValueOf<T, K>
284
- ): Promise<boolean> {
285
- let value = val as any;
286
- this.loggers.debug(
287
- `[${(this.data as any)._id}] Setting ${key} to ${value}`
288
- );
289
- try {
290
- if (value instanceof AutoUpdatedClientObject)
291
- value = (value as any).extractedData._id;
292
- const path = key.split(".");
293
- let obj = this.data as any;
294
- let lastClass = this as any;
295
- let lastPath = key as string;
296
- for (let i = 0; i < path.length - 1; i++) {
297
- if (
298
- typeof obj[path[i]] !== "object" ||
299
- obj[path[i]] instanceof ObjectId
300
- ) {
301
- let temp = this.resolveReference(
302
- obj[path[i]].toString()
303
- ) as AutoUpdated<any>;
304
- if (!temp) {
305
- return false;
306
- }
307
- lastClass = temp;
308
- lastPath = path.slice(i + 1).join(".");
309
- return await lastClass.setValue(lastPath, value);
310
- } else obj = obj[path[i]];
311
- }
312
-
313
- if (lastClass !== this || lastPath !== (key as any))
314
- throw new Error("???");
315
-
316
- const success = await this.setValueInternal(lastPath, value);
317
-
318
- if (!success) {
319
- return false;
320
- }
321
- const pathArr = lastPath.split(".");
322
- if (pathArr.length === 1) {
323
- (this.data as any)[key as any] = value;
324
- return true;
325
- }
326
- const pathMinusLast = pathArr.splice(0, 1);
327
- let ref = this as any;
328
- for (const p of pathMinusLast) {
329
- ref = ref[p];
330
- }
331
- ref[pathArr.at(-1)!] = value;
332
- return true;
333
- } catch (error) {
334
- this.loggers.error(error);
335
- return false;
336
- }
337
- }
338
-
339
- protected async setValueInternal(key: string, value: any): Promise<boolean> {
340
- const update: ServerUpdateRequest<T> = this.makeUpdate(key, value);
341
- const promise = new Promise<boolean>((resolve) => {
342
- try {
343
- this.socket.emit(
344
- "update" + this.className + this.data._id,
345
- update,
346
- (res: ServerResponse<T>) => {
347
- resolve(res.success);
348
- }
349
- );
350
- } catch (error) {
351
- this.loggers.error("Error sending update:", error);
352
- resolve(false);
353
- }
354
- });
355
- return promise;
356
- }
357
-
358
- protected makeUpdate(key: string, value: any): any {
359
- const id = this.data._id.toString();
360
- return { _id: id, key, value } as any;
361
- }
362
-
363
- // return a properly typed AutoUpdatedClientClass (or null)
364
- // inside AutoUpdatedClientClass
365
- protected resolveReference(id: string): AutoUpdatedClientObject<any> | null {
366
- if (!this.autoClassers) throw new Error("No autoClassers");
367
- for (const autoClasser of Object.values(this.autoClassers)) {
368
- const data = autoClasser.getObject(id);
369
- if (data) return data;
370
- }
371
- return null;
372
- }
373
-
374
- private async loadForceReferences(
375
- obj: any = this.data,
376
- proto: any = this.classProp.prototype
377
- ) {
378
- const props: string[] = Reflect.getMetadata("props", proto) || [];
379
-
380
- for (const key of props) {
381
- const isRef = Reflect.getMetadata("isRef", proto, key);
382
-
383
- if (isRef) {
384
- await this.handleLoadOnForced(obj, key);
385
- }
386
-
387
- // If the property itself is a nested object, check deeper
388
- if (obj[key] && typeof obj[key] === "object") {
389
- const nestedProto = Object.getPrototypeOf(obj[key]);
390
- if (nestedProto) {
391
- await this.loadForceReferences(obj[key], nestedProto);
392
- }
393
- }
394
- }
395
- }
396
-
397
- private async handleLoadOnForced(obj: any, key: string) {
398
- if (!this.autoClassers) throw new Error("No autoClassers");
399
- const refId = obj[key];
400
- if (refId) {
401
- for (const classer of Object.values(this.autoClassers)) {
402
- const result = classer.getObject(refId);
403
- if (result) {
404
- obj[key] = result;
405
-
406
- // Recursively load refs inside the resolved object
407
- if (typeof result.loadForceReferences === "function") {
408
- await result.loadForceReferences();
409
- }
410
- break;
411
- }
412
- }
413
- }
414
- }
415
- public async destroy(): Promise<void> {
416
- this.socket.emit("delete" + this.className, this.data._id);
417
- this.wipeSelf();
418
- }
419
-
420
- protected wipeSelf() {
421
- for (const key of Object.keys(this.data)) {
422
- delete (this.data as any)[key];
423
- }
424
- this.loggers.info(`[${this.data._id}] ${this.className} object wiped`);
425
- }
426
- }
427
-
428
- export function processIsRefProperties(
429
- instance: any,
430
- target: any,
431
- prefix: string | null = null,
432
- allProps: string[] = [],
433
- newData = {} as any,
434
- loggers?: LoggersType
435
- ) {
436
- const props: string[] = Reflect.getMetadata("props", target) || [];
437
-
438
- for (const prop of props) {
439
- const path = prefix ? `${prefix}.${prop}` : prop;
440
- allProps.push(path);
441
- newData[prop] = instance[prop];
442
- if (Reflect.getMetadata("isRef", target, prop)) {
443
- (loggers ?? console).debug("Changing isRef:", path);
444
- newData[prop] =
445
- typeof instance[prop] === "string"
446
- ? instance[prop]
447
- : instance[prop]?._id;
448
- }
449
-
450
- const type = Reflect.getMetadata("design:type", target, prop);
451
- if (type?.prototype) {
452
- const nestedProps = Reflect.getMetadata("props", type.prototype);
453
- if (nestedProps && instance[prop]) {
454
- newData[prop] = processIsRefProperties(
455
- instance[prop],
456
- type.prototype,
457
- path,
458
- allProps,
459
- undefined,
460
- loggers
461
- ).newData;
462
- }
463
- }
464
- }
465
- return { allProps, newData };
466
- }
467
-
468
- export function getMetadataRecursive(
469
- metaKey: string,
470
- proto: any,
471
- prop: string
472
- ) {
473
- while (proto) {
474
- const meta = Reflect.getMetadata(metaKey, proto, prop);
475
- if (meta !== undefined) return meta;
476
- proto = Object.getPrototypeOf(proto);
477
- }
478
- return undefined;
479
- }
480
-
481
- function checkForMissingRefs<C extends Constructor<any>>(
482
- data: IsData<InstanceType<C>>,
483
- props: any,
484
- classParam: C,
485
- autoClassers: { [key: string]: AutoUpdateManager<any> }
486
- ) {
487
- if (typeof data !== "string") {
488
- const entryKeys = Object.keys(data);
489
- for (const prop of props) {
490
- if (
491
- !entryKeys.includes(prop.toString()) &&
492
- getMetadataRecursive("isRef", classParam.prototype, prop.toString())
493
- ) {
494
- findMissingObjectReference(data, prop, autoClassers);
495
- }
496
- }
497
- }
498
- }
499
- function findMissingObjectReference(
500
- data: any,
501
- prop: any,
502
- autoClassers: { [key: string]: AutoUpdateManager<any> }
503
- ) {
504
- for (const ac of Object.values(autoClassers)) {
505
- for (const obj of ac.objectsAsArray) {
506
- const found = Object.values(obj.extractedData).find((value) =>
507
- Array.isArray(value) ? value.includes(data._id) : value === data._id
508
- );
509
- if (found) {
510
- data[prop] = obj._id;
511
- return;
512
- }
513
- }
514
- }
515
- console.log("a");
516
- }
package/CHANGELOG.md DELETED
@@ -1,53 +0,0 @@
1
- # Changelog
2
-
3
- All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
-
5
- ### [0.2.21](https://github.com/Prestizni-Software/client-dem/compare/v0.2.20...v0.2.21) (2025-11-10)
6
-
7
- ### [0.2.20](https://github.com/Prestizni-Software/client-dem/compare/v0.2.19...v0.2.20) (2025-11-10)
8
-
9
- ### [0.2.19](https://github.com/Prestizni-Software/client-dem/compare/v0.2.18...v0.2.19) (2025-11-10)
10
-
11
- ### [0.2.18](https://github.com/Prestizni-Software/client-dem/compare/v0.2.17...v0.2.18) (2025-11-10)
12
-
13
- ### [0.2.17](https://github.com/Prestizni-Software/client-dem/compare/v0.2.16...v0.2.17) (2025-11-10)
14
-
15
- ### [0.2.16](https://github.com/Prestizni-Software/client-dem/compare/v0.2.15...v0.2.16) (2025-11-10)
16
-
17
- ### [0.2.15](https://github.com/Prestizni-Software/client-dem/compare/v0.2.14...v0.2.15) (2025-11-10)
18
-
19
- ### [0.2.14](https://github.com/Prestizni-Software/client-dem/compare/v0.2.13...v0.2.14) (2025-11-06)
20
-
21
- ### [0.2.13](https://github.com/Prestizni-Software/client-dem/compare/v0.2.12...v0.2.13) (2025-11-06)
22
-
23
- ### [0.2.12](https://github.com/Prestizni-Software/client-dem/compare/v0.2.11...v0.2.12) (2025-11-06)
24
-
25
- ### [0.2.11](https://github.com/Prestizni-Software/client-dem/compare/v0.2.10...v0.2.11) (2025-11-06)
26
-
27
- ### [0.2.10](https://github.com/Prestizni-Software/client-dem/compare/v0.2.9...v0.2.10) (2025-11-06)
28
-
29
- ### [0.2.9](https://github.com/Prestizni-Software/client-dem/compare/v0.2.8...v0.2.9) (2025-11-06)
30
-
31
- ### [0.2.8](https://github.com/Prestizni-Software/client-dem/compare/v0.2.7...v0.2.8) (2025-11-06)
32
-
33
- ### [0.2.7](https://github.com/Prestizni-Software/client-dem/compare/v0.2.6...v0.2.7) (2025-11-06)
34
-
35
- ### [0.2.6](https://github.com/Prestizni-Software/client-dem/compare/v0.2.5...v0.2.6) (2025-11-06)
36
-
37
- ### [0.2.5](https://github.com/Prestizni-Software/client-dem/compare/v0.2.4...v0.2.5) (2025-11-06)
38
-
39
- ### [0.2.4](https://github.com/Prestizni-Software/client-dem/compare/v0.2.3...v0.2.4) (2025-11-06)
40
-
41
- ### [0.2.3](https://github.com/Prestizni-Software/client-dem/compare/v0.2.2...v0.2.3) (2025-11-04)
42
-
43
- ### [0.2.2](https://github.com/Prestizni-Software/client-dem/compare/v0.2.1...v0.2.2) (2025-11-04)
44
-
45
- ### [0.2.1](https://github.com/Prestizni-Software/client-dem/compare/v0.1.27...v0.2.1) (2025-11-04)
46
-
47
- ### [0.1.27](https://github.com/Prestizni-Software/client-dem/compare/v0.1.26...v0.1.27) (2025-11-04)
48
-
49
- ### 0.1.26 (2025-11-04)
50
-
51
- # Changelog
52
-
53
- All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.