@coasys/ad4m 0.12.0-rc1-dev.2 → 0.12.0-rc1-dev.3

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 (153) hide show
  1. package/jest.config.js +10 -3
  2. package/lib/index.cjs +6872 -5886
  3. package/lib/index.js +6868 -5874
  4. package/lib/src/Ad4mClient.d.ts +9 -16
  5. package/lib/src/Ad4mClient.js +46 -25
  6. package/lib/src/Literal.d.ts +1 -2
  7. package/lib/src/Literal.js +38 -35
  8. package/lib/src/SmartLiteral.d.ts +1 -2
  9. package/lib/src/SmartLiteral.js +30 -15
  10. package/lib/src/agent/AgentClient.d.ts +1 -4
  11. package/lib/src/agent/AgentClient.js +79 -99
  12. package/lib/src/ai/AIClient.d.ts +1 -2
  13. package/lib/src/ai/AIClient.js +224 -220
  14. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  15. package/lib/src/expression/ExpressionClient.js +73 -86
  16. package/lib/src/index.d.ts +1 -1
  17. package/lib/src/index.js +1 -1
  18. package/lib/src/language/LanguageClient.d.ts +1 -1
  19. package/lib/src/language/LanguageClient.js +52 -52
  20. package/lib/src/model/Ad4mModel.d.ts +1351 -144
  21. package/lib/src/model/Ad4mModel.js +3737 -228
  22. package/lib/src/model/Ad4mModel.test.js +522 -979
  23. package/lib/src/model/Subject.d.ts +3 -3
  24. package/lib/src/model/Subject.js +25 -25
  25. package/lib/src/model/decorators.d.ts +444 -100
  26. package/lib/src/model/decorators.js +686 -321
  27. package/lib/src/model/util.d.ts +6 -6
  28. package/lib/src/model/util.js +24 -24
  29. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +1 -5
  30. package/lib/src/neighbourhood/NeighbourhoodClient.js +179 -242
  31. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +1 -2
  32. package/lib/src/neighbourhood/NeighbourhoodProxy.js +28 -13
  33. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +5 -1
  34. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  35. package/lib/src/perspectives/PerspectiveClient.js +240 -316
  36. package/lib/src/perspectives/PerspectiveProxy.d.ts +99 -61
  37. package/lib/src/perspectives/PerspectiveProxy.js +485 -832
  38. package/lib/src/runtime/RuntimeClient.d.ts +1 -5
  39. package/lib/src/runtime/RuntimeClient.js +238 -412
  40. package/lib/src/shacl/SHACLFlow.test.js +105 -164
  41. package/lib/src/shacl/SHACLShape.d.ts +12 -17
  42. package/lib/src/shacl/SHACLShape.js +115 -128
  43. package/lib/src/shacl/SHACLShape.test.js +176 -244
  44. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  45. package/lib/src/shims/type-graphql.d.ts +32 -0
  46. package/lib/src/src/Ad4mClient.d.ts +28 -0
  47. package/lib/src/src/Address.d.ts +1 -0
  48. package/lib/src/src/DID.d.ts +1 -0
  49. package/lib/src/src/Exception.d.ts +7 -0
  50. package/lib/src/src/Literal.d.ts +7 -0
  51. package/lib/src/src/PubSub.d.ts +17 -0
  52. package/lib/src/src/SmartLiteral.d.ts +12 -0
  53. package/lib/src/src/agent/Agent.d.ts +110 -0
  54. package/lib/src/src/agent/AgentClient.d.ts +62 -0
  55. package/lib/src/src/agent/AgentResolver.d.ts +30 -0
  56. package/lib/src/src/agent/AgentStatus.d.ts +8 -0
  57. package/lib/src/src/ai/AIClient.d.ts +32 -0
  58. package/lib/src/src/ai/AIResolver.d.ts +75 -0
  59. package/lib/src/src/ai/Tasks.d.ts +37 -0
  60. package/lib/src/src/buildSchema.d.ts +1 -0
  61. package/lib/src/src/expression/Expression.d.ts +28 -0
  62. package/lib/src/src/expression/ExpressionClient.d.ts +13 -0
  63. package/lib/src/src/expression/ExpressionRef.d.ts +9 -0
  64. package/lib/src/src/expression/ExpressionResolver.d.ts +10 -0
  65. package/lib/src/src/index.d.ts +35 -0
  66. package/lib/src/src/jestSetup.d.ts +1 -0
  67. package/lib/src/src/language/Icon.d.ts +4 -0
  68. package/lib/src/src/language/Language.d.ts +206 -0
  69. package/lib/src/src/language/LanguageClient.d.ts +17 -0
  70. package/lib/src/src/language/LanguageContext.d.ts +37 -0
  71. package/lib/src/src/language/LanguageHandle.d.ts +9 -0
  72. package/lib/src/src/language/LanguageMeta.d.ts +35 -0
  73. package/lib/src/src/language/LanguageRef.d.ts +6 -0
  74. package/lib/src/src/language/LanguageResolver.d.ts +19 -0
  75. package/lib/src/src/links/Links.d.ts +39 -0
  76. package/lib/src/src/links/Links.test.d.ts +1 -0
  77. package/lib/src/src/model/Ad4mModel.d.ts +1438 -0
  78. package/lib/src/src/model/Ad4mModel.test.d.ts +1 -0
  79. package/lib/src/src/model/Subject.d.ts +25 -0
  80. package/lib/src/src/model/decorators.d.ts +545 -0
  81. package/lib/src/src/model/util.d.ts +12 -0
  82. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +10 -0
  83. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +25 -0
  84. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +19 -0
  85. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +1 -0
  86. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +24 -0
  87. package/lib/src/src/perspectives/LinkQuery.d.ts +11 -0
  88. package/lib/src/src/perspectives/Perspective.d.ts +38 -0
  89. package/lib/src/src/perspectives/Perspective.test.d.ts +1 -0
  90. package/lib/src/src/perspectives/PerspectiveClient.d.ts +97 -0
  91. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +9 -0
  92. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +18 -0
  93. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +865 -0
  94. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +57 -0
  95. package/lib/src/src/runtime/RuntimeClient.d.ts +56 -0
  96. package/lib/src/src/runtime/RuntimeResolver.d.ts +132 -0
  97. package/lib/src/src/shacl/SHACLFlow.d.ts +171 -0
  98. package/lib/src/src/shacl/SHACLFlow.test.d.ts +1 -0
  99. package/lib/src/src/shacl/SHACLShape.d.ts +117 -0
  100. package/lib/src/src/shacl/SHACLShape.test.d.ts +1 -0
  101. package/lib/src/src/typeDefs.d.ts +1 -0
  102. package/lib/src/src/unwrapApolloResult.d.ts +2 -0
  103. package/lib/src/src/utils.d.ts +25 -0
  104. package/lib/src/utils.d.ts +0 -8
  105. package/lib/src/utils.js +7 -21
  106. package/package.json +15 -14
  107. package/src/Ad4mClient.test.ts +1315 -1564
  108. package/src/Ad4mClient.ts +54 -55
  109. package/src/Literal.test.ts +26 -45
  110. package/src/Literal.ts +66 -82
  111. package/src/SmartLiteral.ts +58 -74
  112. package/src/agent/AgentClient.ts +99 -144
  113. package/src/ai/AIClient.ts +359 -409
  114. package/src/expression/ExpressionClient.ts +96 -142
  115. package/src/index.ts +1 -1
  116. package/src/language/LanguageClient.ts +113 -137
  117. package/src/model/Ad4mModel.test.ts +616 -1114
  118. package/src/model/Ad4mModel.ts +4361 -451
  119. package/src/model/Subject.ts +159 -0
  120. package/src/model/decorators.ts +1168 -667
  121. package/src/model/util.ts +54 -53
  122. package/src/neighbourhood/NeighbourhoodClient.ts +266 -392
  123. package/src/neighbourhood/NeighbourhoodProxy.test.ts +7 -3
  124. package/src/neighbourhood/NeighbourhoodProxy.ts +40 -58
  125. package/src/perspectives/PerspectiveClient.ts +540 -779
  126. package/src/perspectives/PerspectiveProxy.ts +2067 -2860
  127. package/src/runtime/RuntimeClient.ts +476 -775
  128. package/src/shacl/SHACLFlow.test.ts +129 -196
  129. package/src/shacl/SHACLShape.test.ts +190 -284
  130. package/src/shacl/SHACLShape.ts +200 -224
  131. package/src/utils.ts +17 -31
  132. package/tsconfig.json +10 -9
  133. package/src/model/IMPROVEMENTS.md +0 -482
  134. package/src/model/PREDICATE_COLLISION_FIX.md +0 -651
  135. package/src/model/README.md +0 -317
  136. package/src/model/SHACL_MUTATION_DECOUPLING.md +0 -356
  137. package/src/model/SUBSCRIPTION_STRATEGY.md +0 -317
  138. package/src/model/TC39_STAGE_3_DECORATORS.md +0 -609
  139. package/src/model/mutation.ts +0 -461
  140. package/src/model/parentUtils.ts +0 -91
  141. package/src/model/prolog/generatePrologFacts.ts +0 -176
  142. package/src/model/prolog/index.ts +0 -1
  143. package/src/model/query/ModelQueryBuilder.ts +0 -173
  144. package/src/model/query/fetchInstance.ts +0 -181
  145. package/src/model/query/hydration.ts +0 -273
  146. package/src/model/query/operations.ts +0 -510
  147. package/src/model/query/snapshot.ts +0 -126
  148. package/src/model/query/surrealCompiler.ts +0 -376
  149. package/src/model/schema/fromJSONSchema.ts +0 -411
  150. package/src/model/schema/metadata.ts +0 -148
  151. package/src/model/subscription.ts +0 -307
  152. package/src/model/transaction.ts +0 -60
  153. package/src/model/types.ts +0 -207
@@ -8,35 +8,7 @@ var __metadata = (this && this.__metadata) || function (k, v) {
8
8
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
9
  };
10
10
  import { Ad4mModel } from "./Ad4mModel";
