@coasys/ad4m 0.10.1-rc9-dev → 0.10.1-release-candidate-2

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.
Files changed (61) hide show
  1. package/lib/index.cjs +3179 -811
  2. package/lib/index.js +3171 -807
  3. package/lib/src/Literal.js +4 -1
  4. package/lib/src/ai/AIClient.d.ts +1 -1
  5. package/lib/src/ai/AIClient.js +6 -6
  6. package/lib/src/ai/AIResolver.d.ts +1 -1
  7. package/lib/src/ai/AIResolver.js +7 -4
  8. package/lib/src/index.d.ts +4 -3
  9. package/lib/src/index.js +4 -3
  10. package/lib/src/model/Ad4mModel.d.ts +609 -0
  11. package/lib/src/model/Ad4mModel.js +1048 -0
  12. package/lib/src/{subject → model}/Subject.d.ts +2 -2
  13. package/lib/src/{subject → model}/Subject.js +18 -18
  14. package/lib/src/model/decorators.d.ts +502 -0
  15. package/lib/src/model/decorators.js +683 -0
  16. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +2 -2
  17. package/lib/src/neighbourhood/NeighbourhoodClient.js +16 -10
  18. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -2
  19. package/lib/src/neighbourhood/NeighbourhoodProxy.js +4 -4
  20. package/lib/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  21. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +31 -0
  22. package/lib/src/neighbourhood/NeighbourhoodResolver.d.ts +2 -2
  23. package/lib/src/neighbourhood/NeighbourhoodResolver.js +6 -4
  24. package/lib/src/perspectives/PerspectiveClient.d.ts +18 -11
  25. package/lib/src/perspectives/PerspectiveClient.js +116 -49
  26. package/lib/src/perspectives/PerspectiveProxy.d.ts +471 -54
  27. package/lib/src/perspectives/PerspectiveProxy.js +579 -64
  28. package/lib/src/perspectives/PerspectiveResolver.d.ts +23 -9
  29. package/lib/src/perspectives/PerspectiveResolver.js +140 -46
  30. package/lib/src/runtime/RuntimeClient.d.ts +5 -1
  31. package/lib/src/runtime/RuntimeClient.js +48 -0
  32. package/lib/src/runtime/RuntimeResolver.d.ts +24 -0
  33. package/lib/src/runtime/RuntimeResolver.js +117 -0
  34. package/lib/src/schema.gql +25 -11
  35. package/lib/src/typeDefs.js +25 -11
  36. package/package.json +2 -1
  37. package/src/Literal.ts +4 -1
  38. package/src/ai/AIClient.ts +6 -6
  39. package/src/ai/AIResolver.ts +6 -3
  40. package/src/index.ts +4 -3
  41. package/src/model/Ad4mModel.ts +1206 -0
  42. package/src/{subject → model}/Subject.ts +16 -16
  43. package/src/{subject/SDNADecorators.ts → model/decorators.ts} +384 -50
  44. package/src/neighbourhood/NeighbourhoodClient.ts +16 -10
  45. package/src/neighbourhood/NeighbourhoodProxy.test.ts +45 -0
  46. package/src/neighbourhood/NeighbourhoodProxy.ts +4 -4
  47. package/src/neighbourhood/NeighbourhoodResolver.ts +2 -2
  48. package/src/perspectives/PerspectiveClient.ts +122 -51
  49. package/src/perspectives/PerspectiveProxy.ts +642 -77
  50. package/src/perspectives/PerspectiveResolver.ts +126 -23
  51. package/src/runtime/RuntimeClient.ts +52 -1
  52. package/src/runtime/RuntimeResolver.ts +77 -0
  53. package/lib/src/subject/SDNADecorators.d.ts +0 -188
  54. package/lib/src/subject/SDNADecorators.js +0 -360
  55. package/lib/src/subject/SubjectEntity.d.ts +0 -110
  56. package/lib/src/subject/SubjectEntity.js +0 -288
  57. package/src/subject/SubjectEntity.ts +0 -336
  58. package/yarn-error.log +0 -90
  59. /package/lib/src/{subject → model}/util.d.ts +0 -0
  60. /package/lib/src/{subject → model}/util.js +0 -0
  61. /package/src/{subject → model}/util.ts +0 -0
