@coasys/ad4m 0.10.1-release-candidate-3-test-2 → 0.10.1-release-candidate-4-debug-strings

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,591 +0,0 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
- };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _SubjectEntity_baseExpression, _SubjectEntity_subjectClassName, _SubjectEntity_source, _SubjectEntity_perspective;
13
- import { Literal } from "../Literal";
14
- import { Link } from "../links/Links";
15
- import { makeRandomPrologAtom } from "./SDNADecorators";
16
- import { singularToPlural } from "./util";
17
- function capitalize(word) {
18
- return word.charAt(0).toUpperCase() + word.slice(1);
19
- }
20
- function buildSourceQuery(source) {
21
- // Constrains the query to instances that have the provided source
22
- if (!source)
23
- return "";
24
- return `triple("${source}", "ad4m://has_child", Base)`;
25
- }
26
- // todo: only return Timestamp & Author from query (Base, AllLinks, and SortLinks not required)
27
- function buildAuthorAndTimestampQuery() {
28
- // Gets the author and timestamp of a SubjectEntity instance (based on the first link mentioning the base)
29
- return `
30
- findall(
31
- [T, A],
32
- link(Base, _, _, T, A),
33
- AllLinks
34
- ),
35
- sort(AllLinks, SortedLinks),
36
- SortedLinks = [[Timestamp, Author]|_]
37
- `;
38
- }
39
- function buildPropertiesQuery(properties) {
40
- // Gets the name, value, and resolve boolean for all (or some) properties on a SubjectEntity instance
41
- // Resolves literals (if property_resolve/2 is true) to their value - either the data field if it is
42
- // an Expression in JSON literal, or the direct literal value if it is a simple literal
43
- // If no properties are provided, all are included
44
- return `
45
- findall([PropertyName, PropertyValue, Resolve], (
46
- % Constrain to specified properties if provided
47
- ${properties ? `member(PropertyName, [${properties.map((name) => `"${name}"`).join(", ")}]),` : ""}
48
- resolve_property(SubjectClass, Base, PropertyName, PropertyValue, Resolve)
49
- ), Properties)
50
- `;
51
- }
52
- function buildCollectionsQuery(collections) {
53
- // Gets the name and array of values for all (or some) collections on a SubjectEntity instance
54
- // If no collections are provided, all are included
55
- return `
56
- findall([CollectionName, CollectionValues], (
57
- % Constrain to specified collections if provided
58
- ${collections ? `member(CollectionName, [${collections.map((name) => `"${name}"`).join(", ")}]),` : ""}
59
-
60
- collection(SubjectClass, CollectionName),
61
- collection_getter(SubjectClass, Base, CollectionName, CollectionValues)
62
- ), Collections)
63
- `;
64
- }
65
- function buildWhereQuery(where = {}) {
66
- // Constrains the query to instances that match the provided where conditions
67
- function formatValue(value) {
68
- // Wrap strings in quotes
69
- return typeof value === "string" ? `"${value}"` : value;
70
- }
71
- return Object.entries(where)
72
- .map(([key, value]) => {
73
- const isSpecial = ["author", "timestamp"].includes(key);
74
- const getter = `resolve_property(SubjectClass, Base, "${key}", Value${key}, _)`;
75
- // const getter = `property_getter(SubjectClass, Base, "${key}", URI), literal_from_url(URI, V, _)`;
76
- const field = capitalize(key);
77
- // Handle direct array values (for IN conditions)
78
- if (Array.isArray(value)) {
79
- const formattedValues = value.map((v) => formatValue(v)).join(", ");
80
- if (isSpecial)
81
- return `member(${field}, [${formattedValues}])`;
82
- else
83
- return `${getter}, member(Value${key}, [${formattedValues}])`;
84
- }
85
- // Handle operation object
86
- if (typeof value === "object" && value !== null) {
87
- const { not, between, lt, lte, gt, gte } = value;
88
- // Handle NOT operation
89
- if (not !== undefined) {
90
- if (Array.isArray(not)) {
91
- // NOT IN array
92
- const formattedValues = not.map((v) => formatValue(v)).join(", ");
93
- if (isSpecial)
94
- return `\\+ member(${field}, [${formattedValues}])`;
95
- else
96
- return `${getter}, \\+ member(Value${key}, [${formattedValues}])`;
97
- }
98
- else {
99
- // NOT EQUAL
100
- if (isSpecial)
101
- return `${field} \\= ${formatValue(not)}`;
102
- else
103
- return `${getter}, Value${key} \\= ${formatValue(not)}`;
104
- }
105
- }
106
- // Handle BETWEEN
107
- if (between !== undefined && Array.isArray(between) && between.length === 2) {
108
- if (isSpecial)
109
- return `${field} >= ${between[0]}, ${field} =< ${between[1]}`;
110
- else
111
- return `${getter}, Value${key} >= ${between[0]}, Value${key} =< ${between[1]}`;
112
- }
113
- // Handle lt, lte, gt, & gte operations
114
- const operators = [
115
- { value: lt, symbol: "<" },
116
- { value: lte, symbol: "=<" },
117
- { value: gt, symbol: ">" },
118
- { value: gte, symbol: ">=" }, // GREATER THAN OR EQUAL TO
119
- ];
120
- for (const { value, symbol } of operators) {
121
- if (value !== undefined)
122
- return isSpecial ? `${field} ${symbol} ${value}` : `${getter}, Value${key} ${symbol} ${value}`;
123
- }
124
- }
125
- // Default to direct equality
126
- if (isSpecial)
127
- return `${field} = ${formatValue(value)}`;
128
- else
129
- return `${getter}, Value${key} = ${formatValue(value)}`;
130
- })
131
- .join(", ");
132
- }
133
- function buildCountQuery(count) {
134
- return count ? "length(UnsortedInstances, TotalCount)" : "";
135
- }
136
- function buildOrderQuery(order) {
137
- if (!order)
138
- return "SortedInstances = UnsortedInstances";
139
- const [propertyName, direction] = Object.entries(order)[0];
140
- return `sort_instances(UnsortedInstances, "${propertyName}", "${direction}", SortedInstances)`;
141
- }
142
- function buildOffsetQuery(offset) {
143
- if (!offset || offset < 0)
144
- return "InstancesWithOffset = SortedInstances";
145
- return `skipN(SortedInstances, ${offset}, InstancesWithOffset)`;
146
- }
147
- function buildLimitQuery(limit) {
148
- if (!limit || limit < 0)
149
- return "AllInstances = InstancesWithOffset";
150
- return `takeN(InstancesWithOffset, ${limit}, AllInstances)`;
151
- }
152
- /**
153
- * Class representing a subject entity.
154
- * Can extend this class to create a new subject entity to add methods interact with SDNA and much better experience then using the bare bone methods.
155
- */
156
- export class SubjectEntity {
157
- static async getClassName(perspective) {
158
- // Get or create the cache for this class
159
- let classCache = this.classNamesByClass.get(this);
160
- if (!classCache) {
161
- classCache = {};
162
- this.classNamesByClass.set(this, classCache);
163
- }
164
- // Get or create the cached name for this perspective
165
- const perspectiveID = perspective.uuid;
166
- if (!classCache[perspectiveID]) {
167
- classCache[perspectiveID] = await perspective.stringOrTemplateObjectToSubjectClassName(this);
168
- }
169
- return classCache[perspectiveID];
170
- }
171
- /**
172
- * Constructs a new subject.
173
- * @param perspective - The perspective that the subject belongs to.
174
- * @param baseExpression - The base expression of the subject.
175
- * @param source - The source of the subject, the expression this instance is linked too.
176
- */
177
- constructor(perspective, baseExpression, source) {
178
- _SubjectEntity_baseExpression.set(this, void 0);
179
- _SubjectEntity_subjectClassName.set(this, void 0);
180
- _SubjectEntity_source.set(this, void 0);
181
- _SubjectEntity_perspective.set(this, void 0);
182
- __classPrivateFieldSet(this, _SubjectEntity_baseExpression, baseExpression ? baseExpression : Literal.from(makeRandomPrologAtom(24)).toUrl(), "f");
183
- __classPrivateFieldSet(this, _SubjectEntity_perspective, perspective, "f");
184
- __classPrivateFieldSet(this, _SubjectEntity_source, source || "ad4m://self", "f");
185
- }
186
- /**
187
- * Gets the base expression of the subject.
188
- */
189
- get baseExpression() {
190
- return __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f");
191
- }
192
- /**
193
- * Protected getter for the perspective.
194
- * Allows subclasses to access the perspective while keeping it private from external code.
195
- */
196
- get perspective() {
197
- return __classPrivateFieldGet(this, _SubjectEntity_perspective, "f");
198
- }
199
- static async assignValuesToInstance(perspective, instance, values) {
200
- // Map properties to object
201
- const propsObject = Object.fromEntries(await Promise.all(values.map(async ([name, value, resolve]) => {
202
- let finalValue = value;
203
- // Resolve the value if necessary
204
- if (resolve) {
205
- let resolvedExpression = await perspective.getExpression(value);
206
- if (resolvedExpression) {
207
- finalValue = resolvedExpression.data;
208
- }
209
- }
210
- return [name, finalValue];
211
- })));
212
- // Assign properties to instance
213
- Object.assign(instance, propsObject);
214
- }
215
- async getData() {
216
- // Builds an object with the author, timestamp, all properties, & all collections on the SubjectEntity and saves it to the instance
217
- const subQueries = [buildAuthorAndTimestampQuery(), buildPropertiesQuery(), buildCollectionsQuery()];
218
- const fullQuery = `
219
- Base = "${__classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f")}",
220
- subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClassName, "f")}", SubjectClass),
221
- ${subQueries.join(", ")}
222
- `;
223
- const result = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(fullQuery);
224
- if (result?.[0]) {
225
- const { Properties, Collections, Timestamp, Author } = result?.[0];
226
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
227
- await SubjectEntity.assignValuesToInstance(__classPrivateFieldGet(this, _SubjectEntity_perspective, "f"), this, values);
228
- }
229
- return this;
230
- }
231
- // Todo: Only return AllInstances (InstancesWithOffset, SortedInstances, & UnsortedInstances not required)
232
- static async queryToProlog(perspective, query) {
233
- const { source, properties, collections, where, order, offset, limit, count } = query;
234
- const instanceQueries = [
235
- buildAuthorAndTimestampQuery(),
236
- buildSourceQuery(source),
237
- buildPropertiesQuery(properties),
238
- buildCollectionsQuery(collections),
239
- buildWhereQuery(where),
240
- ];
241
- const resultSetQueries = [buildCountQuery(count), buildOrderQuery(order), buildOffsetQuery(offset), buildLimitQuery(limit)];
242
- const fullQuery = `
243
- findall([Base, Properties, Collections, Timestamp, Author], (
244
- subject_class("${await this.getClassName(perspective)}", SubjectClass),
245
- instance(SubjectClass, Base),
246
- ${instanceQueries.filter((q) => q).join(", ")}
247
- ), UnsortedInstances),
248
- ${resultSetQueries.filter((q) => q).join(", ")}
249
- `;
250
- return fullQuery;
251
- }
252
- static async instancesFromPrologResult(perspective, query, result) {
253
- if (!result?.[0]?.AllInstances)
254
- return { results: [], totalCount: 0 };
255
- // Map results to instances
256
- const requestedAttribtes = [...(query?.properties || []), ...(query?.collections || [])];
257
- const allInstances = await Promise.all(result[0].AllInstances.map(async ([Base, Properties, Collections, Timestamp, Author]) => {
258
- try {
259
- const instance = new this(perspective, Base);
260
- // Remove unrequested attributes from instance
261
- if (requestedAttribtes.length) {
262
- Object.keys(instance).forEach((key) => {
263
- if (!requestedAttribtes.includes(key))
264
- delete instance[key];
265
- });
266
- }
267
- // Collect values to assign to instance
268
- const values = [...Properties, ...Collections, ["timestamp", Timestamp], ["author", Author]];
269
- await SubjectEntity.assignValuesToInstance(perspective, instance, values);
270
- return instance;
271
- }
272
- catch (error) {
273
- console.error(`Failed to process instance ${Base}:`, error);
274
- // Return null for failed instances - we'll filter these out below
275
- return null;
276
- }
277
- }));
278
- return { results: allInstances.filter((instance) => instance !== null), totalCount: result[0].TotalCount };
279
- }
280
- /**
281
- * Gets all instances of the subject entity in the perspective that match the query params .
282
- * @param perspective - The perspective that the subject entities belongs to.
283
- * @param query - The query object used to define search contraints.
284
- *
285
- * @returns An array of all subject entity matches.
286
- *
287
- */
288
- static async findAll(perspective, query = {}) {
289
- const prologQuery = await this.queryToProlog(perspective, query);
290
- const result = await perspective.infer(prologQuery);
291
- const { results } = await this.instancesFromPrologResult(perspective, query, result);
292
- return results;
293
- }
294
- /**
295
- * Gets all instances of the subject entity in the perspective that match the query params and includes a count of all matches without limit applied.
296
- * @param perspective - The perspective that the subject entities belongs to.
297
- * @param query - The query object used to define search contraints.
298
- *
299
- * @returns An object containing an instances array of all subject entity matches and a count of all matches without limit applied.
300
- *
301
- */
302
- static async findAllAndCount(perspective, query = {}) {
303
- const prologQuery = await this.queryToProlog(perspective, query);
304
- const result = await perspective.infer(prologQuery);
305
- return await this.instancesFromPrologResult(perspective, query, result);
306
- }
307
- /**
308
- * Helper function to make pagination easier with explicit pageSize & pageNumber props.
309
- * @param perspective - The perspective that the subject entities belongs to.
310
- * @param query - The query object used to define search contraints.
311
- *
312
- * @returns An a page of results based on the pageSize & pageNumber props.
313
- *
314
- */
315
- static async paginate(perspective, pageSize, pageNumber, query) {
316
- const paginationQuery = { ...(query || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
317
- const prologQuery = await this.queryToProlog(perspective, paginationQuery);
318
- const result = await perspective.infer(prologQuery);
319
- const { results, totalCount } = await this.instancesFromPrologResult(perspective, paginationQuery, result);
320
- return { results, totalCount, pageSize, pageNumber };
321
- }
322
- static async countQueryToProlog(perspective, query = {}) {
323
- const { source, where } = query;
324
- const instanceQueries = [buildAuthorAndTimestampQuery(), buildSourceQuery(source), buildWhereQuery(where)];
325
- const resultSetQueries = [buildCountQuery(true), buildOrderQuery(), buildOffsetQuery(), buildLimitQuery()];
326
- const fullQuery = `
327
- findall([Base, Properties, Collections, Timestamp, Author], (
328
- subject_class("${await this.getClassName(perspective)}", SubjectClass),
329
- instance(SubjectClass, Base),
330
- ${instanceQueries.filter((q) => q).join(", ")}
331
- ), UnsortedInstances),
332
- ${resultSetQueries.filter((q) => q).join(", ")}
333
- `;
334
- return fullQuery;
335
- }
336
- /**
337
- * Gets a count of all instances of the subject entity in the perspective that match the query params.
338
- * @param perspective - The perspective that the subject entities belongs to.
339
- * @param query - The query object used to define search contraints.
340
- *
341
- * @returns The count of subject entities matching the query.
342
- *
343
- */
344
- static async count(perspective, query = {}) {
345
- const result = await perspective.infer(await this.countQueryToProlog(perspective, query));
346
- return result?.[0]?.TotalCount || 0;
347
- }
348
- async setProperty(key, value) {
349
- const setters = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClassName, "f")}", C), property_setter(C, "${key}", Setter)`);
350
- if (setters && setters.length > 0) {
351
- const actions = eval(setters[0].Setter);
352
- const resolveLanguageResults = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClassName, "f")}", C), property_resolve_language(C, "${key}", Language)`);
353
- let resolveLanguage;
354
- if (resolveLanguageResults && resolveLanguageResults.length > 0) {
355
- resolveLanguage = resolveLanguageResults[0].Language;
356
- }
357
- if (resolveLanguage) {
358
- value = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").createExpression(value, resolveLanguage);
359
- }
360
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value }]);
361
- }
362
- }
363
- async setCollectionSetter(key, value) {
364
- let collectionSetters = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClassName, "f")}", C), collection_setter(C, "${singularToPlural(key)}", Setter)`);
365
- if (!collectionSetters)
366
- collectionSetters = [];
367
- if (collectionSetters.length > 0) {
368
- const actions = eval(collectionSetters[0].Setter);
369
- if (value) {
370
- if (Array.isArray(value)) {
371
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), value.map((v) => ({ name: "value", value: v })));
372
- }
373
- else {
374
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value }]);
375
- }
376
- }
377
- }
378
- }
379
- async setCollectionAdder(key, value) {
380
- let adders = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClassName, "f")}", C), collection_adder(C, "${singularToPlural(key)}", Adder)`);
381
- if (!adders)
382
- adders = [];
383
- if (adders.length > 0) {
384
- const actions = eval(adders[0].Adder);
385
- if (value) {
386
- if (Array.isArray(value)) {
387
- await Promise.all(value.map((v) => __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value: v }])));
388
- }
389
- else {
390
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value }]);
391
- }
392
- }
393
- }
394
- }
395
- async setCollectionRemover(key, value) {
396
- let removers = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClassName, "f")}", C), collection_remover(C, "${singularToPlural(key)}", Remover)`);
397
- if (!removers)
398
- removers = [];
399
- if (removers.length > 0) {
400
- const actions = eval(removers[0].Remover);
401
- if (value) {
402
- if (Array.isArray(value)) {
403
- await Promise.all(value.map((v) => __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value: v }])));
404
- }
405
- else {
406
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value }]);
407
- }
408
- }
409
- }
410
- }
411
- /**
412
- * Save the subject entity.
413
- * This method will create a new subject with the base expression and add a new link from the source to the base expression with the predicate "ad4m://has_child".
414
- *
415
- * If a property has an action, it will perform the action (Only for collections).
416
- * If a property is an array and is not empty, it will set the collection.
417
- * If a property is not undefined, not null, and not an empty string, it will set the property.
418
- *
419
- *
420
- * @throws Will throw an error if the subject entity cannot be converted to a subject class, or if the subject cannot be created, or if the link cannot be added, or if the subject entity cannot be updated.
421
- */
422
- async save() {
423
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").createSubject(this, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"));
424
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").add(new Link({ source: __classPrivateFieldGet(this, _SubjectEntity_source, "f"), predicate: "ad4m://has_child", target: this.baseExpression }));
425
- await this.update();
426
- }
427
- /**
428
- * Update the subject entity.
429
- *
430
- * It will iterate over the properties of the subject entity.
431
- *
432
- * If a property has an action, it will perform the action (Only for collections).
433
- * If a property is an array and is not empty, it will set the collection.
434
- * If a property is not undefined, not null, and not an empty string, it will set the property.
435
- *
436
- * @throws Will throw an error if the subject entity cannot be converted to a subject class, or if a property cannot be set, or if a collection cannot be set, or if the data of the subject entity cannot be gotten.
437
- */
438
- async update() {
439
- __classPrivateFieldSet(this, _SubjectEntity_subjectClassName, await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").stringOrTemplateObjectToSubjectClassName(this), "f");
440
- const entries = Object.entries(this);
441
- for (const [key, value] of entries) {
442
- if (value !== undefined && value !== null) {
443
- if (value?.action) {
444
- switch (value.action) {
445
- case "setter":
446
- await this.setCollectionSetter(key, value.value);
447
- break;
448
- case "adder":
449
- await this.setCollectionAdder(key, value.value);
450
- break;
451
- case "remover":
452
- await this.setCollectionRemover(key, value.value);
453
- default:
454
- await this.setCollectionSetter(key, value.value);
455
- break;
456
- }
457
- }
458
- else if (Array.isArray(value) && value.length > 0) {
459
- await this.setCollectionSetter(key, value);
460
- }
461
- else if (value !== undefined && value !== null && value !== "") {
462
- await this.setProperty(key, value);
463
- }
464
- }
465
- }
466
- await this.getData();
467
- }
468
- /**
469
- * Get the subject entity with all the properties & collection populated.
470
- *
471
- * @returns The subject entity.
472
- *
473
- * @throws Will throw an error if the subject entity cannot be converted to a subject class, or if the data of the subject entity cannot be gotten.
474
- */
475
- async get() {
476
- __classPrivateFieldSet(this, _SubjectEntity_subjectClassName, await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").stringOrTemplateObjectToSubjectClassName(this), "f");
477
- return await this.getData();
478
- }
479
- /**
480
- * Delete the subject entity.
481
- * This method will remove the subject from the perspective.
482
- *
483
- * @throws Will throw an error if the subject entity cannot be removed.
484
- */
485
- async delete() {
486
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").removeSubject(this, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"));
487
- }
488
- /** Query builder for SubjectEntity queries.
489
- * Allows building queries with a fluent interface and either running them once
490
- * or subscribing to updates.
491
- */
492
- static query(perspective, query) {
493
- return new SubjectQueryBuilder(perspective, this, query);
494
- }
495
- }
496
- _SubjectEntity_baseExpression = new WeakMap(), _SubjectEntity_subjectClassName = new WeakMap(), _SubjectEntity_source = new WeakMap(), _SubjectEntity_perspective = new WeakMap();
497
- SubjectEntity.classNamesByClass = new WeakMap();
498
- /** Query builder for SubjectEntity queries.
499
- * Allows building queries with a fluent interface and either running them once
500
- * or subscribing to updates.
501
- */
502
- export class SubjectQueryBuilder {
503
- constructor(perspective, ctor, query) {
504
- this.queryParams = {};
505
- this.perspective = perspective;
506
- this.ctor = ctor;
507
- if (query)
508
- this.queryParams = query;
509
- }
510
- where(conditions) {
511
- this.queryParams.where = conditions;
512
- return this;
513
- }
514
- order(orderBy) {
515
- this.queryParams.order = orderBy;
516
- return this;
517
- }
518
- limit(limit) {
519
- this.queryParams.limit = limit;
520
- return this;
521
- }
522
- offset(offset) {
523
- this.queryParams.offset = offset;
524
- return this;
525
- }
526
- source(source) {
527
- this.queryParams.source = source;
528
- return this;
529
- }
530
- properties(properties) {
531
- this.queryParams.properties = properties;
532
- return this;
533
- }
534
- collections(collections) {
535
- this.queryParams.collections = collections;
536
- return this;
537
- }
538
- /** Execute the query once and return the results */
539
- async get() {
540
- const query = await this.ctor.queryToProlog(this.perspective, this.queryParams);
541
- const result = await this.perspective.infer(query);
542
- const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
543
- return results;
544
- }
545
- /** Subscribe to the query and receive updates when results change */
546
- async subscribe(callback) {
547
- const query = await this.ctor.queryToProlog(this.perspective, this.queryParams);
548
- const subscription = await this.perspective.subscribeInfer(query);
549
- const processResults = async (result) => {
550
- const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, result);
551
- callback(results);
552
- };
553
- subscription.onResult(processResults);
554
- const { results } = await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, subscription.result);
555
- return results;
556
- }
557
- async count() {
558
- const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams);
559
- const result = await this.perspective.infer(query);
560
- return result?.[0]?.TotalCount || 0;
561
- }
562
- async countSubscribe(callback) {
563
- const query = await this.ctor.countQueryToProlog(this.perspective, this.queryParams);
564
- const subscription = await this.perspective.subscribeInfer(query);
565
- const processResults = async (result) => {
566
- const newCount = result?.[0]?.TotalCount || 0;
567
- callback(newCount);
568
- };
569
- subscription.onResult(processResults);
570
- return subscription.result?.[0]?.TotalCount || 0;
571
- }
572
- async paginate(pageSize, pageNumber) {
573
- const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
574
- const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery);
575
- const result = await this.perspective.infer(prologQuery);
576
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, result));
577
- return { results, totalCount, pageSize, pageNumber };
578
- }
579
- async paginateSubscribe(pageSize, pageNumber, callback) {
580
- const paginationQuery = { ...(this.queryParams || {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
581
- const prologQuery = await this.ctor.queryToProlog(this.perspective, paginationQuery);
582
- const subscription = await this.perspective.subscribeInfer(prologQuery);
583
- const processResults = async (r) => {
584
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, this.queryParams, r));
585
- callback({ results, totalCount, pageSize, pageNumber });
586
- };
587
- subscription.onResult(processResults);
588
- const { results, totalCount } = (await this.ctor.instancesFromPrologResult(this.perspective, paginationQuery, subscription.result));
589
- return { results, totalCount, pageSize, pageNumber };
590
- }
591
- }