11
- import { Model, Property, HasMany, Flag } from "./decorators";
12
- import { Literal } from "../Literal";
13
- import { resolveParentPredicate, normalizeParentQuery } from "./parentUtils";
14
- // ── Shared test fixtures ──────────────────────────────────────────────────────
15
- // Defined once at module level — used by queryToSurrealQL,
16
- // instancesFromSurrealResult, and hydration describe blocks alike.
17
- let Recipe = class Recipe extends Ad4mModel {
18
- constructor() {
19
- super(...arguments);
20
- this.name = "";
21
- this.rating = 0;
22
- this.ingredients = [];
23
- }
24
- };
25
- __decorate([
26
- Property({ through: "recipe://name", required: true }),
27
- __metadata("design:type", String)
28
- ], Recipe.prototype, "name", void 0);
29
- __decorate([
30
- Property({ through: "recipe://rating", required: true }),
31
- __metadata("design:type", Number)
32
- ], Recipe.prototype, "rating", void 0);
33
- __decorate([
34
- HasMany({ through: "recipe://ingredient" }),
35
- __metadata("design:type", Array)
36
- ], Recipe.prototype, "ingredients", void 0);
37
- Recipe = __decorate([
38
- Model({ name: "Recipe" })
39
- ], Recipe);
11
+ import { Model, Property, Optional, ReadOnly, HasMany, Flag } from "./decorators";
40
12
  describe("Ad4mModel.getModelMetadata()", () => {
41
13
  it("should extract basic model metadata with className", () => {
42
14
  let SimpleModel = class SimpleModel extends Ad4mModel {
@@ -60,19 +32,15 @@ describe("Ad4mModel.getModelMetadata()", () => {
60
32
  }
61
33
  };
62
34
  __decorate([
63
- Property({
64
- through: "test://name",
65
- resolveLanguage: "literal",
66
- required: true,
67
- }),
35
+ Property({ through: "test://name", resolveLanguage: "literal" }),
68
36
  __metadata("design:type", String)
69
37
  ], PropertyModel.prototype, "name", void 0);
70
38
  __decorate([
71
- Property({ through: "test://optional" }),
39
+ Optional({ through: "test://optional" }),
72
40
  __metadata("design:type", String)
73
41
  ], PropertyModel.prototype, "optional", void 0);
74
42
  __decorate([
75
- Property({ through: "test://readonly", readOnly: true }),
43
+ ReadOnly({ through: "test://readonly", prologGetter: "custom_getter" }),
76
44
  __metadata("design:type", String)
77
45
  ], PropertyModel.prototype, "readonly", void 0);
78
46
  __decorate([
@@ -87,22 +55,23 @@ describe("Ad4mModel.getModelMetadata()", () => {
87
55
  expect(Object.keys(metadata.properties)).toHaveLength(4);
88
56
  // Verify "name" property
89
57
  expect(metadata.properties.name.predicate).toBe("test://name");
90
- expect(metadata.properties.name.required).toBe(true);
91
- expect(metadata.properties.name.readOnly).toBeFalsy();
58
+ expect(metadata.properties.name.required).toBe(false);
59
+ expect(metadata.properties.name.readOnly).toBe(false);
92
60
  expect(metadata.properties.name.resolveLanguage).toBe("literal");
93
61
  // Verify "optional" property
94
62
  expect(metadata.properties.optional.predicate).toBe("test://optional");
95
- expect(metadata.properties.optional.readOnly).toBeFalsy();
63
+ expect(metadata.properties.optional.readOnly).toBe(false);
96
64
  // Verify "readonly" property
97
65
  expect(metadata.properties.readonly.predicate).toBe("test://readonly");
98
66
  expect(metadata.properties.readonly.readOnly).toBe(true);
67
+ expect(metadata.properties.readonly.prologGetter).toBe("custom_getter");
99
68
  // Verify "type" property (flag)
100
69
  expect(metadata.properties.type.predicate).toBe("test://type");
101
70
  expect(metadata.properties.type.flag).toBe(true);
102
71
  expect(metadata.properties.type.initial).toBe("test://flag");
103
72
  });
104
- it("should extract collection metadata", () => {
105
- let CollectionModel = class CollectionModel extends Ad4mModel {
73
+ it("should extract relation metadata with various options", () => {
74
+ let RelationModel = class RelationModel extends Ad4mModel {
106
75
  constructor() {
107
76
  super(...arguments);
108
77
  this.items = [];
@@ -112,20 +81,20 @@ describe("Ad4mModel.getModelMetadata()", () => {
112
81
  __decorate([
113
82
  HasMany({ through: "test://items" }),
114
83
  __metadata("design:type", Array)
115
- ], CollectionModel.prototype, "items", void 0);
84
+ ], RelationModel.prototype, "items", void 0);
116
85
  __decorate([
117
86
  HasMany({ through: "test://local", local: true }),
118
87
  __metadata("design:type", Array)
119
- ], CollectionModel.prototype, "local", void 0);
120
- CollectionModel = __decorate([
121
- Model({ name: "CollectionModel" })
122
- ], CollectionModel);
123
- const metadata = CollectionModel.getModelMetadata();
124
- // Should have 2 collections
88
+ ], RelationModel.prototype, "local", void 0);
89
+ RelationModel = __decorate([
90
+ Model({ name: "RelationModel" })
91
+ ], RelationModel);
92
+ const metadata = RelationModel.getModelMetadata();
93
+ // Should have 2 relations
125
94
  expect(Object.keys(metadata.relations)).toHaveLength(2);
126
- // Verify "items" collection
95
+ // Verify "items" relation
127
96
  expect(metadata.relations.items.predicate).toBe("test://items");
128
- // Verify "local" collection
97
+ // Verify "local" relation
129
98
  expect(metadata.relations.local.predicate).toBe("test://local");
130
99
  expect(metadata.relations.local.local).toBe(true);
131
100
  });
@@ -137,9 +106,9 @@ describe("Ad4mModel.getModelMetadata()", () => {
137
106
  }
138
107
  };
139
108
  __decorate([
140
- Property({
109
+ Optional({
141
110
  through: "test://data",
142
- transform: (value) => value.toUpperCase(),
111
+ transform: (value) => value.toUpperCase()
143
112
  }),
144
113
  __metadata("design:type", String)
145
114
  ], TransformModel.prototype, "data", void 0);
@@ -153,28 +122,31 @@ describe("Ad4mModel.getModelMetadata()", () => {
153
122
  const transformed = metadata.properties.data.transform("test");
154
123
  expect(transformed).toBe("TEST");
155
124
  });
156
- it("should extract custom SurrealQL getter from property metadata", () => {
125
+ it("should extract custom getter and setter from property metadata", () => {
157
126
  let CustomModel = class CustomModel extends Ad4mModel {
158
127
  constructor() {
159
128
  super(...arguments);
160
- this.computed = "";
129
+ this.computed = 0;
161
130
  }
162
131
  };
163
132
  __decorate([
164
- Property({
133
+ Optional({
165
134
  through: "test://computed",
166
- getter: "(<-link[WHERE predicate = 'test://value'].in.uri)[0]",
135
+ prologGetter: "triple(Base, 'test://value', V), Value is V * 2",
136
+ prologSetter: "Value is V / 2, Actions = [{action: 'setSingleTarget', source: 'this', predicate: 'test://value', target: Value}]"
167
137
  }),
168
- __metadata("design:type", String)
138
+ __metadata("design:type", Number)
169
139
  ], CustomModel.prototype, "computed", void 0);
170
140
  CustomModel = __decorate([
171
141
  Model({ name: "CustomModel" })
172
142
  ], CustomModel);
173
143
  const metadata = CustomModel.getModelMetadata();
174
- // Assert getter contains the custom SurrealQL code
175
- expect(metadata.properties.computed.getter).toContain("test://value");
144
+ // Assert prologGetter and prologSetter contain the custom code
145
+ expect(metadata.properties.computed.prologGetter).toContain("triple(Base, 'test://value', V), Value is V * 2");
146
+ expect(metadata.properties.computed.prologSetter).toContain("Value is V / 2");
147
+ expect(metadata.properties.computed.prologSetter).toContain("setSingleTarget");
176
148
  });
177
- it("should register relatedModel factory for typed @HasMany", () => {
149
+ it("should handle relation with typed target relation", () => {
178
150
  let Comment = class Comment extends Ad4mModel {
179
151
  };
180
152
  Comment = __decorate([
@@ -187,24 +159,27 @@ describe("Ad4mModel.getModelMetadata()", () => {
187
159
  }
188
160
  };
189
161
  __decorate([
190
- HasMany(() => Comment, { through: "post://comment" }),
162
+ HasMany({
163
+ through: "post://comment",
164
+ target: () => Comment
165
+ }),
191
166
  __metadata("design:type", Array)
192
167
  ], Post.prototype, "comments", void 0);
193
168
  Post = __decorate([
194
169
  Model({ name: "Post" })
195
170
  ], Post);
196
171
  const metadata = Post.getModelMetadata();
197
- // relatedModel factory should be registered and return Comment
198
- expect(metadata.relations.comments.relatedModel).toBeDefined();
199
- expect(metadata.relations.comments.relatedModel()).toBe(Comment);
172
+ // Assert relation exists with correct predicate
173
+ expect(metadata.relations.comments).toBeDefined();
174
+ expect(metadata.relations.comments.predicate).toBe("post://comment");
200
175
  });
201
- it("should throw error for class without @ModelOptions decorator", () => {
176
+ it("should throw error for class without @Model decorator", () => {
202
177
  class NoDecoratorModel extends Ad4mModel {
203
178
  }
204
179
  // Assert that calling getModelMetadata throws an error
205
180
  expect(() => NoDecoratorModel.getModelMetadata()).toThrow("Model class must be decorated with @Model");
206
181
  });
207
- it("should handle complex model with mixed property and collection types", () => {
182
+ it("should handle complex model with mixed property and relation types", () => {
208
183
  let Recipe = class Recipe extends Ad4mModel {
209
184
  constructor() {
210
185
  super(...arguments);
@@ -216,22 +191,15 @@ describe("Ad4mModel.getModelMetadata()", () => {
216
191
  }
217
192
  };
218
193
  __decorate([
219
- Property({
220
- through: "recipe://name",
221
- required: true,
222
- }),
194
+ Property({ through: "recipe://name", resolveLanguage: "literal" }),
223
195
  __metadata("design:type", String)
224
196
  ], Recipe.prototype, "name", void 0);
225
197
  __decorate([
226
- Property({ through: "recipe://description" }),
198
+ Optional({ through: "recipe://description" }),
227
199
  __metadata("design:type", String)
228
200
  ], Recipe.prototype, "description", void 0);
229
201
  __decorate([
230
- Property({
231
- through: "recipe://rating",
232
- getter: "avg_rating_surreal(Base, Value)",
233
- readOnly: true,
234
- }),
202
+ ReadOnly({ through: "recipe://rating", prologGetter: "avg_rating(Base, Value)" }),
235
203
  __metadata("design:type", Number)
236
204
  ], Recipe.prototype, "rating", void 0);
237
205
  __decorate([
@@ -253,16 +221,16 @@ describe("Ad4mModel.getModelMetadata()", () => {
253
221
  expect(metadata.properties.name).toBeDefined();
254
222
  expect(metadata.properties.description).toBeDefined();
255
223
  expect(metadata.properties.rating).toBeDefined();
256
- // Assert collections has 2 entries
224
+ // Assert relations has 2 entries
257
225
  expect(Object.keys(metadata.relations)).toHaveLength(2);
258
226
  expect(metadata.relations.ingredients).toBeDefined();
259
227
  expect(metadata.relations.steps).toBeDefined();
260
228
  // Verify all metadata fields are correctly extracted
261
229
  expect(metadata.properties.name.predicate).toBe("recipe://name");
262
- expect(metadata.properties.name.resolveLanguage).toBeUndefined(); // "literal" is now the implicit default — no need to store it
230
+ expect(metadata.properties.name.resolveLanguage).toBe("literal");
263
231
  expect(metadata.properties.description.predicate).toBe("recipe://description");
264
232
  expect(metadata.properties.rating.predicate).toBe("recipe://rating");
265
- expect(metadata.properties.rating.getter).toBe("avg_rating_surreal(Base, Value)");
233
+ expect(metadata.properties.rating.prologGetter).toBe("avg_rating(Base, Value)");
266
234
  expect(metadata.relations.ingredients.predicate).toBe("recipe://ingredient");
267
235
  expect(metadata.relations.steps.predicate).toBe("recipe://step");
268
236
  expect(metadata.relations.steps.local).toBe(true);
@@ -276,13 +244,14 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
276
244
  properties: {
277
245
  name: { type: "string" },
278
246
  price: { type: "number" },
279
- description: { type: "string" },
247
+ description: { type: "string" }
280
248
  },
281
- required: ["name", "price"],
249
+ required: ["name", "price"]
282
250
  };
283
251
  const ProductClass = Ad4mModel.fromJSONSchema(schema, {
284
252
  name: "Product",
285
253
  namespace: "product://",
254
+ resolveLanguage: "literal"
286
255
  });
287
256
  const metadata = ProductClass.getModelMetadata();
288
257
  // Verify className
@@ -292,17 +261,17 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
292
261
  expect(metadata.properties.name).toBeDefined();
293
262
  expect(metadata.properties.name.predicate).toBe("product://name");
294
263
  expect(metadata.properties.name.required).toBe(true);
295
- expect(metadata.properties.name.readOnly).toBeFalsy();
296
- expect(metadata.properties.name.resolveLanguage).toBeUndefined(); // implicit literal default
264
+ expect(metadata.properties.name.readOnly).toBe(false);
265
+ expect(metadata.properties.name.resolveLanguage).toBe("literal");
297
266
  expect(metadata.properties.price).toBeDefined();
298
267
  expect(metadata.properties.price.predicate).toBe("product://price");
299
268
  expect(metadata.properties.price.required).toBe(true);
300
- expect(metadata.properties.price.resolveLanguage).toBeUndefined(); // implicit literal default
269
+ expect(metadata.properties.price.resolveLanguage).toBe("literal");
301
270
  expect(metadata.properties.description).toBeDefined();
302
271
  expect(metadata.properties.description.predicate).toBe("product://description");
303
272
  expect(metadata.properties.description.required).toBe(false);
304
273
  });
305
- it("should extract collections from a model created via fromJSONSchema with arrays", () => {
274
+ it("should extract relations from a model created via fromJSONSchema with arrays", () => {
306
275
  const schema = {
307
276
  title: "Post",
308
277
  type: "object",
@@ -310,18 +279,18 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
310
279
  title: { type: "string" },
311
280
  tags: {
312
281
  type: "array",
313
- items: { type: "string" },
282
+ items: { type: "string" }
314
283
  },
315
284
  comments: {
316
285
  type: "array",
317
- items: { type: "string" },
318
- },
286
+ items: { type: "string" }
287
+ }
319
288
  },
320
- required: ["title"],
289
+ required: ["title"]
321
290
  };
322
291
  const PostClass = Ad4mModel.fromJSONSchema(schema, {
323
292
  name: "Post",
324
- namespace: "post://",
293
+ namespace: "post://"
325
294
  });
326
295
  const metadata = PostClass.getModelMetadata();
327
296
  // Verify className
@@ -341,7 +310,7 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
341
310
  const schema = {
342
311
  title: "Contact",
343
312
  "x-ad4m": {
344
- namespace: "contact://",
313
+ namespace: "contact://"
345
314
  },
346
315
  type: "object",
347
316
  properties: {
@@ -349,26 +318,28 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
349
318
  type: "string",
350
319
  "x-ad4m": {
351
320
  through: "foaf://name",
352
- },
321
+ resolveLanguage: "literal",
322
+ writable: true
323
+ }
353
324
  },
354
325
  email: {
355
326
  type: "string",
356
327
  "x-ad4m": {
357
328
  through: "foaf://mbox",
358
- local: true,
359
- },
360
- },
329
+ local: true
330
+ }
331
+ }
361
332
  },
362
- required: ["name"],
333
+ required: ["name"]
363
334
  };
364
335
  const ContactClass = Ad4mModel.fromJSONSchema(schema, {
365
- name: "Contact",
336
+ name: "Contact"
366
337
  });
367
338
  const metadata = ContactClass.getModelMetadata();
368
339
  // Verify x-ad4m metadata is respected
369
340
  expect(metadata.properties.name.predicate).toBe("foaf://name");
370
- expect(metadata.properties.name.resolveLanguage).toBeUndefined(); // implicit literal default
371
- expect(metadata.properties.name.readOnly).toBeFalsy();
341
+ expect(metadata.properties.name.resolveLanguage).toBe("literal");
342
+ expect(metadata.properties.name.readOnly).toBe(false);
372
343
  expect(metadata.properties.name.required).toBe(true);
373
344
  expect(metadata.properties.email.predicate).toBe("foaf://mbox");
374
345
  expect(metadata.properties.email.local).toBe(true);
@@ -379,17 +350,17 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
379
350
  type: "object",
380
351
  properties: {
381
352
  username: { type: "string" },
382
- fullName: { type: "string" },
353
+ fullName: { type: "string" }
383
354
  },
384
- required: ["username"],
355
+ required: ["username"]
385
356
  };
386
357
  const UserClass = Ad4mModel.fromJSONSchema(schema, {
387
358
  name: "User",
388
359
  namespace: "user://",
389
360
  propertyMapping: {
390
361
  username: "custom://identifier",
391
- fullName: "custom://name",
392
- },
362
+ fullName: "custom://name"
363
+ }
393
364
  });
394
365
  const metadata = UserClass.getModelMetadata();
395
366
  // Verify property mappings are applied
@@ -406,21 +377,22 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
406
377
  published: { type: "boolean" },
407
378
  authors: {
408
379
  type: "array",
409
- items: { type: "string" },
380
+ items: { type: "string" }
410
381
  },
411
382
  tags: {
412
383
  type: "array",
413
384
  items: { type: "string" },
414
385
  "x-ad4m": {
415
- local: true,
416
- },
417
- },
386
+ local: true
387
+ }
388
+ }
418
389
  },
419
- required: ["title", "published"],
390
+ required: ["title", "published"]
420
391
  };
421
392
  const ArticleClass = Ad4mModel.fromJSONSchema(schema, {
422
393
  name: "Article",
423
394
  namespace: "article://",
395
+ resolveLanguage: "literal"
424
396
  });
425
397
  const metadata = ArticleClass.getModelMetadata();
426
398
  // Verify className
@@ -429,10 +401,10 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
429
401
  expect(metadata.properties.title).toBeDefined();
430
402
  expect(metadata.properties.title.predicate).toBe("article://title");
431
403
  expect(metadata.properties.title.required).toBe(true);
432
- expect(metadata.properties.title.resolveLanguage).toBeUndefined(); // implicit literal default
404
+ expect(metadata.properties.title.resolveLanguage).toBe("literal");
433
405
  expect(metadata.properties.views).toBeDefined();
434
406
  expect(metadata.properties.views.predicate).toBe("article://views");
435
- expect(metadata.properties.views.resolveLanguage).toBeUndefined(); // implicit literal default
407
+ expect(metadata.properties.views.resolveLanguage).toBe("literal");
436
408
  expect(metadata.properties.published).toBeDefined();
437
409
  expect(metadata.properties.published.predicate).toBe("article://published");
438
410
  expect(metadata.properties.published.required).toBe(true);
@@ -443,28 +415,26 @@ describe("Ad4mModel.fromJSONSchema() with getModelMetadata()", () => {
443
415
  expect(metadata.relations.tags.predicate).toBe("article://tags");
444
416
  expect(metadata.relations.tags.local).toBe(true);
445
417
  });
446
- it("should handle models with only an auto-generated type flag", () => {
447
- const warnSpy = jest.spyOn(console, "warn").mockImplementation(() => { });
418
+ it("should handle models with no properties (open-world, no auto-flag)", () => {
448
419
  const schema = {
449
420
  title: "EmptyModel",
450
421
  type: "object",
451
- properties: {},
422
+ properties: {}
452
423
  };
453
424
  const EmptyModelClass = Ad4mModel.fromJSONSchema(schema, {
454
425
  name: "EmptyModel",
455
- namespace: "empty://",
426
+ namespace: "empty://"
456
427
  });
457
428
  const metadata = EmptyModelClass.getModelMetadata();
458
429
  // Should have className
459
430
  expect(metadata.className).toBe("EmptyModel");
460
- // Should have the auto-generated __ad4m_type property
461
- expect(metadata.properties.__ad4m_type).toBeDefined();
462
- expect(metadata.properties.__ad4m_type.predicate).toBe("ad4m://type");
463
- expect(metadata.properties.__ad4m_type.initial).toBe("empty://instance");
464
- expect(metadata.properties.__ad4m_type.flag).toBe(true);
465
- // The warning is the expected fallback signal for empty schemas
466
- expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining("No properties with initial values found"));
467
- warnSpy.mockRestore();
431
+ // Should NOT have an auto-generated __ad4m_type property —
432
+ // models with all-optional properties use open-world structural matching.
433
+ expect(metadata.properties.__ad4m_type).toBeUndefined();
434
+ // SHACL shape should still be valid with empty constructor/destructor
435
+ const { shape } = EmptyModelClass.generateSHACL();
436
+ expect(shape.constructor_actions).toEqual([]);
437
+ expect(shape.destructor_actions).toEqual([]);
468
438
  });
469
439
  });
470
440
  describe("Ad4mModel.queryToSurrealQL()", () => {
@@ -472,40 +442,58 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
472
442
  const mockPerspective = {};
473
443
  // Helper function to normalize whitespace in queries for easier comparison
474
444
  function normalizeQuery(query) {
475
- return query.replace(/\s+/g, " ").trim();
445
+ return query.replace(/\s+/g, ' ').trim();
476
446
  }
447
+ // Test Recipe model — explicit required: true to test required-property query filters
448
+ let Recipe = class Recipe extends Ad4mModel {
449
+ constructor() {
450
+ super(...arguments);
451
+ this.name = "";
452
+ this.rating = 0;
453
+ this.ingredients = [];
454
+ }
455
+ };
456
+ __decorate([
457
+ Property({ through: "recipe://name", required: true }),
458
+ __metadata("design:type", String)
459
+ ], Recipe.prototype, "name", void 0);
460
+ __decorate([
461
+ Property({ through: "recipe://rating", required: true }),
462
+ __metadata("design:type", Number)
463
+ ], Recipe.prototype, "rating", void 0);
464
+ __decorate([
465
+ HasMany({ through: "recipe://ingredient" }),
466
+ __metadata("design:type", Array)
467
+ ], Recipe.prototype, "ingredients", void 0);
468
+ Recipe = __decorate([
469
+ Model({ name: "Recipe" })
470
+ ], Recipe);
477
471
  it("should generate basic query with no filters", async () => {
478
472
  const query = await Recipe.queryToSurrealQL(mockPerspective, {});
479
473
  expect(query).toContain("id AS source");
480
474
  expect(query).toContain("uri AS source_uri");
481
475
  expect(query).toContain("FROM node");
482
- expect(query).toContain("(SELECT predicate, out.uri AS target, author, timestamp FROM link WHERE in = $parent.id ORDER BY timestamp ASC) AS links");
476
+ expect(query).toContain("->link AS links");
483
477
  expect(query).toContain("WHERE");
484
478
  // Should have graph traversal filters for required properties
485
479
  expect(query).toContain("count(->link[WHERE");
486
480
  });
487
481
  it("should generate query with simple property filter", async () => {
488
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
489
- where: { name: "Pasta" },
490
- });
482
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta" } });
491
483
  // Should have graph traversal filters for required properties and user filter
492
484
  expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
493
485
  expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
494
486
  expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
495
487
  });
496
488
  it("should generate query with multiple property filters", async () => {
497
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
498
- where: { name: "Pasta", rating: 5 },
499
- });
489
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "Pasta", rating: 5 } });
500
490
  expect(query).toContain("WHERE");
501
491
  expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Pasta']) > 0");
502
492
  expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) = 5]) > 0");
503
493
  expect(query).toContain("AND");
504
494
  });
505
495
  it("should handle gt operator (filtered in JavaScript, not SQL)", async () => {
506
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
507
- where: { rating: { gt: 4 } },
508
- });
496
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gt: 4 } } });
509
497
  // Comparison operators for regular properties are now filtered in JavaScript post-query
510
498
  // The SQL just filters on the predicate existing
511
499
  expect(query).toContain("FROM node");
@@ -513,75 +501,72 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
513
501
  expect(query).not.toContain("target > 4");
514
502
  });
515
503
  it("should handle lt operator (filtered in JavaScript, not SQL)", async () => {
516
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
517
- where: { rating: { lt: 3 } },
518
- });
504
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { lt: 3 } } });
519
505
  // Comparison operators are filtered in JavaScript post-query
520
506
  expect(query).toContain("FROM node");
521
507
  expect(query).not.toContain("target < 3");
522
508
  });
523
509
  it("should handle gte and lte operators (filtered in JavaScript, not SQL)", async () => {
524
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
525
- where: { rating: { gte: 3, lte: 5 } },
526
- });
510
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { gte: 3, lte: 5 } } });
527
511
  // Comparison operators are filtered in JavaScript post-query
