@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,360 +0,0 @@
1
- import { Subject } from "./Subject";
2
- import { capitalize, propertyNameToSetterName, singularToPlural, stringifyObjectLiteral } from "./util";
3
- export class PerspectiveAction {
4
- }
5
- export function addLink(source, predicate, target) {
6
- return {
7
- action: "addLink",
8
- source,
9
- predicate,
10
- target,
11
- };
12
- }
13
- export function hasLink(predicate) {
14
- return `triple(this, "${predicate}", _)`;
15
- }
16
- /**
17
- * Decorator for querying instances of a subject class.
18
- *
19
- * @category Decorators
20
- *
21
- * @description
22
- * NOTE: Only works on methods that return a promise and will throw an error if not used on a method that returns a promise.
23
- * This will allow you to query for instances of a subject class with custom clauses within the instance clauses.
24
- *
25
- * @example
26
- * // Usage with where clause
27
- * InstanceQuery({ where: { name: "John" }}) // this will return all the properties of the subject class with the name "John"
28
- *
29
- * @example
30
- * // Usage with condition clause
31
- * InstanceQuery({ condition: "triple(Instance, 'age', Age), Age > 18" }) // this will return all the properties of the subject class with the age greater than 18
32
- *
33
- * @param {Object} [options] - Query options.
34
- */
35
- export function InstanceQuery(options) {
36
- return function (target, key, descriptor) {
37
- const originalMethod = descriptor.value;
38
- if (typeof originalMethod !== "function") {
39
- throw new Error("InstanceQuery decorator can only be applied to methods");
40
- }
41
- descriptor.value = async function (perspective) {
42
- let instances = [];
43
- //@ts-ignore
44
- let subjectClassName = target.name;
45
- let query = `subject_class("${subjectClassName}", C), instance(C, Instance)`;
46
- if (options && options.where) {
47
- for (let prop in options.where) {
48
- let value = options.where[prop];
49
- query += `, property_getter(C, Instance, "${prop}", "${value}")`;
50
- }
51
- }
52
- if (options && options.condition) {
53
- query += ', ' + options.condition;
54
- }
55
- let results = await perspective.infer(query);
56
- if (results == false) {
57
- return instances;
58
- }
59
- if (typeof results == "string") {
60
- throw results;
61
- }
62
- for (let result of results) {
63
- let instance = result.Instance;
64
- let subject = new Subject(perspective, instance, subjectClassName);
65
- await subject.init();
66
- instances.push(subject);
67
- }
68
- return instances;
69
- };
70
- };
71
- }
72
- /**
73
- * Decorator for defining properties of a subject class.
74
- *
75
- * @category Decorators
76
- *
77
- * @description
78
- * This will allow you to define properties with different conditions and how they would be defined in proflog engine.
79
- *
80
- * - All properties must have a `through` option which is the predicate of the property.
81
- * -e If the property is required, it must have an `initial` option which is the initial value of the property.
82
- * - If the property is writable, it will have a setter in prolog engine. A custom setter can be defined with the `setter` option.
83
- * - If resolveLanguage is defined, you can use the default `Literal` Language or use your custom language address that can be used to store the property.
84
- * - If a custom getter is defined, it will be used to get the value of the property in prolog engine. If not, the default getter will be used.
85
- * - If local is defined, the property will be stored locally in the perspective and not in the network. This is useful for properties that are not meant to be shared with the network
86
- *
87
- * @example
88
- * // Usage
89
- * SubjectProperty({ through: "ad4m://name", initial: "John", required: true }) // this will define a property with the name "ad4m://name" and the initial value "John"
90
- *
91
- * @param {PropertyOptions} [opts] - Property options.
92
- */
93
- export function SubjectProperty(opts) {
94
- return function (target, key) {
95
- if (opts.required && !opts.initial) {
96
- throw new Error("SubjectProperty requires an 'initial' option if 'required' is true");
97
- }
98
- if (!opts.through && !opts.getter) {
99
- throw new Error("SubjectProperty requires either 'through' or 'getter' option");
100
- }
101
- target["__properties"] = target["__properties"] || {};
102
- target["__properties"][key] = target["__properties"][key] || {};
103
- target["__properties"][key] = { ...target["__properties"][key], ...opts };
104
- if (opts.writable) {
105
- const value = key;
106
- target[`set${capitalize(value)}`] = () => { };
107
- }
108
- Object.defineProperty(target, key, { configurable: true, writable: true });
109
- };
110
- }
111
- /**
112
- * Decorator for defining flags of a subject class
113
- *
114
- * @category Decorators
115
- *
116
- * @description
117
- * The idea behind flag decorator is to define a property that is required and has an initial value.
118
- * This will allow you to define a strict instance query. This behaviour can also be achieved with the `SubjectProperty` decorator but the `SubjectFlag` decorator is a shorthand for that.
119
- *
120
- * NOTE: Use of Flag is discouraged and should be used only when necessary.
121
- *
122
- * - All properties must have a `through` & `initial` option which is the predicate of the property.
123
- *
124
- * @example
125
- * // Usage
126
- * SubjectFlag({ through: "ad4m://name", value: "John" }) // this will define a flag with the name "ad4m://name" and the initial value "John"
127
- *
128
- * @param {FlagOptions} [opts] Flag options.
129
- */
130
- export function SubjectFlag(opts) {
131
- return function (target, key) {
132
- if (!opts.through && !opts.value) {
133
- throw new Error("SubjectFlag requires a 'through' and 'value' option");
134
- }
135
- if (!opts.through) {
136
- throw new Error("SubjectFlag requires a 'through' option");
137
- }
138
- if (!opts.value) {
139
- throw new Error("SubjectFlag requires a 'value' option");
140
- }
141
- target["__properties"] = target["__properties"] || {};
142
- target["__properties"][key] = target["__properties"][key] || {};
143
- target["__properties"][key] = {
144
- ...target["__properties"][key],
145
- through: opts.through,
146
- required: true,
147
- initial: opts.value,
148
- flag: true
149
- };
150
- // @ts-ignore
151
- target[key] = opts.value;
152
- Object.defineProperty(target, key, { configurable: true, writable: true });
153
- };
154
- }
155
- /**
156
- * Decorator for defining collections of a subject class.
157
- *
158
- * @category Decorators
159
- *
160
- * @description
161
- * This will allow you to define collections with different conditions and how they would be defined in proflog engine.
162
- *
163
- * NOTE: The property needs to be an array for it to picked up during the initialization phase.
164
- *
165
- * - All collections must have a `through` option which is the predicate of the collection.
166
- * - If the collection has a `where` option, it can be used to define a custom condition for the collection.
167
- * - If the collection has a `local` option, the collection will be stored locally in the perspective and not in the network. This is useful for collections that are not meant to be shared with the network.
168
- *
169
- * @example
170
- * // Usage
171
- * SubjectCollection({ through: "ad4m://friends" }) // this will define a collection with the name "ad4m://friends"
172
- *
173
- * @param opts Collection options.
174
- */
175
- export function SubjectCollection(opts) {
176
- return function (target, key) {
177
- target["__collections"] = target["__collections"] || {};
178
- target["__collections"][key] = opts;
179
- const value = key;
180
- target[`add${capitalize(value)}`] = () => { };
181
- target[`remove${capitalize(value)}`] = () => { };
182
- target[`setCollection${capitalize(value)}`] = () => { };
183
- Object.defineProperty(target, key, { configurable: true, writable: true });
184
- };
185
- }
186
- export function makeRandomPrologAtom(length) {
187
- let result = '';
188
- let characters = 'abcdefghijklmnopqrstuvwxyz';
189
- let charactersLength = characters.length;
190
- for (let i = 0; i < length; i++) {
191
- result += characters.charAt(Math.floor(Math.random() * charactersLength));
192
- }
193
- return result;
194
- }
195
- /**
196
- * Decorator for defining an SDNA class.
197
- *
198
- * @category Decorators
199
- *
200
- * @description
201
- * This will create a new SDNA class with the given name and add custom methods to generate the SDNA for the class, for this to work the class need to have the properties defined using the decorators like `SubjectProperty`.
202
- *
203
- * Note: This decorator is required for the class to be picked up during the initialization phase.
204
- *
205
- * @example
206
- * // Usage
207
- * SDNAClass({ name: "Person" }) // this will create a new SDNA class with the name "Person"
208
- *
209
- * @param opts SDNA class options.
210
- */
211
- export function SDNAClass(opts) {
212
- return function (target) {
213
- target.prototype.className = opts.name;
214
- target.className = opts.name;
215
- target.generateSDNA = function () {
216
- let sdna = "";
217
- let subjectName = opts.name;
218
- let obj = target.prototype;
219
- let uuid = makeRandomPrologAtom(8);
220
- sdna += `subject_class("${subjectName}", ${uuid}).\n`;
221
- let classRemoverActions = [];
222
- let constructorActions = [];
223
- if (obj.subjectConstructor && obj.subjectConstructor.length) {
224
- constructorActions = constructorActions.concat(obj.subjectConstructor);
225
- }
226
- let instanceConditions = [];
227
- if (obj.isSubjectInstance && obj.isSubjectInstance.length) {
228
- instanceConditions = instanceConditions.concat(obj.isSubjectInstance);
229
- }
230
- let propertiesCode = [];
231
- let properties = obj.__properties || {};
232
- for (let property in properties) {
233
- let propertyCode = `property(${uuid}, "${property}").\n`;
234
- let { through, initial, required, resolveLanguage, writable, flag, getter, setter, local } = properties[property];
235
- if (resolveLanguage) {
236
- propertyCode += `property_resolve(${uuid}, "${property}").\n`;
237
- propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`;
238
- }
239
- if (getter) {
240
- propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${getter}.\n`;
241
- }
242
- else if (through) {
243
- propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`;
244
- if (required) {
245
- if (flag) {
246
- instanceConditions.push(`triple(Base, "${through}", "${initial}")`);
247
- }
248
- else {
249
- instanceConditions.push(`triple(Base, "${through}", _)`);
250
- }
251
- }
252
- }
253
- if (setter) {
254
- propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${setter}.\n`;
255
- }
256
- else if (writable) {
257
- let setter = obj[propertyNameToSetterName(property)];
258
- if (typeof setter === "function") {
259
- let action = [{
260
- action: "setSingleTarget",
261
- source: "this",
262
- predicate: through,
263
- target: "value",
264
- ...(local && { local: true })
265
- }];
266
- propertyCode += `property_setter(${uuid}, "${property}", '${stringifyObjectLiteral(action)}').\n`;
267
- }
268
- }
269
- propertiesCode.push(propertyCode);
270
- if (initial) {
271
- constructorActions.push({
272
- action: "addLink",
273
- source: "this",
274
- predicate: through,
275
- target: initial,
276
- });
277
- classRemoverActions.push({
278
- action: "removeLink",
279
- source: "this",
280
- predicate: through,
281
- target: initial,
282
- });
283
- }
284
- }
285
- let collectionsCode = [];
286
- let collections = obj.__collections || {};
287
- for (let collection in collections) {
288
- let collectionCode = `collection(${uuid}, "${collection}").\n`;
289
- let { through, where, local } = collections[collection];
290
- if (through) {
291
- if (where) {
292
- if (!where.isInstance && !where.condition) {
293
- throw "'where' needs one of 'isInstance' or 'condition'";
294
- }
295
- let conditions = [];
296
- if (where.isInstance) {
297
- let otherClass;
298
- if (where.isInstance.name) {
299
- otherClass = where.isInstance.name;
300
- }
301
- else {
302
- otherClass = where.isInstance;
303
- }
304
- conditions.push(`instance(OtherClass, Target), subject_class("${otherClass}", OtherClass)`);
305
- }
306
- if (where.condition) {
307
- conditions.push(where.condition);
308
- }
309
- const conditionString = conditions.join(", ");
310
- collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- setof(Target, (triple(Base, "${through}", Target), ${conditionString}), List).\n`;
311
- }
312
- else {
313
- collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
314
- }
315
- let collectionAdderAction = [{
316
- action: "addLink",
317
- source: "this",
318
- predicate: through,
319
- target: "value",
320
- ...(local && { local: true })
321
- }];
322
- let collectionRemoverAction = [{
323
- action: "removeLink",
324
- source: "this",
325
- predicate: through,
326
- target: "value",
327
- }];
328
- let collectionSetterAction = [{
329
- action: "collectionSetter",
330
- source: "this",
331
- predicate: through,
332
- target: "value",
333
- ...(local && { local: true })
334
- }];
335
- collectionCode += `collection_adder(${uuid}, "${singularToPlural(collection)}", '${stringifyObjectLiteral(collectionAdderAction)}').\n`;
336
- collectionCode += `collection_remover(${uuid}, "${singularToPlural(collection)}", '${stringifyObjectLiteral(collectionRemoverAction)}').\n`;
337
- collectionCode += `collection_setter(${uuid}, "${singularToPlural(collection)}", '${stringifyObjectLiteral(collectionSetterAction)}').\n`;
338
- }
339
- collectionsCode.push(collectionCode);
340
- }
341
- let subjectContructorJSONString = stringifyObjectLiteral(constructorActions);
342
- sdna += `constructor(${uuid}, '${subjectContructorJSONString}').\n`;
343
- if (instanceConditions.length > 0) {
344
- let instanceConditionProlog = instanceConditions.join(", ");
345
- sdna += `instance(${uuid}, Base) :- ${instanceConditionProlog}.\n`;
346
- sdna += "\n";
347
- }
348
- sdna += `destructor(${uuid}, '${stringifyObjectLiteral(classRemoverActions)}').\n`;
349
- sdna += "\n";
350
- sdna += propertiesCode.join("\n");
351
- sdna += "\n";
352
- sdna += collectionsCode.join("\n");
353
- return {
354
- sdna,
355
- name: subjectName
356
- };
357
- };
358
- Object.defineProperty(target, 'type', { configurable: true });
359
- };
360
- }
@@ -1,110 +0,0 @@
1
- import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
2
- export type QueryPartialEntity<T> = {
3
- [P in keyof T]?: T[P] | (() => string);
4
- };
5
- /**
6
- * Class representing a subject entity.
7
- * 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.
8
- */
9
- export declare class SubjectEntity {
10
- #private;
11
- author: string;
12
- timestamp: string;
13
- /**
14
- * Constructs a new subject.
15
- * @param perspective - The perspective that the subject belongs to.
16
- * @param baseExpression - The base expression of the subject.
17
- * @param soruce - The source of the subject, the expression this instance is linked too.
18
- */
19
- constructor(perspective: PerspectiveProxy, baseExpression?: string, source?: string);
20
- /**
21
- * Gets the base expression of the subject.
22
- */
23
- get baseExpression(): string;
24
- /**
25
- * Protected getter for the perspective.
26
- * Allows subclasses to access the perspective while keeping it private from external code.
27
- */
28
- protected get perspective(): PerspectiveProxy;
29
- private getData;
30
- private setProperty;
31
- private setCollectionSetter;
32
- private setCollectionAdder;
33
- private setCollectionRemover;
34
- /**
35
- * Save the subject entity.
36
- * 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".
37
- *
38
- * If a property has an action, it will perform the action (Only for collections).
39
- * If a property is an array and is not empty, it will set the collection.
40
- * If a property is not undefined, not null, and not an empty string, it will set the property.
41
- *
42
- *
43
- * @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.
44
- */
45
- save(): Promise<void>;
46
- /**
47
- * Update the subject entity.
48
- *
49
- * It will iterate over the properties of the subject entity.
50
- *
51
- * If a property has an action, it will perform the action (Only for collections).
52
- * If a property is an array and is not empty, it will set the collection.
53
- * If a property is not undefined, not null, and not an empty string, it will set the property.
54
- *
55
- * @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.
56
- */
57
- update(): Promise<void>;
58
- /**
59
- * Get the subject entity with all the properties & collection populated.
60
- *
61
- * @returns The subject entity.
62
- *
63
- * @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.
64
- */
65
- get(): Promise<this>;
66
- /**
67
- * Delete the subject entity.
68
- * This method will remove the subject from the perspective.
69
- *
70
- * @throws Will throw an error if the subject entity cannot be removed.
71
- */
72
- delete(): Promise<void>;
73
- /**
74
- * Get all the subject entities of the subject class.
75
- *
76
- * NOTE: this is a static method and should be called on the class itself.
77
- *
78
- * @param perspective - The perspective that the subject belongs to.
79
- *
80
- * @returns The subject entities.
81
- *
82
- * @throws Will throw an error if the subject entity cannot be converted to a subject class, or if the subject proxies cannot be gotten.
83
- */
84
- static all(perspective: PerspectiveProxy): Promise<any[]>;
85
- /**
86
- * Query the subject entities of the subject class.
87
- *
88
- * NOTE: this is a static method and should be called on the class itself.
89
- *
90
- * @param perspective - The perspective that the subject belongs to.
91
- * @param query - The query of the subject entities.
92
- *
93
- * @returns The subject entities.
94
- *
95
- * @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.
96
- */
97
- static query(perspective: PerspectiveProxy, query?: SubjectEntityQueryParam): Promise<SubjectEntity[]>;
98
- }
99
- export type SubjectArray<T> = T[] | {
100
- action: 'setter' | 'adder' | 'remover';
101
- value: T[];
102
- };
103
- export type SubjectEntityQueryParam = {
104
- source?: string;
105
- size?: number;
106
- page?: number;
107
- where?: {
108
- condition?: string;
109
- } | object;
110
- };