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

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 +0,0 @@
1
- export {};
@@ -1,41 +0,0 @@
1
- import { Literal } from "./Literal";
2
- describe("Literal", () => {
3
- it("can handle strings", () => {
4
- const testString = "test string";
5
- const testUrl = "literal://string:test%20string";
6
- expect(Literal.from(testString).toUrl()).toBe(testUrl);
7
- expect(Literal.fromUrl(testUrl).get()).toBe(testString);
8
- });
9
- it("can handle numbers", () => {
10
- const testNumber = 3.1415;
11
- const testUrl = "literal://number:3.1415";
12
- expect(Literal.from(testNumber).toUrl()).toBe(testUrl);
13
- expect(Literal.fromUrl(testUrl).get()).toBe(testNumber);
14
- });
15
- it("can handle objects", () => {
16
- const testObject = { testNumber: "1337", testString: "test" };
17
- const testUrl = "literal://json:%7B%22testNumber%22%3A%221337%22%2C%22testString%22%3A%22test%22%7D";
18
- expect(Literal.from(testObject).toUrl()).toBe(testUrl);
19
- expect(Literal.fromUrl(testUrl).get()).toStrictEqual(testObject);
20
- });
21
- it("can handle special characters", () => {
22
- const testString = "message(X) :- triple('ad4m://self', _, X).";
23
- const testUrl = "literal://string:message%28X%29%20%3A-%20triple%28%27ad4m%3A%2F%2Fself%27%2C%20_%2C%20X%29.";
24
- expect(Literal.from(testString).toUrl()).toBe(testUrl);
25
- expect(Literal.fromUrl(testUrl).get()).toBe(testString);
26
- });
27
- it("can handle boolean true", () => {
28
- const testUrl = "literal://boolean:true";
29
- expect(Literal.from(true).toUrl()).toBe(testUrl);
30
- expect(Literal.fromUrl(testUrl).get()).toBe(true);
31
- });
32
- it("can handle boolean false", () => {
33
- const testUrl = "literal://boolean:false";
34
- expect(Literal.from(false).toUrl()).toBe(testUrl);
35
- expect(Literal.fromUrl(testUrl).get()).toBe(false);
36
- });
37
- it("can handle zero", () => {
38
- expect(Literal.from(0).toUrl()).toBe("literal://number:0");
39
- expect(Literal.fromUrl("literal://number:0").get()).toBe(0);
40
- });
41
- });
@@ -1,81 +0,0 @@
1
- /**
2
- * Mutation helpers for Ad4mModel — extracted Phase 3c.
3
- *
4
- * All persistence functions that previously lived as private methods on Ad4mModel.
5
- * Each takes a `MutationContext` (perspective, id, instance)
6
- * instead of using `this`, making them independently testable and composable.
7
- *
8
- * Functions exported here cover the full write path:
9
- * - Pure action builders: `generatePropertySetterAction`, `generateRelationAction`
10
- * - Per-field setters: `setProperty`, `setRelationSetter/Adder/Remover`
11
- * - Instance-level persistence: `cleanCopy`, `innerUpdate`, `saveInstance`
12
- */
13
- import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
14
- import type { PropertyOptions, RelationOptions } from "./decorators";
15
- /**
16
- * Bundles the per-instance state needed by every mutation function,
17
- * replacing the private `this.#*` fields from Ad4mModel.
18
- */
19
- export interface MutationContext {
20
- /** The perspective that owns this instance. */
21
- perspective: PerspectiveProxy;
22
- /** URI of the instance's root node in the graph (the base expression). */
23
- id: string;
24
- /** The Ad4mModel instance itself (for `Object.entries`, prototype lookups, etc.) */
25
- instance: any;
26
- }
27
- /**
28
- * Builds a `setSingleTarget` action descriptor from property metadata.
29
- * Throws if the property is a flag, read-only, or has no predicate.
30
- */
31
- export declare function generatePropertySetterAction(key: string, metadata: PropertyOptions): any[];
32
- /**
33
- * Builds an `addLink` / `removeLink` / `relationSetter` action descriptor
34
- * from relation metadata.
35
- */
36
- export declare function generateRelationAction(key: string, metadata: RelationOptions, actionType: "adder" | "remover" | "setter"): any[];
37
- /**
38
- * Persists a single scalar property value for `ctx.instance`.
39
- *
40
- * Values that already carry a URI scheme are passed through unchanged.
41
- * Raw scalars are encoded as `literal://` URIs.
42
- * When a `resolveLanguage` is set, the value is first stored via `createExpression`.
43
- */
44
- export declare function setProperty(ctx: MutationContext, key: string, value: any, batchId?: string): Promise<void>;
45
- /** Sets (replaces) the full set of targets for a relation. */
46
- export declare function setRelationSetter(ctx: MutationContext, key: string, value: any, batchId?: string): Promise<void>;
47
- /** Adds one or more targets to a relation without removing existing ones. */
48
- export declare function setRelationAdder(ctx: MutationContext, key: string, value: any, batchId?: string): Promise<void>;
49
- /** Removes one or more targets from a relation. */
50
- export declare function setRelationRemover(ctx: MutationContext, key: string, value: any, batchId?: string): Promise<void>;
51
- /**
52
- * Returns a shallow copy of `instance` with `null`, `undefined`,
53
- * `author`, and `timestamp` fields omitted.
54
- */
55
- export declare function cleanCopy(instance: any): Record<string, any>;
56
- /**
57
- * Iterates all instance fields and persists each one according to its metadata.
58
- *
59
- * - Fields with an `.action` shape → dispatched to the matching relation mutator.
60
- * - Arrays → treated as relation setters (including empty arrays to clear relations).
61
- * - Scalar values → written via `setProperty` when `setProperties` is `true` and the
62
- * field is not a relation or a flag.
63
- *
64
- * @note `#subjectClassName` was written here in the original implementation but
65
- * is never read anywhere — the write is intentionally omitted.
66
- */
67
- export declare function innerUpdate(ctx: MutationContext, setProperties?: boolean, batchId?: string): Promise<void>;
68
- /**
69
- * Persists `ctx.instance` to `ctx.perspective`.
70
- *
71
- * Auto-detects create vs update by checking whether any links already exist
72
- * for `ctx.id`.
73
- *
74
- * - **Create path**: `createSubject` → `innerUpdate(false)` (relations only).
75
- * - **Update path**: `innerUpdate(true)` (properties + relations).
76
- *
77
- * @param ctx - Mutation context (perspective, id, instance).
78
- * @param batchId - Optional caller-managed batch. When omitted an internal batch
79
- * is created, committed, and the instance is rehydrated automatically.
80
- */
81
- export declare function saveInstance(ctx: MutationContext, batchId?: string, alreadyExists?: boolean): Promise<void>;
@@ -1,317 +0,0 @@
1
- /**
2
- * Mutation helpers for Ad4mModel — extracted Phase 3c.
3
- *
4
- * All persistence functions that previously lived as private methods on Ad4mModel.
5
- * Each takes a `MutationContext` (perspective, id, instance)
6
- * instead of using `this`, making them independently testable and composable.
7
- *
8
- * Functions exported here cover the full write path:
9
- * - Pure action builders: `generatePropertySetterAction`, `generateRelationAction`
10
- * - Per-field setters: `setProperty`, `setRelationSetter/Adder/Remover`
11
- * - Instance-level persistence: `cleanCopy`, `innerUpdate`, `saveInstance`
12
- */
13
- import { Literal } from "../Literal";
14
- import { getPropertiesMetadata, getRelationsMetadata, propertyRegistry, } from "./decorators";
15
- import { formatSurrealValue } from "./query/surrealCompiler";
16
- import { fetchInstanceData } from "./query/fetchInstance";
17
- import { isDirty } from "./query/snapshot";
18
- import { getModelMetadata as _getModelMetadata } from "./schema/metadata";
19
- // ── Pure action builders ───────────────────────────────────────────────────
20
- /**
21
- * Builds a `setSingleTarget` action descriptor from property metadata.
22
- * Throws if the property is a flag, read-only, or has no predicate.
23
- */
24
- export function generatePropertySetterAction(key, metadata) {
25
- if (metadata.flag) {
26
- throw new Error(`Property "${key}" is a @Flag and cannot be set after creation`);
27
- }
28
- if (metadata.readOnly === true) {
29
- throw new Error(`Property "${key}" is read-only and cannot be written`);
30
- }
31
- if (!metadata.through) {
32
- throw new Error(`Property "${key}" has no 'through' predicate defined`);
33
- }
34
- return [
35
- {
36
- action: "setSingleTarget",
37
- source: "this",
38
- predicate: metadata.through,
39
- target: "value",
40
- ...(metadata.local && { local: true }),
41
- },
42
- ];
43
- }
44
- /**
45
- * Builds an `addLink` / `removeLink` / `relationSetter` action descriptor
46
- * from relation metadata.
47
- */
48
- export function generateRelationAction(key, metadata, actionType) {
49
- if (!metadata.through) {
50
- throw new Error(`Relation "${key}" has no 'through' predicate defined`);
51
- }
52
- const actionMap = {
53
- adder: "addLink",
54
- remover: "removeLink",
55
- setter: "relationSetter",
56
- };
57
- return [
58
- {
59
- action: actionMap[actionType],
60
- source: "this",
61
- predicate: metadata.through,
62
- target: "value",
63
- ...(metadata.local && { local: true }),
64
- },
65
- ];
66
- }
67
- // ── Property / relation setters ────────────────────────────────────────────
68
- /**
69
- * Persists a single scalar property value for `ctx.instance`.
70
- *
71
- * Values that already carry a URI scheme are passed through unchanged.
72
- * Raw scalars are encoded as `literal://` URIs.
73
- * When a `resolveLanguage` is set, the value is first stored via `createExpression`.
74
- */
75
- export async function setProperty(ctx, key, value, batchId) {
76
- const proto = Object.getPrototypeOf(ctx.instance);
77
- const metadata = getPropertiesMetadata(proto.constructor)?.[key];
78
- if (!metadata) {
79
- throw new Error(`setProperty called with unknown key "${key}" — ensure the field has a @Property decorator`);
80
- }
81
- const actions = generatePropertySetterAction(key, metadata);
82
- const resolveLanguage = metadata.resolveLanguage;
83
- // Skip empty/null/undefined to avoid storing invalid empty literals.
84
- if (value === undefined || value === null || value === "")
85
- return;
86
- if (resolveLanguage) {
87
- value = await ctx.perspective.createExpression(value, resolveLanguage);
88
- }
89
- else if (typeof value !== "string" ||
90
- !/^[a-zA-Z][a-zA-Z0-9+\-.]*:/.test(value)) {
91
- // Encode raw scalars as literal:// URIs — mirrors Rust's resolve_property_value.
92
- value = Literal.from(value).toUrl();
93
- }
94
- await ctx.perspective.executeAction(actions, ctx.id, [{ name: "value", value }], batchId);
95
- }
96
- /** Normalises an Ad4mModel instance to its id URI, passing other values through unchanged. */
97
- const toId = (v) => v && typeof v === "object" && typeof v.id === "string" ? v.id : v;
98
- /** Sets (replaces) the full set of targets for a relation. */
99
- export async function setRelationSetter(ctx, key, value, batchId) {
100
- const proto = Object.getPrototypeOf(ctx.instance);
101
- const metadata = getRelationsMetadata(proto.constructor)?.[key];
102
- if (!metadata) {
103
- console.warn(`Relation "${key}" has no metadata, skipping`);
104
- return;
105
- }
106
- const actions = generateRelationAction(key, metadata, "setter");
107
- if (value != null) {
108
- if (Array.isArray(value)) {
109
- await ctx.perspective.executeAction(actions, ctx.id, value.map((v) => ({ name: "value", value: toId(v) })), batchId);
110
- }
111
- else {
112
- await ctx.perspective.executeAction(actions, ctx.id, [{ name: "value", value: toId(value) }], batchId);
113
- }
114
- }
115
- }
116
- /** Adds one or more targets to a relation without removing existing ones. */
117
- export async function setRelationAdder(ctx, key, value, batchId) {
118
- const proto = Object.getPrototypeOf(ctx.instance);
119
- const metadata = getRelationsMetadata(proto.constructor)?.[key];
120
- if (!metadata) {
121
- console.warn(`Relation "${key}" has no metadata, skipping`);
122
- return;
123
- }
124
- const actions = generateRelationAction(key, metadata, "adder");
125
- if (value != null) {
126
- if (Array.isArray(value)) {
127
- await Promise.all(value.map((v) => ctx.perspective.executeAction(actions, ctx.id, [{ name: "value", value: toId(v) }], batchId)));
128
- }
129
- else {
130
- await ctx.perspective.executeAction(actions, ctx.id, [{ name: "value", value: toId(value) }], batchId);
131
- }
132
- }
133
- }
134
- /** Removes one or more targets from a relation. */
135
- export async function setRelationRemover(ctx, key, value, batchId) {
136
- const proto = Object.getPrototypeOf(ctx.instance);
137
- const metadata = getRelationsMetadata(proto.constructor)?.[key];
138
- if (!metadata) {
139
- console.warn(`Relation "${key}" has no metadata, skipping`);
140
- return;
141
- }
142
- const actions = generateRelationAction(key, metadata, "remover");
143
- if (value != null) {
144
- if (Array.isArray(value)) {
145
- await Promise.all(value.map((v) => ctx.perspective.executeAction(actions, ctx.id, [{ name: "value", value: toId(v) }], batchId)));
146
- }
147
- else {
148
- await ctx.perspective.executeAction(actions, ctx.id, [{ name: "value", value: toId(value) }], batchId);
149
- }
150
- }
151
- }
152
- // ── Persistence ────────────────────────────────────────────────────────────
153
- /**
154
- * Returns a shallow copy of `instance` with `null`, `undefined`,
155
- * `author`, and `timestamp` fields omitted.
156
- */
157
- export function cleanCopy(instance) {
158
- const clean = {};
159
- for (const [key, value] of Object.entries(instance)) {
160
- if (value !== undefined &&
161
- value !== null &&
162
- key !== "author" &&
163
- key !== "timestamp") {
164
- clean[key] = value;
165
- }
166
- }
167
- return clean;
168
- }
169
- /**
170
- * Iterates all instance fields and persists each one according to its metadata.
171
- *
172
- * - Fields with an `.action` shape → dispatched to the matching relation mutator.
173
- * - Arrays → treated as relation setters (including empty arrays to clear relations).
174
- * - Scalar values → written via `setProperty` when `setProperties` is `true` and the
175
- * field is not a relation or a flag.
176
- *
177
- * @note `#subjectClassName` was written here in the original implementation but
178
- * is never read anywhere — the write is intentionally omitted.
179
- */
180
- export async function innerUpdate(ctx, setProperties = true, batchId) {
181
- const proto = Object.getPrototypeOf(ctx.instance);
182
- for (const [key, value] of Object.entries(ctx.instance)) {
183
- if (value !== undefined && value !== null) {
184
- if (value?.action) {
185
- switch (value.action) {
186
- case "setter":
187
- await setRelationSetter(ctx, key, value.value, batchId);
188
- break;
189
- case "adder":
190
- await setRelationAdder(ctx, key, value.value, batchId);
191
- break;
192
- case "remover":
193
- await setRelationRemover(ctx, key, value.value, batchId);
194
- break;
195
- default:
196
- await setRelationSetter(ctx, key, value.value, batchId);
197
- break;
198
- }
199
- }
200
- else if (Array.isArray(value)) {
201
- // All arrays (including empty) treated as relation setters.
202
- // Skip if the set hasn't changed since the last hydration/save.
203
- if (!isDirty(ctx.instance, key, value))
204
- continue;
205
- await setRelationSetter(ctx, key, value, batchId);
206
- }
207
- else if (value !== undefined && value !== null && value !== "") {
208
- if (setProperties) {
209
- // Skip relation fields — they are not scalar properties.
210
- if (getRelationsMetadata(proto.constructor)?.[key])
211
- continue;
212
- const propMeta = getPropertiesMetadata(proto.constructor)?.[key];
213
- // No @Property decorator for this key — skip silently.
214
- // This covers generated relation methods (addX / removeX / setX)
215
- // that appear as own enumerable properties on the instance, and
216
- // base-class fields like `author` / `createdAt` that have no
217
- // associated predicate.
218
- if (!propMeta)
219
- continue;
220
- // Skip flag fields — flags are immutable, written once by createSubject.
221
- if (propMeta.flag)
222
- continue;
223
- // Skip if the value hasn't changed since the last hydration/save.
224
- if (!isDirty(ctx.instance, key, value))
225
- continue;
226
- await setProperty(ctx, key, value, batchId);
227
- }
228
- }
229
- }
230
- }
231
- }
232
- /**
233
- * Persists `ctx.instance` to `ctx.perspective`.
234
- *
235
- * Auto-detects create vs update by checking whether any links already exist
236
- * for `ctx.id`.
237
- *
238
- * - **Create path**: `createSubject` → `innerUpdate(false)` (relations only).
239
- * - **Update path**: `innerUpdate(true)` (properties + relations).
240
- *
241
- * @param ctx - Mutation context (perspective, id, instance).
242
- * @param batchId - Optional caller-managed batch. When omitted an internal batch
243
- * is created, committed, and the instance is rehydrated automatically.
244
- */
245
- export async function saveInstance(ctx, batchId, alreadyExists) {
246
- const safeBase = formatSurrealValue(ctx.id);
247
- // Skip the DB round-trip when the caller already knows the instance was
248
- // saved once (e.g. the second save() call inside the same uncommitted batch).
249
- let isNew;
250
- if (alreadyExists === true) {
251
- isNew = false;
252
- }
253
- else {
254
- const existingLinks = await ctx.perspective.querySurrealDB(`SELECT 1 FROM link WHERE in.uri = ${safeBase} LIMIT 1`);
255
- isNew = !existingLinks || existingLinks.length === 0;
256
- }
257
- let batchCreatedHere = false;
258
- if (!batchId) {
259
- batchId = await ctx.perspective.createBatch();
260
- batchCreatedHere = true;
261
- }
262
- if (isNew) {
263
- // ── CREATE PATH ─────────────────────────────────────────────────────────
264
- // Build initialValues from decorator-registered scalar properties only.
265
- // We must NOT use Object.entries(ctx.instance) because TypeScript `private`
266
- // fields (e.g. _perspective) are regular enumerable properties at runtime
267
- // and would cause JSON.stringify to throw a circular-reference error when
268
- // the PerspectiveProxy's Apollo InMemoryCache is encountered.
269
- const proto = Object.getPrototypeOf(ctx.instance);
270
- const ownPropKeys = new Set(Object.keys(propertyRegistry.get(proto.constructor) ?? {}));
271
- const allPropMeta = getPropertiesMetadata(proto.constructor);
272
- const initialValues = {};
273
- for (const key of ownPropKeys) {
274
- const propMeta = allPropMeta[key];
275
- if (!propMeta)
276
- continue;
277
- if (propMeta.flag)
278
- continue; // flags handled by constructor actions
279
- const value = ctx.instance[key];
280
- if (value !== undefined &&
281
- value !== null &&
282
- !(Array.isArray(value) && value.length > 0) &&
283
- !value?.action) {
284
- initialValues[key] = value;
285
- }
286
- }
287
- const className = await ctx.perspective.stringOrTemplateObjectToSubjectClassName(ctx.instance);
288
- await ctx.perspective.createSubject(className, ctx.id, initialValues, batchId);
289
- await innerUpdate(ctx, false, batchId);
290
- // Write inherited properties not present in the class's own SHACL shape.
291
- // When a derived class uses sh:node to reference its parent shape, createSubject
292
- // only writes properties defined in the derived shape. Inherited @Property fields
293
- // (registered on the parent constructor) are silently ignored by the Rust backend.
294
- // We detect them by comparing the full merged metadata against the own-only registry.
295
- for (const [key, propMeta] of Object.entries(allPropMeta)) {
296
- if (ownPropKeys.has(key))
297
- continue; // already handled by createSubject
298
- if (propMeta.flag)
299
- continue; // flags are immutable
300
- const value = ctx.instance[key];
301
- if (value !== undefined && value !== null && value !== "") {
302
- await setProperty(ctx, key, value, batchId);
303
- }
304
- }
305
- }
306
- else {
307
- // ── UPDATE PATH ─────────────────────────────────────────────────────────
308
- // Instance already exists — update properties and relations only.
309
- await innerUpdate(ctx, true, batchId);
310
- }
311
- if (batchCreatedHere) {
312
- await ctx.perspective.commitBatch(batchId);
313
- // Rehydrate the instance so callers see the persisted state.
314
- const metadata = _getModelMetadata(ctx.instance.constructor);
315
- await fetchInstanceData(ctx.instance, ctx.perspective, ctx.id, metadata);
316
- }
317
- }
@@ -1,32 +0,0 @@
1
- import type { ModelMetadata, ParentQuery, ParentQueryByPredicate } from "./types";
2
- /**
3
- * Resolves the predicate URI for a parent→child relation, used by
4
- * `Ad4mModel.create()` and the `useLiveQuery` hooks.
5
- *
6
- * If `field` is supplied, that exact relation is looked up on the parent.
7
- * Otherwise, all forward relations on the parent whose `relatedModel()` factory
8
- * returns `childCtor` are scanned; the result is used when exactly one match
9
- * is found.
10
- *
11
- * @throws if the field doesn't exist, or inference is ambiguous / impossible.
12
- *
13
- * @example
14
- * // Explicit field
15
- * resolveParentPredicate(Channel.getModelMetadata(), Poll, 'polls')
16
- *
17
- * // Inferred — only one @HasMany on Channel points to Poll
18
- * resolveParentPredicate(Channel.getModelMetadata(), Poll)
19
- */
20
- export declare function resolveParentPredicate(parentMeta: ModelMetadata, childCtor: (new (...args: any[]) => any) | undefined, field?: string): string;
21
- /**
22
- * Normalises a `Query.parent` option to its raw `{ id, predicate }` form.
23
- *
24
- * When the model-backed form `{ id, model, field? }` is supplied, the predicate
25
- * is resolved via {@link resolveParentPredicate}. The raw `{ id, predicate }`
26
- * form is returned as-is.
27
- *
28
- * @param lf - Either the raw or model-backed `parent` query value.
29
- * @param childCtor - The child model constructor. Required when `field` is
30
- * omitted (used for inference across `@HasMany` metadata).
31
- */
32
- export declare function normalizeParentQuery(lf: ParentQuery, childCtor?: new (...args: any[]) => any): ParentQueryByPredicate;
@@ -1,64 +0,0 @@
1
- /**
2
- * Resolves the predicate URI for a parent→child relation, used by
3
- * `Ad4mModel.create()` and the `useLiveQuery` hooks.
4
- *
5
- * If `field` is supplied, that exact relation is looked up on the parent.
6
- * Otherwise, all forward relations on the parent whose `relatedModel()` factory
7
- * returns `childCtor` are scanned; the result is used when exactly one match
8
- * is found.
9
- *
10
- * @throws if the field doesn't exist, or inference is ambiguous / impossible.
11
- *
12
- * @example
13
- * // Explicit field
14
- * resolveParentPredicate(Channel.getModelMetadata(), Poll, 'polls')
15
- *
16
- * // Inferred — only one @HasMany on Channel points to Poll
17
- * resolveParentPredicate(Channel.getModelMetadata(), Poll)
18
- */
19
- export function resolveParentPredicate(parentMeta, childCtor, field) {
20
- if (field) {
21
- const predicate = parentMeta.relations[field]?.predicate;
22
- if (!predicate) {
23
- throw new Error(`resolveParentPredicate: field "${field}" not found in parent model ` +
24
- `"${parentMeta.className}" relations. Check that @HasMany is declared on that field.`);
25
- }
26
- return predicate;
27
- }
28
- if (!childCtor) {
29
- throw new Error(`resolveParentPredicate: either "field" or a child model constructor must be provided.`);
30
- }
31
- const matches = Object.values(parentMeta.relations).filter((r) => r.direction !== "reverse" && r.relatedModel?.() === childCtor);
32
- if (matches.length === 1)
33
- return matches[0].predicate;
34
- if (matches.length === 0) {
35
- throw new Error(`resolveParentPredicate: no forward relation pointing to ` +
36
- `"${childCtor.name ?? String(childCtor)}" found on parent "${parentMeta.className}". ` +
37
- `Provide "field" explicitly or add a typed @HasMany(() => ${childCtor.name ?? "ChildModel"}) on the parent.`);
38
- }
39
- // matches.length > 1
40
- const fieldNames = Object.entries(parentMeta.relations)
41
- .filter((r) => r[1].direction !== "reverse" && r[1].relatedModel?.() === childCtor)
42
- .map(([k]) => k)
43
- .join(", ");
44
- throw new Error(`resolveParentPredicate: multiple relations on "${parentMeta.className}" point to ` +
45
- `"${childCtor.name ?? String(childCtor)}" (fields: ${fieldNames}). ` +
46
- `Provide "field" to disambiguate.`);
47
- }
48
- /**
49
- * Normalises a `Query.parent` option to its raw `{ id, predicate }` form.
50
- *
51
- * When the model-backed form `{ id, model, field? }` is supplied, the predicate
52
- * is resolved via {@link resolveParentPredicate}. The raw `{ id, predicate }`
53
- * form is returned as-is.
54
- *
55
- * @param lf - Either the raw or model-backed `parent` query value.
56
- * @param childCtor - The child model constructor. Required when `field` is
57
- * omitted (used for inference across `@HasMany` metadata).
58
- */
59
- export function normalizeParentQuery(lf, childCtor) {
60
- if ("predicate" in lf)
61
- return lf;
62
- const predicate = resolveParentPredicate(lf.model.getModelMetadata(), childCtor, lf.field);
63
- return { id: lf.id, predicate };
64
- }
@@ -1,36 +0,0 @@
1
- import type { Ad4mModel } from "../Ad4mModel";
2
- import type { ModelMetadata } from "../Ad4mModel";
3
- type ModelClass = typeof Ad4mModel & {
4
- getModelMetadata(): ModelMetadata;
5
- };
6
- /**
7
- * Generate Prolog predicate facts from a model class's SHACL metadata.
8
- *
9
- * Given a model class decorated with `@ModelOptions` (and its `@Flag`,
10
- * `@Property`, `@Collection` decorators), this function emits a string of
11
- * Prolog clauses that can be prepended to any `perspective.infer()` call.
12
- *
13
- * The generated predicates are:
14
- * - **Instance recognizer** — `modelName(X)` — matches instances of the model
15
- * - **Property getters** — `modelName_propName(X, Value)` — one per property
16
- * - **Collection getters** — `modelName_collName(X, Values)` — one per collection
17
- *
18
- * @example
19
- * ```typescript
20
- * import { generatePrologFacts } from '@coasys/ad4m/model/prolog';
21
- *
22
- * const facts = generatePrologFacts(Poll);
23
- * const result = await perspective.infer(`
24
- * ${facts}
25
- * recent_popular_poll(X) :-
26
- * poll(X),
27
- * poll_vote_count(X, N), N > 10,
28
- * poll_created_at(X, T), T > ${yesterday}.
29
- * `);
30
- * ```
31
- *
32
- * @param ModelClass - A class decorated with `@ModelOptions` that extends `Ad4mModel`
33
- * @returns A multi-line Prolog string ready for use with `perspective.infer()`
34
- */
35
- export declare function generatePrologFacts(ModelClass: ModelClass): string;
36
- export {};
@@ -1 +0,0 @@
1
- export { generatePrologFacts } from './generatePrologFacts';
@@ -1 +0,0 @@
1
- export { generatePrologFacts } from './generatePrologFacts';
@@ -1,82 +0,0 @@
1
- /**
2
- * Fluent query builder for Ad4mModel.
3
- *
4
- * Extracted from Ad4mModel.ts. The class holds a `Query` object and delegates
5
- * all execution to `Ad4mModel` static methods via the `ctor` constructor
6
- * reference, so there is no circular import (this module imports from the
7
- * Ad4mModel module, but Ad4mModel does not import from here — it re-exports
8
- * ModelQueryBuilder from its own file for backward compatibility).
9
- */
10
- import { PerspectiveProxy } from "../../perspectives/PerspectiveProxy";
11
- import { Order, PaginationResult, Query, Where, IncludeMap, SubscribeOptions, Subscription } from "../types";
12
- export type Ad4mModelCtor<T> = typeof import("../Ad4mModel").Ad4mModel & (new (...args: any[]) => T);
13
- /**
14
- * Fluent builder for Ad4mModel queries.
15
- *
16
- * Create via `MyModel.query(perspective)`:
17
- * ```typescript
18
- * const posts = await Post.query(perspective)
19
- * .where({ published: true })
20
- * .order({ createdAt: "DESC" })
21
- * .limit(10)
22
- * .get();
23
- * ```
24
- */
25
- export declare class ModelQueryBuilder<T extends import("../Ad4mModel").Ad4mModel> {
26
- private perspective;
27
- private queryParams;
28
- private modelClassName;
29
- private ctor;
30
- constructor(perspective: PerspectiveProxy, ctor: Ad4mModelCtor<T>, query?: Query);
31
- where(conditions: Where): ModelQueryBuilder<T>;
32
- order(orderBy: Order): ModelQueryBuilder<T>;
33
- limit(limit: number): ModelQueryBuilder<T>;
34
- offset(offset: number): ModelQueryBuilder<T>;
35
- properties(properties: string[]): ModelQueryBuilder<T>;
36
- /**
37
- * Eagerly load specific relations as full model instances.
38
- *
39
- * Key = relation field name on the model.
40
- * Value = `true` (all instances) or a `Query` to filter/order/limit the nested set.
41
- *
42
- * @example
43
- * ```typescript
44
- * Recipe.query(perspective)
45
- * .include({
46
- * comments: true,
47
- * tags: { where: { active: true }, limit: 5 },
48
- * })
49
- * .get();
50
- * ```
51
- */
52
- include(map: IncludeMap): ModelQueryBuilder<T>;
53
- overrideModelClassName(className: string): ModelQueryBuilder<T>;
54
- /** Executes the query and returns all matching instances. */
55
- get(): Promise<T[]>;
56
- /** Returns the first matching instance, or `null` if none found. */
57
- first(): Promise<T | null>;
58
- /** Returns the total count of matching entities. */
59
- count(): Promise<number>;
60
- /** Returns a single page of results with pagination metadata. */
61
- paginate(pageSize: number, pageNumber: number): Promise<PaginationResult<T>>;
62
- /**
63
- * Terminal: creates a live subscription using the query parameters accumulated
64
- * so far. Fires `callback` immediately with current results, then on every
65
- * relevant link change.
66
- *
67
- * Pass additional delivery options (`debounce`, `onError`) in `deliveryOpts`.
68
- * Call `sub.unsubscribe()` to detach.
69
- *
70
- * @example
71
- * ```typescript
72
- * const sub = Post.query(perspective)
73
- * .where({ published: true })
74
- * .order({ createdAt: "DESC" })
75
- * .live((posts) => setPosts(posts), { debounce: 300 });
76
- *
77
- * // cleanup:
78
- * sub.unsubscribe();
79
- * ```
80
- */
81
- live(callback: (results: T[]) => void, deliveryOpts?: Pick<SubscribeOptions, "debounce" | "onError">): Subscription;
82
- }