528
512
  expect(query).toContain("FROM node");
529
513
  expect(query).not.toContain("target >= 3");
530
514
  expect(query).not.toContain("target <= 5");
531
515
  });
532
516
  it("should handle not operator with single value", async () => {
533
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
534
- where: { name: { not: "Salad" } },
535
- });
517
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: "Salad" } } });
536
518
  // Not operator uses graph traversal with count = 0
537
519
  expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) = 'Salad']) = 0");
538
520
  });
539
521
  it("should handle not operator with array (NOT IN)", async () => {
540
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
541
- where: { name: { not: ["Salad", "Soup"] } },
542
- });
522
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { not: ["Salad", "Soup"] } } });
543
523
  // Not operator with array uses graph traversal with count = 0
544
524
  expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Salad', 'Soup']]) = 0");
545
525
  });
546
526
  it("should handle between operator (filtered in JavaScript, not SQL)", async () => {
547
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
548
- where: { rating: { between: [3, 5] } },
549
- });
527
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: { between: [3, 5] } } });
550
528
  // Between operator for regular properties is now filtered in JavaScript post-query
551
529
  expect(query).toContain("FROM node");
552
530
  expect(query).not.toContain("target >= 3");
553
531
  expect(query).not.toContain("target <= 5");
554
532
  });
555
533
  it("should handle contains operator on string property (filtered in JavaScript, not SQL)", async () => {
556
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
557
- where: { name: { contains: "Past" } },
558
- });
534
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Past" } } });
559
535
  // Contains operator for regular properties is now filtered in JavaScript post-query
560
536
  expect(query).toContain("FROM node");
561
537
  expect(query).not.toContain("target CONTAINS 'Past'");
562
538
  });
563
539
  it("should handle contains operator on regular property with substring (filtered in JavaScript, not SQL)", async () => {
564
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
565
- where: { name: { contains: "Salad" } },
566
- });
540
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: { contains: "Salad" } } });
567
541
  // Contains operator is filtered in JavaScript post-query
568
542
  expect(query).toContain("FROM node");
569
543
  expect(query).not.toContain("target CONTAINS 'Salad'");
570
544
  });
545
+ it.skip("should handle contains operator on special field (author)", async () => {
546
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: { contains: "alice" } } });
547
+ expect(query).toContain("WHERE author CONTAINS 'alice'");
548
+ // Should not use a subquery pattern
549
+ expect(query).not.toContain("SELECT source FROM node");
550
+ });
551
+ it.skip("should handle contains operator on special field (id)", async () => {
552
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { contains: "test" } } });
553
+ expect(query).toContain("WHERE source CONTAINS 'test'");
554
+ });
571
555
  it("should handle array values (IN clause)", async () => {
572
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
573
- where: { name: ["Pasta", "Pizza"] },
574
- });
556
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: ["Pasta", "Pizza"] } });
575
557
  expect(query).toContain("count(->link[WHERE predicate = 'recipe://name' AND fn::parse_literal(out.uri) IN ['Pasta', 'Pizza']]) > 0");
576
558
  });
