entropic-bond 1.57.1 → 1.59.0

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,1885 +1,1219 @@
1
- class I {
2
- constructor() {
3
- this.subscribers = /* @__PURE__ */ new Set();
4
- }
5
- /**
6
- * Subscribes a listener callback function. On every notification,
7
- * the listener callback will be called with an event as a parameter if sent.
8
- *
9
- * @param callback the listener callback
10
- * @returns a function to unsubscribe the listener from further notifications
11
- */
12
- subscribe(e) {
13
- return this.subscribers.add(e), () => this.unsubscribe(e);
14
- }
15
- /**
16
- * Removes the callback from the notification list.
17
- *
18
- * @param listenerCallback the listener callback to remove
19
- */
20
- unsubscribe(e) {
21
- this.subscribers.delete(e);
22
- }
23
- /**
24
- * Notifies all the subscribers with the event passed as parameter.
25
- *
26
- * @param event the event passed to all subscribers.
27
- */
28
- notify(e) {
29
- this.subscribers.forEach((t) => t(e));
30
- }
31
- /**
32
- * Returns the number of subscribers.
33
- *
34
- * @returns the number of subscribers
35
- * @example
36
- * const observable = new Observable<number>()
37
- * observable.subscribe( event => console.log( event ) )
38
- * observable.subscribe( event => console.log( event ) )
39
- * observable.subscribe( event => console.log( event ) )
40
- * console.log( observable.subscribersCount ) // 3
41
- */
42
- get subscribersCount() {
43
- return this.subscribers.size;
44
- }
1
+ //#region src/observable/observable.ts
2
+ var e = class {
3
+ constructor() {
4
+ this.subscribers = /* @__PURE__ */ new Set();
5
+ }
6
+ subscribe(e) {
7
+ return this.subscribers.add(e), () => this.unsubscribe(e);
8
+ }
9
+ unsubscribe(e) {
10
+ this.subscribers.delete(e);
11
+ }
12
+ notify(e) {
13
+ this.subscribers.forEach((t) => t(e));
14
+ }
15
+ get subscribersCount() {
16
+ return this.subscribers.size;
17
+ }
18
+ }, t = [];
19
+ for (let e = 0; e < 256; ++e) t.push((e + 256).toString(16).slice(1));
20
+ function n(e, n = 0) {
21
+ return (t[e[n + 0]] + t[e[n + 1]] + t[e[n + 2]] + t[e[n + 3]] + "-" + t[e[n + 4]] + t[e[n + 5]] + "-" + t[e[n + 6]] + t[e[n + 7]] + "-" + t[e[n + 8]] + t[e[n + 9]] + "-" + t[e[n + 10]] + t[e[n + 11]] + t[e[n + 12]] + t[e[n + 13]] + t[e[n + 14]] + t[e[n + 15]]).toLowerCase();
45
22
  }
46
- const m = [];
47
- for (let i = 0; i < 256; ++i)
48
- m.push((i + 256).toString(16).slice(1));
49
- function Y(i, e = 0) {
50
- return (m[i[e + 0]] + m[i[e + 1]] + m[i[e + 2]] + m[i[e + 3]] + "-" + m[i[e + 4]] + m[i[e + 5]] + "-" + m[i[e + 6]] + m[i[e + 7]] + "-" + m[i[e + 8]] + m[i[e + 9]] + "-" + m[i[e + 10]] + m[i[e + 11]] + m[i[e + 12]] + m[i[e + 13]] + m[i[e + 14]] + m[i[e + 15]]).toLowerCase();
23
+ //#endregion
24
+ //#region node_modules/uuid/dist/rng.js
25
+ var r, i = new Uint8Array(16);
26
+ function a() {
27
+ if (!r) {
28
+ if (typeof crypto > "u" || !crypto.getRandomValues) throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
29
+ r = crypto.getRandomValues.bind(crypto);
30
+ }
31
+ return r(i);
51
32
  }
52
- let F;
53
- const z = new Uint8Array(16);
54
- function J() {
55
- if (!F) {
56
- if (typeof crypto > "u" || !crypto.getRandomValues)
57
- throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
58
- F = crypto.getRandomValues.bind(crypto);
59
- }
60
- return F(z);
33
+ var o = { randomUUID: typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto) };
34
+ //#endregion
35
+ //#region node_modules/uuid/dist/v4.js
36
+ function s(e, t, r) {
37
+ e ||= {};
38
+ let i = e.random ?? e.rng?.() ?? a();
39
+ if (i.length < 16) throw Error("Random bytes length must be >= 16");
40
+ if (i[6] = i[6] & 15 | 64, i[8] = i[8] & 63 | 128, t) {
41
+ if (r ||= 0, r < 0 || r + 16 > t.length) throw RangeError(`UUID byte range ${r}:${r + 15} is out of buffer bounds`);
42
+ for (let e = 0; e < 16; ++e) t[r + e] = i[e];
43
+ return t;
44
+ }
45
+ return n(i);
61
46
  }
62
- const H = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), M = { randomUUID: H };
63
- function Z(i, e, t) {
64
- i = i || {};
65
- const r = i.random ?? i.rng?.() ?? J();
66
- if (r.length < 16)
67
- throw new Error("Random bytes length must be >= 16");
68
- return r[6] = r[6] & 15 | 64, r[8] = r[8] & 63 | 128, Y(r);
47
+ function c(e, t, n) {
48
+ return o.randomUUID && !t && !e ? o.randomUUID() : s(e, t, n);
69
49
  }
70
- function G(i, e, t) {
71
- return M.randomUUID && !i ? M.randomUUID() : Z(i);
50
+ //#endregion
51
+ //#region \0@oxc-project+runtime@0.127.0/helpers/decorate.js
52
+ function l(e, t, n, r) {
53
+ var i = arguments.length, a = i < 3 ? t : r === null ? r = Object.getOwnPropertyDescriptor(t, n) : r, o;
54
+ if (typeof Reflect == "object" && typeof Reflect.decorate == "function") a = Reflect.decorate(e, t, n, r);
55
+ else for (var s = e.length - 1; s >= 0; s--) (o = e[s]) && (a = (i < 3 ? o(a) : i > 3 ? o(t, n, a) : o(t, n)) || a);
56
+ return i > 3 && a && Object.defineProperty(t, n, a), a;
72
57
  }
73
- var K = Object.defineProperty, X = (i, e, t, r) => {
74
- for (var s = void 0, n = i.length - 1, o; n >= 0; n--)
75
- (o = i[n]) && (s = o(e, t, s) || s);
76
- return s && K(e, t, s), s;
77
- }, l;
78
- const W = (l = class {
79
- /**
80
- * Registers a class to be used by the persistence engine.
81
- * @param className the name of the class to be registered
82
- * @param factory the constructor of the registered class
83
- * @param annotation an annotation associated with the class
84
- */
85
- static registerFactory(e, t, r, s = !1) {
86
- this._factoryMap[e] = { factory: t, annotation: r, isLegacy: s };
87
- }
88
- /**
89
- * Returns the constructor of a registered class
90
- * @param className the name of the class to be retrieved
91
- * @returns the constructor of the class
92
- * @throws an error if the class is not registered
93
- * @see registerFactory
94
- * @see registeredClasses
95
- * @see classesExtending
96
- * @see annotations
97
- */
98
- static classFactory(e) {
99
- if (!e) throw new Error("You should provide a class name.");
100
- if (!this._factoryMap[e]) throw new Error(`You should register class ${e} prior to use.`);
101
- return this._factoryMap[e].factory;
102
- }
103
- /**
104
- * Returns the names of all registered classes
105
- * @returns the names of all registered classes
106
- * @see registerFactory
107
- * @see classFactory
108
- */
109
- static registeredClasses() {
110
- return Object.entries(this._factoryMap).filter(([, e]) => !e.isLegacy).map(([e]) => e);
111
- }
112
- /**
113
- * Returns the names of all registered classes, including legacy names
114
- * @returns the names of all registered classes, including legacy names
115
- * @see registerFactory
116
- * @see classFactory
117
- */
118
- static registeredClassesAndLegacyNames() {
119
- return Object.keys(this._factoryMap);
120
- }
121
- /**
122
- * Returns the names of all registered classes that extend a given class
123
- * @param derivedFrom the parent class to be queried
124
- * @returns the names of all registered classes that extend the given class
125
- * @see registerFactory
126
- * @see classFactory
127
- */
128
- static classesExtending(e) {
129
- return Object.entries(this._factoryMap).filter(([, t]) => new t.factory() instanceof e && !t.isLegacy).map(([t]) => t);
130
- }
131
- /**
132
- * Returns the annotation associated with a registered class
133
- * @param className the name of the class to be retrieved
134
- * @returns the annotation associated with the class
135
- * @throws an error if the class is not registered
136
- * @see registerFactory
137
- */
138
- static annotations(e) {
139
- if (e instanceof l ? e = e.className : typeof e == "string" || (e = new e().className), !this._factoryMap[e]) throw new Error(`You should register class ${e} prior to use.`);
140
- return this._factoryMap[e].annotation;
141
- }
142
- /**
143
- * Returns a new instance of Persistent class.
144
- * @param className the initial id of this instance. If not provided, a new id will be generated
145
- */
146
- constructor(e = G()) {
147
- this._id = e;
148
- }
149
- /**
150
- * Gets the class name of this instance.
151
- */
152
- get className() {
153
- return this.__className;
154
- }
155
- /**
156
- * Sets the id of this instance.
157
- * @param value the id of this instance
158
- */
159
- setId(e) {
160
- this._id = e;
161
- }
162
- /**
163
- * Returns the id of this instance.
164
- * @returns the id of this instance
165
- */
166
- get id() {
167
- return this._id;
168
- }
169
- /**
170
- * This method is called by the persistence engine when the instance has been
171
- * just serialized. It is called after the properties are initialized with
172
- * serialized data.
173
- */
174
- afterDeserialize() {
175
- }
176
- /**
177
- * This method is called by the persistence engine before the instance is
178
- * serialized.
179
- */
180
- beforeSerialize() {
181
- }
182
- /**
183
- * Returns an array of the persistent properties of this instance.
184
- * @returns an array of the persistent properties of this instance
185
- */
186
- getPersistentProperties() {
187
- return this._persistentProperties ? this._persistentProperties.map((e) => ({
188
- ...e,
189
- name: e.name.slice(1)
190
- })) : [];
191
- }
192
- /**
193
- * Get the property information of this instance
194
- * @param propName the persistent property name
195
- * @returns the property information
196
- */
197
- getPropInfo(e) {
198
- const t = this.getPersistentProperties().find((r) => r.name === e);
199
- if (!t) throw new Error(`Property "${e}" has not been registered.`);
200
- return t;
201
- }
202
- /**
203
- * Query if the property is required
204
- * To mark a property as required, use the @required decorator
205
- * @param propName the persistent property name
206
- * @returns true if the property is required
207
- * @see required
208
- */
209
- isRequired(e) {
210
- const t = this.getPropInfo(e).validator;
211
- return t != null;
212
- }
213
- /**
214
- * Query if the property value is valid
215
- * Define the validator function using the @required decorator
216
- * @param propName the persistent property name
217
- * @returns true if the property value is valid using the validator function
218
- * passed to the @required decorator
219
- * @see required
220
- */
221
- isPropValueValid(e) {
222
- const t = this.getPropInfo(e);
223
- return t.validator ? t.validator(this[t.name], t, this) : !0;
224
- }
225
- /**
226
- * Copy the persistent properties of the given instance to this instance.
227
- * The property `id` will be ignored.
228
- * Only the properties that are not null or undefined will be copied.
229
- * @param instance the instance to be copied
230
- * @returns this instance
231
- * @see fromObject
232
- * @see toObject
233
- */
234
- clone(e) {
235
- const t = e.toObject();
236
- return delete t.id, this.fromObject(t);
237
- }
238
- /**
239
- * Initializes the persistent properties of this instance from the properties
240
- * of given object.
241
- * @param obj the object to be copied
242
- * @returns this instance
243
- * @see clone
244
- * @see toObject
245
- */
246
- fromObject(e) {
247
- return this.fromObj(e), this.afterDeserialize(), this;
248
- }
249
- fromObj(e) {
250
- return this._persistentProperties ? (this._persistentProperties.forEach((t) => {
251
- const r = this.removeUnderscore(t), s = e[r];
252
- s != null && (this[t.name] = this.fromDeepObject(s));
253
- }), this) : this;
254
- }
255
- /**
256
- * Returns a plain object representation of this instance.
257
- * Only the properties that are not null or undefined will be copied.
258
- * @returns a plain object representation of this instance
259
- * @see fromObject
260
- * @see clone
261
- */
262
- toObject() {
263
- const e = {}, t = this.toObj(e);
264
- return this.pushDocument(e, this.className, t), {
265
- ...t,
266
- __rootCollections: e
267
- };
268
- }
269
- toObj(e) {
270
- if (!this._persistentProperties) return {};
271
- this.beforeSerialize();
272
- const t = {};
273
- if (!this.className) throw new Error(`You should register \`${this.constructor.name || this.toString() || "this"}\` class prior to streaming it.`);
274
- return this._persistentProperties.forEach((r) => {
275
- const s = this[r.name], n = this.removeUnderscore(r);
276
- s != null && (r.isReference ? t[n] = this.toReferenceObj(r, e) : t[n] = this.toDeepObj(s, e), r.searchableArray && (t[l.searchableArrayNameFor(n)] = s.map((o) => o.id)));
277
- }), t.__className = this.className, t;
278
- }
279
- static searchableArrayNameFor(e) {
280
- return `__${e}_searchable`;
281
- }
282
- fromDeepObject(e) {
283
- if (e == null) return e;
284
- if (Array.isArray(e))
285
- return e.map((t) => this.fromDeepObject(t));
286
- if (e.__documentReference) {
287
- const t = e, r = l.createInstance(t);
288
- return r.__documentReference = e.__documentReference, r;
289
- }
290
- if (e.__className)
291
- return l.createInstance(e);
292
- if (typeof e == "object") {
293
- const t = {};
294
- return Object.entries(e).forEach(
295
- ([r, s]) => t[r] = this.fromDeepObject(s)
296
- ), t;
297
- }
298
- return e;
299
- }
300
- toDeepObj(e, t) {
301
- if (e != null) {
302
- if (Array.isArray(e))
303
- return e.map((r) => this.toDeepObj(r, t));
304
- if (e.__documentReference) return e;
305
- if (e instanceof l)
306
- return e.toObj(t);
307
- if (typeof e == "object") {
308
- const r = {};
309
- return Object.entries(e).forEach(
310
- ([s, n]) => r[s] = this.toDeepObj(n, t)
311
- ), r;
312
- }
313
- return e;
314
- }
315
- }
316
- static collectionPath(e, t, r) {
317
- let s;
318
- return typeof t.storeInCollection == "function" ? s = t.storeInCollection(e, t, r) : s = t.storeInCollection ?? e.className, s;
319
- }
320
- toReferenceObj(e, t) {
321
- const r = this[e.name];
322
- return Array.isArray(r) ? r.map((s) => (e.isPureReference || this.pushDocument(t, l.collectionPath(s, e), s), this.buildRefObject(s, l.collectionPath(s, e), e.cachedProps))) : (e.isPureReference || this.pushDocument(t, l.collectionPath(r, e), r), this.buildRefObject(r, l.collectionPath(r, e), e.cachedProps));
323
- }
324
- buildRefObject(e, t, r) {
325
- const s = r?.reduce((n, o) => (e[o] !== void 0 && (n[o] = e[o]), n), {});
326
- return {
327
- id: e.id,
328
- __className: e.className || e.__className,
329
- __documentReference: {
330
- storedInCollection: t
331
- },
332
- ...s
333
- };
334
- }
335
- pushDocument(e, t, r) {
336
- if ("__documentReference" in r && r.__documentReference) return;
337
- e[t] || (e[t] = []);
338
- const s = this.toDeepObj(r, e);
339
- e[t].push(s);
340
- }
341
- removeUnderscore(e) {
342
- return e.name.slice(1);
343
- }
344
- static createReference(e) {
345
- const t = l.createInstance(e);
346
- return t.__documentReference = e.__documentReference || { storedInCollection: t.className }, t;
347
- }
348
- static createInstance(e) {
349
- if (typeof e == "string")
350
- return new (l.classFactory(e))();
351
- try {
352
- return new (l.classFactory(e.__className))().fromObject(e);
353
- } catch (t) {
354
- const r = Object.entries(e).filter(([s, n]) => n != null && typeof n != "function").map(([s, n]) => `${s}: ${n}`).join(`,
355
- `);
356
- throw new Error(`${t}
357
- -----> Class name not found in object:
358
- {
359
- ${r}
360
- }
361
- `);
362
- }
363
- }
364
- static propInfo(e, t) {
365
- return l.createInstance(e).getPropInfo(t);
366
- }
367
- /**
368
- * Return the type of a persistent property.
369
- * Several strategies are used to determine the type:
370
- * - If the typeName is defined in the property info a decorator, it is used
371
- * - If the property value is an array, the type of the first element is used
372
- * - If the property value is a Persistent instance, its class name is used
373
- * - Otherwise, the typeof operator is used to determine the type
374
- * @param propInfo the persistent property info to retrieve the type
375
- * @returns the type of the property or the type of the first element if the property is an array or undefined if cannot be determined
376
- */
377
- static propType(e) {
378
- if (e.typeName) return Array.isArray(e.typeName) ? "undefined[]" : e.typeName ?? "undefined";
379
- const r = l.createInstance(e.ownerClassName())[e.name];
380
- if (Array.isArray(r)) {
381
- if (r.length === 0) return "undefined[]";
382
- const s = r[0];
383
- return s instanceof l ? s.className + "[]" : typeof s + "[]";
384
- } else
385
- return r instanceof l ? r.className : typeof r;
386
- }
387
- /**
388
- * Retrieves a collection of references with the properties that are stored in the reference object
389
- * @returns the references collection
390
- */
391
- static getSystemRegisteredReferencesWithCachedProps() {
392
- return l.registeredClasses().reduce((r, s) => {
393
- const o = l.createInstance(s).getPersistentProperties().filter(
394
- (a) => a.cachedProps
395
- );
396
- return o.length > 0 && (r[s] = o), r;
397
- }, {});
398
- }
399
- }, l._factoryMap = {}, l);
400
- X([
401
- j
402
- ], W.prototype, "_id");
403
- let d = W;
404
- function j(i, e) {
405
- return _()(i, e);
406
- }
407
- function ce(i) {
408
- return function(e, t) {
409
- return _({
410
- storeInCollection: i,
411
- isReference: !0
412
- })(e, t);
413
- };
414
- }
415
- function ue(i, e) {
416
- return _({ isReference: !0 })(i, e);
417
- }
418
- function he(i, e, t, r) {
419
- return function(s, n) {
420
- const o = {
421
- isReference: !0,
422
- storeInCollection: t,
423
- typeName: e,
424
- cachedProps: i,
425
- ownerCollection: r ?? s.className
426
- };
427
- return _(o)(s, n);
428
- };
429
- }
430
- function le(i, e, t) {
431
- return _({ isReference: !0, isPureReference: !0, storeInCollection: t })(i, e);
58
+ //#endregion
59
+ //#region src/persistent/persistent.ts
60
+ var u = class e {
61
+ static registerFactory(e, t, n, r = !1) {
62
+ this._factoryMap[e] = {
63
+ factory: t,
64
+ annotation: n,
65
+ isLegacy: r
66
+ };
67
+ }
68
+ static classFactory(e) {
69
+ if (!e) throw Error("You should provide a class name.");
70
+ if (!this._factoryMap[e]) throw Error(`You should register class ${e} prior to use.`);
71
+ return this._factoryMap[e].factory;
72
+ }
73
+ static registeredClasses() {
74
+ return Object.entries(this._factoryMap).filter(([, e]) => !e.isLegacy).map(([e]) => e);
75
+ }
76
+ static registeredClassesAndLegacyNames() {
77
+ return Object.keys(this._factoryMap);
78
+ }
79
+ static classesExtending(e) {
80
+ return Object.entries(this._factoryMap).filter(([, t]) => new t.factory() instanceof e && !t.isLegacy).map(([e]) => e);
81
+ }
82
+ static isInstanceOf(t, n) {
83
+ let r = e.classFactory(n);
84
+ return t instanceof e ? t instanceof r : e.createInstance(t) instanceof r;
85
+ }
86
+ static annotations(t) {
87
+ if (t instanceof e ? t = t.className : typeof t == "string" || (t = new t().className), !this._factoryMap[t]) throw Error(`You should register class ${t} prior to use.`);
88
+ return this._factoryMap[t].annotation;
89
+ }
90
+ constructor(e = c()) {
91
+ this._id = e;
92
+ }
93
+ get className() {
94
+ return this.__className;
95
+ }
96
+ setId(e) {
97
+ this._id = e;
98
+ }
99
+ get id() {
100
+ return this._id;
101
+ }
102
+ afterDeserialize() {}
103
+ beforeSerialize() {}
104
+ getPersistentProperties() {
105
+ return this._persistentProperties ? this._persistentProperties.map((e) => ({
106
+ ...e,
107
+ name: e.name.slice(1)
108
+ })) : [];
109
+ }
110
+ getPropInfo(e) {
111
+ let t = this.getPersistentProperties().find((t) => t.name === e);
112
+ if (!t) throw Error(`Property "${e}" has not been registered.`);
113
+ return t;
114
+ }
115
+ isRequired(e) {
116
+ return this.getPropInfo(e).validator != null;
117
+ }
118
+ isPropValueValid(e) {
119
+ let t = this.getPropInfo(e);
120
+ return t.validator ? t.validator(this[t.name], t, this) : !0;
121
+ }
122
+ clone(e) {
123
+ let t = e.toObject();
124
+ return delete t.id, this.fromObject(t);
125
+ }
126
+ fromObject(e) {
127
+ return this.fromObj(e), this.afterDeserialize(), this;
128
+ }
129
+ fromObj(e) {
130
+ return this._persistentProperties && this._persistentProperties.forEach((t) => {
131
+ let n = e[this.removeUnderscore(t)];
132
+ n != null && (this[t.name] = this.fromDeepObject(n));
133
+ }), this;
134
+ }
135
+ toObject() {
136
+ let e = {}, t = this.toObj(e);
137
+ return this.pushDocument(e, this.className, t), {
138
+ ...t,
139
+ __rootCollections: e
140
+ };
141
+ }
142
+ toObj(t) {
143
+ if (!this._persistentProperties) return {};
144
+ this.beforeSerialize();
145
+ let n = {};
146
+ if (!this.className) throw Error(`You should register \`${this.constructor.name || this.toString() || "this"}\` class prior to streaming it.`);
147
+ return this._persistentProperties.forEach((r) => {
148
+ let i = this[r.name], a = this.removeUnderscore(r);
149
+ i != null && (r.isReference ? n[a] = this.toReferenceObj(r, t) : n[a] = this.toDeepObj(i, t), r.searchableArray && (n[e.searchableArrayNameFor(a)] = i.map((e) => e.id)));
150
+ }), n.__className = this.className, n;
151
+ }
152
+ static searchableArrayNameFor(e) {
153
+ return `__${e}_searchable`;
154
+ }
155
+ fromDeepObject(t) {
156
+ if (t == null) return t;
157
+ if (Array.isArray(t)) return t.map((e) => this.fromDeepObject(e));
158
+ if (t.__documentReference) {
159
+ let n = t, r = e.createInstance(n);
160
+ return r.__documentReference = t.__documentReference, r;
161
+ }
162
+ if (t.__className) return e.createInstance(t);
163
+ if (typeof t == "object") {
164
+ let e = {};
165
+ return Object.entries(t).forEach(([t, n]) => e[t] = this.fromDeepObject(n)), e;
166
+ }
167
+ return t;
168
+ }
169
+ toDeepObj(t, n) {
170
+ if (t != null) {
171
+ if (Array.isArray(t)) return t.map((e) => this.toDeepObj(e, n));
172
+ if (t.__documentReference) return t;
173
+ if (t instanceof e) return t.toObj(n);
174
+ if (typeof t == "object") {
175
+ let e = {};
176
+ return Object.entries(t).forEach(([t, r]) => e[t] = this.toDeepObj(r, n)), e;
177
+ }
178
+ return t;
179
+ }
180
+ }
181
+ static collectionPath(e, t, n) {
182
+ let r;
183
+ return r = typeof t.storeInCollection == "function" ? t.storeInCollection(e, t, n) : t.storeInCollection ?? e.className, r;
184
+ }
185
+ toReferenceObj(t, n) {
186
+ let r = this[t.name];
187
+ return Array.isArray(r) ? r.map((r) => (t.isPureReference || this.pushDocument(n, e.collectionPath(r, t), r), this.buildRefObject(r, e.collectionPath(r, t), t.cachedProps))) : (t.isPureReference || this.pushDocument(n, e.collectionPath(r, t), r), this.buildRefObject(r, e.collectionPath(r, t), t.cachedProps));
188
+ }
189
+ buildRefObject(e, t, n) {
190
+ let r = n?.reduce((t, n) => (e[n] !== void 0 && (t[n] = e[n]), t), {});
191
+ return {
192
+ id: e.id,
193
+ __className: e.className || e.__className,
194
+ __documentReference: { storedInCollection: t },
195
+ ...r
196
+ };
197
+ }
198
+ pushDocument(e, t, n) {
199
+ if ("__documentReference" in n && n.__documentReference) return;
200
+ e[t] || (e[t] = []);
201
+ let r = this.toDeepObj(n, e);
202
+ e[t].push(r);
203
+ }
204
+ removeUnderscore(e) {
205
+ return e.name.slice(1);
206
+ }
207
+ static createReference(t) {
208
+ let n = e.createInstance(t);
209
+ return n.__documentReference = t.__documentReference || { storedInCollection: n.className }, n;
210
+ }
211
+ static createInstance(t) {
212
+ if (typeof t == "string") return new (e.classFactory(t))();
213
+ try {
214
+ return new (e.classFactory(t.__className))().fromObject(t);
215
+ } catch (e) {
216
+ let n = Object.entries(t).filter(([e, t]) => t != null && typeof t != "function").map(([e, t]) => `${e}: ${t}`).join(",\n ");
217
+ throw Error(`${e}\n-----> Class name not found in object:\n{\n\t ${n} \n}\n`);
218
+ }
219
+ }
220
+ static propInfo(t, n) {
221
+ return e.createInstance(t).getPropInfo(n);
222
+ }
223
+ static propType(t) {
224
+ if (t.typeName) return Array.isArray(t.typeName) ? "undefined[]" : t.typeName ?? "undefined";
225
+ let n = e.createInstance(t.ownerClassName())[t.name];
226
+ if (Array.isArray(n)) {
227
+ if (n.length === 0) return "undefined[]";
228
+ let t = n[0];
229
+ return t instanceof e ? t.className + "[]" : typeof t + "[]";
230
+ } else if (n instanceof e) return n.className;
231
+ else return typeof n;
232
+ }
233
+ static getSystemRegisteredReferencesWithCachedProps() {
234
+ return e.registeredClasses().reduce((t, n) => {
235
+ let r = e.createInstance(n).getPersistentProperties().filter((e) => e.cachedProps);
236
+ return r.length > 0 && (t[n] = r), t;
237
+ }, {});
238
+ }
239
+ static {
240
+ this._factoryMap = {};
241
+ }
242
+ };
243
+ l([d], u.prototype, "_id", void 0);
244
+ function d(e, t) {
245
+ return _()(e, t);
432
246
  }
433
- function de(i, e, t, r) {
434
- return function(s, n) {
435
- return _({
436
- isReference: !0,
437
- isPureReference: !0,
438
- storeInCollection: t,
439
- ownerCollection: r,
440
- typeName: e,
441
- cachedProps: i
442
- })(s, n);
443
- };
247
+ function f(e) {
248
+ return function(t, n) {
249
+ return _({
250
+ storeInCollection: e,
251
+ isReference: !0
252
+ })(t, n);
253
+ };
444
254
  }
445
- function _(i) {
446
- return function(e, t) {
447
- Object.getOwnPropertyDescriptor(e, "_persistentProperties") || (e._persistentProperties ? e._persistentProperties = [...e._persistentProperties] : e._persistentProperties = []);
448
- const r = e._persistentProperties.find((s) => s.name === t);
449
- r ? Object.assign(r, i) : e._persistentProperties.push({
450
- name: t,
451
- ownerClassName: () => e.className,
452
- ...i
453
- });
454
- };
255
+ function p(e, t) {
256
+ return _({ isReference: !0 })(e, t);
455
257
  }
456
- function ee(i, e) {
457
- return (t) => {
458
- d.registerFactory(i, t, e), t.prototype.__className = i;
459
- };
258
+ function m(e, t, n, r) {
259
+ return function(i, a) {
260
+ return _({
261
+ isReference: !0,
262
+ storeInCollection: n,
263
+ typeName: t,
264
+ cachedProps: e,
265
+ ownerCollection: r ?? i.className
266
+ })(i, a);
267
+ };
460
268
  }
461
- function fe(i) {
462
- return (e) => {
463
- d.registerFactory(i, e, void 0, !0);
464
- };
269
+ function h(e, t, n) {
270
+ return _({
271
+ isReference: !0,
272
+ isPureReference: !0,
273
+ storeInCollection: n
274
+ })(e, t);
465
275
  }
466
- function me(i, e) {
467
- return _({ searchableArray: !0 })(i, e);
276
+ function g(e, t, n, r) {
277
+ return function(i, a) {
278
+ return _({
279
+ isReference: !0,
280
+ isPureReference: !0,
281
+ storeInCollection: n,
282
+ ownerCollection: r,
283
+ typeName: t,
284
+ cachedProps: e
285
+ })(i, a);
286
+ };
468
287
  }
469
- function pe(i, e) {
470
- return _({ validator: (t) => t != null })(i, e);
288
+ function _(e) {
289
+ return function(t, n) {
290
+ Object.getOwnPropertyDescriptor(t, "_persistentProperties") || (t._persistentProperties ? t._persistentProperties = [...t._persistentProperties] : t._persistentProperties = []);
291
+ let r = t._persistentProperties.find((e) => e.name === n);
292
+ r ? Object.assign(r, e) : t._persistentProperties.push({
293
+ name: n,
294
+ ownerClassName: () => t.className,
295
+ ...e
296
+ });
297
+ };
471
298
  }
472
- function ge(i = (e) => e != null) {
473
- return function(e, t) {
474
- return _({ validator: i })(e, t);
475
- };
299
+ function v(e, t) {
300
+ return (n) => {
301
+ u.registerFactory(e, n, t), n.prototype.__className = e;
302
+ };
476
303
  }
477
- function _e(i) {
478
- let e;
479
- return typeof i == "function" ? e = new i().className : e = i, function(t, r) {
480
- return _({ typeName: e })(t, r);
481
- };
304
+ function y(e) {
305
+ return (t) => {
306
+ u.registerFactory(e, t, void 0, !0);
307
+ };
482
308
  }
483
- class ye extends d {
484
- constructor() {
485
- super(...arguments), this._onChange = new I();
486
- }
487
- /**
488
- * Subscribes a listener callback function. Every time a property is changed,
489
- * the listener callback will be called with the property change event.
490
- *
491
- * @param listenerCallback the listener callback
492
- * @returns a function to unsubscribe the listener from further notifications
493
- */
494
- onChange(e) {
495
- return this._onChange.subscribe(e);
496
- }
497
- /**
498
- * Removes the listener callback subscrition from the notifications.
499
- *
500
- * @param listenerCallback the listener callback to remove
501
- */
502
- removeOnChange(e) {
503
- this._onChange.unsubscribe(e);
504
- }
505
- /**
506
- * Changes the value of the property and notifies the subscribers about the change.
507
- * This is a helper method that can be used in the property setter.
508
- *
509
- * @param propName the name of the property to be changed
510
- * @param value the new value for the property
511
- * @returns true in case the property has been effectively changed, false otherwise
512
- */
513
- changeProp(e, t) {
514
- const r = "_" + String(e);
515
- return this[r] !== t ? (this[r] = t, this._onChange.notify({ [e]: t }), !0) : !1;
516
- }
517
- /**
518
- * Notifies the subscribers a property or group of properties change.
519
- * This is a helper function to be used when you want to notify property changes.
520
- *
521
- * @param event the event with the changed properties
522
- */
523
- notify(e) {
524
- this._onChange.notify(e);
525
- }
526
- /**
527
- * Inserts a new element in an arbitrary array property of this class and
528
- * fires a change event if successfully inserted. To avoid repeated elements
529
- * to be inserted, you can pass a function that checks for inequity.
530
- *
531
- * @param arrayPropName the name of the array property of this class where you
532
- * want to insert the new element.
533
- * @param element the element to be inserted
534
- * @param isUnique a function that checks for inequity of the two elements
535
- * passed as parameter. If the returned value is true, the
536
- * value will be pushed into the array. When the function is
537
- * not provided, the element will be inserted regardless it is
538
- * already in the array.
539
- * @returns the inserted element or undefined if the element was not inserted.
540
- */
541
- pushAndNotify(e, t, r) {
542
- const s = "_" + String(e);
543
- if (!(r && this[s].find(
544
- (o) => !r(o, t)
545
- )))
546
- return this[s].push(t), this.notify({ [e]: this[e] }), t;
547
- }
548
- /**
549
- * Removes an element from an arbitrary array property of this class and fires
550
- * a change event on operation success.
551
- *
552
- * @param arrayPropName the name of the array property of this class where you
553
- * want to insert the new element.
554
- * @param element the element to be inserted
555
- * @param isEqual a function that checks for equity of the two elements
556
- * passed as parameter. If the returned value is true, the
557
- * value will be removed from the array.
558
- * @returns the removed element or undefined if the element was not removed.
559
- */
560
- removeAndNotify(e, t, r) {
561
- const s = "_" + String(e), n = this[s].length;
562
- if (this[s] = this[s].filter(
563
- (o) => !r(o, t)
564
- ), n !== this[s].length)
565
- return this.notify({ [e]: this[e] }), t;
566
- }
309
+ function b(e, t) {
310
+ return _({ searchableArray: !0 })(e, t);
567
311
  }
568
- const N = class N {
569
- constructor(e, t, r) {
570
- if (r) {
571
- if (!(t instanceof d)) throw new Error(N.error.persistentNeedForSubCollection);
572
- this.collectionName = `${t.className}/${t.id}/${r}`;
573
- } else
574
- this.collectionName = t instanceof d ? t.className : t;
575
- this._stream = e;
576
- }
577
- /**
578
- * Finds an stored object in the database by its id. The field id is provided
579
- * by the Persistent parent class and it is automatically managed. Therefore,
580
- * you should obtain the id by looking at the id field of the object.
581
- *
582
- * @param id the id to look for
583
- * @param instance you can pass an instace that will be filled with the found data
584
- * @returns a promise resolving to an instance with the found data
585
- */
586
- findById(e, t) {
587
- return new Promise((r, s) => {
588
- this._stream.findById(e, this.collectionName).then((n) => {
589
- n ? (t ? t.fromObject(n) : t = d.createInstance(n), r(t)) : r(void 0);
590
- }).catch((n) => s(n));
591
- });
592
- }
593
- /**
594
- * Stores an object in the database
595
- *
596
- * @param instance the object instance to store
597
- * @returns a promise
598
- */
599
- save(e) {
600
- const t = e.toObject();
601
- return this.collectionName !== t.__className && (t.__rootCollections[this.collectionName] = t.__rootCollections[t.__className], delete t.__rootCollections[t.__className]), new Promise((r, s) => {
602
- this._stream.save(t.__rootCollections).then(() => r()).catch((n) => s(n));
603
- });
604
- }
605
- /**
606
- * Removes an element from the database by id
607
- * @param id the id of the element to be removed
608
- * @returns a promise
609
- */
610
- delete(e) {
611
- return new Promise((t, r) => {
612
- this._stream.delete(e, this.collectionName).then(() => t()).catch((s) => r(s));
613
- });
614
- }
615
- /**
616
- * Call find to retrieve a Query object used to define the search conditions
617
- * @returns a Query object
618
- */
619
- find() {
620
- return new te(this);
621
- }
622
- /**
623
- * Define the search conditions. You pass query operations and how the query
624
- * results are returned to the QueryObject
625
- * @param queryObject the QueryObject with the search constrains
626
- * @param objectType Deprecated! - restricts the search to a specific instances of the class type
627
- * @returns a promise resolving to a collection of matched documents
628
- */
629
- query(e = {}, t) {
630
- if (t) {
631
- const r = t instanceof d ? t.className : t;
632
- e.operations || (e.operations = []), e.operations.push(
633
- { property: "__className", operator: "==", value: r }
634
- );
635
- }
636
- return this.mapToInstance(
637
- () => this._stream.find(this.preprocessQueryObject(e), this.collectionName)
638
- );
639
- }
640
- /**
641
- * Get the amount of documents matching the query
642
- * @param queryObject the QueryObject with the search constrains
643
- * @returns a promise resolving to the amount of matched documents
644
- */
645
- count(e) {
646
- return this._stream.count(e, this.collectionName);
647
- }
648
- /**
649
- * Get the next bunch of documents matching the last query
650
- * @param limit the max amount of documents to retrieve. If not set, uses the
651
- * last limit set
652
- * @returns a promise resolving to a collection of matched documents
653
- */
654
- next(e) {
655
- return this.mapToInstance(() => this._stream.next(e));
656
- }
657
- onDocumentChange(e, t) {
658
- return this._stream.onDocumentChange(
659
- this.collectionName,
660
- e,
661
- (r) => t(w.toPersistentDocumentChange(r))
662
- );
663
- }
664
- onCollectionChange(e, t) {
665
- return this._stream.onCollectionChange(
666
- this.preprocessQueryObject(e.getQueryObject()),
667
- this.collectionName,
668
- (r) => t(r.map(
669
- (s) => w.toPersistentDocumentChange(s)
670
- ))
671
- );
672
- }
673
- // /**
674
- // * Get the previous bunch of documents matching the last query
675
- // * @param limit the max amount of documents to retrieve. If not set, uses the
676
- // * last limit set
677
- // * @returns a promise resolving to a collection of matched documents
678
- // */
679
- // prev<U extends T>( limit?: number ): Promise<U[]> {
680
- // return this.mapToInstance( () => this._stream.prev( limit ) )
681
- // }
682
- mapToInstance(e) {
683
- return new Promise((t, r) => {
684
- e().then((s) => t(
685
- s.map((n) => d.createInstance(n))
686
- )).catch((s) => r(s));
687
- });
688
- }
689
- /**
690
- * Normalizes the query object to match the data source requirements.
691
- * Call this method before you do any query operation on the concrete data source
692
- * @param queryObject the query object containing the query operations
693
- * @param operatorConversor a function that converts the query operators to the
694
- * operators supported by the concrete data source
695
- * @returns the normalized query object
696
- */
697
- preprocessQueryObject(e) {
698
- if (Object.values(e).length === 0) return e;
699
- const t = e.operations?.map((r) => {
700
- const s = r.value[0] ?? r.value;
701
- return w.isArrayOperator(r.operator) && s instanceof d ? {
702
- property: d.searchableArrayNameFor(r.property),
703
- operator: r.operator,
704
- value: Array.isArray(r.value) ? r.value.map((n) => n.id) : s.id,
705
- aggregate: r.aggregate
706
- } : {
707
- property: r.property,
708
- operator: r.operator,
709
- value: r.value instanceof d ? { id: r.value.id } : r.value,
710
- aggregate: r.aggregate
711
- };
712
- }) ?? [];
713
- return {
714
- ...e,
715
- operations: t
716
- };
717
- }
718
- };
719
- N.error = {
720
- persistentNeedForSubCollection: "The document parameter for a sub-collection should be a Persistent instace",
721
- invalidQueryOrder: "Cannot add where calls after or calls"
722
- };
723
- let R = N;
724
- class te {
725
- constructor(e) {
726
- this.queryObject = { operations: [] }, this.model = e;
727
- }
728
- /**
729
- * Matches all documents that the value of the property satisfies the condition
730
- * in the operator parameter. Subsequent `where` calls will be operated to the
731
- * previous ones using the AND operator
732
- * @param property the property to be compared
733
- * @param operator the operator to be used in the comparison. The available
734
- * operators are: ==, !=, >, >=, < and <=
735
- * @param value the value to be compared
736
- * @param aggregate if true, the query will use the logical or operator and
737
- * aggregate the results to the previous query
738
- * @returns this Query object to make chained calls possible
739
- * @example
740
- * query.where( 'name', '==', 'John' )
741
- * query.where( 'age', '>', 18 )
742
- * query.where( 'age', '==', 18 ).where( 'name', '==', 'John' )
743
- * @see whereDeepProp
744
- * @see or
745
- * @see orDeepProp
746
- */
747
- where(e, t, r, s) {
748
- if (this.queryObject.operations?.at(-1)?.aggregate && !s) throw new Error(R.error.invalidQueryOrder);
749
- return this.queryObject.operations?.push({
750
- property: e,
751
- operator: t,
752
- value: r,
753
- aggregate: s
754
- }), this;
755
- }
756
- // where2<P extends PropPath<T>>( property: P, operator: QueryOperator, value: PropPathType<T, P> ) {
757
- // if ( property.indexOf( '.' ) > 0 ) return this.whereDeepProp( property, operator, value )
758
- // let val = value instanceof Persistent? { id: value.id } : value
759
- // this.queryObject.operations.push({
760
- // property,
761
- // operator,
762
- // value: val
763
- // })
764
- // return this
765
- // }
766
- /**
767
- * Matches all documents that the value of the deep property satisfies the condition
768
- * in the operator parameter
769
- * @param propertyPath the path to the property to be compared
770
- * @param operator the operator to be used in the comparison. The available
771
- * operators are: ==, !=, >, >=, < and <=
772
- * @param value the value to be compared
773
- * @returns this Query object to make chained calls possible
774
- * @example
775
- * query.whereDeepProp( 'address.street', '==', 'Main Street' )
776
- * @see where
777
- * @see or
778
- * @see orDeepProp
779
- */
780
- whereDeepProp(e, t, r, s) {
781
- if (this.queryObject.operations?.at(-1)?.aggregate && !s) throw new Error(R.error.invalidQueryOrder);
782
- const n = e.split(".");
783
- let o = {}, a = n.length > 1 ? o : r;
784
- return n.slice(1).forEach((u, h) => {
785
- o[u] = h < n.length - 2 ? {} : r, o = o[u];
786
- }), this.queryObject.operations?.push({
787
- property: n[0],
788
- operator: t,
789
- value: a,
790
- aggregate: s
791
- }), this;
792
- }
793
- /**
794
- * Matches all documents that the value of the property satisfies the condition
795
- * in the operator parameter and aggregates the results to the previous query
796
- * @param property the property to be compared
797
- * @param operator the operator to be used in the comparison. The available
798
- * operators are: ==, !=, >, >=, < and <=
799
- * @returns this Query object to make chained calls possible
800
- * @example
801
- * query.where( 'name', '==', 'John' ).and( 'age', '>', 18 )
802
- * @see andDeepProp
803
- * @see where
804
- * @see whereDeepProp
805
- * @see or
806
- * @see orDeepProp
807
- */
808
- and(e, t, r) {
809
- return this.where(e, t, r);
810
- }
811
- /**
812
- * Matches all documents that the value of the deep property satisfies the condition
813
- * in the operator parameter and aggregates the results to the previous query
814
- * @param propertyPath the path to the property to be compared
815
- * @param operator the operator to be used in the comparison. The available
816
- * operators are: ==, !=, >, >=, < and <=
817
- * @param value the value to be compared
818
- * @returns this Query object to make chained calls possible
819
- * @example
820
- * query.whereDeepProp( 'address.street', '==', 'Main Street' ).andDeepProp( 'address.city', '==', 'New York' )
821
- * @see and
822
- * @see where
823
- * @see whereDeepProp
824
- * @see or
825
- * @see orDeepProp
826
- */
827
- andDeepProp(e, t, r) {
828
- return this.whereDeepProp(e, t, r);
829
- }
830
- /**
831
- * Matches all documents that the value of the property satisfies the condition
832
- * in the operator parameter and aggregates the results to the previous query
833
- * @param property the property to be compared
834
- * @param operator the operator to be used in the comparison. The available
835
- * operators are: ==, !=, >, >=, < and <=
836
- * @returns this Query object to make chained calls possible
837
- * @example
838
- * query.or( 'name', '==', 'John' )
839
- * query.or( 'age', '>', 18 )
840
- * @see orDeepProp
841
- * @see where
842
- * @see whereDeepProp
843
- */
844
- or(e, t, r) {
845
- return this.where(e, t, r, !0);
846
- }
847
- /**
848
- * Matches all documents that the value of the deep property satisfies the condition
849
- * in the operator parameter and aggregates the results to the previous query
850
- * @param propertyPath the path to the property to be compared
851
- * @param operator the operator to be used in the comparison. The available
852
- * operators are: ==, !=, >, >=, < and <=
853
- * @param value the value to be compared
854
- * @returns this Query object to make chained calls possible
855
- * @example
856
- * query.orDeepProp( 'address.street', '==', 'Main Street' )
857
- * @see or
858
- * @see where
859
- * @see whereDeepProp
860
- */
861
- orDeepProp(e, t, r) {
862
- return this.whereDeepProp(e, t, r, !0);
863
- }
864
- /**
865
- * Defines a where condition to match documents that are instances of the
866
- * given class
867
- * @param classId the class name or an instance to match
868
- * @returns this Query object to make chained calls possible
869
- * @example
870
- * query.instanceOf( 'Person' )
871
- * query.instanceOf( Person )
872
- * query.instanceOf( Person ).where( 'age', '>', 18 )
873
- */
874
- instanceOf(e) {
875
- const t = e instanceof d ? e.className : e;
876
- return this.queryObject.operations?.push({
877
- property: "__className",
878
- operator: "==",
879
- value: t
880
- }), this;
881
- }
882
- /**
883
- * Executes the query and returns the result
884
- * @param limit the max amount of documents to retrieve. If not set, uses the
885
- * last limit set or all the matching documents
886
- * @returns a promise resolving to a collection of matched documents
887
- * @example
888
- * const namedJohn = await query.where( 'name', '==', 'John' ).get()
889
- */
890
- get(e) {
891
- return e && (this.queryObject.limit = e), this.model.query(this.queryObject);
892
- }
893
- /**
894
- * Limits the number of documents to retrieve
895
- * @param maxDocs the max amount of documents to retrieve
896
- * @returns this Query object to make chained calls possible
897
- * @example
898
- * query.where( 'name', '==', 'John' ).limit( 10 )
899
- */
900
- limit(e) {
901
- return this.queryObject.limit = e, this;
902
- }
903
- /**
904
- * Orders the result set by a property.
905
- * @param propertyName The name of the property to order by
906
- * @param order The sort direction. Possible values are 'asc' and 'desc'
907
- * @returns a chainable query object
908
- * @example
909
- * query.orderBy( 'name', 'asc' )
910
- * query.orderBy( 'age', 'desc' )
911
- */
912
- orderBy(e, t = "asc") {
913
- return this.queryObject.sort = {
914
- propertyName: e,
915
- order: t
916
- }, this;
917
- }
918
- /**
919
- * Orders the result set by a deep property
920
- *
921
- * @param propertyPath The full path of the deep property. It should be
922
- * separated by dots like person.name.firstName.
923
- * @param order The sort direction. Possible values are 'asc' and 'desc'
924
- * @returns a chainable query object
925
- */
926
- orderByDeepProp(e, t = "asc") {
927
- return this.queryObject.sort = {
928
- propertyName: e,
929
- order: t
930
- }, this;
931
- }
932
- /**
933
- * Returns the number of documents that match the query
934
- * @returns a promise resolving to the number of documents that match the query
935
- * @example
936
- * const count = await query.where( 'name', '==', 'John' ).count()
937
- */
938
- count() {
939
- return this.model.count(this.queryObject);
940
- }
941
- getQueryObject() {
942
- return this.queryObject;
943
- }
944
- getQueryModel() {
945
- return this.model;
946
- }
947
- }
948
- const P = class P {
949
- constructor() {
950
- }
951
- /**
952
- * Registers a data source to be used by the store.
953
- * You need to register a data source before using the store.
954
- * @param dataSource the data source to be used by the store
955
- */
956
- static useDataSource(e) {
957
- this._dataSource = e;
958
- }
959
- /**
960
- * The data source currently used by the store
961
- * @returns the data source
962
- */
963
- static get dataSource() {
964
- return P._dataSource;
965
- }
966
- /**
967
- * Retrieves a model for a collection
968
- * @param classId the class name or an instance of the document type stored in the collection
969
- * @returns the model for the collection
970
- */
971
- static getModel(e) {
972
- if (!P._dataSource) throw new Error(this.error.shouldBeRegistered);
973
- return new R(P._dataSource, e);
974
- }
975
- /**
976
- * Retrieves a model for a subcollection
977
- * @param document the persistent object that owns the subcollection
978
- * @param subCollection the name of the subcollection
979
- * @returns the model for the subcollection
980
- */
981
- static getModelForSubCollection(e, t) {
982
- if (!P._dataSource) throw new Error(this.error.shouldBeRegistered);
983
- return new R(P._dataSource, e, t);
984
- }
985
- /**
986
- * Populates property references with actual data from the store.
987
- * It will not retrieve data if the instance is already populated
988
- * @param instance the data to be populated.
989
- * @returns the populated instance
990
- */
991
- static async populate(e) {
992
- if (!e) return;
993
- const t = async (r) => {
994
- const s = r;
995
- if (!s.__documentReference) return r;
996
- const o = await this.getModel(s.__documentReference.storedInCollection).findById(s.id, r);
997
- return o && (o.__documentReference = void 0), o;
998
- };
999
- return Array.isArray(e) ? (await Promise.all(
1000
- e.map((s) => t(s))
1001
- )).filter((s) => s) : t(e);
1002
- }
1003
- /**
1004
- * Checks if an instance is populated
1005
- * @param instance the instance or array of instances to be checked
1006
- * @returns true if the instance is populated
1007
- */
1008
- static isPopulated(e) {
1009
- return Array.isArray(e) ? e.reduce(
1010
- (t, r) => t && r.__documentReference === void 0,
1011
- !0
1012
- ) : e.__documentReference === void 0;
1013
- }
1014
- };
1015
- P.error = { shouldBeRegistered: "You should register a data source before using the data Store." };
1016
- let k = P;
1017
- class L {
1018
- constructor(e) {
1019
- this._resolveCollectionPaths = () => {
1020
- throw new Error("The method collectionsMatchingTemplate has not been implemented in the concrete data source");
1021
- }, this._disabledChangeListeners = /* @__PURE__ */ new Set(), this._collectionsToWatch = {}, e && (this._beforeUpdate = e.beforeUpdateDocument, this._afterUpdate = e.afterUpdateDocument, this._afterDocumentChange = e.afterDocumentChange, this._beforeDocumentChange = e.beforeDocumentChange, this._beforeQueryOwnerCollection = e.beforeQueryOwnerCollection), this.installUpdaters();
1022
- }
1023
- installUpdaters() {
1024
- const e = d.getSystemRegisteredReferencesWithCachedProps();
1025
- this._collectionsToWatch = {}, Object.entries(e).forEach(([t, r]) => {
1026
- r.forEach((s) => {
1027
- if (!s.typeName) return;
1028
- (Array.isArray(s.typeName) ? s.typeName : [s?.typeName ?? t]).map((o) => d.collectionPath(d.createInstance(o), s)).forEach((o) => {
1029
- this._collectionsToWatch[o] || (this._collectionsToWatch[o] = []), this._collectionsToWatch[o].find((u) => u.name === s.name && u.ownerClassName() === s.ownerClassName()) || this._collectionsToWatch[o].push(s);
1030
- });
1031
- });
1032
- });
1033
- }
1034
- /**
1035
- * Set a callback to be executed before updating each document that has a cached prop to update.
1036
- * The callback receives the document to update and the prop that triggered the update as parameters.
1037
- * @param callback The callback to be executed before updating each document that has a cached prop to update.
1038
- */
1039
- set beforeDocumentChange(e) {
1040
- this._beforeDocumentChange = e;
1041
- }
1042
- /**
1043
- * Set a callback to be executed after updating each document that has a cached prop to update.
1044
- * The callback receives the document that was updated and the prop that triggered the update as parameters.
1045
- * @param callback The callback to be executed after updating each document that has a cached prop to update.
1046
- */
1047
- set afterDocumentChange(e) {
1048
- this._afterDocumentChange = e;
1049
- }
1050
- /**
1051
- * Set a callback to be executed before updating each document that has a cached prop to update.
1052
- * The callback receives the document to update and the prop that triggered the update as parameters.
1053
- * @param callback The callback to be executed before updating each document that has a cached prop to update.
1054
- */
1055
- set beforeUpdateDocument(e) {
1056
- this._beforeUpdate = e;
1057
- }
1058
- /**
1059
- * Set a callback to be executed after updating each document that has a cached prop to update.
1060
- * The callback receives the document that was updated and the prop that triggered the update as parameters.
1061
- * @param callback The callback to be executed after updating each document that has a cached prop to update.
1062
- */
1063
- set afterUpdateDocument(e) {
1064
- this._afterUpdate = e;
1065
- }
1066
- set beforeQueryOwnerCollection(e) {
1067
- this._beforeQueryOwnerCollection = e;
1068
- }
1069
- set resolveCollectionPaths(e) {
1070
- this._resolveCollectionPaths = e;
1071
- }
1072
- get collectionsToWatch() {
1073
- return this._collectionsToWatch;
1074
- }
1075
- updateProps(e, t) {
1076
- const r = this._collectionsToWatch[e];
1077
- return r ? this.onDocumentChange(t, r) : Promise.resolve();
1078
- }
1079
- async onDocumentChange(e, t) {
1080
- const r = w.toPersistentDocumentChange(e);
1081
- this._beforeDocumentChange?.(r, t);
1082
- const s = {};
1083
- e.type !== "update" || !r.before || r.after?.id && this._disabledChangeListeners.has(r.after?.id) || (await Promise.all(t.map(async (n) => {
1084
- const o = L.ownerCollectionPath(d.createInstance(n.ownerClassName()), n, r.params), a = await this._resolveCollectionPaths(o);
1085
- await Promise.all(a.map(async (u) => {
1086
- const h = k.getModel(u);
1087
- let c = h.find(), b = !1;
1088
- n.cachedProps?.forEach((f) => {
1089
- const S = r.before[f], O = r.after[f];
1090
- S !== O && (b = !0);
1091
- }), b && (n.searchableArray ? c = c.where(n.name, "contains", r.before) : c = c.where(n.name, "==", r.before)), c = this._beforeQueryOwnerCollection?.(c) ?? c;
1092
- const E = await c.get();
1093
- return s[u] = {
1094
- totalDocumentsToUpdate: E.length,
1095
- updatedDocuments: [],
1096
- documentsToUpdate: E.map((f) => f.name ?? f.id)
1097
- }, Promise.all([
1098
- E.map(async (f) => {
1099
- let S = !1;
1100
- if (n.cachedProps?.forEach((O) => {
1101
- const A = r.before[O], q = r.after[O];
1102
- A !== q && (S = !0);
1103
- }), S) {
1104
- if (n.searchableArray) {
1105
- const O = f[n.name].findIndex((A) => A.id === r.before.id);
1106
- f[n.name][O] = r.after;
1107
- } else
1108
- f[`_${n.name}`] = r.after;
1109
- this._beforeUpdate?.(f, n), this.disableChangeListener(f), await h.save(f), this.enableChangeListener(f), s[u]?.updatedDocuments.push(f.id), this._afterUpdate?.(f, n);
1110
- } else return Promise.resolve();
1111
- })
1112
- ]);
1113
- }));
1114
- })), this._afterDocumentChange?.(s, t));
1115
- }
1116
- disableChangeListener(e) {
1117
- this._disabledChangeListeners.add(e.id);
1118
- }
1119
- enableChangeListener(e) {
1120
- this._disabledChangeListeners.delete(e.id);
1121
- }
1122
- static ownerCollectionPath(e, t, r) {
1123
- let s;
1124
- return typeof t.ownerCollection == "function" ? s = t.ownerCollection(e, t, r) : s = t.ownerCollection ?? e.className, s;
1125
- }
312
+ function x(e, t) {
313
+ return _({ validator: (e) => e != null })(e, t);
1126
314
  }
1127
- class w {
1128
- constructor() {
1129
- this._cachedPropsUpdater = void 0;
1130
- }
1131
- installCachedPropsUpdater(e) {
1132
- return this._cachedPropsUpdater = new L(e), this._cachedPropsUpdater.resolveCollectionPaths = this.resolveCollectionPaths.bind(this), this._cachedPropsUpdater;
1133
- }
1134
- get cachedPropsUpdater() {
1135
- return this._cachedPropsUpdater;
1136
- }
1137
- /**
1138
- * Utility method to convert a query object to a property path query object
1139
- *
1140
- * @param queryObject the query object to be converted
1141
- * @returns a property path query object
1142
- * @example
1143
- * const queryObject = {
1144
- * operations: [{ property: 'name', operator: '==', value: { ancestorName: { father: 'Felipe' }}]
1145
- * }
1146
- * const propPathQueryObject = DataSource.toPropertyPathQueryObject( queryObject )
1147
- * // returned value: [{ property: 'name.ancestorName.father', operator: '==', value: 'Felipe' }]
1148
- */
1149
- static toPropertyPathOperations(e) {
1150
- return e ? e.map((t) => {
1151
- if (w.isArrayOperator(t.operator) && t.value[0] instanceof d)
1152
- return {
1153
- property: d.searchableArrayNameFor(t.property),
1154
- operator: t.operator,
1155
- value: t.value.map((o) => o.id),
1156
- aggregate: t.aggregate
1157
- };
1158
- const [r, s] = this.toPropertyPathValue(t.value);
1159
- return {
1160
- property: `${String(t.property)}${r ? "." + r : ""}`,
1161
- operator: t.operator,
1162
- value: s,
1163
- aggregate: t.aggregate
1164
- };
1165
- }) : [];
1166
- }
1167
- static isArrayOperator(e) {
1168
- return e === "containsAny" || e === "contains";
1169
- }
1170
- static toPersistentDocumentChange(e) {
1171
- return {
1172
- ...e,
1173
- before: e.before && d.createInstance(e.before),
1174
- after: e.after && d.createInstance(e.after)
1175
- };
1176
- }
1177
- static toPropertyPathValue(e) {
1178
- if (typeof e == "object" && !Array.isArray(e)) {
1179
- const t = Object.keys(e)[0], [r, s] = this.toPropertyPathValue(e[t]);
1180
- return [`${t}${r ? "." + r : ""}`, s];
1181
- } else
1182
- return [void 0, e];
1183
- }
1184
- static isStringMatchingTemplate(e, t) {
1185
- const s = e.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&").replace(/\\\$\\\{[^}]+\\\}/g, "([^/]+)").replace(/\\\{[^}]+\\\}/g, "([^/]+)");
1186
- return new RegExp("^" + s + "$").test(t);
1187
- }
1188
- static extractTemplateParams(e, t) {
1189
- const r = [], n = t.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&").replace(/\\\{([^}]+)\\\}/g, (h, c) => (r.push(c), "([^/]+)")), o = new RegExp("^" + n + "$"), a = e.match(o), u = {};
1190
- return a && r.forEach((h, c) => {
1191
- u[h] = a[c + 1];
1192
- }), u;
1193
- }
315
+ function S(e = (e) => e != null) {
316
+ return function(t, n) {
317
+ return _({ validator: e })(t, n);
318
+ };
1194
319
  }
1195
- class be extends w {
1196
- /**
1197
- * @param jsonRawData the JSON object to be used as data store
1198
- */
1199
- constructor(e) {
1200
- super(), this._jsonRawData = {}, this._lastMatchingDocs = [], this._lastLimit = 0, this._cursor = 0, this._simulateDelay = 0, this._pendingPromises = [], this._documentListeners = {}, this._collectionListeners = {}, this._serverCollectionListeners = {}, e && (this._jsonRawData = e);
1201
- }
1202
- /**
1203
- * Set the JSON object to initialize the data store. Use to set the it after
1204
- * the constructor has been called.
1205
- * @param jsonRawData the JSON object to be used as data store
1206
- */
1207
- setDataStore(e) {
1208
- return this._jsonRawData = e, this;
1209
- }
1210
- /**
1211
- * Introduce a delay in the execution of operations to simulate a real data source
1212
- * @param miliSeconds the number of milliseconds to delay the execution of operations
1213
- * @returns a chainable reference to this object
1214
- */
1215
- simulateDelay(e) {
1216
- return this._simulateDelay = e, this;
1217
- }
1218
- findById(e, t) {
1219
- if (this._simulateError?.findById) throw new Error(this._simulateError.findById);
1220
- return this.resolveWithDelay(this._jsonRawData[t]?.[e]);
1221
- }
1222
- save(e) {
1223
- if (this._simulateError?.store) throw new Error(this._simulateError.store);
1224
- return Object.entries(e).forEach(([t, r]) => {
1225
- this._jsonRawData[t] || (this._jsonRawData[t] = {}), r?.forEach((s) => {
1226
- const n = this._jsonRawData[t][s.id];
1227
- this._jsonRawData[t][s.id] = s, this.notifyChange(t, s, n);
1228
- });
1229
- }), this.resolveWithDelay();
1230
- }
1231
- find(e, t) {
1232
- if (this._simulateError?.find) throw new Error(this._simulateError.find);
1233
- const r = Object.values(this._jsonRawData[t] || {});
1234
- return e ? (this._lastLimit = e.limit || 0, this._cursor = 0, this._lastMatchingDocs = Object.entries(e).reduce(
1235
- (s, [n, o]) => this.queryProcessor(s, n, o),
1236
- Object.values(r)
1237
- ), this.resolveWithDelay(this._lastMatchingDocs.slice(0, e.limit))) : this.resolveWithDelay(r);
1238
- }
1239
- delete(e, t) {
1240
- if (this._simulateError?.delete) throw new Error(this._simulateError.delete);
1241
- return delete this._jsonRawData[t][e], this.resolveWithDelay();
1242
- }
1243
- next(e) {
1244
- return e && (this._lastLimit = e), this.incCursor(this._lastLimit), this.resolveWithDelay(this._lastMatchingDocs.slice(this._cursor, this._cursor + this._lastLimit));
1245
- }
1246
- count(e, t) {
1247
- return this.resolveWithDelay(
1248
- Object.keys(this._jsonRawData[t] ?? {}).length
1249
- );
1250
- }
1251
- onCollectionChange(e, t, r) {
1252
- let s = this._collectionListeners[t];
1253
- s || (this._collectionListeners[t] = {}, s = this._collectionListeners[t]);
1254
- const n = (a) => {
1255
- if (!a.after) return;
1256
- const u = [a.after];
1257
- a.before && u.push(a.before);
1258
- const c = this.retrieveQueryDocs(u, e.operations).filter((b, E, f) => E === f.findIndex((S) => S.id === b.id));
1259
- c.length > 0 && r(c.map((b) => ({
1260
- before: a.before,
1261
- after: b,
1262
- type: a.type,
1263
- params: a.params
1264
- })));
1265
- }, o = Math.random().toString(36).substring(2, 9);
1266
- return s[o] = n, () => delete s[o];
1267
- }
1268
- onDocumentChange(e, t, r) {
1269
- let s = this._documentListeners[e];
1270
- s || (this._documentListeners[e] = {}, s = this._documentListeners[e]);
1271
- const n = (a) => {
1272
- a.after && a.after.id === t && r(a);
1273
- }, o = Math.random().toString(36).substring(2, 9);
1274
- return s[o] = n, () => delete s[o];
1275
- }
1276
- /**
1277
- * @returns the raw data store data as a JSON object
1278
- */
1279
- get rawData() {
1280
- return this._jsonRawData;
1281
- }
1282
- /**
1283
- * Wait for all pending promises to be resolved
1284
- * @returns a promise that resolves when all pending promises are resolved
1285
- */
1286
- wait() {
1287
- return Promise.all([...this._pendingPromises]);
1288
- }
1289
- incCursor(e) {
1290
- this._cursor += e, this._cursor > this._lastMatchingDocs.length && (this._cursor = this._lastMatchingDocs.length);
1291
- }
1292
- simulateError(e) {
1293
- return e === void 0 ? (this._simulateError = void 0, this) : (typeof e == "string" ? this._simulateError = {
1294
- store: e,
1295
- find: e,
1296
- findById: e,
1297
- delete: e
1298
- } : this._simulateError = e, this);
1299
- }
1300
- notifyChange(e, t, r) {
1301
- const s = {
1302
- before: r,
1303
- after: t,
1304
- collectionPath: e,
1305
- params: {},
1306
- type: r ? "update" : "create"
1307
- };
1308
- Object.values(this._serverCollectionListeners[e] ?? {}).forEach((n) => n(s)), Object.values(this._documentListeners[e] ?? {}).forEach((n) => n(s)), Object.values(this._collectionListeners[e] ?? {}).forEach((n) => n(s));
1309
- }
1310
- decCursor(e) {
1311
- return this._cursor -= e, this._cursor < 0 ? (this._cursor = 0, !0) : !1;
1312
- }
1313
- queryProcessor(e, t, r) {
1314
- return {
1315
- limit: (n) => e,
1316
- //.slice( 0, limit ),
1317
- operations: (n) => this.retrieveQueryDocs(e, n),
1318
- sort: ({ order: n, propertyName: o }) => e.sort((a, u) => n === "asc" ? this.deepValue(a, o) > this.deepValue(u, o) ? 1 : -1 : this.deepValue(a, o) < this.deepValue(u, o) ? 1 : -1)
1319
- }[t](r);
1320
- }
1321
- retrieveQueryDocs(e, t) {
1322
- return t.reduce((r, s, n) => {
1323
- if (s.aggregate) {
1324
- const o = e.filter((a) => this.isQueryMatched(a, s));
1325
- return n === 0 ? o : r.concat(o);
1326
- } else
1327
- return r.filter((o) => this.isQueryMatched(o, s));
1328
- }, e);
1329
- }
1330
- deepValue(e, t) {
1331
- return t.split(".").reduce((s, n) => s[n], e);
1332
- }
1333
- isQueryMatched(e, t) {
1334
- const r = {
1335
- "==": (h, c) => h === c,
1336
- "!=": (h, c) => h !== c,
1337
- "<": (h, c) => h < c,
1338
- "<=": (h, c) => h <= c,
1339
- ">": (h, c) => h > c,
1340
- ">=": (h, c) => h >= c,
1341
- containsAny: (h, c) => h?.some((b) => c?.includes(b)),
1342
- contains: (h, c) => h?.includes(c)
1343
- }, { property: s, value: n, operator: o } = t, [a, u] = this.retrieveValuesToCompare(e, s, n);
1344
- return r[o](a, u);
1345
- }
1346
- retrieveValuesToCompare(e, t, r) {
1347
- const s = e[t];
1348
- if (s && typeof r == "object" && !Array.isArray(r)) {
1349
- const a = Object.keys(r)[0];
1350
- var [n, o] = this.retrieveValuesToCompare(s, a, r?.[a]);
1351
- }
1352
- return [n || s, o || r];
1353
- }
1354
- resolveWithDelay(e) {
1355
- if (this._simulateDelay <= 0) return Promise.resolve(e);
1356
- const t = new Promise((r) => {
1357
- setTimeout(
1358
- () => r(e),
1359
- this._simulateDelay
1360
- );
1361
- });
1362
- return this._pendingPromises.push(t), t.finally(
1363
- () => this._pendingPromises = this._pendingPromises.filter((r) => r === t)
1364
- ), t;
1365
- }
1366
- resolveCollectionPaths(e) {
1367
- return Promise.resolve(this.collectionsMatchingTemplate(e));
1368
- }
1369
- collectionsMatchingTemplate(e) {
1370
- return Object.keys(this._jsonRawData).filter((t) => w.isStringMatchingTemplate(e, t));
1371
- }
320
+ function C(e) {
321
+ let t;
322
+ return t = typeof e == "function" ? new e().className : e, function(e, n) {
323
+ return _({ typeName: t })(e, n);
324
+ };
1372
325
  }
1373
- const v = class v {
1374
- static registerCloudStorage(e, t) {
1375
- v._cloudStorageFactoryMap[e] = t;
1376
- }
1377
- static createInstance(e) {
1378
- const t = v._cloudStorageFactoryMap[e];
1379
- if (!t)
1380
- throw new Error(`You should register the ${e} cloud storage provider prior to use it`);
1381
- return t();
1382
- }
1383
- get className() {
1384
- return this.__className;
1385
- }
1386
- static useCloudStorage(e) {
1387
- v._defaultCloudStorage = e;
1388
- }
1389
- static get defaultCloudStorage() {
1390
- if (!v._defaultCloudStorage)
1391
- throw new Error("You should define a default cloud storage provider prior to use it");
1392
- return v._defaultCloudStorage;
1393
- }
326
+ //#endregion
327
+ //#region src/persistent/entropic-component.ts
328
+ var w = class extends u {
329
+ constructor(...t) {
330
+ super(...t), this._onChange = new e();
331
+ }
332
+ onChange(e) {
333
+ return this._onChange.subscribe(e);
334
+ }
335
+ removeOnChange(e) {
336
+ this._onChange.unsubscribe(e);
337
+ }
338
+ changeProp(e, t) {
339
+ let n = "_" + String(e);
340
+ return this[n] === t ? !1 : (this[n] = t, this._onChange.notify({ [e]: t }), !0);
341
+ }
342
+ notify(e) {
343
+ this._onChange.notify(e);
344
+ }
345
+ pushAndNotify(e, t, n) {
346
+ let r = "_" + String(e);
347
+ if (!(n && this[r].find((e) => !n(e, t)))) return this[r].push(t), this.notify({ [e]: this[e] }), t;
348
+ }
349
+ removeAndNotify(e, t, n) {
350
+ let r = "_" + String(e), i = this[r].length;
351
+ if (this[r] = this[r].filter((e) => !n(e, t)), i !== this[r].length) return this.notify({ [e]: this[e] }), t;
352
+ }
353
+ }, T = class e {
354
+ static {
355
+ this.error = {
356
+ persistentNeedForSubCollection: "The document parameter for a sub-collection should be a Persistent instace",
357
+ invalidQueryOrder: "Cannot add where calls after or calls"
358
+ };
359
+ }
360
+ constructor(t, n, r) {
361
+ if (r) {
362
+ if (!(n instanceof u)) throw Error(e.error.persistentNeedForSubCollection);
363
+ this.collectionName = `${n.className}/${n.id}/${r}`;
364
+ } else this.collectionName = n instanceof u ? n.className : n;
365
+ this._stream = t;
366
+ }
367
+ findById(e, t) {
368
+ return new Promise((n, r) => {
369
+ this._stream.findById(e, this.collectionName).then((e) => {
370
+ e ? (t ? t.fromObject(e) : t = u.createInstance(e), n(t)) : n(void 0);
371
+ }).catch((e) => r(e));
372
+ });
373
+ }
374
+ save(e) {
375
+ let t = e.toObject();
376
+ return this.collectionName !== t.__className && (t.__rootCollections[this.collectionName] = t.__rootCollections[t.__className], delete t.__rootCollections[t.__className]), new Promise((e, n) => {
377
+ this._stream.save(t.__rootCollections).then(() => e()).catch((e) => n(e));
378
+ });
379
+ }
380
+ delete(e) {
381
+ return new Promise((t, n) => {
382
+ this._stream.delete(e, this.collectionName).then(() => t()).catch((e) => n(e));
383
+ });
384
+ }
385
+ find() {
386
+ return new E(this);
387
+ }
388
+ query(e = {}, t) {
389
+ if (t) {
390
+ let n = t instanceof u ? t.className : t;
391
+ e.operations ||= [], e.operations.push({
392
+ property: "__className",
393
+ operator: "==",
394
+ value: n
395
+ });
396
+ }
397
+ return this.mapToInstance(() => this._stream.find(this.preprocessQueryObject(e), this.collectionName));
398
+ }
399
+ count(e) {
400
+ return this._stream.count(e, this.collectionName);
401
+ }
402
+ next(e) {
403
+ return this.mapToInstance(() => this._stream.next(e));
404
+ }
405
+ onDocumentChange(e, t) {
406
+ return this._stream.onDocumentChange(this.collectionName, e, (e) => t(k.toPersistentDocumentChange(e)));
407
+ }
408
+ onCollectionChange(e, t) {
409
+ return this._stream.onCollectionChange(this.preprocessQueryObject(e.getQueryObject()), this.collectionName, (e) => t(e.map((e) => k.toPersistentDocumentChange(e))));
410
+ }
411
+ onCollectionTemplateChange(e, t) {
412
+ return this._stream.onDocumentTemplateChange(e, (e) => t(k.toPersistentDocumentChange(e)));
413
+ }
414
+ mapToInstance(e) {
415
+ return new Promise((t, n) => {
416
+ e().then((e) => t(e.map((e) => u.createInstance(e)))).catch((e) => n(e));
417
+ });
418
+ }
419
+ preprocessQueryObject(e) {
420
+ if (Object.values(e).length === 0) return e;
421
+ let t = e.operations?.map((e) => {
422
+ let t = e.value[0] ?? e.value;
423
+ return k.isArrayOperator(e.operator) && t instanceof u ? {
424
+ property: u.searchableArrayNameFor(e.property),
425
+ operator: e.operator,
426
+ value: Array.isArray(e.value) ? e.value.map((e) => e.id) : t.id,
427
+ aggregate: e.aggregate
428
+ } : {
429
+ property: e.property,
430
+ operator: e.operator,
431
+ value: e.value instanceof u ? { id: e.value.id } : e.value,
432
+ aggregate: e.aggregate
433
+ };
434
+ }) ?? [];
435
+ return {
436
+ ...e,
437
+ operations: t
438
+ };
439
+ }
440
+ }, E = class {
441
+ constructor(e) {
442
+ this.queryObject = { operations: [] }, this.model = e;
443
+ }
444
+ where(e, t, n, r) {
445
+ if (this.queryObject.operations?.at(-1)?.aggregate && !r) throw Error(T.error.invalidQueryOrder);
446
+ return this.queryObject.operations?.push({
447
+ property: e,
448
+ operator: t,
449
+ value: n,
450
+ aggregate: r
451
+ }), this;
452
+ }
453
+ whereDeepProp(e, t, n, r) {
454
+ if (this.queryObject.operations?.at(-1)?.aggregate && !r) throw Error(T.error.invalidQueryOrder);
455
+ let i = e.split("."), a = {}, o = i.length > 1 ? a : n;
456
+ return i.slice(1).forEach((e, t) => {
457
+ a[e] = t < i.length - 2 ? {} : n, a = a[e];
458
+ }), this.queryObject.operations?.push({
459
+ property: i[0],
460
+ operator: t,
461
+ value: o,
462
+ aggregate: r
463
+ }), this;
464
+ }
465
+ and(e, t, n) {
466
+ return this.where(e, t, n);
467
+ }
468
+ andDeepProp(e, t, n) {
469
+ return this.whereDeepProp(e, t, n);
470
+ }
471
+ or(e, t, n) {
472
+ return this.where(e, t, n, !0);
473
+ }
474
+ orDeepProp(e, t, n) {
475
+ return this.whereDeepProp(e, t, n, !0);
476
+ }
477
+ instanceOf(e) {
478
+ let t = e instanceof u ? e.className : e;
479
+ return this.queryObject.operations?.push({
480
+ property: "__className",
481
+ operator: "==",
482
+ value: t
483
+ }), this;
484
+ }
485
+ get(e) {
486
+ return e && (this.queryObject.limit = e), this.model.query(this.queryObject);
487
+ }
488
+ limit(e) {
489
+ return this.queryObject.limit = e, this;
490
+ }
491
+ orderBy(e, t = "asc") {
492
+ return this.queryObject.sort = {
493
+ propertyName: e,
494
+ order: t
495
+ }, this;
496
+ }
497
+ orderByDeepProp(e, t = "asc") {
498
+ return this.queryObject.sort = {
499
+ propertyName: e,
500
+ order: t
501
+ }, this;
502
+ }
503
+ count() {
504
+ return this.model.count(this.queryObject);
505
+ }
506
+ getQueryObject() {
507
+ return this.queryObject;
508
+ }
509
+ getQueryModel() {
510
+ return this.model;
511
+ }
512
+ }, D = class e {
513
+ constructor() {}
514
+ static {
515
+ this.error = { shouldBeRegistered: "You should register a data source before using the data Store." };
516
+ }
517
+ static useDataSource(e) {
518
+ this._dataSource = e;
519
+ }
520
+ static get dataSource() {
521
+ return e._dataSource;
522
+ }
523
+ static getModel(t) {
524
+ if (!e._dataSource) throw Error(this.error.shouldBeRegistered);
525
+ return new T(e._dataSource, t);
526
+ }
527
+ static getModelForSubCollection(t, n) {
528
+ if (!e._dataSource) throw Error(this.error.shouldBeRegistered);
529
+ return new T(e._dataSource, t, n);
530
+ }
531
+ static async populate(e) {
532
+ if (!e) return;
533
+ let t = async (e) => {
534
+ let t = e;
535
+ if (!t.__documentReference) return e;
536
+ let n = await this.getModel(t.__documentReference.storedInCollection).findById(t.id, e);
537
+ return n && (n.__documentReference = void 0), n;
538
+ };
539
+ return Array.isArray(e) ? (await Promise.all(e.map((e) => t(e)))).filter((e) => e) : t(e);
540
+ }
541
+ static isPopulated(e) {
542
+ return Array.isArray(e) ? e.reduce((e, t) => e && t.__documentReference === void 0, !0) : e.__documentReference === void 0;
543
+ }
544
+ }, O = class e {
545
+ constructor(e) {
546
+ this._resolveCollectionPaths = () => {
547
+ throw Error("The method collectionsMatchingTemplate has not been implemented in the concrete data source");
548
+ }, this._disabledChangeListeners = /* @__PURE__ */ new Set(), this._collectionsToWatch = {}, e && (this._beforeUpdate = e.beforeUpdateDocument, this._afterUpdate = e.afterUpdateDocument, this._afterDocumentChange = e.afterDocumentChange, this._beforeDocumentChange = e.beforeDocumentChange, this._beforeQueryOwnerCollection = e.beforeQueryOwnerCollection), this.installUpdaters();
549
+ }
550
+ installUpdaters() {
551
+ let e = u.getSystemRegisteredReferencesWithCachedProps();
552
+ this._collectionsToWatch = {}, Object.entries(e).forEach(([e, t]) => {
553
+ t.forEach((t) => {
554
+ t.typeName && (Array.isArray(t.typeName) ? t.typeName : [t?.typeName ?? e]).map((e) => u.collectionPath(u.createInstance(e), t)).forEach((e) => {
555
+ this._collectionsToWatch[e] || (this._collectionsToWatch[e] = []), this._collectionsToWatch[e].find((e) => e.name === t.name && e.ownerClassName() === t.ownerClassName()) || this._collectionsToWatch[e].push(t);
556
+ });
557
+ });
558
+ });
559
+ }
560
+ set beforeDocumentChange(e) {
561
+ this._beforeDocumentChange = e;
562
+ }
563
+ set afterDocumentChange(e) {
564
+ this._afterDocumentChange = e;
565
+ }
566
+ set beforeUpdateDocument(e) {
567
+ this._beforeUpdate = e;
568
+ }
569
+ set afterUpdateDocument(e) {
570
+ this._afterUpdate = e;
571
+ }
572
+ set beforeQueryOwnerCollection(e) {
573
+ this._beforeQueryOwnerCollection = e;
574
+ }
575
+ set resolveCollectionPaths(e) {
576
+ this._resolveCollectionPaths = e;
577
+ }
578
+ get collectionsToWatch() {
579
+ return this._collectionsToWatch;
580
+ }
581
+ updateProps(e, t) {
582
+ let n = this._collectionsToWatch[e];
583
+ return n ? this.onDocumentChange(t, n) : Promise.resolve();
584
+ }
585
+ async onDocumentChange(t, n) {
586
+ let r = k.toPersistentDocumentChange(t);
587
+ this._beforeDocumentChange?.(r, n);
588
+ let i = {};
589
+ t.type !== "update" || !r.before || r.after?.id && this._disabledChangeListeners.has(r.after?.id) || (await Promise.all(n.map(async (t) => {
590
+ let n = e.ownerCollectionPath(u.createInstance(t.ownerClassName()), t, r.params), a = await this._resolveCollectionPaths(n);
591
+ await Promise.all(a.map(async (e) => {
592
+ let n = D.getModel(e), a = n.find(), o = !1;
593
+ t.cachedProps?.forEach((e) => {
594
+ r.before[e] !== r.after[e] && (o = !0);
595
+ }), o && (a = t.searchableArray ? a.where(t.name, "contains", r.before) : a.where(t.name, "==", r.before)), a = this._beforeQueryOwnerCollection?.(a) ?? a;
596
+ let s = await a.get();
597
+ return i[e] = {
598
+ totalDocumentsToUpdate: s.length,
599
+ updatedDocuments: [],
600
+ documentsToUpdate: s.map((e) => e.name ?? e.id)
601
+ }, Promise.all([s.map(async (a) => {
602
+ let o = !1;
603
+ if (t.cachedProps?.forEach((e) => {
604
+ r.before[e] !== r.after[e] && (o = !0);
605
+ }), o) {
606
+ if (t.searchableArray) {
607
+ let e = a[t.name].findIndex((e) => e.id === r.before.id);
608
+ a[t.name][e] = r.after;
609
+ } else a[`_${t.name}`] = r.after;
610
+ this._beforeUpdate?.(a, t), this.disableChangeListener(a), await n.save(a), this.enableChangeListener(a), i[e]?.updatedDocuments.push(a.id), this._afterUpdate?.(a, t);
611
+ } else return Promise.resolve();
612
+ })]);
613
+ }));
614
+ })), this._afterDocumentChange?.(i, n));
615
+ }
616
+ disableChangeListener(e) {
617
+ this._disabledChangeListeners.add(e.id);
618
+ }
619
+ enableChangeListener(e) {
620
+ this._disabledChangeListeners.delete(e.id);
621
+ }
622
+ static ownerCollectionPath(e, t, n) {
623
+ let r;
624
+ return r = typeof t.ownerCollection == "function" ? t.ownerCollection(e, t, n) : t.ownerCollection ?? e.className, r;
625
+ }
626
+ }, k = class e {
627
+ constructor() {
628
+ this._cachedPropsUpdater = void 0;
629
+ }
630
+ installCachedPropsUpdater(e) {
631
+ return this._cachedPropsUpdater = new O(e), this._cachedPropsUpdater.resolveCollectionPaths = this.resolveCollectionPaths.bind(this), this._cachedPropsUpdater;
632
+ }
633
+ get cachedPropsUpdater() {
634
+ return this._cachedPropsUpdater;
635
+ }
636
+ static toPropertyPathOperations(t) {
637
+ return t ? t.map((t) => {
638
+ if (e.isArrayOperator(t.operator) && t.value[0] instanceof u) return {
639
+ property: u.searchableArrayNameFor(t.property),
640
+ operator: t.operator,
641
+ value: t.value.map((e) => e.id),
642
+ aggregate: t.aggregate
643
+ };
644
+ let [n, r] = this.toPropertyPathValue(t.value);
645
+ return {
646
+ property: `${String(t.property)}${n ? "." + n : ""}`,
647
+ operator: t.operator,
648
+ value: r,
649
+ aggregate: t.aggregate
650
+ };
651
+ }) : [];
652
+ }
653
+ static isArrayOperator(e) {
654
+ return e === "containsAny" || e === "contains";
655
+ }
656
+ static toPersistentDocumentChange(e) {
657
+ return {
658
+ ...e,
659
+ before: e.before && u.createInstance(e.before),
660
+ after: e.after && u.createInstance(e.after)
661
+ };
662
+ }
663
+ static toPropertyPathValue(e) {
664
+ if (typeof e == "object" && !Array.isArray(e)) {
665
+ let t = Object.keys(e)[0], [n, r] = this.toPropertyPathValue(e[t]);
666
+ return [`${t}${n ? "." + n : ""}`, r];
667
+ } else return [void 0, e];
668
+ }
669
+ static isStringMatchingTemplate(e, t) {
670
+ let n = e.split("/"), r = t.split("/");
671
+ if (r.length > n.length) return !1;
672
+ for (let e = 0; e < r.length; e++) {
673
+ let t = n[e], i = r[e];
674
+ if (!(t.startsWith("{") && t.endsWith("}") || t.startsWith("${") && t.endsWith("}")) && t !== i) return !1;
675
+ }
676
+ for (let e = r.length; e < n.length; e++) {
677
+ let t = n[e];
678
+ if (!(t.startsWith("{") && t.endsWith("}") || t.startsWith("${") && t.endsWith("}"))) return !1;
679
+ }
680
+ return !0;
681
+ }
682
+ static extractTemplateParams(e, t) {
683
+ let n = t.split("/"), r = e.split("/"), i = {};
684
+ if (r.length > n.length) return i;
685
+ for (let e = 0; e < r.length; e++) {
686
+ let t = n[e], a = r[e];
687
+ if (t.startsWith("{") && t.endsWith("}")) i[t.slice(1, -1)] = a;
688
+ else if (t.startsWith("${") && t.endsWith("}")) i[t.slice(2, -1)] = a;
689
+ else if (t !== a) return {};
690
+ }
691
+ for (let e = r.length; e < n.length; e++) {
692
+ let t = n[e];
693
+ if (!(t.startsWith("{") && t.endsWith("}") || t.startsWith("${") && t.endsWith("}"))) return {};
694
+ }
695
+ return i;
696
+ }
697
+ }, A = class extends k {
698
+ constructor(e) {
699
+ super(), this._jsonRawData = {}, this._lastMatchingDocs = [], this._lastLimit = 0, this._cursor = 0, this._simulateDelay = 0, this._pendingPromises = [], this._documentListeners = {}, this._collectionListeners = {}, e && (this._jsonRawData = e);
700
+ }
701
+ setDataStore(e) {
702
+ return this._jsonRawData = e, this;
703
+ }
704
+ simulateDelay(e) {
705
+ return this._simulateDelay = e, this;
706
+ }
707
+ findById(e, t) {
708
+ if (this._simulateError?.findById) throw Error(this._simulateError.findById);
709
+ return this.resolveWithDelay(this._jsonRawData[t]?.[e]);
710
+ }
711
+ save(e) {
712
+ if (this._simulateError?.store) throw Error(this._simulateError.store);
713
+ return Object.entries(e).forEach(([e, t]) => {
714
+ this._jsonRawData[e] || (this._jsonRawData[e] = {}), t?.forEach((t) => {
715
+ let n = this._jsonRawData[e][t.id];
716
+ this._jsonRawData[e][t.id] = t, this.notifyChange(e, t, n);
717
+ });
718
+ }), this.resolveWithDelay();
719
+ }
720
+ find(e, t) {
721
+ if (this._simulateError?.find) throw Error(this._simulateError.find);
722
+ let n = Object.values(this._jsonRawData[t] || {});
723
+ return e ? (this._lastLimit = e.limit || 0, this._cursor = 0, this._lastMatchingDocs = Object.entries(e).reduce((e, [t, n]) => this.queryProcessor(e, t, n), Object.values(n)), this.resolveWithDelay(this._lastMatchingDocs.slice(0, e.limit))) : this.resolveWithDelay(n);
724
+ }
725
+ delete(e, t) {
726
+ if (this._simulateError?.delete) throw Error(this._simulateError.delete);
727
+ return delete this._jsonRawData[t][e], this.resolveWithDelay();
728
+ }
729
+ next(e) {
730
+ return e && (this._lastLimit = e), this.incCursor(this._lastLimit), this.resolveWithDelay(this._lastMatchingDocs.slice(this._cursor, this._cursor + this._lastLimit));
731
+ }
732
+ count(e, t) {
733
+ return this.resolveWithDelay(Object.keys(this._jsonRawData[t] ?? {}).length);
734
+ }
735
+ onCollectionChange(e, t, n) {
736
+ let r = this._collectionListeners[t];
737
+ r ||= (this._collectionListeners[t] = {}, this._collectionListeners[t]);
738
+ let i = (t) => {
739
+ if (!t.after) return;
740
+ let r = [t.after];
741
+ t.before && r.push(t.before);
742
+ let i = this.retrieveQueryDocs(r, e.operations).filter((e, t, n) => t === n.findIndex((t) => t.id === e.id));
743
+ i.length > 0 && n(i.map((e) => ({
744
+ before: t.before,
745
+ after: e,
746
+ type: t.type,
747
+ params: t.params
748
+ })));
749
+ }, a = Math.random().toString(36).substring(2, 9);
750
+ return r[a] = i, () => delete r[a];
751
+ }
752
+ onDocumentChange(e, t, n) {
753
+ let r = this._documentListeners[e];
754
+ r ||= (this._documentListeners[e] = {}, this._documentListeners[e]);
755
+ let i = (e) => {
756
+ e.after && e.after.id === t && n(e);
757
+ }, a = Math.random().toString(36).substring(2, 9);
758
+ return r[a] = i, () => delete r[a];
759
+ }
760
+ onDocumentTemplateChange(e, t) {
761
+ let n = this.collectionsMatchingTemplate(e), r = [];
762
+ return n.forEach((n) => {
763
+ let i = this._documentListeners[n];
764
+ i ||= (this._documentListeners[n] = {}, this._documentListeners[n]);
765
+ let a = (r) => {
766
+ r.params = k.extractTemplateParams(n, e), t(r);
767
+ }, o = Math.random().toString(36).substring(2, 9);
768
+ i[o] = a, r.push(() => delete i[o]);
769
+ }), () => r.forEach((e) => e());
770
+ }
771
+ get rawData() {
772
+ return this._jsonRawData;
773
+ }
774
+ wait() {
775
+ return Promise.all([...this._pendingPromises]);
776
+ }
777
+ incCursor(e) {
778
+ this._cursor += e, this._cursor > this._lastMatchingDocs.length && (this._cursor = this._lastMatchingDocs.length);
779
+ }
780
+ simulateError(e) {
781
+ return e === void 0 ? (this._simulateError = void 0, this) : (typeof e == "string" ? this._simulateError = {
782
+ store: e,
783
+ find: e,
784
+ findById: e,
785
+ delete: e
786
+ } : this._simulateError = e, this);
787
+ }
788
+ notifyChange(e, t, n) {
789
+ let r = {
790
+ before: n,
791
+ after: t,
792
+ collectionPath: e,
793
+ params: {},
794
+ type: n ? "update" : "create"
795
+ };
796
+ Object.values(this._documentListeners[e] ?? {}).forEach((e) => e(r)), Object.values(this._collectionListeners[e] ?? {}).forEach((e) => e(r));
797
+ }
798
+ decCursor(e) {
799
+ return this._cursor -= e, this._cursor < 0 ? (this._cursor = 0, !0) : !1;
800
+ }
801
+ queryProcessor(e, t, n) {
802
+ return {
803
+ limit: (t) => e,
804
+ operations: (t) => this.retrieveQueryDocs(e, t),
805
+ sort: ({ order: t, propertyName: n }) => e.sort((e, r) => t === "asc" ? this.deepValue(e, n) > this.deepValue(r, n) ? 1 : -1 : this.deepValue(e, n) < this.deepValue(r, n) ? 1 : -1)
806
+ }[t](n);
807
+ }
808
+ retrieveQueryDocs(e, t) {
809
+ return t.reduce((t, n, r) => {
810
+ if (n.aggregate) {
811
+ let i = e.filter((e) => this.isQueryMatched(e, n));
812
+ return r === 0 ? i : t.concat(i);
813
+ } else return t.filter((e) => this.isQueryMatched(e, n));
814
+ }, e);
815
+ }
816
+ deepValue(e, t) {
817
+ return t.split(".").reduce((e, t) => e[t], e);
818
+ }
819
+ isQueryMatched(e, t) {
820
+ let n = {
821
+ "==": (e, t) => e === t,
822
+ "!=": (e, t) => e !== t,
823
+ "<": (e, t) => e < t,
824
+ "<=": (e, t) => e <= t,
825
+ ">": (e, t) => e > t,
826
+ ">=": (e, t) => e >= t,
827
+ containsAny: (e, t) => e?.some((e) => t?.includes(e)),
828
+ contains: (e, t) => e?.includes(t)
829
+ }, { property: r, value: i, operator: a } = t, [o, s] = this.retrieveValuesToCompare(e, r, i);
830
+ return n[a](o, s);
831
+ }
832
+ retrieveValuesToCompare(e, t, n) {
833
+ let r = e[t];
834
+ if (r && typeof n == "object" && !Array.isArray(n)) {
835
+ let e = Object.keys(n)[0];
836
+ var [i, a] = this.retrieveValuesToCompare(r, e, n?.[e]);
837
+ }
838
+ return [i || r, a || n];
839
+ }
840
+ resolveWithDelay(e) {
841
+ if (this._simulateDelay <= 0) return Promise.resolve(e);
842
+ let t = new Promise((t) => {
843
+ setTimeout(() => t(e), this._simulateDelay);
844
+ });
845
+ return this._pendingPromises.push(t), t.finally(() => this._pendingPromises = this._pendingPromises.filter((e) => e === t)), t;
846
+ }
847
+ resolveCollectionPaths(e) {
848
+ return Promise.resolve(this.collectionsMatchingTemplate(e));
849
+ }
850
+ collectionsMatchingTemplate(e) {
851
+ return Object.keys(this._jsonRawData).filter((t) => k.isStringMatchingTemplate(e, t));
852
+ }
853
+ }, j = class e {
854
+ static registerCloudStorage(t, n) {
855
+ e._cloudStorageFactoryMap[t] = n;
856
+ }
857
+ static createInstance(t) {
858
+ let n = e._cloudStorageFactoryMap[t];
859
+ if (!n) throw Error(`You should register the ${t} cloud storage provider prior to use it`);
860
+ return n();
861
+ }
862
+ get className() {
863
+ return this.__className;
864
+ }
865
+ static useCloudStorage(t) {
866
+ e._defaultCloudStorage = t;
867
+ }
868
+ static get defaultCloudStorage() {
869
+ if (!e._defaultCloudStorage) throw Error("You should define a default cloud storage provider prior to use it");
870
+ return e._defaultCloudStorage;
871
+ }
872
+ static {
873
+ this._cloudStorageFactoryMap = {};
874
+ }
1394
875
  };
1395
- v._cloudStorageFactoryMap = {};
1396
- let C = v;
1397
- function re(i, e) {
1398
- return C.registerCloudStorage(i, e), (t) => {
1399
- t.prototype.__className = i;
1400
- };
876
+ function M(e, t) {
877
+ return j.registerCloudStorage(e, t), (t) => {
878
+ t.prototype.__className = e;
879
+ };
1401
880
  }
1402
- var se = Object.getOwnPropertyDescriptor, ie = (i, e, t, r) => {
1403
- for (var s = r > 1 ? void 0 : r ? se(e, t) : e, n = i.length - 1, o; n >= 0; n--)
1404
- (o = i[n]) && (s = o(s) || s);
1405
- return s;
881
+ //#endregion
882
+ //#region src/cloud-storage/mock-cloud-storage.ts
883
+ var N = class extends j {
884
+ constructor(e = "") {
885
+ super(), this._simulateDelay = 0, this._pendingPromises = [], this.mockFileSystem = {}, this._pathToMockFiles = e;
886
+ }
887
+ simulateDelay(e) {
888
+ return this._simulateDelay = e, this;
889
+ }
890
+ resolveWithDelay(e) {
891
+ if (this._simulateDelay <= 0) return Promise.resolve(e);
892
+ let t = new Promise((t) => {
893
+ setTimeout(() => t(e), this._simulateDelay);
894
+ });
895
+ return this._pendingPromises.push(t), t.finally(() => this._pendingPromises = this._pendingPromises.filter((e) => e === t)), t;
896
+ }
897
+ save(e, t) {
898
+ let n = e;
899
+ this._onProgress && this._onProgress(0, 100), this.mockFileSystem[e] = JSON.stringify(t), this._onProgress && this._onProgress(100, 100);
900
+ let r = t instanceof File ? t.name : n;
901
+ return this.resolveWithDelay(r);
902
+ }
903
+ uploadControl() {
904
+ return {
905
+ resume: () => {},
906
+ pause: () => {},
907
+ cancel: () => {},
908
+ onProgress: (e) => this._onProgress = e
909
+ };
910
+ }
911
+ getUrl(e) {
912
+ return Promise.resolve(this._pathToMockFiles + e);
913
+ }
914
+ delete(e) {
915
+ return delete this.mockFileSystem[e], this.resolveWithDelay();
916
+ }
1406
917
  };
1407
- let T = class extends C {
1408
- constructor(i = "") {
1409
- super(), this._simulateDelay = 0, this._pendingPromises = [], this.mockFileSystem = {}, this._pathToMockFiles = i;
1410
- }
1411
- /**
1412
- * Introduce a delay in the execution of operations to simulate a real data source
1413
- * @param miliSeconds the number of milliseconds to delay the execution of operations
1414
- * @returns a chainable reference to this object
1415
- */
1416
- simulateDelay(i) {
1417
- return this._simulateDelay = i, this;
1418
- }
1419
- resolveWithDelay(i) {
1420
- if (this._simulateDelay <= 0) return Promise.resolve(i);
1421
- const e = new Promise((t) => {
1422
- setTimeout(
1423
- () => t(i),
1424
- this._simulateDelay
1425
- );
1426
- });
1427
- return this._pendingPromises.push(e), e.finally(
1428
- () => this._pendingPromises = this._pendingPromises.filter((t) => t === e)
1429
- ), e;
1430
- }
1431
- save(i, e) {
1432
- const t = i;
1433
- this._onProgress && this._onProgress(0, 100), this.mockFileSystem[i] = JSON.stringify(e), this._onProgress && this._onProgress(100, 100);
1434
- const r = e instanceof File ? e.name : t;
1435
- return this.resolveWithDelay(r);
1436
- }
1437
- uploadControl() {
1438
- return {
1439
- resume: () => {
1440
- },
1441
- pause: () => {
1442
- },
1443
- cancel: () => {
1444
- },
1445
- onProgress: (i) => this._onProgress = i
1446
- };
1447
- }
1448
- getUrl(i) {
1449
- return Promise.resolve(this._pathToMockFiles + i);
1450
- }
1451
- delete(i) {
1452
- return delete this.mockFileSystem[i], this.resolveWithDelay();
1453
- }
918
+ N = l([M("MockCloudStorage", () => new N())], N);
919
+ //#endregion
920
+ //#region src/cloud-storage/stored-file.ts
921
+ var P = /* @__PURE__ */ function(e) {
922
+ return e[e.stored = 0] = "stored", e[e.pendingDataSet = 1] = "pendingDataSet", e[e.deleted = 2] = "deleted", e;
923
+ }({}), F = class extends u {
924
+ constructor(...t) {
925
+ super(...t), this._onChange = new e();
926
+ }
927
+ async save({ data: e, fileName: t, progress: n, cloudStorageProvider: r } = {}) {
928
+ let i = e || this._pendingData;
929
+ i && (this._reference && await this.delete(), this.provider = r || j.defaultCloudStorage, this._originalFileName = t || (i instanceof File ? i.name : void 0), this._reference = await this.provider.save(this.id, i, n), this._url = await this.provider.getUrl(this._reference), this._pendingData = void 0, this._onChange.notify({
930
+ event: P.stored,
931
+ storedFile: this
932
+ }));
933
+ }
934
+ uploadControl() {
935
+ return this.provider.uploadControl();
936
+ }
937
+ async delete() {
938
+ if (!this._reference) throw Error("Cannot delete a not stored file");
939
+ await this.provider.delete(this._reference), this._reference = void 0, this._url = void 0, this._onChange.notify({
940
+ event: P.deleted,
941
+ storedFile: this
942
+ });
943
+ }
944
+ set provider(e) {
945
+ this._provider = e, this._cloudStorageProviderName = e.className;
946
+ }
947
+ get provider() {
948
+ if (!this._provider) try {
949
+ this._provider = j.createInstance(this._cloudStorageProviderName);
950
+ } catch {
951
+ this._provider = j.defaultCloudStorage;
952
+ }
953
+ return this._provider;
954
+ }
955
+ get url() {
956
+ return this._url;
957
+ }
958
+ get mimeType() {
959
+ return this._mimeType;
960
+ }
961
+ setDataToStore(e) {
962
+ return this._pendingData = e, this._originalFileName = e instanceof File ? e.name : void 0, this._mimeType = e instanceof Blob ? e.type : void 0, this._onChange.notify({
963
+ event: P.pendingDataSet,
964
+ pendingData: e,
965
+ storedFile: this
966
+ }), this;
967
+ }
968
+ get originalFileName() {
969
+ return this._originalFileName;
970
+ }
971
+ onChange(e) {
972
+ return this._onChange.subscribe(e);
973
+ }
1454
974
  };
1455
- T = ie([
1456
- re("MockCloudStorage", () => new T())
1457
- ], T);
1458
- var ne = Object.defineProperty, oe = Object.getOwnPropertyDescriptor, U = (i, e, t, r) => {
1459
- for (var s = r > 1 ? void 0 : r ? oe(e, t) : e, n = i.length - 1, o; n >= 0; n--)
1460
- (o = i[n]) && (s = (r ? o(e, t, s) : o(s)) || s);
1461
- return r && s && ne(e, t, s), s;
1462
- }, ae = /* @__PURE__ */ ((i) => (i[i.stored = 0] = "stored", i[i.pendingDataSet = 1] = "pendingDataSet", i[i.deleted = 2] = "deleted", i))(ae || {});
1463
- let D = class extends d {
1464
- constructor() {
1465
- super(...arguments), this._onChange = new I();
1466
- }
1467
- async save({ data: i, fileName: e, progress: t, cloudStorageProvider: r } = {}) {
1468
- const s = i || this._pendingData;
1469
- s && (this._reference && await this.delete(), this.provider = r || C.defaultCloudStorage, this._originalFileName = e || (s instanceof File ? s.name : void 0), this._reference = await this.provider.save(this.id, s, t), this._url = await this.provider.getUrl(this._reference), this._pendingData = void 0, this._onChange.notify({ event: 0, storedFile: this }));
1470
- }
1471
- uploadControl() {
1472
- return this.provider.uploadControl();
1473
- }
1474
- async delete() {
1475
- if (!this._reference) throw new Error("Cannot delete a not stored file");
1476
- await this.provider.delete(this._reference), this._reference = void 0, this._url = void 0, this._onChange.notify({ event: 2, storedFile: this });
1477
- }
1478
- set provider(i) {
1479
- this._provider = i, this._cloudStorageProviderName = i.className;
1480
- }
1481
- get provider() {
1482
- if (!this._provider)
1483
- try {
1484
- this._provider = C.createInstance(this._cloudStorageProviderName);
1485
- } catch {
1486
- this._provider = C.defaultCloudStorage;
1487
- }
1488
- return this._provider;
1489
- }
1490
- get url() {
1491
- return this._url;
1492
- }
1493
- get mimeType() {
1494
- return this._mimeType;
1495
- }
1496
- setDataToStore(i) {
1497
- return this._pendingData = i, this._originalFileName = i instanceof File ? i.name : void 0, this._mimeType = i instanceof Blob ? i.type : void 0, this._onChange.notify({
1498
- event: 1,
1499
- pendingData: i,
1500
- storedFile: this
1501
- }), this;
1502
- }
1503
- get originalFileName() {
1504
- return this._originalFileName;
1505
- }
1506
- onChange(i) {
1507
- return this._onChange.subscribe(i);
1508
- }
975
+ l([d], F.prototype, "_reference", void 0), l([d], F.prototype, "_url", void 0), l([d], F.prototype, "_cloudStorageProviderName", void 0), l([d], F.prototype, "_originalFileName", void 0), l([d], F.prototype, "_mimeType", void 0), F = l([v("StoredFile")], F);
976
+ //#endregion
977
+ //#region src/auth/auth.ts
978
+ var I = class {}, L = class t extends I {
979
+ static {
980
+ this.error = { shouldBeRegistered: "You should register an auth service before using Auth." };
981
+ }
982
+ constructor() {
983
+ if (super(), this._onAuthStateChange = new e(), !t._authService) throw Error(t.error.shouldBeRegistered);
984
+ t._authService.onAuthStateChange((e) => this.authStateChanged(e));
985
+ }
986
+ static useAuthService(e) {
987
+ t._authService != e && (t._authService = e, this._instance = void 0);
988
+ }
989
+ static get instance() {
990
+ return this._instance ||= new this();
991
+ }
992
+ signUp(e) {
993
+ return t._authService.signUp(e);
994
+ }
995
+ login(e) {
996
+ return t._authService.login(e);
997
+ }
998
+ logout() {
999
+ return t._authService.logout();
1000
+ }
1001
+ resetEmailPassword(e) {
1002
+ return t._authService.resetEmailPassword(e);
1003
+ }
1004
+ resendVerificationEmail(e, n, r) {
1005
+ return t._authService.resendVerificationEmail(e, n, r);
1006
+ }
1007
+ refreshToken() {
1008
+ return t._authService.refreshToken();
1009
+ }
1010
+ onAuthStateChange(e) {
1011
+ return this._onAuthStateChange.subscribe(e);
1012
+ }
1013
+ removeAuthStateChange(e) {
1014
+ this._onAuthStateChange.unsubscribe(e);
1015
+ }
1016
+ linkAdditionalProvider(e) {
1017
+ return t._authService.linkAdditionalProvider(e);
1018
+ }
1019
+ unlinkProvider(e) {
1020
+ return t._authService.unlinkProvider(e);
1021
+ }
1022
+ authStateChanged(e) {
1023
+ this._onAuthStateChange.notify(e);
1024
+ }
1025
+ static {
1026
+ this._instance = void 0;
1027
+ }
1028
+ }, R = class extends I {
1029
+ constructor(...e) {
1030
+ super(...e), this.pendingPromises = [], this._fakeRegisteredUsers = {};
1031
+ }
1032
+ signUp(e) {
1033
+ let { verificationLink: t, email: n, password: r, authProvider: i } = e, a = new Promise(async (a, o) => {
1034
+ i === "email" && (n || o({
1035
+ code: "missingEmail",
1036
+ message: "missingEmail"
1037
+ }), r || o({
1038
+ code: "missingPassword",
1039
+ message: "missingPassword"
1040
+ })), r !== "fail" && n !== "fail" ? (this._loggedUser = this.userCredentials(e), this._fakeRegisteredUsers[this._loggedUser.id] = this._loggedUser, a(this._loggedUser), this.notifyChange?.(this._loggedUser)) : (o({
1041
+ code: "userNotFound",
1042
+ message: t || "Test auth error"
1043
+ }), this.notifyChange?.(void 0));
1044
+ });
1045
+ return this.pendingPromises.push(a), a;
1046
+ }
1047
+ login(e) {
1048
+ let t = Object.values(this._fakeRegisteredUsers).find((t) => t.email === e.email);
1049
+ return e.authProvider === "email" && !t && e.email && (e.email = "fail"), this.signUp(e);
1050
+ }
1051
+ onAuthStateChange(e) {
1052
+ this.notifyChange = e, this.notifyChange(this._loggedUser);
1053
+ }
1054
+ async logout() {
1055
+ let e = new Promise((e) => {
1056
+ this._loggedUser = void 0, e(), this.notifyChange?.(void 0);
1057
+ });
1058
+ return this.pendingPromises.push(e), e;
1059
+ }
1060
+ resetEmailPassword(e) {
1061
+ return Object.values(this._fakeRegisteredUsers).find((t) => t.email === e) ? Promise.resolve() : Promise.reject({
1062
+ code: "userNotFound",
1063
+ message: "Test auth error"
1064
+ });
1065
+ }
1066
+ resendVerificationEmail(e, t, n) {
1067
+ return Object.values(this._fakeRegisteredUsers).find((t) => t.email === e) ? Promise.resolve() : Promise.reject({
1068
+ code: "userNotFound",
1069
+ message: "Test auth error"
1070
+ });
1071
+ }
1072
+ refreshToken() {
1073
+ return Promise.resolve();
1074
+ }
1075
+ linkAdditionalProvider(e) {
1076
+ throw Error("Not implemented.");
1077
+ }
1078
+ unlinkProvider(e) {
1079
+ throw Error("Not implemented.");
1080
+ }
1081
+ async flush() {
1082
+ await Promise.all(this.pendingPromises), this.pendingPromises = [];
1083
+ }
1084
+ fakeRegisteredUser(e) {
1085
+ if (this._fakeRegisteredUsers[e.id]) throw Error(`User with id ${e.id} already exists in fake user list`);
1086
+ return this._fakeRegisteredUsers[e.id] = e, this;
1087
+ }
1088
+ get fakeRegisteredUsers() {
1089
+ return this._fakeRegisteredUsers;
1090
+ }
1091
+ userCredentials(e) {
1092
+ let t = Object.values(this._fakeRegisteredUsers).find((t) => t.email === e.email);
1093
+ return t ? { ...t } : {
1094
+ id: e.authProvider || `testUID${e.email ? "-" + e.email : ""}`,
1095
+ email: e.email || "testEmail",
1096
+ name: e.authProvider || `testName${e.email ? " " + e.email : ""}`,
1097
+ phoneNumber: "testPhone",
1098
+ customData: { role: "test" },
1099
+ lastLogin: 0,
1100
+ creationDate: 0
1101
+ };
1102
+ }
1103
+ }, z = class e {
1104
+ constructor() {}
1105
+ static {
1106
+ this.error = { shouldBeRegistered: "You should register a cloud functions service with useCloudFunctionsService static method before using CloudFunctions." };
1107
+ }
1108
+ static useCloudFunctionsService(e) {
1109
+ this._cloudFunctionsService != e && (this._cloudFunctionsService = e);
1110
+ }
1111
+ static get instance() {
1112
+ if (!this._cloudFunctionsService) throw Error(e.error.shouldBeRegistered);
1113
+ return e._instance ||= new e();
1114
+ }
1115
+ getRawFunction(t) {
1116
+ return e._cloudFunctionsService.retrieveFunction(t);
1117
+ }
1118
+ getFunction(t) {
1119
+ let n = e._cloudFunctionsService.callFunction, r = this.getRawFunction(t);
1120
+ return async (e) => {
1121
+ let t = await n(r, this.processParam(e));
1122
+ return this.processResult(t);
1123
+ };
1124
+ }
1125
+ processParam(e) {
1126
+ if (e != null) return e instanceof u ? e.toObject() : Array.isArray(e) ? e.map((e) => this.processParam(e)) : typeof e == "object" ? Object.entries(e).reduce((e, [t, n]) => (e[t] = this.processParam(n), e), {}) : e;
1127
+ }
1128
+ processResult(e) {
1129
+ if (e != null) return e.__className ? u.createInstance(e) : Array.isArray(e) ? e.map((e) => this.processResult(e)) : typeof e == "object" ? Object.entries(e).reduce((e, [t, n]) => (e[t] = this.processResult(n), e), {}) : e;
1130
+ }
1131
+ }, B = class {
1132
+ constructor(e) {
1133
+ this._registeredFunctions = e;
1134
+ }
1135
+ retrieveFunction(e) {
1136
+ let t = this._registeredFunctions[e];
1137
+ if (!t) throw Error(`Cloud function ${e} is not registered.`);
1138
+ return t;
1139
+ }
1140
+ callFunction(e, t) {
1141
+ return e(t);
1142
+ }
1143
+ }, V = class {}, H = class e extends V {
1144
+ static {
1145
+ this.error = { shouldBeRegistered: "You should register a Server Auth service before using the Server Auth." };
1146
+ }
1147
+ constructor() {
1148
+ super();
1149
+ }
1150
+ static useServerAuthService(t) {
1151
+ e._authService != t && (e._authService = t, this._instance = void 0);
1152
+ }
1153
+ static get instance() {
1154
+ if (!e._authService) throw Error(e.error.shouldBeRegistered);
1155
+ return this._instance ||= new e();
1156
+ }
1157
+ getUser(t) {
1158
+ return e._authService.getUser(t);
1159
+ }
1160
+ updateUser(t, n) {
1161
+ return e._authService.updateUser(t, n);
1162
+ }
1163
+ setCustomCredentials(t, n) {
1164
+ return e._authService.setCustomCredentials(t, n);
1165
+ }
1166
+ deleteUser(t) {
1167
+ return e._authService.deleteUser(t);
1168
+ }
1169
+ static {
1170
+ this._instance = void 0;
1171
+ }
1172
+ }, U = class extends V {
1173
+ constructor(e) {
1174
+ super(), this._userCredentials = e;
1175
+ }
1176
+ getUser(e) {
1177
+ return this._userCredentials[e] || Promise.resolve(void 0), Promise.resolve(this._userCredentials[e]);
1178
+ }
1179
+ setCustomCredentials(e, t) {
1180
+ let n = this._userCredentials[e];
1181
+ if (!n) throw Error(`User ${e} not found in the auth system`);
1182
+ return n.customData = { ...t }, Promise.resolve();
1183
+ }
1184
+ updateUser(e, t) {
1185
+ return this._userCredentials[e] = {
1186
+ ...this._userCredentials,
1187
+ ...t,
1188
+ id: e
1189
+ }, Promise.resolve(this._userCredentials[e]);
1190
+ }
1191
+ deleteUser(e) {
1192
+ return delete this._userCredentials[e], Promise.resolve();
1193
+ }
1194
+ get userCredentials() {
1195
+ return this._userCredentials;
1196
+ }
1509
1197
  };
1510
- U([
1511
- j
1512
- ], D.prototype, "_reference", 2);
1513
- U([
1514
- j
1515
- ], D.prototype, "_url", 2);
1516
- U([
1517
- j
1518
- ], D.prototype, "_cloudStorageProviderName", 2);
1519
- U([
1520
- j
1521
- ], D.prototype, "_originalFileName", 2);
1522
- U([
1523
- j
1524
- ], D.prototype, "_mimeType", 2);
1525
- D = U([
1526
- ee("StoredFile")
1527
- ], D);
1528
- class Q {
1198
+ //#endregion
1199
+ //#region src/utils/utils.ts
1200
+ function W(e, t) {
1201
+ return e ? e.replace(/\${\s*(\w*)\s*}/g, function(e, n) {
1202
+ return t[n] || "";
1203
+ }) : "";
1529
1204
  }
1530
- const p = class p extends Q {
1531
- constructor() {
1532
- if (super(), this._onAuthStateChange = new I(), !p._authService) throw new Error(p.error.shouldBeRegistered);
1533
- p._authService.onAuthStateChange(
1534
- (e) => this.authStateChanged(e)
1535
- );
1536
- }
1537
- /**
1538
- * Registers an authentication service to be used by the Auth class.
1539
- * You need to register an authentication service before using the Auth class.
1540
- * @param authService the authentication service to be used by the Auth class
1541
- */
1542
- static useAuthService(e) {
1543
- p._authService != e && (p._authService = e, this._instance = void 0);
1544
- }
1545
- /**
1546
- * The instance of the Auth class
1547
- * @returns the authentication service
1548
- */
1549
- static get instance() {
1550
- return this._instance || (this._instance = new this());
1551
- }
1552
- /**
1553
- * Signs up a new user
1554
- * @param singData the data to be used to sign up the user
1555
- * @returns a promise that resolves to the user credentials
1556
- * @example
1557
- * // Sign up a new user with email and password
1558
- * Auth.instance.signUp({ authProvider: 'email', email: 'john@test.com', password: '123456' })
1559
- * // Sign up a new user with a Google account
1560
- * Auth.instance.signUp({ authProvider: 'google'})
1561
- */
1562
- signUp(e) {
1563
- return p._authService.signUp(e);
1564
- }
1565
- /**
1566
- * Logs in an existing user
1567
- * @param singData the data to be used to log in the user
1568
- * @returns a promise that resolves to the user credentials
1569
- * @example
1570
- * // Log in an existing user with email and password
1571
- * Auth.instance.login({ authProvider: 'email', email: 'john@test.com', password: '123456' })
1572
- * // Log in an existing user with a Google account
1573
- * Auth.instance.login({ authProvider: 'google'})
1574
- */
1575
- login(e) {
1576
- return p._authService.login(e);
1577
- }
1578
- /**
1579
- * Logs out the current user
1580
- * @returns a promise that resolves when the user is logged out
1581
- */
1582
- logout() {
1583
- return p._authService.logout();
1584
- }
1585
- /**
1586
- * Resets the password associated with the email.
1587
- * @param email the email address of the user to reset the password
1588
- * @returns a promise that resolves when the process is done
1589
- */
1590
- resetEmailPassword(e) {
1591
- return p._authService.resetEmailPassword(e);
1592
- }
1593
- /**
1594
- * Resends the email verification to the user.
1595
- * @returns a promise that resolves when the process is done
1596
- */
1597
- resendVerificationEmail(e, t, r) {
1598
- return p._authService.resendVerificationEmail(e, t, r);
1599
- }
1600
- refreshToken() {
1601
- return p._authService.refreshToken();
1602
- }
1603
- /**
1604
- * Adds a listener to be called when the authentication state changes.
1605
- * @param onChange the listener to be called when the authentication state changes.
1606
- * The listener is called with the user credentials as a parameter.
1607
- * If the user is logged out, the listener is called with `undefined` as a parameter.
1608
- * @returns a function to remove the listener
1609
- * @example
1610
- * // Add a listener to be called when the authentication state changes
1611
- * const removeListener = Auth.instance.onAuthStateChange( userCredentials => {
1612
- * if ( userCredentials ) {
1613
- * // The user is logged in
1614
- * } else {
1615
- * // The user is logged out
1616
- * }
1617
- * })
1618
- */
1619
- onAuthStateChange(e) {
1620
- return this._onAuthStateChange.subscribe(e);
1621
- }
1622
- /**
1623
- * Removes a listener that was added by `onAuthStateChange` method.
1624
- * @param onChange the listener to be removed
1625
- */
1626
- removeAuthStateChange(e) {
1627
- this._onAuthStateChange.unsubscribe(e);
1628
- }
1629
- /**
1630
- * Links an additional authentication provider to the authenticated user.
1631
- * @param provider the provider to be linked
1632
- * @returns a promise that resolves when the process is done
1633
- * @example
1634
- * // Link a Google account to the auth service
1635
- * Auth.instance.linkAdditionalProvider({ authProvider: 'google' })
1636
- */
1637
- linkAdditionalProvider(e) {
1638
- return p._authService.linkAdditionalProvider(e);
1639
- }
1640
- /**
1641
- * Unlinks an authentication provider from the authenticated user.
1642
- * @param provider the provider to be unlinked
1643
- * @returns a promise that resolves when the process is done
1644
- * @example
1645
- * // Unlink the Google account from the auth service
1646
- * Auth.instance.unlinkProvider({ authProvider: 'google' })
1647
- */
1648
- unlinkProvider(e) {
1649
- return p._authService.unlinkProvider(e);
1650
- }
1651
- authStateChanged(e) {
1652
- this._onAuthStateChange.notify(e);
1653
- }
1654
- };
1655
- p.error = { shouldBeRegistered: "You should register an auth service before using Auth." }, p._instance = void 0;
1656
- let x = p;
1657
- class Pe extends Q {
1658
- constructor() {
1659
- super(...arguments), this.pendingPromises = [], this._fakeRegisteredUsers = {};
1660
- }
1661
- signUp(e) {
1662
- const { verificationLink: t, email: r, password: s, authProvider: n } = e, o = new Promise(async (a, u) => {
1663
- n === "email" && (r || u({ code: "missingEmail", message: "missingEmail" }), s || u({ code: "missingPassword", message: "missingPassword" })), s !== "fail" && r !== "fail" ? (this._loggedUser = this.userCredentials(e), this._fakeRegisteredUsers[this._loggedUser.id] = this._loggedUser, a(this._loggedUser), this.notifyChange?.(this._loggedUser)) : (u({ code: "userNotFound", message: t || "Test auth error" }), this.notifyChange?.(void 0));
1664
- });
1665
- return this.pendingPromises.push(o), o;
1666
- }
1667
- login(e) {
1668
- const t = Object.values(this._fakeRegisteredUsers).find(
1669
- (r) => r.email === e.email
1670
- );
1671
- return e.authProvider === "email" && !t && e.email && (e.email = "fail"), this.signUp(e);
1672
- }
1673
- onAuthStateChange(e) {
1674
- this.notifyChange = e, this.notifyChange(this._loggedUser);
1675
- }
1676
- async logout() {
1677
- const e = new Promise((t) => {
1678
- this._loggedUser = void 0, t(), this.notifyChange?.(void 0);
1679
- });
1680
- return this.pendingPromises.push(e), e;
1681
- }
1682
- resetEmailPassword(e) {
1683
- return Object.values(this._fakeRegisteredUsers).find(
1684
- (r) => r.email === e
1685
- ) ? Promise.resolve() : Promise.reject({ code: "userNotFound", message: "Test auth error" });
1686
- }
1687
- resendVerificationEmail(e, t, r) {
1688
- return Object.values(this._fakeRegisteredUsers).find(
1689
- (n) => n.email === e
1690
- ) ? Promise.resolve() : Promise.reject({ code: "userNotFound", message: "Test auth error" });
1691
- }
1692
- refreshToken() {
1693
- return Promise.resolve();
1694
- }
1695
- linkAdditionalProvider(e) {
1696
- throw new Error("Not implemented.");
1697
- }
1698
- unlinkProvider(e) {
1699
- throw new Error("Not implemented.");
1700
- }
1701
- async flush() {
1702
- await Promise.all(this.pendingPromises), this.pendingPromises = [];
1703
- }
1704
- fakeRegisteredUser(e) {
1705
- if (this._fakeRegisteredUsers[e.id]) throw new Error(`User with id ${e.id} already exists in fake user list`);
1706
- return this._fakeRegisteredUsers[e.id] = e, this;
1707
- }
1708
- get fakeRegisteredUsers() {
1709
- return this._fakeRegisteredUsers;
1710
- }
1711
- userCredentials(e) {
1712
- const t = Object.values(this._fakeRegisteredUsers).find(
1713
- (r) => r.email === e.email
1714
- );
1715
- return t ? { ...t } : {
1716
- id: e.authProvider || `testUID${e.email ? "-" + e.email : ""}`,
1717
- email: e.email || "testEmail",
1718
- name: e.authProvider || `testName${e.email ? " " + e.email : ""}`,
1719
- phoneNumber: "testPhone",
1720
- customData: {
1721
- role: "test"
1722
- },
1723
- lastLogin: 0,
1724
- creationDate: 0
1725
- };
1726
- }
1727
- }
1728
- const y = class y {
1729
- constructor() {
1730
- }
1731
- static useCloudFunctionsService(e) {
1732
- this._cloudFunctionsService != e && (this._cloudFunctionsService = e);
1733
- }
1734
- static get instance() {
1735
- if (!this._cloudFunctionsService) throw new Error(y.error.shouldBeRegistered);
1736
- return y._instance || (y._instance = new y());
1737
- }
1738
- getRawFunction(e) {
1739
- return y._cloudFunctionsService.retrieveFunction(e);
1740
- }
1741
- getFunction(e) {
1742
- const t = y._cloudFunctionsService.callFunction, r = this.getRawFunction(e);
1743
- return async (s) => {
1744
- const n = await t(r, this.processParam(s));
1745
- return this.processResult(n);
1746
- };
1747
- }
1748
- processParam(e) {
1749
- if (e != null)
1750
- return e instanceof d ? e.toObject() : Array.isArray(e) ? e.map((t) => this.processParam(t)) : typeof e == "object" ? Object.entries(e).reduce((t, [r, s]) => (t[r] = this.processParam(s), t), {}) : e;
1751
- }
1752
- processResult(e) {
1753
- if (e != null)
1754
- return e.__className ? d.createInstance(e) : Array.isArray(e) ? e.map((t) => this.processResult(t)) : typeof e == "object" ? Object.entries(e).reduce((t, [r, s]) => (t[r] = this.processResult(s), t), {}) : e;
1755
- }
1756
- };
1757
- y.error = { shouldBeRegistered: "You should register a cloud functions service with useCloudFunctionsService static method before using CloudFunctions." };
1758
- let $ = y;
1759
- class ve {
1760
- constructor(e) {
1761
- this._registeredFunctions = e;
1762
- }
1763
- retrieveFunction(e) {
1764
- const t = this._registeredFunctions[e];
1765
- if (!t) throw new Error(`Cloud function ${e} is not registered.`);
1766
- return t;
1767
- }
1768
- callFunction(e, t) {
1769
- return e(t);
1770
- }
1205
+ function G(e) {
1206
+ return e ? e.replace(/([-_ ][\w])/g, (e) => e.toUpperCase().replace("-", "").replace("_", "").replace(" ", "")) : "";
1771
1207
  }
1772
- class B {
1773
- }
1774
- const g = class g extends B {
1775
- constructor() {
1776
- super();
1777
- }
1778
- static useServerAuthService(e) {
1779
- g._authService != e && (g._authService = e, this._instance = void 0);
1780
- }
1781
- static get instance() {
1782
- if (!g._authService) throw new Error(g.error.shouldBeRegistered);
1783
- return this._instance || (this._instance = new g());
1784
- }
1785
- getUser(e) {
1786
- return g._authService.getUser(e);
1787
- }
1788
- updateUser(e, t) {
1789
- return g._authService.updateUser(e, t);
1790
- }
1791
- setCustomCredentials(e, t) {
1792
- return g._authService.setCustomCredentials(e, t);
1793
- }
1794
- deleteUser(e) {
1795
- return g._authService.deleteUser(e);
1796
- }
1797
- };
1798
- g.error = { shouldBeRegistered: "You should register a Server Auth service before using the Server Auth." }, g._instance = void 0;
1799
- let V = g;
1800
- class we extends B {
1801
- constructor(e) {
1802
- super(), this._userCredentials = e;
1803
- }
1804
- getUser(e) {
1805
- return this._userCredentials[e] || Promise.resolve(void 0), Promise.resolve(this._userCredentials[e]);
1806
- }
1807
- setCustomCredentials(e, t) {
1808
- const r = this._userCredentials[e];
1809
- if (!r) throw new Error(`User ${e} not found in the auth system`);
1810
- return r.customData = { ...t }, Promise.resolve();
1811
- }
1812
- updateUser(e, t) {
1813
- return this._userCredentials[e] = {
1814
- ...this._userCredentials,
1815
- ...t,
1816
- id: e
1817
- }, Promise.resolve(this._userCredentials[e]);
1818
- }
1819
- deleteUser(e) {
1820
- return delete this._userCredentials[e], Promise.resolve();
1821
- }
1822
- get userCredentials() {
1823
- return this._userCredentials;
1824
- }
1208
+ function K(e, t = "-") {
1209
+ if (!e) return "";
1210
+ let n = e.slice(1).replace(/( |[A-Z])/g, (e) => e === " " ? "-" : t + e[0].toLowerCase());
1211
+ return e[0].toLocaleLowerCase() + n.replace(/--/g, "-");
1825
1212
  }
1826
- function Ce(i, e) {
1827
- return i ? i.replace(/\${\s*(\w*)\s*}/g, function(t, r) {
1828
- return e[r] || "";
1829
- }) : "";
1213
+ function q(e, t) {
1214
+ return t.split(".").reduce((e, t) => e[t], e);
1830
1215
  }
1831
- function De(i) {
1832
- return i ? i.replace(
1833
- /([-_ ][\w])/g,
1834
- (e) => e.toUpperCase().replace("-", "").replace("_", "").replace(" ", "")
1835
- ) : "";
1836
- }
1837
- function Se(i, e = "-") {
1838
- if (!i) return "";
1839
- const t = i.slice(1).replace(/( |[A-Z])/g, (r) => r === " " ? "-" : e + r[0].toLowerCase());
1840
- return i[0].toLocaleLowerCase() + t.replace(/--/g, "-");
1841
- }
1842
- function Oe(i, e) {
1843
- return e.split(".").reduce((t, r) => t[r], i);
1844
- }
1845
- export {
1846
- x as Auth,
1847
- Pe as AuthMock,
1848
- Q as AuthService,
1849
- $ as CloudFunctions,
1850
- ve as CloudFunctionsMock,
1851
- C as CloudStorage,
1852
- w as DataSource,
1853
- ye as EntropicComponent,
1854
- be as JsonDataSource,
1855
- T as MockCloudStorage,
1856
- R as Model,
1857
- I as Observable,
1858
- d as Persistent,
1859
- te as Query,
1860
- V as ServerAuth,
1861
- we as ServerAuthMock,
1862
- B as ServerAuthService,
1863
- k as Store,
1864
- D as StoredFile,
1865
- ae as StoredFileEvent,
1866
- De as camelCase,
1867
- Oe as getDeepValue,
1868
- j as persistent,
1869
- _ as persistentParser,
1870
- le as persistentPureReference,
1871
- de as persistentPureReferenceWithCachedProps,
1872
- ue as persistentReference,
1873
- ce as persistentReferenceAt,
1874
- he as persistentReferenceWithCachedProps,
1875
- re as registerCloudStorage,
1876
- fe as registerLegacyClassName,
1877
- ee as registerPersistentClass,
1878
- Ce as replaceValue,
1879
- pe as required,
1880
- ge as requiredWithValidator,
1881
- me as searchableArray,
1882
- Se as snakeCase,
1883
- _e as typeName
1884
- };
1885
- //# sourceMappingURL=entropic-bond.js.map
1216
+ //#endregion
1217
+ export { L as Auth, R as AuthMock, I as AuthService, z as CloudFunctions, B as CloudFunctionsMock, j as CloudStorage, k as DataSource, w as EntropicComponent, A as JsonDataSource, N as MockCloudStorage, T as Model, e as Observable, u as Persistent, E as Query, H as ServerAuth, U as ServerAuthMock, V as ServerAuthService, D as Store, F as StoredFile, P as StoredFileEvent, G as camelCase, q as getDeepValue, d as persistent, _ as persistentParser, h as persistentPureReference, g as persistentPureReferenceWithCachedProps, p as persistentReference, f as persistentReferenceAt, m as persistentReferenceWithCachedProps, M as registerCloudStorage, y as registerLegacyClassName, v as registerPersistentClass, W as replaceValue, x as required, S as requiredWithValidator, b as searchableArray, K as snakeCase, C as typeName };
1218
+
1219
+ //# sourceMappingURL=entropic-bond.js.map