@coasys/ad4m 0.10.1-dev-1 → 0.10.1-multi-user-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.
@@ -291,3 +291,39 @@ export class AuthInfoInput {
291
291
  this.appIconPath = appIconPath;
292
292
  }
293
293
  }
294
+
295
+ @ObjectType()
296
+ export class User {
297
+ @Field()
298
+ username: string;
299
+
300
+ @Field()
301
+ did: string;
302
+
303
+ @Field()
304
+ password: string;
305
+
306
+ constructor(username: string, did: string, password: string) {
307
+ this.username = username;
308
+ this.did = did;
309
+ this.password = password;
310
+ }
311
+ }
312
+
313
+ @ObjectType()
314
+ export class UserCreationResult {
315
+ @Field()
316
+ did: string;
317
+
318
+ @Field()
319
+ success: boolean;
320
+
321
+ @Field({ nullable: true })
322
+ error?: string;
323
+
324
+ constructor(did: string, success: boolean, error?: string) {
325
+ this.did = did;
326
+ this.success = success;
327
+ this.error = error;
328
+ }
329
+ }
@@ -8,6 +8,7 @@ import {
8
8
  AuthInfoInput,
9
9
  EntanglementProof,
10
10
  EntanglementProofInput,
11
+ UserCreationResult,
11
12
  } from "./Agent";
12
13
  import { AgentStatus } from "./AgentStatus";
13
14
  import { LinkMutations } from "../links/Links";
@@ -528,4 +529,33 @@ export class AgentClient {
528
529
  );
529
530
  return agentSignMessage;
530
531
  }
532
+
533
+ // Multi-user methods
534
+ async createUser(email: string, password: string): Promise<UserCreationResult> {
535
+ const { runtimeCreateUser } = unwrapApolloResult(
536
+ await this.#apolloClient.mutate({
537
+ mutation: gql`mutation runtimeCreateUser($email: String!, $password: String!) {
538
+ runtimeCreateUser(email: $email, password: $password) {
539
+ did
540
+ success
541
+ error
542
+ }
543
+ }`,
544
+ variables: { email, password },
545
+ })
546
+ );
547
+ return runtimeCreateUser;
548
+ }
549
+
550
+ async loginUser(email: string, password: string): Promise<string> {
551
+ const { runtimeLoginUser } = unwrapApolloResult(
552
+ await this.#apolloClient.mutate({
553
+ mutation: gql`mutation runtimeLoginUser($email: String!, $password: String!) {
554
+ runtimeLoginUser(email: $email, password: $password)
555
+ }`,
556
+ variables: { email, password },
557
+ })
558
+ );
559
+ return runtimeLoginUser;
560
+ }
531
561
  }