559
+ it.skip("should handle special fields (author, timestamp) without subqueries", async () => {
560
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { author: "did:key:alice" } });
561
+ expect(query).toContain("WHERE author = 'did:key:alice'");
562
+ // Ensure it's NOT using a subquery pattern for author in WHERE clause
563
+ expect(normalizeQuery(query)).not.toMatch(/WHERE.*source IN.*SELECT source FROM node.*author/);
564
+ });
577
565
  it("should not generate ORDER BY clause in SQL (handled in JavaScript)", async () => {
578
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
579
- order: { timestamp: "DESC" },
580
- });
566
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { timestamp: "DESC" } });
581
567
  // ORDER BY is now handled in JavaScript post-query
582
- // Note: the links correlated subquery uses ORDER BY timestamp ASC internally for link ordering
583
568
  expect(query).toContain("FROM node");
584
- expect(query).not.toContain("ORDER BY timestamp DESC");
569
+ expect(query).not.toContain("ORDER BY");
585
570
  });
586
571
  it("should not generate LIMIT clause in SQL (handled in JavaScript)", async () => {
587
572
  const query = await Recipe.queryToSurrealQL(mockPerspective, { limit: 10 });
@@ -590,9 +575,7 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
590
575
  expect(query).not.toContain("LIMIT");
591
576
  });
592
577
  it("should not generate START clause in SQL (handled in JavaScript)", async () => {
593
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
594
- offset: 20,
595
- });
578
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { offset: 20 });
596
579
  // START/offset is now handled in JavaScript post-query
597
580
  expect(query).toContain("FROM node");
598
581
  expect(query).not.toContain("START");
@@ -602,7 +585,7 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
602
585
  where: { name: "Pasta", rating: { gt: 4 } },
603
586
  order: { timestamp: "DESC" },
604
587
  limit: 10,
605
- offset: 20,
588
+ offset: 20
606
589
  });
607
590
  // WHERE clause uses graph traversal filters
608
591
  expect(query).toContain("WHERE");
@@ -611,20 +594,17 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
611
594
  expect(query).not.toContain("out.uri > 4");
612
595
  expect(query).not.toContain("target > 4");
613
596
  // ORDER BY, LIMIT, START are now handled in JavaScript post-query
614
- // Note: the links subquery uses ORDER BY timestamp ASC internally
615
- expect(query).not.toContain("ORDER BY timestamp DESC");
597
+ expect(query).not.toContain("ORDER BY");
616
598
  expect(query).not.toContain("LIMIT");
617
599
  expect(query).not.toContain("START");
618
600
  });
619
- it("should only select requested fields", async () => {
620
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
621
- properties: ["name"],
622
- });
601
+ it("should only select requested properties", async () => {
602
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name"] });
623
603
  // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
624
- expect(query).toContain("(SELECT predicate, out.uri AS target, author, timestamp FROM link WHERE in = $parent.id ORDER BY timestamp ASC) AS links");
604
+ expect(query).toContain("->link AS links");
625
605
  });
626
- it("should only select requested relations", async () => {
627
- let MultiCollectionModel = class MultiCollectionModel extends Ad4mModel {
606
+ it("should select all link data for relations", async () => {
607
+ let MultiRelationModel = class MultiRelationModel extends Ad4mModel {
628
608
  constructor() {
629
609
  super(...arguments);
630
610
  this.coll1 = [];
@@ -634,42 +614,38 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
634
614
  __decorate([
635
615
  HasMany({ through: "test://coll1" }),
636
616
  __metadata("design:type", Array)
637
- ], MultiCollectionModel.prototype, "coll1", void 0);
617
+ ], MultiRelationModel.prototype, "coll1", void 0);
638
618
  __decorate([
639
619
  HasMany({ through: "test://coll2" }),
640
620
  __metadata("design:type", Array)
641
- ], MultiCollectionModel.prototype, "coll2", void 0);
642
- MultiCollectionModel = __decorate([
643
- Model({ name: "MultiCollectionModel" })
644
- ], MultiCollectionModel);
645
- const query = await MultiCollectionModel.queryToSurrealQL(mockPerspective, {});
646
- // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
647
- expect(query).toContain("(SELECT predicate, out.uri AS target, author, timestamp FROM link WHERE in = $parent.id ORDER BY timestamp ASC) AS links");
621
+ ], MultiRelationModel.prototype, "coll2", void 0);
622
+ MultiRelationModel = __decorate([
623
+ Model({ name: "MultiRelationModel" })
624
+ ], MultiRelationModel);
625
+ const query = await MultiRelationModel.queryToSurrealQL(mockPerspective, {});
626
+ // With array::group(), all link data is selected
627
+ expect(query).toContain("->link AS links");
648
628
  });
649
629
  it("should escape single quotes in string values", async () => {
650
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
651
- where: { name: "O'Brien's Recipe" },
652
- });
630
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { name: "O'Brien's Recipe" } });
653
631
  // Single quotes are escaped with backslash in SurrealDB
654
632
  expect(query).toContain("O\\'Brien\\'s Recipe");
655
633
  });
656
634
  it("should handle numeric values without quotes", async () => {
657
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
658
- where: { rating: 5 },
659
- });
635
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: 5 } });
660
636
  // Numeric values should not have quotes around them
661
637
  expect(query).toContain("fn::parse_literal(out.uri) = 5");
662
- expect(query).not.toContain("out.uri = '5'");
638
+ expect(query).not.toContain("fn::parse_literal(out.uri) = '5'");
663
639
  });
664
640
  it("should handle complex nested query (comparisons, ORDER BY, LIMIT handled in JS)", async () => {
665
641
  const query = await Recipe.queryToSurrealQL(mockPerspective, {
666
642
  where: {
667
643
  name: "Pasta",
668
644
  rating: { gte: 4, lte: 5 },
669
- author: "did:key:alice",
645
+ author: "did:key:alice"
670
646
  },
671
647
  order: { rating: "DESC" },
672
- limit: 5,
648
+ limit: 5
673
649
  });
674
650
  const normalized = normalizeQuery(query);
675
651
  // Verify graph traversal filters are present
@@ -682,8 +658,7 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
682
658
  // author and timestamp filtering is done in JavaScript post-query
683
659
  expect(normalized).not.toContain("author = 'did:key:alice'");
684
660
  // ORDER BY and LIMIT are handled in JavaScript post-query
685
- // Note: the links correlated subquery uses ORDER BY timestamp ASC internally
686
- expect(normalized).not.toContain("ORDER BY rating");
661
+ expect(normalized).not.toContain("ORDER BY");
687
662
  expect(normalized).not.toContain("LIMIT");
688
663
  // Verify query structure (FROM node, no GROUP BY)
689
664
  expect(normalized).toContain("FROM node");
@@ -698,58 +673,42 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
698
673
  expect(query).toContain("WHERE");
699
674
  expect(query).toContain("count(->link[WHERE predicate = 'recipe://name']) > 0");
700
675
  expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating']) > 0");
701
- // No user-requested ORDER BY or START should appear at the top level
676
+ expect(query).not.toContain("ORDER BY");
702
677
  expect(query).not.toContain("START");
703
678
  });
704
- it("should handle base special field", async () => {
705
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
706
- where: { base: "literal://test" },
707
- });
679
+ it("should handle id special field", async () => {
680
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: "literal://test" } });
708
681
  expect(query).toContain("uri = 'literal://test'");
709
682
  });
710
- it("should handle base special field with array (IN clause)", async () => {
711
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
712
- where: { base: ["literal://test1", "literal://test2"] },
713
- });
683
+ it("should handle id special field with array (IN clause)", async () => {
684
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: ["literal://test1", "literal://test2"] } });
714
685
  expect(query).toContain("uri IN ['literal://test1', 'literal://test2']");
715
686
  });
716
- it("should handle base special field with not operator", async () => {
717
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
718
- where: { base: { not: "literal://test" } },
719
- });
687
+ it("should handle id special field with not operator", async () => {
688
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { not: "literal://test" } } });
720
689
  expect(query).toContain("uri != 'literal://test'");
721
690
  });
722
- it("should handle base special field with not operator and array (NOT IN)", async () => {
723
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
724
- where: { base: { not: ["literal://test1", "literal://test2"] } },
725
- });
691
+ it("should handle id special field with not operator and array (NOT IN)", async () => {
692
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { not: ["literal://test1", "literal://test2"] } } });
726
693
  expect(query).toContain("uri NOT IN ['literal://test1', 'literal://test2']");
727
694
  });
728
- it("should handle base special field with between operator", async () => {
729
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
730
- where: { base: { between: ["literal://a", "literal://z"] } },
731
- });
695
+ it("should handle id special field with between operator", async () => {
696
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { between: ["literal://a", "literal://z"] } } });
732
697
  const normalized = normalizeQuery(query);
733
698
  expect(normalized).toContain("uri >= 'literal://a' AND uri <= 'literal://z'");
734
699
  });
735
- it("should handle base special field with gt operator", async () => {
736
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
737
- where: { base: { gt: "literal://m" } },
738
- });
700
+ it("should handle id special field with gt operator", async () => {
701
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { gt: "literal://m" } } });
739
702
  expect(query).toContain("uri > 'literal://m'");
740
703
  });
741
- it("should handle base special field with gte and lte operators", async () => {
742
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
743
- where: { base: { gte: "literal://a", lte: "literal://z" } },
744
- });
704
+ it("should handle id special field with gte and lte operators", async () => {
705
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { id: { gte: "literal://a", lte: "literal://z" } } });
745
706
  const normalized = normalizeQuery(query);
746
707
  expect(normalized).toContain("uri >= 'literal://a'");
747
708
  expect(normalized).toContain("uri <= 'literal://z'");
748
709
  });
749
710
  it("should handle timestamp special field with gt operator (filtered in JavaScript)", async () => {
750
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
751
- where: { timestamp: { gt: 1234567890 } },
752
- });
711
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { timestamp: { gt: 1234567890 } } });
753
712
  // timestamp filtering is done in JavaScript post-query
754
713
  expect(query).toContain("FROM node");
755
714
  expect(query).not.toContain("timestamp > 1234567890");
@@ -758,8 +717,8 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
758
717
  const query = await Recipe.queryToSurrealQL(mockPerspective, {
759
718
  where: {
760
719
  author: "did:key:alice",
761
- timestamp: { gt: 1000 },
762
- },
720
+ timestamp: { gt: 1000 }
721
+ }
763
722
  });
764
723
  // author and timestamp filtering is done in JavaScript post-query
765
724
  expect(query).toContain("FROM node");
@@ -771,8 +730,8 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
771
730
  where: {
772
731
  name: "Pasta",
773
732
  author: "did:key:alice",
774
- rating: { gt: 4 },
775
- },
733
+ rating: { gt: 4 }
734
+ }
776
735
  });
777
736
  const normalized = normalizeQuery(query);
778
737
  // Regular properties use graph traversal filters
@@ -791,97 +750,76 @@ describe("Ad4mModel.queryToSurrealQL()", () => {
791
750
  }
792
751
  };
793
752
  __decorate([
794
- Property({
795
- through: "task://completed",
796
- required: true,
797
- }),
753
+ Property({ through: "task://completed" }),
798
754
  __metadata("design:type", Boolean)
799
755
  ], Task.prototype, "completed", void 0);
800
756
  Task = __decorate([
801
757
  Model({ name: "Task" })
802
758
  ], Task);
803
- const query = await Task.queryToSurrealQL(mockPerspective, {
804
- where: { completed: true },
805
- });
759
+ const query = await Task.queryToSurrealQL(mockPerspective, { where: { completed: true } });
806
760
  expect(query).toContain("fn::parse_literal(out.uri) = true");
807
761
  });
808
762
  it("should handle array of numbers", async () => {
809
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
810
- where: { rating: [4, 5] },
811
- });
763
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { rating: [4, 5] } });
812
764
  expect(query).toContain("count(->link[WHERE predicate = 'recipe://rating' AND fn::parse_literal(out.uri) IN [4, 5]]) > 0");
813
765
  });
814
766
  it("should skip unknown properties in where clause", async () => {
815
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
816
- where: { unknownProp: "value" },
817
- });
767
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { where: { unknownProp: "value" } });
818
768
  // Should not throw error, just skip the unknown property
819
769
  expect(query).toContain("source");
820
770
  // Should not contain any condition for unknownProp
821
771
  expect(query).not.toContain("unknownProp");
822
772
  });
773
+ it.skip("should skip unknown properties in select clause", async () => {
774
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "unknownProp"] });
775
+ // Should include name using aggregation
776
+ expect(query).toContain("array::first(target[WHERE predicate = 'recipe://name']) AS name");
777
+ // Should not error on unknownProp, just skip it
778
+ expect(query).not.toContain("unknownProp");
779
+ });
823
780
  it("should handle order by regular property (handled in JavaScript)", async () => {
824
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
825
- order: { name: "ASC" },
826
- });
781
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { order: { name: "ASC" } });
827
782
  // ORDER BY is now handled in JavaScript post-query
