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

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.
@@ -53,7 +53,7 @@ export function formatQueryValue(value: any): string {
53
53
  export function buildWhereCondition(
54
54
  predicate: string,
55
55
  condition: WhereCondition,
56
- opts?: { resolveLanguage?: string },
56
+ opts?: { resolveLanguage?: string; varIndex?: number },
57
57
  ): string {
58
58
  const escapedPredicate = escapeQueryString(predicate);
59
59
  // For literal-resolved properties, we match against the raw IRI (which is a literal: URI)
@@ -62,6 +62,8 @@ export function buildWhereCondition(
62
62
  // For language-resolved properties, values are plain URIs
63
63
  const isLiteral = !opts?.resolveLanguage || opts.resolveLanguage === 'literal';
64
64
 
65
+ const varSuffix = opts?.varIndex ?? 0;
66
+
65
67
  function formatValue(v: any): string {
66
68
  if (typeof v === 'string') {
67
69
  return isLiteral
@@ -72,8 +74,45 @@ export function buildWhereCondition(
72
74
  return `<literal:string:${v}>`;
73
75
  }
74
76
 
77
+ /**
78
+ * For literal properties, generate a FILTER-based match that handles both
79
+ * the raw value and the literal-encoded value. This mirrors the Rust
80
+ * `build_projection_where_patterns` approach which uses:
81
+ * FILTER(STR(?var) = "value" || STR(?var) = "literal:string:encodedValue")
82
+ * This is more robust than exact IRI matching because it handles edge cases
83
+ * where the stored format might vary.
84
+ */
85
+ function formatLiteralFilter(varName: string, v: any): string {
86
+ const raw = escapeQueryString(String(v));
87
+ const encoded = encodeURIComponent(String(v))
88
+ .replace(/!/g, '%21')
89
+ .replace(/'/g, '%27')
90
+ .replace(/\(/g, '%28')
91
+ .replace(/\)/g, '%29')
92
+ .replace(/\*/g, '%2A');
93
+ if (typeof v === 'string') {
94
+ return `FILTER(STR(${varName}) = "${raw}" || STR(${varName}) = "literal:string:${encoded}")`;
95
+ } else if (typeof v === 'number') {
96
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:number:${v}")`;
97
+ } else if (typeof v === 'boolean') {
98
+ return `FILTER(STR(${varName}) = "${v}" || STR(${varName}) = "literal:boolean:${v}")`;
99
+ }
100
+ return `FILTER(STR(${varName}) = "${raw}")`;
101
+ }
102
+
75
103
  if (Array.isArray(condition)) {
76
104
  // Array values → FILTER IN
105
+ if (isLiteral) {
106
+ const varName = `?_wc${varSuffix}`;
107
+ const inValues = (condition as any[]).flatMap(v => {
108
+ const raw = escapeQueryString(String(v));
109
+ const encoded = encodeURIComponent(String(v))
110
+ .replace(/!/g, '%21').replace(/'/g, '%27')
111
+ .replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
112
+ return [`"${raw}"`, `"literal:string:${encoded}"`];
113
+ }).join(', ');
114
+ return `?target <${escapedPredicate}> ${varName} . FILTER(STR(${varName}) IN (${inValues}))`;
115
+ }
77
116
  const formattedValues = (condition as any[]).map(formatValue).join(', ');
78
117
  return `FILTER EXISTS { ?target <${escapedPredicate}> ?_val . FILTER(?_val IN (${formattedValues})) }`;
79
118
  } else if (typeof condition === 'object' && condition !== null) {
@@ -112,6 +151,12 @@ export function buildWhereCondition(
112
151
  return parts.join(' ');
113
152
  } else {
114
153
  // Simple equality
154
+ if (isLiteral) {
155
+ // Use FILTER matching (mirrors Rust build_projection_where_patterns)
156
+ // to handle both raw values and literal-encoded IRIs robustly.
157
+ const varName = `?_wc${varSuffix}`;
158
+ return `?target <${escapedPredicate}> ${varName} . ${formatLiteralFilter(varName, condition)}`;
159
+ }
115
160
  return `?target <${escapedPredicate}> ${formatValue(condition)} .`;
116
161
  }
117
162
  }
@@ -154,7 +199,7 @@ export function compileWhereClause(
154
199
  predicate = propertyName;
155
200
  }
156
201
 
157
- const cond = buildWhereCondition(predicate, condition, { resolveLanguage });
202
+ const cond = buildWhereCondition(predicate, condition, { resolveLanguage, varIndex: conditions.length });
158
203
  if (cond) {
159
204
  conditions.push(cond);
160
205
  }
@@ -127,12 +127,11 @@ export type Query = {
127
127
  count?: boolean;
128
128
  /**
129
129
  * When true, SPARQL property getters (@Property with `getter`) ARE evaluated
130
- * during collection hydration. By default, collection queries skip getter
131
- * evaluation for performance — getters run only on single-instance get().
130
+ * during collection hydration. Defaults to true — getters run post-pagination
131
+ * via batched VALUES queries so the cost is O(getters), not O(instances × getters).
132
132
  *
133
- * Use this when you need getter-backed properties (e.g. `replyingTo`,
134
- * `isPopular`) in a list query. For most list/feed UIs, leave this off
135
- * and use `Ad4mModel.evaluateGetters()` on visible items only.
133
+ * Set to false to explicitly skip getter evaluation for performance-sensitive
134
+ * queries where getter-backed properties are not needed.
136
135
  */
137
136
  deepQuery?: boolean;
138
137
  };
@@ -193,6 +193,25 @@ export class PerspectiveClient {
193
193
  return JSON.parse(resultJson)
194
194
  }
195
195
 
196
+ async evaluateGetters(
197
+ uuid: string,
198
+ className: string,
199
+ instanceIds: string[],
200
+ shapeJson: string,
201
+ propertyNames?: string[],
202
+ ): Promise<Record<string, Record<string, any>>> {
203
+ const resultJson = await this.#apiClient.call<string>(
204
+ 'perspective.evaluateGetters', {
205
+ uuid,
206
+ class_name: className,
207
+ instance_ids: instanceIds,
208
+ shape_json: shapeJson,
209
+ ...(propertyNames && { property_names: propertyNames }),
210
+ }
211
+ )
212
+ return JSON.parse(resultJson)
213
+ }
214
+
196
215
  async modelSubscribe(uuid: string, className: string, queryJson: string, shapeJson?: string): Promise<{ subscriptionId: string, result: any }> {
197
216
  const response = await this.#apiClient.call<{ subscription_id: string, result: string }>(
198
217
  'perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson, shape_json: shapeJson }
@@ -612,6 +612,30 @@ export class PerspectiveProxy {
612
612
  return await this.#client.modelQuery(this.#handle.uuid, className, queryJson, shapeJson);
613
613
  }
614
614
 
615
+ /**
616
+ * Evaluate property getters for a batch of instances in a single RPC call.
617
+ * Returns a map of `{ instanceId: { prop: value, ... } }`.
618
+ *
619
+ * Use this instead of `Ad4mModel.evaluateGetters()` for lazy-loading
620
+ * getter-backed properties on visible items (e.g. `replyingTo` on messages).
621
+ *
622
+ * @param className - The model class name (e.g. "Message")
623
+ * @param instanceIds - Array of instance base expression URIs
624
+ * @param shapeJson - Shape metadata JSON from the model class
625
+ * @param propertyNames - Optional subset of property names to evaluate
626
+ * @returns Map of instance ID → evaluated property values
627
+ */
628
+ async evaluateGetters(
629
+ className: string,
630
+ instanceIds: string[],
631
+ shapeJson: string,
632
+ propertyNames?: string[],
633
+ ): Promise<Record<string, Record<string, any>>> {
634
+ return await this.#client.evaluateGetters(
635
+ this.#handle.uuid, className, instanceIds, shapeJson, propertyNames,
636
+ );
637
+ }
638
+
615
639
  /**
616
640
  * Subscribe to model query changes. Builds trigger SPARQL from the model shape
617
641
  * internally in Rust, registers a subscription, runs the initial query, and