@coasys/ad4m 0.11.2-dev-multi-user-email → 0.11.2-dev-sdna-only-prolog

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.
@@ -958,14 +958,48 @@ export class PerspectiveProxy {
958
958
  */
959
959
  async isSubjectInstance(expression, subjectClass) {
960
960
  let className = await this.stringOrTemplateObjectToSubjectClassName(subjectClass);
961
- let isInstance = false;
962
- const maxAttempts = 5;
963
- let attempts = 0;
964
- while (attempts < maxAttempts && !isInstance) {
965
- isInstance = await this.infer(`subject_class("${className}", C), instance(C, "${expression}")`);
966
- attempts++;
961
+ // Get metadata from SDNA using Prolog metaprogramming
962
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
963
+ if (!metadata) {
964
+ return false;
967
965
  }
968
- return isInstance;
966
+ // If no required triples, any expression with links is an instance
967
+ if (metadata.requiredTriples.length === 0) {
968
+ console.log("no required triples, checking surrealDB");
969
+ const checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${expression}'`;
970
+ console.log("checkQuery", checkQuery);
971
+ const result = await this.querySurrealDB(checkQuery);
972
+ console.log("result", result);
973
+ const count = result[0]?.count ?? 0;
974
+ const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
975
+ return countValue > 0;
976
+ }
977
+ // Check if the expression has all required triples (predicate + optional exact target)
978
+ for (const triple of metadata.requiredTriples) {
979
+ console.log("checking triple", triple);
980
+ let checkQuery;
981
+ if (triple.target) {
982
+ // Flag: must match both predicate AND exact target value
983
+ checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${expression}' AND predicate = '${triple.predicate}' AND out.uri = '${triple.target}'`;
984
+ }
985
+ else {
986
+ // Property: just check predicate exists
987
+ checkQuery = `SELECT count() AS count FROM link WHERE in.uri = '${expression}' AND predicate = '${triple.predicate}'`;
988
+ }
989
+ console.log("checkQuery", checkQuery);
990
+ const result = await this.querySurrealDB(checkQuery);
991
+ console.log("result", result);
992
+ if (!result || result.length === 0) {
993
+ return false;
994
+ }
995
+ const count = result[0]?.count ?? 0;
996
+ // Handle potential object response like {Int: 0}
997
+ const countValue = typeof count === 'object' && count?.Int !== undefined ? count.Int : count;
998
+ if (countValue === 0) {
999
+ return false;
1000
+ }
1001
+ }
1002
+ return true;
969
1003
  }
970
1004
  /** For an existing subject instance (existing in the perspective's links)
971
1005
  * this function returns a proxy object that can be used to access the subject's
@@ -985,6 +1019,254 @@ export class PerspectiveProxy {
985
1019
  await subject.init();
986
1020
  return subject;
987
1021
  }
1022
+ /**
1023
+ * Extracts subject class metadata from SDNA by parsing the Prolog text.
1024
+ * Parses the instance rule to extract required predicates.
1025
+ * Returns required predicates that define what makes something an instance,
1026
+ * plus a map of property/collection names to their predicates.
1027
+ */
1028
+ async getSubjectClassMetadataFromSDNA(className) {
1029
+ try {
1030
+ // Get SDNA code from perspective - it's stored as a link
1031
+ const sdnaLinks = await this.get(new LinkQuery({
1032
+ source: `literal://string:${className}`,
1033
+ predicate: "ad4m://sdna"
1034
+ }));
1035
+ //console.log(`getSubjectClassMetadataFromSDNA: sdnaLinks for ${className}:`, sdnaLinks);
1036
+ if (!sdnaLinks || sdnaLinks.length === 0) {
1037
+ console.warn(`No SDNA found for class ${className}`);
1038
+ return null;
1039
+ }
1040
+ if (!sdnaLinks[0].data.target) {
1041
+ console.error(`SDNA link for ${className} has no target:`, sdnaLinks[0]);
1042
+ return null;
1043
+ }
1044
+ // Extract SDNA code from the literal
1045
+ const sdnaCode = Literal.fromUrl(sdnaLinks[0].data.target).get();
1046
+ //console.log("sdnaCode for", className, ":", sdnaCode.substring(0, 200));
1047
+ // Store required triples as {predicate, target?}
1048
+ // target is only set for flags (exact matches), otherwise undefined
1049
+ const requiredTriples = [];
1050
+ // Parse the instance rule from the SDNA code
1051
+ // Format: instance(c, Base) :- triple(Base, "pred1", _), triple(Base, "pred2", "exact_value").
1052
+ const instanceRuleMatch = sdnaCode.match(/instance\([^,]+,\s*\w+\)\s*:-\s*(.+?)\./s);
1053
+ if (instanceRuleMatch) {
1054
+ const ruleBody = instanceRuleMatch[1];
1055
+ console.log("instance rule body:", ruleBody);
1056
+ // Extract all triple(Base, "predicate", Target) patterns
1057
+ // Match both: triple(Base, "pred", _) and triple(Base, "pred", "value")
1058
+ const tripleRegex = /triple\([^,]+,\s*"([^"]+)",\s*(?:"([^"]+)"|_)\)/g;
1059
+ let match;
1060
+ while ((match = tripleRegex.exec(ruleBody)) !== null) {
1061
+ const predicate = match[1];
1062
+ const target = match[2]; // undefined if matched "_"
1063
+ requiredTriples.push({ predicate, target });
1064
+ console.log(`Extracted triple: predicate="${predicate}", target="${target}"`);
1065
+ }
1066
+ }
1067
+ else {
1068
+ console.warn(`No instance rule found in SDNA for ${className}`);
1069
+ }
1070
+ // For backward compatibility, also maintain requiredPredicates array
1071
+ const requiredPredicates = requiredTriples.map(t => t.predicate);
1072
+ console.log("extracted requiredTriples:", requiredTriples);
1073
+ // Extract property metadata
1074
+ const properties = new Map();
1075
+ const propertyResults = await this.infer(`subject_class("${className}", C), property(C, P)`);
1076
+ //console.log("propertyResults", propertyResults);
1077
+ if (propertyResults) {
1078
+ for (const result of propertyResults) {
1079
+ const propName = result.P;
1080
+ let predicate = null;
1081
+ // Try to extract predicate from property_setter first
1082
+ const setterResults = await this.infer(`subject_class("${className}", C), property_setter(C, "${propName}", Setter)`);
1083
+ if (setterResults && setterResults.length > 0) {
1084
+ const setterString = setterResults[0].Setter;
1085
+ const predicateMatch = setterString.match(/predicate:\s*"([^"]+)"|predicate:\s*([^,}\]]+)/);
1086
+ if (predicateMatch) {
1087
+ predicate = predicateMatch[1] || predicateMatch[2];
1088
+ }
1089
+ }
1090
+ // If no setter, try to extract from SDNA property_getter Prolog code
1091
+ if (!predicate) {
1092
+ // Parse the SDNA code for property_getter definition
1093
+ const getterMatch = sdnaCode.match(new RegExp(`property_getter\\([^,]+,\\s*[^,]+,\\s*"${propName}"[^)]*\\)\\s*:-\\s*triple\\([^,]+,\\s*"([^"]+)"`));
1094
+ if (getterMatch) {
1095
+ predicate = getterMatch[1];
1096
+ }
1097
+ }
1098
+ if (predicate) {
1099
+ // Check if property has resolveLanguage
1100
+ const resolveResults = await this.infer(`subject_class("${className}", C), property_resolve_language(C, "${propName}", Lang)`);
1101
+ const resolveLanguage = resolveResults && resolveResults.length > 0 ? resolveResults[0].Lang : undefined;
1102
+ properties.set(propName, { predicate, resolveLanguage });
1103
+ }
1104
+ }
1105
+ }
1106
+ //console.log("properties", properties);
1107
+ // Extract collection metadata
1108
+ const collections = new Map();
1109
+ const collectionResults = await this.infer(`subject_class("${className}", C), collection(C, Coll)`);
1110
+ //console.log("collectionResults", collectionResults);
1111
+ if (collectionResults) {
1112
+ for (const result of collectionResults) {
1113
+ const collName = result.Coll;
1114
+ let predicate = null;
1115
+ let instanceFilter = undefined;
1116
+ // Try to extract predicate from collection_adder first
1117
+ const adderResults = await this.infer(`subject_class("${className}", C), collection_adder(C, "${collName}", Adder)`);
1118
+ if (adderResults && adderResults.length > 0) {
1119
+ const adderString = adderResults[0].Adder;
1120
+ const predicateMatch = adderString.match(/predicate:\s*"([^"]+)"|predicate:\s*([^,}\]]+)/);
1121
+ if (predicateMatch) {
1122
+ predicate = predicateMatch[1] || predicateMatch[2];
1123
+ }
1124
+ }
1125
+ // Parse collection_getter from SDNA to extract predicate and instanceFilter
1126
+ // Format 1 (findall): collection_getter(c, Base, "comments", List) :- findall(C, triple(Base, "todo://comment", C), List).
1127
+ // Format 2 (setof): collection_getter(c, Base, "messages", List) :- setof(Target, (triple(Base, "flux://entry_type", Target), ...), List).
1128
+ // Use a line-based match to avoid capturing multiple collections
1129
+ const getterLinePattern = new RegExp(`collection_getter\\([^,]+,\\s*[^,]+,\\s*"${collName}"[^)]*\\)\\s*:-[^.]+\\.`);
1130
+ const getterLineMatch = sdnaCode.match(getterLinePattern);
1131
+ if (getterLineMatch) {
1132
+ const getterLine = getterLineMatch[0];
1133
+ // Extract the body between setof/findall and the final ).
1134
+ // Pattern: findall(Var, Body, List) or setof(Var, (Body), List)
1135
+ const bodyPattern = /(?:setof|findall)\([^,]+,\s*(.+),\s*\w+\)\./;
1136
+ const bodyMatch = getterLine.match(bodyPattern);
1137
+ if (bodyMatch) {
1138
+ let getterBody = bodyMatch[1];
1139
+ // Remove outer parentheses if present (setof case)
1140
+ if (getterBody.startsWith('(') && getterBody.endsWith(')')) {
1141
+ getterBody = getterBody.substring(1, getterBody.length - 1);
1142
+ }
1143
+ console.log(`Collection "${collName}" getter body:`, getterBody);
1144
+ // Extract predicate from triple(Base, "predicate", Target)
1145
+ if (!predicate) {
1146
+ const tripleMatch = getterBody.match(/triple\([^,]+,\s*"([^"]+)"/);
1147
+ if (tripleMatch) {
1148
+ predicate = tripleMatch[1];
1149
+ }
1150
+ }
1151
+ // Check for instance filter: subject_class("ClassName", OtherClass)
1152
+ const instanceMatch = getterBody.match(/subject_class\("([^"]+)"/);
1153
+ if (instanceMatch) {
1154
+ instanceFilter = instanceMatch[1];
1155
+ console.log(`Collection "${collName}" has instanceFilter: ${instanceFilter}`);
1156
+ }
1157
+ }
1158
+ }
1159
+ if (predicate) {
1160
+ collections.set(collName, { predicate, instanceFilter });
1161
+ }
1162
+ }
1163
+ }
1164
+ //console.log("collections", collections);
1165
+ return { requiredPredicates, requiredTriples, properties, collections };
1166
+ }
1167
+ catch (e) {
1168
+ console.error(`Error getting metadata for ${className}:`, e);
1169
+ return null;
1170
+ }
1171
+ }
1172
+ /**
1173
+ * Generates a SurrealDB query to find instances based on class metadata.
1174
+ */
1175
+ generateSurrealInstanceQuery(metadata) {
1176
+ console.log("generateSurrealInstanceQuery called with requiredTriples:", metadata.requiredTriples);
1177
+ if (metadata.requiredTriples.length === 0) {
1178
+ // No required triples - any node with links is an instance
1179
+ const query = `SELECT DISTINCT uri AS base FROM node WHERE count(->link) > 0`;
1180
+ console.log("Generated query (no required triples):", query);
1181
+ return query;
1182
+ }
1183
+ // Generate WHERE conditions for each required triple (predicate + optional exact target)
1184
+ const whereConditions = metadata.requiredTriples.map(triple => {
1185
+ if (triple.target) {
1186
+ // Flag: must match both predicate AND exact target value
1187
+ return `count(->link[WHERE predicate = '${triple.predicate}' AND out.uri = '${triple.target}']) > 0`;
1188
+ }
1189
+ else {
1190
+ // Property: just check predicate exists
1191
+ return `count(->link[WHERE predicate = '${triple.predicate}']) > 0`;
1192
+ }
1193
+ }).join(' AND ');
1194
+ const query = `SELECT uri AS base FROM node WHERE ${whereConditions}`;
1195
+ console.log("Generated query:", query);
1196
+ return query;
1197
+ }
1198
+ /**
1199
+ * Gets a property value using SurrealDB when Prolog fails.
1200
+ * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
1201
+ */
1202
+ async getPropertyValueViaSurreal(baseExpression, className, propertyName) {
1203
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1204
+ if (!metadata) {
1205
+ return undefined;
1206
+ }
1207
+ const propMeta = metadata.properties.get(propertyName);
1208
+ if (!propMeta) {
1209
+ return undefined;
1210
+ }
1211
+ const query = `SELECT out.uri AS value FROM link WHERE in.uri = '${baseExpression}' AND predicate = '${propMeta.predicate}' LIMIT 1`;
1212
+ const result = await this.querySurrealDB(query);
1213
+ if (!result || result.length === 0) {
1214
+ return undefined;
1215
+ }
1216
+ const value = result[0].value;
1217
+ // Handle expression resolution if needed
1218
+ if (propMeta.resolveLanguage && value) {
1219
+ try {
1220
+ const expression = await this.getExpression(value);
1221
+ try {
1222
+ return JSON.parse(expression.data);
1223
+ }
1224
+ catch (e) {
1225
+ return expression.data;
1226
+ }
1227
+ }
1228
+ catch (err) {
1229
+ return value;
1230
+ }
1231
+ }
1232
+ return value;
1233
+ }
1234
+ /**
1235
+ * Gets collection values using SurrealDB when Prolog fails.
1236
+ * This is used as a fallback in SdnaOnly mode where link data isn't in Prolog.
1237
+ */
1238
+ async getCollectionValuesViaSurreal(baseExpression, className, collectionName) {
1239
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1240
+ if (!metadata) {
1241
+ return [];
1242
+ }
1243
+ const collMeta = metadata.collections.get(collectionName);
1244
+ if (!collMeta) {
1245
+ return [];
1246
+ }
1247
+ const query = `SELECT out.uri AS value, timestamp FROM link WHERE in.uri = '${baseExpression}' AND predicate = '${collMeta.predicate}' ORDER BY timestamp ASC`;
1248
+ const result = await this.querySurrealDB(query);
1249
+ if (!result || result.length === 0) {
1250
+ return [];
1251
+ }
1252
+ let values = result.map(r => r.value).filter(v => v !== "" && v !== '');
1253
+ console.log(`getCollectionValuesViaSurreal: base="${baseExpression}", collection="${collectionName}", predicate="${collMeta.predicate}", found ${values.length} values:`, values);
1254
+ // Apply instance filter if present
1255
+ if (collMeta.instanceFilter) {
1256
+ console.log(` Applying instance filter "${collMeta.instanceFilter}" to collection "${collectionName}"`);
1257
+ const filteredValues = [];
1258
+ for (const value of values) {
1259
+ const isInstance = await this.isSubjectInstance(value, collMeta.instanceFilter);
1260
+ console.log(` Checking if "${value}" is instance of "${collMeta.instanceFilter}": ${isInstance}`);
1261
+ if (isInstance) {
1262
+ filteredValues.push(value);
1263
+ }
1264
+ }
1265
+ console.log(` After filtering: ${filteredValues.length} values`);
1266
+ return filteredValues;
1267
+ }
1268
+ return values;
1269
+ }
988
1270
  /** Returns all subject instances of the given subject class as proxy objects.
989
1271
  * @param subjectClass Either a string with the name of the subject class, or an object
990
1272
  * with the properties of the subject class. In the latter case, all subject classes
@@ -1000,10 +1282,32 @@ export class PerspectiveProxy {
1000
1282
  }
1001
1283
  let instances = [];
1002
1284
  for (let className of classes) {
1003
- let instanceBaseExpressions = await this.infer(`subject_class("${className}", C), instance(C, X)`);
1004
- let newInstances = await Promise.all(instanceBaseExpressions.map(async (x) => await this.getSubjectProxy(x.X, className)));
1005
- instances = instances.concat(newInstances);
1285
+ //console.log(`getAllSubjectInstances: Processing class ${className}`);
1286
+ // Query SDNA for metadata, then query SurrealDB for instances
1287
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1288
+ //console.log(`getAllSubjectInstances: Got metadata for ${className}:`, metadata);
1289
+ if (metadata) {
1290
+ const surrealQuery = this.generateSurrealInstanceQuery(metadata);
1291
+ const results = await this.querySurrealDB(surrealQuery);
1292
+ // console.log(`getAllSubjectInstances: SurrealDB returned ${results?.length || 0} results`);
1293
+ for (const result of results || []) {
1294
+ //console.log(`getAllSubjectInstances: Creating subject for base ${result.base}`);
1295
+ try {
1296
+ let subject = new Subject(this, result.base, className);
1297
+ await subject.init();
1298
+ instances.push(subject);
1299
+ //console.log(`getAllSubjectInstances: Successfully created subject for ${result.base}`);
1300
+ }
1301
+ catch (e) {
1302
+ //console.warn(`Failed to create subject for ${result.base}:`, e);
1303
+ }
1304
+ }
1305
+ }
1306
+ else {
1307
+ //console.warn(`getAllSubjectInstances: No metadata found for ${className}`);
1308
+ }
1006
1309
  }
1310
+ //console.log(`getAllSubjectInstances: Returning ${instances.length} instances`);
1007
1311
  return instances;
1008
1312
  }
1009
1313
  /** Returns all subject proxies of the given subject class.
@@ -1021,8 +1325,24 @@ export class PerspectiveProxy {
1021
1325
  }
1022
1326
  let instances = [];
1023
1327
  for (let className of classes) {
1024
- instances = await this.infer(`subject_class("${className}", C), instance(C, X)`);
1328
+ //console.log(`getAllSubjectProxies: Processing class ${className}`);
1329
+ // Query SDNA for metadata, then query SurrealDB for instances
1330
+ const metadata = await this.getSubjectClassMetadataFromSDNA(className);
1331
+ //console.log(`getAllSubjectProxies: Got metadata for ${className}`);
1332
+ if (metadata) {
1333
+ const surrealQuery = this.generateSurrealInstanceQuery(metadata);
1334
+ console.log("surrealQuery", surrealQuery);
1335
+ const results = await this.querySurrealDB(surrealQuery);
1336
+ console.log(`getAllSubjectProxies: SurrealDB returned ${results?.length || 0} results`);
1337
+ const newInstance = results.map(r => ({ X: r.base }));
1338
+ console.log("newInstance", newInstance);
1339
+ instances = instances.concat(newInstance);
1340
+ }
1341
+ else {
1342
+ console.warn(`getAllSubjectProxies: No metadata found for ${className}`);
1343
+ }
1025
1344
  }
1345
+ //console.log(`getAllSubjectProxies: Returning ${instances.length} proxies`);
1026
1346
  return instances;
1027
1347
  }
1028
1348
  buildQueryFromTemplate(obj) {
@@ -73,6 +73,7 @@ export declare class VerificationRequestResult {
73
73
  success: boolean;
74
74
  message: string;
75
75
  requiresPassword: boolean;
76
+ isExistingUser: boolean;
76
77
  }
77
78
  /**
78
79
  * Resolver classes are used here to define the GraphQL schema
@@ -307,6 +307,10 @@ __decorate([
307
307
  Field(),
308
308
  __metadata("design:type", Boolean)
309
309
  ], VerificationRequestResult.prototype, "requiresPassword", void 0);
310
+ __decorate([
311
+ Field(),
312
+ __metadata("design:type", Boolean)
313
+ ], VerificationRequestResult.prototype, "isExistingUser", void 0);
310
314
  VerificationRequestResult = __decorate([
311
315
  ObjectType()
312
316
  ], VerificationRequestResult);
@@ -479,7 +483,8 @@ let RuntimeResolver = class RuntimeResolver {
479
483
  return {
480
484
  success: true,
481
485
  message: "Verification email sent",
482
- requiresPassword: false
486
+ requiresPassword: false,
487
+ isExistingUser: true
483
488
  };
484
489
  }
485
490
  runtimeVerifyEmailCode(email, code, verificationType) {
@@ -576,6 +576,7 @@ type UserStatistics {
576
576
  }
577
577
 
578
578
  type VerificationRequestResult {
579
+ isExistingUser: Boolean!
579
580
  message: String!
580
581
  requiresPassword: Boolean!
581
582
  success: Boolean!
@@ -572,6 +572,7 @@ type UserStatistics {
572
572
  }
573
573
 
574
574
  type VerificationRequestResult {
575
+ isExistingUser: Boolean!
575
576
  message: String!
576
577
  requiresPassword: Boolean!
577
578
  success: Boolean!
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "module": "lib/index.js",
6
6
  "types": "lib/src/index.d.ts",
7
7
  "type": "module",
8
-
8
+
9
9
  "scripts": {
10
10
  "build": "patch-package && tsc && pnpm run buildSchema && pnpm run bundle",
11
11
  "buildSchema": "node --es-module-specifier-resolution=node lib/src/buildSchema.js",
@@ -69,5 +69,5 @@
69
69
  "graphql@15.7.2": "patches/graphql@15.7.2.patch"
70
70
  }
71
71
  },
72
- "version": "0.11.2-dev-multi-user-email"
72
+ "version": "0.11.2-dev-sdna-only-prolog"
73
73
  }
@@ -568,6 +568,7 @@ export class AgentClient {
568
568
  success
569
569
  message
570
570
  requiresPassword
571
+ isExistingUser
571
572
  }
572
573
  }`,
573
574
  variables: { email, appInfo },