@coasys/ad4m 0.13.0-postmessage-ws-proxy.3 → 0.13.0-postmessage-ws-proxy.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.
Files changed (39) hide show
  1. package/lib/index.cjs +214 -145
  2. package/lib/index.js +205 -146
  3. package/lib/src/Ad4mClient.d.ts +1 -0
  4. package/lib/src/Ad4mClient.js +1 -1
  5. package/lib/src/ai/AIClient.js +1 -1
  6. package/lib/src/apiClient.d.ts +4 -1
  7. package/lib/src/apiClient.js +6 -1
  8. package/lib/src/index.d.ts +3 -0
  9. package/lib/src/index.js +3 -0
  10. package/lib/src/model/Ad4mModel.d.ts +0 -15
  11. package/lib/src/model/Ad4mModel.js +2 -118
  12. package/lib/src/model/ModelQueryBuilder.js +12 -22
  13. package/lib/src/model/decorators.d.ts +7 -4
  14. package/lib/src/model/shacl-gen.js +5 -1
  15. package/lib/src/model/types.d.ts +2 -1
  16. package/lib/src/shacl/NodeExpression.d.ts +44 -0
  17. package/lib/src/shacl/NodeExpression.js +39 -0
  18. package/lib/src/shacl/SHACLShape.d.ts +5 -0
  19. package/lib/src/shacl/SHACLShape.js +32 -1
  20. package/lib/src/shacl/builders.d.ts +58 -0
  21. package/lib/src/shacl/builders.js +76 -0
  22. package/lib/src/shacl/index.d.ts +36 -0
  23. package/lib/src/shacl/index.js +33 -0
  24. package/package.json +1 -1
  25. package/src/Ad4mClient.ts +2 -2
  26. package/src/ai/AIClient.ts +1 -1
  27. package/src/apiClient.ts +8 -1
  28. package/src/index.ts +3 -0
  29. package/src/model/Ad4mModel.test.ts +10 -10
  30. package/src/model/Ad4mModel.ts +2 -113
  31. package/src/model/ModelQueryBuilder.ts +12 -23
  32. package/src/model/decorators.ts +7 -4
  33. package/src/model/shacl-gen.ts +6 -1
  34. package/src/model/types.ts +2 -1
  35. package/src/shacl/NodeExpression.ts +54 -0
  36. package/src/shacl/SHACLShape.test.ts +62 -0
  37. package/src/shacl/SHACLShape.ts +48 -1
  38. package/src/shacl/builders.ts +86 -0
  39. package/src/shacl/index.ts +72 -0
package/lib/index.js CHANGED
@@ -19,7 +19,7 @@ function nextId() {
19
19
  return String(++_idCounter);
20
20
  }