@@ -168,10 +168,10 @@ export interface LinkSyncAdapter {
168
168
  /** What revision are we on now -> what changes are included in output of render() */
169
169
  currentRevision(): Promise<string>;
170
170
 
171
- /**
172
- * Check for and get new changes,
171
+ /**
172
+ * Check for and get new changes,
173
173
  * notify others of local changes.
174
- * This function will be called every
174
+ * This function will be called every
175
175
  * few seconds by the ad4m-executor.
176
176
  * */
177
177
  sync(): Promise<PerspectiveDiff>;
@@ -187,6 +187,18 @@ export interface LinkSyncAdapter {
187
187
 
188
188
  /** Add a sync state callback method */
189
189
  addSyncStateChangeCallback(callback: SyncStateChangeObserver);
190
+
191
+ /**
192
+ * Set the local agents (DIDs) that own this perspective/neighbourhood.
193
+ * This is used to determine which agents should be registered in the DHT.
194
+ * Optional - if not implemented, all local agents may be registered.
195
+ *
196
+ * This is a temporary hack to support multiple users on one node joining the same neighbourhood.
197
+ * Once we migrate the LanguageController to Rust and run Languages per user, each user will get their
198
+ * own language instance and we won't need to explicitly set local agents. This will provide better
199
+ * isolation and avoid the need to share language state between users.
200
+ */
201
+ setLocalAgents?(agents: DID[]): void;
190
202
  }
191
203
 
192
204
  export type MessageCallback = (message: PerspectiveExpression) => void;
@@ -255,7 +267,7 @@ export class OnlineAgent {
255
267
  status: PerspectiveExpression
256
268
  }
257
269
 
258
- export type TelepresenceSignalCallback = (payload: PerspectiveExpression) => void;
270
+ export type TelepresenceSignalCallback = (payload: PerspectiveExpression, recipientDid?: string) => void;
259
271
  export interface TelepresenceAdapter {
260
272
  setOnlineStatus(status: PerspectiveExpression): Promise<void>;
261
273
  getOnlineAgents(): Promise<OnlineAgent[]>;
@@ -1,47 +1,8 @@
1
1
  import { Literal } from "../Literal";
2
2
  import { Link } from "../links/Links";
3
3
  import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
4
- import { makeRandomPrologAtom, PropertyOptions, CollectionOptions, ModelOptions } from "./decorators";
5
- import { singularToPlural, pluralToSingular, propertyNameToSetterName, collectionToAdderName, collectionToRemoverName, collectionToSetterName } from "./util";
6
-
7
- // JSON Schema type definitions
8
- interface JSONSchemaProperty {
9
- type: string | string[];
10
- items?: JSONSchemaProperty;
11
- properties?: { [key: string]: JSONSchemaProperty };
12
- required?: string[];
13
- "x-ad4m"?: {
14
- through?: string;
15
- resolveLanguage?: string;
16
- local?: boolean;
17
- writable?: boolean;
18
- initial?: string;
19
- };
20
- }
21
-
22
- interface JSONSchema {
23
- $schema?: string;
24
- title?: string;
25
- $id?: string;
26
- type?: string;
27
- properties?: { [key: string]: JSONSchemaProperty };
28
- required?: string[];
29
- "x-ad4m"?: {
30
- namespace?: string;
31
- className?: string;
32
- };
33
- }
34
-
35
- interface JSONSchemaToModelOptions {
36
- name: string;
37
- namespace?: string;
38
- predicateTemplate?: string;
39
- predicateGenerator?: (title: string, property: string) => string;
40
- propertyMapping?: Record<string, string>;
41
- resolveLanguage?: string;
42
- local?: boolean;
43
- propertyOptions?: Record<string, Partial<PropertyOptions>>;
44
- }
4
+ import { makeRandomPrologAtom } from "./decorators";
5
+ import { singularToPlural } from "./util";
45
6
 
46
7
  type ValueTuple = [name: string, value: any, resolve?: boolean];
47
8
  type WhereOps = {
@@ -938,339 +899,6 @@ export class Ad4mModel {
938
899
  ): ModelQueryBuilder<T> {
939
900
  return new ModelQueryBuilder<T>(perspective, this as any, query);
940
901
  }
941
-
942
- /**
943
- * Creates an Ad4mModel class from a JSON Schema definition.
944
- *
945
- * @description
946
- * This method dynamically generates an Ad4mModel subclass from a JSON Schema,
947
- * enabling integration with systems that use JSON Schema for type definitions.
948
- *
949
- * The method follows a cascading approach for determining predicates:
950
- * 1. Explicit configuration in options parameter (highest precedence)
951
- * 2. x-ad4m metadata in the JSON Schema
952
- * 3. Inference from schema title and property names
953
- * 4. Error if no namespace can be determined
954
- *
955
- * @example
956
- * ```typescript
957
- * // With explicit configuration
958
- * const PersonClass = Ad4mModel.fromJSONSchema(schema, {
959
- * name: "Person",
960
- * namespace: "person://",
961
- * resolveLanguage: "literal"
962
- * });
963
- *
964
- * // With property mapping
965
- * const ContactClass = Ad4mModel.fromJSONSchema(schema, {
966
- * name: "Contact",
967
- * namespace: "contact://",
968
- * propertyMapping: {
969
- * "name": "foaf://name",
970
- * "email": "foaf://mbox"
971
- * }
972
- * });
973
- *
974
- * // With x-ad4m metadata in schema
975
- * const schema = {
976
- * "title": "Product",
977
- * "x-ad4m": { "namespace": "product://" },
978
- * "properties": {
979
- * "name": {
980
- * "type": "string",
981
- * "x-ad4m": { "through": "product://title" }
982
- * }
983
- * }
984
- * };
985
- * const ProductClass = Ad4mModel.fromJSONSchema(schema, { name: "Product" });
986
- * ```
987
- *
988
- * @param schema - JSON Schema definition
989
- * @param options - Configuration options
990
- * @returns Generated Ad4mModel subclass
991
- * @throws Error when namespace cannot be inferred
992
- */
993
- static fromJSONSchema(
994
- schema: JSONSchema,
995
- options: JSONSchemaToModelOptions
996
- ): typeof Ad4mModel {
997
- // Disallow top-level "author" property since Ad4mModel provides it implicitly via link authorship
998
- if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
999
- throw new Error('JSON Schema must not define a top-level "author" property because Ad4mModel already exposes it. Please rename the property (e.g., "writer").');
1000
- }
1001
- // Determine namespace with cascading precedence
1002
- const namespace = this.determineNamespace(schema, options);
1003
-
1004
- // Create the dynamic class
1005
- const DynamicModelClass = class extends Ad4mModel {};
1006
-
1007
- // Set up class metadata
1008
- Object.defineProperty(DynamicModelClass, 'name', { value: options.name });
1009
- (DynamicModelClass as any).className = options.name;
1010
- (DynamicModelClass.prototype as any).className = options.name;
1011
-
1012
- // Generate properties and collections metadata
1013
- const properties: any = {};
1014
- const collections: any = {};
1015
-
1016
- if (schema.properties) {
1017
- for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
1018
- const predicate = this.determinePredicate(schema, propertyName, propertySchema, namespace, options);
1019
- const isRequired = schema.required?.includes(propertyName) || false;
1020
- const isArray = propertySchema.type === 'array';
1021
-
1022
- if (isArray) {
1023
- // Handle arrays as collections
1024
- // Store the singular form as the collection key since SDNA generation expects singular
1025
- collections[propertyName] = {
1026
- through: predicate,
1027
- local: this.getPropertyOption(propertyName, propertySchema, options, 'local')
1028
- };
1029
-
1030
- // Define the property on prototype
1031
- Object.defineProperty(DynamicModelClass.prototype, propertyName, {
1032
- configurable: true,
1033
- writable: true,
1034
- value: []
1035
- });
1036
-
1037
- // Add collection methods
1038
- const adderName = `add${capitalize(propertyName)}`;
1039
- const removerName = `remove${capitalize(propertyName)}`;
1040
- const setterName = `setCollection${capitalize(propertyName)}`;
1041
-
1042
- (DynamicModelClass.prototype as any)[adderName] = function() {
1043
- // Placeholder function for SDNA generation
1044
- };
1045
- (DynamicModelClass.prototype as any)[removerName] = function() {
1046
- // Placeholder function for SDNA generation
1047
- };
1048
- (DynamicModelClass.prototype as any)[setterName] = function() {
1049
- // Placeholder function for SDNA generation
1050
- };
1051
-
1052
- } else {
1053
- // Handle regular properties
1054
- let resolveLanguage = this.getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
1055
- // If no specific resolveLanguage for this property, use the global one
1056
- if (!resolveLanguage && options.resolveLanguage) {
1057
- resolveLanguage = options.resolveLanguage;
1058
- }
1059
- const local = this.getPropertyOption(propertyName, propertySchema, options, 'local');
1060
- const writable = this.getPropertyOption(propertyName, propertySchema, options, 'writable', true);
1061
- let initial = this.getPropertyOption(propertyName, propertySchema, options, 'initial');
1062
-
1063
- // Handle nested objects by serializing to JSON
1064
- if (propertySchema.type === 'object' && !resolveLanguage) {
1065
- resolveLanguage = 'literal';
1066
- console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
1067
- }
1068
-
1069
- // Ensure numeric properties use literal language for correct typing
1070
- if ((resolveLanguage === undefined || resolveLanguage === null) && (propertySchema.type === 'number' || propertySchema.type === 'integer')) {
1071
- resolveLanguage = 'literal';
1072
- }
1073
-
1074
- // If property is required, ensure it has an initial value
1075
- if (isRequired && !initial) {
1076
- if (propertySchema.type === 'object') {
1077
- initial = 'literal://json:{}';
1078
- } else {
1079
- initial = "ad4m://undefined";
1080
- }
1081
- }
1082
-
1083
- properties[propertyName] = {
1084
- through: predicate,
1085
- required: isRequired,
1086
- writable: writable,
1087
- ...(resolveLanguage && { resolveLanguage }),
1088
- ...(local !== undefined && { local }),
1089
- ...(initial && { initial })
1090
- };
1091
-
1092
- // Define the property on prototype
1093
- Object.defineProperty(DynamicModelClass.prototype, propertyName, {
1094
- configurable: true,
1095
- writable: true,
1096
- value: this.getDefaultValueForType(propertySchema.type as string)
1097
- });
1098
-
1099
- // Add setter function if writable
1100
- if (writable) {
1101
- const setterName = propertyNameToSetterName(propertyName);
1102
- (DynamicModelClass.prototype as any)[setterName] = function() {
1103
- // This is a placeholder function that the SDNA generation looks for
1104
- // The actual setter logic is handled by the Ad4mModel base class
1105
- };
1106
- }
1107
- }
1108
- }
1109
- }
1110
-
1111
- // Validate that at least one property has an initial value (needed for valid SDNA constructor)
1112
- // Collections don't create constructor actions, only properties with initial values do
1113
- const hasPropertyWithInitial = Object.values(properties).some((prop: any) => prop.initial);
1114
-
1115
- if (!hasPropertyWithInitial) {
1116
- // If no properties have initial values, add a type identifier automatically
1117
- const typeProperty = `ad4m://type`;
1118
- const typeValue = `${namespace.replace('://', '')}://instance`;
1119
-
1120
- properties['__ad4m_type'] = {
1121
- through: typeProperty,
1122
- required: true,
1123
- writable: false,
1124
- initial: typeValue,
1125
- flag: true
1126
- };
1127
-
1128
- // Add the type property to the prototype
1129
- Object.defineProperty(DynamicModelClass.prototype, '__ad4m_type', {
1130
- configurable: true,
1131
- writable: false,
1132
- value: typeValue
1133
- });
1134
-
1135
- console.warn(`No properties with initial values found. Added automatic type flag: ${typeProperty} = ${typeValue}`);
1136
- }
1137
-
1138
- // Attach metadata to prototype
1139
- (DynamicModelClass.prototype as any).__properties = properties;
1140
- (DynamicModelClass.prototype as any).__collections = collections;
1141
-
1142
- // Apply the ModelOptions decorator to set up the generateSDNA method
1143
- const ModelOptionsDecorator = ModelOptions({ name: options.name });
1144
- ModelOptionsDecorator(DynamicModelClass);
1145
-
1146
- return DynamicModelClass as typeof Ad4mModel;
1147
- }
1148
-
1149
- /**
1150
- * Determines the namespace for predicates using cascading precedence
1151
- */
1152
- private static determineNamespace(schema: JSONSchema, options: JSONSchemaToModelOptions): string {
1153
- // 1. Explicit namespace in options (highest precedence)
1154
- if (options.namespace) {
1155
- return options.namespace;
1156
- }
1157
-
1158
- // 2. x-ad4m metadata in schema
1159
- if (schema["x-ad4m"]?.namespace) {
1160
- return schema["x-ad4m"].namespace;
1161
- }
1162
-
1163
- // 3. Infer from schema title
1164
- if (schema.title) {
1165
- return `${schema.title.toLowerCase()}://`;
1166
- }
1167
-
1168
- // 4. Try to extract from $id if it's a URL
1169
- if (schema.$id) {
1170
- try {
1171
- const url = new URL(schema.$id);
1172
- const pathParts = url.pathname.split('/').filter(p => p);
1173
- if (pathParts.length > 0) {
1174
- const lastPart = pathParts[pathParts.length - 1];
1175
- const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
1176
- return `${baseName.toLowerCase()}://`;
1177
- }
1178
- } catch {
1179
- // If $id is not a valid URL, continue to error
1180
- }
1181
- }
1182
-
1183
- // 5. Error if no namespace can be determined
1184
- throw new Error(
1185
- `Cannot infer namespace for JSON Schema. Please provide one of:
1186
- - options.namespace
1187
- - schema["x-ad4m"].namespace
1188
- - schema.title
1189
- - valid schema.$id`
1190
- );
1191
- }
1192
-
1193
- /**
1194
- * Determines the predicate for a specific property using cascading precedence
1195
- */
1196
- private static determinePredicate(
1197
- schema: JSONSchema,
1198
- propertyName: string,
1199
- propertySchema: JSONSchemaProperty,
1200
- namespace: string,
1201
- options: JSONSchemaToModelOptions
1202
- ): string {
1203
- // 1. Explicit property mapping (highest precedence)
1204
- if (options.propertyMapping?.[propertyName]) {
1205
- return options.propertyMapping[propertyName];
1206
- }
1207
-
1208
- // 2. x-ad4m metadata in property schema
1209
- if (propertySchema["x-ad4m"]?.through) {
1210
- return propertySchema["x-ad4m"].through;
1211
- }
1212
-
1213
- // 3. Generate from namespace + property name
1214
- if (options.predicateTemplate) {
1215
- return options.predicateTemplate
1216
- .replace('${namespace}', namespace.replace('://', ''))
1217
- .replace('${title}', schema.title || '')
1218
- .replace('${property}', propertyName);
1219
- }
1220
-
1221
- // 4. Custom predicate generator
1222
- if (options.predicateGenerator) {
1223
- return options.predicateGenerator(schema.title || '', propertyName);
1224
- }
1225
-
1226
- // 5. Default: namespace + property name
1227
- const cleanNamespace = namespace.endsWith('://') ? namespace.slice(0, -3) : namespace;
1228
- return `${cleanNamespace}://${propertyName}`;
1229
- }
1230
-
1231
- /**
1232
- * Gets property-specific options using cascading precedence
1233
- */
1234
- private static getPropertyOption(
1235
- propertyName: string,
1236
- propertySchema: JSONSchemaProperty,
1237
- options: JSONSchemaToModelOptions,
1238
- optionName: keyof PropertyOptions,
1239
- defaultValue?: any
1240
- ): any {
1241
- // 1. Property-specific options
1242
- if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
1243
- return options.propertyOptions[propertyName][optionName];
1244
- }
1245
-
1246
- // 2. x-ad4m metadata in property
1247
- if (propertySchema["x-ad4m"]?.[optionName as keyof JSONSchemaProperty["x-ad4m"]] !== undefined) {
1248
- return propertySchema["x-ad4m"][optionName as keyof JSONSchemaProperty["x-ad4m"]];
1249
- }
1250
-
1251
- // 3. Global option
1252
- if (options[optionName as keyof JSONSchemaToModelOptions] !== undefined) {
1253
- return options[optionName as keyof JSONSchemaToModelOptions];
1254
- }
1255
-
1256
- // 4. Default value
1257
- return defaultValue;
1258
- }
1259
-
1260
- /**
1261
- * Gets default value for a JSON Schema type
1262
- */
1263
- private static getDefaultValueForType(type: string): any {
1264
- switch (type) {
1265
- case 'string': return '';
1266
- case 'number': return 0;
1267
- case 'integer': return 0;
1268
- case 'boolean': return false;
1269
- case 'array': return [];
1270
- case 'object': return {};
1271
- default: return '';
1272
- }
1273
- }
1274
902
  }
