@coasys/ad4m 0.12.0-rc1-dev.4 → 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 (166) hide show
  1. package/lib/index.cjs +5052 -4446
  2. package/lib/index.js +5019 -4442
  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 -782
  8. package/lib/src/model/Ad4mModel.js +160 -2354
  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 +71 -23
  12. package/lib/src/model/decorators.js +133 -384
  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/relation-filtering.test.js +838 -0
  28. package/lib/src/model/sdna.d.ts +14 -0
  29. package/lib/src/model/sdna.js +141 -0
  30. package/lib/src/model/shacl-gen.d.ts +31 -0
  31. package/lib/src/model/shacl-gen.js +246 -0
  32. package/lib/src/model/surreal-utils.d.ts +42 -0
  33. package/lib/src/model/surreal-utils.js +128 -0
  34. package/lib/src/model/types.d.ts +75 -96
  35. package/lib/src/model/types.js +4 -4
  36. package/lib/src/model/util.d.ts +4 -5
  37. package/lib/src/model/util.js +12 -32
  38. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  39. package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
  40. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
  41. package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
  42. package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
  43. package/lib/src/runtime/RuntimeResolver.js +73 -0
  44. package/lib/src/schema.gql +14 -0
  45. package/lib/src/shacl/SHACLShape.d.ts +23 -0
  46. package/lib/src/shacl/SHACLShape.js +45 -0
  47. package/lib/src/typeDefs.js +14 -0
  48. package/package.json +13 -8
  49. package/src/agent/AgentClient.ts +45 -0
  50. package/src/index.ts +2 -3
  51. package/src/model/Ad4mModel.ts +1089 -3686
  52. package/src/model/ModelQueryBuilder.ts +617 -0
  53. package/src/model/Subject.ts +1 -1
  54. package/src/model/decorators.ts +218 -453
  55. package/src/model/hydration.ts +796 -0
  56. package/src/model/index.ts +21 -0
  57. package/src/model/json-schema.ts +424 -0
  58. package/src/model/prolog-facts.ts +145 -0
  59. package/src/model/query-common.ts +48 -0
  60. package/src/model/query-prolog.ts +148 -0
  61. package/src/model/query-surreal.ts +280 -0
  62. package/src/model/relation-filtering.test.ts +803 -0
  63. package/src/model/sdna.ts +170 -0
  64. package/src/model/shacl-gen.ts +292 -0
  65. package/src/model/surreal-utils.ts +147 -0
  66. package/src/model/types.ts +182 -0
  67. package/src/model/util.ts +13 -36
  68. package/src/perspectives/PerspectiveClient.ts +1 -1
  69. package/src/perspectives/PerspectiveProxy.ts +1 -1
  70. package/src/perspectives/WakerSubscriptionManager.ts +292 -0
  71. package/src/runtime/RuntimeResolver.ts +53 -0
  72. package/src/shacl/SHACLShape.ts +83 -0
  73. package/lib/src/Ad4mClient.test.js +0 -1204
  74. package/lib/src/Literal.test.d.ts +0 -1
  75. package/lib/src/Literal.test.js +0 -41
  76. package/lib/src/model/mutation.d.ts +0 -81
  77. package/lib/src/model/mutation.js +0 -317
  78. package/lib/src/model/parentUtils.d.ts +0 -32
  79. package/lib/src/model/parentUtils.js +0 -64
  80. package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
  81. package/lib/src/model/prolog/index.d.ts +0 -1
  82. package/lib/src/model/prolog/index.js +0 -1
  83. package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
  84. package/lib/src/model/query/ModelQueryBuilder.js +0 -115
  85. package/lib/src/model/query/QueryBuilder.d.ts +0 -101
  86. package/lib/src/model/query/QueryBuilder.js +0 -193
  87. package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
  88. package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
  89. package/lib/src/model/query/fetchInstance.d.ts +0 -24
  90. package/lib/src/model/query/fetchInstance.js +0 -144
  91. package/lib/src/model/query/hydration.d.ts +0 -54
  92. package/lib/src/model/query/hydration.js +0 -214
  93. package/lib/src/model/query/operations.d.ts +0 -59
  94. package/lib/src/model/query/operations.js +0 -384
  95. package/lib/src/model/query/snapshot.d.ts +0 -59
  96. package/lib/src/model/query/snapshot.js +0 -106
  97. package/lib/src/model/query/surrealCompiler.d.ts +0 -42
  98. package/lib/src/model/query/surrealCompiler.js +0 -304
  99. package/lib/src/model/schema/fromJSONSchema.js +0 -264
  100. package/lib/src/model/schema/metadata.d.ts +0 -15
  101. package/lib/src/model/schema/metadata.js +0 -112
  102. package/lib/src/model/subscription.d.ts +0 -47
  103. package/lib/src/model/subscription.js +0 -231
  104. package/lib/src/model/transaction.d.ts +0 -27
  105. package/lib/src/model/transaction.js +0 -32
  106. package/lib/src/shims/reflect-metadata.d.ts +0 -0
  107. package/lib/src/shims/type-graphql.d.ts +0 -32
  108. package/lib/src/src/Ad4mClient.d.ts +0 -28
  109. package/lib/src/src/Address.d.ts +0 -1
  110. package/lib/src/src/DID.d.ts +0 -1
  111. package/lib/src/src/Exception.d.ts +0 -7
  112. package/lib/src/src/Literal.d.ts +0 -7
  113. package/lib/src/src/PubSub.d.ts +0 -17
  114. package/lib/src/src/SmartLiteral.d.ts +0 -12
  115. package/lib/src/src/agent/Agent.d.ts +0 -110
  116. package/lib/src/src/agent/AgentClient.d.ts +0 -62
  117. package/lib/src/src/agent/AgentResolver.d.ts +0 -30
  118. package/lib/src/src/agent/AgentStatus.d.ts +0 -8
  119. package/lib/src/src/ai/AIClient.d.ts +0 -32
  120. package/lib/src/src/ai/AIResolver.d.ts +0 -75
  121. package/lib/src/src/ai/Tasks.d.ts +0 -37
  122. package/lib/src/src/buildSchema.d.ts +0 -1
  123. package/lib/src/src/expression/Expression.d.ts +0 -28
  124. package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
  125. package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
  126. package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
  127. package/lib/src/src/index.d.ts +0 -35
  128. package/lib/src/src/jestSetup.d.ts +0 -1
  129. package/lib/src/src/language/Icon.d.ts +0 -4
  130. package/lib/src/src/language/Language.d.ts +0 -206
  131. package/lib/src/src/language/LanguageClient.d.ts +0 -17
  132. package/lib/src/src/language/LanguageContext.d.ts +0 -37
  133. package/lib/src/src/language/LanguageHandle.d.ts +0 -9
  134. package/lib/src/src/language/LanguageMeta.d.ts +0 -35
  135. package/lib/src/src/language/LanguageRef.d.ts +0 -6
  136. package/lib/src/src/language/LanguageResolver.d.ts +0 -19
  137. package/lib/src/src/links/Links.d.ts +0 -39
  138. package/lib/src/src/links/Links.test.d.ts +0 -1
  139. package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
  140. package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
  141. package/lib/src/src/model/Subject.d.ts +0 -25
  142. package/lib/src/src/model/decorators.d.ts +0 -545
  143. package/lib/src/src/model/util.d.ts +0 -12
  144. package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
  145. package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
  146. package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
  147. package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
  148. package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
  149. package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
  150. package/lib/src/src/perspectives/Perspective.d.ts +0 -38
  151. package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
  152. package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
  153. package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
  154. package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
  155. package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
  156. package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
  157. package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
  158. package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
  159. package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
  160. package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
  161. package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
  162. package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
  163. package/lib/src/src/typeDefs.d.ts +0 -1
  164. package/lib/src/src/unwrapApolloResult.d.ts +0 -2
  165. package/lib/src/src/utils.d.ts +0 -25
  166. /package/lib/src/{Ad4mClient.test.d.ts → model/relation-filtering.test.d.ts} +0 -0