828
- // Note: the links correlated subquery uses ORDER BY timestamp ASC internally
829
783
  expect(query).toContain("FROM node");
830
- expect(query).not.toContain("ORDER BY name");
784
+ expect(query).not.toContain("ORDER BY");
831
785
  });
832
- it("should generate query with only fields, no relations", async () => {
833
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
834
- properties: ["name", "rating"],
835
- });
786
+ it("should generate query with only properties specified", async () => {
787
+ const query = await Recipe.queryToSurrealQL(mockPerspective, { properties: ["name", "rating"] });
836
788
  // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
837
- expect(query).toContain("(SELECT predicate, out.uri AS target, author, timestamp FROM link WHERE in = $parent.id ORDER BY timestamp ASC) AS links");
838
- });
839
- it("should generate query with only relations, no fields", async () => {
840
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
841
- properties: [],
842
- });
843
- // With array::group(), all link data is selected, filtering happens in instancesFromSurrealResult
844
- expect(query).toContain("(SELECT predicate, out.uri AS target, author, timestamp FROM link WHERE in = $parent.id ORDER BY timestamp ASC) AS links");
845
- });
846
- it("should include backward link filter when parent is given as raw predicate form", async () => {
847
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
848
- parent: { id: "some://parent-uri", predicate: "custom://has_recipe" },
849
- });
850
- expect(query).toContain("count(<-link[WHERE predicate = 'custom://has_recipe' AND in.uri = 'some://parent-uri']) > 0");
851
- });
852
- it("should resolve model-backed parent form and include correct backward link filter", async () => {
853
- let MenuForQueryTest = class MenuForQueryTest extends Ad4mModel {
854
- constructor() {
855
- super(...arguments);
856
- this.recipes = [];
857
- }
858
- };
859
- __decorate([
860
- HasMany(() => Recipe, { through: "menu://has_recipe" }),
861
- __metadata("design:type", Array)
862
- ], MenuForQueryTest.prototype, "recipes", void 0);
863
- MenuForQueryTest = __decorate([
864
- Model({ name: "MenuForQueryTest" })
865
- ], MenuForQueryTest);
866
- const query = await Recipe.queryToSurrealQL(mockPerspective, {
867
- parent: {
868
- id: "some://menu-uri",
869
- model: MenuForQueryTest,
870
- field: "recipes",
871
- },
872
- });
873
- expect(query).toContain("count(<-link[WHERE predicate = 'menu://has_recipe' AND in.uri = 'some://menu-uri']) > 0");
789
+ expect(query).toContain("->link AS links");
874
790
  });
875
791
  });
876
- describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatch", () => {
792
+ describe("Ad4mModel.instancesFromSurrealResult() and SurrealDB integration", () => {
793
+ // Test Recipe model
794
+ let Recipe = class Recipe extends Ad4mModel {
795
+ constructor() {
796
+ super(...arguments);
797
+ this.name = "";
798
+ this.rating = 0;
799
+ this.ingredients = [];
800
+ }
801
+ };
802
+ __decorate([
803
+ Property({ through: "recipe://name" }),
804
+ __metadata("design:type", String)
805
+ ], Recipe.prototype, "name", void 0);
806
+ __decorate([
807
+ Property({ through: "recipe://rating" }),
808
+ __metadata("design:type", Number)
809
+ ], Recipe.prototype, "rating", void 0);
810
+ __decorate([
811
+ HasMany({ through: "recipe://ingredient" }),
812
+ __metadata("design:type", Array)
813
+ ], Recipe.prototype, "ingredients", void 0);
814
+ Recipe = __decorate([
815
+ Model({ name: "Recipe" })
816
+ ], Recipe);
877
817
  // Mock perspective with both querySurrealDB and infer methods
878
818
  const mockPerspective = {
879
819
  querySurrealDB: jest.fn(),
880
820
  infer: jest.fn(),
881
- uuid: "test-perspective-uuid",
882
- stringOrTemplateObjectToSubjectClassName: jest
883
- .fn()
884
- .mockResolvedValue("Recipe"),
821
+ uuid: 'test-perspective-uuid',
822
+ stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
885
823
  };
886
824
  beforeEach(() => {
887
825
  jest.clearAllMocks();
@@ -897,74 +835,24 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
897
835
  source: "node:abc123",
898
836
  source_uri: "literal://recipe1",
899
837
  links: [
900
- {
901
- predicate: "recipe://name",
902
- target: Literal.from("Pasta").toUrl(),
903
- author: "did:key:alice",
904
- timestamp: "2023-01-01T00:00:00Z",
905
- },
906
- {
907
- predicate: "recipe://rating",
908
- target: Literal.from(5).toUrl(),
909
- author: "did:key:alice",
910
- timestamp: "2023-01-01T00:00:00Z",
911
- },
912
- {
913
- predicate: "recipe://ingredient",
914
- target: "pasta",
915
- author: "did:key:alice",
916
- timestamp: "2023-01-01T00:00:00Z",
917
- },
918
- {
919
- predicate: "recipe://ingredient",
920
- target: "tomato",
921
- author: "did:key:alice",
922
- timestamp: "2023-01-01T00:00:00Z",
923
- },
924
- {
925
- predicate: "recipe://ingredient",
926
- target: "cheese",
927
- author: "did:key:alice",
928
- timestamp: "2023-01-01T00:00:00Z",
929
- },
930
- ],
838
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
839
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
840
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
841
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
842
+ { predicate: "recipe://ingredient", target: "cheese", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
843
+ ]
931
844
  },
932
845
  {
933
846
  source: "node:def456",
934
847
  source_uri: "literal://recipe2",
935
848
  links: [
936
- {
937
- predicate: "recipe://name",
938
- target: Literal.from("Pizza").toUrl(),
939
- author: "did:key:bob",
940
- timestamp: "2023-01-02T00:00:00Z",
941
- },
942
- {
943
- predicate: "recipe://rating",
944
- target: Literal.from(4).toUrl(),
945
- author: "did:key:bob",
946
- timestamp: "2023-01-02T00:00:00Z",
947
- },
948
- {
949
- predicate: "recipe://ingredient",
950
- target: "dough",
951
- author: "did:key:bob",
952
- timestamp: "2023-01-02T00:00:00Z",
953
- },
954
- {
955
- predicate: "recipe://ingredient",
956
- target: "cheese",
957
- author: "did:key:bob",
958
- timestamp: "2023-01-02T00:00:00Z",
959
- },
960
- {
961
- predicate: "recipe://ingredient",
962
- target: "tomato",
963
- author: "did:key:bob",
964
- timestamp: "2023-01-02T00:00:00Z",
965
- },
966
- ],
967
- },
849
+ { predicate: "recipe://name", target: "Pizza", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
850
+ { predicate: "recipe://rating", target: "4", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
851
+ { predicate: "recipe://ingredient", target: "dough", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
852
+ { predicate: "recipe://ingredient", target: "cheese", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
853
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
854
+ ]
855
+ }
968
856
  ];
969
857
  const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
970
858
  expect(result.results).toHaveLength(2);
@@ -979,160 +867,42 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
979
867
  expect(recipe2.name).toBe("Pizza");
980
868
  expect(recipe2.rating).toBe(4);
981
869
  });
982
- it("should set instance id from source_uri", async () => {
983
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, [
984
- {
985
- source: "node:abc123",
986
- source_uri: "literal://recipe1",
987
- links: [
988
- {
989
- predicate: "recipe://name",
990
- target: Literal.from("Pasta").toUrl(),
991
- author: "did:key:alice",
992
- timestamp: "2023-01-01T00:00:00Z",
993
- },
994
- {
995
- predicate: "recipe://rating",
996
- target: Literal.from(5).toUrl(),
997
- author: "did:key:alice",
998
- timestamp: "2023-01-01T00:00:00Z",
999
- },
1000
- ],
1001
- },
1002
- ]);
1003
- expect(result.results).toHaveLength(1);
1004
- // id is derived from source_uri (the node's URI in the graph)
1005
- expect(result.results[0].id).toBe("literal://recipe1");
1006
- });
1007
- it("should use latest-wins semantics when multiple links share a predicate", async () => {
1008
- const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, [
870
+ it("should filter properties when query specifies properties", async () => {
871
+ const surrealResults = [
1009
872
  {
1010
873
  source: "node:abc123",
1011
874
  source_uri: "literal://recipe1",
1012
875
  links: [
1013
- {
1014
- predicate: "recipe://name",
1015
- target: Literal.from("Old Name").toUrl(),
1016
- author: "did:key:alice",
1017
- timestamp: "2023-01-01T00:00:00Z",
1018
- },
1019
- {
1020
- // later timestamp — this value should win
1021
- predicate: "recipe://name",
1022
- target: Literal.from("New Name").toUrl(),
1023
- author: "did:key:alice",
1024
- timestamp: "2023-01-02T00:00:00Z",
1025
- },
1026
- {
1027
- predicate: "recipe://rating",
1028
- target: Literal.from(5).toUrl(),
1029
- author: "did:key:alice",
1030
- timestamp: "2023-01-01T00:00:00Z",
1031
- },
1032
- ],
1033
- },
1034
- ]);
1035
- expect(result.results).toHaveLength(1);
1036
- expect(result.results[0].name).toBe("New Name");
1037
- });
1038
- it("should apply transform function during hydration", async () => {
1039
- let TransformRecipe = class TransformRecipe extends Ad4mModel {
1040
- constructor() {
1041
- super(...arguments);
1042
- this.name = "";
876
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
877
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
878
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
879
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
880
+ ]
1043
881
  }
1044
- };
1045
- __decorate([
1046
- Property({
1047
- through: "recipe://name",
1048
- transform: (v) => v.toUpperCase(),
1049
- }),
1050
- __metadata("design:type", String)
1051
- ], TransformRecipe.prototype, "name", void 0);
1052
- TransformRecipe = __decorate([
1053
- Model({ name: "TransformRecipe" })
1054
- ], TransformRecipe);
1055
- const result = await TransformRecipe.instancesFromSurrealResult(mockPerspective, {}, [
1056
- {
1057
- source: "node:abc123",
1058
- source_uri: "literal://tr1",
1059
- links: [
1060
- {
1061
- predicate: "recipe://name",
1062
- target: Literal.from("pasta").toUrl(),
1063
- author: "did:key:alice",
1064
- timestamp: "2023-01-01T00:00:00Z",
1065
- },
1066
- ],
1067
- },
1068
- ]);
882
+ ];
883
+ const result = await Recipe.instancesFromSurrealResult(mockPerspective, { properties: ["name"] }, surrealResults);
1069
884
  expect(result.results).toHaveLength(1);
1070
- expect(result.results[0].name).toBe("PASTA");
1071
- });
1072
- it("should apply JS-level operator filters — smoke test", async () => {
1073
- // Ratings 1–5 encoded as Literals so the JS filter receives actual numbers
1074
- const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1075
- source: `node:abc${i + 1}`,
1076
- source_uri: `literal://recipe${i + 1}`,
1077
- links: [
1078
- {
1079
- predicate: "recipe://name",
1080
- target: Literal.from(`Recipe ${i + 1}`).toUrl(),
1081
- author: "did:key:alice",
1082
- timestamp: "2023-01-01T00:00:00Z",
1083
- },
1084
- {
1085
- predicate: "recipe://rating",
1086
- target: Literal.from(i + 1).toUrl(),
1087
- author: "did:key:alice",
1088
- timestamp: "2023-01-01T00:00:00Z",
1089
- },
1090
- ],
1091
- }));
1092
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1093
- // Only ratings 4 and 5 pass the JS-level gt filter
1094
- const results = await Recipe.findAll(mockPerspective, {
1095
- where: { rating: { gt: 3 } },
1096
- });
1097
- expect(results).toHaveLength(2);
1098
- // count() must be consistent with findAll()
1099
- const count = await Recipe.count(mockPerspective, {
1100
- where: { rating: { gt: 3 } },
1101
- });
1102
- expect(count).toBe(2);
885
+ const recipe = result.results[0];
886
+ expect(recipe.name).toBe("Pasta");
887
+ // rating and ingredients should be removed since only "name" was requested
888
+ expect(recipe.rating).toBeUndefined();
889
+ expect(recipe.ingredients).toBeUndefined();
890
+ // author, createdAt, updatedAt are also stripped unless explicitly requested
891
+ expect(recipe.author).toBeUndefined();
892
+ expect(recipe.timestamp).toBeUndefined();
1103
893
  });
