@coasys/ad4m 0.12.0-rc1-dev.5 → 0.12.0-rc2

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 (161) hide show
  1. package/lib/index.cjs +4968 -4805
  2. package/lib/index.js +4936 -4801
  3. package/lib/src/agent/AgentClient.d.ts +4 -0
  4. package/lib/src/agent/AgentClient.js +34 -0
  5. package/lib/src/index.d.ts +2 -3
  6. package/lib/src/index.js +2 -3
  7. package/lib/src/model/Ad4mModel.d.ts +8 -812
  8. package/lib/src/model/Ad4mModel.js +78 -2390
  9. package/lib/src/model/ModelQueryBuilder.d.ts +370 -0
  10. package/lib/src/model/ModelQueryBuilder.js +556 -0
  11. package/lib/src/model/decorators.d.ts +2 -20
  12. package/lib/src/model/decorators.js +5 -410
  13. package/lib/src/model/hydration.d.ts +102 -0
  14. package/lib/src/model/hydration.js +709 -0
  15. package/lib/src/model/index.d.ts +20 -0
  16. package/lib/src/model/index.js +20 -0
  17. package/lib/src/model/{schema/fromJSONSchema.d.ts → json-schema.d.ts} +45 -12
  18. package/lib/src/model/json-schema.js +326 -0
  19. package/lib/src/model/prolog-facts.d.ts +37 -0
  20. package/lib/src/model/{prolog/generatePrologFacts.js → prolog-facts.js} +47 -52
  21. package/lib/src/model/query-common.d.ts +14 -0
  22. package/lib/src/model/query-common.js +36 -0
  23. package/lib/src/model/query-prolog.d.ts +15 -0
  24. package/lib/src/model/query-prolog.js +140 -0
  25. package/lib/src/model/query-surreal.d.ts +44 -0
  26. package/lib/src/model/query-surreal.js +249 -0
  27. package/lib/src/model/sdna.d.ts +14 -0
  28. package/lib/src/model/sdna.js +141 -0
  29. package/lib/src/model/shacl-gen.d.ts +31 -0
  30. package/lib/src/model/shacl-gen.js +246 -0
  31. package/lib/src/model/surreal-utils.d.ts +1 -1
  32. package/lib/src/model/types.d.ts +75 -96
  33. package/lib/src/model/types.js +4 -4
  34. package/lib/src/model/util.d.ts +4 -5
  35. package/lib/src/model/util.js +12 -32
  36. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  37. package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
  38. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
  39. package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
  40. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  41. package/lib/src/runtime/RuntimeResolver.js +73 -0
  42. package/lib/src/schema.gql +14 -0
  43. package/lib/src/typeDefs.js +14 -0
  44. package/package.json +13 -8
  45. package/src/agent/AgentClient.ts +45 -0
  46. package/src/index.ts +2 -3
  47. package/src/model/Ad4mModel.ts +1084 -3818
  48. package/src/model/ModelQueryBuilder.ts +617 -0
  49. package/src/model/Subject.ts +1 -1
  50. package/src/model/decorators.ts +17 -475
  51. package/src/model/hydration.ts +796 -0
  52. package/src/model/index.ts +21 -0
  53. package/src/model/json-schema.ts +424 -0
  54. package/src/model/prolog-facts.ts +145 -0
  55. package/src/model/query-common.ts +48 -0
  56. package/src/model/query-prolog.ts +148 -0
  57. package/src/model/query-surreal.ts +280 -0
  58. package/src/model/relation-filtering.test.ts +0 -1
  59. package/src/model/sdna.ts +170 -0
  60. package/src/model/shacl-gen.ts +292 -0
  61. package/src/model/surreal-utils.ts +1 -1
  62. package/src/model/types.ts +182 -0
  63. package/src/model/util.ts +13 -36
  64. package/src/perspectives/PerspectiveClient.ts +1 -1
  65. package/src/perspectives/PerspectiveProxy.ts +1 -1
  66. package/src/perspectives/WakerSubscriptionManager.ts +292 -0
  67. package/src/runtime/RuntimeResolver.ts +53 -0
  68. package/lib/src/Ad4mClient.test.d.ts +0 -1
  69. package/lib/src/Ad4mClient.test.js +0 -1204
  70. package/lib/src/Literal.test.d.ts +0 -1
  71. package/lib/src/Literal.test.js +0 -41
  72. package/lib/src/model/mutation.d.ts +0 -81
  73. package/lib/src/model/mutation.js +0 -317
  74. package/lib/src/model/parentUtils.d.ts +0 -32
  75. package/lib/src/model/parentUtils.js +0 -64
  76. package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
  77. package/lib/src/model/prolog/index.d.ts +0 -1
  78. package/lib/src/model/prolog/index.js +0 -1
  79. package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
  80. package/lib/src/model/query/ModelQueryBuilder.js +0 -115
  81. package/lib/src/model/query/QueryBuilder.d.ts +0 -101
  82. package/lib/src/model/query/QueryBuilder.js +0 -193
  83. package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
  84. package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
  85. package/lib/src/model/query/fetchInstance.d.ts +0 -24
  86. package/lib/src/model/query/fetchInstance.js +0 -144
  87. package/lib/src/model/query/hydration.d.ts +0 -54
  88. package/lib/src/model/query/hydration.js +0 -214
  89. package/lib/src/model/query/operations.d.ts +0 -59
  90. package/lib/src/model/query/operations.js +0 -384
  91. package/lib/src/model/query/snapshot.d.ts +0 -59
  92. package/lib/src/model/query/snapshot.js +0 -106
  93. package/lib/src/model/query/surrealCompiler.d.ts +0 -42
  94. package/lib/src/model/query/surrealCompiler.js +0 -304
  95. package/lib/src/model/schema/fromJSONSchema.js +0 -264
  96. package/lib/src/model/schema/metadata.d.ts +0 -15
  97. package/lib/src/model/schema/metadata.js +0 -112
  98. package/lib/src/model/subscription.d.ts +0 -47
  99. package/lib/src/model/subscription.js +0 -231
  100. package/lib/src/model/transaction.d.ts +0 -27
  101. package/lib/src/model/transaction.js +0 -32
  102. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  103. package/lib/src/shims/type-graphql.d.ts +0 -32
  104. package/lib/src/src/Ad4mClient.d.ts +0 -28
  105. package/lib/src/src/Address.d.ts +0 -1
  106. package/lib/src/src/DID.d.ts +0 -1
  107. package/lib/src/src/Exception.d.ts +0 -7
  108. package/lib/src/src/Literal.d.ts +0 -7
  109. package/lib/src/src/PubSub.d.ts +0 -17
  110. package/lib/src/src/SmartLiteral.d.ts +0 -12
  111. package/lib/src/src/agent/Agent.d.ts +0 -110
  112. package/lib/src/src/agent/AgentClient.d.ts +0 -62
  113. package/lib/src/src/agent/AgentResolver.d.ts +0 -30
  114. package/lib/src/src/agent/AgentStatus.d.ts +0 -8
  115. package/lib/src/src/ai/AIClient.d.ts +0 -32
  116. package/lib/src/src/ai/AIResolver.d.ts +0 -75
  117. package/lib/src/src/ai/Tasks.d.ts +0 -37
  118. package/lib/src/src/buildSchema.d.ts +0 -1
  119. package/lib/src/src/expression/Expression.d.ts +0 -28
  120. package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
  121. package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
  122. package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
  123. package/lib/src/src/index.d.ts +0 -35
  124. package/lib/src/src/jestSetup.d.ts +0 -1
  125. package/lib/src/src/language/Icon.d.ts +0 -4
  126. package/lib/src/src/language/Language.d.ts +0 -206
  127. package/lib/src/src/language/LanguageClient.d.ts +0 -17
  128. package/lib/src/src/language/LanguageContext.d.ts +0 -37
  129. package/lib/src/src/language/LanguageHandle.d.ts +0 -9
  130. package/lib/src/src/language/LanguageMeta.d.ts +0 -35
  131. package/lib/src/src/language/LanguageRef.d.ts +0 -6
  132. package/lib/src/src/language/LanguageResolver.d.ts +0 -19
  133. package/lib/src/src/links/Links.d.ts +0 -39
  134. package/lib/src/src/links/Links.test.d.ts +0 -1
  135. package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
  136. package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
  137. package/lib/src/src/model/Subject.d.ts +0 -25
  138. package/lib/src/src/model/decorators.d.ts +0 -545
  139. package/lib/src/src/model/util.d.ts +0 -12
  140. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
  141. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
  142. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
  143. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
  144. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
  145. package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
  146. package/lib/src/src/perspectives/Perspective.d.ts +0 -38
  147. package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
  148. package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
  149. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
  150. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
  151. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
  152. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
  153. package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
  154. package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
  155. package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
  156. package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
  157. package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
  158. package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
  159. package/lib/src/src/typeDefs.d.ts +0 -1
  160. package/lib/src/src/unwrapApolloResult.d.ts +0 -2
  161. package/lib/src/src/utils.d.ts +0 -25