21
21
  class ApiClient {
22
- constructor(baseUrl, token, webSocketImpl) {
22
+ constructor(baseUrl, token, webSocketImpl, fetchImpl) {
23
23
  // ── WebSocket RPC core ──────────────────────────────────────────────────
24
24
  this._ws = null;
25
25
  this._wsCallbacks = new Set();
@@ -33,9 +33,14 @@ class ApiClient {
33
33
  this.baseUrl = baseUrl;
34
34
  this.token = token;
35
35
  this._webSocketImpl = webSocketImpl;
36
+ this._fetchImpl = fetchImpl;
36
37
  }
37
38
  getBaseUrl() { return this.baseUrl; }
38
39
  getToken() { return this.token; }
40
+ /** Perform an HTTP request, using an injected fetch implementation if provided. */
41
+ doFetch(url, init) {
42
+ return this._fetchImpl ? this._fetchImpl(url, init) : fetch(url, init);
43
+ }
39
44
  setToken(token) {
40
45
  this.token = token;
41
46
  }
@@ -954,6 +959,46 @@ function buildSDNA(subjectName, obj, properties, allRelationsMeta) {
954
959
  };
955
960
  }
956
961
 
962
+ /**
963
+ * SHACL-AF Node Expressions for property transforms.
964
+ *
965
+ * A `NodeExpression` is a JSON-serializable tree that describes how to transform
966
+ * a resolved property value. Unlike JS lambdas, these are portable, inspectable,
967
+ * and can be executed in the Rust model query engine.
968
+ *
969
+ * Each expression is a tagged union that evaluates to a `Value` (JSON-compatible).
970
+ */
971
+ /**
972
+ * Type guard to check if a value is a valid NodeExpression.
973
+ */
974
+ function isNodeExpression(v) {
975
+ if (typeof v !== 'object' || v === null)
976
+ return false;
977
+ const obj = v;
978
+ const type = obj.type;
979
+ switch (type) {
980
+ case 'focus':
981
+ return typeof obj.type === 'string';
982
+ case 'literal':
983
+ return typeof obj.value === 'string' || typeof obj.value === 'number' || typeof obj.value === 'boolean';
984
+ case 'path':
985
+ return typeof obj.predicate === 'string';
986
+ case 'exists':
987
+ return isNodeExpression(obj.expr);
988
+ case 'if':
989
+ return isNodeExpression(obj.cond) && isNodeExpression(obj.then) &&
990
+ (obj.else === undefined || isNodeExpression(obj.else));
991
+ case 'concat':
992
+ return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
993
+ case 'coalesce':
994
+ return Array.isArray(obj.args) && obj.args.every(isNodeExpression);
995
+ case 'function':
996
+ return typeof obj.iri === 'string' && Array.isArray(obj.args) && obj.args.every(isNodeExpression);
997
+ default:
998
+ return false;
999
+ }
1000
+ }
1001
+
957
1002
  /**
958
1003
  * Extract namespace from a URI
959
1004
  * Examples:
@@ -1284,7 +1329,7 @@ class SHACLShape {
1284
1329
  target: `literal:${prop.writable}`
1285
1330
  });
1286
1331
  }
1287
- if (prop.resolveLanguage) {
1332
+ if (prop.resolveLanguage != null) {
1288
1333
  links.push({
1289
1334
  source: propShapeId,
1290
1335
  predicate: "ad4m://resolveLanguage",
@@ -1376,6 +1421,13 @@ class SHACLShape {
1376
1421
  target: `literal:${prop.filter}`
1377
1422
  });
1378
1423
  }
1424
+ if (prop.transform && typeof prop.transform === 'object') {
1425
+ links.push({
1426
+ source: propShapeId,
1427
+ predicate: "ad4m://transform",
1428
+ target: `literal:string:${JSON.stringify(prop.transform)}`
1429
+ });
1430
+ }
1379
1431
  }
1380
1432
  return links;
1381
1433
  }
@@ -1595,6 +1647,22 @@ class SHACLShape {
1595
1647
  val = val.substring(8);
1596
1648
  prop.filter = val === 'true';
1597
1649
  }
1650
+ const transformLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://transform");
1651
+ if (transformLink) {
1652
+ const jsonStr = transformLink.target.replace(/^literal:\/\/string:|^literal:string:/, '');
1653
+ try {
1654
+ const parsed = JSON.parse(jsonStr);
1655
+ if (!isNodeExpression(parsed)) {
1656
+ throw new Error(`Invalid transform for property ${propShapeId}: ` +
1657
+ `payload is not a valid NodeExpression. Received: ${jsonStr}`);
1658
+ }
1659
+ prop.transform = parsed;
1660
+ }
1661
+ catch (e) {
1662
+ throw new Error(`Failed to deserialize transform for property ${propShapeId}: ` +
1663
+ `${e instanceof Error ? e.message : String(e)}. Payload: ${jsonStr}`);
1664
+ }
1665
+ }
1598
1666
  shape.addProperty(prop);
1599
1667
  }
1600
1668
  return shape;
@@ -1636,6 +1704,7 @@ class SHACLShape {
1636
1704
  where_filter: p.whereFilter,
1637
1705
  where_predicates: p.wherePredicates,
1638
1706
  filter: p.filter,
1707
+ transform: p.transform,
1639
1708
  })),
1640
1709
  constructor_actions: this.constructor_actions,
1641
1710
  destructor_actions: this.destructor_actions,
@@ -1649,6 +1718,11 @@ class SHACLShape {
1649
1718
  ? new SHACLShape(json.node_shape_uri, json.target_class)
1650
1719
  : new SHACLShape(json.target_class);
1651
1720
  for (const p of json.properties || []) {
1721
+ // Validate transform if present
1722
+ if (p.transform && !isNodeExpression(p.transform)) {
1723
+ throw new Error(`Invalid transform for property ${p.name}: ` +
1724
+ `payload is not a valid NodeExpression. Received: ${JSON.stringify(p.transform)}`);
1725
+ }
1652
1726
  shape.addProperty({
1653
1727
  path: p.path,
1654
1728
  name: p.name,
@@ -1675,6 +1749,7 @@ class SHACLShape {
1675
1749
  whereFilter: p.where_filter,
1676
1750
  wherePredicates: p.where_predicates,
1677
1751
  filter: p.filter,
1752
+ transform: p.transform,
1678
1753
  });
1679
1754
  }
1680
1755
  if (json.constructor_actions) {
@@ -1801,7 +1876,7 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
1801
1876
  if (propMeta.writable !== undefined) {
1802
1877
  propShape.writable = propMeta.writable;
1803
1878
  }
1804
- if (propMeta.resolveLanguage) {
1879
+ if (propMeta.resolveLanguage != null) {
1805
1880
  propShape.resolveLanguage = propMeta.resolveLanguage;
1806
1881
  }
1807
1882
  // Explicit getter SPARQL — the executor evaluates this when
@@ -1810,6 +1885,10 @@ function buildSHACL(subjectName, target, properties, allRelationsMeta, conforman
1810
1885
  if (propMeta.getter) {
1811
1886
  propShape.getter = propMeta.getter;
1812
1887
  }
1888
+ // Serializable transform expression (SHACL-AF Node Expression)
1889
+ if (propMeta.transform) {
1890
+ propShape.transform = propMeta.transform;
1891
+ }
1813
1892
  // ── Setter actions ──────────────────────────────────────────────
1814
1893
  if (propMeta.prologSetter) {
1815
1894
  console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
@@ -13792,7 +13871,7 @@ class AIClient {
13792
13871
  // Use slice to get only the relevant portion of the underlying ArrayBuffer
13793
13872
  // (Float32Array may be a view over a larger buffer)
13794
13873
  const bodyBuffer = typedAudio.buffer.slice(typedAudio.byteOffset, typedAudio.byteOffset + typedAudio.byteLength);
13795
- const response = await fetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
13874
+ const response = await __classPrivateFieldGet$2(this, _AIClient_apiClient, "f").doFetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
13796
13875
  method: 'POST',
13797
13876
  headers: {
13798
13877
  'Content-Type': 'application/octet-stream',
@@ -14959,14 +15038,8 @@ class ModelQueryBuilder {
14959
15038
  const parseResults = (raw) => {
14960
15039
  return ctor.parseModelResult(this.perspective, raw, this.queryParams.include, this.queryParams.properties);
14961
15040
  };
14962
- // Resolve non-literal (file-language) properties — handles both raw URI strings
14963
- // and already-resolved FileData objects returned by the Rust executor.
14964
- const resolveAndReturn = async (instances) => {
14965
- await ctor.resolveNonLiteralProps(this.perspective, instances);
14966
- return instances;
14967
- };
14968
- // Parse initial results (with non-literal resolution)
14969
- const initialResults = await resolveAndReturn(parseResults(initialModelResult));
15041
+ // Transforms are now applied by the Rust executor during hydration
15042
+ const initialResults = parseResults(initialModelResult);
14970
15043
  // Track last emitted result fingerprint to suppress duplicate callbacks
14971
15044
  let lastResultFingerprint = null;
14972
15045
  const buildFingerprint = (results) => {
@@ -14979,20 +15052,16 @@ class ModelQueryBuilder {
14979
15052
  // When Rust re-runs the model query and finds changed results, it pushes them.
14980
15053
  const unsubscribe = this.perspective.client.subscribeToQueryUpdates(subscriptionId, (rawResult) => {
14981
15054
  try {
14982
- const parsed = parseResults(rawResult);
14983
- console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${parsed.length} instances`);
14984
- resolveAndReturn(parsed).then((results) => {
14985
- const fp = buildFingerprint(results);
14986
- if (fp === lastResultFingerprint) {
14987
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
14988
- return;
14989
- }
14990
- console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
14991
- lastResultFingerprint = fp;
14992
- callback(results);
14993
- }).catch((e) => {
14994
- console.error('Model subscription update resolve error:', e);
14995
- });
15055
+ const results = parseResults(rawResult);
15056
+ console.debug(`[ModelQueryBuilder.subscribe] Update received for ${subscriptionId}: ${results.length} instances`);
15057
+ const fp = buildFingerprint(results);
15058
+ if (fp === lastResultFingerprint) {
15059
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint unchanged, skipping callback`);
15060
+ return;
15061
+ }
15062
+ console.debug(`[ModelQueryBuilder.subscribe] Fingerprint changed, calling callback with ${results.length} results`);
15063
+ lastResultFingerprint = fp;
15064
+ callback(results);
14996
15065
  }
14997
15066
  catch (e) {
14998
15067
  console.error('Model subscription update parse error:', e);
@@ -15347,48 +15416,6 @@ function normalizeValue(value) {
15347
15416
  return value;
15348
15417
  }
15349
15418
 
15350
- // ---------------------------------------------------------------------------
15351
- // Default decoder for file-storage (non-literal resolveLanguage) properties
15352
- // ---------------------------------------------------------------------------
15353
- /**
15354
- * When the Rust executor resolves a non-literal expression it may return a
15355
- * `FileData`-shaped object (`{ data_base64, file_type, ... }`) rather than a
15356
- * raw URI string. If the model class has no custom `transform` registered
15357
- * (e.g. it was synthesised from a SHACL shape at runtime) we still want to
15358
- * decode the content rather than passing raw `FileData` to callers.
15359
- *
15360
- * Decoding rules (mirrors the JS `decodeFileAsJson` / `decodeFileAsString` helpers):
15361
- * - `application/json` (default when `file_type` is absent) → JSON.parse
15362
- * - anything else → raw decoded string
15363
- *
15364
- * If `resolved` is not a `FileData` object the value is returned unchanged so
15365
- * that callers can use this as a safe unconditional fallback.
15366
- */
15367
- function defaultFileDecode(resolved) {
15368
- if (resolved !== null &&
15369
- typeof resolved === 'object' &&
15370
- 'data_base64' in resolved) {
15371
- const fd = resolved;
15372
- let raw;
15373
- try {
15374
- raw = atob(fd.data_base64);
15375
- }
15376
- catch {
15377
- return resolved; // malformed base64 — keep as-is
15378
- }
15379
- const isJson = !fd.file_type || fd.file_type === 'application/json';
15380
- if (isJson) {
15381
- try {
15382
- return JSON.parse(raw);
15383
- }
15384
- catch {
15385
- return raw;
15386
- }
15387
- }
15388
- return raw;
15389
- }
15390
- return resolved;
15391
- }
15392
15419
  // ---------------------------------------------------------------------------
15393
15420
  // Helpers for Rust-side include resolution
15394
15421
  // ---------------------------------------------------------------------------
@@ -15436,24 +15463,6 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
15436
15463
  }
15437
15464
  instance[key] = value;
15438
15465
  }
