@coasys/ad4m 0.9.0 → 0.9.1-prerelease.1

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.
@@ -66,55 +66,7 @@ export class PerspectiveProxy {
66
66
  }
67
67
 
68
68
  async executeAction(actions, expression, parameters: Parameter[]) {
69
- const replaceThis = (input: string|undefined) => {
70
- if(input) {
71
- if (input === 'this') {
72
- return expression
73
- } else {
74
- return input
75
- }
76
- } else {
77
- return undefined
78
- }
79
- }
80
-
81
- const replaceParameters = (input: string|undefined) => {
82
- if(parameters) {
83
- let output = input
84
- for(const parameter of parameters) {
85
- output = output.replace(parameter.name, parameter.value)
86
- }
87
- return output
88
- } else
89
- return input
90
- }
91
-
92
- for(let command of actions) {
93
- let source = replaceThis(replaceParameters(command.source))
94
- let predicate = replaceThis(replaceParameters(command.predicate))
95
- let target = replaceThis(replaceParameters(command.target))
96
- let local = command?.local ?? false
97
-
98
- switch(command.action) {
99
- case 'addLink':
100
- await this.add(new Link({source, predicate, target}), local ? 'local' : 'shared')
101
- break;
102
- case 'removeLink':
103
- const linkExpressions = await this.get(new LinkQuery({source, predicate, target}))
104
- for (const linkExpression of linkExpressions) {
105
- await this.remove(linkExpression)
106
- }
107
- break;
108
- case 'setSingleTarget':
109
- await this.setSingleTarget(new Link({source, predicate, target}), local ? 'local' : 'shared')
110
- break;
111
- case 'collectionSetter':
112
- const links = await this.get(new LinkQuery({ source, predicate }))
113
- await this.removeLinks(links);
114
- await this.addLinks(parameters.map(p => new Link({source, predicate, target: p.value})), local ? 'local' : 'shared')
115
- break;
116
- }
117
- }
69
+ return await this.#client.executeCommands(this.#handle.uuid, JSON.stringify(actions), expression, JSON.stringify(parameters))
118
70
  }
119
71
 
120
72
  /** Returns all the links of this perspective that matches the LinkQuery */
