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

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 (128) hide show
  1. package/jest.config.js +4 -4
  2. package/lib/index.cjs +5999 -6044
  3. package/lib/index.js +5977 -6038
  4. package/lib/src/Ad4mClient.d.ts +16 -9
  5. package/lib/src/Ad4mClient.js +25 -46
  6. package/lib/src/Ad4mClient.test.d.ts +1 -0
  7. package/lib/src/Ad4mClient.test.js +1204 -0
  8. package/lib/src/Literal.d.ts +2 -1
  9. package/lib/src/Literal.js +35 -38
  10. package/lib/src/Literal.test.d.ts +1 -0
  11. package/lib/src/Literal.test.js +41 -0
  12. package/lib/src/SmartLiteral.d.ts +2 -1
  13. package/lib/src/SmartLiteral.js +15 -30
  14. package/lib/src/agent/AgentClient.d.ts +4 -1
  15. package/lib/src/agent/AgentClient.js +99 -79
  16. package/lib/src/ai/AIClient.d.ts +2 -1
  17. package/lib/src/ai/AIClient.js +220 -224
  18. package/lib/src/expression/ExpressionClient.d.ts +1 -1
  19. package/lib/src/expression/ExpressionClient.js +86 -73
  20. package/lib/src/index.d.ts +1 -1
  21. package/lib/src/index.js +1 -1
  22. package/lib/src/language/LanguageClient.d.ts +1 -1
  23. package/lib/src/language/LanguageClient.js +52 -52
  24. package/lib/src/model/Ad4mModel.d.ts +157 -937
  25. package/lib/src/model/Ad4mModel.js +212 -2797
  26. package/lib/src/model/Ad4mModel.test.js +1002 -561
  27. package/lib/src/model/decorators.d.ts +94 -426
  28. package/lib/src/model/decorators.js +333 -741
  29. package/lib/src/model/mutation.d.ts +81 -0
  30. package/lib/src/model/mutation.js +317 -0
  31. package/lib/src/model/parentUtils.d.ts +32 -0
  32. package/lib/src/model/parentUtils.js +64 -0
  33. package/lib/src/model/prolog/generatePrologFacts.d.ts +36 -0
  34. package/lib/src/model/prolog/generatePrologFacts.js +139 -0
  35. package/lib/src/model/prolog/index.d.ts +1 -0
  36. package/lib/src/model/prolog/index.js +1 -0
  37. package/lib/src/model/query/ModelQueryBuilder.d.ts +82 -0
  38. package/lib/src/model/query/ModelQueryBuilder.js +115 -0
  39. package/lib/src/model/query/QueryBuilder.d.ts +101 -0
  40. package/lib/src/model/query/QueryBuilder.js +193 -0
  41. package/lib/src/model/query/SurrealQueryBuilder.d.ts +48 -0
  42. package/lib/src/model/query/SurrealQueryBuilder.js +371 -0
  43. package/lib/src/model/query/fetchInstance.d.ts +24 -0
  44. package/lib/src/model/query/fetchInstance.js +144 -0
  45. package/lib/src/model/query/hydration.d.ts +54 -0
  46. package/lib/src/model/query/hydration.js +214 -0
  47. package/lib/src/model/query/operations.d.ts +59 -0
  48. package/lib/src/model/query/operations.js +384 -0
  49. package/lib/src/model/query/snapshot.d.ts +59 -0
  50. package/lib/src/model/query/snapshot.js +106 -0
  51. package/lib/src/model/query/surrealCompiler.d.ts +42 -0
  52. package/lib/src/model/query/surrealCompiler.js +304 -0
  53. package/lib/src/model/schema/fromJSONSchema.d.ts +67 -0
  54. package/lib/src/model/schema/fromJSONSchema.js +264 -0
  55. package/lib/src/model/schema/metadata.d.ts +15 -0
  56. package/lib/src/model/schema/metadata.js +112 -0
  57. package/lib/src/model/subscription.d.ts +47 -0
  58. package/lib/src/model/subscription.js +231 -0
  59. package/lib/src/model/transaction.d.ts +27 -0
  60. package/lib/src/model/transaction.js +32 -0
  61. package/lib/src/model/types.d.ts +195 -0
  62. package/lib/src/model/types.js +8 -0
  63. package/lib/src/model/util.js +7 -7
  64. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +5 -1
  65. package/lib/src/neighbourhood/NeighbourhoodClient.js +263 -181
  66. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +2 -1
  67. package/lib/src/neighbourhood/NeighbourhoodProxy.js +13 -28
  68. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +1 -5
  69. package/lib/src/perspectives/PerspectiveClient.d.ts +9 -9
  70. package/lib/src/perspectives/PerspectiveClient.js +316 -240
  71. package/lib/src/perspectives/PerspectiveProxy.d.ts +54 -92
  72. package/lib/src/perspectives/PerspectiveProxy.js +803 -444
  73. package/lib/src/runtime/RuntimeClient.d.ts +5 -1
  74. package/lib/src/runtime/RuntimeClient.js +412 -238
  75. package/lib/src/shacl/SHACLFlow.test.js +164 -105
  76. package/lib/src/shacl/SHACLShape.d.ts +17 -3
  77. package/lib/src/shacl/SHACLShape.js +127 -90
  78. package/lib/src/shacl/SHACLShape.test.js +244 -176
  79. package/lib/src/utils.d.ts +8 -0
  80. package/lib/src/utils.js +21 -7
  81. package/package.json +8 -13
  82. package/src/Ad4mClient.test.ts +1564 -1315
  83. package/src/Ad4mClient.ts +55 -54
  84. package/src/Literal.test.ts +45 -26
  85. package/src/Literal.ts +82 -66
  86. package/src/SmartLiteral.ts +74 -58
  87. package/src/agent/AgentClient.ts +144 -99
  88. package/src/ai/AIClient.ts +409 -359
  89. package/src/expression/ExpressionClient.ts +142 -96
  90. package/src/index.ts +1 -1
  91. package/src/language/LanguageClient.ts +137 -113
  92. package/src/model/Ad4mModel.test.ts +1128 -647
  93. package/src/model/Ad4mModel.ts +485 -3247
  94. package/src/model/IMPROVEMENTS.md +482 -0
  95. package/src/model/PREDICATE_COLLISION_FIX.md +651 -0
  96. package/src/model/README.md +317 -0
  97. package/src/model/SHACL_MUTATION_DECOUPLING.md +356 -0
  98. package/src/model/SUBSCRIPTION_STRATEGY.md +317 -0
  99. package/src/model/TC39_STAGE_3_DECORATORS.md +609 -0
  100. package/src/model/decorators.ts +689 -1046
  101. package/src/model/mutation.ts +461 -0
  102. package/src/model/parentUtils.ts +91 -0
  103. package/src/model/prolog/generatePrologFacts.ts +176 -0
  104. package/src/model/prolog/index.ts +1 -0
  105. package/src/model/query/ModelQueryBuilder.ts +173 -0
  106. package/src/model/query/fetchInstance.ts +181 -0
  107. package/src/model/query/hydration.ts +273 -0
  108. package/src/model/query/operations.ts +510 -0
  109. package/src/model/query/snapshot.ts +126 -0
  110. package/src/model/query/surrealCompiler.ts +376 -0
  111. package/src/model/schema/fromJSONSchema.ts +411 -0
  112. package/src/model/schema/metadata.ts +148 -0
  113. package/src/model/subscription.ts +307 -0
  114. package/src/model/transaction.ts +60 -0
  115. package/src/model/types.ts +207 -0
  116. package/src/model/util.ts +47 -48
  117. package/src/neighbourhood/NeighbourhoodClient.ts +393 -251
  118. package/src/neighbourhood/NeighbourhoodProxy.test.ts +3 -7
  119. package/src/neighbourhood/NeighbourhoodProxy.ts +58 -40
  120. package/src/perspectives/PerspectiveClient.ts +779 -540
  121. package/src/perspectives/PerspectiveProxy.ts +2860 -2053
  122. package/src/runtime/RuntimeClient.ts +775 -476
  123. package/src/shacl/SHACLFlow.test.ts +196 -129
  124. package/src/shacl/SHACLShape.test.ts +284 -190
  125. package/src/shacl/SHACLShape.ts +225 -172
  126. package/src/utils.ts +31 -17
  127. package/tsconfig.json +9 -10
  128. package/src/model/Subject.ts +0 -159
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Dirty-tracking snapshot registry for Ad4mModel instances.
3
+ *
4
+ * A lightweight WeakMap-based store that records the schema-declared field
5
+ * values of an instance immediately after hydration or save. `innerUpdate`
6
+ * consults this snapshot to skip writing fields that haven't changed since the
7
+ * last successful persist, preventing the "re-save duplicates relations" bug.
8
+ *
9
+ * ## Design notes
10
+ *
11
+ * - A **WeakMap** is used so snapshot entries are GC'd when the instance is
12
+ * collected — no manual cleanup needed.
13
+ * - Arrays are normalised to `string[]` on capture (model instances → their ID
14
+ * URI) so the comparison is stable regardless of whether `include` hydration
15
+ * was used.
16
+ * - There is **no snapshot** for a freshly constructed instance that has never
17
+ * been hydrated or saved. `isDirty` returns `true` in that case, preserving
18
+ * existing create-path behaviour (write everything).
19
+ * - Only Tier-1 saves (no caller-provided `batchId`) trigger a post-save
20
+ * rehydration via `fetchInstanceData`, which re-captures the snapshot. Tier-2
21
+ * / Tier-3 (caller-managed batch / `transaction()`) skip rehydration by
22
+ * design; fields that were not changed may be re-sent on the next Tier-1
23
+ * save, which is idempotent and acceptable.
24
+ */
25
+ type SnapshotEntry = Record<string, any>;
26
+ /**
27
+ * Records the current schema-field values of `instance` as its clean baseline.
28
+ *
29
+ * Call this after every hydration (bulk or single-instance path) and after
30
+ * every successful internal-batch save (the latter comes for free because
31
+ * `saveInstance` calls `fetchInstanceData` which ends with a `captureSnapshot`
32
+ * call).
33
+ *
34
+ * @param instance - The Ad4mModel instance to snapshot.
35
+ * @param keys - Schema-declared field names to record (@Property keys +
36
+ * relation keys). Internal machinery (`_id`, `_perspective`,
37
+ * dynamically-wired `addX`/`removeX`/`setX` methods) must
38
+ * NOT be included.
39
+ */
40
+ export declare function captureSnapshot(instance: object, keys: string[]): void;
41
+ /**
42
+ * Returns the snapshot entry for `instance`, or `undefined` if none has been
43
+ * captured yet (i.e. the instance has never been hydrated or saved via an
44
+ * internal batch).
45
+ */
46
+ export declare function readSnapshot(instance: object): SnapshotEntry | undefined;
47
+ /**
48
+ * Returns `true` if `currentValue` differs from the snapshot value for `key`.
49
+ *
50
+ * Always returns `true` (→ write the field) when:
51
+ * - No snapshot has been captured (create path / instance never hydrated).
52
+ * - The key was not present in the snapshot (new field added after hydration).
53
+ *
54
+ * Array comparison is order-insensitive: both sides are sorted before checking
55
+ * element-wise equality, because a fresh hydration may return relation IDs in a
56
+ * different order than they were originally written.
57
+ */
58
+ export declare function isDirty(instance: object, key: string, currentValue: any): boolean;
59
+ export {};
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Dirty-tracking snapshot registry for Ad4mModel instances.
3
+ *
4
+ * A lightweight WeakMap-based store that records the schema-declared field
5
+ * values of an instance immediately after hydration or save. `innerUpdate`
6
+ * consults this snapshot to skip writing fields that haven't changed since the
7
+ * last successful persist, preventing the "re-save duplicates relations" bug.
8
+ *
9
+ * ## Design notes
10
+ *
11
+ * - A **WeakMap** is used so snapshot entries are GC'd when the instance is
12
+ * collected — no manual cleanup needed.
13
+ * - Arrays are normalised to `string[]` on capture (model instances → their ID
14
+ * URI) so the comparison is stable regardless of whether `include` hydration
15
+ * was used.
16
+ * - There is **no snapshot** for a freshly constructed instance that has never
17
+ * been hydrated or saved. `isDirty` returns `true` in that case, preserving
18
+ * existing create-path behaviour (write everything).
19
+ * - Only Tier-1 saves (no caller-provided `batchId`) trigger a post-save
20
+ * rehydration via `fetchInstanceData`, which re-captures the snapshot. Tier-2
21
+ * / Tier-3 (caller-managed batch / `transaction()`) skip rehydration by
22
+ * design; fields that were not changed may be re-sent on the next Tier-1
23
+ * save, which is idempotent and acceptable.
24
+ */
25
+ // ─────────────────────────────────────────────────────────────────────────────
26
+ // Registry
27
+ // ─────────────────────────────────────────────────────────────────────────────
28
+ const snapshots = new WeakMap();
29
+ // ─────────────────────────────────────────────────────────────────────────────
30
+ // Helpers
31
+ // ─────────────────────────────────────────────────────────────────────────────
32
+ /**
33
+ * Normalise a field value for snapshot storage and comparison.
34
+ *
35
+ * - Arrays whose items may be model instances (from `include` hydration) are
36
+ * reduced to their `id` URI strings so comparisons are stable.
37
+ * - All other values are stored as-is.
38
+ */
39
+ function normalizeValue(value) {
40
+ if (Array.isArray(value)) {
41
+ return value.map((v) => v && typeof v === "object" && typeof v.id === "string" ? v.id : v);
42
+ }
43
+ return value;
44
+ }
45
+ // ─────────────────────────────────────────────────────────────────────────────
46
+ // Public API
47
+ // ─────────────────────────────────────────────────────────────────────────────
48
+ /**
49
+ * Records the current schema-field values of `instance` as its clean baseline.
50
+ *
51
+ * Call this after every hydration (bulk or single-instance path) and after
52
+ * every successful internal-batch save (the latter comes for free because
53
+ * `saveInstance` calls `fetchInstanceData` which ends with a `captureSnapshot`
54
+ * call).
55
+ *
56
+ * @param instance - The Ad4mModel instance to snapshot.
57
+ * @param keys - Schema-declared field names to record (@Property keys +
58
+ * relation keys). Internal machinery (`_id`, `_perspective`,
59
+ * dynamically-wired `addX`/`removeX`/`setX` methods) must
60
+ * NOT be included.
61
+ */
62
+ export function captureSnapshot(instance, keys) {
63
+ const entry = {};
64
+ for (const key of keys) {
65
+ entry[key] = normalizeValue(instance[key]);
66
+ }
67
+ snapshots.set(instance, entry);
68
+ }
69
+ /**
70
+ * Returns the snapshot entry for `instance`, or `undefined` if none has been
71
+ * captured yet (i.e. the instance has never been hydrated or saved via an
72
+ * internal batch).
73
+ */
74
+ export function readSnapshot(instance) {
75
+ return snapshots.get(instance);
76
+ }
77
+ /**
78
+ * Returns `true` if `currentValue` differs from the snapshot value for `key`.
79
+ *
80
+ * Always returns `true` (→ write the field) when:
81
+ * - No snapshot has been captured (create path / instance never hydrated).
82
+ * - The key was not present in the snapshot (new field added after hydration).
83
+ *
84
+ * Array comparison is order-insensitive: both sides are sorted before checking
85
+ * element-wise equality, because a fresh hydration may return relation IDs in a
86
+ * different order than they were originally written.
87
+ */
88
+ export function isDirty(instance, key, currentValue) {
89
+ const snap = snapshots.get(instance);
90
+ if (!snap)
91
+ return true; // no snapshot → always write (create path)
92
+ if (!(key in snap))
93
+ return true; // field absent from snapshot → write
94
+ const snapVal = snap[key];
95
+ const currNorm = normalizeValue(currentValue);
96
+ if (Array.isArray(currNorm) && Array.isArray(snapVal)) {
97
+ if (currNorm.length !== snapVal.length)
98
+ return true;
99
+ // Relations are semantically sets; sort before comparing so reordering
100
+ // after a fresh hydration doesn't produce false positives.
101
+ const a = [...currNorm].sort();
102
+ const b = [...snapVal].sort();
103
+ return a.some((v, i) => v !== b[i]);
104
+ }
105
+ return currNorm !== snapVal;
106
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Pure SurrealQL compiler — translates high-level `Query<T>` objects into
3
+ * raw SurrealQL strings.
4
+ *
5
+ * All functions are stateless — they take `ModelMetadata` (and optionally a
6
+ * `Query`) as plain data and return strings or booleans. No dependency on the
7
+ * `Ad4mModel` class, which means they can be imported by tests and other
8
+ * modules without pulling in the full class graph.
9
+ *
10
+ * `Ad4mModel` keeps thin static wrapper methods with the original signatures so
11
+ * the public API is unchanged.
12
+ */
13
+ import { ModelMetadata, Query, Where, WhereCondition } from "../types";
14
+ /**
15
+ * Formats a value for use in SurrealQL queries.
16
+ *
17
+ * - Strings: wrapped in single quotes, special characters escaped
18
+ * - Numbers / booleans: converted to string
19
+ * - Arrays: recursively formatted, wrapped in `[...]`
20
+ */
21
+ export declare function formatSurrealValue(value: any): string;
22
+ /**
23
+ * Builds graph-traversal WHERE clause filters (`->link[WHERE ...]`).
24
+ * Used by `buildSurrealQuery` — more efficient than subqueries because
25
+ * SurrealDB can use graph indexes.
26
+ */
27
+ export declare function buildGraphTraversalWhereClause(metadata: ModelMetadata, where?: Where): string;
28
+ /**
29
+ * Builds the SurrealQL SELECT query for a given model metadata + query params.
30
+ * This is the extracted, pure-function form of `Ad4mModel.queryToSurrealQL`.
31
+ */
32
+ export declare function buildSurrealQuery(metadata: ModelMetadata, query: Query): string;
33
+ /**
34
+ * Builds a count query (same as `buildSurrealQuery` but without LIMIT/OFFSET).
35
+ */
36
+ export declare function buildSurrealCountQuery(metadata: ModelMetadata, query: Query): string;
37
+ /**
38
+ * Checks whether a single value satisfies a WhereCondition.
39
+ * Used for post-query JavaScript filtering of operators that SurrealDB
40
+ * cannot evaluate reliably (gt/gte/lt/lte/between/contains on literals).
41
+ */
42
+ export declare function matchesCondition(value: any, condition: WhereCondition): boolean;
@@ -0,0 +1,304 @@
1
+ /**
2
+ * Pure SurrealQL compiler — translates high-level `Query<T>` objects into
3
+ * raw SurrealQL strings.
4
+ *
5
+ * All functions are stateless — they take `ModelMetadata` (and optionally a
6
+ * `Query`) as plain data and return strings or booleans. No dependency on the
7
+ * `Ad4mModel` class, which means they can be imported by tests and other
8
+ * modules without pulling in the full class graph.
9
+ *
10
+ * `Ad4mModel` keeps thin static wrapper methods with the original signatures so
11
+ * the public API is unchanged.
12
+ */
13
+ import { escapeSurrealString } from "../../utils";
14
+ // ── Value formatting ────────────────────────────────────────────────────────
15
+ /**
16
+ * Formats a value for use in SurrealQL queries.
17
+ *
18
+ * - Strings: wrapped in single quotes, special characters escaped
19
+ * - Numbers / booleans: converted to string
20
+ * - Arrays: recursively formatted, wrapped in `[...]`
21
+ */
22
+ export function formatSurrealValue(value) {
23
+ if (typeof value === "string") {
24
+ const escaped = value
25
+ .replace(/\\/g, "\\\\")
26
+ .replace(/'/g, "\\'")
27
+ .replace(/"/g, '\\"')
28
+ .replace(/\n/g, "\\n")
29
+ .replace(/\r/g, "\\r")
30
+ .replace(/\t/g, "\\t");
31
+ return `'${escaped}'`;
32
+ }
33
+ else if (typeof value === "number" || typeof value === "boolean") {
34
+ return String(value);
35
+ }
36
+ else if (Array.isArray(value)) {
37
+ return `[${value.map(formatSurrealValue).join(", ")}]`;
38
+ }
39
+ else {
40
+ return String(value);
41
+ }
42
+ }
43
+ // ── WHERE clause builders ───────────────────────────────────────────────────
44
+ /**
45
+ * Builds graph-traversal WHERE clause filters (`->link[WHERE ...]`).
46
+ * Used by `buildSurrealQuery` — more efficient than subqueries because
47
+ * SurrealDB can use graph indexes.
48
+ */
49
+ export function buildGraphTraversalWhereClause(metadata, where) {
50
+ if (!where)
51
+ return "";
52
+ const conditions = [];
53
+ for (const [propertyName, condition] of Object.entries(where)) {
54
+ const isSpecial = ["base", "id", "author", "timestamp"].includes(propertyName);
55
+ if (isSpecial) {
56
+ if (propertyName === "author" || propertyName === "timestamp") {
57
+ continue; // filtered post-query in JavaScript
58
+ }
59
+ const columnName = "uri"; // base/id → uri in node table
60
+ if (Array.isArray(condition)) {
61
+ const formattedValues = condition.map(formatSurrealValue).join(", ");
62
+ conditions.push(`${columnName} IN [${formattedValues}]`);
63
+ }
64
+ else if (typeof condition === "object" && condition !== null) {
65
+ const ops = condition;
66
+ if (ops.not !== undefined) {
67
+ if (Array.isArray(ops.not)) {
68
+ const formattedValues = ops.not.map(formatSurrealValue).join(", ");
69
+ conditions.push(`${columnName} NOT IN [${formattedValues}]`);
70
+ }
71
+ else {
72
+ conditions.push(`${columnName} != ${formatSurrealValue(ops.not)}`);
73
+ }
74
+ }
75
+ if (ops.between !== undefined &&
76
+ Array.isArray(ops.between) &&
77
+ ops.between.length === 2) {
78
+ conditions.push(`${columnName} >= ${formatSurrealValue(ops.between[0])} AND ${columnName} <= ${formatSurrealValue(ops.between[1])}`);
79
+ }
80
+ if (ops.gt !== undefined)
81
+ conditions.push(`${columnName} > ${formatSurrealValue(ops.gt)}`);
82
+ if (ops.gte !== undefined)
83
+ conditions.push(`${columnName} >= ${formatSurrealValue(ops.gte)}`);
84
+ if (ops.lt !== undefined)
85
+ conditions.push(`${columnName} < ${formatSurrealValue(ops.lt)}`);
86
+ if (ops.lte !== undefined)
87
+ conditions.push(`${columnName} <= ${formatSurrealValue(ops.lte)}`);
88
+ if (ops.contains !== undefined)
89
+ conditions.push(`${columnName} CONTAINS ${formatSurrealValue(ops.contains)}`);
90
+ }
91
+ else {
92
+ conditions.push(`${columnName} = ${formatSurrealValue(condition)}`);
93
+ }
94
+ }
95
+ else {
96
+ const propMeta = metadata.properties[propertyName];
97
+ if (!propMeta) {
98
+ // ── Relation-based where clause ────────────────────────────────────
99
+ // If the where key is a relation name (e.g. `where: { post: postId }`),
100
+ // generate a graph-traversal filter on the link predicate.
101
+ //
102
+ // • Reverse relations (@BelongsToOne / @BelongsToMany):
103
+ // The link is stored as parentId --predicate--> thisId.
104
+ // From this node we traverse <-link (incoming) and check in.uri.
105
+ //
106
+ // • Forward relations (@HasMany / @HasOne):
107
+ // The link is stored as thisId --predicate--> childId.
108
+ // From this node we traverse ->link (outgoing) and check out.uri.
109
+ const relMeta = metadata.relations[propertyName];
110
+ if (!relMeta)
111
+ continue;
112
+ const predicate = escapeSurrealString(relMeta.predicate);
113
+ const isReverse = relMeta.direction === "reverse";
114
+ const arrow = isReverse ? "<-" : "->";
115
+ const uriField = isReverse ? "in.uri" : "out.uri";
116
+ if (Array.isArray(condition)) {
117
+ const formattedValues = condition.map(formatSurrealValue).join(", ");
118
+ conditions.push(`count(${arrow}link[WHERE predicate = '${predicate}' AND ${uriField} IN [${formattedValues}]]) > 0`);
119
+ }
120
+ else if (typeof condition === "object" && condition !== null) {
121
+ const ops = condition;
122
+ if (ops.not !== undefined) {
123
+ if (Array.isArray(ops.not)) {
124
+ const formattedValues = ops.not
125
+ .map(formatSurrealValue)
126
+ .join(", ");
127
+ conditions.push(`count(${arrow}link[WHERE predicate = '${predicate}' AND ${uriField} IN [${formattedValues}]]) = 0`);
128
+ }
129
+ else {
130
+ conditions.push(`count(${arrow}link[WHERE predicate = '${predicate}' AND ${uriField} = ${formatSurrealValue(ops.not)}]) = 0`);
131
+ }
132
+ }
133
+ // Comparison operators on relation IDs are unusual but handled:
134
+ // they'll be caught in JS post-filtering (step 6 in operations.ts).
135
+ }
136
+ else {
137
+ conditions.push(`count(${arrow}link[WHERE predicate = '${predicate}' AND ${uriField} = ${formatSurrealValue(condition)}]) > 0`);
138
+ }
139
+ continue;
140
+ }
141
+ const predicate = escapeSurrealString(propMeta.predicate);
142
+ // Scalar properties (resolveLanguage === "literal" or unset) store values as
143
+ // literal:// URIs — use fn::parse_literal to unwrap before comparing.
144
+ // Only non-literal custom languages (e.g. IPFS) store raw expression URLs.
145
+ const targetField = !propMeta.resolveLanguage || propMeta.resolveLanguage === "literal"
146
+ ? "fn::parse_literal(out.uri)"
147
+ : "out.uri";
148
+ if (Array.isArray(condition)) {
149
+ const formattedValues = condition.map(formatSurrealValue).join(", ");
150
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) > 0`);
151
+ }
152
+ else if (typeof condition === "object" && condition !== null) {
153
+ const ops = condition;
154
+ if (ops.not !== undefined) {
155
+ if (Array.isArray(ops.not)) {
156
+ const formattedValues = ops.not.map(formatSurrealValue).join(", ");
157
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
158
+ }
159
+ else {
160
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
161
+ }
162
+ }
163
+ const hasComparisonOps = ops.gt !== undefined ||
164
+ ops.gte !== undefined ||
165
+ ops.lt !== undefined ||
166
+ ops.lte !== undefined ||
167
+ ops.between !== undefined ||
168
+ ops.contains !== undefined;
169
+ if (hasComparisonOps) {
170
+ conditions.push(`count(->link[WHERE predicate = '${predicate}']) > 0`);
171
+ }
172
+ }
173
+ else {
174
+ conditions.push(`count(->link[WHERE predicate = '${predicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`);
175
+ }
176
+ }
177
+ }
178
+ return conditions.join(" AND ");
179
+ }
180
+ // ── Main query builders ─────────────────────────────────────────────────────
181
+ /**
182
+ * Builds the SurrealQL SELECT query for a given model metadata + query params.
183
+ * This is the extracted, pure-function form of `Ad4mModel.queryToSurrealQL`.
184
+ */
185
+ export function buildSurrealQuery(metadata, query) {
186
+ const { where, parent: linkedFrom } = query;
187
+ const graphTraversalFilters = [];
188
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
189
+ if (propMeta.required) {
190
+ if (propMeta.flag && propMeta.initial) {
191
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
192
+ }
193
+ else {
194
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
195
+ }
196
+ }
197
+ }
198
+ if (graphTraversalFilters.length === 0) {
199
+ for (const [, propMeta] of Object.entries(metadata.properties)) {
200
+ if (propMeta.initial) {
201
+ if (propMeta.flag) {
202
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
203
+ }
204
+ else {
205
+ graphTraversalFilters.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.predicate)}']) > 0`);
206
+ }
207
+ break;
208
+ }
209
+ }
210
+ }
211
+ // Last-resort fallback: require at least one link with any of the model's
212
+ // own declared predicates (properties OR relations). This prevents matching
213
+ // SDNA registration nodes (which use sh://, ad4m://, rdf:// predicates) for
214
+ // models that have no @Flag, no required, and no initial-valued properties.
215
+ if (graphTraversalFilters.length === 0) {
216
+ const allPredicates = [
217
+ ...Object.values(metadata.properties).map((p) => p.predicate),
218
+ ...Object.values(metadata.relations).map((r) => r.predicate),
219
+ ].filter(Boolean);
220
+ if (allPredicates.length > 0) {
221
+ const predicateConditions = allPredicates
222
+ .map((p) => `count(->link[WHERE predicate = '${escapeSurrealString(p)}']) > 0`)
223
+ .join(" OR ");
224
+ graphTraversalFilters.push(`(${predicateConditions})`);
225
+ }
226
+ }
227
+ const userWhereClause = buildGraphTraversalWhereClause(metadata, where);
228
+ const whereConditions = [
229
+ ...graphTraversalFilters,
230
+ ...(userWhereClause ? [userWhereClause] : []),
231
+ ...(linkedFrom
232
+ ? [
233
+ `count(<-link[WHERE predicate = '${escapeSurrealString(linkedFrom.predicate)}' AND in.uri = '${escapeSurrealString(linkedFrom.id)}']) > 0`,
234
+ ]
235
+ : []),
236
+ ];
237
+ // Ensure we always have at least one condition to produce valid SurrealQL
238
+ const whereClause = whereConditions.length > 0
239
+ ? whereConditions.join(" AND ")
240
+ : "count(->link) > 0";
241
+ return `
242
+ SELECT
243
+ id AS source,
244
+ uri AS source_uri,
245
+ (SELECT predicate, out.uri AS target, author, timestamp FROM link WHERE in = $parent.id ORDER BY timestamp ASC) AS links
246
+ FROM node
247
+ WHERE ${whereClause}
248
+ `.trim();
249
+ }
250
+ /**
251
+ * Builds a count query (same as `buildSurrealQuery` but without LIMIT/OFFSET).
252
+ */
253
+ export function buildSurrealCountQuery(metadata, query) {
254
+ const countQuery = { ...query };
255
+ delete countQuery.limit;
256
+ delete countQuery.offset;
257
+ return buildSurrealQuery(metadata, countQuery);
258
+ }
259
+ // ── Post-query filtering ────────────────────────────────────────────────────
260
+ /**
261
+ * Checks whether a single value satisfies a WhereCondition.
262
+ * Used for post-query JavaScript filtering of operators that SurrealDB
263
+ * cannot evaluate reliably (gt/gte/lt/lte/between/contains on literals).
264
+ */
265
+ export function matchesCondition(value, condition) {
266
+ if (Array.isArray(condition)) {
267
+ return condition.includes(value);
268
+ }
269
+ if (typeof condition === "object" && condition !== null) {
270
+ const ops = condition;
271
+ let allMet = true;
272
+ if (ops.not !== undefined)
273
+ allMet =
274
+ allMet &&
275
+ (Array.isArray(ops.not)
276
+ ? !ops.not.includes(value)
277
+ : value !== ops.not);
278
+ if (ops.between !== undefined &&
279
+ Array.isArray(ops.between) &&
280
+ ops.between.length === 2)
281
+ allMet = allMet && value >= ops.between[0] && value <= ops.between[1];
282
+ if (ops.gt !== undefined)
283
+ allMet = allMet && value > ops.gt;
284
+ if (ops.gte !== undefined)
285
+ allMet = allMet && value >= ops.gte;
286
+ if (ops.lt !== undefined)
287
+ allMet = allMet && value < ops.lt;
288
+ if (ops.lte !== undefined)
289
+ allMet = allMet && value <= ops.lte;
290
+ if (ops.contains !== undefined) {
291
+ if (typeof value === "string") {
292
+ allMet = allMet && value.includes(String(ops.contains));
293
+ }
294
+ else if (Array.isArray(value)) {
295
+ allMet = allMet && value.includes(ops.contains);
296
+ }
297
+ else {
298
+ allMet = false;
299
+ }
300
+ }
301
+ return allMet;
302
+ }
303
+ return value === condition;
304
+ }
@@ -0,0 +1,67 @@
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 { PropertyOptions } from "../decorators";
10
+ export interface JSONSchemaProperty {
11
+ type: string | string[];
12
+ items?: JSONSchemaProperty;
13
+ properties?: {
14
+ [key: string]: JSONSchemaProperty;
15
+ };
16
+ required?: string[];
17
+ "x-ad4m"?: {
18
+ through?: string;
19
+ resolveLanguage?: string;
20
+ local?: boolean;
21
+ readOnly?: boolean;
22
+ initial?: string;
23
+ };
24
+ }
25
+ export interface JSONSchema {
26
+ $schema?: string;
27
+ title?: string;
28
+ $id?: string;
29
+ type?: string;
30
+ properties?: {
31
+ [key: string]: JSONSchemaProperty;
32
+ };
33
+ required?: string[];
34
+ "x-ad4m"?: {
35
+ namespace?: string;
36
+ className?: string;
37
+ };
38
+ }
39
+ export interface JSONSchemaToModelOptions {
40
+ name: string;
41
+ namespace?: string;
42
+ predicateTemplate?: string;
43
+ predicateGenerator?: (title: string, property: string) => string;
44
+ propertyMapping?: Record<string, string>;
45
+ resolveLanguage?: string;
46
+ local?: boolean;
47
+ propertyOptions?: Record<string, Partial<PropertyOptions>>;
48
+ }
49
+ export declare function normalizeNamespaceString(namespace: string): string;
50
+ export declare function normalizeSchemaType(type?: string | string[]): string | undefined;
51
+ export declare function isSchemaType(schema: JSONSchemaProperty, expectedType: string): boolean;
52
+ export declare function isArrayType(schema: JSONSchemaProperty): boolean;
53
+ export declare function isObjectType(schema: JSONSchemaProperty): boolean;
54
+ export declare function isNumericType(schema: JSONSchemaProperty): boolean;
55
+ export declare function determineNamespace(schema: JSONSchema, options: JSONSchemaToModelOptions): string;
56
+ export declare function determinePredicate(schema: JSONSchema, propertyName: string, propertySchema: JSONSchemaProperty, namespace: string, options: JSONSchemaToModelOptions): string;
57
+ export declare function getPropertyOption(propertyName: string, propertySchema: JSONSchemaProperty, options: JSONSchemaToModelOptions, optionName: keyof PropertyOptions, defaultValue?: any): any;
58
+ export declare function getDefaultValueForType(type?: string): any;
59
+ /**
60
+ * Creates an Ad4mModel subclass dynamically from a JSON Schema definition.
61
+ *
62
+ * Takes `BaseClass` as a parameter (rather than importing `Ad4mModel` directly)
63
+ * to avoid a circular dependency between this module and `Ad4mModel.ts`.
64
+ *
65
+ * `Ad4mModel.fromJSONSchema()` is a thin wrapper that calls this with `this`.
66
+ */
67
+ export declare function createModelFromJSONSchema(BaseClass: any, schema: JSONSchema, options: JSONSchemaToModelOptions): any;