1275
903
 
1276
904
  /** Query builder for Ad4mModel queries.
@@ -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, NotificationInput, Notification, TriggeredNotification, ImportResult } from "./RuntimeResolver"
4
+ import { RuntimeInfo, ExceptionInfo, SentMessage, NotificationInput, Notification, TriggeredNotification, ImportResult, UserStatistics } from "./RuntimeResolver"
5
5
 
6
6
  const PERSPECTIVE_EXPRESSION_FIELDS = `
7
7
  author
@@ -386,6 +386,39 @@ export class RuntimeClient {
386
386
  return runtimeImportPerspective
387
387
  }
388
388
 
389
+ async multiUserEnabled(): Promise<boolean> {
390
+ const { runtimeMultiUserEnabled } = unwrapApolloResult(await this.#apolloClient.query({
391
+ query: gql`query runtimeMultiUserEnabled {
392
+ runtimeMultiUserEnabled
393
+ }`,
394
+ }))
395
+ return runtimeMultiUserEnabled
396
+ }
397
+
398
+ async setMultiUserEnabled(enabled: boolean): Promise<boolean> {
399
+ const { runtimeSetMultiUserEnabled } = unwrapApolloResult(await this.#apolloClient.mutate({
400
+ mutation: gql`mutation runtimeSetMultiUserEnabled($enabled: Boolean!) {
401
+ runtimeSetMultiUserEnabled(enabled: $enabled)
402
+ }`,
403
+ variables: { enabled }
404
+ }))
405
+ return runtimeSetMultiUserEnabled
406
+ }
407
+
408
+ async listUsers(): Promise<UserStatistics[]> {
409
+ const { runtimeListUsers } = unwrapApolloResult(await this.#apolloClient.query({
410
+ query: gql`query runtimeListUsers {
411
+ runtimeListUsers {
412
+ email
413
+ did
414
+ lastSeen
415
+ perspectiveCount
416
+ }
417
+ }`
418
+ }))
419
+ return runtimeListUsers
420
+ }
421
+
389
422
  addNotificationTriggeredCallback(cb: NotificationTriggeredCallback) {
390
423
  this.#notificationTriggeredCallbacks.push(cb)
391
424
  }
@@ -192,6 +192,21 @@ export class ImportResult {
192
192
  knownLinkLanguages: ImportStats;
193
193
  }
194
194
 
195
+ @ObjectType()
196
+ export class UserStatistics {
197
+ @Field()
198
+ email: string;
199
+
200
+ @Field()
201
+ did: string;
202
+
203
+ @Field({nullable: true})
204
+ lastSeen?: string;
205
+
206
+ @Field(type => Int)
207
+ perspectiveCount: number;
208
+ }
209
+
195
210
  /**
196
211
  * Resolver classes are used here to define the GraphQL schema
197
212
  * (through the type-graphql annotations)
@@ -426,5 +441,25 @@ export default class RuntimeResolver {
426
441
  runtimeImportPerspective(@Arg("filePath", type => String) filePath: string): boolean {
427
442
  return true
428
443
  }
444
+
445
+ @Query(returns => Boolean)
446
+ runtimeMultiUserEnabled(): boolean {
447
+ return false
448
+ }
449
+
450
+ @Mutation(returns => Boolean)
451
+ runtimeSetMultiUserEnabled(@Arg("enabled") enabled: boolean): boolean {
452
+ return enabled
453
+ }
454
+
455
+ @Query(returns => [UserStatistics])
456
+ runtimeListUsers(): UserStatistics[] {
457
+ return [{
458
+ email: "test@example.com",
459
+ did: "did:key:test123",
460
+ lastSeen: new Date().toISOString(),
461
+ perspectiveCount: 5
462
+ }]
463
+ }
429
464
  }
430
465