1104
- it("should filter fields when query specifies fields", async () => {
894
+ it("should filter properties when query specifies properties", async () => {
1105
895
  const surrealResults = [
1106
896
  {
1107
897
  source: "node:abc123",
1108
898
  source_uri: "literal://recipe1",
1109
899
  links: [
1110
- {
1111
- predicate: "recipe://name",
1112
- target: "Pasta",
1113
- author: "did:key:alice",
1114
- timestamp: "2023-01-01T00:00:00Z",
1115
- },
1116
- {
1117
- predicate: "recipe://rating",
1118
- target: "5",
1119
- author: "did:key:alice",
1120
- timestamp: "2023-01-01T00:00:00Z",
1121
- },
1122
- {
1123
- predicate: "recipe://ingredient",
1124
- target: "pasta",
1125
- author: "did:key:alice",
1126
- timestamp: "2023-01-01T00:00:00Z",
1127
- },
1128
- {
1129
- predicate: "recipe://ingredient",
1130
- target: "tomato",
1131
- author: "did:key:alice",
1132
- timestamp: "2023-01-01T00:00:00Z",
1133
- },
1134
- ],
1135
- },
900
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
901
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
902
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
903
+ { predicate: "recipe://ingredient", target: "tomato", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
904
+ ]
905
+ }
1136
906
  ];
1137
907
  const result = await Recipe.instancesFromSurrealResult(mockPerspective, { properties: ["name"] }, surrealResults);
1138
908
  expect(result.results).toHaveLength(1);
@@ -1140,32 +910,16 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1140
910
  expect(recipe.name).toBe("Pasta");
1141
911
  // rating and ingredients should be removed since only "name" was requested
1142
912
  expect(recipe.rating).toBeUndefined();
1143
- expect(recipe.ingredients).toBeUndefined();
1144
- // author and timestamp are metadata fields — they are also stripped unless
1145
- // explicitly listed in `properties`. Integration tests cover the
1146
- // `properties: ["author", "createdAt"]` case.
1147
- expect(recipe.author).toBeUndefined();
1148
- expect(recipe.createdAt).toBeUndefined();
1149
913
  });
1150
914
  it("should handle results missing base field", async () => {
1151
915
  const surrealResults = [
1152
916
  {
1153
917
  links: [
1154
- {
1155
- predicate: "recipe://name",
1156
- target: "Pasta",
1157
- author: "did:key:alice",
1158
- timestamp: "2023-01-01T00:00:00Z",
1159
- },
1160
- {
1161
- predicate: "recipe://rating",
1162
- target: "5",
1163
- author: "did:key:alice",
1164
- timestamp: "2023-01-01T00:00:00Z",
1165
- },
1166
- ],
918
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
919
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
920
+ ]
1167
921
  // Missing source field
1168
- },
922
+ }
1169
923
  ];
1170
924
  const result = await Recipe.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
1171
925
  // Should filter out the invalid result (or handle gracefully)
@@ -1178,26 +932,11 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1178
932
  source: "node:abc123",
1179
933
  source_uri: "literal://recipe1",
1180
934
  links: [
1181
- {
1182
- predicate: "recipe://name",
1183
- target: "Pasta",
1184
- author: "did:key:alice",
1185
- timestamp: "2023-01-01T00:00:00Z",
1186
- },
1187
- {
1188
- predicate: "recipe://rating",
1189
- target: "5",
1190
- author: "did:key:alice",
1191
- timestamp: "2023-01-01T00:00:00Z",
1192
- },
1193
- {
1194
- predicate: "recipe://ingredient",
1195
- target: "pasta",
1196
- author: "did:key:alice",
1197
- timestamp: "2023-01-01T00:00:00Z",
1198
- },
1199
- ],
1200
- },
935
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
936
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
937
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
938
+ ]
939
+ }
1201
940
  ];
1202
941
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1203
942
  const results = await Recipe.findAll(mockPerspective, {});
@@ -1206,32 +945,30 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1206
945
  expect(results).toHaveLength(1);
1207
946
  expect(results[0].name).toBe("Pasta");
1208
947
  });
948
+ it("should use Prolog when useSurrealDB is false in findAll()", async () => {
949
+ const prologResults = [{
950
+ AllInstances: [
951
+ ["literal://recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
952
+ ],
953
+ TotalCount: 1
954
+ }];
955
+ mockPerspective.infer.mockResolvedValue(prologResults);
956
+ const results = await Recipe.findAll(mockPerspective, {}, false);
957
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
958
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
959
+ expect(results).toHaveLength(1);
960
+ });
1209
961
  it("should use SurrealDB by default in findAllAndCount()", async () => {
1210
962
  const surrealResults = [
1211
963
  {
1212
964
  source: "node:abc123",
1213
965
  source_uri: "literal://recipe1",
1214
966
  links: [
1215
- {
1216
- predicate: "recipe://name",
1217
- target: "Pasta",
1218
- author: "did:key:alice",
1219
- timestamp: "2023-01-01T00:00:00Z",
1220
- },
1221
- {
1222
- predicate: "recipe://rating",
1223
- target: "5",
1224
- author: "did:key:alice",
1225
- timestamp: "2023-01-01T00:00:00Z",
1226
- },
1227
- {
1228
- predicate: "recipe://ingredient",
1229
- target: "pasta",
1230
- author: "did:key:alice",
1231
- timestamp: "2023-01-01T00:00:00Z",
1232
- },
1233
- ],
1234
- },
967
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
968
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
969
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
970
+ ]
971
+ }
1235
972
  ];
1236
973
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1237
974
  const { results, totalCount } = await Recipe.findAllAndCount(mockPerspective, {});
@@ -1246,26 +983,11 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1246
983
  source: "node:abc123",
1247
984
  source_uri: "literal://recipe1",
1248
985
  links: [
1249
- {
1250
- predicate: "recipe://name",
1251
- target: "Pasta",
1252
- author: "did:key:alice",
1253
- timestamp: "2023-01-01T00:00:00Z",
1254
- },
1255
- {
1256
- predicate: "recipe://rating",
1257
- target: "5",
1258
- author: "did:key:alice",
1259
- timestamp: "2023-01-01T00:00:00Z",
1260
- },
1261
- {
1262
- predicate: "recipe://ingredient",
1263
- target: "pasta",
1264
- author: "did:key:alice",
1265
- timestamp: "2023-01-01T00:00:00Z",
1266
- },
1267
- ],
1268
- },
986
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
987
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
988
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
989
+ ]
990
+ }
1269
991
  ];
1270
992
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1271
993
  const page = await Recipe.paginate(mockPerspective, 10, 1, {});
@@ -1282,19 +1004,9 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1282
1004
  source: `node:abc${i + 1}`,
1283
1005
  source_uri: `literal://recipe${i + 1}`,
1284
1006
  links: [
1285
- {
1286
- predicate: "recipe://name",
1287
- target: `Recipe ${i + 1}`,
1288
- author: "did:key:alice",
1289
- timestamp: "2023-01-01T00:00:00Z",
1290
- },
1291
- {
1292
- predicate: "recipe://rating",
1293
- target: "5",
1294
- author: "did:key:alice",
1295
- timestamp: "2023-01-01T00:00:00Z",
1296
- },
1297
- ],
1007
+ { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1008
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1009
+ ]
1298
1010
  }));
1299
1011
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1300
1012
  const count = await Recipe.count(mockPerspective, {});
@@ -1302,32 +1014,25 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1302
1014
  expect(mockPerspective.infer).not.toHaveBeenCalled();
1303
1015
  expect(count).toBe(5);
1304
1016
  });
1017
+ it("should use Prolog when useSurrealDB is false in count()", async () => {
1018
+ const prologResults = [{ TotalCount: 10 }];
1019
+ mockPerspective.infer.mockResolvedValue(prologResults);
1020
+ const count = await Recipe.count(mockPerspective, {}, false);
1021
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1022
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1023
+ expect(count).toBe(10);
1024
+ });
1305
1025
  it("should use SurrealDB by default in ModelQueryBuilder.get()", async () => {
1306
1026
  const surrealResults = [
1307
1027
  {
1308
1028
  source: "node:abc123",
1309
1029
  source_uri: "literal://recipe1",
1310
1030
  links: [
1311
- {
1312
- predicate: "recipe://name",
1313
- target: "Pasta",
1314
- author: "did:key:alice",
1315
- timestamp: "2023-01-01T00:00:00Z",
1316
- },
1317
- {
1318
- predicate: "recipe://rating",
1319
- target: "5",
1320
- author: "did:key:alice",
1321
- timestamp: "2023-01-01T00:00:00Z",
1322
- },
1323
- {
1324
- predicate: "recipe://ingredient",
1325
- target: "pasta",
1326
- author: "did:key:alice",
1327
- timestamp: "2023-01-01T00:00:00Z",
1328
- },
1329
- ],
1330
- },
1031
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1032
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1033
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1034
+ ]
1035
+ }
1331
1036
  ];
1332
1037
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1333
1038
  const results = await Recipe.query(mockPerspective)
@@ -1338,25 +1043,31 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1338
1043
  expect(results).toHaveLength(1);
1339
1044
  expect(results[0].name).toBe("Pasta");
1340
1045
  });
1046
+ it("should use Prolog when useSurrealDB(false) in ModelQueryBuilder.get()", async () => {
1047
+ const prologResults = [{
1048
+ AllInstances: [
1049
+ ["literal://recipe1", [["name", "Pasta"]], [["ingredients", ["pasta"]]], "2023-01-01T00:00:00Z", "did:key:alice"]
1050
+ ],
1051
+ TotalCount: 1
1052
+ }];
1053
+ mockPerspective.infer.mockResolvedValue(prologResults);
1054
+ const results = await Recipe.query(mockPerspective)
1055
+ .where({ name: "Pasta" })
1056
+ .useSurrealDB(false)
1057
+ .get();
1058
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1059
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1060
+ expect(results).toHaveLength(1);
1061
+ });
1341
1062
  it("should use SurrealDB by default in ModelQueryBuilder.count()", async () => {
1342
1063
  // count() counts the number of rows returned by the query (one row per source)
1343
1064
  const surrealResults = Array.from({ length: 3 }, (_, i) => ({
1344
1065
  source: `node:abc${i + 1}`,
1345
1066
  source_uri: `literal://recipe${i + 1}`,
1346
1067
  links: [
1347
- {
1348
- predicate: "recipe://name",
1349
- target: `Recipe ${i + 1}`,
1350
- author: "did:key:alice",
1351
- timestamp: "2023-01-01T00:00:00Z",
1352
- },
1353
- {
1354
- predicate: "recipe://rating",
1355
- target: "5",
1356
- author: "did:key:alice",
1357
- timestamp: "2023-01-01T00:00:00Z",
1358
- },
1359
- ],
1068
+ { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1069
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1070
+ ]
1360
1071
  }));
1361
1072
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1362
1073
  const count = await Recipe.query(mockPerspective)
@@ -1372,26 +1083,11 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1372
1083
  source: "node:abc123",
1373
1084
  source_uri: "literal://recipe1",
1374
1085
  links: [
1375
- {
1376
- predicate: "recipe://name",
1377
- target: "Pasta",
1378
- author: "did:key:alice",
1379
- timestamp: "2023-01-01T00:00:00Z",
1380
- },
1381
- {
1382
- predicate: "recipe://rating",
1383
- target: "5",
1384
- author: "did:key:alice",
1385
- timestamp: "2023-01-01T00:00:00Z",
1386
- },
1387
- {
1388
- predicate: "recipe://ingredient",
1389
- target: "pasta",
1390
- author: "did:key:alice",
1391
- timestamp: "2023-01-01T00:00:00Z",
1392
- },
1393
- ],
1394
- },
1086
+ { predicate: "recipe://name", target: "Pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1087
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1088
+ { predicate: "recipe://ingredient", target: "pasta", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1089
+ ]
1090
+ }
1395
1091
  ];
1396
1092
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1397
1093
  const page = await Recipe.query(mockPerspective)
@@ -1404,363 +1100,210 @@ describe("Ad4mModel.instancesFromSurrealResult() — hydration and query dispatc
1404
1100
  expect(page.pageNumber).toBe(1);
1405
1101
  });
1406
1102
  });
