@coasys/ad4m 0.13.0-test-4 → 0.13.0-test-6

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 (72) hide show
  1. package/lib/index.cjs +1507 -1372
  2. package/lib/index.js +1505 -1370
  3. package/lib/src/Ad4mClient.d.ts +1 -1
  4. package/lib/src/Ad4mClient.js +12 -1
  5. package/lib/src/agent/AgentClient.d.ts +16 -0
  6. package/lib/src/agent/AgentClient.js +74 -4
  7. package/lib/src/cache/PersistentCache.d.ts +40 -0
  8. package/lib/src/cache/PersistentCache.js +139 -0
  9. package/lib/src/expression/ExpressionClient.d.ts +8 -0
  10. package/lib/src/expression/ExpressionClient.js +113 -5
  11. package/lib/src/index.d.ts +1 -0
  12. package/lib/src/index.js +1 -0
  13. package/lib/src/model/Ad4mModel.d.ts +20 -7
  14. package/lib/src/model/Ad4mModel.js +102 -108
  15. package/lib/src/model/Ad4mModel.test.js +688 -1434
  16. package/lib/src/model/ModelQueryBuilder.d.ts +6 -6
  17. package/lib/src/model/ModelQueryBuilder.js +29 -20
  18. package/lib/src/model/Subject.js +6 -6
  19. package/lib/src/model/hydration.d.ts +2 -39
  20. package/lib/src/model/hydration.js +2 -260
  21. package/lib/src/model/query-surreal.d.ts +44 -0
  22. package/lib/src/model/query-surreal.js +249 -0
  23. package/lib/src/model/query-utils.d.ts +1 -0
  24. package/lib/src/model/query-utils.js +46 -1
  25. package/lib/src/model/relation-filtering.test.js +15 -15
  26. package/lib/src/model/surreal-utils.d.ts +42 -0
  27. package/lib/src/model/surreal-utils.js +128 -0
  28. package/lib/src/model/types.d.ts +4 -6
  29. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  30. package/lib/src/perspectives/PerspectiveClient.js +15 -13
  31. package/lib/src/perspectives/PerspectiveProxy.d.ts +14 -0
  32. package/lib/src/perspectives/PerspectiveProxy.js +16 -3
  33. package/lib/src/perspectives/PerspectiveResolver.d.ts +1 -0
  34. package/lib/src/perspectives/PerspectiveResolver.js +11 -0
  35. package/lib/src/runtime/RuntimeResolver.d.ts +1 -28
  36. package/lib/src/runtime/RuntimeResolver.js +4 -197
  37. package/lib/src/schema.gql +1 -27
  38. package/lib/src/shacl/SHACLShape.test.js +0 -82
  39. package/package.json +11 -8
  40. package/src/Ad4mClient.test.ts +14 -4
  41. package/src/Ad4mClient.ts +12 -1
  42. package/src/agent/AgentClient.ts +84 -2
  43. package/src/cache/PersistentCache.ts +145 -0
  44. package/src/cache/cache.test.ts +713 -0
  45. package/src/expression/ExpressionClient.ts +137 -3
  46. package/src/index.ts +1 -0
  47. package/src/model/Ad4mModel.test.ts +59 -358
  48. package/src/model/Ad4mModel.ts +112 -108
  49. package/src/model/ModelQueryBuilder.ts +29 -17
  50. package/src/model/hydration.ts +2 -279
  51. package/src/model/query-utils.ts +47 -2
  52. package/src/model/types.ts +5 -6
  53. package/src/perspectives/PerspectiveClient.ts +26 -17
  54. package/src/perspectives/PerspectiveProxy.ts +24 -3
  55. package/lib/src/model/hydration-batch.d.ts +0 -34
  56. package/lib/src/model/hydration-batch.js +0 -147
  57. package/lib/src/model/hydration-batching.test.d.ts +0 -7
  58. package/lib/src/model/hydration-batching.test.js +0 -456
  59. package/lib/src/model/model-manifest.d.ts +0 -41
  60. package/lib/src/model/model-manifest.js +0 -11
  61. package/lib/src/model/query-cache.test.d.ts +0 -1
  62. package/lib/src/model/query-cache.test.js +0 -43
  63. package/lib/src/model/query-sparql-batch.d.ts +0 -17
  64. package/lib/src/model/query-sparql-batch.js +0 -260
  65. package/lib/src/model/query-sparql.test.d.ts +0 -1
  66. package/lib/src/model/query-sparql.test.js +0 -312
  67. package/lib/src/model/subscription-delta.test.d.ts +0 -24
  68. package/lib/src/model/subscription-delta.test.js +0 -180
  69. package/lib/src/model/subscription-pool.d.ts +0 -39
  70. package/lib/src/model/subscription-pool.js +0 -165
  71. package/lib/src/perspectives/PerspectiveClient.test.d.ts +0 -1
  72. package/lib/src/perspectives/PerspectiveClient.test.js +0 -224