@@ -1,7 +1,7 @@
1
- import { capitalize, propertyNameToSetterName, stringifyObjectLiteral } from "./util";
2
- import { SHACLShape } from "../shacl/SHACLShape";
1
+ import { capitalize } from "./util";
2
+ import { buildSDNA } from "./sdna";
3
+ import { buildSHACL } from "./shacl-gen";
3
4
  import { escapeSurrealString } from "../utils";
4
- import { compileWhereClause } from "./surreal-utils";
5
5
  /** Registry of property metadata keyed by constructor → { propName → metadata } */
6
6
  const propertyRegistry = new WeakMap();
7
7
  /** Registry of relation metadata keyed by constructor → { propName → metadata } */
@@ -113,45 +113,6 @@ export function buildConformanceFilter(relationPredicate, targetClass) {
113
113
  return undefined;
114
114
  }
115
115
  }
116
- /**
117
- * Convert a model instance to a plain serializable object.
118
- * Reads the property metadata and extracts values from the instance.
119
- */
120
- export function instanceToSerializable(instance) {
121
- const ctor = instance.constructor;
122
- const props = getPropertiesMetadata(ctor);
123
- const result = {};
124
- for (const [key, _meta] of Object.entries(props)) {
125
- result[key] = instance[key];
126
- }
127
- return result;
128
- }
129
- /**
130
- * Generate a random identifier string (lowercase alpha).
131
- * Generate a random identifier string of the given length (lowercase alpha).
132
- */
133
- export function makeRandomId(length) {
134
- let result = '';
135
- const characters = 'abcdefghijklmnopqrstuvwxyz';
136
- const charactersLength = characters.length;
137
- for (let i = 0; i < length; i++) {
138
- result += characters.charAt(Math.floor(Math.random() * charactersLength));
139
- }
140
- return result;
141
- }
142
- export class PerspectiveAction {
143
- }
144
- export function addLink(source, predicate, target) {
145
- return {
146
- action: "addLink",
147
- source,
148
- predicate,
149
- target,
150
- };
151
- }
152
- export function hasLink(predicate) {
153
- return `triple(this, "${predicate}", _)`;
154
- }
155
116
  /**
156
117
  * Internal core implementation for registering property metadata on the prototype.
157
118
  * All property decorators (@Property, @Optional, @ReadOnly) and relation decorators
@@ -348,376 +309,10 @@ export function Model(opts) {
348
309
  target.prototype.className = opts.name;
349
310
  target.className = opts.name;
350
311
  target.generateSDNA = function () {
351
- let sdna = "";
352
- let subjectName = opts.name;
353
- let obj = target.prototype;
354
- let uuid = makeRandomId(8);
355
- sdna += `subject_class("${subjectName}", ${uuid}).\n`;
356
- let classRemoverActions = [];
357
- let constructorActions = [];
358
- if (obj.subjectConstructor && obj.subjectConstructor.length) {
359
- constructorActions = constructorActions.concat(obj.subjectConstructor);
360
- }
361
- let instanceConditions = [];
362
- if (obj.isSubjectInstance && obj.isSubjectInstance.length) {
363
- instanceConditions = instanceConditions.concat(obj.isSubjectInstance);
364
- }
365
- let propertiesCode = [];
366
- let properties = getPropertiesMetadata(target);
367
- for (let property in properties) {
368
- let propertyCode = `property(${uuid}, "${property}").\n`;
369
- let { through, initial, required, resolveLanguage, writable, flag, prologGetter, prologSetter, local } = properties[property];
370
- if (resolveLanguage) {
371
- propertyCode += `property_resolve(${uuid}, "${property}").\n`;
372
- propertyCode += `property_resolve_language(${uuid}, "${property}", "${resolveLanguage}").\n`;
373
- }
374
- if (prologGetter) {
375
- propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- ${prologGetter}.\n`;
376
- }
377
- else if (through) {
378
- propertyCode += `property_getter(${uuid}, Base, "${property}", Value) :- triple(Base, "${through}", Value).\n`;
379
- if (required) {
380
- if (flag) {
381
- instanceConditions.push(`triple(Base, "${through}", "${initial}")`);
382
- }
383
- else {
384
- instanceConditions.push(`triple(Base, "${through}", _)`);
385
- }
386
- }
387
- }
388
- if (prologSetter) {
389
- propertyCode += `property_setter(${uuid}, "${property}", Actions) :- ${prologSetter}.\n`;
390
- }
391
- else if (writable && through) {
392
- let setter = obj[propertyNameToSetterName(property)];
393
- if (typeof setter === "function") {
394
- let action = [{
395
- action: "setSingleTarget",
396
- source: "this",
397
- predicate: through,
398
- target: "value",
399
- ...(local && { local: true })
400
- }];
401
- propertyCode += `property_setter(${uuid}, "${property}", '${stringifyObjectLiteral(action)}').\n`;
402
- }
403
- }
404
- propertiesCode.push(propertyCode);
405
- // Auto-derive effectiveInitial for required, writable, non-flag properties
406
- // so constructor/destructor always handle the property link.
407
- // Optional properties (required: false) are excluded — they should
408
- // remain unset (undefined) until explicitly assigned.
409
- const effectiveInitial = initial
410
- ?? (required && writable && !flag && through ? "literal://string:" : undefined);
411
- if (effectiveInitial) {
412
- constructorActions.push({
413
- action: "addLink",
414
- source: "this",
415
- predicate: through,
416
- target: effectiveInitial,
417
- });
418
- classRemoverActions.push({
419
- action: "removeLink",
420
- source: "this",
421
- predicate: through,
422
- target: "*",
423
- });
424
- }
425
- }
426
- let relationsCode = [];
427
- const allRelationsMeta = getRelationsMetadata(target);
428
- const relations = Object.fromEntries(Object.entries(allRelationsMeta).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
429
- for (let relation in relations) {
430
- let relationCode = `collection(${uuid}, "${relation}").\n`;
431
- let { predicate: through, local } = relations[relation];
432
- if (through) {
433
- relationCode += `collection_getter(${uuid}, Base, "${relation}", List) :- findall(C, triple(Base, "${through}", C), List).\n`;
434
- let relationAdderAction = [{
435
- action: "addLink",
436
- source: "this",
437
- predicate: through,
438
- target: "value",
439
- ...(local && { local: true })
440
- }];
441
- let relationRemoverAction = [{
442
- action: "removeLink",
443
- source: "this",
444
- predicate: through,
445
- target: "value",
446
- }];
447
- let relationSetterAction = [{
448
- action: "collectionSetter",
449
- source: "this",
450
- predicate: through,
451
- target: "value",
452
- ...(local && { local: true })
453
- }];
454
- relationCode += `collection_adder(${uuid}, "${relation}", '${stringifyObjectLiteral(relationAdderAction)}').\n`;
455
- relationCode += `collection_remover(${uuid}, "${relation}", '${stringifyObjectLiteral(relationRemoverAction)}').\n`;
456
- relationCode += `collection_setter(${uuid}, "${relation}", '${stringifyObjectLiteral(relationSetterAction)}').\n`;
457
- }
458
- relationsCode.push(relationCode);
459
- }
460
- let subjectContructorJSONString = stringifyObjectLiteral(constructorActions);
461
- sdna += `constructor(${uuid}, '${subjectContructorJSONString}').\n`;
462
- if (instanceConditions.length > 0) {
463
- let instanceConditionProlog = instanceConditions.join(", ");
464
- sdna += `instance(${uuid}, Base) :- ${instanceConditionProlog}.\n`;
465
- sdna += "\n";
466
- }
467
- sdna += `destructor(${uuid}, '${stringifyObjectLiteral(classRemoverActions)}').\n`;
468
- sdna += "\n";
469
- sdna += propertiesCode.join("\n");
470
- sdna += "\n";
471
- sdna += relationsCode.join("\n");
472
- return {
473
- sdna,
474
- name: subjectName
475
- };
312
+ return buildSDNA(opts.name, target.prototype, getPropertiesMetadata(target), getRelationsMetadata(target));
476
313
  };
477
- // Generate SHACL shape (W3C standard + AD4M action definitions)
478
314
  target.generateSHACL = function () {
479
- const subjectName = opts.name;
480
- const obj = target.prototype;
481
- // Determine namespace from first property or relation, or use default
482
- let namespace = "ad4m://";
483
- const properties = getPropertiesMetadata(target);
484
- const allRelationsMeta2 = getRelationsMetadata(target);
485
- const relations = Object.fromEntries(Object.entries(allRelationsMeta2).filter(([, r]) => r.kind === 'hasMany' || r.kind === 'belongsToMany'));
486
- // Try properties first
487
- if (Object.keys(properties).length > 0) {
488
- const firstProp = properties[Object.keys(properties)[0]];
489
- if (firstProp.through) {
490
- // Extract namespace from through predicate (e.g., "recipe://name" -> "recipe://")
491
- const match = firstProp.through.match(/^([^:]+:\/\/)/);
492
- if (match) {
493
- namespace = match[1];
494
- }
495
- }
496
- }
497
- // Fall back to relations if no properties
498
- else if (Object.keys(relations).length > 0) {
499
- const firstRel = relations[Object.keys(relations)[0]];
500
- if (firstRel.predicate) {
501
- const match = firstRel.predicate.match(/^([^:]+:\/\/)/);
502
- if (match) {
503
- namespace = match[1];
504
- }
505
- }
506
- }
507
- // Create SHACL shape
508
- const shapeUri = `${namespace}${subjectName}Shape`;
509
- const targetClass = `${namespace}${subjectName}`;
510
- const shape = new SHACLShape(shapeUri, targetClass);
511
- // Detect @Model inheritance — if the parent class also has
512
- // generateSHACL it is itself a @Model and we reference its shape
513
- // via sh:node so SHACL validators can walk the hierarchy.
514
- const parentCtor = Object.getPrototypeOf(target);
515
- if (parentCtor && typeof parentCtor.generateSHACL === 'function') {
516
- const parentSHACL = parentCtor.generateSHACL();
517
- if (parentSHACL?.shape?.nodeShapeUri) {
518
- shape.addParentShape(parentSHACL.shape.nodeShapeUri);
519
- }
520
- }
521
- // === Extract Constructor Actions (same logic as generateSDNA) ===
522
- let constructorActions = [];
523
- if (obj.subjectConstructor && obj.subjectConstructor.length) {
524
- constructorActions = constructorActions.concat(obj.subjectConstructor);
525
- }
526
- // === Extract Destructor Actions ===
527
- let destructorActions = [];
528
- // Convert properties to SHACL property shapes
529
- for (const propName in properties) {
530
- const propMeta = properties[propName];
531
- if (!propMeta.through)
532
- continue; // Skip properties without predicates
533
- const propShape = {
534
- name: propName,
535
- path: propMeta.through,
536
- };
537
- // Determine datatype from initial value or resolveLanguage
538
- if (propMeta.resolveLanguage === "literal") {
539
- // If it resolves via literal language, it's likely a string
540
- propShape.datatype = "xsd://string";
541
- }
542
- else if (propMeta.initial) {
543
- // Try to infer from initial value type
544
- const initialType = typeof obj[propName];
545
- if (initialType === "number") {
546
- propShape.datatype = "xsd://integer";
547
- }
548
- else if (initialType === "boolean") {
549
- propShape.datatype = "xsd://boolean";
550
- }
551
- else if (initialType === "string") {
552
- propShape.datatype = "xsd://string";
553
- }
554
- }
555
- // Cardinality constraints
556
- if (propMeta.required) {
557
- propShape.minCount = 1;
558
- }
559
- // Single-valued properties get maxCount 1
560
- // (relations are handled separately below)
561
- propShape.maxCount = 1;
562
- // Flag properties have fixed value
563
- if (propMeta.flag && propMeta.initial) {
564
- propShape.hasValue = propMeta.initial;
565
- }
566
- // AD4M-specific metadata
567
- if (propMeta.local !== undefined) {
568
- propShape.local = propMeta.local;
569
- }
570
- if (propMeta.writable !== undefined) {
571
- propShape.writable = propMeta.writable;
572
- }
573
- if (propMeta.resolveLanguage) {
574
- propShape.resolveLanguage = propMeta.resolveLanguage;
575
- }
576
- // === Extract Setter Actions (same logic as generateSDNA) ===
577
- if (propMeta.prologSetter) {
578
- // Custom Prolog setter defined - not yet supported in SHACL
579
- console.warn(`[SHACL Generation] Custom Prolog setter for property '${propName}' in class '${subjectName}' is not yet supported. ` +
580
- `The property will be created without setter actions. Consider using standard writable properties or provide explicit SHACL JSON.`);
581
- // TODO: Parse custom Prolog setter to extract actions
582
- }
583
- else if (propMeta.writable && propMeta.through) {
584
- let setter = obj[propertyNameToSetterName(propName)];
585
- if (typeof setter === "function") {
586
- propShape.setter = [{
587
- action: "setSingleTarget",
588
- source: "this",
589
- predicate: propMeta.through,
590
- target: "value",
591
- ...(propMeta.local && { local: true })
592
- }];
593
- }
594
- }
595
- // Add to constructor actions if property has initial value
596
- // Auto-derive effectiveInitial for required, writable, non-flag properties.
597
- // Optional properties (required: false) are excluded — they should
598
- // remain unset (undefined) until explicitly assigned.
599
- const effectiveInitial = propMeta.initial
600
- ?? (propMeta.required && propMeta.writable && !propMeta.flag && propMeta.through
601
- ? "literal://string:" : undefined);
602
- if (effectiveInitial) {
603
- constructorActions.push({
604
- action: "addLink",
605
- source: "this",
606
- predicate: propMeta.through,
607
- target: effectiveInitial,
608
- });
609
- // Add to destructor actions
610
- destructorActions.push({
611
- action: "removeLink",
612
- source: "this",
613
- predicate: propMeta.through,
614
- target: "*",
615
- });
616
- }
617
- shape.addProperty(propShape);
618
- }
619
- // Convert relations to SHACL property shapes
620
- // (relations variable already declared above for namespace inference)
621
- for (const relName in relations) {
622
- const relMeta = relations[relName];
623
- if (!relMeta.predicate)
624
- continue;
625
- const relShape = {
626
- name: relName,
627
- path: relMeta.predicate,
628
- // Relations have no maxCount (unlimited)
629
- // minCount defaults to 0 (optional)
630
- };
631
- // Determine node kind — relations typically contain IRIs
632
- relShape.nodeKind = 'IRI';
633
- // AD4M-specific metadata
634
- if (relMeta.local !== undefined) {
635
- relShape.local = relMeta.local;
636
- }
637
- // === Extract Relation Actions (adder/remover) ===
638
- // Adder action - adds a link to the relation
639
- relShape.adder = [{
640
- action: "addLink",
641
- source: "this",
642
- predicate: relMeta.predicate,
643
- target: "value",
644
- ...(relMeta.local && { local: true })
645
- }];
646
- // Remover action - removes a link from the relation
647
- relShape.remover = [{
648
- action: "removeLink",
649
- source: "this",
650
- predicate: relMeta.predicate,
651
- target: "value",
652
- ...(relMeta.local && { local: true })
653
- }];
654
- // === Build Getter (conformance filter) ===
655
- // Priority chain:
656
- // 1. Explicit getter string → use verbatim
657
- // 2. `where` clause → compile DSL to SurrealQL getter
658
- // 3. target + filter !== false → auto-derive from shape
659
- if (relMeta.getter) {
660
- relShape.getter = relMeta.getter;
661
- }
662
- else if (relMeta.where) {
663
- // Compile Where DSL → SurrealQL getter
664
- try {
665
- const TargetClass = relMeta.target?.();
666
- const targetMetadata = TargetClass
667
- ? TargetClass.getModelMetadata?.() ?? null
668
- : null;
669
- const conditions = compileWhereClause(relMeta.where, targetMetadata);
670
- if (conditions.length > 0) {
671
- const escapedPredicate = escapeSurrealString(relMeta.predicate);
672
- relShape.getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
673
- }
674
- }
675
- catch (e) {
676
- // Target metadata may not be available yet
677
- }
678
- }
679
- else if (relMeta.target && relMeta.filter !== false) {
680
- try {
681
- const TargetClass = relMeta.target();
682
- const filter = buildConformanceFilter(relMeta.predicate, TargetClass);
683
- if (filter) {
684
- relShape.getter = filter.getter;
685
- relShape.conformanceConditions = filter.conformanceConditions;
686
- }
687
- }
688
- catch (e) {
689
- // Target class may not be available yet — getter will be
690
- // absent and runtime will fall back to unfiltered get_links
691
- }
692
- }
693
- // === sh:class — target shape reference ===
694
- // Always set when a target model is declared, regardless of filter.
695
- // This enables typed construction on the Rust/MCP side.
696
- if (relMeta.target) {
697
- try {
698
- const TargetClass = relMeta.target();
699
- const targetSHACL = TargetClass.generateSHACL?.();
700
- if (targetSHACL?.shape?.nodeShapeUri) {
701
- relShape.class = targetSHACL.shape.nodeShapeUri;
702
- }
703
- }
704
- catch (e) {
705
- // Target class may not be available yet
706
- }
707
- }
708
- shape.addProperty(relShape);
709
- }
710
- // Always set constructor and destructor actions on the shape, even
711
- // when empty. An empty array serialises to `literal://string:[]`
712
- // which the Rust executor parses as a valid (no-op) command list,
713
- // avoiding "No SHACL constructor found" errors for models whose
714
- // properties are all optional and have no @Flag.
715
- shape.setConstructorActions(constructorActions);
716
- shape.setDestructorActions(destructorActions);
717
- return {
718
- shape,
719
- name: subjectName
720
- };
315
+ return buildSHACL(opts.name, target, getPropertiesMetadata(target), getRelationsMetadata(target), buildConformanceFilter);
721
316
  };
722
317
  Object.defineProperty(target, 'type', { configurable: true });
723
318
  };
@@ -0,0 +1,102 @@
1
+ /**
2
+ * hydration.ts — Instance hydration helpers extracted from Ad4mModel.
3
+ *
4
+ * Pure / stateless functions that populate Ad4mModel instances from
5
+ * raw link arrays, Prolog tuples, or SurrealDB rows. None of these
6
+ * functions depend on the `Ad4mModel` class at runtime — they accept
7
+ * the instance, metadata, or perspective as explicit parameters.
8
+ */
9
+ import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
10
+ import type { PropertyMetadata, ModelMetadata, ValueTuple, WhereCondition, IncludeMap } from "./types";
11
+ /**
12
+ * Normalize a value for snapshot storage.
13
+ * Arrays of model instances are reduced to their `.id` strings so that
14
+ * dirty-tracking compares stable identifiers instead of object references.
15
+ */
16
+ export declare function normalizeValue(value: any): any;
17
+ /**
18
+ * Checks if a value matches a where-condition (for post-query filtering).
19
+ */
20
+ export declare function matchesCondition(value: any, condition: WhereCondition): boolean;
21
+ /**
22
+ * Resolves a single property value from a raw link target string.
23
+ *
24
+ * Handles expression resolution, literal URI parsing, primitive
25
+ * type coercion, and optional transform functions.
26
+ *
27
+ * @param target - The raw target string from the link
28
+ * @param propMeta - Property metadata from the decorator registry
29
+ * @param perspective - The perspective for expression resolution
30
+ * @param expectedType - Optional JS typeof hint for coercion (e.g. 'number')
31
+ * @returns The resolved value
32
+ */
33
+ export declare function hydratePropertyValue(target: string, propMeta: PropertyMetadata, perspective: PerspectiveProxy, expectedType?: string): Promise<any>;
34
+ /**
35
+ * Hydrates an instance from an array of raw links.
36
+ *
37
+ * Processes properties (latest-wins semantics), relations
38
+ * (chronological accumulation), and timestamps/author in a single
39
+ * pass over the links array.
40
+ *
41
+ * @param instance - The blank model instance to populate
42
+ * @param links - Array of link objects (predicate, target, author?, timestamp?)
43
+ * @param metadata - Model metadata from `getModelMetadata()`
44
+ * @param perspective - The perspective for expression resolution
45
+ * @param requestedProperties - Optional sparse fieldset; when provided, only these
46
+ * property names are hydrated (relations are unaffected).
47
+ * Omit or pass `undefined` to hydrate all properties.
48
+ */
49
+ export declare function hydrateFromLinks(instance: any, links: Array<{
50
+ predicate: string;
51
+ target: string;
52
+ author?: string;
53
+ timestamp?: string | number;
54
+ }>, metadata: ModelMetadata, perspective: PerspectiveProxy, requestedProperties?: string[]): Promise<void>;
55
+ /**
56
+ * Assigns decoded Prolog property values to an instance.
57
+ *
58
+ * Handles UTF-8 byte sequence reconstruction, expression resolution,
59
+ * transform functions, and read-only property filtering.
60
+ */
61
+ export declare function assignValuesToInstance(perspective: PerspectiveProxy, instance: any, values: ValueTuple[]): Promise<void>;
62
+ /**
63
+ * Builds a SurrealQL conformance getter for a relation whose `target` model
64
+ * is known but no explicit `getter` string was supplied.
65
+ *
66
+ * The generated getter traverses outgoing links matching the relation's
67
+ * predicate and then filters the target nodes to only those that conform to
68
+ * the target model's shape (required properties / flags).
69
+ *
70
+ * Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
71
+ * so the same logic is used at shape-definition time and at query time.
72
+ *
73
+ * @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
74
+ * @param targetClass - The target model class (result of calling the `target()` thunk)
75
+ * @returns A SurrealQL expression string, or `undefined` if no conformance
76
+ * conditions could be derived from the target model.
77
+ */
78
+ export declare function buildConformanceGetter(relationPredicate: string, targetClass: any): string | undefined;
79
+ /**
80
+ * Evaluates custom SurrealQL getters for properties and relations on a specific instance.
81
+ *
82
+ * For relations that declare a `target` but no explicit `getter`, a conformance
83
+ * getter is auto-generated from the target model's metadata (unless `filter: false`).
84
+ */
85
+ export declare function evaluateCustomGettersForInstance(instance: any, perspective: PerspectiveProxy, metadata: ModelMetadata, options?: {
86
+ requestedProperties?: string[];
87
+ include?: Record<string, any>;
88
+ }): Promise<void>;
89
+ /**
90
+ * Hydrates relation fields on instances according to the provided IncludeMap.
91
+ *
92
+ * For each relation listed in `includeMap`, the raw expression-URI strings
93
+ * stored on the instance are replaced with fully-hydrated model instances
94
+ * (fetched via the relation's `target()` class). Nested IncludeMaps are
95
+ * supported for multi-level eager loading.
96
+ *
97
+ * @param modelClass - The model class whose relation metadata to read
98
+ * @param instances - The instances whose relations should be hydrated
99
+ * @param perspective - The perspective to fetch related instances from
100
+ * @param includeMap - Describes which relations to hydrate
101
+ */
102
+ export declare function hydrateRelations<T>(modelClass: any, instances: T[], perspective: PerspectiveProxy, includeMap: IncludeMap | undefined): Promise<void>;