@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,264 +0,0 @@
1
- /**
2
- * Dynamic model creation from JSON Schema.
3
- *
4
- * Extracted from Ad4mModel.ts so it can be tested and reused independently.
5
- * The main entry point — `createModelFromJSONSchema` — takes the `Ad4mModel`
6
- * class as `BaseClass` to avoid a circular import between this module and the
7
- * class file.
8
- */
9
- import { Model, propertyRegistry, relationRegistry, } from "../decorators";
10
- import { capitalize, propertyNameToSetterName } from "../util";
11
- // ── Internal schema helpers ─────────────────────────────────────────────────
12
- export function normalizeNamespaceString(namespace) {
13
- if (!namespace)
14
- return "";
15
- if (namespace.includes("://")) {
16
- const [scheme, rest] = namespace.split("://");
17
- const path = (rest || "").replace(/\/+$/, "");
18
- return `${scheme}://${path}`;
19
- }
20
- else {
21
- return namespace.replace(/\/+$/, "");
22
- }
23
- }
24
- export function normalizeSchemaType(type) {
25
- if (!type)
26
- return undefined;
27
- if (typeof type === "string")
28
- return type;
29
- if (Array.isArray(type) && type.length > 0) {
30
- const nonNull = type.find((t) => t !== "null");
31
- return nonNull || type[0];
32
- }
33
- return undefined;
34
- }
35
- export function isSchemaType(schema, expectedType) {
36
- return normalizeSchemaType(schema.type) === expectedType;
37
- }
38
- export function isArrayType(schema) {
39
- return isSchemaType(schema, "array");
40
- }
41
- export function isObjectType(schema) {
42
- return isSchemaType(schema, "object");
43
- }
44
- export function isNumericType(schema) {
45
- const normalized = normalizeSchemaType(schema.type);
46
- return normalized === "number" || normalized === "integer";
47
- }
48
- // ── Predicate + namespace resolution ───────────────────────────────────────
49
- export function determineNamespace(schema, options) {
50
- if (options.namespace)
51
- return options.namespace;
52
- if (schema["x-ad4m"]?.namespace)
53
- return schema["x-ad4m"].namespace;
54
- if (schema.title)
55
- return `${schema.title.toLowerCase()}://`;
56
- if (schema.$id) {
57
- try {
58
- const url = new URL(schema.$id);
59
- const pathParts = url.pathname.split("/").filter((p) => p);
60
- if (pathParts.length > 0) {
61
- const lastPart = pathParts[pathParts.length - 1];
62
- const baseName = lastPart
63
- .replace(/\.schema\.json$/, "")
64
- .replace(/\.json$/, "");
65
- return `${baseName.toLowerCase()}://`;
66
- }
67
- }
68
- catch {
69
- // not a valid URL — fall through to error
70
- }
71
- }
72
- throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:\n` +
73
- ` - options.namespace\n` +
74
- ` - schema["x-ad4m"].namespace\n` +
75
- ` - schema.title\n` +
76
- ` - valid schema.$id`);
77
- }
78
- export function determinePredicate(schema, propertyName, propertySchema, namespace, options) {
79
- if (options.propertyMapping?.[propertyName]) {
80
- return options.propertyMapping[propertyName];
81
- }
82
- if (propertySchema["x-ad4m"]?.through) {
83
- return propertySchema["x-ad4m"].through;
84
- }
85
- if (options.predicateTemplate) {
86
- const normalizedNs = normalizeNamespaceString(namespace);
87
- const [scheme, rest] = normalizedNs.includes("://")
88
- ? normalizedNs.split("://")
89
- : ["", normalizedNs];
90
- const nsNoScheme = rest || "";
91
- return options.predicateTemplate
92
- .replace("${namespace}", nsNoScheme)
93
- .replace("${scheme}", scheme)
94
- .replace("${ns}", nsNoScheme)
95
- .replace("${title}", schema.title || "")
96
- .replace("${property}", propertyName);
97
- }
98
- if (options.predicateGenerator) {
99
- return options.predicateGenerator(schema.title || "", propertyName);
100
- }
101
- const normalizedNs = normalizeNamespaceString(namespace);
102
- if (normalizedNs.includes("://")) {
103
- return `${normalizedNs}${propertyName}`;
104
- }
105
- else {
106
- return `${normalizedNs}://${propertyName}`;
107
- }
108
- }
109
- export function getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue) {
110
- if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
111
- return options.propertyOptions[propertyName][optionName];
112
- }
113
- if (propertySchema["x-ad4m"]?.[optionName] !== undefined) {
114
- return propertySchema["x-ad4m"][optionName];
115
- }
116
- if (options[optionName] !== undefined) {
117
- return options[optionName];
118
- }
119
- return defaultValue;
120
- }
121
- export function getDefaultValueForType(type) {
122
- switch (type) {
123
- case "string":
124
- return "";
125
- case "number":
126
- return 0;
127
- case "integer":
128
- return 0;
129
- case "boolean":
130
- return false;
131
- case "array":
132
- return [];
133
- case "object":
134
- return {};
135
- default:
136
- return "";
137
- }
138
- }
139
- // ── Main factory ────────────────────────────────────────────────────────────
140
- /**
141
- * Creates an Ad4mModel subclass dynamically from a JSON Schema definition.
142
- *
143
- * Takes `BaseClass` as a parameter (rather than importing `Ad4mModel` directly)
144
- * to avoid a circular dependency between this module and `Ad4mModel.ts`.
145
- *
146
- * `Ad4mModel.fromJSONSchema()` is a thin wrapper that calls this with `this`.
147
- */
148
- export function createModelFromJSONSchema(BaseClass, schema, options) {
149
- if (schema?.properties &&
150
- Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
151
- throw new Error('JSON Schema must not define a top-level "author" property because Ad4mModel already exposes it. Please rename the property (e.g., "writer").');
152
- }
153
- const namespace = determineNamespace(schema, options);
154
- const DynamicModelClass = class extends BaseClass {
155
- };
156
- if (!options.name || options.name.trim() === "") {
157
- throw new Error("options.name is required and cannot be empty");
158
- }
159
- DynamicModelClass.className = options.name;
160
- DynamicModelClass.prototype.className = options.name;
161
- const properties = {};
162
- const relations = {};
163
- if (schema.properties) {
164
- for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
165
- const predicate = determinePredicate(schema, propertyName, propertySchema, namespace, options);
166
- const isRequired = schema.required?.includes(propertyName) || false;
167
- const propertyType = normalizeSchemaType(propertySchema.type);
168
- const isArray = isArrayType(propertySchema);
169
- if (isArray) {
170
- relations[propertyName] = {
171
- through: predicate,
172
- local: getPropertyOption(propertyName, propertySchema, options, "local"),
173
- };
174
- Object.defineProperty(DynamicModelClass.prototype, propertyName, {
175
- configurable: true,
176
- writable: true,
177
- value: [],
178
- });
179
- const adderName = `add${capitalize(propertyName)}`;
180
- const removerName = `remove${capitalize(propertyName)}`;
181
- const setterName = `set${capitalize(propertyName)}`;
182
- DynamicModelClass.prototype[adderName] = function () { };
183
- DynamicModelClass.prototype[removerName] = function () { };
184
- DynamicModelClass.prototype[setterName] = function () { };
185
- }
186
- else {
187
- let resolveLanguage = getPropertyOption(propertyName, propertySchema, options, "resolveLanguage");
188
- if (!resolveLanguage && options.resolveLanguage) {
189
- resolveLanguage = options.resolveLanguage;
190
- }
191
- const local = getPropertyOption(propertyName, propertySchema, options, "local");
192
- const readOnly = getPropertyOption(propertyName, propertySchema, options, "readOnly");
193
- let initial = getPropertyOption(propertyName, propertySchema, options, "initial");
194
- if (isObjectType(propertySchema) && !resolveLanguage) {
195
- resolveLanguage = "literal";
196
- console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
197
- }
198
- // No auto-assignment for numeric types — resolveLanguage === undefined
199
- // is now the implicit 'literal' default throughout the model layer.
200
- if (isRequired && !initial) {
201
- if (isObjectType(propertySchema)) {
202
- initial = "literal://json:{}";
203
- }
204
- else {
205
- initial = "ad4m://undefined";
206
- }
207
- }
208
- properties[propertyName] = {
209
- through: predicate,
210
- required: isRequired,
211
- ...(readOnly && { readOnly }),
212
- ...(resolveLanguage && { resolveLanguage }),
213
- ...(local !== undefined && { local }),
214
- ...(initial && { initial }),
215
- };
216
- Object.defineProperty(DynamicModelClass.prototype, propertyName, {
217
- configurable: true,
218
- writable: true,
219
- value: getDefaultValueForType(propertyType),
220
- });
221
- if (!readOnly) {
222
- const setterName = propertyNameToSetterName(propertyName);
223
- DynamicModelClass.prototype[setterName] = function () { };
224
- }
225
- }
226
- }
227
- }
228
- // Ensure at least one property has an initial value (needed for a valid SDNA constructor)
229
- const hasPropertyWithInitial = Object.values(properties).some((prop) => prop.initial);
230
- if (!hasPropertyWithInitial) {
231
- const typeProperty = `ad4m://type`;
232
- let typeValue;
233
- if (namespace.includes("://")) {
234
- const [scheme, rest] = namespace.split("://");
235
- const path = (rest || "").replace(/\/+$/, "");
236
- typeValue = path
237
- ? `${scheme}://${path}/instance`
238
- : `${scheme}://instance`;
239
- }
240
- else {
241
- typeValue = `${namespace.replace(/\/+$/, "")}/instance`;
242
- }
243
- properties["__ad4m_type"] = {
244
- through: typeProperty,
245
- required: true,
246
- readOnly: true,
247
- initial: typeValue,
248
- flag: true,
249
- };
250
- Object.defineProperty(DynamicModelClass.prototype, "__ad4m_type", {
251
- configurable: true,
252
- writable: false,
253
- value: typeValue,
254
- });
255
- console.warn(`No properties with initial values found. Added automatic type flag: ${typeProperty} = ${typeValue}`);
256
- }
257
- propertyRegistry.set(DynamicModelClass, properties);
258
- relationRegistry.set(DynamicModelClass, relations);
259
- DynamicModelClass.prototype.__jsonSchema = schema;
260
- DynamicModelClass.prototype.__jsonSchemaOptions = options;
261
- const ModelDecorator = Model({ name: options.name });
262
- ModelDecorator(DynamicModelClass);
263
- return DynamicModelClass;
264
- }
@@ -1,15 +0,0 @@
1
- /**
2
- * Metadata extraction helper for Ad4mModel.
3
- *
4
- * - `getModelMetadata(ctor)` — builds a {@link ModelMetadata} descriptor from
5
- * the decorator registries, or falls back to the attached JSON Schema.
6
- */
7
- import type { ModelMetadata } from "../types";
8
- /**
9
- * Builds a {@link ModelMetadata} descriptor for `ctor` from its decorator
10
- * registries, falling back to the attached JSON Schema if no decorators are
11
- * found.
12
- *
13
- * The matching `Ad4mModel.getModelMetadata()` static method delegates here.
14
- */
15
- export declare function getModelMetadata(ctor: any): ModelMetadata;
@@ -1,112 +0,0 @@
1
- /**
2
- * Metadata extraction helper for Ad4mModel.
3
- *
4
- * - `getModelMetadata(ctor)` — builds a {@link ModelMetadata} descriptor from
5
- * the decorator registries, or falls back to the attached JSON Schema.
6
- */
7
- import { getPropertiesMetadata, getRelationsMetadata } from "../decorators";
8
- import { isArrayType, determinePredicate, determineNamespace, } from "./fromJSONSchema";
9
- // ─────────────────────────────────────────────────────────────────────────────
10
- // getModelMetadataForClass
11
- // ─────────────────────────────────────────────────────────────────────────────
12
- /**
13
- * Builds a {@link ModelMetadata} descriptor for `ctor` from its decorator
14
- * registries, falling back to the attached JSON Schema if no decorators are
15
- * found.
16
- *
17
- * The matching `Ad4mModel.getModelMetadata()` static method delegates here.
18
- */
19
- export function getModelMetadata(ctor) {
20
- const prototype = ctor.prototype;
21
- if (!prototype.className || prototype.className === "Ad4mModel") {
22
- throw new Error("Model class must be decorated with @Model");
23
- }
24
- const className = prototype.className;
25
- // ── Extract from decorator registries ──────────────────────────────────────
26
- const propertiesMetadata = {};
27
- const prototypeProperties = getPropertiesMetadata(ctor);
28
- for (const [propertyName, opts] of Object.entries(prototypeProperties)) {
29
- const options = opts;
30
- propertiesMetadata[propertyName] = {
31
- name: propertyName,
32
- predicate: options.through || "",
33
- required: options.required || false,
34
- ...(options.readOnly !== undefined && { readOnly: options.readOnly }),
35
- ...(options.initial !== undefined && { initial: options.initial }),
36
- ...(options.resolveLanguage !== undefined && {
37
- resolveLanguage: options.resolveLanguage,
38
- }),
39
- ...(options.getter !== undefined && { getter: options.getter }),
40
- ...(options.local !== undefined && { local: options.local }),
41
- ...(options.transform !== undefined && { transform: options.transform }),
42
- ...(options.flag !== undefined && { flag: options.flag }),
43
- };
44
- }
45
- const relationsMetadata = {};
46
- const prototypeRelations = getRelationsMetadata(ctor);
47
- for (const [relationName, opts] of Object.entries(prototypeRelations)) {
48
- const options = opts;
49
- relationsMetadata[relationName] = {
50
- name: relationName,
51
- predicate: options.through || "",
52
- ...(options.local !== undefined && { local: options.local }),
53
- ...(options.getter !== undefined && { getter: options.getter }),
54
- ...(opts.direction !== undefined && {
55
- direction: opts.direction,
56
- }),
57
- ...(opts.maxCount !== undefined && {
58
- maxCount: opts.maxCount,
59
- }),
60
- ...(opts.relatedModel !== undefined && {
61
- relatedModel: opts.relatedModel,
62
- }),
63
- };
64
- }
65
- // ── Fallback: derive from attached JSON Schema if registries are empty ──────
66
- const hasMetadata = Object.keys(propertiesMetadata).length > 0 ||
67
- Object.keys(relationsMetadata).length > 0;
68
- if (!hasMetadata && prototype.__jsonSchema) {
69
- const schema = prototype.__jsonSchema;
70
- const schemaOptions = prototype.__jsonSchemaOptions || {};
71
- if (schema.properties) {
72
- for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
73
- const isArray = isArrayType(propertySchema);
74
- const predicate = determinePredicate(schema, propertyName, propertySchema, determineNamespace(schema, schemaOptions), schemaOptions);
75
- if (isArray) {
76
- relationsMetadata[propertyName] = {
77
- name: propertyName,
78
- predicate,
79
- ...(propertySchema["x-ad4m"]?.local !== undefined && {
80
- local: propertySchema["x-ad4m"].local,
81
- }),
82
- };
83
- }
84
- else {
85
- propertiesMetadata[propertyName] = {
86
- name: propertyName,
87
- predicate,
88
- required: schema.required?.includes(propertyName) || false,
89
- ...(propertySchema["x-ad4m"]?.readOnly && {
90
- readOnly: true,
91
- }),
92
- ...(propertySchema["x-ad4m"]?.resolveLanguage && {
93
- resolveLanguage: propertySchema["x-ad4m"]
94
- .resolveLanguage,
95
- }),
96
- ...(propertySchema["x-ad4m"]?.initial && {
97
- initial: propertySchema["x-ad4m"].initial,
98
- }),
99
- ...(propertySchema["x-ad4m"]?.local !== undefined && {
100
- local: propertySchema["x-ad4m"].local,
101
- }),
102
- };
103
- }
104
- }
105
- }
106
- }
107
- return {
108
- className,
109
- properties: propertiesMetadata,
110
- relations: relationsMetadata,
111
- };
112
- }
@@ -1,47 +0,0 @@
1
- /**
2
- * Live subscription implementation for Ad4mModel.
3
- *
4
- * Identical queries on the same perspective share a single `findAll()` call
5
- * and a single pair of link listeners via an internal registry — multiple
6
- * components subscribing to the same data cooperate rather than each running
7
- * independent queries.
8
- *
9
- * Results are fingerprinted before broadcasting: callbacks only fire when
10
- * the result set has actually changed.
11
- */
12
- import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
13
- import type { Query, ModelMetadata, Subscription, SubscribeOptions } from "./types";
14
- /**
15
- * Creates a live subscription for a model query.
16
- *
17
- * Immediately invokes `callback` with the initial query results, then
18
- * re-invokes it whenever a relevant link is added to or removed from the
19
- * perspective.
20
- *
21
- * Multiple callers subscribing to the same model + query on the same
22
- * perspective share a single `findAll()` execution and a single pair of link
23
- * listeners via an internal registry. Callbacks are only fired when the
24
- * result set has actually changed.
25
- *
26
- * @param findAll - The model's `findAll` static method
27
- * @param getMetadata - The model's `getModelMetadata` static method
28
- * @param perspective - The perspective to watch
29
- * @param options - Query parameters + delivery options (debounce, onError)
30
- * @param callback - Invoked with fresh results on every relevant change
31
- * @returns A `Subscription` handle with `unsubscribe()` and `lastError`
32
- *
33
- * @example
34
- * ```typescript
35
- * const sub = createSubscription(
36
- * (p, q) => Post.findAll(p, q),
37
- * () => Post.getModelMetadata(),
38
- * perspective,
39
- * { where: { published: true }, debounce: 200 },
40
- * (posts) => console.log("Posts updated:", posts),
41
- * );
42
- *
43
- * // Later:
44
- * sub.unsubscribe();
45
- * ```
46
- */
47
- export declare function createSubscription<T>(findAll: (perspective: PerspectiveProxy, query?: Query) => Promise<T[]>, getMetadata: () => ModelMetadata, perspective: PerspectiveProxy, options: SubscribeOptions, callback: (results: T[]) => void, ctor?: new (...args: any[]) => any): Subscription;
@@ -1,231 +0,0 @@
1
- /**
2
- * Live subscription implementation for Ad4mModel.
3
- *
4
- * Identical queries on the same perspective share a single `findAll()` call
5
- * and a single pair of link listeners via an internal registry — multiple
6
- * components subscribing to the same data cooperate rather than each running
7
- * independent queries.
8
- *
9
- * Results are fingerprinted before broadcasting: callbacks only fire when
10
- * the result set has actually changed.
11
- */
12
- import { instanceToSerializable } from "./decorators";
13
- import { normalizeParentQuery } from "./parentUtils";
14
- // ─── Helpers ──────────────────────────────────────────────────────────────────
15
- /**
16
- * Stable JSON key for a Query — sorts object keys so that equivalent queries
17
- * produced from different code paths hash to the same string.
18
- */
19
- function stableQueryKey(query) {
20
- if (Object.keys(query).length === 0)
21
- return "{}";
22
- const sorted = {};
23
- for (const k of Object.keys(query).sort()) {
24
- sorted[k] = query[k];
25
- }
26
- return JSON.stringify(sorted);
27
- }
28
- /**
29
- * Stable fingerprint for an array of model instances.
30
- *
31
- * Sorted by `id` so result ordering doesn't cause false positives.
32
- * `id` is a prototype getter and therefore not serialised by
33
- * `JSON.stringify` automatically — it is extracted explicitly.
34
- *
35
- * Delegates to `instanceToSerializable` (from decorators.ts) which strips
36
- * all non-decorator-registered fields — including the runtime-enumerable
37
- * TypeScript `private _perspective` that would otherwise cause
38
- * `JSON.stringify` to throw a circular-reference error via
39
- * PerspectiveProxy → Apollo InMemoryCache.
40
- */
41
- function stableFingerprint(results) {
42
- const sorted = [...results].sort((a, b) => {
43
- const aId = a.id ?? "";
44
- const bId = b.id ?? "";
45
- return aId < bId ? -1 : aId > bId ? 1 : 0;
46
- });
47
- return JSON.stringify(sorted.map(instanceToSerializable));
48
- }
49
- const registry = new WeakMap();
50
- function getOrCreateSharedEntry(findAll, perspective, query, metadata, debounceMs, perspEntries, key) {
51
- const existing = perspEntries.get(key);
52
- if (existing)
53
- return existing;
54
- // Minimum coalesce window — even without a user-configured debounce, a
55
- // single save() emits several link events; this collapses them into one
56
- // findAll() call. Not a timing workaround — SurrealDB is guaranteed
57
- // committed before link-added events are published.
58
- const SETTLE_MS = 50;
59
- const effectiveDebounce = Math.max(debounceMs, SETTLE_MS);
60
- const watchedPredicates = new Set();
61
- for (const prop of Object.values(metadata.properties)) {
62
- if (prop.predicate)
63
- watchedPredicates.add(prop.predicate);
64
- }
65
- for (const rel of Object.values(metadata.relations)) {
66
- if (rel.predicate)
67
- watchedPredicates.add(rel.predicate);
68
- }
69
- // If the query is scoped to a parent via parent query, also watch the
70
- // parent-relationship predicate so that adding/removing a child link
71
- // triggers a live re-query even though it's not in the child model's schema.
72
- if (query.parent && 'predicate' in query.parent) {
73
- watchedPredicates.add(query.parent.predicate);
74
- }
75
- const entry = {
76
- listeners: new Map(),
77
- lastResults: null,
78
- lastFingerprint: null,
79
- debounceTimer: null,
80
- active: true,
81
- detach: () => { },
82
- };
83
- const broadcast = (results) => {
84
- for (const { callback, onError, setLastError, } of entry.listeners.values()) {
85
- try {
86
- callback(results);
87
- }
88
- catch (err) {
89
- setLastError(err);
90
- (onError ?? console.error)(err);
91
- }
92
- }
93
- };
94
- const notifyError = (err) => {
95
- for (const { onError, setLastError } of entry.listeners.values()) {
96
- setLastError(err);
97
- (onError ?? console.error)(err);
98
- }
99
- };
100
- const rerun = async () => {
101
- if (!entry.active)
102
- return;
103
- try {
104
- const results = await findAll(perspective, query);
105
- if (!entry.active)
106
- return;
107
- // Only broadcast if results actually changed.
108
- const fingerprint = stableFingerprint(results);
109
- if (fingerprint === entry.lastFingerprint)
110
- return;
111
- entry.lastFingerprint = fingerprint;
112
- entry.lastResults = results;
113
- broadcast(results);
114
- }
115
- catch (err) {
116
- notifyError(err);
117
- }
118
- };
119
- const scheduleRerun = () => {
120
- if (entry.debounceTimer !== null)
121
- clearTimeout(entry.debounceTimer);
122
- entry.debounceTimer = setTimeout(rerun, effectiveDebounce);
123
- };
124
- // LinkCallback must return null (see PerspectiveClient.ts type definition)
125
- const linkChangedCb = (link) => {
126
- if (watchedPredicates.has(link.data?.predicate ?? ""))
127
- scheduleRerun();
128
- return null;
129
- };
130
- perspective.addListener("link-added", linkChangedCb);
131
- perspective.addListener("link-removed", linkChangedCb);
132
- entry.detach = () => {
133
- // Fire-and-forget — removeListener is async but just does an array splice.
134
- // entry.active = false ensures no further callbacks fire regardless.
135
- perspective.removeListener("link-added", linkChangedCb);
136
- perspective.removeListener("link-removed", linkChangedCb);
137
- };
138
- // Fire immediately with initial results.
139
- rerun();
140
- perspEntries.set(key, entry);
141
- return entry;
142
- }
143
- // ─── Public API ───────────────────────────────────────────────────────────────
144
- /**
145
- * Creates a live subscription for a model query.
146
- *
147
- * Immediately invokes `callback` with the initial query results, then
148
- * re-invokes it whenever a relevant link is added to or removed from the
149
- * perspective.
150
- *
151
- * Multiple callers subscribing to the same model + query on the same
152
- * perspective share a single `findAll()` execution and a single pair of link
153
- * listeners via an internal registry. Callbacks are only fired when the
154
- * result set has actually changed.
155
- *
156
- * @param findAll - The model's `findAll` static method
157
- * @param getMetadata - The model's `getModelMetadata` static method
158
- * @param perspective - The perspective to watch
159
- * @param options - Query parameters + delivery options (debounce, onError)
160
- * @param callback - Invoked with fresh results on every relevant change
161
- * @returns A `Subscription` handle with `unsubscribe()` and `lastError`
162
- *
163
- * @example
164
- * ```typescript
165
- * const sub = createSubscription(
166
- * (p, q) => Post.findAll(p, q),
167
- * () => Post.getModelMetadata(),
168
- * perspective,
169
- * { where: { published: true }, debounce: 200 },
170
- * (posts) => console.log("Posts updated:", posts),
171
- * );
172
- *
173
- * // Later:
174
- * sub.unsubscribe();
175
- * ```
176
- */
177
- export function createSubscription(findAll, getMetadata, perspective, options, callback, ctor) {
178
- const { debounce: debounceMs = 0, onError, ...queryOptions } = options;
179
- // Normalise model-backed parent query to { id, predicate } before key
180
- // computation so the shared-entry registry and predicate watcher both
181
- // operate on the resolved string form.
182
- const rawParent = queryOptions.parent;
183
- const resolvedOptions = rawParent
184
- ? { ...queryOptions, parent: normalizeParentQuery(rawParent, ctor) }
185
- : queryOptions;
186
- const query = resolvedOptions;
187
- const metadata = getMetadata();
188
- const key = `${metadata.className}:${stableQueryKey(query)}`;
189
- let perspEntries = registry.get(perspective);
190
- if (!perspEntries) {
191
- perspEntries = new Map();
192
- registry.set(perspective, perspEntries);
193
- }
194
- const entry = getOrCreateSharedEntry(findAll, perspective, query, metadata, debounceMs, perspEntries, key);
195
- const listenerId = Symbol();
196
- let lastError = null;
197
- entry.listeners.set(listenerId, {
198
- callback: callback,
199
- onError,
200
- setLastError: (err) => {
201
- lastError = err;
202
- },
203
- });
204
- // Late subscriber: if the shared entry already ran at least once, fire
205
- // immediately with cached results — avoids an extra findAll() round-trip.
206
- if (entry.lastResults !== null) {
207
- const cached = entry.lastResults;
208
- Promise.resolve().then(() => {
209
- if (entry.listeners.has(listenerId))
210
- callback(cached);
211
- });
212
- }
213
- return {
214
- get lastError() {
215
- return lastError;
216
- },
217
- unsubscribe() {
218
- entry.listeners.delete(listenerId);
219
- if (entry.listeners.size === 0) {
220
- // Last subscriber — tear down the shared entry entirely.
221
- entry.active = false;
222
- if (entry.debounceTimer !== null) {
223
- clearTimeout(entry.debounceTimer);
224
- entry.debounceTimer = null;
225
- }
226
- entry.detach();
227
- perspEntries.delete(key);
228
- }
229
- },
230
- };
231
- }