@@ -364,17 +316,28 @@ export class PerspectiveProxy {
364
316
  * @param exprAddr The address of the expression to be turned into a subject instance
365
317
  */
366
318
  async createSubject<T>(subjectClass: T, exprAddr: string): Promise<T> {
367
- let className = await this.stringOrTemplateObjectToSubjectClass(subjectClass)
368
- let result = await this.infer(`subject_class("${className}", C), constructor(C, Actions)`)
369
- if(!result.length) {
370
- throw "No constructor found for given subject class: " + className
319
+ let className: string;
320
+
321
+ if(typeof subjectClass === "string") {
322
+ className = subjectClass
323
+
324
+ await this.#client.createSubject(this.#handle.uuid, JSON.stringify({className}), exprAddr);
325
+ } else {
326
+ let query = this.buildQueryFromTemplate(subjectClass as object)
327
+ await this.#client.createSubject(this.#handle.uuid, JSON.stringify({query}), exprAddr);
371
328
  }
372
329
 
373
- let actions = result.map(x => eval(x.Actions))
374
- await this.executeAction(actions[0], exprAddr, undefined)
375
330
  return this.getSubjectProxy(exprAddr, subjectClass)
376
331
  }
377
332
 
333
+ async getSubjectData<T>(subjectClass: T, exprAddr: string): Promise<T> {
334
+ if (typeof subjectClass === "string") {
335
+ return JSON.parse(await this.#client.getSubjectData(this.#handle.uuid, JSON.stringify({className: subjectClass}), exprAddr))
336
+ }
337
+ let query = this.buildQueryFromTemplate(subjectClass as object)
338
+ return JSON.parse(await this.#client.getSubjectData(this.#handle.uuid, JSON.stringify({query}), exprAddr))
339
+ }
340
+
378
341
  /** Removes a subject instance by running its (SDNA defined) destructor,
379
342
  * which means removing links around the given expression address
380
343
  *
@@ -468,18 +431,7 @@ export class PerspectiveProxy {
468
431
  }
469
432
 
470
433
 
471
- /** Returns all subject classes that match the given template object.
472
- * This function looks at the properties of the template object and
473
- * its setters and collections to create a Prolog query that finds
474
- * all subject classes that would be converted to a proxy object
475
- * with exactly the same properties and collections.
476
- *
477
- * Since there could be multiple subject classes that match the given
478
- * criteria, this function returns a list of class names.
479
- *
480
- * @param obj The template object
481
- */
482
- async subjectClassesByTemplate(obj: object): Promise<string[]> {
434
+ private buildQueryFromTemplate(obj: object): string {
483
435
  // Collect all string properties of the object in a list
484
436
  let properties = []
485
437
 
@@ -550,6 +502,23 @@ export class PerspectiveProxy {
550
502
 
551
503
 
552
504
  query += "."
505
+
506
+ return query;
507
+ }
508
+
509
+ /** Returns all subject classes that match the given template object.
510
+ * This function looks at the properties of the template object and
511
+ * its setters and collections to create a Prolog query that finds
512
+ * all subject classes that would be converted to a proxy object
513
+ * with exactly the same properties and collections.
514
+ *
515
+ * Since there could be multiple subject classes that match the given
516
+ * criteria, this function returns a list of class names.
517
+ *
518
+ * @param obj The template object
519
+ */
520
+ async subjectClassesByTemplate(obj: object): Promise<string[]> {
521
+ const query = this.buildQueryFromTemplate(obj);
553
522
  let result = await this.infer(query)
554
523
  if(!result) {
555
524
  return []
@@ -181,12 +181,40 @@ export default class PerspectiveResolver {
181
181
  pubSub.publish(LINK_REMOVED_TOPIC)
182
182
  return true
183
183
  }
184
-
184
+
185
185
  @Mutation(returns => Boolean)
186
186
  perspectiveAddSdna(@Arg('uuid') uuid: string, @Arg('name') name: string, @Arg('sdnaCode') sdnaCode: string, @Arg('sdnaType') sdnaType: string, @PubSub() pubSub: any): Boolean {
187
187
  return true
188
188
  }
189
189
 
190
+ @Mutation(returns => Boolean)
191
+ perspectiveExecuteCommands(
192
+ @Arg('uuid') uuid: string,
193
+ @Arg('commands') commands: string,
194
+ @Arg('expression') expression: string,
195
+ @Arg('parameters', type => String, {nullable: true}) parameters: string
196
+ ): Boolean {
197
+ return true
198
+ }
199
+
200
+ @Mutation(returns => Boolean)
201
+ perspectiveCreateSubject(
202
+ @Arg('uuid') uuid: string,
203
+ @Arg('subjectClass') SubjectClass: string,
204
+ @Arg('expressionAddress') expressionAddress: string
205
+ ): Boolean {
206
+ return true
207
+ }
208
+
209
+ @Mutation(returns => String)
210
+ perspectiveGetSubjectData(
211
+ @Arg('uuid') uuid: string,
212
+ @Arg('subjectClass') SubjectClass: string,
213
+ @Arg('expressionAddress') expressionAddress: string
214
+ ): String {
215
+ return ""
216
+ }
217
+
190
218
  @Subscription({topics: PERSPECTIVE_ADDED_TOPIC, nullable: true})
191
219
  perspectiveAdded(): PerspectiveHandle {
192
220
  const perspective = new PerspectiveHandle('00001', 'New Perspective');
@@ -1,7 +1,7 @@
1
1
  import { ApolloClient, gql } from "@apollo/client/core"
2
2
  import { Perspective, PerspectiveExpression } from "../perspectives/Perspective"
3
3
  import unwrapApolloResult from "../unwrapApolloResult"
4
- import { RuntimeInfo, ExceptionInfo, SentMessage } from "./RuntimeResolver"
4
+ import { RuntimeInfo, ExceptionInfo, SentMessage, NotificationInput, Notification, TriggeredNotification } from "./RuntimeResolver"
5
5
 
6
6
  const PERSPECTIVE_EXPRESSION_FIELDS = `
7
7
  author
@@ -17,22 +17,53 @@ data {
17
17
  proof { valid, invalid, signature, key }
18
18
  `
19
19
 
20
+ const NOTIFICATION_DEFINITION_FIELDS = `
21
+ description
22
+ appName
23
+ appUrl
24
+ appIconPath
25
+ trigger
26
+ perspectiveIds
27
+ webhookUrl
28
+ webhookAuth
29
+ `
30
+
31
+ const NOTIFICATION_FIELDS = `
32
+ id
33
+ granted
34
+ ${NOTIFICATION_DEFINITION_FIELDS}
35
+ `
36
+
37
+ const TRIGGERED_NOTIFICATION_FIELDS = `
38
+ notification { ${NOTIFICATION_FIELDS} }
39
+ perspectiveId
40
+ triggerMatch
41
+ `
42
+
20
43
  export type MessageCallback = (message: PerspectiveExpression) => null
21
44
  export type ExceptionCallback = (info: ExceptionInfo) => null
45
+ export type NotificationTriggeredCallback = (notification: TriggeredNotification) => null
46
+ export type NotificationRequestedCallback = (notification: Notification) => null
22
47
 
23
48
  export class RuntimeClient {
24
49
  #apolloClient: ApolloClient<any>
25
50
  #messageReceivedCallbacks: MessageCallback[]
26
51
  #exceptionOccurredCallbacks: ExceptionCallback[]
52
+ #notificationTriggeredCallbacks: NotificationTriggeredCallback[]
53
+ #notificationRequestedCallbacks: NotificationRequestedCallback[]
27
54
 
28
55
  constructor(client: ApolloClient<any>, subscribe: boolean = true) {
29
56
  this.#apolloClient = client
30
57
  this.#messageReceivedCallbacks = []
31
58
  this.#exceptionOccurredCallbacks = []
59
+ this.#notificationTriggeredCallbacks = []
60
+ this.#notificationRequestedCallbacks = []
32
61
 
33
62
  if(subscribe) {
34
63
  this.subscribeMessageReceived()
35
64
  this.subscribeExceptionOccurred()
65
+ this.subscribeNotificationTriggered()
66
+ this.subscribeNotificationRequested()
36
67
  }
37
68
  }
38
69
 
@@ -238,6 +269,94 @@ export class RuntimeClient {
238
269
  return runtimeMessageOutbox
239
270
  }
240
271
 
272
+ async requestInstallNotification(notification: NotificationInput) {
273
+ const { runtimeRequestInstallNotification } = unwrapApolloResult(await this.#apolloClient.mutate({
274
+ mutation: gql`mutation runtimeRequestInstallNotification($notification: NotificationInput!) {
275
+ runtimeRequestInstallNotification(notification: $notification)
276
+ }`,
277
+ variables: { notification }
278
+ }))
279
+ return runtimeRequestInstallNotification
280
+ }
281
+
282
+ async grantNotification(id: string): Promise<boolean> {
283
+ const { runtimeGrantNotification } = unwrapApolloResult(await this.#apolloClient.mutate({
284
+ mutation: gql`mutation runtimeGrantNotification($id: String!) {
285
+ runtimeGrantNotification(id: $id)
286
+ }`,
287
+ variables: { id }
288
+ }))
289
+ return runtimeGrantNotification
290
+ }
291
+
292
+ async notifications(): Promise<Notification[]> {
293
+ const { runtimeNotifications } = unwrapApolloResult(await this.#apolloClient.query({
294
+ query: gql`query runtimeNotifications {
295
+ runtimeNotifications { ${NOTIFICATION_FIELDS} }
296
+ }`,
297
+ }))
298
+ return runtimeNotifications
299
+ }
300
+
301
+ async updateNotification(id: string, notification: NotificationInput): Promise<boolean> {
302
+ const { runtimeUpdateNotification } = unwrapApolloResult(await this.#apolloClient.mutate({
303
+ mutation: gql`mutation runtimeUpdateNotification($id: String!, $notification: NotificationInput!) {
304
+ runtimeUpdateNotification(id: $id, notification: $notification)
305
+ }`,
306
+ variables: { id, notification }
307
+ }))
308
+ return runtimeUpdateNotification
309
+ }
310
+
311
+ async removeNotification(id: string): Promise<boolean> {
312
+ const { runtimeRemoveNotification } = unwrapApolloResult(await this.#apolloClient.mutate({
313
+ mutation: gql`mutation runtimeRemoveNotification($id: String!) {
314
+ runtimeRemoveNotification(id: $id)
315
+ }`,
316
+ variables: { id }
317
+ }))
318
+ return runtimeRemoveNotification
319
+ }
320
+
321
+
322
+ addNotificationTriggeredCallback(cb: NotificationTriggeredCallback) {
323
+ this.#notificationTriggeredCallbacks.push(cb)
324
+ }
325
+
326
+ addNotificationRequestedCallback(cb: NotificationRequestedCallback) {
327
+ this.#notificationRequestedCallbacks.push(cb)
328
+ }
329
+
330
+ subscribeNotificationTriggered() {
331
+ this.#apolloClient.subscribe({
332
+ query: gql` subscription {
333
+ runtimeNotificationTriggered { ${TRIGGERED_NOTIFICATION_FIELDS} }
334
+ }
335
+ `}).subscribe({
336
+ next: result => {
337
+ this.#notificationTriggeredCallbacks.forEach(cb => {
338
+ cb(result.data.runtimeNotificationTriggered)
339
+ })
340
+ },
341
+ error: (e) => console.error(e)
342
+ })
343
+ }
344
+
345
+ subscribeNotificationRequested() {
346
+ this.#apolloClient.subscribe({
347
+ query: gql` subscription {
348
+ runtimeNotificationRequested { ${NOTIFICATION_FIELDS} }
349
+ }
350
+ `}).subscribe({
351
+ next: result => {
352
+ this.#notificationRequestedCallbacks.forEach(cb => {
353
+ cb(result.data.runtimeNotificationRequested)
354
+ })
355
+ },
356
+ error: (e) => console.error(e)
357
+ })
358
+ }
359
+
241
360
  addMessageCallback(cb: MessageCallback) {
242
361
  this.#messageReceivedCallbacks.push(cb)
243
362
  }
