@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.
- package/lib/index.cjs +5052 -4446
- package/lib/index.js +5019 -4442
- package/lib/src/agent/AgentClient.d.ts +4 -0
- package/lib/src/agent/AgentClient.js +34 -0
- package/lib/src/index.d.ts +2 -3
- package/lib/src/index.js +2 -3
- package/lib/src/model/Ad4mModel.d.ts +8 -782
- package/lib/src/model/Ad4mModel.js +160 -2354
- package/lib/src/model/ModelQueryBuilder.d.ts +370 -0
- package/lib/src/model/ModelQueryBuilder.js +556 -0
- package/lib/src/model/decorators.d.ts +71 -23
- package/lib/src/model/decorators.js +133 -384
- package/lib/src/model/hydration.d.ts +102 -0
- package/lib/src/model/hydration.js +709 -0
- package/lib/src/model/index.d.ts +20 -0
- package/lib/src/model/index.js +20 -0
- package/lib/src/model/{schema/fromJSONSchema.d.ts → json-schema.d.ts} +45 -12
- package/lib/src/model/json-schema.js +326 -0
- package/lib/src/model/prolog-facts.d.ts +37 -0
- package/lib/src/model/{prolog/generatePrologFacts.js → prolog-facts.js} +47 -52
- package/lib/src/model/query-common.d.ts +14 -0
- package/lib/src/model/query-common.js +36 -0
- package/lib/src/model/query-prolog.d.ts +15 -0
- package/lib/src/model/query-prolog.js +140 -0
- package/lib/src/model/query-surreal.d.ts +44 -0
- package/lib/src/model/query-surreal.js +249 -0
- package/lib/src/model/relation-filtering.test.js +838 -0
- package/lib/src/model/sdna.d.ts +14 -0
- package/lib/src/model/sdna.js +141 -0
- package/lib/src/model/shacl-gen.d.ts +31 -0
- package/lib/src/model/shacl-gen.js +246 -0
- package/lib/src/model/surreal-utils.d.ts +42 -0
- package/lib/src/model/surreal-utils.js +128 -0
- package/lib/src/model/types.d.ts +75 -96
- package/lib/src/model/types.js +4 -4
- package/lib/src/model/util.d.ts +4 -5
- package/lib/src/model/util.js +12 -32
- package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
- package/lib/src/perspectives/PerspectiveProxy.d.ts +1 -1
- package/lib/src/perspectives/WakerSubscriptionManager.d.ts +79 -0
- package/lib/src/perspectives/WakerSubscriptionManager.js +196 -0
- package/lib/src/runtime/RuntimeResolver.d.ts +14 -0
- package/lib/src/runtime/RuntimeResolver.js +73 -0
- package/lib/src/schema.gql +14 -0
- package/lib/src/shacl/SHACLShape.d.ts +23 -0
- package/lib/src/shacl/SHACLShape.js +45 -0
- package/lib/src/typeDefs.js +14 -0
- package/package.json +13 -8
- package/src/agent/AgentClient.ts +45 -0
- package/src/index.ts +2 -3
- package/src/model/Ad4mModel.ts +1089 -3686
- package/src/model/ModelQueryBuilder.ts +617 -0
- package/src/model/Subject.ts +1 -1
- package/src/model/decorators.ts +218 -453
- package/src/model/hydration.ts +796 -0
- package/src/model/index.ts +21 -0
- package/src/model/json-schema.ts +424 -0
- package/src/model/prolog-facts.ts +145 -0
- package/src/model/query-common.ts +48 -0
- package/src/model/query-prolog.ts +148 -0
- package/src/model/query-surreal.ts +280 -0
- package/src/model/relation-filtering.test.ts +803 -0
- package/src/model/sdna.ts +170 -0
- package/src/model/shacl-gen.ts +292 -0
- package/src/model/surreal-utils.ts +147 -0
- package/src/model/types.ts +182 -0
- package/src/model/util.ts +13 -36
- package/src/perspectives/PerspectiveClient.ts +1 -1
- package/src/perspectives/PerspectiveProxy.ts +1 -1
- package/src/perspectives/WakerSubscriptionManager.ts +292 -0
- package/src/runtime/RuntimeResolver.ts +53 -0
- package/src/shacl/SHACLShape.ts +83 -0
- package/lib/src/Ad4mClient.test.js +0 -1204
- package/lib/src/Literal.test.d.ts +0 -1
- package/lib/src/Literal.test.js +0 -41
- package/lib/src/model/mutation.d.ts +0 -81
- package/lib/src/model/mutation.js +0 -317
- package/lib/src/model/parentUtils.d.ts +0 -32
- package/lib/src/model/parentUtils.js +0 -64
- package/lib/src/model/prolog/generatePrologFacts.d.ts +0 -36
- package/lib/src/model/prolog/index.d.ts +0 -1
- package/lib/src/model/prolog/index.js +0 -1
- package/lib/src/model/query/ModelQueryBuilder.d.ts +0 -82
- package/lib/src/model/query/ModelQueryBuilder.js +0 -115
- package/lib/src/model/query/QueryBuilder.d.ts +0 -101
- package/lib/src/model/query/QueryBuilder.js +0 -193
- package/lib/src/model/query/SurrealQueryBuilder.d.ts +0 -48
- package/lib/src/model/query/SurrealQueryBuilder.js +0 -371
- package/lib/src/model/query/fetchInstance.d.ts +0 -24
- package/lib/src/model/query/fetchInstance.js +0 -144
- package/lib/src/model/query/hydration.d.ts +0 -54
- package/lib/src/model/query/hydration.js +0 -214
- package/lib/src/model/query/operations.d.ts +0 -59
- package/lib/src/model/query/operations.js +0 -384
- package/lib/src/model/query/snapshot.d.ts +0 -59
- package/lib/src/model/query/snapshot.js +0 -106
- package/lib/src/model/query/surrealCompiler.d.ts +0 -42
- package/lib/src/model/query/surrealCompiler.js +0 -304
- package/lib/src/model/schema/fromJSONSchema.js +0 -264
- package/lib/src/model/schema/metadata.d.ts +0 -15
- package/lib/src/model/schema/metadata.js +0 -112
- package/lib/src/model/subscription.d.ts +0 -47
- package/lib/src/model/subscription.js +0 -231
- package/lib/src/model/transaction.d.ts +0 -27
- package/lib/src/model/transaction.js +0 -32
- package/lib/src/shims/reflect-metadata.d.ts +0 -0
- package/lib/src/shims/type-graphql.d.ts +0 -32
- package/lib/src/src/Ad4mClient.d.ts +0 -28
- package/lib/src/src/Address.d.ts +0 -1
- package/lib/src/src/DID.d.ts +0 -1
- package/lib/src/src/Exception.d.ts +0 -7
- package/lib/src/src/Literal.d.ts +0 -7
- package/lib/src/src/PubSub.d.ts +0 -17
- package/lib/src/src/SmartLiteral.d.ts +0 -12
- package/lib/src/src/agent/Agent.d.ts +0 -110
- package/lib/src/src/agent/AgentClient.d.ts +0 -62
- package/lib/src/src/agent/AgentResolver.d.ts +0 -30
- package/lib/src/src/agent/AgentStatus.d.ts +0 -8
- package/lib/src/src/ai/AIClient.d.ts +0 -32
- package/lib/src/src/ai/AIResolver.d.ts +0 -75
- package/lib/src/src/ai/Tasks.d.ts +0 -37
- package/lib/src/src/buildSchema.d.ts +0 -1
- package/lib/src/src/expression/Expression.d.ts +0 -28
- package/lib/src/src/expression/ExpressionClient.d.ts +0 -13
- package/lib/src/src/expression/ExpressionRef.d.ts +0 -9
- package/lib/src/src/expression/ExpressionResolver.d.ts +0 -10
- package/lib/src/src/index.d.ts +0 -35
- package/lib/src/src/jestSetup.d.ts +0 -1
- package/lib/src/src/language/Icon.d.ts +0 -4
- package/lib/src/src/language/Language.d.ts +0 -206
- package/lib/src/src/language/LanguageClient.d.ts +0 -17
- package/lib/src/src/language/LanguageContext.d.ts +0 -37
- package/lib/src/src/language/LanguageHandle.d.ts +0 -9
- package/lib/src/src/language/LanguageMeta.d.ts +0 -35
- package/lib/src/src/language/LanguageRef.d.ts +0 -6
- package/lib/src/src/language/LanguageResolver.d.ts +0 -19
- package/lib/src/src/links/Links.d.ts +0 -39
- package/lib/src/src/links/Links.test.d.ts +0 -1
- package/lib/src/src/model/Ad4mModel.d.ts +0 -1438
- package/lib/src/src/model/Ad4mModel.test.d.ts +0 -1
- package/lib/src/src/model/Subject.d.ts +0 -25
- package/lib/src/src/model/decorators.d.ts +0 -545
- package/lib/src/src/model/util.d.ts +0 -12
- package/lib/src/src/neighbourhood/Neighbourhood.d.ts +0 -10
- package/lib/src/src/neighbourhood/NeighbourhoodClient.d.ts +0 -25
- package/lib/src/src/neighbourhood/NeighbourhoodProxy.d.ts +0 -19
- package/lib/src/src/neighbourhood/NeighbourhoodProxy.test.d.ts +0 -1
- package/lib/src/src/neighbourhood/NeighbourhoodResolver.d.ts +0 -24
- package/lib/src/src/perspectives/LinkQuery.d.ts +0 -11
- package/lib/src/src/perspectives/Perspective.d.ts +0 -38
- package/lib/src/src/perspectives/Perspective.test.d.ts +0 -1
- package/lib/src/src/perspectives/PerspectiveClient.d.ts +0 -97
- package/lib/src/src/perspectives/PerspectiveDiff.d.ts +0 -9
- package/lib/src/src/perspectives/PerspectiveHandle.d.ts +0 -18
- package/lib/src/src/perspectives/PerspectiveProxy.d.ts +0 -865
- package/lib/src/src/perspectives/PerspectiveResolver.d.ts +0 -57
- package/lib/src/src/runtime/RuntimeClient.d.ts +0 -56
- package/lib/src/src/runtime/RuntimeResolver.d.ts +0 -132
- package/lib/src/src/shacl/SHACLFlow.d.ts +0 -171
- package/lib/src/src/shacl/SHACLFlow.test.d.ts +0 -1
- package/lib/src/src/shacl/SHACLShape.d.ts +0 -117
- package/lib/src/src/shacl/SHACLShape.test.d.ts +0 -1
- package/lib/src/src/typeDefs.d.ts +0 -1
- package/lib/src/src/unwrapApolloResult.d.ts +0 -2
- package/lib/src/src/utils.d.ts +0 -25
- /package/lib/src/{Ad4mClient.test.d.ts → model/relation-filtering.test.d.ts} +0 -0
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared type definitions for the Ad4mModel system.
|
|
3
|
+
*
|
|
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
|
+
*/
|
|
8
|
+
|
|
9
|
+
// ---------------------------------------------------------------------------
|
|
10
|
+
// Forward type-only reference to Ad4mModel (no runtime circular dependency)
|
|
11
|
+
// ---------------------------------------------------------------------------
|
|
12
|
+
import type { Ad4mModel } from "./Ad4mModel";
|
|
13
|
+
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
// Query DSL types
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
|
|
18
|
+
export type WhereOps = {
|
|
19
|
+
not: string | number | boolean | string[] | number[];
|
|
20
|
+
between: [number, number];
|
|
21
|
+
lt: number; // less than
|
|
22
|
+
lte: number; // less than or equal to
|
|
23
|
+
gt: number; // greater than
|
|
24
|
+
gte: number; // greater than or equal to
|
|
25
|
+
contains: string | number; // substring/element check
|
|
26
|
+
};
|
|
27
|
+
export type WhereCondition = string | number | boolean | string[] | number[] | { [K in keyof WhereOps]?: WhereOps[K] };
|
|
28
|
+
export type Where = { [propertyName: string]: WhereCondition };
|
|
29
|
+
export type Order = { [propertyName: string]: "ASC" | "DESC" };
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Discriminated union for parent-scoped queries.
|
|
33
|
+
*
|
|
34
|
+
* **Model form** (preferred) — predicate auto-resolved from the parent model's
|
|
35
|
+
* relation metadata. Use `field` to disambiguate when the parent has multiple
|
|
36
|
+
* relations targeting the same child class.
|
|
37
|
+
*
|
|
38
|
+
* **Raw form** — explicit predicate string, no metadata lookup.
|
|
39
|
+
*/
|
|
40
|
+
export type ParentScope =
|
|
41
|
+
| { model: typeof Ad4mModel; id: string; field?: string }
|
|
42
|
+
| { id: string; predicate: string };
|
|
43
|
+
|
|
44
|
+
/**
|
|
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
|
+
* ```
|
|
62
|
+
*/
|
|
63
|
+
export interface IncludeMap {
|
|
64
|
+
[relation: string]: boolean | RelationSubQuery;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export type Query = {
|
|
68
|
+
/** Filter to instances that are the target of a link from a given parent. */
|
|
69
|
+
parent?: ParentScope;
|
|
70
|
+
properties?: string[];
|
|
71
|
+
include?: IncludeMap;
|
|
72
|
+
where?: Where;
|
|
73
|
+
order?: Order;
|
|
74
|
+
offset?: number;
|
|
75
|
+
limit?: number;
|
|
76
|
+
count?: boolean;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Sub-query options for a specific relation inside an `IncludeMap`.
|
|
81
|
+
*
|
|
82
|
+
* Equivalent to `Query` without top-level scoping (`parent`) or `count`,
|
|
83
|
+
* since the result set is already constrained to the linked relation.
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```typescript
|
|
87
|
+
* await post.get({ include: { comments: { order: { createdAt: 'DESC' }, limit: 5 } } });
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
export type RelationSubQuery = Omit<Query, 'parent' | 'count'>;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Options accepted by the instance `get()` method.
|
|
94
|
+
*
|
|
95
|
+
* A subset of `Query` — only hydration controls apply to a single known instance.
|
|
96
|
+
*/
|
|
97
|
+
export type GetOptions = Pick<Query, 'include' | 'properties'>;
|
|
98
|
+
|
|
99
|
+
// ---------------------------------------------------------------------------
|
|
100
|
+
// Result types
|
|
101
|
+
// ---------------------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
export type AllInstancesResult = { AllInstances: Ad4mModel[]; TotalCount?: number; isInit?: boolean };
|
|
104
|
+
export type ResultsWithTotalCount<T> = { results: T[]; totalCount?: number };
|
|
105
|
+
export type PaginationResult<T> = { results: T[]; totalCount?: number; pageSize: number; pageNumber: number };
|
|
106
|
+
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
// Internal value transport
|
|
109
|
+
// ---------------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
export type ValueTuple = [name: string, value: any, resolve?: boolean];
|
|
112
|
+
|
|
113
|
+
// ---------------------------------------------------------------------------
|
|
114
|
+
// Model metadata interfaces
|
|
115
|
+
// ---------------------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Metadata for a single property extracted from decorators.
|
|
119
|
+
*/
|
|
120
|
+
export interface PropertyMetadata {
|
|
121
|
+
/** The property name */
|
|
122
|
+
name: string;
|
|
123
|
+
/** The predicate URI (through value) */
|
|
124
|
+
predicate: string;
|
|
125
|
+
/** Whether the property is required */
|
|
126
|
+
required: boolean;
|
|
127
|
+
/** Whether the property is read-only */
|
|
128
|
+
readOnly: boolean;
|
|
129
|
+
/** Initial value if specified */
|
|
130
|
+
initial?: string;
|
|
131
|
+
/** Language for resolution (e.g., "literal") */
|
|
132
|
+
resolveLanguage?: string;
|
|
133
|
+
/** Custom Prolog getter code */
|
|
134
|
+
prologGetter?: string;
|
|
135
|
+
/** Custom Prolog setter code */
|
|
136
|
+
prologSetter?: string;
|
|
137
|
+
/** Custom SurrealQL getter code */
|
|
138
|
+
getter?: string;
|
|
139
|
+
/** Whether stored locally only */
|
|
140
|
+
local?: boolean;
|
|
141
|
+
/** Transform function */
|
|
142
|
+
transform?: (value: any) => any;
|
|
143
|
+
/** Whether this is a flag property */
|
|
144
|
+
flag?: boolean;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Metadata for a single relation extracted from decorators.
|
|
149
|
+
*/
|
|
150
|
+
export interface RelationMetadata {
|
|
151
|
+
/** The relation name */
|
|
152
|
+
name: string;
|
|
153
|
+
/** The predicate URI (through value) */
|
|
154
|
+
predicate: string;
|
|
155
|
+
/** Custom SurrealQL getter code */
|
|
156
|
+
getter?: string;
|
|
157
|
+
/** Whether stored locally only */
|
|
158
|
+
local?: boolean;
|
|
159
|
+
/** Link direction: 'forward' for HasMany/HasOne, 'reverse' for BelongsToMany/BelongsToOne */
|
|
160
|
+
direction?: 'forward' | 'reverse';
|
|
161
|
+
/** Target model class thunk for hydration and type filtering */
|
|
162
|
+
target?: () => any;
|
|
163
|
+
/**
|
|
164
|
+
* Whether to auto-generate a conformance filter when `target` is set.
|
|
165
|
+
* Defaults to `true` — set to `false` to opt out of DB-level type filtering.
|
|
166
|
+
*/
|
|
167
|
+
filter?: boolean;
|
|
168
|
+
/** Where clause for relation filtering (query DSL) */
|
|
169
|
+
where?: Where;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Complete model metadata extracted from decorators.
|
|
174
|
+
*/
|
|
175
|
+
export interface ModelMetadata {
|
|
176
|
+
/** The model class name from @Model */
|
|
177
|
+
className: string;
|
|
178
|
+
/** Map of property name to metadata */
|
|
179
|
+
properties: Record<string, PropertyMetadata>;
|
|
180
|
+
/** Map of relation name to metadata */
|
|
181
|
+
relations: Record<string, RelationMetadata>;
|
|
182
|
+
}
|
package/src/model/util.ts
CHANGED
|
@@ -7,19 +7,6 @@ export function propertyNameToSetterName(property: string): string {
|
|
|
7
7
|
return `set${capitalize(property)}`
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
-
// e.g. "setName" -> "name"
|
|
11
|
-
export function setterNameToPropertyName(setter: string): string {
|
|
12
|
-
return setter.replace("set", "").replace(/^[A-Z]/, (m) => m.toLowerCase())
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export function singularToPlural(singular: string): string {
|
|
16
|
-
if(singular.endsWith("y")) {
|
|
17
|
-
return singular.slice(0, -1) + "ies"
|
|
18
|
-
} else {
|
|
19
|
-
return singular + "s"
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
|
|
23
10
|
export function pluralToSingular(plural: string): string {
|
|
24
11
|
if(plural.endsWith("ies")) {
|
|
25
12
|
return plural.slice(0, -3) + "y"
|
|
@@ -35,40 +22,30 @@ export function relationToAdderName(relation: string): string {
|
|
|
35
22
|
return `add${capitalize(pluralToSingular(relation))}`
|
|
36
23
|
}
|
|
37
24
|
|
|
38
|
-
// e.g. "addComments" -> "comments"
|
|
39
|
-
export function relationAdderToName(adderName: string): string {
|
|
40
|
-
// Extract the relation name after "add" and lowercase first char
|
|
41
|
-
// The method name already has the plural relation name (e.g., "addComments")
|
|
42
|
-
let relationName = adderName.substring(3)
|
|
43
|
-
return relationName.charAt(0).toLowerCase() + relationName.slice(1)
|
|
44
|
-
}
|
|
45
|
-
|
|
46
25
|
// e.g. "comments" -> "removeComment"
|
|
47
26
|
export function relationToRemoverName(relation: string): string {
|
|
48
27
|
return `remove${capitalize(pluralToSingular(relation))}`
|
|
49
28
|
}
|
|
50
29
|
|
|
51
|
-
// e.g. "removeComments" -> "comments"
|
|
52
|
-
export function relationRemoverToName(removerName: string): string {
|
|
53
|
-
// Extract the relation name after "remove" and lowercase first char
|
|
54
|
-
// The method name already has the plural relation name (e.g., "removeComments")
|
|
55
|
-
let relationName = removerName.substring(6)
|
|
56
|
-
return relationName.charAt(0).toLowerCase() + relationName.slice(1)
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
export function relationSetterToName(setterName: string): string {
|
|
60
|
-
// Extract the relation name after "set" and lowercase first char
|
|
61
|
-
// The method name already has the plural relation name (e.g., "setComments")
|
|
62
|
-
let relationName = setterName.substring(3)
|
|
63
|
-
return relationName.charAt(0).toLowerCase() + relationName.slice(1)
|
|
64
|
-
}
|
|
65
|
-
|
|
66
30
|
// e.g. "comments" -> "setComments"
|
|
67
31
|
export function relationToSetterName(relation: string): string {
|
|
68
32
|
return `set${capitalize(relation)}`
|
|
69
33
|
}
|
|
70
34
|
|
|
71
35
|
|
|
36
|
+
/**
|
|
37
|
+
* Generate a random identifier string of the given length (lowercase alpha).
|
|
38
|
+
*/
|
|
39
|
+
export function makeRandomId(length: number): string {
|
|
40
|
+
let result = '';
|
|
41
|
+
const characters = 'abcdefghijklmnopqrstuvwxyz';
|
|
42
|
+
const charactersLength = characters.length;
|
|
43
|
+
for (let i = 0; i < length; i++) {
|
|
44
|
+
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
|
45
|
+
}
|
|
46
|
+
return result;
|
|
47
|
+
}
|
|
48
|
+
|
|
72
49
|
export function stringifyObjectLiteral(obj) {
|
|
73
50
|
if(Array.isArray(obj)) {
|
|
74
51
|
//@ts-ignore
|
|
@@ -10,7 +10,7 @@ import { Perspective } from "./Perspective";
|
|
|
10
10
|
import { PerspectiveHandle, PerspectiveState } from "./PerspectiveHandle";
|
|
11
11
|
import { LinkStatus, PerspectiveProxy } from './PerspectiveProxy';
|
|
12
12
|
import { AIClient } from "../ai/AIClient";
|
|
13
|
-
import { AllInstancesResult } from "../model/
|
|
13
|
+
import { AllInstancesResult } from "../model/types";
|
|
14
14
|
|
|
15
15
|
const LINK_EXPRESSION_FIELDS = `
|
|
16
16
|
author
|
|
@@ -12,7 +12,7 @@ import { AIClient } from "../ai/AIClient";
|
|
|
12
12
|
import { PERSPECTIVE_QUERY_SUBSCRIPTION } from "./PerspectiveResolver";
|
|
13
13
|
import { gql } from "@apollo/client/core";
|
|
14
14
|
import { getPropertiesMetadata, getRelationsMetadata } from "../model/decorators";
|
|
15
|
-
import { AllInstancesResult } from "../model/
|
|
15
|
+
import { AllInstancesResult } from "../model/types";
|
|
16
16
|
import { escapeSurrealString } from "../utils";
|
|
17
17
|
import { SHACLShape } from "../shacl/SHACLShape";
|
|
18
18
|
import { SHACLFlow, LinkPattern } from "../shacl/SHACLFlow";
|
|
@@ -0,0 +1,292 @@
|
|
|
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
|
+
|
|
10
|
+
export interface WakerSubscription {
|
|
11
|
+
id: string;
|
|
12
|
+
type: "mention" | "channel-messages";
|
|
13
|
+
perspective: string;
|
|
14
|
+
channel: string;
|
|
15
|
+
query: string;
|
|
16
|
+
neighbourhood?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Per-message parent resolution result for mention subscriptions. */
|
|
20
|
+
export interface MentionMessage {
|
|
21
|
+
/** The message's expression address (source of the body link). */
|
|
22
|
+
address: string;
|
|
23
|
+
/** All parent addresses this message belongs to (channels, conversations, etc.). */
|
|
24
|
+
parents: string[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface WakerLogger {
|
|
28
|
+
info(msg: string): void;
|
|
29
|
+
warn(msg: string): void;
|
|
30
|
+
error(msg: string): void;
|
|
31
|
+
debug(msg: string): void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface WakerSubscriptionManagerOptions {
|
|
35
|
+
/** PerspectiveClient from Ad4mClient (provides perspectiveSubscribeSurrealQuery etc.) */
|
|
36
|
+
perspectiveClient: any;
|
|
37
|
+
/** Logger instance */
|
|
38
|
+
logger: WakerLogger;
|
|
39
|
+
/** Debounce interval in ms before firing the wake callback (default 2000) */
|
|
40
|
+
debounceMs?: number;
|
|
41
|
+
/** Called when a subscription fires (after debounce). Return value is ignored.
|
|
42
|
+
* For mention subs, `mentions` contains per-message parent info. */
|
|
43
|
+
onWake: (sub: WakerSubscription, result: any, mentions?: MentionMessage[]) => void;
|
|
44
|
+
/** Called when the active subscription list changes (for persistence). */
|
|
45
|
+
onPersist?: (subscriptions: WakerSubscription[], seenMessages: Record<string, string[]>) => void;
|
|
46
|
+
/** Previously persisted seen message IDs per subscription. Seeds seenMessages on resubscribe to avoid duplicate wakes. */
|
|
47
|
+
previousSeenMessages?: Record<string, string[]>;
|
|
48
|
+
/** Optional: provide QuerySubscriptionProxy class directly (avoids require("@coasys/ad4m") at runtime). */
|
|
49
|
+
QuerySubscriptionProxy?: any;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export class WakerSubscriptionManager {
|
|
53
|
+
private perspectiveClient: any;
|
|
54
|
+
private logger: WakerLogger;
|
|
55
|
+
private debounceMs: number;
|
|
56
|
+
private onWake: (sub: WakerSubscription, result: any, mentions?: MentionMessage[]) => void;
|
|
57
|
+
private onPersist?: (subscriptions: WakerSubscription[], seenMessages: Record<string, string[]>) => void;
|
|
58
|
+
private QuerySubscriptionProxyCtor: any;
|
|
59
|
+
private previousSeenMessages: Record<string, string[]>;
|
|
60
|
+
|
|
61
|
+
private proxies = new Map<string, any>();
|
|
62
|
+
private activeSubscriptions = new Map<string, WakerSubscription>();
|
|
63
|
+
private debounceTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
64
|
+
/** Per-subscription set of already-processed message addresses (for mention subs)
|
|
65
|
+
* or serialized result hash (for channel-messages subs). */
|
|
66
|
+
private seenMessages = new Map<string, Set<string>>();
|
|
67
|
+
|
|
68
|
+
constructor(options: WakerSubscriptionManagerOptions) {
|
|
69
|
+
this.perspectiveClient = options.perspectiveClient;
|
|
70
|
+
this.logger = options.logger;
|
|
71
|
+
this.debounceMs = options.debounceMs ?? 2000;
|
|
72
|
+
this.onWake = options.onWake;
|
|
73
|
+
this.onPersist = options.onPersist;
|
|
74
|
+
this.QuerySubscriptionProxyCtor = options.QuerySubscriptionProxy ?? null;
|
|
75
|
+
this.previousSeenMessages = options.previousSeenMessages ?? {};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Create a live SurrealDB subscription.
|
|
80
|
+
* If a subscription with the same id already exists, it is disposed first.
|
|
81
|
+
*/
|
|
82
|
+
async subscribe(sub: WakerSubscription): Promise<void> {
|
|
83
|
+
// Dispose existing subscription with same id if any
|
|
84
|
+
this.dispose(sub.id, false);
|
|
85
|
+
|
|
86
|
+
if (!this.QuerySubscriptionProxyCtor) {
|
|
87
|
+
throw new Error("WakerSubscriptionManager: QuerySubscriptionProxy must be provided via constructor options");
|
|
88
|
+
}
|
|
89
|
+
const QuerySubscriptionProxy = this.QuerySubscriptionProxyCtor;
|
|
90
|
+
|
|
91
|
+
this.logger.info(
|
|
92
|
+
`[waker] ${sub.id}: creating subscription (perspective=${sub.perspective}, type=${sub.type})`,
|
|
93
|
+
);
|
|
94
|
+
this.logger.info(`[waker] ${sub.id}: SurrealQL query:\n${sub.query}`);
|
|
95
|
+
|
|
96
|
+
const proxy = new QuerySubscriptionProxy(
|
|
97
|
+
sub.perspective,
|
|
98
|
+
sub.query,
|
|
99
|
+
this.perspectiveClient,
|
|
100
|
+
);
|
|
101
|
+
proxy.isSurrealDB = true;
|
|
102
|
+
// Suppress unhandled rejection from proxy.initialized — QuerySubscriptionProxy
|
|
103
|
+
// rejects this promise internally when subscribe() fails, and if nobody catches
|
|
104
|
+
// it before the next microtask it crashes the process.
|
|
105
|
+
if (proxy.initialized && typeof proxy.initialized.catch === "function") {
|
|
106
|
+
proxy.initialized.catch(() => {});
|
|
107
|
+
}
|
|
108
|
+
try {
|
|
109
|
+
await proxy.subscribe();
|
|
110
|
+
await proxy.initialized;
|
|
111
|
+
} catch (err: any) {
|
|
112
|
+
const msg = err?.message ?? String(err);
|
|
113
|
+
this.logger.warn(
|
|
114
|
+
`[waker] ${sub.id}: subscription failed — ${msg}`,
|
|
115
|
+
);
|
|
116
|
+
try { proxy.dispose(); } catch {}
|
|
117
|
+
// Remove from active state so it doesn't get persisted/retried
|
|
118
|
+
this.activeSubscriptions.delete(sub.id);
|
|
119
|
+
this.seenMessages.delete(sub.id);
|
|
120
|
+
this.persist();
|
|
121
|
+
return; // Don't throw — caller should not crash
|
|
122
|
+
}
|
|
123
|
+
this.logger.info(`[waker] ${sub.id}: subscription initialized successfully`);
|
|
124
|
+
|
|
125
|
+
// Seed from persisted seen messages so we don't re-wake after restart
|
|
126
|
+
const seen = new Set<string>(this.previousSeenMessages[sub.id] ?? []);
|
|
127
|
+
this.seenMessages.set(sub.id, seen);
|
|
128
|
+
if (seen.size > 0) {
|
|
129
|
+
this.logger.info(`[waker] ${sub.id}: seeded ${seen.size} seen message(s) from persisted state`);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
proxy.onResult(async (result: any) => {
|
|
133
|
+
this.logger.info(
|
|
134
|
+
`[waker] ${sub.id}: onResult fired — type=${typeof result}, isArray=${Array.isArray(result)}, value=${String(JSON.stringify(result)).substring(0, 500)}`,
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
// SurrealDB can deliver non-array values (e.g. false) on disconnect/reconnect — ignore them
|
|
138
|
+
if (!Array.isArray(result)) {
|
|
139
|
+
this.logger.warn(
|
|
140
|
+
`[waker] ${sub.id}: ignoring non-array result: ${JSON.stringify(result)}`,
|
|
141
|
+
);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (sub.type === "mention") {
|
|
146
|
+
// For mention subscriptions: track seen message addresses.
|
|
147
|
+
// Only wake for messages we haven't seen before.
|
|
148
|
+
const currentSeen = this.seenMessages.get(sub.id) ?? new Set<string>();
|
|
149
|
+
const newMessages: string[] = [];
|
|
150
|
+
|
|
151
|
+
for (const item of result) {
|
|
152
|
+
if (item && item.source && !currentSeen.has(item.source)) {
|
|
153
|
+
newMessages.push(item.source);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (newMessages.length === 0) {
|
|
158
|
+
this.logger.info(
|
|
159
|
+
`[waker] ${sub.id}: all ${result.length} items already seen, skipping`,
|
|
160
|
+
);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
this.logger.info(
|
|
165
|
+
`[waker] ${sub.id}: ${newMessages.length} new message(s) out of ${result.length} total`,
|
|
166
|
+
);
|
|
167
|
+
|
|
168
|
+
// Resolve parents per new message
|
|
169
|
+
const mentions: MentionMessage[] = [];
|
|
170
|
+
for (const msgAddr of newMessages) {
|
|
171
|
+
const parents: string[] = [];
|
|
172
|
+
try {
|
|
173
|
+
const escaped = msgAddr.replace(/'/g, "\\'");
|
|
174
|
+
const parentQuery = `SELECT * FROM link WHERE predicate = 'ad4m://has_child' AND target = '${escaped}'`;
|
|
175
|
+
this.logger.info(`[waker] ${sub.id}: resolving parents for ${msgAddr}`);
|
|
176
|
+
const parentResult = await this.perspectiveClient.querySurrealDB(sub.perspective, parentQuery);
|
|
177
|
+
if (Array.isArray(parentResult)) {
|
|
178
|
+
for (const link of parentResult) {
|
|
179
|
+
if (link && link.source) {
|
|
180
|
+
parents.push(link.source);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
} catch (err: any) {
|
|
185
|
+
this.logger.warn(
|
|
186
|
+
`[waker] ${sub.id}: parent resolution failed for ${msgAddr} — ${err?.message ?? err}`,
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
this.logger.info(
|
|
190
|
+
`[waker] ${sub.id}: message ${msgAddr} has ${parents.length} parent(s): ${parents.join(", ")}`,
|
|
191
|
+
);
|
|
192
|
+
mentions.push({ address: msgAddr, parents });
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Mark all new messages as seen
|
|
196
|
+
for (const addr of newMessages) {
|
|
197
|
+
currentSeen.add(addr);
|
|
198
|
+
}
|
|
199
|
+
this.seenMessages.set(sub.id, currentSeen);
|
|
200
|
+
|
|
201
|
+
// Debounce the wake callback
|
|
202
|
+
const existing = this.debounceTimers.get(sub.id);
|
|
203
|
+
if (existing) clearTimeout(existing);
|
|
204
|
+
|
|
205
|
+
this.debounceTimers.set(
|
|
206
|
+
sub.id,
|
|
207
|
+
setTimeout(() => {
|
|
208
|
+
this.onWake(sub, result, mentions);
|
|
209
|
+
this.debounceTimers.delete(sub.id);
|
|
210
|
+
this.persist();
|
|
211
|
+
}, this.debounceMs),
|
|
212
|
+
);
|
|
213
|
+
} else {
|
|
214
|
+
// For channel-messages: always notify the agent on every subscription push.
|
|
215
|
+
// No deduplication — the agent reads recent messages itself.
|
|
216
|
+
this.logger.info(
|
|
217
|
+
`[waker] ${sub.id}: channel update (${result.length} items)`,
|
|
218
|
+
);
|
|
219
|
+
|
|
220
|
+
const existing = this.debounceTimers.get(sub.id);
|
|
221
|
+
if (existing) clearTimeout(existing);
|
|
222
|
+
|
|
223
|
+
this.debounceTimers.set(
|
|
224
|
+
sub.id,
|
|
225
|
+
setTimeout(() => {
|
|
226
|
+
this.onWake(sub, result);
|
|
227
|
+
this.debounceTimers.delete(sub.id);
|
|
228
|
+
}, this.debounceMs),
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
this.proxies.set(sub.id, proxy);
|
|
234
|
+
this.activeSubscriptions.set(sub.id, sub);
|
|
235
|
+
this.persist();
|
|
236
|
+
|
|
237
|
+
this.logger.info(
|
|
238
|
+
`[waker] Subscription ${sub.id} active (type=${sub.type}, perspective=${sub.perspective})`,
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Dispose a single subscription.
|
|
244
|
+
* @param persist — if false, skip calling onPersist (used during batch cleanup).
|
|
245
|
+
*/
|
|
246
|
+
dispose(id: string, persist = true): void {
|
|
247
|
+
const proxy = this.proxies.get(id);
|
|
248
|
+
if (proxy) {
|
|
249
|
+
try {
|
|
250
|
+
proxy.dispose();
|
|
251
|
+
} catch {
|
|
252
|
+
/* ignore */
|
|
253
|
+
}
|
|
254
|
+
this.proxies.delete(id);
|
|
255
|
+
}
|
|
256
|
+
const timer = this.debounceTimers.get(id);
|
|
257
|
+
if (timer) {
|
|
258
|
+
clearTimeout(timer);
|
|
259
|
+
this.debounceTimers.delete(id);
|
|
260
|
+
}
|
|
261
|
+
this.activeSubscriptions.delete(id);
|
|
262
|
+
this.seenMessages.delete(id);
|
|
263
|
+
if (persist) this.persist();
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Dispose all active subscriptions. */
|
|
267
|
+
disposeAll(): void {
|
|
268
|
+
for (const [id] of this.proxies) {
|
|
269
|
+
this.dispose(id, false);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Get all active subscriptions. */
|
|
274
|
+
getActive(): WakerSubscription[] {
|
|
275
|
+
return Array.from(this.activeSubscriptions.values());
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Check if a subscription exists. */
|
|
279
|
+
has(id: string): boolean {
|
|
280
|
+
return this.activeSubscriptions.has(id);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
private persist(): void {
|
|
284
|
+
if (this.onPersist) {
|
|
285
|
+
const seen: Record<string, string[]> = {};
|
|
286
|
+
for (const [id, set] of this.seenMessages) {
|
|
287
|
+
seen[id] = Array.from(set);
|
|
288
|
+
}
|
|
289
|
+
this.onPersist(this.getActive(), seen);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
@@ -223,6 +223,38 @@ export class VerificationRequestResult {
|
|
|
223
223
|
isExistingUser: boolean;
|
|
224
224
|
}
|
|
225
225
|
|
|
226
|
+
@ObjectType()
|
|
227
|
+
export class HostingUserInfo {
|
|
228
|
+
@Field()
|
|
229
|
+
email: string;
|
|
230
|
+
|
|
231
|
+
@Field()
|
|
232
|
+
remainingCredits: string;
|
|
233
|
+
|
|
234
|
+
@Field({ nullable: true })
|
|
235
|
+
hotWalletAddress?: string;
|
|
236
|
+
|
|
237
|
+
constructor(email: string, remainingCredits: string, hotWalletAddress?: string) {
|
|
238
|
+
this.email = email;
|
|
239
|
+
this.remainingCredits = remainingCredits;
|
|
240
|
+
this.hotWalletAddress = hotWalletAddress;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
@ObjectType()
|
|
245
|
+
export class PaymentRequestResult {
|
|
246
|
+
@Field()
|
|
247
|
+
success: boolean;
|
|
248
|
+
|
|
249
|
+
@Field()
|
|
250
|
+
message: string;
|
|
251
|
+
|
|
252
|
+
constructor(success: boolean, message: string) {
|
|
253
|
+
this.success = success;
|
|
254
|
+
this.message = message;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
226
258
|
/**
|
|
227
259
|
* Resolver classes are used here to define the GraphQL schema
|
|
228
260
|
* (through the type-graphql annotations)
|
|
@@ -560,5 +592,26 @@ export default class RuntimeResolver {
|
|
|
560
592
|
// For testing: simulate setting expiry (no-op in mock)
|
|
561
593
|
return true
|
|
562
594
|
}
|
|
595
|
+
|
|
596
|
+
// Hosting mutations & queries
|
|
597
|
+
|
|
598
|
+
@Query(returns => HostingUserInfo)
|
|
599
|
+
runtimeHostingUserInfo(): HostingUserInfo {
|
|
600
|
+
return new HostingUserInfo("test@example.com", "100000000", null)
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
@Mutation(returns => Boolean)
|
|
604
|
+
runtimeSetHotWalletAddress(
|
|
605
|
+
@Arg("address") address: string
|
|
606
|
+
): boolean {
|
|
607
|
+
return true
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
@Mutation(returns => PaymentRequestResult)
|
|
611
|
+
runtimeRequestPayment(
|
|
612
|
+
@Arg("amountHOT") amountHOT: string
|
|
613
|
+
): PaymentRequestResult {
|
|
614
|
+
return new PaymentRequestResult(true, "Mock payment of " + amountHOT + " base units credited")
|
|
615
|
+
}
|
|
563
616
|
}
|
|
564
617
|
|