1407
- describe("resolveLanguage implicit literal default", () => {
1408
- // A plain @Property with no resolveLanguage should behave identically to
1409
- // resolveLanguage: "literal" — scalar values encoded as literal:// URIs
1410
- // are unwrapped on read, and no createExpression call is made on write.
1411
- let ImplicitLiteralModel = class ImplicitLiteralModel extends Ad4mModel {
1103
+ describe("Ad4mModel.count() with advanced where conditions", () => {
1104
+ // Test Recipe model
1105
+ let Recipe = class Recipe extends Ad4mModel {
1412
1106
  constructor() {
1413
1107
  super(...arguments);
1414
1108
  this.name = "";
1415
- this.count = 0;
1416
- this.active = false;
1109
+ this.rating = 0;
1110
+ this.ingredients = [];
1417
1111
  }
1418
1112
  };
1419
1113
  __decorate([
1420
- Property({ through: "test://name" }),
1114
+ Property({ through: "recipe://name" }),
1421
1115
  __metadata("design:type", String)
1422
- ], ImplicitLiteralModel.prototype, "name", void 0);
1116
+ ], Recipe.prototype, "name", void 0);
1423
1117
  __decorate([
1424
- Property({ through: "test://count" }),
1118
+ Property({ through: "recipe://rating" }),
1425
1119
  __metadata("design:type", Number)
1426
- ], ImplicitLiteralModel.prototype, "count", void 0);
1120
+ ], Recipe.prototype, "rating", void 0);
1427
1121
  __decorate([
1428
- Property({ through: "test://active" }),
1429
- __metadata("design:type", Boolean)
1430
- ], ImplicitLiteralModel.prototype, "active", void 0);
1431
- ImplicitLiteralModel = __decorate([
1432
- Model({ name: "ImplicitLiteralModel" })
1433
- ], ImplicitLiteralModel);
1122
+ HasMany({ through: "recipe://ingredient" }),
1123
+ __metadata("design:type", Array)
1124
+ ], Recipe.prototype, "ingredients", void 0);
1125
+ Recipe = __decorate([
1126
+ Model({ name: "Recipe" })
1127
+ ], Recipe);
1128
+ // Mock perspective
1434
1129
  const mockPerspective = {
1435
1130
  querySurrealDB: jest.fn(),
1436
1131
  infer: jest.fn(),
1437
- uuid: "test-perspective-uuid",
1438
- stringOrTemplateObjectToSubjectClassName: jest
1439
- .fn()
1440
- .mockResolvedValue("ImplicitLiteralModel"),
1132
+ uuid: 'test-perspective-uuid',
1133
+ stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue('Recipe')
1441
1134
  };