15439
- // Apply property transform functions from decorators (only for literal-resolved
15440
- // or no-resolveLanguage properties; non-literal properties are resolved + transformed
15441
- // asynchronously in executeModelQuery).
15442
- try {
15443
- const propsMeta = getPropertiesMetadata(ModelClass);
15444
- for (const [propName, opts] of Object.entries(propsMeta)) {
15445
- const o = opts;
15446
- if (typeof o.transform !== 'function' || !(propName in json))
15447
- continue;
15448
- // Skip non-literal resolveLanguage props — they need async expression resolution first
15449
- if (o.resolveLanguage != null && o.resolveLanguage !== 'literal')
15450
- continue;
15451
- instance[propName] = o.transform(instance[propName]);
15452
- }
15453
- }
15454
- catch (e) {
15455
- console.debug('jsonToModelInstance: transform metadata unavailable:', e);
15456
- }
15457
15466
  // Recursively convert included relation values to class instances
15458
15467
  if (include) {
15459
15468
  const relMeta = getRelationsMetadata(ModelClass);
@@ -15691,8 +15700,8 @@ class Ad4mModel {
15691
15700
  ...(options.getter !== undefined && { getter: options.getter }),
15692
15701
  ...(options.prologSetter !== undefined && { prologSetter: options.prologSetter }),
15693
15702
  ...(options.local !== undefined && { local: options.local }),
15694
- ...(options.transform !== undefined && { transform: options.transform }),
15695
- ...(options.flag !== undefined && { flag: options.flag })
15703
+ ...(options.flag !== undefined && { flag: options.flag }),
15704
+ ...(options.transform !== undefined && { transform: options.transform })
15696
15705
  };
15697
15706
  }