@@ -0,0 +1,249 @@
1
+ /**
2
+ * SurrealQL query building utilities for Ad4mModel.
3
+ *
4
+ * Contains the graph-traversal WHERE clause builder, legacy
5
+ * subquery-based clause builders, SELECT-field builders, and
6
+ * the main `buildSurrealQLQuery()` function that produces a
7
+ * complete SurrealQL query string from a `Query` object.
8
+ *
9
+ * All functions are stateless — model metadata and relation metadata
10
+ * are passed in as parameters instead of accessed via `this`.
11
+ *
12
+ * @module
13
+ */
14
+ import { escapeSurrealString } from "../utils";
15
+ import { formatSurrealValue } from "./surreal-utils";
16
+ import { resolveParentPredicate } from "./query-common";
17
+ // ─── Graph Traversal WHERE Clause ────────────────────────────────────────────
18
+ /**
19
+ * Builds WHERE clause filters using SurrealDB graph traversal syntax.
20
+ *
21
+ * Translates where conditions into `->link[WHERE ...]` / `<-link[WHERE ...]`
22
+ * filters that SurrealDB can optimize via graph indexes.
23
+ *
24
+ * @param metadata - Model metadata from `getModelMetadata()`
25
+ * @param allRelationsMetadata - Full relation metadata (needed for belongs-to
26
+ * direction detection)
27
+ * @param where - User-supplied where conditions
28
+ * @returns Combined AND-joined condition string, or empty string
29
+ */
30
+ export function buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where) {
31
+ if (!where)
32
+ return '';
33
+ const conditions = [];
34
+ for (const [propertyName, condition] of Object.entries(where)) {
35
+ const isSpecial = ['id', 'author', 'timestamp'].includes(propertyName);
36
+ if (isSpecial) {
37
+ if (propertyName === 'author' || propertyName === 'timestamp') {
38
+ continue; // Filtered post-query in JS
39
+ }
40
+ const columnName = 'uri';
41
+ if (Array.isArray(condition)) {
42
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
43
+ conditions.push(`${columnName} IN [${formattedValues}]`);
44
+ }
45
+ else if (typeof condition === 'object' && condition !== null) {
46
+ const ops = condition;
47
+ if (ops.not !== undefined) {
48
+ if (Array.isArray(ops.not)) {
49
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
50
+ conditions.push(`${columnName} NOT IN [${formattedValues}]`);
51
+ }
52
+ else {
53
+ conditions.push(`${columnName} != ${formatSurrealValue(ops.not)}`);
54
+ }
55
+ }
56
+ if (ops.between !== undefined && Array.isArray(ops.between) && ops.between.length === 2) {
57
+ conditions.push(`${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`);
58
+ }
59
+ if (ops.gt !== undefined) {
60
+ conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
61
+ }
62
+ if (ops.gte !== undefined) {
63
+ conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
64
+ }
65
+ if (ops.lt !== undefined) {
66
+ conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
67
+ }
68
+ if (ops.lte !== undefined) {
69
+ conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
70
+ }
71
+ if (ops.contains !== undefined) {
72
+ conditions.push(`${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`);
73
+ }
74
+ }
75
+ else {
76
+ conditions.push(`${columnName} = ${formatSurrealValue(condition)}`);
77
+ }
78
+ }
79
+ else {
80
+ // Regular properties — check relation metadata first for direction
81
+ const relMeta = allRelationsMetadata[propertyName];
82
+ const isBelongs = relMeta?.kind === 'belongsToOne' || relMeta?.kind === 'belongsToMany';
83
+ if (relMeta) {
84
+ const predicate = escapeSurrealString(relMeta.predicate);
85
+ if (Array.isArray(condition)) {
86
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
87
+ if (isBelongs) {
88
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) > 0`);
89
+ }
90
+ else {
91
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) > 0`);
92
+ }
93
+ }
94
+ else if (typeof condition === 'object' && condition !== null) {
95
+ const ops = condition;
96
+ if (ops.not !== undefined) {
97
+ if (Array.isArray(ops.not)) {
98
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
99
+ if (isBelongs) {
100
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri IN [${formattedValues}]]) = 0`);
101
+ }
102
+ else {
103
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri IN [${formattedValues}]]) = 0`);
104
+ }
105
+ }
106
+ else {
107
+ if (isBelongs) {
108
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(ops.not)}]) = 0`);
109
+ }
110
+ else {
111
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(ops.not)}]) = 0`);
112
+ }
113
+ }
114
+ }
115
+ }
116
+ else {
117
+ if (isBelongs) {
118
+ conditions.push(`count(<-link[WHERE predicate = '${predicate}' AND in.uri = ${formatSurrealValue(condition)}]) > 0`);
119
+ }
120
+ else {
121
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND out.uri = ${formatSurrealValue(condition)}]) > 0`);
122
+ }
123
+ }
124
+ continue;
125
+ }
126
+ const propMeta = metadata.properties[propertyName];
127
+ if (!propMeta)
128
+ continue;
129
+ const predicate = escapeSurrealString(propMeta.predicate);
130
+ const targetField = propMeta.resolveLanguage === 'literal' ? 'fn::parse_literal(out.uri)' : 'out.uri';
131
+ if (Array.isArray(condition)) {
132
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
133
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
134
+ }
135
+ else if (typeof condition === 'object' && condition !== null) {
136
+ const ops = condition;
137
+ if (ops.not !== undefined) {
138
+ if (Array.isArray(ops.not)) {
139
+ const formattedValues = ops.not.map(v => formatSurrealValue(v)).join(', ');
140
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
141
+ }
142
+ else {
143
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
144
+ }
145
+ }
146
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
147
+ ops.lt !== undefined || ops.lte !== undefined ||
148
+ ops.between !== undefined || ops.contains !== undefined;
149
+ if (hasComparisonOps) {
150
+ conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
151
+ }
152
+ }
153
+ else {
154
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`);
155
+ }
156
+ }
157
+ }
158
+ return conditions.join(' AND ');
159
+ }
160
+ // ─── Main Query Builder ─────────────────────────────────────────────────────
161
+ /**
162
+ * Builds a complete SurrealQL query from a Query object and model metadata.
163
+ *
164
+ * This is the core implementation behind `Ad4mModel.queryToSurrealQL()`.
165
+ * It produces a graph-traversal query that:
166
+ * 1. Filters nodes by required predicates (conformance check)
167
+ * 2. Applies user WHERE conditions
168
+ * 3. Fetches all outgoing links for hydration
169
+ *
170
+ * @param metadata - Model metadata from `getModelMetadata()`
171
+ * @param allRelationsMetadata - Full relation registry (for belongs-to detection)
172
+ * @param query - Query parameters
173
+ * @param modelClass - The model class (for `resolveParentPredicate`)
174
+ * @returns Complete SurrealQL query string
175
+ */
176
+ export function buildSurrealQLQuery(metadata, allRelationsMetadata, query, modelClass) {
177
+ const { where } = query;
178
+ // Build graph traversal filters for required predicates
179
+ const graphTraversalFilters = [];
180
+ // Parent filter
181
+ if (query.parent) {
182
+ const parentPredicate = resolveParentPredicate(query.parent, modelClass);
183
+ graphTraversalFilters.push(`count(<-link[WHERE in.uri = ${formatSurrealValue(query.parent.id)} AND predicate = '${escapeSurrealString(parentPredicate)}']) > 0`);
184
+ }
185
+ // Required property filters
186
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
187
+ if (propMeta.required) {
188
+ if (propMeta.getter)
189
+ continue;
190
+ if (propMeta.flag && propMeta.initial) {
191
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
192
+ }
193
+ else {
194
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
195
+ }
196
+ }
197
+ }
198
+ // Fallback: initial-value filters
199
+ if (graphTraversalFilters.length === 0) {
200
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
201
+ if (propMeta.initial) {
202
+ if (propMeta.flag) {
203
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
204
+ }
205
+ else {
206
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
207
+ }
208
+ break;
209
+ }
210
+ }
211
+ }
212
+ // Fallback: open-world structural matching
213
+ if (graphTraversalFilters.length === 0) {
214
+ const structuralPredicates = [];
215
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
216
+ if (propMeta.predicate) {
217
+ structuralPredicates.push(`predicate = '${escapeSurrealString(propMeta.predicate)}'`);
218
+ }
219
+ }
220
+ if (metadata.relations) {
221
+ for (const [, relMeta] of Object.entries(metadata.relations)) {
222
+ if (relMeta.predicate) {
223
+ structuralPredicates.push(`predicate = '${escapeSurrealString(relMeta.predicate)}'`);
224
+ }
225
+ }
226
+ }
227
+ if (structuralPredicates.length > 0) {
228
+ graphTraversalFilters.push(`count(->link[WHERE (${structuralPredicates.join(' OR ')})]) > 0`);
229
+ }
230
+ }
231
+ // User WHERE clause
232
+ const userWhereClause = buildGraphTraversalWhereClause(metadata, allRelationsMetadata, where);
233
+ const whereConditions = [];
234
+ whereConditions.push(...graphTraversalFilters);
235
+ if (userWhereClause) {
236
+ whereConditions.push(userWhereClause);
237
+ }
238
+ whereConditions.push(`count(->link) > 0`);
239
+ const fullQuery = `
240
+ SELECT
241
+ id AS source,
242
+ uri AS source_uri,
243
+ ->link AS links
244
+ FROM node
245
+ WHERE ${whereConditions.join(' AND ')}
246
+ FETCH links
247
+ `.trim();
248
+ return fullQuery;
249
+ }
@@ -30,6 +30,7 @@ export declare function formatQueryValue(value: any): string;
30
30
  */
