@coasys/ad4m 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +229 -0
  2. package/jest-setup.ts +1 -0
  3. package/jest.config.js +6 -0
  4. package/jsdoc.json +28 -0
  5. package/lib/index.cjs +8144 -0
  6. package/lib/shims/reflect-metadata.d.ts +0 -0
  7. package/lib/shims/type-graphql.d.ts +32 -0
  8. package/lib/src/Ad4mClient.d.ts +26 -0
  9. package/lib/src/Address.d.ts +1 -0
  10. package/lib/src/DID.d.ts +1 -0
  11. package/lib/src/Exception.d.ts +6 -0
  12. package/lib/src/Literal.d.ts +7 -0
  13. package/lib/src/PubSub.d.ts +14 -0
  14. package/lib/src/SmartLiteral.d.ts +12 -0
  15. package/lib/src/agent/Agent.d.ts +104 -0
  16. package/lib/src/agent/AgentClient.d.ts +57 -0
  17. package/lib/src/agent/AgentResolver.d.ts +30 -0
  18. package/lib/src/agent/AgentStatus.d.ts +8 -0
  19. package/lib/src/buildSchema.d.ts +1 -0
  20. package/lib/src/expression/Expression.d.ts +28 -0
  21. package/lib/src/expression/ExpressionClient.d.ts +13 -0
  22. package/lib/src/expression/ExpressionRef.d.ts +9 -0
  23. package/lib/src/expression/ExpressionResolver.d.ts +10 -0
  24. package/lib/src/index.d.ts +30 -0
  25. package/lib/src/jestSetup.d.ts +1 -0
  26. package/lib/src/language/Icon.d.ts +4 -0
  27. package/lib/src/language/Language.d.ts +195 -0
  28. package/lib/src/language/LanguageClient.d.ts +17 -0
  29. package/lib/src/language/LanguageContext.d.ts +37 -0
  30. package/lib/src/language/LanguageHandle.d.ts +9 -0
  31. package/lib/src/language/LanguageMeta.d.ts +35 -0
  32. package/lib/src/language/LanguageRef.d.ts +6 -0
  33. package/lib/src/language/LanguageResolver.d.ts +19 -0
  34. package/lib/src/links/Links.d.ts +39 -0
  35. package/lib/src/links/Links.test.d.ts +1 -0
  36. package/lib/src/neighbourhood/Neighbourhood.d.ts +10 -0
  37. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  38. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  39. package/lib/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  40. package/lib/src/perspectives/LinkQuery.d.ts +11 -0
  41. package/lib/src/perspectives/Perspective.d.ts +38 -0
  42. package/lib/src/perspectives/Perspective.test.d.ts +1 -0
  43. package/lib/src/perspectives/PerspectiveClient.d.ts +54 -0
  44. package/lib/src/perspectives/PerspectiveDiff.d.ts +9 -0
  45. package/lib/src/perspectives/PerspectiveHandle.d.ts +16 -0
  46. package/lib/src/perspectives/PerspectiveProxy.d.ts +178 -0
  47. package/lib/src/perspectives/PerspectiveResolver.d.ts +37 -0
  48. package/lib/src/runtime/RuntimeClient.d.ts +33 -0
  49. package/lib/src/runtime/RuntimeResolver.d.ts +47 -0
  50. package/lib/src/schema.gql +382 -0
  51. package/lib/src/subject/SDNADecorators.d.ts +45 -0
  52. package/lib/src/subject/Subject.d.ts +7 -0
  53. package/lib/src/subject/SubjectEntity.d.ts +31 -0
  54. package/lib/src/subject/util.d.ts +12 -0
  55. package/lib/src/typeDefs.d.ts +1 -0
  56. package/lib/src/unwrapApolloResult.d.ts +2 -0
  57. package/lib/src/utils.d.ts +2 -0
  58. package/package.json +60 -0
  59. package/rollup.config.js +27 -0
  60. package/shims/reflect-metadata.ts +0 -0
  61. package/shims/type-graphql.ts +75 -0
  62. package/src/Ad4mClient.test.ts +1085 -0
  63. package/src/Ad4mClient.ts +63 -0
  64. package/src/Address.ts +1 -0
  65. package/src/DID.ts +1 -0
  66. package/src/Exception.ts +6 -0
  67. package/src/Literal.test.ts +31 -0
  68. package/src/Literal.ts +81 -0
  69. package/src/PubSub.ts +14 -0
  70. package/src/SmartLiteral.ts +75 -0
  71. package/src/agent/Agent.ts +293 -0
  72. package/src/agent/AgentClient.ts +531 -0
  73. package/src/agent/AgentResolver.ts +263 -0
  74. package/src/agent/AgentStatus.ts +44 -0
  75. package/src/buildSchema.ts +41 -0
  76. package/src/expression/Expression.ts +99 -0
  77. package/src/expression/ExpressionClient.ts +99 -0
  78. package/src/expression/ExpressionRef.ts +63 -0
  79. package/src/expression/ExpressionResolver.ts +64 -0
  80. package/src/index.ts +30 -0
  81. package/src/jestSetup.ts +1 -0
  82. package/src/language/Icon.ts +11 -0
  83. package/src/language/Language.ts +266 -0
  84. package/src/language/LanguageClient.ts +160 -0
  85. package/src/language/LanguageContext.ts +37 -0
  86. package/src/language/LanguageHandle.ts +23 -0
  87. package/src/language/LanguageMeta.ts +70 -0
  88. package/src/language/LanguageRef.ts +18 -0
  89. package/src/language/LanguageResolver.ts +98 -0
  90. package/src/links/Links.test.ts +40 -0
  91. package/src/links/Links.ts +107 -0
  92. package/src/neighbourhood/Neighbourhood.ts +22 -0
  93. package/src/neighbourhood/NeighbourhoodClient.ts +276 -0
  94. package/src/neighbourhood/NeighbourhoodProxy.ts +58 -0
  95. package/src/neighbourhood/NeighbourhoodResolver.ts +100 -0
  96. package/src/perspectives/LinkQuery.ts +66 -0
  97. package/src/perspectives/Perspective.test.ts +23 -0
  98. package/src/perspectives/Perspective.ts +118 -0
  99. package/src/perspectives/PerspectiveClient.ts +444 -0
  100. package/src/perspectives/PerspectiveDiff.ts +15 -0
  101. package/src/perspectives/PerspectiveHandle.ts +39 -0
  102. package/src/perspectives/PerspectiveProxy.ts +611 -0
  103. package/src/perspectives/PerspectiveResolver.ts +220 -0
  104. package/src/runtime/RuntimeClient.ts +283 -0
  105. package/src/runtime/RuntimeResolver.ts +193 -0
  106. package/src/subject/SDNADecorators.ts +334 -0
  107. package/src/subject/Subject.ts +153 -0
  108. package/src/subject/SubjectEntity.ts +292 -0
  109. package/src/subject/util.ts +85 -0
  110. package/src/typeDefs.ts +6 -0
  111. package/src/unwrapApolloResult.ts +14 -0
  112. package/src/utils.ts +25 -0
  113. package/tsconfig-browser.json +82 -0
  114. package/tsconfig.json +80 -0