15698
15707
  // Extract relations (relations) from WeakMap registry
@@ -16169,57 +16178,6 @@ class Ad4mModel {
16169
16178
  return [];
16170
16179
  return arr.map((json) => jsonToModelInstance(this, perspective, json, include, properties));
16171
16180
  }
16172
- /**
16173
- * Resolve non-literal (file-language) properties on an array of already-constructed
16174
- * model instances. Handles two cases:
16175
- *
16176
- * 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
16177
- * 2. The Rust executor already resolved the expression and returned a `FileData` object
16178
- * (happens when the perspective backend eagerly fetches file content) → apply transform
16179
- * (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
16180
- * synthesised model classes).
16181
- *
16182
- * Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
16183
- * duplicating logic or introducing a circular dependency.
16184
- * @internal
16185
- */
16186
- static async resolveNonLiteralProps(perspective, instances) {
16187
- const propsMeta = getPropertiesMetadata(this);
16188
- const resolveProps = Object.entries(propsMeta).filter(([, opts]) => opts.resolveLanguage != null &&
16189
- opts.resolveLanguage !== 'literal');
16190
- if (resolveProps.length === 0)
16191
- return;
16192
- await Promise.all(instances.map(async (inst) => {
16193
- for (const [propName, opts] of resolveProps) {
16194
- const val = inst[propName];
16195
- const transform = opts.transform;
16196
- const applyTransform = (resolved) => typeof transform === 'function' ? transform(resolved) : defaultFileDecode(resolved);
16197
- if (typeof val === 'string' && val && !val.startsWith('literal:')) {
16198
- // Case 1: raw URI — fetch from language runtime
16199
- try {
16200
- const expression = await perspective.getExpression(val);
16201
- if (expression) {
16202
- let resolved;
16203
- try {
16204
- resolved = JSON.parse(expression.data);
16205
- }
16206
- catch {
16207
- resolved = expression.data;
16208
- }
16209
- inst[propName] = applyTransform(resolved);
16210
- }
16211
- }
16212
- catch (e) {
16213
- console.debug(`resolveNonLiteralProps: resolution failed for '${propName}':`, e);
16214
- }
16215
- }
16216
- else if (val !== null && val !== undefined && typeof val === 'object') {
16217
- // Case 2: already resolved by Rust — apply transform / default decode
16218
- inst[propName] = applyTransform(val);
16219
- }
16220
- }
16221
- }));
16222
- }
16223
16181
  // instancesFromQueryResult — removed (superseded by Rust executeModelQuery pipeline)