@@ -1,288 +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_subjectClass, _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
- /**
18
- * Class representing a subject entity.
19
- * 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.
20
- */
21
- export class SubjectEntity {
22
- /**
23
- * Constructs a new subject.
24
- * @param perspective - The perspective that the subject belongs to.
25
- * @param baseExpression - The base expression of the subject.
26
- * @param soruce - The source of the subject, the expression this instance is linked too.
27
- */
28
- constructor(perspective, baseExpression, source) {
29
- _SubjectEntity_baseExpression.set(this, void 0);
30
- _SubjectEntity_subjectClass.set(this, void 0);
31
- _SubjectEntity_source.set(this, void 0);
32
- _SubjectEntity_perspective.set(this, void 0);
33
- __classPrivateFieldSet(this, _SubjectEntity_baseExpression, baseExpression ? baseExpression : Literal.from(makeRandomPrologAtom(24)).toUrl(), "f");
34
- __classPrivateFieldSet(this, _SubjectEntity_perspective, perspective, "f");
35
- __classPrivateFieldSet(this, _SubjectEntity_source, source || "ad4m://self", "f");
36
- }
37
- /**
38
- * Gets the base expression of the subject.
39
- */
40
- get baseExpression() {
41
- return __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f");
42
- }
43
- /**
44
- * Protected getter for the perspective.
45
- * Allows subclasses to access the perspective while keeping it private from external code.
46
- */
47
- get perspective() {
48
- return __classPrivateFieldGet(this, _SubjectEntity_perspective, "f");
49
- }
50
- async getData(id) {
51
- const tempId = id ?? __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f");
52
- let data = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").getSubjectData(__classPrivateFieldGet(this, _SubjectEntity_subjectClass, "f"), tempId);
53
- Object.assign(this, data);
54
- __classPrivateFieldSet(this, _SubjectEntity_baseExpression, tempId, "f");
55
- return this;
56
- }
57
- async setProperty(key, value) {
58
- const setters = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClass, "f")}", C), property_setter(C, "${key}", Setter)`);
59
- if (setters && setters.length > 0) {
60
- const actions = eval(setters[0].Setter);
61
- const resolveLanguageResults = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClass, "f")}", C), property_resolve_language(C, "${key}", Language)`);
62
- let resolveLanguage;
63
- if (resolveLanguageResults && resolveLanguageResults.length > 0) {
64
- resolveLanguage = resolveLanguageResults[0].Language;
65
- }
66
- if (resolveLanguage) {
67
- value = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").createExpression(value, resolveLanguage);
68
- }
69
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value }]);
70
- }
71
- }
72
- async setCollectionSetter(key, value) {
73
- let collectionSetters = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClass, "f")}", C), collection_setter(C, "${singularToPlural(key)}", Setter)`);
74
- if (!collectionSetters)
75
- collectionSetters = [];
76
- if (collectionSetters.length > 0) {
77
- const actions = eval(collectionSetters[0].Setter);
78
- if (value) {
79
- if (Array.isArray(value)) {
80
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), value.map(v => ({ name: "value", value: v })));
81
- }
82
- else {
83
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value }]);
84
- }
85
- }
86
- }
87
- }
88
- async setCollectionAdder(key, value) {
89
- let adders = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClass, "f")}", C), collection_adder(C, "${singularToPlural(key)}", Adder)`);
90
- if (!adders)
91
- adders = [];
92
- if (adders.length > 0) {
93
- const actions = eval(adders[0].Adder);
94
- if (value) {
95
- if (Array.isArray(value)) {
96
- await Promise.all(value.map(v => __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value: v }])));
97
- }
98
- else {
99
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value }]);
100
- }
101
- }
102
- }
103
- }
104
- async setCollectionRemover(key, value) {
105
- let removers = await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").infer(`subject_class("${__classPrivateFieldGet(this, _SubjectEntity_subjectClass, "f")}", C), collection_remover(C, "${singularToPlural(key)}", Remover)`);
106
- if (!removers)
107
- removers = [];
108
- if (removers.length > 0) {
109
- const actions = eval(removers[0].Remover);
110
- if (value) {
111
- if (Array.isArray(value)) {
112
- await Promise.all(value.map(v => __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value: v }])));
113
- }
114
- else {
115
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").executeAction(actions, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"), [{ name: "value", value }]);
116
- }
117
- }
118
- }
119
- }
120
- /**
121
- * Save the subject entity.
122
- * 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".
123
- *
124
- * If a property has an action, it will perform the action (Only for collections).
125
- * If a property is an array and is not empty, it will set the collection.
126
- * If a property is not undefined, not null, and not an empty string, it will set the property.
127
- *
128
- *
129
- * @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.
130
- */
131
- async save() {
132
- __classPrivateFieldSet(this, _SubjectEntity_subjectClass, await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").stringOrTemplateObjectToSubjectClass(this), "f");
133
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").createSubject(this, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"));
134
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").add(new Link({
135
- source: __classPrivateFieldGet(this, _SubjectEntity_source, "f"),
136
- predicate: "ad4m://has_child",
137
- target: this.baseExpression,
138
- }));
139
- await this.update();
140
- }
141
- /**
142
- * Update the subject entity.
143
- *
144
- * It will iterate over the properties of the subject entity.
145
- *
146
- * If a property has an action, it will perform the action (Only for collections).
147
- * If a property is an array and is not empty, it will set the collection.
148
- * If a property is not undefined, not null, and not an empty string, it will set the property.
149
- *
150
- * @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.
151
- */
152
- async update() {
153
- __classPrivateFieldSet(this, _SubjectEntity_subjectClass, await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").stringOrTemplateObjectToSubjectClass(this), "f");
154
- const entries = Object.entries(this);
155
- for (const [key, value] of entries) {
156
- if (value !== undefined && value !== null) {
157
- if (value?.action) {
158
- switch (value.action) {
159
- case 'setter':
160
- await this.setCollectionSetter(key, value.value);
161
- break;
162
- case "adder":
163
- await this.setCollectionAdder(key, value.value);
164
- break;
165
- case 'remover':
166
- await this.setCollectionRemover(key, value.value);
167
- default:
168
- await this.setCollectionSetter(key, value.value);
169
- break;
170
- }
171
- }
172
- else if (Array.isArray(value) && value.length > 0) {
173
- await this.setCollectionSetter(key, value);
174
- }
175
- else if (value !== undefined && value !== null && value !== "") {
176
- await this.setProperty(key, value);
177
- }
178
- }
179
- }
180
- await this.getData();
181
- }
182
- /**
183
- * Get the subject entity with all the properties & collection populated.
184
- *
185
- * @returns The subject entity.
186
- *
187
- * @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.
188
- */
189
- async get() {
190
- __classPrivateFieldSet(this, _SubjectEntity_subjectClass, await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").stringOrTemplateObjectToSubjectClass(this), "f");
191
- return await this.getData();
192
- }
193
- /**
194
- * Delete the subject entity.
195
- * This method will remove the subject from the perspective.
196
- *
197
- * @throws Will throw an error if the subject entity cannot be removed.
198
- */
199
- async delete() {
200
- await __classPrivateFieldGet(this, _SubjectEntity_perspective, "f").removeSubject(this, __classPrivateFieldGet(this, _SubjectEntity_baseExpression, "f"));
201
- }
202
- /**
203
- * Get all the subject entities of the subject class.
204
- *
205
- * NOTE: this is a static method and should be called on the class itself.
206
- *
207
- * @param perspective - The perspective that the subject belongs to.
208
- *
209
- * @returns The subject entities.
210
- *
211
- * @throws Will throw an error if the subject entity cannot be converted to a subject class, or if the subject proxies cannot be gotten.
212
- */
213
- static async all(perspective) {
214
- let subjectClass = await perspective.stringOrTemplateObjectToSubjectClass(this);
215
- const proxies = await perspective.getAllSubjectProxies(subjectClass);
216
- const instances = [];
217
- if (proxies) {
218
- for (const proxy of proxies) {
219
- // @ts-ignore
220
- const instance = new this(perspective, proxy.X);
221
- instances.push(await instance.get());
222
- }
223
- return instances;
224
- }
225
- return [];
226
- }
227
- /**
228
- * Query the subject entities of the subject class.
229
- *
230
- * NOTE: this is a static method and should be called on the class itself.
231
- *
232
- * @param perspective - The perspective that the subject belongs to.
233
- * @param query - The query of the subject entities.
234
- *
235
- * @returns The subject entities.
236
- *
237
- * @throws Will throw an error if the subject entity cannot be converted to a subject class, or if the query cannot be inferred, or if the data of the subject entities cannot be gotten.
238
- */
239
- static async query(perspective, query) {
240
- const source = query?.source || "ad4m://self";
241
- let subjectClass = await perspective.stringOrTemplateObjectToSubjectClass(this);
242
- let res = [];
243
- let instanceConditions = `subject_class("${subjectClass}", C), instance(C, Base), link("${source}", Predicate, Base, Timestamp, Author)`;
244
- if (query) {
245
- if (query.where) {
246
- if (query.where["condition"]) {
247
- instanceConditions += ", " + query.where["condition"];
248
- }
249
- else {
250
- const pairs = Object.entries(query.where);
251
- for (let p of pairs) {
252
- const propertyName = p[0];
253
- const propertyValue = p[1];
254
- instanceConditions += `, property_getter(C, Base, "${propertyName}", "${propertyValue}")`;
255
- }
256
- }
257
- }
258
- try {
259
- const queryResponse = (await perspective.infer(`findall([Timestamp, Base], (${instanceConditions}), AllData), sort(AllData, SortedData), length(SortedData, DataLength).`))[0];
260
- if (queryResponse.DataLength >= query.size) {
261
- const mainQuery = `findall([Timestamp, Base], (${instanceConditions}), AllData), sort(AllData, SortedData), reverse(SortedData, ReverseSortedData), paginate(ReverseSortedData, ${query.page}, ${query.size}, PageData).`;
262
- res = await perspective.infer(mainQuery);
263
- res = res[0].PageData.map(r => ({
264
- Base: r[1],
265
- Timestamp: r[0]
266
- }));
267
- }
268
- else {
269
- res = await perspective.infer(instanceConditions);
270
- }
271
- }
272
- catch (e) {
273
- console.log("Query failed", e);
274
- }
275
- }
276
- else {
277
- res = await perspective.infer(instanceConditions);
278
- }
279
- if (!res)
280
- return [];
281
- const data = await Promise.all(res.map(async (result) => {
282
- const instance = new this(perspective, result.Base);
283
- return await instance.get();
284
- }));
285
- return data;
286
- }
287
- }
288
- _SubjectEntity_baseExpression = new WeakMap(), _SubjectEntity_subjectClass = new WeakMap(), _SubjectEntity_source = new WeakMap(), _SubjectEntity_perspective = new WeakMap();
@@ -1,336 +0,0 @@
1
- import { Literal } from "../Literal";
2
- import { Link } from "../links/Links";
3
- import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
4
- import { makeRandomPrologAtom } from "./SDNADecorators";
5
- import { singularToPlural } from "./util";
6
-
7
- export type QueryPartialEntity<T> = {
8
- [P in keyof T]?: T[P] | (() => string);
9
- };
10
-
11
-
12
- /**
13
- * Class representing a subject entity.
14
- * 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.
15
- */
16
- export class SubjectEntity {
17
- #baseExpression: string;
18
- #subjectClass: string;
19
- #source: string;
20
- #perspective: PerspectiveProxy
21
- author: string;
22
- timestamp: string;
23
-
24
-
25
- /**
26
- * Constructs a new subject.
27
- * @param perspective - The perspective that the subject belongs to.
28
- * @param baseExpression - The base expression of the subject.
29
- * @param soruce - The source of the subject, the expression this instance is linked too.
30
- */
31
- constructor(perspective: PerspectiveProxy, baseExpression?: string, source?: string) {
32
- this.#baseExpression = baseExpression ? baseExpression : Literal.from(makeRandomPrologAtom(24)).toUrl();
33
- this.#perspective = perspective;
34
- this.#source = source || "ad4m://self";
35
- }
36
-
37
- /**
38
- * Gets the base expression of the subject.
39
- */
40
- get baseExpression() {
41
- return this.#baseExpression
42
- }
43
-
44
- /**
45
- * Protected getter for the perspective.
46
- * Allows subclasses to access the perspective while keeping it private from external code.
47
- */
48
- protected get perspective(): PerspectiveProxy {
49
- return this.#perspective;
50
- }
51
-
52
- private async getData(id?: string) {
53
- const tempId = id ?? this.#baseExpression;
54
- let data = await this.#perspective.getSubjectData(this.#subjectClass, tempId)
55
- Object.assign(this, data);
56
- this.#baseExpression = tempId;
57
- return this
58
- }
59
-
60
- private async setProperty(key: string, value: any) {
61
- const setters = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property_setter(C, "${key}", Setter)`)
62
- if (setters && setters.length > 0) {
63
- const actions = eval(setters[0].Setter)
64
- const resolveLanguageResults = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property_resolve_language(C, "${key}", Language)`)
65
- let resolveLanguage
66
- if (resolveLanguageResults && resolveLanguageResults.length > 0) {
67
- resolveLanguage = resolveLanguageResults[0].Language
68
- }
69
-
70
- if (resolveLanguage) {
71
- value = await this.#perspective.createExpression(value, resolveLanguage)
72
- }
73
- await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }])
74
- }
75
- }
76
-
77
- private async setCollectionSetter(key: string, value: any) {
78
- let collectionSetters = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection_setter(C, "${singularToPlural(key)}", Setter)`)
79
- if (!collectionSetters) collectionSetters = []
80
-
81
- if (collectionSetters.length > 0) {
82
- const actions = eval(collectionSetters[0].Setter)
83
-
84
- if (value) {
85
- if (Array.isArray(value)) {
86
- await this.#perspective.executeAction(actions, this.#baseExpression, value.map(v => ({ name: "value", value: v })))
87
- } else {
88
- await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }])
89
- }
90
- }
91
- }
92
- }
93
-
94
- private async setCollectionAdder(key: string, value: any) {
95
- let adders = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection_adder(C, "${singularToPlural(key)}", Adder)`)
96
- if (!adders) adders = []
97
-
98
- if (adders.length > 0) {
99
- const actions = eval(adders[0].Adder)
100
- if (value) {
101
- if (Array.isArray(value)) {
102
- await Promise.all(value.map(v => this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value: v }])))
103
- } else {
104
- await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }])
105
- }
106
- }
107
- }
108
- }
109
-
110
- private async setCollectionRemover(key: string, value: any) {
111
- let removers = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection_remover(C, "${singularToPlural(key)}", Remover)`)
112
- if (!removers) removers = []
113
-
114
- if (removers.length > 0) {
115
- const actions = eval(removers[0].Remover)
116
- if (value) {
117
- if (Array.isArray(value)) {
118
- await Promise.all(value.map(v => this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value: v }])))
119
- } else {
120
- await this.#perspective.executeAction(actions, this.#baseExpression, [{ name: "value", value }])
121
- }
122
- }
123
- }
124
- }
125
-
126
- /**
127
- * Save the subject entity.
128
- * 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".
129
- *
130
- * If a property has an action, it will perform the action (Only for collections).
131
- * If a property is an array and is not empty, it will set the collection.
132
- * If a property is not undefined, not null, and not an empty string, it will set the property.
133
- *
134
- *
135
- * @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.
136
- */
137
- async save() {
138
- this.#subjectClass = await this.#perspective.stringOrTemplateObjectToSubjectClass(this)
139
-
140
- await this.#perspective.createSubject(this, this.#baseExpression);
141
-
142
- await this.#perspective.add(
143
- new Link({
144
- source: this.#source,
145
- predicate: "ad4m://has_child",
146
- target: this.baseExpression,
147
- })
148
- );
149
-
150
- await this.update()
151
- }
152
-
153
- /**
154
- * Update the subject entity.
155
- *
156
- * It will iterate over the properties of the subject entity.
157
- *
158
- * If a property has an action, it will perform the action (Only for collections).
159
- * If a property is an array and is not empty, it will set the collection.
160
- * If a property is not undefined, not null, and not an empty string, it will set the property.
161
- *
162
- * @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.
163
- */
164
- async update() {
165
- this.#subjectClass = await this.#perspective.stringOrTemplateObjectToSubjectClass(this)
166
-
167
- const entries = Object.entries(this);
168
-
169
- for (const [key, value] of entries) {
170
- if (value !== undefined && value !== null) {
171
- if (value?.action) {
172
- switch (value.action) {
173
- case 'setter':
174
- await this.setCollectionSetter(key, value.value)
175
- break;
176
- case "adder":
177
- await this.setCollectionAdder(key, value.value)
178
- break;
179
- case 'remover':
180
- await this.setCollectionRemover(key, value.value)
181
- default:
182
- await this.setCollectionSetter(key, value.value)
183
- break;
184
- }
185
- } else if (Array.isArray(value) && value.length > 0) {
186
- await this.setCollectionSetter(key, value)
187
- } else if (value !== undefined && value !== null && value !== "") {
188
- await this.setProperty(key, value);
189
- }
190
- }
191
- }
192
-
193
- await this.getData();
194
- }
195
-
196
- /**
197
- * Get the subject entity with all the properties & collection populated.
198
- *
199
- * @returns The subject entity.
200
- *
201
- * @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.
202
- */
203
- async get() {
204
- this.#subjectClass = await this.#perspective.stringOrTemplateObjectToSubjectClass(this)
205
-
206
- return await this.getData()
207
- }
208
-
209
-
210
- /**
211
- * Delete the subject entity.
212
- * This method will remove the subject from the perspective.
213
- *
214
- * @throws Will throw an error if the subject entity cannot be removed.
215
- */
216
- async delete() {
217
- await this.#perspective.removeSubject(this, this.#baseExpression);
218
- }
219
-
220
- /**
221
- * Get all the subject entities of the subject class.
222
- *
223
- * NOTE: this is a static method and should be called on the class itself.
224
- *
225
- * @param perspective - The perspective that the subject belongs to.
226
- *
227
- * @returns The subject entities.
228
- *
229
- * @throws Will throw an error if the subject entity cannot be converted to a subject class, or if the subject proxies cannot be gotten.
230
- */
231
- static async all(perspective: PerspectiveProxy) {
232
- let subjectClass = await perspective.stringOrTemplateObjectToSubjectClass(this)
233
- const proxies = await perspective.getAllSubjectProxies(subjectClass)
234
-
235
- const instances = []
236
-
237
- if (proxies) {
238
- for (const proxy of proxies) {
239
- // @ts-ignore
240
- const instance = new this(perspective, proxy.X)
241
- instances.push(await instance.get())
242
- }
243
-
244
- return instances;
245
- }
246
-
247
- return []
248
- }
249
-
250
- /**
251
- * Query the subject entities of the subject class.
252
- *
253
- * NOTE: this is a static method and should be called on the class itself.
254
- *
255
- * @param perspective - The perspective that the subject belongs to.
256
- * @param query - The query of the subject entities.
257
- *
258
- * @returns The subject entities.
259
- *
260
- * @throws Will throw an error if the subject entity cannot be converted to a subject class, or if the query cannot be inferred, or if the data of the subject entities cannot be gotten.
261
- */
262
- static async query(perspective: PerspectiveProxy, query?: SubjectEntityQueryParam) {
263
- const source = query?.source || "ad4m://self";
264
- let subjectClass = await perspective.stringOrTemplateObjectToSubjectClass(this)
265
-
266
- let res = [];
267
- let instanceConditions = `subject_class("${subjectClass}", C), instance(C, Base), link("${source}", Predicate, Base, Timestamp, Author)`
268
-
269
- if (query) {
270
- if(query.where) {
271
- if(query.where["condition"]) {
272
- instanceConditions += ", " + query.where["condition"]
273
- } else {
274
- const pairs = Object.entries(query.where);
275
- for(let p of pairs) {
276
- const propertyName = p[0];
277
- const propertyValue = p[1];
278
- instanceConditions += `, property_getter(C, Base, "${propertyName}", "${propertyValue}")`
279
- }
280
- }
281
- }
282
-
283
- try {
284
- const queryResponse = (await perspective.infer(`findall([Timestamp, Base], (${instanceConditions}), AllData), sort(AllData, SortedData), length(SortedData, DataLength).`))[0]
285
-
286
- if (queryResponse.DataLength >= query.size) {
287
- const mainQuery = `findall([Timestamp, Base], (${instanceConditions}), AllData), sort(AllData, SortedData), reverse(SortedData, ReverseSortedData), paginate(ReverseSortedData, ${query.page}, ${query.size}, PageData).`
288
-
289
- res = await perspective.infer(mainQuery);
290
-
291
- res = res[0].PageData.map(r => ({
292
- Base: r[1],
293
- Timestamp: r[0]
294
- }))
295
- } else {
296
- res = await perspective.infer(instanceConditions);
297
- }
298
- } catch (e) {
299
- console.log("Query failed", e);
300
- }
301
- } else {
302
- res = await perspective.infer(instanceConditions);
303
- }
304
-
305
- if (!res) return [];
306
-
307
- const data = await Promise.all(
308
- res.map(async (result) => {
309
- const instance = new this(perspective, result.Base)
310
-
311
- return await instance.get();
312
- })
313
- );
314
-
315
- return data;
316
- }
317
- }
318
-
319
- export type SubjectArray<T> = T[] | {
320
- action: 'setter' | 'adder' | 'remover',
321
- value: T[]
322
- }
323
-
324
- export type SubjectEntityQueryParam = {
325
- // The source of the query.
326
- source?: string;
327
-
328
- // The size of the query.
329
- size?: number;
330
-
331
- // The page of the query.
332
- page?: number;
333
-
334
- // conditions on properties
335
- where?: { condition?: string } | object;
336
- }