1442
- beforeEach(() => jest.clearAllMocks());
1443
- it('should store undefined resolveLanguage in metadata (not "literal")', () => {
1444
- const metadata = ImplicitLiteralModel.getModelMetadata();
1445
- expect(metadata.properties.name.resolveLanguage).toBeUndefined();
1446
- expect(metadata.properties.count.resolveLanguage).toBeUndefined();
1447
- expect(metadata.properties.active.resolveLanguage).toBeUndefined();
1448
- });
1449
- it("should hydrate literal:// encoded targets for properties with no resolveLanguage", async () => {
1450
- const surrealResults = [
1451
- {
1452
- source: "node:abc123",
1453
- source_uri: "literal://base",
1454
- links: [
1455
- {
1456
- predicate: "test://name",
1457
- target: Literal.from("hello world").toUrl(),
1458
- author: "did:key:alice",
1459
- timestamp: "2023-01-01T00:00:00Z",
1460
- },
1461
- {
1462
- predicate: "test://count",
1463
- target: Literal.from(42).toUrl(),
1464
- author: "did:key:alice",
1465
- timestamp: "2023-01-01T00:00:00Z",
1466
- },
1467
- {
1468
- predicate: "test://active",
1469
- target: Literal.from(true).toUrl(),
1470
- author: "did:key:alice",
1471
- timestamp: "2023-01-01T00:00:00Z",
1472
- },
1473
- ],
1474
- },
1475
- ];
1476
- mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1477
- const result = await ImplicitLiteralModel.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
1478
- expect(result.results).toHaveLength(1);
1479
- const instance = result.results[0];
1480
- expect(instance.name).toBe("hello world");
1481
- expect(instance.count).toBe(42);
1482
- expect(instance.active).toBe(true);
1135
+ beforeEach(() => {
1136
+ jest.clearAllMocks();
1483
1137
  });
1484
- it("should NOT call perspective.getExpression for properties with no resolveLanguage", async () => {
1485
- const surrealResults = [
1486
- {
1487
- source: "node:abc123",
1488
- source_uri: "literal://base",
1489
- links: [
1490
- {
1491
- predicate: "test://name",
1492
- target: Literal.from("test").toUrl(),
1493
- author: "did:key:alice",
1494
- timestamp: "2023-01-01T00:00:00Z",
1495
- },
1496
- ],
1497
- },
1498
- ];
1138
+ it("should apply JS-level filtering for gt operator on properties in SurrealDB count()", async () => {
1139
+ // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1140
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1141
+ source: `node:abc${i + 1}`,
1142
+ source_uri: `literal://recipe${i + 1}`,
1143
+ links: [
1144
+ { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1145
+ { predicate: "recipe://rating", target: `${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1146
+ ]
1147
+ }));
1499
1148
  mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1500
- const getExpression = jest.fn();
1501
- mockPerspective.getExpression = getExpression;
1502
- await ImplicitLiteralModel.instancesFromSurrealResult(mockPerspective, {}, surrealResults);
1503
- expect(getExpression).not.toHaveBeenCalled();
1504
- });
1505
- });
1506
- describe("resolveParentPredicate()", () => {
1507
- let Comment = class Comment extends Ad4mModel {
1508
- };
1509
- Comment = __decorate([
1510
- Model({ name: "Comment" })
1511
- ], Comment);
1512
- let Tag = class Tag extends Ad4mModel {
1513
- };
1514
- Tag = __decorate([
1515
- Model({ name: "Tag" })
1516
- ], Tag);
1517
- let Channel = class Channel extends Ad4mModel {
1518
- constructor() {
1519
- super(...arguments);
1520
- this.comments = [];
1521
- this.tags = [];
1522
- }
1523
- };
1524
- __decorate([
1525
- HasMany(() => Comment, { through: "channel://has_comment" }),
1526
- __metadata("design:type", Array)
1527
- ], Channel.prototype, "comments", void 0);
1528
- __decorate([
1529
- HasMany(() => Tag, { through: "channel://has_tag" }),
1530
- __metadata("design:type", Array)
1531
- ], Channel.prototype, "tags", void 0);
1532
- Channel = __decorate([
1533
- Model({ name: "Channel" })
1534
- ], Channel);
1535
- let AmbiguousParent = class AmbiguousParent extends Ad4mModel {
1536
- constructor() {
1537
- super(...arguments);
1538
- this.primaryComments = [];
1539
- this.secondaryComments = [];
1540
- }
1541
- };
1542
- __decorate([
1543
- HasMany(() => Comment, { through: "parent://primary_comments" }),
1544
- __metadata("design:type", Array)
1545
- ], AmbiguousParent.prototype, "primaryComments", void 0);
1546
- __decorate([
1547
- HasMany(() => Comment, { through: "parent://secondary_comments" }),
1548
- __metadata("design:type", Array)
1549
- ], AmbiguousParent.prototype, "secondaryComments", void 0);
1550
- AmbiguousParent = __decorate([
1551
- Model({ name: "AmbiguousParent" })
1552
- ], AmbiguousParent);
1553
- it("resolves predicate by explicit field name", () => {
1554
- const meta = Channel.getModelMetadata();
1555
- expect(resolveParentPredicate(meta, Comment, "comments")).toBe("channel://has_comment");
1556
- });
1557
- it("infers predicate from child constructor when field is omitted", () => {
1558
- const meta = Channel.getModelMetadata();
1559
- expect(resolveParentPredicate(meta, Comment)).toBe("channel://has_comment");
1560
- });
1561
- it("throws when explicit field does not exist on parent", () => {
1562
- const meta = Channel.getModelMetadata();
1563
- expect(() => resolveParentPredicate(meta, Comment, "nonExistent")).toThrow(/field "nonExistent" not found/);
1564
- });
1565
- it("throws when no relation on parent matches the child type", () => {
1566
- let UnrelatedParent = class UnrelatedParent extends Ad4mModel {
1567
- };
1568
- UnrelatedParent = __decorate([
1569
- Model({ name: "UnrelatedParent" })
1570
- ], UnrelatedParent);
1571
- const meta = UnrelatedParent.getModelMetadata();
1572
- expect(() => resolveParentPredicate(meta, Comment)).toThrow(/no forward relation pointing to "Comment"/);
1149
+ // Count recipes with rating > 3 (should match 2 recipes: rating 4 and 5)
1150
+ const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } });
1151
+ // Verify count matches the number of instances that would be returned by findAll
1152
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { gt: 3 } } });
1153
+ expect(count).toBe(2);
1154
+ expect(count).toBe(findAllResults.length);
1573
1155
  });
1574
- it("throws when neither field nor childCtor is provided", () => {
1575
- const meta = Channel.getModelMetadata();
1576
- expect(() => resolveParentPredicate(meta, undefined)).toThrow(/either "field" or a child model constructor must be provided/);
1156
+ it("should apply JS-level filtering for between operator on properties in SurrealDB count()", async () => {
1157
+ // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1158
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1159
+ source: `node:abc${i + 1}`,
1160
+ source_uri: `literal://recipe${i + 1}`,
1161
+ links: [
1162
+ { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1163
+ { predicate: "recipe://rating", target: `${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1164
+ ]
1165
+ }));
1166
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1167
+ // Count recipes with rating between 2 and 4 (should match 3 recipes: rating 2, 3, 4)
1168
+ const count = await Recipe.count(mockPerspective, { where: { rating: { between: [2, 4] } } });
1169
+ // Verify count matches the number of instances that would be returned by findAll
1170
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { rating: { between: [2, 4] } } });
1171
+ expect(count).toBe(3);
1172
+ expect(count).toBe(findAllResults.length);
1577
1173
  });
1578
- it("throws with disambiguation hint when multiple relations point to the same type", () => {
1579
- const meta = AmbiguousParent.getModelMetadata();
1580
- expect(() => resolveParentPredicate(meta, Comment)).toThrow(/multiple relations.*provide "field" to disambiguate/i);
1174
+ it("should apply JS-level filtering for timestamp gt operator in SurrealDB count()", async () => {
1175
+ // Mock SurrealDB results: 5 recipes with different timestamps
1176
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1177
+ source: `node:abc${i + 1}`,
1178
+ source_uri: `literal://recipe${i + 1}`,
1179
+ links: [
1180
+ { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` },
1181
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` }
1182
+ ]
1183
+ }));
1184
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1185
+ // Count recipes with timestamp > 2023-01-03 (should match 2 recipes: 2023-01-04 and 2023-01-05)
1186
+ const targetTimestamp = new Date("2023-01-03T00:00:00Z").getTime();
1187
+ const count = await Recipe.count(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
1188
+ // Verify count matches the number of instances that would be returned by findAll
1189
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { timestamp: { gt: targetTimestamp } } });
1190
+ expect(count).toBe(2);
1191
+ expect(count).toBe(findAllResults.length);
1581
1192
  });
1582
- });
1583
- describe("normalizeParentQuery()", () => {
1584
- let NpqTag = class NpqTag extends Ad4mModel {
1585
- };
1586
- NpqTag = __decorate([
1587
- Model({ name: "NpqTag" })
1588
- ], NpqTag);
1589
- let NpqComment = class NpqComment extends Ad4mModel {
1590
- };
1591
- NpqComment = __decorate([
1592
- Model({ name: "NpqComment" })
1593
- ], NpqComment);
1594
- let NpqBlogPost = class NpqBlogPost extends Ad4mModel {
1595
- constructor() {
1596
- super(...arguments);
1597
- this.tags = [];
1598
- this.comments = [];
1599
- this.pinnedComments = [];
1600
- }
1601
- };
1602
- __decorate([
1603
- HasMany(() => NpqTag, { through: "blog://has_tag" }),
1604
- __metadata("design:type", Array)
1605
- ], NpqBlogPost.prototype, "tags", void 0);
1606
- __decorate([
1607
- HasMany(() => NpqComment, { through: "blog://has_comment" }),
1608
- __metadata("design:type", Array)
1609
- ], NpqBlogPost.prototype, "comments", void 0);
1610
- __decorate([
1611
- HasMany(() => NpqComment, { through: "blog://has_pinned_comment" }),
1612
- __metadata("design:type", Array)
1613
- ], NpqBlogPost.prototype, "pinnedComments", void 0);
1614
- NpqBlogPost = __decorate([
1615
- Model({ name: "NpqBlogPost" })
1616
- ], NpqBlogPost);
1617
- it("passes through raw { id, predicate } form unchanged", () => {
1618
- const raw = { id: "some://uri", predicate: "custom://predicate" };
1619
- expect(normalizeParentQuery(raw)).toEqual(raw);
1620
- });
1621
- it("resolves model-backed form with explicit field", () => {
1622
- const result = normalizeParentQuery({
1623
- id: "some://uri",
1624
- model: NpqBlogPost,
1625
- field: "tags",
1193
+ it("should apply JS-level filtering for timestamp between operator in SurrealDB count()", async () => {
1194
+ // Mock SurrealDB results: 5 recipes with different timestamps
1195
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1196
+ source: `node:abc${i + 1}`,
1197
+ source_uri: `literal://recipe${i + 1}`,
1198
+ links: [
1199
+ { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` },
1200
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` }
1201
+ ]
1202
+ }));
1203
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1204
+ // Count recipes with timestamp between 2023-01-02 and 2023-01-04
1205
+ const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1206
+ const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1207
+ const count = await Recipe.count(mockPerspective, {
1208
+ where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1626
1209
  });
1627
- expect(result).toEqual({ id: "some://uri", predicate: "blog://has_tag" });
1210
+ // Verify count matches the number of instances that would be returned by findAll
1211
+ const findAllResults = await Recipe.findAll(mockPerspective, {
1212
+ where: { timestamp: { between: [startTimestamp, endTimestamp] } }
1213
+ });
1214
+ expect(count).toBe(3);
1215
+ expect(count).toBe(findAllResults.length);
1628
1216
  });
1629
- it("infers predicate from childCtor when field is omitted", () => {
1630
- const result = normalizeParentQuery({ id: "some://uri", model: NpqBlogPost }, NpqTag);
1631
- expect(result).toEqual({ id: "some://uri", predicate: "blog://has_tag" });
1217
+ it("should apply JS-level filtering for author filtering in SurrealDB count()", async () => {
1218
+ // Mock SurrealDB results: 3 recipes by Alice and 2 by Bob
1219
+ const surrealResults = [
1220
+ ...Array.from({ length: 3 }, (_, i) => ({
1221
+ source: `node:abc${i + 1}`,
1222
+ source_uri: `literal://recipe${i + 1}`,
1223
+ links: [
1224
+ { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1225
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1226
+ ]
1227
+ })),
1228
+ ...Array.from({ length: 2 }, (_, i) => ({
1229
+ source: `node:def${i + 4}`,
1230
+ source_uri: `literal://recipe${i + 4}`,
1231
+ links: [
1232
+ { predicate: "recipe://name", target: `Recipe ${i + 4}`, author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" },
1233
+ { predicate: "recipe://rating", target: "5", author: "did:key:bob", timestamp: "2023-01-02T00:00:00Z" }
1234
+ ]
1235
+ }))
1236
+ ];
1237
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1238
+ // Count recipes by Alice (should match 3 recipes)
1239
+ const count = await Recipe.count(mockPerspective, { where: { author: "did:key:alice" } });
1240
+ // Verify count matches the number of instances that would be returned by findAll
1241
+ const findAllResults = await Recipe.findAll(mockPerspective, { where: { author: "did:key:alice" } });
1242
+ expect(count).toBe(3);
1243
+ expect(count).toBe(findAllResults.length);
1632
1244
  });
1633
- it("throws when model-backed form has no field and multiple relations point to the same child type", () => {
1634
- expect(() => normalizeParentQuery({ id: "some://uri", model: NpqBlogPost }, NpqComment)).toThrow(/multiple relations.*provide "field" to disambiguate/i);
1245
+ it("should apply JS-level filtering in ModelQueryBuilder.count() with gt operator", async () => {
1246
+ // Mock SurrealDB results: 5 recipes with ratings 1, 2, 3, 4, 5
1247
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1248
+ source: `node:abc${i + 1}`,
1249
+ source_uri: `literal://recipe${i + 1}`,
1250
+ links: [
1251
+ { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" },
1252
+ { predicate: "recipe://rating", target: `${i + 1}`, author: "did:key:alice", timestamp: "2023-01-01T00:00:00Z" }
1253
+ ]
1254
+ }));
1255
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1256
+ // Count recipes with rating > 3 using ModelQueryBuilder
1257
+ const count = await Recipe.query(mockPerspective)
1258
+ .where({ rating: { gt: 3 } })
1259
+ .count();
1260
+ // Verify count matches the number of instances that would be returned by get()
1261
+ const getResults = await Recipe.query(mockPerspective)
1262
+ .where({ rating: { gt: 3 } })
1263
+ .get();
1264
+ expect(count).toBe(2);
1265
+ expect(count).toBe(getResults.length);
1635
1266
  });
1636
- });
1637
- describe("Ad4mModel.update() — static convenience method", () => {
1638
- let UpdatableModel = class UpdatableModel extends Ad4mModel {
1639
- constructor() {
1640
- super(...arguments);
1641
- this.title = "";
1642
- this.body = "";
1643
- this.count = 0;
1644
- }
1645
- };
1646
- __decorate([
1647
- Property({ through: "test://title" }),
1648
- __metadata("design:type", String)
1649
- ], UpdatableModel.prototype, "title", void 0);
1650
- __decorate([
1651
- Property({ through: "test://body" }),
1652
- __metadata("design:type", String)
1653
- ], UpdatableModel.prototype, "body", void 0);
1654
- __decorate([
1655
- Property({ through: "test://count" }),
1656
- __metadata("design:type", Number)
1657
- ], UpdatableModel.prototype, "count", void 0);
1658
- UpdatableModel = __decorate([
1659
- Model({ name: "UpdatableModel" })
1660
- ], UpdatableModel);
1661
- it("calls get() then save() after merging data", async () => {
1662
- const existingTitle = "Original Title";
1663
- const existingBody = "Original Body";
1664
- const mockPerspective = {
1665
- querySurrealDB: jest.fn().mockResolvedValue([
1666
- {
1667
- source: "literal://string:abc123",
1668
- source_uri: "literal://string:abc123",
1669
- links: [
1670
- { predicate: "test://title", target: `literal://string:${existingTitle}`, author: "did:key:alice", timestamp: "2024-01-01T00:00:00Z" },
1671
- { predicate: "test://body", target: `literal://string:${existingBody}`, author: "did:key:alice", timestamp: "2024-01-01T00:00:00Z" },
1672
- { predicate: "test://count", target: "literal://number:5", author: "did:key:alice", timestamp: "2024-01-01T00:00:00Z" },
1673
- ],
1674
- },
1675
- ]),
1676
- infer: jest.fn(),
1677
- uuid: "test-uuid",
1678
- stringOrTemplateObjectToSubjectClassName: jest.fn().mockResolvedValue("UpdatableModel"),
1679
- add: jest.fn(),
1680
- remove: jest.fn(),
1681
- get: jest.fn().mockResolvedValue([]),
1682
- removeSubject: jest.fn(),
1683
- createSubject: jest.fn(),
1684
- subjectEntities: jest.fn().mockResolvedValue([]),
1685
- };
1686
- const saveSpy = jest.spyOn(UpdatableModel.prototype, "save").mockResolvedValue();
1687
- const getSpy = jest.spyOn(UpdatableModel.prototype, "get").mockImplementation(async function () {
1688
- this.title = existingTitle;
1689
- this.body = existingBody;
1690
- this.count = 5;
1691
- return this;
1692
- });
1693
- const result = await UpdatableModel.update(mockPerspective, "literal://string:abc123", { title: "New Title" });
1694
- // get() must be called to fetch the pre-existing state
1695
- expect(getSpy).toHaveBeenCalledTimes(1);
1696
- // save() must be called after merging
1697
- expect(saveSpy).toHaveBeenCalledTimes(1);
1698
- // Only the provided field was overwritten
1699
- expect(result.title).toBe("New Title");
1700
- // Other fields are preserved from the fetched state
1701
- expect(result.body).toBe(existingBody);
1702
- expect(result.count).toBe(5);
1703
- getSpy.mockRestore();
1704
- saveSpy.mockRestore();
1705
- });
1706
- it("returns the updated instance", async () => {
1707
- const saveSpy = jest.spyOn(UpdatableModel.prototype, "save").mockResolvedValue();
1708
- const getSpy = jest.spyOn(UpdatableModel.prototype, "get").mockImplementation(async function () {
1709
- this.title = "Old";
1710
- this.body = "kept";
1711
- return this;
1712
- });
1713
- const mockPerspective = {};
1714
- const result = await UpdatableModel.update(mockPerspective, "literal://string:xyz", { title: "New" });
1715
- expect(result).toBeInstanceOf(UpdatableModel);
1716
- expect(result.id).toBe("literal://string:xyz");
1717
- getSpy.mockRestore();
1718
- saveSpy.mockRestore();
1719
- });
1720
- it("passes batchId through to save()", async () => {
1721
- const saveSpy = jest.spyOn(UpdatableModel.prototype, "save").mockResolvedValue();
1722
- const getSpy = jest.spyOn(UpdatableModel.prototype, "get").mockImplementation(async function () {
1723
- return this;
1724
- });
1725
- await UpdatableModel.update({}, "literal://string:id1", {}, "batch-42");
1726
- expect(saveSpy).toHaveBeenCalledWith("batch-42");
1727
- getSpy.mockRestore();
1728
- saveSpy.mockRestore();
1267
+ it("should apply JS-level filtering in ModelQueryBuilder.count() with timestamp between", async () => {
1268
+ // Mock SurrealDB results: 5 recipes with different timestamps
1269
+ const surrealResults = Array.from({ length: 5 }, (_, i) => ({
1270
+ source: `node:abc${i + 1}`,
1271
+ source_uri: `literal://recipe${i + 1}`,
1272
+ links: [
1273
+ { predicate: "recipe://name", target: `Recipe ${i + 1}`, author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` },
1274
+ { predicate: "recipe://rating", target: "5", author: "did:key:alice", timestamp: `2023-01-0${i + 1}T00:00:00Z` }
1275
+ ]
1276
+ }));
1277
+ mockPerspective.querySurrealDB.mockResolvedValue(surrealResults);
1278
+ const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1279
+ const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1280
+ // Count using ModelQueryBuilder
1281
+ const count = await Recipe.query(mockPerspective)
1282
+ .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1283
+ .count();
1284
+ // Verify count matches the number of instances that would be returned by get()
1285
+ const getResults = await Recipe.query(mockPerspective)
1286
+ .where({ timestamp: { between: [startTimestamp, endTimestamp] } })
1287
+ .get();
1288
+ expect(count).toBe(3);
1289
+ expect(count).toBe(getResults.length);
1290
+ });
1291
+ it("should handle count() with Prolog for gt operator (legacy)", async () => {
1292
+ const prologResults = [{ TotalCount: 2 }];
1293
+ mockPerspective.infer.mockResolvedValue(prologResults);
1294
+ const count = await Recipe.count(mockPerspective, { where: { rating: { gt: 3 } } }, false);
1295
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1296
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1297
+ expect(count).toBe(2);
1729
1298
  });
1730
- });
1731
- describe("Ad4mModel.delete() — static convenience method", () => {
1732
- let DeletableModel = class DeletableModel extends Ad4mModel {
1733
- constructor() {
1734
- super(...arguments);
1735
- this.label = "";
1736
- }
1737
- };
1738
- __decorate([
1739
- Property({ through: "test://label" }),
1740
- __metadata("design:type", String)
1741
- ], DeletableModel.prototype, "label", void 0);
1742
- DeletableModel = __decorate([
1743
- Model({ name: "DeletableModel" })
1744
- ], DeletableModel);
1745
- it("calls instance.delete() with no batchId by default", async () => {
1746
- const deleteSpy = jest.spyOn(DeletableModel.prototype, "delete").mockResolvedValue();
1747
- await DeletableModel.delete({}, "literal://string:del1");
1748
- expect(deleteSpy).toHaveBeenCalledTimes(1);
1749
- expect(deleteSpy).toHaveBeenCalledWith(undefined);
1750
- deleteSpy.mockRestore();
1751
- });
1752
- it("forwards batchId to instance.delete()", async () => {
1753
- const deleteSpy = jest.spyOn(DeletableModel.prototype, "delete").mockResolvedValue();
1754
- await DeletableModel.delete({}, "literal://string:del2", "batch-99");
1755
- expect(deleteSpy).toHaveBeenCalledWith("batch-99");
1756
- deleteSpy.mockRestore();
1757
- });
1758
- it("constructs an instance with the given id", async () => {
1759
- const deleteSpy = jest.spyOn(DeletableModel.prototype, "delete").mockResolvedValue();
1760
- const targetId = "literal://string:target-id";
1761
- await DeletableModel.delete({}, targetId);
1762
- // The static method must target the correct id
1763
- expect(deleteSpy.mock.instances[0].id).toBe(targetId);
1764
- deleteSpy.mockRestore();
1299
+ it("should handle count() with Prolog for timestamp between (legacy)", async () => {
1300
+ const prologResults = [{ TotalCount: 3 }];
1301
+ mockPerspective.infer.mockResolvedValue(prologResults);
1302
+ const startTimestamp = new Date("2023-01-02T00:00:00Z").getTime();
1303
+ const endTimestamp = new Date("2023-01-04T00:00:00Z").getTime();
1304
+ const count = await Recipe.count(mockPerspective, { where: { timestamp: { between: [startTimestamp, endTimestamp] } } }, false);
1305
+ expect(mockPerspective.infer).toHaveBeenCalledTimes(1);
1306
+ expect(mockPerspective.querySurrealDB).not.toHaveBeenCalled();
1307
+ expect(count).toBe(3);
1765
1308
  });
1766
1309
  });