@@ -1,9 +1,9 @@
1
- import { Arg, Mutation, Resolver, Query, Subscription, ObjectType, Field, Int } from "type-graphql";
1
+ import { Arg, Mutation, Resolver, Query, Subscription, ObjectType, Field, Int, InputType } from "type-graphql";
2
2
  import { Perspective, PerspectiveExpression, PerspectiveInput } from "../perspectives/Perspective";
3
3
  import { ExpressionProof } from "../expression/Expression";
4
4
  import { LinkExpression } from "../links/Links";
5
5
  import { ExceptionType } from "../Exception";
6
- import { RUNTIME_MESSAGED_RECEIVED_TOPIC, EXCEPTION_OCCURRED_TOPIC } from '../PubSub';
6
+ import { RUNTIME_MESSAGED_RECEIVED_TOPIC, EXCEPTION_OCCURRED_TOPIC, RUNTIME_NOTIFICATION_REQUESTED_TOPIC, RUNTIME_NOTIFICATION_TRIGGERED_TOPIC } from '../PubSub';
7
7
 
8
8
  const testLink = new LinkExpression()
9
9
  testLink.author = "did:ad4m:test"
@@ -54,6 +54,90 @@ export class ExceptionInfo {
54
54
  addon?: string;
55
55
  }
56
56
 