31
31
  export declare function buildWhereCondition(predicate: string, condition: WhereCondition, opts?: {
32
32
  resolveLanguage?: string;
33
+ varIndex?: number;
33
34
  }): string;
34
35
  /**
35
36
  * Compile a full `Where` clause to an array of SPARQL condition strings.
@@ -56,6 +56,7 @@ export function buildWhereCondition(predicate, condition, opts) {
56
56
  // For literal-resolved properties, values are stored as IRIs like <literal:string:VALUE>
57
57
  // For language-resolved properties, values are plain URIs
58
58
  const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
59
+ const varSuffix = opts?.varIndex ?? 0;
59
60
  function formatValue(v) {
60
61
  if (typeof v === 'string') {
61
62
  return isLiteral
@@ -65,8 +66,46 @@ export function buildWhereCondition(predicate, condition, opts) {
65
66
  // Numbers/booleans — also stored as literal:string: in AD4M
66
67
  return `<literal:string:${v}>`;
67
68
  }
69
+ /**
70
+ * For literal properties, generate a FILTER-based match that handles both
71
+ * the raw value and the literal-encoded value. This mirrors the Rust
72
+ * `build_projection_where_patterns` approach which uses:
73
+ * FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
74
+ * This is more robust than exact IRI matching because it handles edge cases
75
+ * where the stored format might vary.
76
+ */
77
+ function formatLiteralFilter(varName, v) {
78
+ const raw = escapeQueryString(String(v));
79
+ const encoded = encodeURIComponent(String(v))
80
+ .replace(/!/g, '%21')
81
+ .replace(/'/g, '%27')
82
+ .replace(/\(/g, '%28')
83
+ .replace(/\)/g, '%29')
84
+ .replace(/\*/g, '%2A');
85
+ if (typeof v === 'string') {
86
+ return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
87
+ }
88
+ else if (typeof v === 'number') {
89
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
90
+ }
91
+ else if (typeof v === 'boolean') {
92
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
93
+ }
94
+ return `FILTER(STR(${varName}) = "${raw}")`;
95
+ }
68
96
  if (Array.isArray(condition)) {
69
97
  // Array values → FILTER IN
98
+ if (isLiteral) {
99
+ const varName = `?_wc${varSuffix}`;
100
+ const inValues = condition.flatMap(v => {
101
+ const raw = escapeQueryString(String(v));
102
+ const encoded = encodeURIComponent(String(v))
103
+ .replace(/!/g, '%21').replace(/'/g, '%27')
104
+ .replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
105
+ return [`"${raw}"`, `"literal:string:${encoded}"`];
106
+ }).join(', ');
107
+ return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
108
+ }
70
109
  const formattedValues = condition.map(formatValue).join(', ');
71
110
  return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
72
111
  }
@@ -98,6 +137,12 @@ export function buildWhereCondition(predicate, condition, opts) {
98
137
  }
99
138
  else {
100
139
  // Simple equality
140
+ if (isLiteral) {
141
+ // Use FILTER matching (mirrors Rust build_projection_where_patterns)
142
+ // to handle both raw values and literal-encoded IRIs robustly.
143
+ const varName = `?_wc${varSuffix}`;
144
+ return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
145
+ }
101
146
  return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
102
147
  }
103
148
  }
@@ -135,7 +180,7 @@ export function compileWhereClause(where, metadata) {
135
180
  // No metadata — treat name as raw predicate URI
136
181
  predicate = propertyName;
137
182
  }
138
- const cond = buildWhereCondition(predicate, condition, { resolveLanguage });
183
+ const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
139
184
  if (cond) {
140
185
  conditions.push(cond);
141
186
  }
@@ -20,7 +20,7 @@ var __metadata = (this && this.__metadata) || function (k, v) {
20
20
  import { Ad4mModel } from "./Ad4mModel";
21
21
  import { Model, Property, Flag, HasMany, Optional, buildConformanceFilter, } from "./decorators";
22
22
  import { SHACLShape, } from "../shacl/SHACLShape";
23
- import { compileWhereClause } from "./query-utils";
23
+ import { compileWhereClause } from "./surreal-utils";
24
24
  // ============================================================================
25
25
  // Test models
26
26
  // ============================================================================
@@ -88,7 +88,7 @@ __decorate([
88
88
  ], ParentWithRelations.prototype, "unfilteredItems", void 0);
89
89
  __decorate([
90
90
  HasMany({
91
- getter: "SELECT ?target WHERE { ?target <test://custom> ?source . }",
91
+ getter: "(<-link[WHERE predicate = 'test://custom'].in.uri)",
92
92
  }),
93
93
  __metadata("design:type", Array)
94
94
  ], ParentWithRelations.prototype, "customItems", void 0);
@@ -113,8 +113,8 @@ describe("buildConformanceFilter()", () => {
113
113
  expect(reqCond).toBeDefined();
114
114
  expect(reqCond.predicate).toBe("test://name");
115
115
  expect(reqCond.value).toBeUndefined();
116
- // Getter string should be a SPARQL expression
117
- expect(result.getter).toContain("SELECT ?target WHERE");
116
+ // Getter string should be a SurrealQL expression
117
+ expect(result.getter).toContain("->link[WHERE predicate =");
118
118
  expect(result.getter).toContain("test://has_flagged");
119
119
  expect(result.getter).toContain("test://type");
120
120
  expect(result.getter).toContain("test://flagged_type");
@@ -161,7 +161,7 @@ describe("buildConformanceFilter()", () => {
161
161
  Property({
162
162
  through: "test://computed",
163
163
  required: true,
164
- getter: "SELECT ?target WHERE { ?target <test://custom> ?source . } LIMIT 1",
164
+ getter: "(<-link[WHERE predicate = 'test://custom'].in.uri)[0]",
165
165
  }),
166
166
  __metadata("design:type", String)
167
167
  ], CustomGetterTarget.prototype, "computed", void 0);
@@ -179,7 +179,7 @@ describe("buildConformanceFilter()", () => {
179
179
  // SHACL serialization round-trip tests
180
180
  // ============================================================================
181
181
  describe("SHACL shape getter serialization", () => {
182
- const testGetter = "SELECT ?target WHERE { <Base> <test://pred> ?target . ?target <test://type> <test://flag> . }";
182
+ const testGetter = "(->link[WHERE predicate = 'test://pred'].out[WHERE count(->link[WHERE predicate = 'test://type' AND out.uri = 'test://flag']) > 0].uri)";
183
183
  const testConditions = [
184
184
  { type: "flag", predicate: "test://type", value: "test://flag" },
185
185
  { type: "required", predicate: "test://name" },
@@ -198,7 +198,7 @@ describe("SHACL shape getter serialization", () => {
198
198
  // Verify getter link exists
199
199
  const getterLink = links.find(l => l.predicate === "ad4m://getter");
200
200
  expect(getterLink).toBeDefined();
201
- expect(getterLink.target).toBe(`literal:string:${testGetter}`);
201
+ expect(getterLink.target).toBe(`literal://string:${testGetter}`);
202
202
  // Verify conditions link exists
203
203
  const conditionsLink = links.find(l => l.predicate === "ad4m://conformanceConditions");
204
204
  expect(conditionsLink).toBeDefined();
@@ -321,7 +321,7 @@ describe("Ad4mModel.getModelMetadata() relation filtering fields", () => {
321
321
  it("should expose explicit getter on relations with custom getter", () => {
322
322
  const metadata = ParentWithRelations.getModelMetadata();
323
323
  // Explicit getter provided via decorator (getter-only, no predicate)
324
- expect(metadata.relations.customItems.getter).toBe("SELECT ?target WHERE { ?target <test://custom> ?source . }");
324
+ expect(metadata.relations.customItems.getter).toBe("(<-link[WHERE predicate = 'test://custom'].in.uri)");
325
325
  expect(metadata.relations.customItems.predicate).toBe("");
326
326
  // Auto-generated getter is NOT in decorator metadata (it's in the SHACL shape)
327
327
  expect(metadata.relations.flaggedItems.getter).toBeUndefined();
@@ -364,7 +364,7 @@ describe("Relation decorator validation", () => {
364
364
  };
365
365
  __decorate([
366
366
  HasMany({
367
- getter: "SELECT ?target WHERE { ?target ?p ?source . }",
367
+ getter: "(<-link.in.uri)",
368
368
  target: () => FlaggedTarget,
369
369
  }),
370
370
  __metadata("design:type", Array)
@@ -384,7 +384,7 @@ describe("Relation decorator validation", () => {
384
384
  };
385
385
  __decorate([
386
386
  HasMany({
387
- getter: "SELECT ?target WHERE { ?target ?p ?source . }",
387
+ getter: "(<-link.in.uri)",
388
388
  through: "test://pred",
389
389
  }),
390
390
  __metadata("design:type", Array)
@@ -404,7 +404,7 @@ describe("Relation decorator validation", () => {
404
404
  };
405
405
  __decorate([
406
406
  HasMany({
407
- getter: "SELECT ?target WHERE { ?target ?p ?source . }",
407
+ getter: "(<-link.in.uri)",
408
408
  }),
409
409
  __metadata("design:type", Array)
410
410
  ], _Valid.prototype, "items", void 0);
@@ -541,7 +541,7 @@ describe("where clause validation", () => {
541
541
  __decorate([
542
542
  HasMany({
543
543
  where: { status: "active" },
544
- getter: "SELECT ?target WHERE { ?target ?p ?source . }",
544
+ getter: "(<-link.in.uri)",
545
545
  }),
546
546
  __metadata("design:type", Array)
547
547
  ], _Invalid.prototype, "items", void 0);
@@ -573,7 +573,7 @@ describe("where clause validation", () => {
573
573
  });
574
574
  });
575
575
  describe("where clause compilation", () => {
576
- it("should compile where clause to SPARQL getter", () => {
576
+ it("should compile where clause to SurrealQL getter", () => {
577
577
  let WhereTarget = class WhereTarget extends Ad4mModel {
578
578
  constructor() {
579
579
  super(...arguments);
@@ -810,7 +810,7 @@ describe("where clause compilation", () => {
810
810
  // compileWhereClause() unit tests
811
811
  // ============================================================================
812
812
  describe("compileWhereClause()", () => {
813
- it("should compile simple equality to SPARQL condition", () => {
813
+ it("should compile simple equality to SurrealQL condition", () => {
814
814
  const conditions = compileWhereClause({ status: "active" }, { properties: { status: { name: "status", predicate: "test://status", required: false, readOnly: false } }, relations: {}, className: "Test" });
815
815
  expect(conditions).toHaveLength(1);
816
816
  expect(conditions[0]).toContain("test://status");
@@ -819,7 +819,7 @@ describe("compileWhereClause()", () => {
819
819
  it("should compile not operator", () => {
820
820
  const conditions = compileWhereClause({ status: { not: "archived" } }, { properties: { status: { name: "status", predicate: "test://status", required: false, readOnly: false } }, relations: {}, className: "Test" });
821
821
  expect(conditions).toHaveLength(1);
822
- expect(conditions[0]).toContain("NOT EXISTS"); // negation
822
+ expect(conditions[0]).toContain("= 0"); // negation
823
823
  expect(conditions[0]).toContain("archived");
824
824
  });
825
825
  it("should compile array values to IN clause", () => {
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Shared SurrealQL compilation utilities.
3
+ *
4
+ * These functions are used by both the runtime query builder (`Ad4mModel`) and
5
+ * the compile-time SHACL generator (`decorators.ts`).
6
+ */
7
+ import type { WhereCondition, Where, ModelMetadata } from "./types";
8
+ /**
9
+ * Format a JavaScript value for embedding in a SurrealQL expression.
10
+ *
11
+ * - Strings are single-quoted with backslash / quote / newline escaping
12
+ * - Numbers and booleans are passed through as-is
13
+ * - Arrays are recursed
14
+ */
15
+ export declare function formatSurrealValue(value: any): string;
16
+ /**
17
+ * Compile a single Where condition for a property into a SurrealQL
18
+ * graph-traversal sub-expression.
19
+ *
20
+ * Operates on the **target node** — generates `count(->link[WHERE ...]) > 0`
21
+ * style checks that can be used inside a `[WHERE ...]` filter on nodes.
22
+ *
23
+ * @param predicate - The predicate URI for the property
24
+ * @param condition - The Where condition value
25
+ * @param opts - Optional settings (e.g. `resolveLanguage`)
26
+ * @returns A single SurrealQL condition string
27
+ */
28
+ export declare function buildWhereCondition(predicate: string, condition: WhereCondition, opts?: {
29
+ resolveLanguage?: string;
30
+ }): string;
31
+ /**
32
+ * Compile a full `Where` clause to an array of SurrealQL condition strings.
33
+ *
34
+ * When `metadata` is provided, property names are resolved to predicates
35
+ * using the model's property metadata. When `metadata` is `null`, property
36
+ * names are treated as raw predicate URIs.
37
+ *
38
+ * Only handles **regular properties** — special fields (`id`, `author`,
39
+ * `timestamp`) and relation fields are skipped (they are only relevant at
40
+ * runtime query time, not for compile-time getter generation).
41
+ */
42
+ export declare function compileWhereClause(where: Where, metadata: ModelMetadata | null): string[];
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Shared SurrealQL compilation utilities.
3
+ *
4
+ * These functions are used by both the runtime query builder (`Ad4mModel`) and
5
+ * the compile-time SHACL generator (`decorators.ts`).
6
+ */
7
+ import { escapeSurrealString } from "../utils";
8
+ /**
9
+ * Format a JavaScript value for embedding in a SurrealQL expression.
10
+ *
11
+ * - Strings are single-quoted with backslash / quote / newline escaping
12
+ * - Numbers and booleans are passed through as-is
13
+ * - Arrays are recursed
14
+ */
15
+ export function formatSurrealValue(value) {
16
+ if (typeof value === 'string') {
17
+ // Escape backslashes first, then single quotes and other special characters
18
+ const escaped = value
19
+ .replace(/\\/g, '\\\\') // Backslash -> \\
20
+ .replace(/'/g, "\\'") // Single quote -> \'
21
+ .replace(/"/g, '\\"') // Double quote -> \"
22
+ .replace(/\n/g, '\\n') // Newline -> \n
23
+ .replace(/\r/g, '\\r') // Carriage return -> \r
24
+ .replace(/\t/g, '\\t'); // Tab -> \t
25
+ return `'${escaped}'`;
26
+ }
27
+ else if (typeof value === 'number' || typeof value === 'boolean') {
28
+ return String(value);
29
+ }
30
+ else if (Array.isArray(value)) {
31
+ return `[${value.map(v => formatSurrealValue(v)).join(', ')}]`;
32
+ }
33
+ else {
34
+ return String(value);
35
+ }
36
+ }
37
+ /**
38
+ * Compile a single Where condition for a property into a SurrealQL
39
+ * graph-traversal sub-expression.
40
+ *
41
+ * Operates on the **target node** — generates `count(->link[WHERE ...]) > 0`
42
+ * style checks that can be used inside a `[WHERE ...]` filter on nodes.
43
+ *
44
+ * @param predicate - The predicate URI for the property
45
+ * @param condition - The Where condition value
46
+ * @param opts - Optional settings (e.g. `resolveLanguage`)
47
+ * @returns A single SurrealQL condition string
48
+ */
49
+ export function buildWhereCondition(predicate, condition, opts) {
50
+ const escapedPredicate = escapeSurrealString(predicate);
51
+ const targetField = opts?.resolveLanguage === 'literal'
52
+ ? 'fn::parse_literal(out.uri)'
53
+ : 'out.uri';
54
+ if (Array.isArray(condition)) {
55
+ // Array values → IN clause
56
+ const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
57
+ return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) > 0`;
58
+ }
59
+ else if (typeof condition === 'object' && condition !== null) {
60
+ // Operator object
61
+ const ops = condition;
62
+ const parts = [];
63
+ if (ops.not !== undefined) {
64
+ if (Array.isArray(ops.not)) {
65
+ const formattedValues = ops.not.map((v) => formatSurrealValue(v)).join(', ');
66
+ parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
67
+ }
68
+ else {
69
+ parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
70
+ }
71
+ }
72
+ // Comparison operators — ensure property exists (actual comparison
73
+ // may be post-filtered in JS at runtime, but the SurrealQL condition
74
+ // is valid for compile-time getter generation too).
75
+ const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
76
+ ops.lt !== undefined || ops.lte !== undefined ||
77
+ ops.between !== undefined || ops.contains !== undefined;
78
+ if (hasComparisonOps) {
79
+ parts.push(`count(->link[WHERE predicate = '${escapedPredicate}']) > 0`);
80
+ }
81
+ return parts.join(' AND ');
82
+ }
83
+ else {
84
+ // Simple equality
85
+ return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`;
86
+ }
87
+ }
88
+ /**
89
+ * Compile a full `Where` clause to an array of SurrealQL condition strings.
90
+ *
91
+ * When `metadata` is provided, property names are resolved to predicates
92
+ * using the model's property metadata. When `metadata` is `null`, property
93
+ * names are treated as raw predicate URIs.
94
+ *
95
+ * Only handles **regular properties** — special fields (`id`, `author`,
96
+ * `timestamp`) and relation fields are skipped (they are only relevant at
97
+ * runtime query time, not for compile-time getter generation).
98
+ */
99
+ export function compileWhereClause(where, metadata) {
100
+ const conditions = [];
101
+ for (const [propertyName, condition] of Object.entries(where)) {
102
+ // Skip special fields that don't apply at compile time
103
+ if (['id', 'author', 'timestamp'].includes(propertyName))
104
+ continue;
105
+ let predicate;
106
+ let resolveLanguage;
107
+ if (metadata) {
108
+ const propMeta = metadata.properties[propertyName];
109
+ if (propMeta) {
110
+ predicate = propMeta.predicate;
111
+ resolveLanguage = propMeta.resolveLanguage;
112
+ }
113
+ else {
114
+ // Property not found in metadata — treat name as raw predicate URI
115
+ predicate = propertyName;
116
+ }
117
+ }
118
+ else {
119
+ // No metadata — treat name as raw predicate URI
120
+ predicate = propertyName;
121
+ }
122
+ const cond = buildWhereCondition(predicate, condition, { resolveLanguage });
123
+ if (cond) {
124
+ conditions.push(cond);
125
+ }
126
+ }
127
+ return conditions;
128
+ }
@@ -122,12 +122,11 @@ export type Query = {
122
122
  count?: boolean;
123
123
  /**
124
124
  * When true, SPARQL property getters (@Property with `getter`) ARE evaluated
125
- * during collection hydration. By default, collection queries skip getter
126
- * evaluation for performance — getters run only on single-instance get().
125
+ * during collection hydration. Defaults to true — getters run post-pagination
126
+ * via batched VALUES queries so the cost is O(getters), not O(instances × getters).
127
127
  *
128
- * Use this when you need getter-backed properties (e.g. `replyingTo`,
129
- * `isPopular`) in a list query. For most list/feed UIs, leave this off
130
- * and use `Ad4mModel.evaluateGetters()` on visible items only.
128
+ * Set to false to explicitly skip getter evaluation for performance-sensitive
129
+ * queries where getter-backed properties are not needed.
131
130
  */
132
131
  deepQuery?: boolean;
133
132
  };
@@ -152,7 +151,6 @@ export type GetOptions = Pick<Query, 'include' | 'properties'>;
152
151
  export type AllInstancesResult = {
153
152
  AllInstances: Ad4mModel[];
154
153
  TotalCount?: number;
155
- isInit?: boolean;
156
154
  };
157
155
  export type ResultsWithTotalCount<T> = {
158
156
  results: T[];