@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
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Ad4mModel — barrel re-exports.
3
+ *
4
+ * All public symbols from the model subsystem are re-exported here so that
5
+ * consumers can import from `"./model"` (or `"@coasys/ad4m"` via the
6
+ * top-level barrel) without knowing the internal file layout.
7
+ */
8
+ export * from "./types";
9
+ export * from "./Ad4mModel";
10
+ export * from "./decorators";
11
+ export * from "./Subject";
12
+ export * from "./query-common";
13
+ export * from "./query-prolog";
14
+ export * from "./prolog-facts";
15
+ export * from "./json-schema";
16
+ export * from "./query-surreal";
17
+ export * from "./hydration";
18
+ export * from "./ModelQueryBuilder";
19
+ export * from "./sdna";
20
+ export * from "./shacl-gen";
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Ad4mModel — barrel re-exports.
3
+ *
4
+ * All public symbols from the model subsystem are re-exported here so that
5
+ * consumers can import from `"./model"` (or `"@coasys/ad4m"` via the
6
+ * top-level barrel) without knowing the internal file layout.
7
+ */
8
+ export * from "./types";
9
+ export * from "./Ad4mModel";
10
+ export * from "./decorators";
11
+ export * from "./Subject";
12
+ export * from "./query-common";
13
+ export * from "./query-prolog";
14
+ export * from "./prolog-facts";
15
+ export * from "./json-schema";
16
+ export * from "./query-surreal";
17
+ export * from "./hydration";
18
+ export * from "./ModelQueryBuilder";
19
+ export * from "./sdna";
20
+ export * from "./shacl-gen";
@@ -1,12 +1,16 @@
1
1
  /**
2
- * Dynamic model creation from JSON Schema.
2
+ * JSON Schema → Ad4mModel class builder and related utilities.
3
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.
4
+ * Contains:
5
+ * - JSON Schema type definitions (JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions)
6
+ * - Schema type helpers (normalizeNamespaceString, isArrayType, etc.)
7
+ * - Predicate / namespace resolution helpers
8
+ * - `buildModelFromJSONSchema()` — core implementation of `Ad4mModel.fromJSONSchema()`
9
+ *
10
+ * @module
8
11
  */
9
- import { PropertyOptions } from "../decorators";
12
+ import type { Ad4mModel } from "./Ad4mModel";
13
+ import type { PropertyOptions } from "./decorators";
10
14
  export interface JSONSchemaProperty {
11
15
  type: string | string[];
12
16
  items?: JSONSchemaProperty;
@@ -18,7 +22,7 @@ export interface JSONSchemaProperty {
18
22
  through?: string;
19
23
  resolveLanguage?: string;
20
24
  local?: boolean;
21
- readOnly?: boolean;
25
+ writable?: boolean;
22
26
  initial?: string;
23
27
  };
24
28
  }