57
+ // This class defines a Notification and is what an app provides
58
+ // when registering and installing a notification.
59
+ @InputType()
60
+ export class NotificationInput {
61
+ @Field()
62
+ description: string;
63
+ @Field()
64
+ appName: string;
65
+ @Field()
66
+ appUrl: string;
67
+ @Field()
68
+ appIconPath: string;
69
+
70
+ // This is Prolog query which will be executed on every perspective change.
71
+ // All matched unbound variables will be part of the triggerMatch, i.e.
72
+ // the content that will be sent to the launcher via subscription
73
+ // and to the webhook.
74
+ @Field()
75
+ trigger: string;
76
+
77
+ // List Perspectives this Notification is active on.
78
+ @Field(type => [String])
79
+ perspectiveIds: string[];
80
+
81
+ // URL to which the notification matches will be sent via POST
82
+ @Field()
83
+ webhookUrl: string;
84
+
85
+ // Authentication bearer token to be sent via POST to the webhookUrl.
86
+ @Field()
87
+ webhookAuth: string;
88
+ }
89
+
90
+ // This is a notification as it is stored in the runtime.
91
+ // Above definition plus ID and granted flag.
92
+ @ObjectType()
93
+ export class Notification {
94
+ @Field()
95
+ id: string;
96
+ @Field()
97
+ granted: boolean;
98
+ @Field()
99
+ description: string;
100
+ @Field()
101
+ appName: string;
102
+ @Field()
103
+ appUrl: string;
104
+ @Field()
105
+ appIconPath: string;
106
+
107
+ // This is Prolog query which will be executed on every perspective change.
108
+ // All matched unbound variables will be part of the triggerMatch, i.e.
109
+ // the content that will be sent to the launcher via subscription
110
+ // and to the webhook.
111
+ @Field()
112
+ trigger: string;
113
+
114
+ // List Perspectives this Notification is active on.
115
+ @Field(type => [String])
116
+ perspectiveIds: string[];
117
+
118
+ // URL to which the notification matches will be sent via POST
119
+ @Field()
120
+ webhookUrl: string;
121
+
122
+ // Authentication bearer token to be sent via POST to the webhookUrl.
123
+ @Field()
124
+ webhookAuth: string;
125
+ }
126
+
127
+ // This is what is sent to the launcher and the webhook.
128
+ @ObjectType()
129
+ export class TriggeredNotification {
130
+ @Field()
131
+ notification: Notification;
132
+ @Field()
133
+ perspectiveId: string;
134
+
135
+ // This is the Prolog query match that triggered the notification.
136
+ // It is a list of all variable bindings that match the notification's trigger.
137
+ @Field()
138
+ triggerMatch: string;
139
+ }
140
+
57
141
  /**
58
142
  * Resolver classes are used here to define the GraphQL schema
59
143
  * (through the type-graphql annotations)
@@ -190,4 +274,84 @@ export default class RuntimeResolver {
190
274
  type: ExceptionType.LanguageIsNotLoaded,
191
275
  }
192
276
  }
193
- }
277
+
278
+ @Mutation()
279
+ runtimeRequestInstallNotification(
280
+ @Arg("notification", type => NotificationInput) notification: NotificationInput
281
+ ): string {
282
+ return "new-notification-id"
283
+ }
284
+
285
+ @Query(returns => [Notification])
286
+ runtimeNotifications(): Notification[] {
287
+ return [{
288
+ id: "test-id",
289
+ granted: false,
290
+ description: "Test description",
291
+ appName: "Test app name",
292
+ appUrl: "https://example.com",
293
+ appIconPath: "https://fluxsocial.io/favicon",
294
+ trigger: "triple(X, ad4m://has_type, flux://message)",
295
+ perspectiveIds: ["u983ud-jdhh38d"],
296
+ webhookUrl: "https://example.com/webhook",
297
+ webhookAuth: "test-auth",
298
+
299
+ }]
300
+ }
301
+
302
+ @Mutation()
303
+ runtimeUpdateNotification(
304
+ @Arg("id", type => String) id: string,
305
+ @Arg("notification", type => NotificationInput) notification: NotificationInput
306
+ ): boolean {
307
+ return true
308
+ }
309
+
310
+ @Mutation()
311
+ runtimeRemoveNotification(@Arg("id", type => String) id: string): boolean {
312
+ return true
313
+ }
314
+
315
+ @Mutation()
316
+ runtimeGrantNotification(@Arg("id", type => String) id: string): boolean {
317
+ return true
318
+ }
319
+
320
+ @Subscription({topics: RUNTIME_NOTIFICATION_REQUESTED_TOPIC, nullable: true})
321
+ runtimeNotificationRequested(): Notification {
322
+ return {
323
+ id: "test-id",
324
+ granted: false,
325
+ description: "Test description",
326
+ appName: "Test app name",
327
+ appUrl: "https://example.com",
328
+ appIconPath: "https://fluxsocial.io/favicon",
329
+ trigger: "triple(X, ad4m://has_type, flux://message)",
330
+ perspectiveIds: ["u983ud-jdhh38d"],
331
+ webhookUrl: "https://example.com/webhook",
332
+ webhookAuth: "test-auth",
333
+
334
+ }
335
+ }
336
+
337
+ @Subscription({topics: RUNTIME_NOTIFICATION_TRIGGERED_TOPIC, nullable: true})
338
+ runtimeNotificationTriggered(): TriggeredNotification {
339
+ return {
340
+ perspectiveId: "test-perspective-id",
341
+ triggerMatch: "test-trigger-match",
342
+ notification: {
343
+ id: "test-id",
344
+ granted: false,
345
+ description: "Test description",
346
+ appName: "Test app name",
347
+ appUrl: "https://example.com",
348
+ appIconPath: "https://fluxsocial.io/favicon",
349
+ trigger: "triple(X, ad4m://has_type, flux://message)",
350
+ perspectiveIds: ["u983ud-jdhh38d"],
351
+ webhookUrl: "https://example.com/webhook",
352
+ webhookAuth: "test-auth",
353
+ }
354
+ }
355
+ }
356
+ }
357
+
@@ -43,63 +43,11 @@ export class SubjectEntity {
43
43
 
44
44
  private async getData(id?: string) {
45
45
  const tempId = id ?? this.#baseExpression;
46
- let isInstance = await this.#perspective.isSubjectInstance(tempId, this.#subjectClass)
47
- if (!isInstance) {
48
- throw `Not a valid subject instance of ${this.#subjectClass} for ${tempId}`
49
- }
50
-
51
- let results = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property(C, Property)`)
52
- let properties = results.map(result => result.Property)
53
-
54
- for (let p of properties) {
55
- const resolveExpressionURI = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property_resolve(C, "${p}")`)
56
- const getProperty = async () => {
57
- let results = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property_getter(C, "${tempId}", "${p}", Value)`)
58
- if (results && results.length > 0) {
59
- let expressionURI = results[0].Value
60
- if (resolveExpressionURI) {
61
- try {
62
- const expression = await this.#perspective.getExpression(expressionURI)
63
- try {
64
- return JSON.parse(expression.data)
65
- } catch (e) {
66
- return expression.data
67
- }
68
- } catch (err) {
69
- return expressionURI
70
- }
71
- } else {
72
- return expressionURI
73
- }
74
- } else if (results) {
75
- return results
76
- } else {
77
- return undefined
78
- }
79
- };
80
-
81
- this[p] = await getProperty()
82
- }
83
-
84
- let results2 = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection(C, Collection)`)
85
- if (!results2) results2 = []
86
- let collections = results2.map(result => result.Collection)
87
-
88
- for (let c of collections) {
89
- const getProperty = async () => {
90
- let results = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection_getter(C, "${tempId}", "${c}", Value)`)
91
- if (results && results.length > 0 && results[0].Value) {
92
- return eval(results[0].Value)
93
- } else {
94
- return []
95
- }
96
- }
97
-
98
- this[c] = await getProperty()
99
- }
100
-
46
+ console.log("SubjectEntity: getData")
47
+ let data = await this.#perspective.getSubjectData(this.#subjectClass, tempId)
48
+ console.log("SubjectEntity got data:", data)
49
+ Object.assign(this, data);
101
50
  this.#baseExpression = tempId;
102
-
103
51
  return this
104
52
  }
105
53