@@ -1,11 +1,12 @@
1
1
  /**
2
- * Public types for the AD4M model layer.
2
+ * Shared type definitions for the Ad4mModel system.
3
3
  *
4
- * Extracted from Ad4mModel.ts so they can be imported by query builders,
5
- * hydration helpers, and external consumers without pulling in the full
6
- * Ad4mModel class.
4
+ * Extracted into a standalone module so that utility files
5
+ * (`surreal-utils.ts`, `decorators.ts`, etc.) can import types without
6
+ * creating circular runtime dependencies on `Ad4mModel.ts`.
7
7
  */
8
- type WhereOps = {
8
+ import type { Ad4mModel } from "./Ad4mModel";
9
+ export type WhereOps = {
9
10
  not: string | number | boolean | string[] | number[];
10
11
  between: [number, number];
11
12
  lt: number;
@@ -24,109 +25,78 @@ export type Order = {
24
25
  [propertyName: string]: "ASC" | "DESC";
25
26
  };
26
27
  /**
27
- * Prisma-style eager-loading map.
28
+ * Discriminated union for parent-scoped queries.
28
29
  *
29
- * Key = relation field name on the model.
30
- * Value = `true` (hydrate all with no filter) or a `Query` to
31
- * filter / order / limit the nested set.
30
+ * **Model form** (preferred) — predicate auto-resolved from the parent model's
31
+ * relation metadata. Use `field` to disambiguate when the parent has multiple
32
+ * relations targeting the same child class.
32
33
  *
33
- * @example
34
- * ```typescript
35
- * Recipe.findAll(perspective, {
36
- * include: {
37
- * comments: true,
38
- * tags: { where: { active: true }, order: { name: 'ASC' }, limit: 5 },
39
- * },
40
- * });
41
- * ```
34
+ * **Raw form** — explicit predicate string, no metadata lookup.
42
35
  */
43
- export type IncludeMap = {
44
- [relationName: string]: true | Query;
45
- };
46
- /**
47
- * Minimal interface a parent model class must satisfy for the model-backed
48
- * `parent` query form. Avoids a circular import between types.ts and Ad4mModel.ts.
49
- */
50
- type ParentQueryParentCtor = {
51
- getModelMetadata(): ModelMetadata;
52
- };
53
- /** Raw predicate form — use for ad-hoc or cross-package predicates. */
54
- export type ParentQueryByPredicate = {
36
+ export type ParentScope = {
37
+ model: typeof Ad4mModel;
38
+ id: string;
39
+ field?: string;
40
+ } | {
55
41
  id: string;
56
42
  predicate: string;
57
43
  };
58
44
  /**
59
- * Model-backed form — DRY alternative that resolves the predicate from the
60
- * parent model's `@HasMany` decorator metadata at query time.
45
+ * Describes which relations to eager-load when querying.
46
+ *
47
+ * Each value is either:
48
+ * - `true` — hydrate the relation one level deep
49
+ * - A `RelationSubQuery` — scoped sub-query (filter / sort / paginate / nested include)
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * // One level deep
54
+ * { comments: true }
55
+ *
56
+ * // Sub-query: only the 5 most-recent comments
57
+ * { comments: { order: { createdAt: 'DESC' }, limit: 5 } }
58
+ *
59
+ * // Nested eager-load
60
+ * { comments: { include: { author: true } } }
61
+ * ```
61
62
  */
62
- export type ParentQueryByModel = {
63
- id: string;
64
- model: ParentQueryParentCtor;
65
- /** The `@HasMany` field name on `model`. Optional when unambiguous. */
66
- field?: string;
67
- };
68
- /** Union of the two `parent` query forms accepted by {@link Query}. */
69
- export type ParentQuery = ParentQueryByPredicate | ParentQueryByModel;
63
+ export interface IncludeMap {
64
+ [relation: string]: boolean | RelationSubQuery;
65
+ }
70
66
  export type Query = {
67
+ /** Filter to instances that are the target of a link from a given parent. */
68
+ parent?: ParentScope;
71
69
  properties?: string[];
72
- /** Eagerly hydrate relations. Key = field name; value = `true` or a sub-`Query`. See {@link IncludeMap}. */
73
70
  include?: IncludeMap;
74
71
  where?: Where;
75
72
  order?: Order;
76
73
  offset?: number;
77
74
  limit?: number;
78
75
  count?: boolean;
79
- /**
80
- * When provided, restricts results to instances reachable from the given
81
- * parent node via the given predicate.
82
- *
83
- * The subscription layer also watches this predicate so that adding or
84
- * removing a child link triggers a live re-query.
85
- *
86
- * Two equivalent forms are accepted:
87
- * - Raw: `{ id, predicate }` — use for ad-hoc / foreign predicates.
88
- * - Model-backed: `{ id, model, field? }` — DRY, refactor-safe; the
89
- * predicate is resolved automatically from the parent model's `@HasMany`
90
- * decorator metadata. `field` is the `@HasMany` field name; when the
91
- * parent has exactly one `@HasMany` pointing to the child type it may be
92
- * omitted (but is recommended for clarity).
93
- *
94
- * @example
95
- * // Raw form (still valid for foreign predicates)
96
- * parent: { id: parentId, predicate: 'custom://my_pred' }
97
- *
98
- * // Model-backed form (preferred for schema-declared relations)
99
- * parent: { id: poll.id, model: Poll, field: 'answers' }
100
- */
101
- parent?: ParentQuery;
102
76
  };
103
77
  /**
104
- * Extends `Query` (minus `count`) with subscription delivery options.
105
- * Pass to {@link Ad4mModel.subscribe} or the builder's `.subscribe()`.
78
+ * Sub-query options for a specific relation inside an `IncludeMap`.
79
+ *
80
+ * Equivalent to `Query` without top-level scoping (`parent`) or `count`,
81
+ * since the result set is already constrained to the linked relation.
82
+ *
83
+ * @example
84
+ * ```typescript
85
+ * await post.get({ include: { comments: { order: { createdAt: 'DESC' }, limit: 5 } } });
86
+ * ```
106
87
  */
107
- export type SubscribeOptions = Omit<Query, "count"> & {
108
- /**
109
- * Debounce delay in milliseconds. Multiple link changes within this window
110
- * trigger only one re-query. Default: `0` (no debouncing).
111
- */
112
- debounce?: number;
113
- /**
114
- * Called when the re-query or the callback throws.
115
- * Defaults to `console.error` so failures are always visible without
116
- * requiring every caller to handle them.
117
- */
118
- onError?: (err: Error) => void;
119
- };
88
+ export type RelationSubQuery = Omit<Query, 'parent' | 'count'>;
120
89
  /**
121
- * Handle returned by `Ad4mModel.subscribe()`. Call `unsubscribe()` in cleanup.
122
- * `lastError` holds the most recent unhandled error, or `null`.
90
+ * Options accepted by the instance `get()` method.
91
+ *
92
+ * A subset of `Query` — only hydration controls apply to a single known instance.
123
93
  */
124
- export type Subscription = {
125
- unsubscribe(): void;
126
- /** The most recent unhandled error from re-query or callback, or `null`. */
127
- readonly lastError: Error | null;
94
+ export type GetOptions = Pick<Query, 'include' | 'properties'>;
95
+ export type AllInstancesResult = {
96
+ AllInstances: Ad4mModel[];
97
+ TotalCount?: number;
98
+ isInit?: boolean;
128
99
  };
129
- export type AllInstancesResult = any;
130
100
  export type ResultsWithTotalCount<T> = {
131
101
  results: T[];
132
102
  totalCount?: number;
@@ -137,6 +107,7 @@ export type PaginationResult<T> = {
137
107
  pageSize: number;
138
108
  pageNumber: number;
139
109
  };
110
+ export type ValueTuple = [name: string, value: any, resolve?: boolean];
140
111
  /**
141
112
  * Metadata for a single property extracted from decorators.
142
113
  */
@@ -147,12 +118,16 @@ export interface PropertyMetadata {
147
118
  predicate: string;
148
119
  /** Whether the property is required */
149
120
  required: boolean;
150
- /** Whether the property is read-only (default: false, i.e. writable) */
151
- readOnly?: boolean;
121
+ /** Whether the property is read-only */
122
+ readOnly: boolean;
152
123
  /** Initial value if specified */
153
124
  initial?: string;
154
125
  /** Language for resolution (e.g., "literal") */
155
126
  resolveLanguage?: string;
127
+ /** Custom Prolog getter code */
128
+ prologGetter?: string;
129
+ /** Custom Prolog setter code */
130
+ prologSetter?: string;
156
131
  /** Custom SurrealQL getter code */
157
132
  getter?: string;
158
133
  /** Whether stored locally only */
@@ -174,22 +149,26 @@ export interface RelationMetadata {
174
149
  getter?: string;
175
150
  /** Whether stored locally only */
176
151
  local?: boolean;
177
- /** Traversal direction — "forward" (default) for @HasMany/@HasOne, "reverse" for @BelongsToOne/@BelongsToMany */
178
- direction?: "forward" | "reverse";
179
- /** Maximum number of results (1 for @BelongsToOne / @HasOne) */
180
- maxCount?: number;
181
- /** Model factory for eager hydration — set when decorator is called with () => ModelClass */
182
- relatedModel?: () => any;
152
+ /** Link direction: 'forward' for HasMany/HasOne, 'reverse' for BelongsToMany/BelongsToOne */
153
+ direction?: 'forward' | 'reverse';
154
+ /** Target model class thunk for hydration and type filtering */
155
+ target?: () => any;
156
+ /**
157
+ * Whether to auto-generate a conformance filter when `target` is set.
158
+ * Defaults to `true` — set to `false` to opt out of DB-level type filtering.
159
+ */
160
+ filter?: boolean;
161
+ /** Where clause for relation filtering (query DSL) */
162
+ where?: Where;
183
163
  }
184
164
  /**
185
165
  * Complete model metadata extracted from decorators.
186
166
  */
187
167
  export interface ModelMetadata {
188
- /** The model class name from @ModelOptions */
168
+ /** The model class name from @Model */
189
169
  className: string;
190
170
  /** Map of property name to metadata */
191
171
  properties: Record<string, PropertyMetadata>;
192
172
  /** Map of relation name to metadata */
193
173
  relations: Record<string, RelationMetadata>;
194
174
  }
195
- export {};
@@ -1,8 +1,8 @@
1
1
  /**
2
- * Public types for the AD4M model layer.
2
+ * Shared type definitions for the Ad4mModel system.
3
3
  *
4
- * Extracted from Ad4mModel.ts so they can be imported by query builders,
5
- * hydration helpers, and external consumers without pulling in the full
6
- * Ad4mModel class.
4
+ * Extracted into a standalone module so that utility files
5
+ * (`surreal-utils.ts`, `decorators.ts`, etc.) can import types without
6
+ * creating circular runtime dependencies on `Ad4mModel.ts`.
7
7
  */
8
8
  export {};
@@ -1,12 +1,11 @@
1
1
  export declare function capitalize(str: string): string;
2
2
  export declare function propertyNameToSetterName(property: string): string;
3
- export declare function setterNameToPropertyName(setter: string): string;
4
- export declare function singularToPlural(singular: string): string;
5
3
  export declare function pluralToSingular(plural: string): string;
6
4
  export declare function relationToAdderName(relation: string): string;
7
- export declare function relationAdderToName(adderName: string): string;
8
5
  export declare function relationToRemoverName(relation: string): string;
9
- export declare function relationRemoverToName(removerName: string): string;
10
- export declare function relationSetterToName(setterName: string): string;
11
6
  export declare function relationToSetterName(relation: string): string;
7
+ /**
8
+ * Generate a random identifier string of the given length (lowercase alpha).
9
+ */
10
+ export declare function makeRandomId(length: number): string;
12
11
  export declare function stringifyObjectLiteral(obj: any): any;
@@ -5,18 +5,6 @@ export function capitalize(str) {
5
5
  export function propertyNameToSetterName(property) {
6
6
  return `set${capitalize(property)}`;
7
7
  }
8
- // e.g. "setName" -> "name"
9
- export function setterNameToPropertyName(setter) {
10
- return setter.replace("set", "").replace(/^[A-Z]/, (m) => m.toLowerCase());
11
- }
12
- export function singularToPlural(singular) {
13
- if (singular.endsWith("y")) {
14
- return singular.slice(0, -1) + "ies";
15
- }
16
- else {
17
- return singular + "s";
18
- }
19
- }
20
8
  export function pluralToSingular(plural) {
21
9
  if (plural.endsWith("ies")) {
22
10
  return plural.slice(0, -3) + "y";
@@ -32,34 +20,26 @@ export function pluralToSingular(plural) {
32
20
  export function relationToAdderName(relation) {
33
21
  return `add${capitalize(pluralToSingular(relation))}`;
34
22
  }
35
- // e.g. "addComments" -> "comments"
36
- export function relationAdderToName(adderName) {
37
- // Extract the relation name after "add" and lowercase first char
38
- // The method name already has the plural relation name (e.g., "addComments")
39
- let relationName = adderName.substring(3);
40
- return relationName.charAt(0).toLowerCase() + relationName.slice(1);
41
- }
42
23
  // e.g. "comments" -> "removeComment"
43
24
  export function relationToRemoverName(relation) {
44
25
  return `remove${capitalize(pluralToSingular(relation))}`;
45
26
  }
46
- // e.g. "removeComments" -> "comments"
47
- export function relationRemoverToName(removerName) {
48
- // Extract the relation name after "remove" and lowercase first char
49
- // The method name already has the plural relation name (e.g., "removeComments")
50
- let relationName = removerName.substring(6);
51
- return relationName.charAt(0).toLowerCase() + relationName.slice(1);
52
- }
53
- export function relationSetterToName(setterName) {
54
- // Extract the relation name after "set" and lowercase first char
55
- // The method name already has the plural relation name (e.g., "setComments")
56
- let relationName = setterName.substring(3);
57
- return relationName.charAt(0).toLowerCase() + relationName.slice(1);
58
- }
59
27
  // e.g. "comments" -> "setComments"
60
28
  export function relationToSetterName(relation) {
61
29
  return `set${capitalize(relation)}`;
62
30
  }
31
+ /**
32
+ * Generate a random identifier string of the given length (lowercase alpha).
33
+ */
34
+ export function makeRandomId(length) {
35
+ let result = '';
36
+ const characters = 'abcdefghijklmnopqrstuvwxyz';
37
+ const charactersLength = characters.length;
38
+ for (let i = 0; i < length; i++) {
39
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
40
+ }
41
+ return result;
42
+ }
63
43
  export function stringifyObjectLiteral(obj) {
64
44
  if (Array.isArray(obj)) {
65
45
  //@ts-ignore
@@ -9,7 +9,7 @@ import { Perspective } from "./Perspective";
9
9
  import { PerspectiveHandle, PerspectiveState } from "./PerspectiveHandle";
10
10
  import { LinkStatus, PerspectiveProxy } from './PerspectiveProxy';
11
11
  import { AIClient } from "../ai/AIClient";
12
- import { AllInstancesResult } from "../model/Ad4mModel";
12
+ import { AllInstancesResult } from "../model/types";
13
13
  export type PerspectiveHandleCallback = (perspective: PerspectiveHandle) => null;
14
14
  export type UuidCallback = (uuid: string) => null;
15
15
  export type LinkCallback = (link: LinkExpression) => null;
@@ -7,7 +7,7 @@ import { ExpressionRendered } from "../expression/Expression";
7
7
  import { NeighbourhoodProxy } from "../neighbourhood/NeighbourhoodProxy";
8
8
  import { NeighbourhoodExpression } from "../neighbourhood/Neighbourhood";
9
9
  import { AIClient } from "../ai/AIClient";
10
- import { AllInstancesResult } from "../model/Ad4mModel";
10
+ import { AllInstancesResult } from "../model/types";
11
11
  import { SHACLShape } from "../shacl/SHACLShape";
12
12
  import { SHACLFlow } from "../shacl/SHACLFlow";
13
13
  type QueryCallback = (result: AllInstancesResult) => void;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * WakerSubscriptionManager — manages live SurrealDB subscriptions for the waker.
3
+ *
4
+ * Lives in core so it can be imported by both the plugin and integration tests
5
+ * without ESM/CJS import issues.
6
+ *
7
+ * NOTE: keep in sync with plugins/ad4m/wakerSubscriptionManager.ts
8
+ */
9
+ export interface WakerSubscription {
10
+ id: string;
11
+ type: "mention" | "channel-messages";
12
+ perspective: string;
13
+ channel: string;
14
+ query: string;
15
+ neighbourhood?: string;
16
+ }
17
+ /** Per-message parent resolution result for mention subscriptions. */
18
+ export interface MentionMessage {
19
+ /** The message's expression address (source of the body link). */
20
+ address: string;
21
+ /** All parent addresses this message belongs to (channels, conversations, etc.). */
22
+ parents: string[];
23
+ }
24
+ export interface WakerLogger {
25
+ info(msg: string): void;
26
+ warn(msg: string): void;
27
+ error(msg: string): void;
28
+ debug(msg: string): void;
29
+ }
30
+ export interface WakerSubscriptionManagerOptions {
31
+ /** PerspectiveClient from Ad4mClient (provides perspectiveSubscribeSurrealQuery etc.) */
32
+ perspectiveClient: any;
33
+ /** Logger instance */
34
+ logger: WakerLogger;
35
+ /** Debounce interval in ms before firing the wake callback (default 2000) */
36
+ debounceMs?: number;
37
+ /** Called when a subscription fires (after debounce). Return value is ignored.
38
+ * For mention subs, `mentions` contains per-message parent info. */
39
+ onWake: (sub: WakerSubscription, result: any, mentions?: MentionMessage[]) => void;
40
+ /** Called when the active subscription list changes (for persistence). */
41
+ onPersist?: (subscriptions: WakerSubscription[], seenMessages: Record<string, string[]>) => void;
42
+ /** Previously persisted seen message IDs per subscription. Seeds seenMessages on resubscribe to avoid duplicate wakes. */
43
+ previousSeenMessages?: Record<string, string[]>;
44
+ /** Optional: provide QuerySubscriptionProxy class directly (avoids require("@coasys/ad4m") at runtime). */
45
+ QuerySubscriptionProxy?: any;
46
+ }
47
+ export declare class WakerSubscriptionManager {
48
+ private perspectiveClient;
49
+ private logger;
50
+ private debounceMs;
51
+ private onWake;
52
+ private onPersist?;
53
+ private QuerySubscriptionProxyCtor;
54
+ private previousSeenMessages;
55
+ private proxies;
56
+ private activeSubscriptions;
57
+ private debounceTimers;
58
+ /** Per-subscription set of already-processed message addresses (for mention subs)
59
+ * or serialized result hash (for channel-messages subs). */
60
+ private seenMessages;
61
+ constructor(options: WakerSubscriptionManagerOptions);
62
+ /**
63
+ * Create a live SurrealDB subscription.
64
+ * If a subscription with the same id already exists, it is disposed first.
65
+ */
66
+ subscribe(sub: WakerSubscription): Promise<void>;
67
+ /**
68
+ * Dispose a single subscription.
69
+ * @param persist — if false, skip calling onPersist (used during batch cleanup).
70
+ */
71
+ dispose(id: string, persist?: boolean): void;
72
+ /** Dispose all active subscriptions. */
73
+ disposeAll(): void;
74
+ /** Get all active subscriptions. */
75
+ getActive(): WakerSubscription[];
76
+ /** Check if a subscription exists. */
77
+ has(id: string): boolean;
78
+ private persist;
79
+ }
@@ -0,0 +1,196 @@
1
+ /**
2
+ * WakerSubscriptionManager — manages live SurrealDB subscriptions for the waker.
3
+ *
4
+ * Lives in core so it can be imported by both the plugin and integration tests
5
+ * without ESM/CJS import issues.
6
+ *
7
+ * NOTE: keep in sync with plugins/ad4m/wakerSubscriptionManager.ts
8
+ */
9
+ export class WakerSubscriptionManager {
10
+ constructor(options) {
11
+ this.proxies = new Map();
12
+ this.activeSubscriptions = new Map();
13
+ this.debounceTimers = new Map();
14
+ /** Per-subscription set of already-processed message addresses (for mention subs)
15
+ * or serialized result hash (for channel-messages subs). */
16
+ this.seenMessages = new Map();
17
+ this.perspectiveClient = options.perspectiveClient;
18
+ this.logger = options.logger;
19
+ this.debounceMs = options.debounceMs ?? 2000;
20
+ this.onWake = options.onWake;
21
+ this.onPersist = options.onPersist;
22
+ this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;
23
+ this.previousSeenMessages = options.previousSeenMessages ?? {};
24
+ }
25
+ /**
26
+ * Create a live SurrealDB subscription.
27
+ * If a subscription with the same id already exists, it is disposed first.
28
+ */
29
+ async subscribe(sub) {
30
+ // Dispose existing subscription with same id if any
31
+ this.dispose(sub.id, false);
32
+ if (!this.QuerySubscriptionProxyCtor) {
33
+ throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
34
+ }
35
+ const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
36
+ this.logger.info(`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`);
37
+ this.logger.info(`[waker] ${sub.id}: SurrealQL query:\n${sub.query}`);
38
+ const proxy = new QuerySubscriptionProxy(sub.perspective, sub.query, this.perspectiveClient);
39
+ proxy.isSurrealDB = true;
40
+ // Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
41
+ // rejects this promise internally when subscribe() fails, and if nobody catches
42
+ // it before the next microtask it crashes the process.
43
+ if (proxy.initialized && typeof proxy.initialized.catch === "function") {
44
+ proxy.initialized.catch(() => { });
45
+ }
46
+ try {
47
+ await proxy.subscribe();
48
+ await proxy.initialized;
49
+ }
50
+ catch (err) {
51
+ const msg = err?.message ?? String(err);
52
+ this.logger.warn(`[waker] ${sub.id}: subscription failed — ${msg}`);
53
+ try {
54
+ proxy.dispose();
55
+ }
56
+ catch { }
57
+ // Remove from active state so it doesn't get persisted/retried
58
+ this.activeSubscriptions.delete(sub.id);
59
+ this.seenMessages.delete(sub.id);
60
+ this.persist();
61
+ return; // Don't throw — caller should not crash
62
+ }
63
+ this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
64
+ // Seed from persisted seen messages so we don't re-wake after restart
65
+ const seen = new Set(this.previousSeenMessages[sub.id] ?? []);
66
+ this.seenMessages.set(sub.id, seen);
67
+ if (seen.size > 0) {
68
+ this.logger.info(`[waker] ${sub.id}: seeded ${seen.size} seen message(s) from persisted state`);
69
+ }
70
+ proxy.onResult(async (result) => {
71
+ this.logger.info(`[waker] ${sub.id}: onResult fired — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`);
72
+ // SurrealDB can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
73
+ if (!Array.isArray(result)) {
74
+ this.logger.warn(`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`);
75
+ return;
76
+ }
77
+ if (sub.type === "mention") {
78
+ // For mention subscriptions: track seen message addresses.
79
+ // Only wake for messages we haven't seen before.
80
+ const currentSeen = this.seenMessages.get(sub.id) ?? new Set();
81
+ const newMessages = [];
82
+ for (const item of result) {
83
+ if (item && item.source && !currentSeen.has(item.source)) {
84
+ newMessages.push(item.source);
85
+ }
86
+ }
87
+ if (newMessages.length === 0) {
88
+ this.logger.info(`[waker] ${sub.id}: all ${result.length} items already seen, skipping`);
89
+ return;
90
+ }
91
+ this.logger.info(`[waker] ${sub.id}: ${newMessages.length} new message(s) out of ${result.length} total`);
92
+ // Resolve parents per new message
93
+ const mentions = [];
94
+ for (const msgAddr of newMessages) {
95
+ const parents = [];
96
+ try {
97
+ const escaped = msgAddr.replace(/'/g, "\\'");
98
+ const parentQuery = `SELECT * FROM link WHERE predicate = 'ad4m://has_child' AND target = '${escaped}'`;
99
+ this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
100
+ const parentResult = await this.perspectiveClient.querySurrealDB(sub.perspective, parentQuery);
101
+ if (Array.isArray(parentResult)) {
102
+ for (const link of parentResult) {
103
+ if (link && link.source) {
104
+ parents.push(link.source);
105
+ }
106
+ }
107
+ }
108
+ }
109
+ catch (err) {
110
+ this.logger.warn(`[waker] ${sub.id}: parent resolution failed for ${msgAddr} — ${err?.message ?? err}`);
111
+ }
112
+ this.logger.info(`[waker] ${sub.id}: message ${msgAddr} has ${parents.length} parent(s): ${parents.join(", ")}`);
113
+ mentions.push({ address: msgAddr, parents });
114
+ }
115
+ // Mark all new messages as seen
116
+ for (const addr of newMessages) {
117
+ currentSeen.add(addr);
118
+ }
119
+ this.seenMessages.set(sub.id, currentSeen);
120
+ // Debounce the wake callback
121
+ const existing = this.debounceTimers.get(sub.id);
122
+ if (existing)
123
+ clearTimeout(existing);
124
+ this.debounceTimers.set(sub.id, setTimeout(() => {
125
+ this.onWake(sub, result, mentions);
126
+ this.debounceTimers.delete(sub.id);
127
+ this.persist();
128
+ }, this.debounceMs));
129
+ }
130
+ else {
131
+ // For channel-messages: always notify the agent on every subscription push.
132
+ // No deduplication — the agent reads recent messages itself.
133
+ this.logger.info(`[waker] ${sub.id}: channel update (${result.length} items)`);
134
+ const existing = this.debounceTimers.get(sub.id);
135
+ if (existing)
136
+ clearTimeout(existing);
137
+ this.debounceTimers.set(sub.id, setTimeout(() => {
138
+ this.onWake(sub, result);
139
+ this.debounceTimers.delete(sub.id);
140
+ }, this.debounceMs));
141
+ }
142
+ });
143
+ this.proxies.set(sub.id, proxy);
144
+ this.activeSubscriptions.set(sub.id, sub);
145
+ this.persist();
146
+ this.logger.info(`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`);
147
+ }
148
+ /**
149
+ * Dispose a single subscription.
150
+ * @param persist — if false, skip calling onPersist (used during batch cleanup).
151
+ */
152
+ dispose(id, persist = true) {
153
+ const proxy = this.proxies.get(id);
154
+ if (proxy) {
155
+ try {
156
+ proxy.dispose();
157
+ }
158
+ catch {
159
+ /* ignore */
160
+ }
161
+ this.proxies.delete(id);
162
+ }
163
+ const timer = this.debounceTimers.get(id);
164
+ if (timer) {
165
+ clearTimeout(timer);
166
+ this.debounceTimers.delete(id);
167
+ }
168
+ this.activeSubscriptions.delete(id);
169
+ this.seenMessages.delete(id);
170
+ if (persist)
171
+ this.persist();
172
+ }
173
+ /** Dispose all active subscriptions. */
174
+ disposeAll() {
175
+ for (const [id] of this.proxies) {
176
+ this.dispose(id, false);
177
+ }
178
+ }
179
+ /** Get all active subscriptions. */
180
+ getActive() {
181
+ return Array.from(this.activeSubscriptions.values());
182
+ }
183
+ /** Check if a subscription exists. */
184
+ has(id) {
185
+ return this.activeSubscriptions.has(id);
186
+ }
187
+ persist() {
188
+ if (this.onPersist) {
189
+ const seen = {};
190
+ for (const [id, set] of this.seenMessages) {
191
+ seen[id] = Array.from(set);
192
+ }
193
+ this.onPersist(this.getActive(), seen);
194
+ }
195
+ }
196
+ }
@@ -75,6 +75,17 @@ export declare class VerificationRequestResult {
75
75
  requiresPassword: boolean;
76
76
  isExistingUser: boolean;
77
77
  }
78
+ export declare class HostingUserInfo {
79
+ email: string;
80
+ remainingCredits: string;
81
+ hotWalletAddress?: string;
82
+ constructor(email: string, remainingCredits: string, hotWalletAddress?: string);
83
+ }
84
+ export declare class PaymentRequestResult {
85
+ success: boolean;
86
+ message: string;
87
+ constructor(success: boolean, message: string);
88
+ }
78
89
  /**
79
90
  * Resolver classes are used here to define the GraphQL schema
80
91
  * (through the type-graphql annotations)
@@ -129,4 +140,7 @@ export default class RuntimeResolver {
129
140
  runtimeEmailTestGetCode(email: string): string | null;
130
141
  runtimeEmailTestClearCodes(): boolean;
131
142
  runtimeEmailTestSetExpiry(email: string, verificationType: string, expiresAt: number): boolean;
143
+ runtimeHostingUserInfo(): HostingUserInfo;
144
+ runtimeSetHotWalletAddress(address: string): boolean;
145
+ runtimeRequestPayment(amountHOT: string): PaymentRequestResult;
132
146
  }