@@ -52,16 +56,45 @@ export declare function isSchemaType(schema: JSONSchemaProperty, expectedType: s
52
56
  export declare function isArrayType(schema: JSONSchemaProperty): boolean;
53
57
  export declare function isObjectType(schema: JSONSchemaProperty): boolean;
54
58
  export declare function isNumericType(schema: JSONSchemaProperty): boolean;
59
+ /**
60
+ * Determines the namespace for predicates using cascading precedence:
61
+ * 1. Explicit namespace in options
62
+ * 2. x-ad4m metadata in schema
63
+ * 3. Infer from schema title
64
+ * 4. Try to extract from $id
65
+ * 5. Error if nothing works
66
+ */
55
67
  export declare function determineNamespace(schema: JSONSchema, options: JSONSchemaToModelOptions): string;
68
+ /**
69
+ * Determines the predicate for a specific property using cascading precedence:
70
+ * 1. Explicit property mapping
71
+ * 2. x-ad4m metadata in property schema
72
+ * 3. Predicate template
73
+ * 4. Custom predicate generator
74
+ * 5. Default: namespace + property name
75
+ */
56
76
  export declare function determinePredicate(schema: JSONSchema, propertyName: string, propertySchema: JSONSchemaProperty, namespace: string, options: JSONSchemaToModelOptions): string;
77
+ /**
78
+ * Gets property-specific options using cascading precedence:
79
+ * 1. Property-specific options
80
+ * 2. x-ad4m metadata in property
81
+ * 3. Global option
82
+ * 4. Default value
83
+ */
57
84
  export declare function getPropertyOption(propertyName: string, propertySchema: JSONSchemaProperty, options: JSONSchemaToModelOptions, optionName: keyof PropertyOptions, defaultValue?: any): any;
85
+ /**
86
+ * Gets default value for a JSON Schema type.
87
+ */
58
88
  export declare function getDefaultValueForType(type?: string): any;
59
89
  /**
60
- * Creates an Ad4mModel subclass dynamically from a JSON Schema definition.
90
+ * Core implementation of `Ad4mModel.fromJSONSchema()`.
61
91
  *
62
- * Takes `BaseClass` as a parameter (rather than importing `Ad4mModel` directly)
63
- * to avoid a circular dependency between this module and `Ad4mModel.ts`.
92
+ * Creates a dynamic Ad4mModel subclass from a JSON Schema definition,
93
+ * wiring up property / relation metadata, setters, and the `@Model` decorator.
64
94
  *
65
- * `Ad4mModel.fromJSONSchema()` is a thin wrapper that calls this with `this`.
95
+ * @param BaseClass - The Ad4mModel class (or subclass) to extend
96
+ * @param schema - JSON Schema definition
97
+ * @param options - Configuration options
98
+ * @returns Generated Ad4mModel subclass
66
99
  */
67
- export declare function createModelFromJSONSchema(BaseClass: any, schema: JSONSchema, options: JSONSchemaToModelOptions): any;
100
+ export declare function buildModelFromJSONSchema(BaseClass: typeof Ad4mModel, schema: JSONSchema, options: JSONSchemaToModelOptions): typeof Ad4mModel;
@@ -0,0 +1,326 @@
1
+ /**
2
+ * JSON Schema → Ad4mModel class builder and related utilities.
3
+ *
4
+ * Contains:
5
+ * - JSON Schema type definitions (JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions)
6
+ * - Schema type helpers (normalizeNamespaceString, isArrayType, etc.)
7
+ * - Predicate / namespace resolution helpers
8
+ * - `buildModelFromJSONSchema()` — core implementation of `Ad4mModel.fromJSONSchema()`
9
+ *
10
+ * @module
11
+ */
12
+ import { capitalize, propertyNameToSetterName } from "./util";
13
+ import { Model, setPropertyRegistryEntry, setRelationRegistryEntry } from "./decorators";
14
+ // ─── Schema Type Helpers ─────────────────────────────────────────────────────
15
+ export function normalizeNamespaceString(namespace) {
16
+ if (!namespace)
17
+ return '';
18
+ if (namespace.includes('://')) {
19
+ const [scheme, rest] = namespace.split('://');
20
+ const path = (rest || '').replace(/\/+$/, '');
21
+ return `${scheme}://${path}`;
22
+ }
23
+ else {
24
+ return namespace.replace(/\/+$/, '');
25
+ }
26
+ }
27
+ export function normalizeSchemaType(type) {
28
+ if (!type)
29
+ return undefined;
30
+ if (typeof type === "string")
31
+ return type;
32
+ if (Array.isArray(type) && type.length > 0) {
33
+ const nonNull = type.find((t) => t !== "null");
34
+ return nonNull || type[0];
35
+ }
36
+ return undefined;
37
+ }
38
+ export function isSchemaType(schema, expectedType) {
39
+ return normalizeSchemaType(schema.type) === expectedType;
40
+ }
41
+ export function isArrayType(schema) {
42
+ return isSchemaType(schema, "array");
43
+ }
44
+ export function isObjectType(schema) {
45
+ return isSchemaType(schema, "object");
46
+ }
47
+ export function isNumericType(schema) {
48
+ const normalized = normalizeSchemaType(schema.type);
49
+ return normalized === "number" || normalized === "integer";
50
+ }
51
+ // ─── Predicate / Namespace Resolution ────────────────────────────────────────
52
+ /**
53
+ * Determines the namespace for predicates using cascading precedence:
54
+ * 1. Explicit namespace in options
55
+ * 2. x-ad4m metadata in schema
56
+ * 3. Infer from schema title
57
+ * 4. Try to extract from $id
58
+ * 5. Error if nothing works
59
+ */
60
+ export function determineNamespace(schema, options) {
61
+ // 1. Explicit namespace in options (highest precedence)
62
+ if (options.namespace) {
63
+ return options.namespace;
64
+ }
65
+ // 2. x-ad4m metadata in schema
66
+ if (schema["x-ad4m"]?.namespace) {
67
+ return schema["x-ad4m"].namespace;
68
+ }
69
+ // 3. Infer from schema title
70
+ if (schema.title) {
71
+ return `${schema.title.toLowerCase()}://`;
72
+ }
73
+ // 4. Try to extract from $id if it's a URL
74
+ if (schema.$id) {
75
+ try {
76
+ const url = new URL(schema.$id);
77
+ const pathParts = url.pathname.split('/').filter(p => p);
78
+ if (pathParts.length > 0) {
79
+ const lastPart = pathParts[pathParts.length - 1];
80
+ const baseName = lastPart.replace(/\.schema\.json$/, '').replace(/\.json$/, '');
81
+ return `${baseName.toLowerCase()}://`;
82
+ }
83
+ }
84
+ catch {
85
+ // If $id is not a valid URL, continue to error
86
+ }
87
+ }
88
+ // 5. Error if no namespace can be determined
89
+ throw new Error(`Cannot infer namespace for JSON Schema. Please provide one of:
90
+ - options.namespace
91
+ - schema["x-ad4m"].namespace
92
+ - schema.title
93
+ - valid schema.$id`);
94
+ }
95
+ /**
96
+ * Determines the predicate for a specific property using cascading precedence:
97
+ * 1. Explicit property mapping
98
+ * 2. x-ad4m metadata in property schema
99
+ * 3. Predicate template
100
+ * 4. Custom predicate generator
101
+ * 5. Default: namespace + property name
102
+ */
103
+ export function determinePredicate(schema, propertyName, propertySchema, namespace, options) {
104
+ // 1. Explicit property mapping (highest precedence)
105
+ if (options.propertyMapping?.[propertyName]) {
106
+ return options.propertyMapping[propertyName];
107
+ }
108
+ // 2. x-ad4m metadata in property schema
109
+ if (propertySchema["x-ad4m"]?.through) {
110
+ return propertySchema["x-ad4m"].through;
111
+ }
112
+ // 3. Generate from namespace + property name
113
+ if (options.predicateTemplate) {
114
+ const normalizedNs = normalizeNamespaceString(namespace);
115
+ const [scheme, rest] = normalizedNs.includes('://') ? normalizedNs.split('://') : ['', normalizedNs];
116
+ const nsNoScheme = rest || '';
117
+ return options.predicateTemplate
118
+ .replace('${namespace}', nsNoScheme)
119
+ .replace('${scheme}', scheme)
120
+ .replace('${ns}', nsNoScheme)
121
+ .replace('${title}', schema.title || '')
122
+ .replace('${property}', propertyName);
123
+ }
124
+ // 4. Custom predicate generator
125
+ if (options.predicateGenerator) {
126
+ return options.predicateGenerator(schema.title || '', propertyName);
127
+ }
128
+ // 5. Default: namespace + property name
129
+ const normalizedNs = normalizeNamespaceString(namespace);
130
+ if (normalizedNs.includes('://')) {
131
+ // For namespaces like "product://", append property directly
132
+ return `${normalizedNs}${propertyName}`;
133
+ }
134
+ else {
135
+ return `${normalizedNs}://${propertyName}`;
136
+ }
137
+ }
138
+ /**
139
+ * Gets property-specific options using cascading precedence:
140
+ * 1. Property-specific options
141
+ * 2. x-ad4m metadata in property
142
+ * 3. Global option
143
+ * 4. Default value
144
+ */
145
+ export function getPropertyOption(propertyName, propertySchema, options, optionName, defaultValue) {
146
+ // 1. Property-specific options
147
+ if (options.propertyOptions?.[propertyName]?.[optionName] !== undefined) {
148
+ return options.propertyOptions[propertyName][optionName];
149
+ }
150
+ // 2. x-ad4m metadata in property
151
+ if (propertySchema["x-ad4m"]?.[optionName] !== undefined) {
152
+ return propertySchema["x-ad4m"][optionName];
153
+ }
154
+ // 3. Global option
155
+ if (options[optionName] !== undefined) {
156
+ return options[optionName];
157
+ }
158
+ // 4. Default value
159
+ return defaultValue;
160
+ }
161
+ /**
162
+ * Gets default value for a JSON Schema type.
163
+ */
164
+ export function getDefaultValueForType(type) {
165
+ switch (type) {
166
+ case 'string': return '';
167
+ case 'number': return 0;
168
+ case 'integer': return 0;
169
+ case 'boolean': return false;
170
+ case 'array': return [];
171
+ case 'object': return {};
172
+ default: return '';
173
+ }
174
+ }
175
+ // ─── buildModelFromJSONSchema ────────────────────────────────────────────────
176
+ /**
177
+ * Core implementation of `Ad4mModel.fromJSONSchema()`.
178
+ *
179
+ * Creates a dynamic Ad4mModel subclass from a JSON Schema definition,
180
+ * wiring up property / relation metadata, setters, and the `@Model` decorator.
181
+ *
182
+ * @param BaseClass - The Ad4mModel class (or subclass) to extend
183
+ * @param schema - JSON Schema definition
184
+ * @param options - Configuration options
185
+ * @returns Generated Ad4mModel subclass
186
+ */
187
+ export function buildModelFromJSONSchema(BaseClass, schema, options) {
188
+ // Disallow top-level "author" property since Ad4mModel provides it implicitly via link authorship
189
+ if (schema?.properties && Object.prototype.hasOwnProperty.call(schema.properties, "author")) {
190
+ 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").');
191
+ }
192
+ // Determine namespace with cascading precedence
193
+ const namespace = determineNamespace(schema, options);
194
+ // Create the dynamic class
195
+ const DynamicModelClass = class extends BaseClass {
196
+ };
197
+ // Set up class metadata
198
+ if (!options.name || options.name.trim() === '') {
199
+ throw new Error("options.name is required and cannot be empty");
200
+ }
201
+ DynamicModelClass.className = options.name;
202
+ DynamicModelClass.prototype.className = options.name;
203
+ // Generate properties and relations metadata
204
+ const properties = {};
205
+ const relations = {};
206
+ if (schema.properties) {
207
+ for (const [propertyName, propertySchema] of Object.entries(schema.properties)) {
208
+ const predicate = determinePredicate(schema, propertyName, propertySchema, namespace, options);
209
+ const isRequired = schema.required?.includes(propertyName) || false;
210
+ const propertyType = normalizeSchemaType(propertySchema.type);
211
+ const isArray = isArrayType(propertySchema);
212
+ if (isArray) {
213
+ // Handle arrays as relations
214
+ // Store the singular form as the relation key since SDNA generation expects singular
215
+ relations[propertyName] = {
216
+ through: predicate,
217
+ local: getPropertyOption(propertyName, propertySchema, options, 'local')
218
+ };
219
+ // Define the property on prototype
220
+ Object.defineProperty(DynamicModelClass.prototype, propertyName, {
221
+ configurable: true,
222
+ writable: true,
223
+ value: []
224
+ });
225
+ // Add relation methods
226
+ const adderName = `add${capitalize(propertyName)}`;
227
+ const removerName = `remove${capitalize(propertyName)}`;
228
+ const setterName = `set${capitalize(propertyName)}`;
229
+ DynamicModelClass.prototype[adderName] = function () {
230
+ // Placeholder function for SDNA generation
231
+ };
232
+ DynamicModelClass.prototype[removerName] = function () {
233
+ // Placeholder function for SDNA generation
234
+ };
235
+ DynamicModelClass.prototype[setterName] = function () {
236
+ // Placeholder function for SDNA generation
237
+ };
238
+ }
239
+ else {
240
+ // Handle regular properties
241
+ let resolveLanguage = getPropertyOption(propertyName, propertySchema, options, 'resolveLanguage');
242
+ // If no specific resolveLanguage for this property, use the global one
243
+ if (!resolveLanguage && options.resolveLanguage) {
244
+ resolveLanguage = options.resolveLanguage;
245
+ }
246
+ const local = getPropertyOption(propertyName, propertySchema, options, 'local');
247
+ // Determine readOnly: check PropertyOptions first, then x-ad4m.writable (inverted) for JSON Schema wire format
248
+ let readOnly = getPropertyOption(propertyName, propertySchema, options, 'readOnly');
249
+ if (readOnly === undefined) {
250
+ const xWritable = propertySchema["x-ad4m"]?.writable;
251
+ readOnly = xWritable !== undefined ? !xWritable : false;
252
+ }
253
+ const writable = !readOnly;
254
+ let initial = getPropertyOption(propertyName, propertySchema, options, 'initial');
255
+ // Handle nested objects by serializing to JSON
256
+ if (isObjectType(propertySchema) && !resolveLanguage) {
257
+ resolveLanguage = 'literal';
258
+ console.warn(`Property "${propertyName}" is an object type. It will be stored as JSON. Consider flattening complex objects for better semantic querying.`);
259
+ }
260
+ // Ensure numeric properties use literal language for correct typing
261
+ if ((resolveLanguage === undefined || resolveLanguage === null) && isNumericType(propertySchema)) {
262
+ resolveLanguage = 'literal';
263
+ }
264
+ // Default resolveLanguage to 'literal' for all remaining property types,
265
+ // matching the @Property decorator behaviour. Without this, string values
266
+ // stored as literal:// URLs are returned unparsed.
267
+ if (resolveLanguage === undefined || resolveLanguage === null) {
268
+ resolveLanguage = 'literal';
269
+ }
270
+ // If property is required, ensure it has an initial value
271
+ if (isRequired && !initial) {
272
+ if (isObjectType(propertySchema)) {
273
+ initial = 'literal://json:{}';
274
+ }
275
+ else {
276
+ initial = "ad4m://undefined";
277
+ }
278
+ }
279
+ properties[propertyName] = {
280
+ through: predicate,
281
+ required: isRequired,
282
+ writable: writable,
283
+ ...(resolveLanguage && { resolveLanguage }),
284
+ ...(local !== undefined && { local }),
285
+ ...(initial && { initial })
286
+ };
287
+ // Define the property on prototype
288
+ Object.defineProperty(DynamicModelClass.prototype, propertyName, {
289
+ configurable: true,
290
+ writable: true,
291
+ value: getDefaultValueForType(propertyType)
292
+ });
293
+ // Add setter function if writable
294
+ if (writable) {
295
+ const setterName = propertyNameToSetterName(propertyName);
296
+ DynamicModelClass.prototype[setterName] = function () {
297
+ // This is a placeholder function that the SDNA generation looks for
298
+ // The actual setter logic is handled by the Ad4mModel base class
299
+ };
300
+ }
301
+ }
302
+ }
303
+ }
304
+ // No auto-flag generation — models with all-optional properties use
305
+ // open-world structural matching. Consumers who need type discrimination
306
+ // should add an explicit @Flag to their model definition.
307
+ // Attach metadata to WeakMap registries
308
+ for (const [propName, propMeta] of Object.entries(properties)) {
309
+ setPropertyRegistryEntry(DynamicModelClass, propName, propMeta);
310
+ }
311
+ for (const [relName, relMeta] of Object.entries(relations)) {
312
+ setRelationRegistryEntry(DynamicModelClass, relName, {
313
+ predicate: relMeta.through || "",
314
+ kind: 'hasMany',
315
+ ...(relMeta.getter !== undefined && { getter: relMeta.getter }),
316
+ ...(relMeta.local !== undefined && { local: relMeta.local }),
317
+ });
318
+ }
319
+ // Store the JSON schema and options on the prototype for potential fallback use by getModelMetadata()
320
+ DynamicModelClass.prototype.__jsonSchema = schema;
321
+ DynamicModelClass.prototype.__jsonSchemaOptions = options;
322
+ // Apply the Model decorator to set up the generateSDNA method
323
+ const ModelDecorator = Model({ name: options.name });
324
+ ModelDecorator(DynamicModelClass);
325
+ return DynamicModelClass;
326
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Standalone Prolog fact generator for Ad4mModel classes.
3
+ *
4
+ * Converts decorator metadata into Prolog clauses that can be prepended to
5
+ * `perspective.infer()` calls, enabling custom Prolog rules to reference
6
+ * model instances and their fields.
7
+ */
8
+ import type { Ad4mModel } from "./Ad4mModel";
9
+ /**
10
+ * Generate Prolog predicate facts from a model class's decorator metadata.
11
+ *
12
+ * Given a model class decorated with `@Model` (and its `@Flag`, `@Property`,
13
+ * `@HasMany`, `@BelongsToMany` decorators), this function emits a string of
14
+ * Prolog clauses that can be prepended to any `perspective.infer()` call.
15
+ *
16
+ * The generated predicates are:
17
+ * - **Instance recognizer** — `modelName(X)` — matches instances of the model
18
+ * - **Property getters** — `modelName_propName(X, Value)` — one per property
19
+ * - **Relation getters** — `modelName_relName(X, Values)` — one per relation
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * import { generatePrologFacts } from '@coasys/ad4m';
24
+ *
25
+ * const facts = generatePrologFacts(Poll);
26
+ * const result = await perspective.infer(\`
27
+ * \${facts}
28
+ * recent_popular_poll(X) :-
29
+ * poll(X),
30
+ * poll_vote_count(X, N), N > 10.
31
+ * \`);
32
+ * ```
33
+ *
34
+ * @param ModelClass - A class decorated with `@Model` that extends `Ad4mModel`
35
+ * @returns A multi-line Prolog string ready for use with `perspective.infer()`
36
+ */
37
+ export declare function generatePrologFacts(ModelClass: typeof Ad4mModel): string;
@@ -1,3 +1,11 @@
1
+ /**
2
+ * Standalone Prolog fact generator for Ad4mModel classes.
3
+ *
4
+ * Converts decorator metadata into Prolog clauses that can be prepended to
5
+ * `perspective.infer()` calls, enabling custom Prolog rules to reference
6
+ * model instances and their fields.
7
+ */
8
+ // ── Helpers ──────────────────────────────────────────────────────────────────
1
9
  /**
2
10
  * Convert a camelCase or PascalCase identifier to snake_case.
3
11
  * Examples: "TestPost" -> "test_post", "createdAt" -> "created_at"
@@ -8,17 +16,6 @@ function toSnakeCase(str) {
8
16
  .toLowerCase()
9
17
  .replace(/^_/, "");
10
18
  }
11
- /**
12
- * Build the instance recognizer clause for a model.
13
- *
14
- * Uses @Flag properties (fixed-value predicates) as the primary recognition
15
- * strategy, since they uniquely identify the type in the graph. Falls back to
16
- * required properties if no flags are present.
17
- *
18
- * Examples:
19
- * poll(X) :- triple(X, 'flux://entry_type', 'flux://has_poll').
20
- * note(X) :- triple(X, 'ad4m://title', _).
21
- */
22
19
  function buildInstanceClause(predicateName, metadata) {
23
20
  const props = metadata.properties;
24
21
  // Collect flags first — these are the strongest recognizers
@@ -37,72 +34,70 @@ function buildInstanceClause(predicateName, metadata) {
37
34
  .join(",\n ");
38
35
  return `${predicateName}(X) :-\n ${conditions}.`;
39
36
  }
37
+ // Open-world structural fallback: match nodes that have at least one of the
38
+ // model's declared property predicates. Uses disjunction (;) so any single
39
+ // predicate is enough.
40
+ const allPredicates = Object.values(props)
41
+ .filter((p) => p.predicate)
42
+ .map((p) => p.predicate);
43
+ if (metadata.relations) {
44
+ for (const rel of Object.values(metadata.relations)) {
45
+ if (rel.predicate)
46
+ allPredicates.push(rel.predicate);
47
+ }
48
+ }
49
+ if (allPredicates.length > 0) {
50
+ const disjunction = allPredicates
51
+ .map((pred) => `triple(X, '${pred}', _)`)
52
+ .join(" ;\n ");
53
+ return `${predicateName}(X) :-\n (${disjunction}).`;
54
+ }
40
55
  return null;
41
56
  }
42
- /**
43
- * Build a property getter clause for a single property.
44
- *
45
- * Example:
46
- * poll_title(X, Value) :- triple(X, 'rdf://title', Value).
47
- */
48
57
  function buildPropertyClause(modelPredicateName, prop) {
49
- // Flags are handled by the instance clause, not individual getters
50
58
  if (prop.flag)
51
59
  return null;
52
- // No predicate = no clause
53
60
  if (!prop.predicate)
54
61
  return null;
55
62
  const clauseName = `${modelPredicateName}_${toSnakeCase(prop.name)}`;
56
63
  return `${clauseName}(X, Value) :- triple(X, '${prop.predicate}', Value).`;
57
64
  }
58
- /**
59
- * Build a collection getter clause.
60
- *
61
- * Forward relations (@HasMany / @HasOne):
62
- * poll_entries(X, Values) :- findall(V, triple(X, 'flux://entry', V), Values).
63
- *
64
- * Reverse relations (@BelongsToMany / @BelongsToOne):
65
- * The link points TO this instance (OtherNode → predicate → ThisNode), so
66
- * the subject and object are swapped:
67
- * test_tag_posts(X, Values) :- findall(V, triple(V, 'test://has_tag', X), Values).
68
- */
69
- function buildCollectionClause(modelPredicateName, coll) {
70
- if (!coll.predicate)
65
+ function buildRelationClause(modelPredicateName, relation) {
66
+ if (!relation.predicate)
71
67
  return null;
72
- const clauseName = `${modelPredicateName}_${toSnakeCase(coll.name)}`;
73
- if (coll.direction === "reverse") {
74
- // Reverse traversal: find nodes whose outgoing predicate link points to X
75
- return `${clauseName}(X, Values) :- findall(V, triple(V, '${coll.predicate}', X), Values).`;
68
+ const clauseName = `${modelPredicateName}_${toSnakeCase(relation.name)}`;
69
+ if (relation.direction === "reverse") {
70
+ return `${clauseName}(X, Values) :- findall(V, triple(V, '${relation.predicate}', X), Values).`;
76
71
  }
77
- return `${clauseName}(X, Values) :- findall(V, triple(X, '${coll.predicate}', V), Values).`;
72
+ return `${clauseName}(X, Values) :- findall(V, triple(X, '${relation.predicate}', V), Values).`;
78
73
  }
74
+ // ── Public API ───────────────────────────────────────────────────────────────
79
75
  /**
80
- * Generate Prolog predicate facts from a model class's SHACL metadata.
76
+ * Generate Prolog predicate facts from a model class's decorator metadata.
81
77
  *
82
- * Given a model class decorated with `@ModelOptions` (and its `@Flag`,
83
- * `@Property`, `@Collection` decorators), this function emits a string of
78
+ * Given a model class decorated with `@Model` (and its `@Flag`, `@Property`,
79
+ * `@HasMany`, `@BelongsToMany` decorators), this function emits a string of
84
80
  * Prolog clauses that can be prepended to any `perspective.infer()` call.
85
81
  *
86
82
  * The generated predicates are:
87
83
  * - **Instance recognizer** — `modelName(X)` — matches instances of the model
88
84
  * - **Property getters** — `modelName_propName(X, Value)` — one per property
89
- * - **Collection getters** — `modelName_collName(X, Values)` — one per collection
85
+ * - **Relation getters** — `modelName_relName(X, Values)` — one per relation
90
86
  *
91
87
  * @example
92
88
  * ```typescript
93
- * import { generatePrologFacts } from '@coasys/ad4m/model/prolog';
89
+ * import { generatePrologFacts } from '@coasys/ad4m';
94
90
  *
95
91
  * const facts = generatePrologFacts(Poll);
96
- * const result = await perspective.infer(`
97
- * ${facts}
92
+ * const result = await perspective.infer(\`
93
+ * \${facts}
98
94
  * recent_popular_poll(X) :-
99
95
  * poll(X),
100
- * poll_vote_count(X, N), N > 10,
101
- * poll_created_at(X, T), T > ${yesterday}.
102
- * `);
96
+ * poll_vote_count(X, N), N > 10.
97
+ * \`);
103
98
  * ```
104
99
  *
105
- * @param ModelClass - A class decorated with `@ModelOptions` that extends `Ad4mModel`
100
+ * @param ModelClass - A class decorated with `@Model` that extends `Ad4mModel`
106
101
  * @returns A multi-line Prolog string ready for use with `perspective.infer()`
107
102
  */
108
103
  export function generatePrologFacts(ModelClass) {
@@ -127,13 +122,13 @@ export function generatePrologFacts(ModelClass) {
127
122
  lines.push(...propClauses);
128
123
  }
129
124
  // Relation getters
130
- const collClauses = Object.values(metadata.relations)
131
- .map((c) => buildCollectionClause(predicateName, c))
125
+ const relClauses = Object.values(metadata.relations)
126
+ .map((c) => buildRelationClause(predicateName, c))
132
127
  .filter((c) => c !== null);
133
- if (collClauses.length > 0) {
128
+ if (relClauses.length > 0) {
134
129
  lines.push("");
135
130
  lines.push(`% Relation getters`);
136
- lines.push(...collClauses);
131
+ lines.push(...relClauses);
137
132
  }
138
133
  return lines.join("\n");
139
134
  }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Shared query helpers used by both the Prolog and SurrealQL query pipelines.
3
+ */
4
+ import type { ParentScope } from "./types";
5
+ /**
6
+ * Resolves the predicate for a parent query.
7
+ *
8
+ * Uses TS discriminated union narrowing:
9
+ * - Raw form (`{ id, predicate }`) → predicate used as-is
10
+ * - Model form (`{ model, id, field? }`) → lookup from relation metadata
11
+ * - With `field`: direct key lookup
12
+ * - Without `field`: scan for a relation whose `target()` matches `childCtor`
13
+ */
14
+ export declare function resolveParentPredicate(parent: ParentScope, childCtor: Function): string;