@@ -0,0 +1,193 @@
1
+ import { Arg, Mutation, Resolver, Query, Subscription, ObjectType, Field } from "type-graphql";
2
+ import { Perspective, PerspectiveExpression, PerspectiveInput } from "../perspectives/Perspective";
3
+ import { ExpressionProof } from "../expression/Expression";
4
+ import { LinkExpression } from "../links/Links";
5
+ import { ExceptionType } from "../Exception";
6
+ import { RUNTIME_MESSAGED_RECEIVED_TOPIC, EXCEPTION_OCCURRED_TOPIC } from '../PubSub';
7
+
8
+ const testLink = new LinkExpression()
9
+ testLink.author = "did:ad4m:test"
10
+ testLink.timestamp = Date.now()
11
+ testLink.data = {
12
+ source: 'root',
13
+ target: 'neighbourhood://Qm12345'
14
+ }
15
+ testLink.proof = {
16
+ signature: '',
17
+ key: '',
18
+ valid: true
19
+ }
20
+
21
+ const testPerspectiveExpression = new PerspectiveExpression()
22
+ testPerspectiveExpression.author = 'did:ad4m:test'
23
+ testPerspectiveExpression.timestamp = Date.now().toString()
24
+ testPerspectiveExpression.proof = new ExpressionProof('', '')
25
+ testPerspectiveExpression.data = new Perspective([testLink])
26
+
27
+ @ObjectType()
28
+ export class SentMessage {
29
+ @Field()
30
+ recipient: string;
31
+ @Field()
32
+ message: PerspectiveExpression;
33
+ }
34
+
35
+ @ObjectType()
36
+ export class RuntimeInfo {
37
+ @Field()
38
+ ad4mExecutorVersion: string;
39
+ @Field()
40
+ isInitialized: Boolean;
41
+ @Field()
42
+ isUnlocked: Boolean;
43
+ }
44
+
45
+ @ObjectType()
46
+ export class ExceptionInfo {
47
+ @Field()
48
+ title: string;
49
+ @Field()
50
+ message: string;
51
+ @Field()
52
+ type: ExceptionType;
53
+ @Field({ nullable: true })
54
+ addon?: string;
55
+ }
56
+
57
+ /**
58
+ * Resolver classes are used here to define the GraphQL schema
59
+ * (through the type-graphql annotations)
60
+ * and are spawned in the client tests in Ad4mClient.test.ts.
61
+ * For the latter, they return test fixtures.
62
+ */
63
+ @Resolver()
64
+ export default class RuntimeResolver {
65
+ @Mutation(returns => Boolean)
66
+ runtimeQuit(): Boolean {
67
+ return true
68
+ }
69
+
70
+ @Mutation(returns => Boolean)
71
+ runtimeOpenLink(@Arg('url') url: string): Boolean {
72
+ return true
73
+ }
74
+
75
+ @Query(returns => RuntimeInfo)
76
+ runtimeInfo(): RuntimeInfo {
77
+ return {
78
+ ad4mExecutorVersion: "x.x.x",
79
+ isInitialized: true,
80
+ isUnlocked: true
81
+ } as RuntimeInfo
82
+ }
83
+
84
+ @Mutation(returns => [String])
85
+ addTrustedAgents(@Arg("agents", type => [String]) agents: string[]): string[] {
86
+ return agents
87
+ }
88
+
89
+ @Mutation(returns => [String])
90
+ deleteTrustedAgents(@Arg("agents", type => [String]) agents: string[]): string[] {
91
+ return []
92
+ }
93
+
94
+ @Query(returns => [String])
95
+ getTrustedAgents(): string[] {
96
+ return ["agentPubKey"]
97
+ }
98
+
99
+ @Query(returns => [String])
100
+ runtimeKnownLinkLanguageTemplates(): string[] {
101
+ return ["Qm12345abcdef"]
102
+ }
103
+
104
+ @Mutation(returns => [String])
105
+ runtimeAddKnownLinkLanguageTemplates(@Arg("addresses", type => [String]) addresses: string[]): string[] {
106
+ return addresses
107
+ }
108
+
109
+ @Mutation(returns => [String])
110
+ runtimeRemoveKnownLinkLanguageTemplates(@Arg("addresses", type => [String]) addresses: string[]): string[] {
111
+ return []
112
+ }
113
+
114
+ @Query(returns => [String])
115
+ runtimeFriends(): string[] {
116
+ return ["did:test:friend"]
117
+ }
118
+
119
+ @Mutation(returns => [String])
120
+ runtimeAddFriends(@Arg("dids", type => [String]) dids: string[]): string[] {
121
+ return dids
122
+ }
123
+
124
+ @Mutation(returns => [String])
125
+ runtimeRemoveFriends(@Arg("dids", type => [String]) dids: string[]): string[] {
126
+ return []
127
+ }
128
+
129
+ @Query()
130
+ runtimeHcAgentInfos(): String {
131
+ return JSON.stringify([{"agent":{"type":"Buffer","data":[9,191,231,58,255,107,202,55,206,57,9,103,17,34,206,195,207,114,5,73,77,198,56,136,17,227,242,231,194,135,128,48,170,189,119,186]},"signature":{"type":"Buffer","data":[195,143,170,36,234,123,255,85,188,138,124,2,91,18,53,231,44,41,240,8,80,131,100,150,165,125,146,90,17,200,190,129,114,211,11,146,150,128,198,199,79,118,157,101,194,68,58,245,98,182,79,139,140,41,143,129,8,136,87,77,180,231,218,11]},"agent_info":{"type":"Buffer","data":[134,165,115,112,97,99,101,196,36,203,165,212,173,24,215,165,196,25,145,248,113,246,139,205,182,241,138,57,0,26,8,217,179,23,126,59,136,128,213,110,225,173,72,197,95,165,97,103,101,110,116,196,36,9,191,231,58,255,107,202,55,206,57,9,103,17,34,206,195,207,114,5,73,77,198,56,136,17,227,242,231,194,135,128,48,170,189,119,186,164,117,114,108,115,145,217,99,107,105,116,115,117,110,101,45,112,114,111,120,121,58,47,47,101,83,52,86,112,54,109,118,80,48,122,116,85,101,104,114,117,113,89,52,102,66,53,101,69,98,121,48,69,66,100,89,84,50,95,67,48,69,112,77,111,76,111,47,107,105,116,115,117,110,101,45,113,117,105,99,47,104,47,49,57,50,46,49,54,56,46,49,55,56,46,54,48,47,112,47,55,55,52,52,47,45,45,172,115,105,103,110,101,100,95,97,116,95,109,115,207,0,0,1,123,233,104,189,50,176,101,120,112,105,114,101,115,95,97,102,116,101,114,95,109,115,206,0,18,79,128,169,109,101,116,97,95,105,110,102,111,196,34,129,187,100,104,116,95,115,116,111,114,97,103,101,95,97,114,99,95,104,97,108,102,95,108,101,110,103,116,104,206,128,0,0,1]}},{"agent":{"type":"Buffer","data":[98,187,145,48,115,209,94,143,31,153,102,69,138,29,133,213,34,52,39,164,157,139,178,111,23,33,118,250,28,155,78,246,128,49,179,38]},"signature":{"type":"Buffer","data":[233,192,38,3,59,248,124,231,57,255,40,154,50,60,119,252,68,198,154,109,175,155,106,217,211,155,109,223,249,91,221,210,17,132,72,230,11,230,247,119,72,244,145,91,75,7,67,5,130,151,44,231,52,220,28,154,212,82,58,90,203,211,236,4]},"agent_info":{"type":"Buffer","data":[134,165,115,112,97,99,101,196,36,203,165,212,173,24,215,165,196,25,145,248,113,246,139,205,182,241,138,57,0,26,8,217,179,23,126,59,136,128,213,110,225,173,72,197,95,165,97,103,101,110,116,196,36,98,187,145,48,115,209,94,143,31,153,102,69,138,29,133,213,34,52,39,164,157,139,178,111,23,33,118,250,28,155,78,246,128,49,179,38,164,117,114,108,115,145,217,99,107,105,116,115,117,110,101,45,112,114,111,120,121,58,47,47,55,101,77,106,48,73,83,72,56,56,81,56,45,89,51,74,89,70,53,76,72,57,83,54,68,119,71,73,49,88,45,115,87,53,68,104,66,87,121,71,119,78,115,47,107,105,116,115,117,110,101,45,113,117,105,99,47,104,47,49,57,50,46,49,54,56,46,49,55,56,46,54,48,47,112,47,55,55,52,52,47,45,45,172,115,105,103,110,101,100,95,97,116,95,109,115,207,0,0,1,123,233,103,45,197,176,101,120,112,105,114,101,115,95,97,102,116,101,114,95,109,115,206,0,18,79,128,169,109,101,116,97,95,105,110,102,111,196,34,129,187,100,104,116,95,115,116,111,114,97,103,101,95,97,114,99,95,104,97,108,102,95,108,101,110,103,116,104,206,128,0,0,1]}},{"agent":{"type":"Buffer","data":[181,101,115,45,214,127,198,153,159,184,30,87,67,224,208,184,203,176,130,158,236,127,153,125,243,183,188,167,154,25,118,254,101,145,210,109]},"signature":{"type":"Buffer","data":[88,189,229,122,44,171,194,156,90,79,148,49,207,224,34,199,219,88,24,243,103,127,123,41,87,171,127,92,6,216,198,171,26,226,237,217,122,78,98,146,55,255,68,240,202,83,58,140,147,185,3,66,15,216,210,22,99,197,73,234,120,17,74,1]},"agent_info":{"type":"Buffer","data":[134,165,115,112,97,99,101,196,36,203,165,212,173,24,215,165,196,25,145,248,113,246,139,205,182,241,138,57,0,26,8,217,179,23,126,59,136,128,213,110,225,173,72,197,95,165,97,103,101,110,116,196,36,181,101,115,45,214,127,198,153,159,184,30,87,67,224,208,184,203,176,130,158,236,127,153,125,243,183,188,167,154,25,118,254,101,145,210,109,164,117,114,108,115,145,217,99,107,105,116,115,117,110,101,45,112,114,111,120,121,58,47,47,114,70,71,83,100,113,104,101,68,107,70,70,56,69,102,109,45,69,116,55,119,81,101,120,83,88,55,65,112,69,51,89,86,99,45,120,102,52,104,106,77,115,77,47,107,105,116,115,117,110,101,45,113,117,105,99,47,104,47,49,57,50,46,49,54,56,46,49,55,56,46,54,48,47,112,47,55,55,52,52,47,45,45,172,115,105,103,110,101,100,95,97,116,95,109,115,207,0,0,1,123,233,113,23,220,176,101,120,112,105,114,101,115,95,97,102,116,101,114,95,109,115,206,0,18,79,128,169,109,101,116,97,95,105,110,102,111,196,34,129,187,100,104,116,95,115,116,111,114,97,103,101,95,97,114,99,95,104,97,108,102,95,108,101,110,103,116,104,206,128,0,0,1]}},{"agent":{"type":"Buffer","data":[3,171,237,107,186,245,165,47,237,235,211,49,245,62,113,53,255,252,223,226,75,118,148,187,23,53,70,174,160,184,64,63,94,210,227,56]},"signature":{"type":"Buffer","data":[129,12,55,104,239,121,138,2,86,106,136,51,219,79,170,8,195,69,81,188,225,192,247,196,54,39,164,110,75,39,240,56,245,189,154,77,72,11,97,250,202,149,242,97,128,28,47,164,236,104,136,82,212,246,44,143,132,119,255,135,112,11,20,13]},"agent_info":{"type":"Buffer","data":[134,165,115,112,97,99,101,196,36,203,165,212,173,24,215,165,196,25,145,248,113,246,139,205,182,241,138,57,0,26,8,217,179,23,126,59,136,128,213,110,225,173,72,197,95,165,97,103,101,110,116,196,36,3,171,237,107,186,245,165,47,237,235,211,49,245,62,113,53,255,252,223,226,75,118,148,187,23,53,70,174,160,184,64,63,94,210,227,56,164,117,114,108,115,145,217,97,107,105,116,115,117,110,101,45,112,114,111,120,121,58,47,47,104,121,112,115,86,121,103,117,80,84,115,53,118,73,80,65,102,97,112,90,88,113,117,84,115,79,80,100,67,81,79,79,117,103,57,51,82,103,106,95,114,85,73,47,107,105,116,115,117,110,101,45,113,117,105,99,47,104,47,49,54,53,46,50,50,46,51,50,46,49,49,47,112,47,53,55,55,57,47,45,45,172,115,105,103,110,101,100,95,97,116,95,109,115,207,0,0,1,123,233,113,188,123,176,101,120,112,105,114,101,115,95,97,102,116,101,114,95,109,115,206,0,18,79,128,169,109,101,116,97,95,105,110,102,111,196,34,129,187,100,104,116,95,115,116,111,114,97,103,101,95,97,114,99,95,104,97,108,102,95,108,101,110,103,116,104,206,128,0,0,1]}}])
132
+ }
133
+
134
+ @Mutation(returns => Boolean)
135
+ runtimeHcAddAgentInfos(@Arg("agentInfos", type => String) agentInfos): boolean {
136
+ return true
137
+ }
138
+
139
+ @Query(returns => Boolean)
140
+ runtimeVerifyStringSignedByDid(
141
+ @Arg("did", type => String) did: string,
142
+ @Arg("didSigningKeyId", type => String) didSigningKeyId: string,
143
+ @Arg("data", type => String) data: string,
144
+ @Arg("signedData", type => String) signedData: string) {
145
+ return true
146
+ }
147
+
148
+ @Mutation()
149
+ runtimeSetStatus(@Arg("status", type => PerspectiveInput) status: Perspective): boolean {
150
+ return true
151
+ }
152
+
153
+ @Query({nullable: true})
154
+ runtimeFriendStatus(@Arg("did", type => String) did: string): PerspectiveExpression {
155
+ return testPerspectiveExpression
156
+ }
157
+
158
+ @Mutation()
159
+ runtimeFriendSendMessage(
160
+ @Arg("did", type => String) did: string,
161
+ @Arg("message", type => PerspectiveInput) message: PerspectiveInput
162
+ ): boolean {
163
+ return true
164
+ }
165
+
166
+ @Query(returns => [PerspectiveExpression])
167
+ runtimeMessageInbox(@Arg("filter", type => String, {nullable: true }) filter?: string): PerspectiveExpression[] {
168
+ return [testPerspectiveExpression]
169
+ }
170
+
171
+ @Query(returns => [SentMessage])
172
+ runtimeMessageOutbox(@Arg("filter", type => String, {nullable: true }) filter?: string): SentMessage[] {
173
+ return [{
174
+ recipient: "did:test:recipient",
175
+ message: testPerspectiveExpression
176
+ } as SentMessage]
177
+ }
178
+
179
+
180
+ @Subscription({topics: RUNTIME_MESSAGED_RECEIVED_TOPIC, nullable: true})
181
+ runtimeMessageReceived(): PerspectiveExpression {
182
+ return testPerspectiveExpression
183
+ }
184
+
185
+ @Subscription({topics: EXCEPTION_OCCURRED_TOPIC, nullable: true})
186
+ exceptionOccurred(): ExceptionInfo {
187
+ return {
188
+ title: "Test title",
189
+ message: "Test message",
190
+ type: ExceptionType.LanguageIsNotLoaded,
191
+ }
192
+ }
193
+ }
@@ -0,0 +1,334 @@
1
+ import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
2
+ import { Subject } from "./Subject";
3
+ import { capitalize, propertyNameToSetterName, singularToPlural, stringifyObjectLiteral } from "./util";
4
+
5
+ export class PerspectiveAction {
6
+ action: string
7
+ source: string
8
+ predicate: string
9
+ target: string
10
+ }
11
+
12
+ export function addLink(source: string, predicate: string, target: string): PerspectiveAction {
13
+ return {
14
+ action: "addLink",
15
+ source,
16
+ predicate,
17
+ target,
18
+ };
19
+ }
20
+
21
+ export function hasLink(predicate: string): string {
22
+ return `triple(this, "${predicate}", _)`
23
+ }
24
+
25
+ interface InstanceQueryParams {
26
+ where?: object;
27
+ condition?: string;
28
+ }
29
+
30
+ export function instanceQuery(options?: InstanceQueryParams) {
31
+ return function <T>(target: T, key: keyof T, descriptor: PropertyDescriptor) {
32
+ const originalMethod = descriptor.value;
33
+ if(typeof originalMethod !== "function") {
34
+ throw new Error("instanceQuery decorator can only be applied to methods");
35
+ }
36
+
37
+ descriptor.value = async function(perspective: PerspectiveProxy): Promise<T[]> {
38
+ let instances: T[] = []
39
+ //@ts-ignore
40
+ let subjectClassName = target.name
41
+ let query = `subject_class("${subjectClassName}", C), instance(C, Instance)`
42
+ if(options && options.where) {
43
+ for(let prop in options.where) {
44
+ let value = options.where[prop]
45
+ query += `, property_getter(C, Instance, "${prop}", "${value}")`
46
+ }
47
+ }
48
+
49
+ if(options && options.condition) {
50
+ query += ', ' + options.condition
51
+ }
52
+
53
+ let results = await perspective.infer(query)
54
+ if(results == false) {
55
+ return instances
56
+ }
57
+ if(typeof results == "string") {
58
+ throw results
59
+ }
60
+ for(let result of results) {
61
+ let instance = result.Instance
62
+ let subject = new Subject(perspective, instance, subjectClassName)
63
+ await subject.init()
64
+ instances.push(subject as T)
65
+ }
66
+
67
+ return instances
68
+ }
69
+ };
70
+ }
71
+
72
+
73
+ interface PropertyOptions {
74
+ through?: string;
75
+ initial?: string,
76
+ required?: boolean,
77
+ writable?: boolean,
78
+ resolveLanguage?: string;
79
+ getter?: string;
80
+ setter?: string;
81
+ local?: boolean
82
+ }
83
+ export function subjectProperty(opts: PropertyOptions) {
84
+ return function <T>(target: T, key: keyof T) {
85
+ target["__properties"] = target["__properties"] || {};
86
+ target["__properties"][key] = target["__properties"][key] || {};
87
+ target["__properties"][key] = { ...target["__properties"][key], ...opts }
88
+
89
+ if (opts.writable) {
90
+ const value = key as string
91
+ target[`set${capitalize(value)}`] = () => {}
92
+ }
93
+
94
+ Object.defineProperty(target, key, {configurable: true, writable: true});
95
+ };
96
+ }
97
+
98
+ interface FlagOptions {
99
+ through: string;
100
+ value: string;
101
+ }
102
+ export function subjectFlag(opts: FlagOptions) {
103
+ return function <T>(target: T, key: keyof T) {
104
+ target["__properties"] = target["__properties"] || {};
105
+ target["__properties"][key] = target["__properties"][key] || {};
106
+ target["__properties"][key] = {
107
+ ...target["__properties"][key],
108
+ through: opts.through,
109
+ required: true,
110
+ initial: opts.value,
111
+ flag: true
112
+ }
113
+
114
+ // @ts-ignore
115
+ target[key] = opts.value;
116
+
117
+ Object.defineProperty(target, key, {configurable: true, writable: true});
118
+ };
119
+ }
120
+
121
+ interface WhereOptions {
122
+ isInstance?: any
123
+ condition?: string
124
+ }
125
+ interface CollectionOptions {
126
+ through: string,
127
+ where?: WhereOptions,
128
+ local?: boolean
129
+ }
130
+
131
+ export function subjectCollection(opts: CollectionOptions) {
132
+ return function <T>(target: T, key: keyof T) {
133
+ target["__collections"] = target["__collections"] || {};
134
+ target["__collections"][key] = opts;
135
+
136
+ const value = key as string
137
+ target[`add${capitalize(value)}`] = () => {}
138
+ target[`remove${capitalize(value)}`] = () => {}
139
+ target[`setCollection${capitalize(value)}`] = () => {}
140
+
141
+ Object.defineProperty(target, key, {configurable: true, writable: true});
142
+ };
143
+ }
144
+
145
+ export function makeRandomPrologAtom(length: number): string {
146
+ let result = '';
147
+ let characters = 'abcdefghijklmnopqrstuvwxyz';
148
+ let charactersLength = characters.length;
149
+ for (let i = 0; i < length; i++) {
150
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
151
+ }
152
+ return result;
153
+ }
154
+
155
+ interface SDNAClassOptions {
156
+ name: string;
157
+ }
158
+
159
+ export function SDNAClass(opts: SDNAClassOptions) {
160
+ return function (target: any) {
161
+ target.prototype.className = opts.name;
162
+ target.className = opts.name;
163
+
164
+ target.generateSDNA = function() {
165
+ let sdna = ""
166
+ let subjectName = opts.name
167
+ let obj = target.prototype;
168
+
169
+ let uuid = makeRandomPrologAtom(8)
170
+
171
+ sdna += `subject_class("${subjectName}", ${uuid}).\n`
172
+
173
+
174
+ let classRemoverActions = []
175
+
176
+ let constructorActions = []
177
+ if(obj.subjectConstructor && obj.subjectConstructor.length) {
178
+ constructorActions = constructorActions.concat(obj.subjectConstructor)
179
+ }
180
+
181
+ let instanceConditions = []
182
+ if(obj.isSubjectInstance && obj.isSubjectInstance.length) {
183
+ instanceConditions = instanceConditions.concat(obj.isSubjectInstance)
184
+ }
185
+
186
+ let propertiesCode = []
187
+ let properties = obj.__properties || {}
188
+ for(let property in properties) {
189
+ let propertyCode = `property(${uuid}, "${property}").\n`
190
+
191
+ let { through, initial, required, resolveLanguage, writable, flag, getter, setter, local } = properties[property]
192
+
193
+ if(resolveLanguage) {
194
+ propertyCode += `property_resolve(${uuid}, "${property}").\n`
195
+ propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`
196
+ }
197
+
198
+ if(getter) {
199
+ propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${getter}.\n`
200
+ } else if(through) {
201
+ propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`
202
+
203
+ if(required) {
204
+ if(flag) {
205
+ instanceConditions.push(`triple(Base, "${through}", "${initial}")`)
206
+ } else {
207
+ instanceConditions.push(`triple(Base, "${through}", _)`)
208
+ }
209
+ }
210
+ }
211
+
212
+ if(setter) {
213
+ propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${setter}.\n`
214
+ } else if (writable) {
215
+ let setter = obj[propertyNameToSetterName(property)]
216
+ if(typeof setter === "function") {
217
+ let action = [{
218
+ action: "setSingleTarget",
219
+ source: "this",
220
+ predicate: through,
221
+ target: "value",
222
+ ...(local && { local: true })
223
+ }]
224
+ propertyCode += `property_setter(${uuid}, "${property}", '${stringifyObjectLiteral(action)}').\n`
225
+ }
226
+ }
227
+
228
+ propertiesCode.push(propertyCode)
229
+
230
+ if(initial) {
231
+ constructorActions.push({
232
+ action: "addLink",
233
+ source: "this",
234
+ predicate: through,
235
+ target: initial,
236
+ })
237
+
238
+ classRemoverActions.push({
239
+ action: "removeLink",
240
+ source: "this",
241
+ predicate: through,
242
+ target: initial,
243
+ })
244
+ }
245
+ }
246
+
247
+ let collectionsCode = []
248
+ let collections = obj.__collections || {}
249
+ for(let collection in collections) {
250
+ let collectionCode = `collection(${uuid}, "${collection}").\n`
251
+
252
+ let { through, where, local} = collections[collection]
253
+
254
+ if(through) {
255
+ if(where) {
256
+ if(!where.isInstance && !where.condition) {
257
+ throw "'where' needs one of 'isInstance' or 'condition'"
258
+ }
259
+
260
+ let conditions = []
261
+
262
+ if(where.isInstance) {
263
+ let otherClass
264
+ if(where.isInstance.name) {
265
+ otherClass = where.isInstance.name
266
+ } else {
267
+ otherClass = where.isInstance
268
+ }
269
+ conditions.push(`instance(OtherClass, Target), subject_class("${otherClass}", OtherClass)`)
270
+ }
271
+
272
+ if(where.condition) {
273
+ conditions.push(where.condition)
274
+ }
275
+
276
+ const conditionString = conditions.join(", ")
277
+
278
+ collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- setof(Target, (triple(Base, "${through}", Target), ${conditionString}), List).\n`
279
+ } else {
280
+ collectionCode += `collection_getter(${uuid}, Base, "${collection}", List) :- findall(C, triple(Base, "${through}", C), List).\n`
281
+ }
282
+
283
+ let collectionAdderAction = [{
284
+ action: "addLink",
285
+ source: "this",
286
+ predicate: through,
287
+ target: "value",
288
+ ...(local && { local: true })
289
+ }]
290
+
291
+ let collectionRemoverAction = [{
292
+ action: "removeLink",
293
+ source: "this",
294
+ predicate: through,
295
+ target: "value",
296
+ }]
297
+
298
+ let collectionSetterAction = [{
299
+ action: "collectionSetter",
300
+ source: "this",
301
+ predicate: through,
302
+ target: "value",
303
+ ...(local && { local: true })
304
+ }]
305
+ collectionCode += `collection_adder(${uuid}, "${singularToPlural(collection)}", '${stringifyObjectLiteral(collectionAdderAction)}').\n`
306
+ collectionCode += `collection_remover(${uuid}, "${singularToPlural(collection)}", '${stringifyObjectLiteral(collectionRemoverAction)}').\n`
307
+ collectionCode += `collection_setter(${uuid}, "${singularToPlural(collection)}", '${stringifyObjectLiteral(collectionSetterAction)}').\n`
308
+ }
309
+
310
+ collectionsCode.push(collectionCode)
311
+ }
312
+
313
+ let subjectContructorJSONString = stringifyObjectLiteral(constructorActions)
314
+ sdna += `constructor(${uuid}, '${subjectContructorJSONString}').\n`
315
+ if(instanceConditions.length > 0) {
316
+ let instanceConditionProlog = instanceConditions.join(", ")
317
+ sdna += `instance(${uuid}, Base) :- ${instanceConditionProlog}.\n`
318
+ sdna += "\n"
319
+ }
320
+ sdna += `destructor(${uuid}, '${stringifyObjectLiteral(classRemoverActions)}').\n`
321
+ sdna += "\n"
322
+ sdna += propertiesCode.join("\n")
323
+ sdna += "\n"
324
+ sdna += collectionsCode.join("\n")
325
+
326
+ return {
327
+ sdna,
328
+ name: subjectName
329
+ }
330
+ }
331
+
332
+ Object.defineProperty(target, 'type', {configurable: true});
333
+ }
334
+ }
@@ -0,0 +1,153 @@
1
+ import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
2
+ import { collectionSetterToName, collectionToAdderName, collectionToRemoverName, collectionToSetterName, propertyNameToSetterName } from "./util";
3
+
4
+ export class Subject {
5
+ #baseExpression: string;
6
+ #subjectClass: string;
7
+ #perspective: PerspectiveProxy
8
+
9
+ constructor(perspective: PerspectiveProxy, baseExpression: string, subjectClass: string) {
10
+ this.#baseExpression = baseExpression
11
+ this.#subjectClass = subjectClass
12
+ this.#perspective = perspective
13
+ }
14
+
15
+ get baseExpression() {
16
+ return this.#baseExpression
17
+ }
18
+
19
+ async init() {
20
+ let isInstance = await this.#perspective.isSubjectInstance(this.#baseExpression, this.#subjectClass)
21
+ if(!isInstance) {
22
+ throw `Not a valid subject instance of ${this.#subjectClass} for ${this.#baseExpression}`
23
+ }
24
+
25
+ let results = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property(C, Property)`)
26
+ let properties = results.map(result => result.Property)
27
+ //console.log("Subject properties: " + properties)
28
+
29
+
30
+ for(let p of properties) {
31
+ const resolveExpressionURI = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property_resolve(C, "${p}")`)
32
+ Object.defineProperty(this, p, {
33
+ configurable: true,
34
+ get: async () => {
35
+ let results = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property_getter(C, "${this.#baseExpression}", "${p}", Value)`)
36
+ if(results && results.length > 0) {
37
+ let expressionURI = results[0].Value
38
+ if(resolveExpressionURI) {
39
+ try {
40
+ const expression = await this.#perspective.getExpression(expressionURI)
41
+ try {
42
+ return JSON.parse(expression.data)
43
+ } catch(e) {
44
+ return expression.data
45
+ }
46
+ } catch (err) {
47
+ return expressionURI
48
+ }
49
+ } else {
50
+ return expressionURI
51
+ }
52
+ } else if(results) {
53
+ return results
54
+ } else {
55
+ return undefined
56
+ }
57
+ }
58
+ })
59
+ }
60
+
61
+
62
+ const setters = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property_setter(C, Property, Setter)`)
63
+
64
+ //console.log("Subject setters: " + setters.map(setter => setter.Property))
65
+ for(let setter of (setters ? setters : [])) {
66
+ if(setter) {
67
+ const property = setter.Property
68
+ const actions = eval(setter.Setter)
69
+ const resolveLanguageResults = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), property_resolve_language(C, "${property}", Language)`)
70
+ let resolveLanguage
71
+ if(resolveLanguageResults && resolveLanguageResults.length > 0) {
72
+ resolveLanguage = resolveLanguageResults[0].Language
73
+ }
74
+ this[propertyNameToSetterName(property)] = async (value: any) => {
75
+ if(resolveLanguage) {
76
+ value = await this.#perspective.createExpression(value, resolveLanguage)
77
+ }
78
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{name: "value", value}])
79
+ }
80
+ }
81
+ }
82
+
83
+ let results2 = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection(C, Collection)`)
84
+ if(!results2) results2 = []
85
+ let collections = results2.map(result => result.Collection)
86
+
87
+ for(let c of collections) {
88
+ Object.defineProperty(this, c, {
89
+ configurable: true,
90
+ get: async () => {
91
+ let results = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection_getter(C, "${this.#baseExpression}", "${c}", Value)`)
92
+ if(results && results.length > 0 && results[0].Value) {
93
+ let collectionContent = results[0].Value.filter((v: any) => v !== "" && v !== '')
94
+ return collectionContent
95
+ } else {
96
+ return []
97
+ }
98
+ }
99
+ })
100
+ }
101
+
102
+ let adders = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection_adder(C, Collection, Adder)`)
103
+ if(!adders) adders = []
104
+
105
+ for(let adder of adders) {
106
+ if(adder) {
107
+ const collection = adder.Collection
108
+ const actions = eval(adder.Adder)
109
+ this[collectionToAdderName(collection)] = async (value: any) => {
110
+ if (Array.isArray(value)) {
111
+ await Promise.all(value.map(v => this.#perspective.executeAction(actions, this.#baseExpression, [{name: "value", value: v}])))
112
+ } else {
113
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{name: "value", value}])
114
+ }
115
+ }
116
+ }
117
+ }
118
+
119
+ let removers = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection_remover(C, Collection, Remover)`)
120
+ if(!removers) removers = []
121
+
122
+ for(let remover of removers) {
123
+ if(remover) {
124
+ const collection = remover.Collection
125
+ const actions = eval(remover.Remover)
126
+ this[collectionToRemoverName(collection)] = async (value: any) => {
127
+ if (Array.isArray(value)) {
128
+ await Promise.all(value.map(v => this.#perspective.executeAction(actions, this.#baseExpression, [{name: "value", value: v}])))
129
+ } else {
130
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{name: "value", value}])
131
+ }
132
+ }
133
+ }
134
+ }
135
+
136
+ let collectionSetters = await this.#perspective.infer(`subject_class("${this.#subjectClass}", C), collection_setter(C, Collection, Setter)`)
137
+ if(!collectionSetters) collectionSetters = []
138
+
139
+ for(let collectionSetter of collectionSetters) {
140
+ if(collectionSetter) {
141
+ const collection = collectionSetter.Collection
142
+ const actions = eval(collectionSetter.Setter)
143
+ this[collectionToSetterName(collection)] = async (value: any) => {
144
+ if (Array.isArray(value)) {
145
+ await this.#perspective.executeAction(actions, this.#baseExpression, value.map(v => ({name: "value", value: v})))
146
+ } else {
147
+ await this.#perspective.executeAction(actions, this.#baseExpression, [{name: "value", value}])
148
+ }
149
+ }
150
+ }
151
+ }
152
+ }
153
+ }