16224
16182
  /**
16225
16183
  * Execute a model query via the executor-side endpoint.
@@ -16239,11 +16197,6 @@ class Ad4mModel {
16239
16197
  const instances = result.instances.map((json) => {
16240
16198
  return jsonToModelInstance(this, perspective, json, query.include, query.properties);
16241
16199
  });
16242
- // Resolve non-literal expressions (e.g. file languages where the stored
16243
- // value is a content-addressed hash that must be fetched from the language
16244
- // runtime). The Rust endpoint may return either a raw target URI (string)
16245
- // or an already-resolved FileData object — both cases are handled here.
16246
- await this.resolveNonLiteralProps(perspective, instances);
16247
16200
  // Take snapshots for dirty tracking (exclude $-prefixed projection keys)
16248
16201
  const snapshotRelations = query.include
16249
16202
  ? Object.fromEntries(Object.entries(query.include).filter(([k]) => !k.startsWith('$')))
@@ -17259,7 +17212,7 @@ class Ad4mClient {
17259
17212
  _Ad4mClient_aiClient.set(this, void 0);
17260
17213
  __classPrivateFieldSet$1(this, _Ad4mClient_baseUrl, baseUrl, "f");
17261
17214
  __classPrivateFieldSet$1(this, _Ad4mClient_token, token, "f");
17262
- __classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl), "f");
17215
+ __classPrivateFieldSet$1(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl, options?.fetchImpl), "f");
17263
17216
  __classPrivateFieldSet$1(this, _Ad4mClient_agentClient, new AgentClient(baseUrl, token, subscribe, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17264
17217
  __classPrivateFieldSet$1(this, _Ad4mClient_expressionClient, new ExpressionClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
17265
17218
  __classPrivateFieldSet$1(this, _Ad4mClient_languageClient, new LanguageClient(baseUrl, token, __classPrivateFieldGet$1(this, _Ad4mClient_apiClient, "f")), "f");
@@ -18040,4 +17993,110 @@ class ModelInput {
18040
17993
  class VoiceActivityParamsInput {
18041
17994
  }
18042
17995
 
18043
- export { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, compileWhereClause, createPersistentCache, determineNamespace, determinePredicate, escapeQueryString, exprRef2String, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNumericType, isObjectType, isSchemaType, linkEqual, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };
17996
+ /**
17997
+ * Builder functions for SHACL-AF Node Expressions.
17998
+ *
17999
+ * These functions construct JSON-serializable expression trees for property transforms.
18000
+ * All builders return frozen objects to prevent accidental mutation.
18001
+ */
18002
+ /**
18003
+ * Identity expression: pass the focus node through unchanged.
18004
+ */
18005
+ function focus() {
18006
+ return Object.freeze({ type: 'focus' });
18007
+ }
18008
+ /**
18009
+ * Literal constant expression.
18010
+ */
18011
+ function literal(value) {
18012
+ return Object.freeze({ type: 'literal', value });
18013
+ }
18014
+ /**
18015
+ * Path expression: navigate to a property on the resolved object.
18016
+ * The predicate can be a full IRI (e.g., "file_storage://data_base64")
18017
+ * or a simple property name. The Rust evaluator will strip the namespace.
18018
+ */
18019
+ function path(predicate) {
18020
+ return Object.freeze({ type: 'path', predicate });
18021
+ }
18022
+ /**
18023
+ * Existence check: returns true if the inner expression is non-null and non-empty.
18024
+ */
18025
+ function exists(expr) {
18026
+ return Object.freeze({ type: 'exists', expr });
18027
+ }
18028
+ /**
18029
+ * Conditional expression with optional else branch.
18030
+ * Returns a chainable builder that supports `.then()` and `.else()`.
18031
+ */
18032
+ function ifExpr(cond) {
18033
+ return {
18034
+ then: (thenExpr) => ({
18035
+ else: (elseExpr) => {
18036
+ return Object.freeze({
18037
+ type: 'if',
18038
+ cond,
18039
+ then: thenExpr,
18040
+ ...(elseExpr !== undefined && { else: elseExpr }),
18041
+ });
18042
+ },
18043
+ // Allow chaining without explicit else()
18044
+ toExpression: () => Object.freeze({
18045
+ type: 'if',
18046
+ cond,
18047
+ then: thenExpr,
18048
+ }),
18049
+ }),
18050
+ };
18051
+ }
18052
+ /**
18053
+ * String concatenation: joins evaluated arguments as strings.
18054
+ * Null/undefined arguments are skipped.
18055
+ */
18056
+ function concat(...args) {
18057
+ return Object.freeze({ type: 'concat', args });
18058
+ }
18059
+ /**
18060
+ * Coalesce: returns the first non-null evaluated argument.
18061
+ */
18062
+ function coalesce(...args) {
18063
+ return Object.freeze({ type: 'coalesce', args });
18064
+ }
18065
+ /**
18066
+ * Function call: invoke a named transform function by IRI.
18067
+ * Primarily used for built-in functions like "ad4m://fn/defaultFileDecode".
18068
+ */
18069
+ function fn(iri, args = []) {
18070
+ return Object.freeze({ type: 'function', iri, args });
18071
+ }
18072
+
18073
+ /**
18074
+ * SHACL-AF Transform DSL — public API
18075
+ *
18076
+ * Re-exports builder functions and provides common built-in transforms.
18077
+ */
18078
+ /**
18079
+ * Built-in transform: FileData → data: URI
18080
+ *
18081
+ * Converts a file stored via FILE_STORAGE_LANGUAGE into a data: URL.
18082
+ * If the object has a `data_base64` field, returns:
18083
+ * `data:{file_type};base64,{data_base64}`
18084
+ * Otherwise passes through the input unchanged.
18085
+ *
18086
+ * This is the Rust equivalent of the JS `defaultFileDecode` function.
18087
+ *
18088
+ * Usage:
18089
+ * ```typescript
18090
+ * @Property({
18091
+ * through: 'we://image',
18092
+ * resolveLanguage: FILE_STORAGE_LANGUAGE,
18093
+ * transform: fileToDataUri,
18094
+ * })
18095
+ * avatar?: string;
18096
+ * ```
18097
+ */
18098
+ const fileToDataUri = ifExpr(exists(path('file_storage://data_base64')))
18099
+ .then(concat(literal('data:'), coalesce(path('file_storage://file_type'), literal('image/png')), literal(';base64,'), path('file_storage://data_base64')))
18100
+ .else(focus());
18101
+
18102
+ export { AIClient, Model as AIModel, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, BelongsToMany, BelongsToOne, Capability, CapabilityInput, ComputeLogEntry, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, HasMany, HasOne, HostingUserInfo, IDBCache, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, LocalModel, LocalModelInput, Model$1 as Model, ModelApi, ModelApiInput, ModelInput, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, NullCache, OnlineAgent, Optional, PaymentRequestResult, Perspective, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RpcError as RestError, RpcError, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, TokenizerSource, TokenizerSourceInput, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, VoiceActivityParamsInput, WakerSubscriptionManager, buildConformanceFilter, buildModelFromJSONSchema, buildPaginationSubquery, buildSDNA, buildSHACL, buildSPARQLQuery, buildWhereCondition, capSentence, clearQueryCache, coalesce, compileWhereClause, concat, createPersistentCache, determineNamespace, determinePredicate, escapeQueryString, exists, exprRef2String, fileToDataUri, fn, focus, formatList, formatQueryValue, formatSPARQLValue, getCachedResult, getDefaultValueForType, getMemoizedSHACL, getPropertiesMetadata, getPropertyOption, getRelationsMetadata, hasJsOnlyWhereFilters, ifExpr, invalidatePerspectiveCache, isArrayType, isExpression, isIncludeProjection, isLink, isNodeExpression, isNumericType, isObjectType, isSchemaType, linkEqual, literal, normalizeNamespaceString, normalizeSchemaType, normalizeValue, parseExprUrl, parseLit, parseLitBoolean, parseLitNumber, parseSparqlCount, path, queryCacheSize, resolveParentPredicate, setCachedResult, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };
@@ -18,6 +18,7 @@ export declare class Ad4mClient {
18
18
  #private;
19
19
  constructor(baseUrl: string, token?: string, subscribe?: boolean, options?: {
20
20
  webSocketImpl?: new (url: string) => WebSocket;
21
+ fetchImpl?: typeof fetch;
21
22
  });
22
23
  get agent(): AgentClient;
23
24
  get expression(): ExpressionClient;
@@ -42,7 +42,7 @@ export class Ad4mClient {
42
42
  _Ad4mClient_aiClient.set(this, void 0);
43
43
  __classPrivateFieldSet(this, _Ad4mClient_baseUrl, baseUrl, "f");
44
44
  __classPrivateFieldSet(this, _Ad4mClient_token, token, "f");
45
- __classPrivateFieldSet(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl), "f");
45
+ __classPrivateFieldSet(this, _Ad4mClient_apiClient, new ApiClient(baseUrl, token, options?.webSocketImpl, options?.fetchImpl), "f");
46
46
  __classPrivateFieldSet(this, _Ad4mClient_agentClient, new AgentClient(baseUrl, token, subscribe, __classPrivateFieldGet(this, _Ad4mClient_apiClient, "f")), "f");
47
47
  __classPrivateFieldSet(this, _Ad4mClient_expressionClient, new ExpressionClient(baseUrl, token, __classPrivateFieldGet(this, _Ad4mClient_apiClient, "f")), "f");
48
48
  __classPrivateFieldSet(this, _Ad4mClient_languageClient, new LanguageClient(baseUrl, token, __classPrivateFieldGet(this, _Ad4mClient_apiClient, "f")), "f");
@@ -120,7 +120,7 @@ export class AIClient {
120
120
  // Use slice to get only the relevant portion of the underlying ArrayBuffer
121
121
  // (Float32Array may be a view over a larger buffer)
122
122
  const bodyBuffer = typedAudio.buffer.slice(typedAudio.byteOffset, typedAudio.byteOffset + typedAudio.byteLength);
123
- const response = await fetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
123
+ const response = await __classPrivateFieldGet(this, _AIClient_apiClient, "f").doFetch(`${baseUrl}/api/v1/ai/transcription/feed`, {
124
124
  method: 'POST',
125
125
  headers: {
126
126
  'Content-Type': 'application/octet-stream',
@@ -15,9 +15,12 @@ export declare class ApiClient {
15
15
  private baseUrl;
16
16
  private token?;
17
17
  private readonly _webSocketImpl?;
18
- constructor(baseUrl: string, token?: string, webSocketImpl?: new (url: string) => WebSocket);
18
+ private readonly _fetchImpl?;
19
+ constructor(baseUrl: string, token?: string, webSocketImpl?: new (url: string) => WebSocket, fetchImpl?: typeof fetch);
19
20
  getBaseUrl(): string;
20
21
  getToken(): string | undefined;
22
+ /** Perform an HTTP request, using an injected fetch implementation if provided. */
23
+ doFetch(url: string, init: RequestInit): Promise<Response>;
21
24
  setToken(token: string): void;
22
25
  private _ws;
23
26
  private _wsCallbacks;
@@ -19,7 +19,7 @@ function nextId() {
19
19
  return String(++_idCounter);
20
20
  }
21
21
  export class ApiClient {
22
- constructor(baseUrl, token, webSocketImpl) {
22
+ constructor(baseUrl, token, webSocketImpl, fetchImpl) {
23
23
  // ── WebSocket RPC core ──────────────────────────────────────────────────
24
24
  this._ws = null;
25
25
  this._wsCallbacks = new Set();
@@ -33,9 +33,14 @@ export class ApiClient {
33
33
  this.baseUrl = baseUrl;
34
34
  this.token = token;
35
35
  this._webSocketImpl = webSocketImpl;
36
+ this._fetchImpl = fetchImpl;
36
37
  }
37
38
  getBaseUrl() { return this.baseUrl; }
38
39
  getToken() { return this.token; }
40
+ /** Perform an HTTP request, using an injected fetch implementation if provided. */
41
+ doFetch(url, init) {
42
+ return this._fetchImpl ? this._fetchImpl(url, init) : fetch(url, init);
43
+ }
39
44
  setToken(token) {
40
45
  this.token = token;
41
46
  }
@@ -34,6 +34,9 @@ export * from "./runtime/RuntimeTypes";
34
34
  export { Model as AIModel, ModelApi, TokenizerSource, LocalModel, ModelType, ModelApiInput, TokenizerSourceInput, LocalModelInput, ModelInput, VoiceActivityParamsInput } from "./ai/AITypes";
35
35
  export * from './shacl/SHACLShape';
36
36
  export { SHACLFlow, FlowState, FlowTransition, LinkPattern, FlowableCondition } from './shacl/SHACLFlow';
37
+ export * from './shacl/NodeExpression';
38
+ export * from './shacl/builders';
39
+ export { fileToDataUri } from './shacl/index';
37
40
  export * from "./generated/api";
38
41
  export { RpcError } from "./apiClient";
39
42
  /** @deprecated Use `RpcError` instead. */
package/lib/src/index.js CHANGED
@@ -34,6 +34,9 @@ export * from "./runtime/RuntimeTypes";
34
34
  export { Model as AIModel, ModelApi, TokenizerSource, LocalModel, ModelApiInput, TokenizerSourceInput, LocalModelInput, ModelInput, VoiceActivityParamsInput } from "./ai/AITypes";
35
35
  export * from './shacl/SHACLShape';
36
36
  export { SHACLFlow } from './shacl/SHACLFlow';
37
+ export * from './shacl/NodeExpression';
38
+ export * from './shacl/builders';
39
+ export { fileToDataUri } from './shacl/index';
37
40
  export * from "./generated/api";
38
41
  export { RpcError } from "./apiClient";
39
42
  /** @deprecated Use `RpcError` instead. */
@@ -315,21 +315,6 @@ export declare class Ad4mModel {
315
315
  * @internal
316
316
  */
317
317
  static parseModelResult<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, raw: any, include?: IncludeMap, properties?: string[]): T[];
318
- /**
319
- * Resolve non-literal (file-language) properties on an array of already-constructed
320
- * model instances. Handles two cases:
321
- *
322
- * 1. The Rust executor returned a raw URI string → fetch via `getExpression` then apply transform.
323
- * 2. The Rust executor already resolved the expression and returned a `FileData` object
324
- * (happens when the perspective backend eagerly fetches file content) → apply transform
325
- * (or `defaultFileDecode` if no transform is registered on the class, e.g. for SHACL-
326
- * synthesised model classes).
327
- *
328
- * Extracted as a public static so `ModelQueryBuilder.subscribe()` can reuse it without
329
- * duplicating logic or introducing a circular dependency.
330
- * @internal
331
- */
332
- static resolveNonLiteralProps<T extends Ad4mModel>(this: typeof Ad4mModel & (new (...args: any[]) => T), perspective: PerspectiveProxy, instances: T[]): Promise<void>;
333
318
  /**
334
319
  * Execute a model query via the executor-side endpoint.
335
320
  *