@coasys/ad4m 0.13.0-postmessage-ws-proxy.0 → 0.13.0-postmessage-ws-proxy.3
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 +564 -461
- package/lib/index.js +561 -462
- package/lib/src/index.d.ts +1 -0
- package/lib/src/index.js +1 -0
- package/lib/src/model/Ad4mModel.d.ts +9 -17
- package/lib/src/model/Ad4mModel.js +34 -148
- package/lib/src/model/ModelQueryBuilder.d.ts +5 -10
- package/lib/src/model/ModelQueryBuilder.js +8 -14
- package/lib/src/model/shacl-gen.js +115 -46
- package/lib/src/model/types.d.ts +138 -3
- package/lib/src/perspectives/PerspectiveClient.d.ts +4 -4
- package/lib/src/perspectives/PerspectiveClient.js +5 -6
- package/lib/src/perspectives/PerspectiveProxy.d.ts +8 -7
- package/lib/src/perspectives/PerspectiveProxy.js +10 -9
- package/lib/src/perspectives/SparqlBindings.d.ts +47 -0
- package/lib/src/perspectives/SparqlBindings.js +65 -0
- package/lib/src/shacl/SHACLShape.d.ts +18 -0
- package/lib/src/shacl/SHACLShape.js +83 -0
- package/package.json +8 -11
- package/src/index.ts +1 -0
- package/src/model/Ad4mModel.test.ts +23 -64
- package/src/model/Ad4mModel.ts +52 -159
- package/src/model/ModelQueryBuilder.ts +17 -23
- package/src/model/relation-filtering.test.ts +46 -39
- package/src/model/shacl-gen.ts +122 -53
- package/src/model/shacl-roundtrip.test.ts +197 -0
- package/src/model/types-typed-query.test.ts +360 -0
- package/src/model/types.ts +194 -3
- package/src/perspectives/PerspectiveClient.ts +6 -8
- package/src/perspectives/PerspectiveProxy.ts +13 -13
- package/src/perspectives/SparqlBindings.ts +79 -0
- package/src/shacl/SHACLShape.test.ts +110 -0
- package/src/shacl/SHACLShape.ts +125 -0
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type-level assertion tests for the TypedQuery / TypedWhere / TypedIncludeMap
|
|
3
|
+
* surface added in PLAN_6.
|
|
4
|
+
*
|
|
5
|
+
* These tests verify the *compile-time* behaviour of the generic query types.
|
|
6
|
+
* Runtime assertions are minimal — the real checks are the `// @ts-expect-error`
|
|
7
|
+
* markers and the `expectAssignable` / `expectExact` helpers, all of which fail
|
|
8
|
+
* loudly under `tsc --noEmit`.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { Ad4mModel } from "./Ad4mModel";
|
|
12
|
+
import { Model, Property, HasMany, BelongsToOne } from "./decorators";
|
|
13
|
+
import type {
|
|
14
|
+
PropertyKeysOf, RelationKeysOf, RelatedModel,
|
|
15
|
+
TypedQuery, TypedWhere, TypedOrder, TypedIncludeMap, TypedIncludeProjection,
|
|
16
|
+
IncludeExtras, Query,
|
|
17
|
+
} from "./types";
|
|
18
|
+
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
// Fixtures
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
|
|
23
|
+
@Model({ name: "Comment" })
|
|
24
|
+
class Comment extends Ad4mModel {
|
|
25
|
+
@Property({ through: "comment://text" })
|
|
26
|
+
text: string = "";
|
|
27
|
+
|
|
28
|
+
@Property({ through: "comment://likes" })
|
|
29
|
+
likes: number = 0;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
@Model({ name: "Post" })
|
|
33
|
+
class Post extends Ad4mModel {
|
|
34
|
+
@Property({ through: "post://title", required: true })
|
|
35
|
+
title: string = "";
|
|
36
|
+
|
|
37
|
+
@Property({ through: "post://body" })
|
|
38
|
+
body: string = "";
|
|
39
|
+
|
|
40
|
+
@Property({ through: "post://is_pinned" })
|
|
41
|
+
isPinned: boolean = false;
|
|
42
|
+
|
|
43
|
+
@Property({ through: "post://views" })
|
|
44
|
+
views: number = 0;
|
|
45
|
+
|
|
46
|
+
@HasMany(() => Comment, { through: "post://comment" })
|
|
47
|
+
comments: Comment[] = [];
|
|
48
|
+
|
|
49
|
+
@BelongsToOne({ through: "post://author_of" })
|
|
50
|
+
authorRef: Comment | null = null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// AgentProfile-like fixture: inheritance + optional HasOne relation.
|
|
54
|
+
// This mirrors `we/packages/models/src/entities/AgentProfile.ts` which
|
|
55
|
+
// previously surfaced a type bug in StrictTypedIncludeMap.
|
|
56
|
+
class WeNodeLike extends Ad4mModel {
|
|
57
|
+
@HasMany({ through: "we://signal" })
|
|
58
|
+
signals: string[] = [];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
class LocationBlockLike extends WeNodeLike {
|
|
62
|
+
@Property({ through: "loc://name" })
|
|
63
|
+
name: string = "";
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
@Model({ name: "AgentProfileLike" })
|
|
67
|
+
class AgentProfileLike extends WeNodeLike {
|
|
68
|
+
@Property({ through: "we://handle" })
|
|
69
|
+
handle: string = "";
|
|
70
|
+
|
|
71
|
+
@Property({ through: "we://avatar" })
|
|
72
|
+
avatar?: string;
|
|
73
|
+
|
|
74
|
+
// Optional HasOne — Ad4mModel | undefined. Was previously not picked up
|
|
75
|
+
// by RelationKeysOf (which only checked `| null`), causing valid
|
|
76
|
+
// `include: { location: true }` calls to be rejected at the type level.
|
|
77
|
+
location?: LocationBlockLike;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Optional-array fixture: covers `?: T[]` and `?: string[]` patterns. Before
|
|
81
|
+
// the `NonNullable<T[K]> extends X[]` change, these optional array relations
|
|
82
|
+
// were silently dropped from RelationKeysOf because `Foo[] | undefined extends
|
|
83
|
+
// Foo[]` evaluates to false.
|
|
84
|
+
@Model({ name: "OptionalArrayLike" })
|
|
85
|
+
class OptionalArrayLike extends Ad4mModel {
|
|
86
|
+
@Property({ through: "x://name" })
|
|
87
|
+
name: string = "";
|
|
88
|
+
|
|
89
|
+
// Optional typed-array relation
|
|
90
|
+
@HasMany(() => Comment, { through: "x://comments" })
|
|
91
|
+
comments?: Comment[];
|
|
92
|
+
|
|
93
|
+
// Optional string[] relation (the `@HasMany` + `string[]` pattern)
|
|
94
|
+
@HasMany({ through: "x://members" })
|
|
95
|
+
members?: string[];
|
|
96
|
+
|
|
97
|
+
// Optional scalar array — also `string[] | undefined`, should appear as a
|
|
98
|
+
// relation too (matches the runtime semantics: any array field can be a
|
|
99
|
+
// link collection unless we have stronger schema info).
|
|
100
|
+
tags?: string[];
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
// Type-level helpers
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
|
|
107
|
+
type Equals<X, Y> =
|
|
108
|
+
(<T>() => T extends X ? 1 : 2) extends
|
|
109
|
+
(<T>() => T extends Y ? 1 : 2) ? true : false;
|
|
110
|
+
|
|
111
|
+
function expectExact<T1, T2>(_: Equals<T1, T2> extends true ? true : never): void {}
|
|
112
|
+
function expectAssignable<T>(_: T): void {}
|
|
113
|
+
|
|
114
|
+
// ---------------------------------------------------------------------------
|
|
115
|
+
// PropertyKeysOf / RelationKeysOf
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
type PostProps = PropertyKeysOf<Post>;
|
|
119
|
+
type PostRels = RelationKeysOf<Post>;
|
|
120
|
+
|
|
121
|
+
expectExact<PostProps, "title" | "body" | "isPinned" | "views">(true);
|
|
122
|
+
expectExact<PostRels, "comments" | "authorRef">(true);
|
|
123
|
+
|
|
124
|
+
expectExact<RelatedModel<Post, "comments">, Comment>(true);
|
|
125
|
+
expectExact<RelatedModel<Post, "authorRef">, Comment>(true);
|
|
126
|
+
|
|
127
|
+
// AgentProfileLike — inheritance + optional HasOne via `?: T`
|
|
128
|
+
type AgentRels = RelationKeysOf<AgentProfileLike>;
|
|
129
|
+
type AgentProps = PropertyKeysOf<AgentProfileLike>;
|
|
130
|
+
|
|
131
|
+
// `location?: LocationBlockLike` (i.e. `LocationBlockLike | undefined`) must
|
|
132
|
+
// be recognised as a relation. `signals: string[]` inherited from WeNodeLike
|
|
133
|
+
// also counts (the `@HasMany` + `string[]` pattern).
|
|
134
|
+
expectAssignable<AgentRels>("location");
|
|
135
|
+
expectAssignable<AgentRels>("signals");
|
|
136
|
+
expectAssignable<AgentProps>("handle");
|
|
137
|
+
expectAssignable<AgentProps>("avatar");
|
|
138
|
+
|
|
139
|
+
expectAssignable<TypedIncludeMap<AgentProfileLike>>({ location: true });
|
|
140
|
+
expectAssignable<TypedIncludeMap<AgentProfileLike>>({ signals: true });
|
|
141
|
+
|
|
142
|
+
// Optional-array regression: `comments?: Comment[]`, `members?: string[]`,
|
|
143
|
+
// `tags?: string[]` should all be recognised as relations. Previously
|
|
144
|
+
// rejected because `T[K] = T[] | undefined` doesn't extend `T[]`.
|
|
145
|
+
type OptArrRels = RelationKeysOf<OptionalArrayLike>;
|
|
146
|
+
expectAssignable<OptArrRels>("comments");
|
|
147
|
+
expectAssignable<OptArrRels>("members");
|
|
148
|
+
expectAssignable<OptArrRels>("tags");
|
|
149
|
+
|
|
150
|
+
expectAssignable<TypedIncludeMap<OptionalArrayLike>>({ comments: true });
|
|
151
|
+
expectAssignable<TypedIncludeMap<OptionalArrayLike>>({ members: true });
|
|
152
|
+
expectAssignable<TypedIncludeMap<OptionalArrayLike>>({
|
|
153
|
+
$commentCount: { from: "comments", count: true },
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
// RelatedModel must also peel the optional wrapper before inferring U
|
|
157
|
+
expectExact<RelatedModel<OptionalArrayLike, "comments">, Comment>(true);
|
|
158
|
+
|
|
159
|
+
// ---------------------------------------------------------------------------
|
|
160
|
+
// TypedWhere
|
|
161
|
+
// ---------------------------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
// Valid where shapes
|
|
164
|
+
expectAssignable<TypedWhere<Post>>({ title: "hello" });
|
|
165
|
+
expectAssignable<TypedWhere<Post>>({ title: { contains: "x" } });
|
|
166
|
+
expectAssignable<TypedWhere<Post>>({ views: { gt: 5, lte: 100 } });
|
|
167
|
+
expectAssignable<TypedWhere<Post>>({ isPinned: true });
|
|
168
|
+
expectAssignable<TypedWhere<Post>>({ id: "literal:foo" });
|
|
169
|
+
expectAssignable<TypedWhere<Post>>({ author: "did:key:alice" });
|
|
170
|
+
|
|
171
|
+
// Misspelled property — must error
|
|
172
|
+
// @ts-expect-error
|
|
173
|
+
expectAssignable<TypedWhere<Post>>({ titel: "hello" });
|
|
174
|
+
|
|
175
|
+
// Wrong value type — must error
|
|
176
|
+
// @ts-expect-error
|
|
177
|
+
expectAssignable<TypedWhere<Post>>({ isPinned: "yes" });
|
|
178
|
+
|
|
179
|
+
// Numeric op on string field — must error
|
|
180
|
+
// @ts-expect-error
|
|
181
|
+
expectAssignable<TypedWhere<Post>>({ title: { gt: 5 } });
|
|
182
|
+
|
|
183
|
+
// String op on numeric field — must error
|
|
184
|
+
// @ts-expect-error
|
|
185
|
+
expectAssignable<TypedWhere<Post>>({ views: { contains: "x" } });
|
|
186
|
+
|
|
187
|
+
// ---------------------------------------------------------------------------
|
|
188
|
+
// TypedOrder
|
|
189
|
+
// ---------------------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
expectAssignable<TypedOrder<Post>>({ title: "ASC" });
|
|
192
|
+
expectAssignable<TypedOrder<Post>>({ views: "DESC", timestamp: "ASC" });
|
|
193
|
+
|
|
194
|
+
// @ts-expect-error — unknown field
|
|
195
|
+
expectAssignable<TypedOrder<Post>>({ titel: "ASC" });
|
|
196
|
+
|
|
197
|
+
// @ts-expect-error — invalid direction
|
|
198
|
+
expectAssignable<TypedOrder<Post>>({ title: "ASCENDING" });
|
|
199
|
+
|
|
200
|
+
// ---------------------------------------------------------------------------
|
|
201
|
+
// TypedIncludeMap — eager-load + nested
|
|
202
|
+
// ---------------------------------------------------------------------------
|
|
203
|
+
|
|
204
|
+
expectAssignable<TypedIncludeMap<Post>>({ comments: true });
|
|
205
|
+
expectAssignable<TypedIncludeMap<Post>>({ authorRef: true });
|
|
206
|
+
expectAssignable<TypedIncludeMap<Post>>({
|
|
207
|
+
comments: { where: { text: "x" }, order: { likes: "DESC" }, limit: 5 },
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
// Misspelled relation — must error
|
|
211
|
+
// @ts-expect-error
|
|
212
|
+
expectAssignable<TypedIncludeMap<Post>>({ commments: true });
|
|
213
|
+
|
|
214
|
+
// Nested where typo — must error
|
|
215
|
+
// @ts-expect-error
|
|
216
|
+
expectAssignable<TypedIncludeMap<Post>>({ comments: { where: { txet: "x" } } });
|
|
217
|
+
|
|
218
|
+
// Nested numeric op on string — must error
|
|
219
|
+
// @ts-expect-error
|
|
220
|
+
expectAssignable<TypedIncludeMap<Post>>({ comments: { where: { text: { gt: 5 } } } });
|
|
221
|
+
|
|
222
|
+
// ---------------------------------------------------------------------------
|
|
223
|
+
// TypedIncludeProjection ($-prefixed keys)
|
|
224
|
+
// ---------------------------------------------------------------------------
|
|
225
|
+
|
|
226
|
+
// Valid: count true projection
|
|
227
|
+
expectAssignable<TypedIncludeMap<Post>>({
|
|
228
|
+
$commentCount: { from: "comments", count: true },
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
// Valid: filtered projection with limit
|
|
232
|
+
expectAssignable<TypedIncludeMap<Post>>({
|
|
233
|
+
$firstComment: { from: "comments", where: { text: "hi" }, limit: 1 },
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
// `from` must reference a real relation
|
|
237
|
+
{
|
|
238
|
+
const _bad1: TypedIncludeMap<Post> = {
|
|
239
|
+
$bogus: {
|
|
240
|
+
// @ts-expect-error — "notARelation" is not in RelationKeysOf<Post>
|
|
241
|
+
from: "notARelation",
|
|
242
|
+
count: true,
|
|
243
|
+
},
|
|
244
|
+
};
|
|
245
|
+
void _bad1;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Projection's nested where uses the *target's* property keys
|
|
249
|
+
expectAssignable<TypedIncludeMap<Post>>({
|
|
250
|
+
$popular: { from: "comments", where: { likes: { gt: 100 } }, limit: 10 },
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
// Wrong nested where key on the target
|
|
254
|
+
{
|
|
255
|
+
const _bad2: TypedIncludeMap<Post> = {
|
|
256
|
+
$bad: {
|
|
257
|
+
from: "comments",
|
|
258
|
+
// @ts-expect-error — "titel" is not a property of Comment
|
|
259
|
+
where: { titel: "x" },
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
void _bad2;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// ---------------------------------------------------------------------------
|
|
266
|
+
// IncludeExtras — propagating $-keys into the row type
|
|
267
|
+
// ---------------------------------------------------------------------------
|
|
268
|
+
|
|
269
|
+
type CountProjection = { $commentCount: { from: "comments"; count: true } };
|
|
270
|
+
type Limit1Projection = { $firstComment: { from: "comments"; limit: 1 } };
|
|
271
|
+
type ListProjection = { $allComments: { from: "comments" } };
|
|
272
|
+
|
|
273
|
+
expectExact<IncludeExtras<Post, CountProjection>["$commentCount"], number>(true);
|
|
274
|
+
expectExact<IncludeExtras<Post, Limit1Projection>["$firstComment"], Comment | null>(true);
|
|
275
|
+
expectExact<IncludeExtras<Post, ListProjection>["$allComments"], Comment[]>(true);
|
|
276
|
+
|
|
277
|
+
// ---------------------------------------------------------------------------
|
|
278
|
+
// TypedQuery — full shape
|
|
279
|
+
// ---------------------------------------------------------------------------
|
|
280
|
+
|
|
281
|
+
expectAssignable<TypedQuery<Post>>({
|
|
282
|
+
where: { isPinned: true, views: { gt: 10 } },
|
|
283
|
+
order: { views: "DESC" },
|
|
284
|
+
include: { comments: { limit: 5 }, $commentCount: { from: "comments", count: true } },
|
|
285
|
+
includeAll: false,
|
|
286
|
+
deepQuery: true,
|
|
287
|
+
limit: 20,
|
|
288
|
+
offset: 0,
|
|
289
|
+
count: true,
|
|
290
|
+
properties: ["title", "body"],
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
// @ts-expect-error — properties[] only accepts declared property names
|
|
294
|
+
expectAssignable<TypedQuery<Post>>({ properties: ["title", "nonsense"] });
|
|
295
|
+
|
|
296
|
+
// ---------------------------------------------------------------------------
|
|
297
|
+
// fromSHACL escape hatch — TypedQuery<Ad4mModel> collapses to loose Query
|
|
298
|
+
// ---------------------------------------------------------------------------
|
|
299
|
+
|
|
300
|
+
// When T has no declared fields (i.e. Ad4mModel itself), TypedQuery<T> ≡ Query.
|
|
301
|
+
expectExact<TypedQuery<Ad4mModel>, Query>(true);
|
|
302
|
+
expectAssignable<TypedQuery<Ad4mModel>>({ where: { anyKey: "value" } });
|
|
303
|
+
|
|
304
|
+
// ---------------------------------------------------------------------------
|
|
305
|
+
// End-to-end inference through findAll / findOne — verifies that the literal
|
|
306
|
+
// `count: true` propagates through `Q extends TypedQuery<T>` into the return
|
|
307
|
+
// type so callers don't need `(row as any).$xxx` casts.
|
|
308
|
+
// ---------------------------------------------------------------------------
|
|
309
|
+
|
|
310
|
+
import type { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
|
|
311
|
+
declare const persp: PerspectiveProxy;
|
|
312
|
+
|
|
313
|
+
// Skip async actually-running them — these calls are unreachable at runtime
|
|
314
|
+
// (no perspective). The point is that they compile with correct return types.
|
|
315
|
+
function _typeFlowChecks() {
|
|
316
|
+
return async () => {
|
|
317
|
+
// No include — plain Post[]
|
|
318
|
+
const a = await Post.findAll(persp);
|
|
319
|
+
expectAssignable<Post[]>(a);
|
|
320
|
+
|
|
321
|
+
// Include eager-loaded relation — still Post[]
|
|
322
|
+
const b = await Post.findAll(persp, { include: { comments: true } });
|
|
323
|
+
expectAssignable<Post[]>(b);
|
|
324
|
+
|
|
325
|
+
// Projection: count → number on result rows
|
|
326
|
+
const c = await Post.findAll(persp, {
|
|
327
|
+
include: { $commentCount: { from: "comments", count: true } },
|
|
328
|
+
});
|
|
329
|
+
expectAssignable<number>(c[0].$commentCount);
|
|
330
|
+
|
|
331
|
+
// Projection: limit 1 → scalar | null on result rows
|
|
332
|
+
const d = await Post.findAll(persp, {
|
|
333
|
+
include: { $top: { from: "comments", limit: 1 } },
|
|
334
|
+
});
|
|
335
|
+
expectAssignable<Comment | null>(d[0].$top);
|
|
336
|
+
|
|
337
|
+
// Projection: no limit → array on result rows
|
|
338
|
+
const e = await Post.findAll(persp, {
|
|
339
|
+
include: { $all: { from: "comments" } },
|
|
340
|
+
});
|
|
341
|
+
expectAssignable<Comment[]>(e[0].$all);
|
|
342
|
+
|
|
343
|
+
// findOne — same propagation, nullable wrapper
|
|
344
|
+
const f = await Post.findOne(persp, {
|
|
345
|
+
include: { $commentCount: { from: "comments", count: true } },
|
|
346
|
+
});
|
|
347
|
+
if (f) expectAssignable<number>(f.$commentCount);
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// ---------------------------------------------------------------------------
|
|
352
|
+
// Runtime placeholder — Jest requires at least one test in the file
|
|
353
|
+
// ---------------------------------------------------------------------------
|
|
354
|
+
|
|
355
|
+
describe("typed-query types (compile-time)", () => {
|
|
356
|
+
it("compiles", () => {
|
|
357
|
+
// All assertions above are at type level; this test passes if tsc passed.
|
|
358
|
+
expect(true).toBe(true);
|
|
359
|
+
});
|
|
360
|
+
});
|
package/src/model/types.ts
CHANGED
|
@@ -90,11 +90,12 @@ export interface IncludeProjection {
|
|
|
90
90
|
/** When true, attaches an integer count instead of a list. */
|
|
91
91
|
count?: true;
|
|
92
92
|
/**
|
|
93
|
-
*
|
|
94
|
-
*
|
|
93
|
+
* Bare class name of the projection target. Set automatically by
|
|
94
|
+
* `prepareModelQueryParams`; the executor resolves the target's shape
|
|
95
|
+
* through its in-memory cache when applying projection where filters.
|
|
95
96
|
* @internal
|
|
96
97
|
*/
|
|
97
|
-
|
|
98
|
+
targetClassName?: string;
|
|
98
99
|
/** Post-hydration where clause applied to the target instances. */
|
|
99
100
|
where?: Where;
|
|
100
101
|
/** Limit results (when 1, the attached value is unwrapped to a scalar). */
|
|
@@ -149,6 +150,196 @@ export type Query = {
|
|
|
149
150
|
*/
|
|
150
151
|
export type RelationSubQuery = Omit<Query, 'parent' | 'count'>;
|
|
151
152
|
|
|
153
|
+
// ---------------------------------------------------------------------------
|
|
154
|
+
// Typed Query DSL — Phase 1 of PLAN_6_TYPED_QUERIES.md
|
|
155
|
+
//
|
|
156
|
+
// These types layer compile-time field-name and value-type checking on top of
|
|
157
|
+
// the loose Query/Where/Order/IncludeMap. They infer everything from the
|
|
158
|
+
// model class's declared TS fields — no codegen, no runtime changes.
|
|
159
|
+
//
|
|
160
|
+
// Dynamic models (e.g. produced by `Ad4mModel.fromSHACL()`) carry no
|
|
161
|
+
// field-level type information; for those `TypedQuery<Ad4mModel>` collapses
|
|
162
|
+
// to the loose `Query` shape, which is the correct escape hatch.
|
|
163
|
+
// ---------------------------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
/** Keys of T that are user-declared (not methods, not inherited from Ad4mModel). */
|
|
166
|
+
export type ModelDataKeys<T extends Ad4mModel> = {
|
|
167
|
+
[K in keyof T]: K extends keyof Ad4mModel ? never
|
|
168
|
+
: T[K] extends (...args: any[]) => any ? never
|
|
169
|
+
: K
|
|
170
|
+
}[keyof T];
|
|
171
|
+
|
|
172
|
+
/** Keys of T that can appear in a `where` clause — scalars and scalar arrays.
|
|
173
|
+
* Excludes typed Ad4mModel references (single or array); `string[]`/`number[]`
|
|
174
|
+
* remain included because they're often filterable even when also used as
|
|
175
|
+
* link targets.
|
|
176
|
+
*
|
|
177
|
+
* Iterates over `keyof T` directly (not `ModelDataKeys<T>`) to preserve the
|
|
178
|
+
* key constraint — mapped types over computed type aliases sometimes widen
|
|
179
|
+
* to `string | undefined` in the key position, which then breaks indexing. */
|
|
180
|
+
export type PropertyKeysOf<T extends Ad4mModel> = {
|
|
181
|
+
[K in keyof T]: K extends ModelDataKeys<T>
|
|
182
|
+
? NonNullable<T[K]> extends Ad4mModel ? never
|
|
183
|
+
: NonNullable<T[K]> extends Ad4mModel[] ? never
|
|
184
|
+
: K
|
|
185
|
+
: never
|
|
186
|
+
}[keyof T];
|
|
187
|
+
|
|
188
|
+
/** Keys of T that can appear in `include` — typed Ad4mModel references AND
|
|
189
|
+
* `string[]` link-target arrays (the `@HasMany` + `string[]` pattern that
|
|
190
|
+
* AD4M uses for relations without a target class thunk). Handles both
|
|
191
|
+
* `?: Foo` (optional → `Foo | undefined`) and `Foo | null` field shapes, and
|
|
192
|
+
* optional/nullable array variants (`?: Foo[]`, `Foo[] | null`). */
|
|
193
|
+
export type RelationKeysOf<T extends Ad4mModel> = {
|
|
194
|
+
[K in keyof T]: K extends ModelDataKeys<T>
|
|
195
|
+
? NonNullable<T[K]> extends Ad4mModel ? K
|
|
196
|
+
: NonNullable<T[K]> extends Ad4mModel[] ? K
|
|
197
|
+
: NonNullable<T[K]> extends string[] ? K
|
|
198
|
+
: never
|
|
199
|
+
: never
|
|
200
|
+
}[keyof T];
|
|
201
|
+
|
|
202
|
+
/** The model type referenced by a relation field K on T.
|
|
203
|
+
* Falls back to `Ad4mModel` (loose) for the `string[]` relation pattern,
|
|
204
|
+
* since no target class is available at the type level. */
|
|
205
|
+
export type RelatedModel<T extends Ad4mModel, K extends RelationKeysOf<T>> =
|
|
206
|
+
NonNullable<T[K]> extends (infer U)[] ? (U extends Ad4mModel ? U : Ad4mModel)
|
|
207
|
+
: NonNullable<T[K]> extends Ad4mModel ? NonNullable<T[K]>
|
|
208
|
+
: Ad4mModel;
|
|
209
|
+
|
|
210
|
+
/** True when T has no statically-declared data fields (e.g. fromSHACL classes). */
|
|
211
|
+
type HasNoTypedFields<T extends Ad4mModel> =
|
|
212
|
+
[PropertyKeysOf<T> | RelationKeysOf<T>] extends [never] ? true : false;
|
|
213
|
+
|
|
214
|
+
// ---- Typed where conditions --------------------------------------------------
|
|
215
|
+
|
|
216
|
+
export type StringWhereOps = {
|
|
217
|
+
not?: string | string[];
|
|
218
|
+
contains?: string;
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
export type NumericWhereOps = {
|
|
222
|
+
not?: number | number[];
|
|
223
|
+
lt?: number;
|
|
224
|
+
lte?: number;
|
|
225
|
+
gt?: number;
|
|
226
|
+
gte?: number;
|
|
227
|
+
between?: [number, number];
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
export type TypedWhereCondition<V> =
|
|
231
|
+
V extends string ? string | string[] | StringWhereOps
|
|
232
|
+
: V extends number ? number | number[] | NumericWhereOps
|
|
233
|
+
: V extends boolean ? boolean
|
|
234
|
+
: V extends Array<infer U>
|
|
235
|
+
? U extends string ? string | string[] | StringWhereOps
|
|
236
|
+
: U extends number ? number | number[] | NumericWhereOps
|
|
237
|
+
: WhereCondition
|
|
238
|
+
: WhereCondition;
|
|
239
|
+
|
|
240
|
+
/** Strict Where: keys constrained to T's properties, plus the well-known
|
|
241
|
+
* link-metadata fields (`id`/`author`/`timestamp`). */
|
|
242
|
+
type StrictTypedWhere<T extends Ad4mModel> =
|
|
243
|
+
& { [K in PropertyKeysOf<T>]?: TypedWhereCondition<T[K]> }
|
|
244
|
+
& {
|
|
245
|
+
base?: string | string[];
|
|
246
|
+
id?: string | string[];
|
|
247
|
+
author?: WhereCondition;
|
|
248
|
+
timestamp?: WhereCondition;
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
/** Public typed `where` for a model class. Falls back to the loose `Where`
|
|
252
|
+
* shape when T has no declared fields (e.g. fromSHACL-derived classes). */
|
|
253
|
+
export type TypedWhere<T extends Ad4mModel> =
|
|
254
|
+
HasNoTypedFields<T> extends true ? Where : StrictTypedWhere<T>;
|
|
255
|
+
|
|
256
|
+
// ---- Typed order -------------------------------------------------------------
|
|
257
|
+
|
|
258
|
+
type StrictTypedOrder<T extends Ad4mModel> = {
|
|
259
|
+
[K in PropertyKeysOf<T> | 'timestamp' | 'author' | 'createdAt' | 'updatedAt']?: 'ASC' | 'DESC';
|
|
260
|
+
};
|
|
261
|
+
|
|
262
|
+
export type TypedOrder<T extends Ad4mModel> =
|
|
263
|
+
HasNoTypedFields<T> extends true ? Order : StrictTypedOrder<T>;
|
|
264
|
+
|
|
265
|
+
// ---- Typed include + projection ---------------------------------------------
|
|
266
|
+
|
|
267
|
+
/** Sub-query for an eager-loaded relation — inherits the target model's constraints. */
|
|
268
|
+
export type TypedRelationSubQuery<U extends Ad4mModel> = {
|
|
269
|
+
where?: TypedWhere<U>;
|
|
270
|
+
order?: TypedOrder<U>;
|
|
271
|
+
include?: TypedIncludeMap<U>;
|
|
272
|
+
limit?: number;
|
|
273
|
+
offset?: number;
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
/** Projection — `from` must be a real relation on T; `where`/`order` constrained to that target.
|
|
277
|
+
* Modelled as a discriminated union so the literal `count: true` and `limit: 1`
|
|
278
|
+
* variants narrow inference into `IncludeExtras` (count → number, limit-1 → scalar). */
|
|
279
|
+
export type TypedIncludeProjection<T extends Ad4mModel> = {
|
|
280
|
+
[K in RelationKeysOf<T>]:
|
|
281
|
+
| { from: K; count: true }
|
|
282
|
+
| { from: K; limit: 1; where?: TypedWhere<RelatedModel<T, K>>; order?: TypedOrder<RelatedModel<T, K>> }
|
|
283
|
+
| { from: K; limit?: number; where?: TypedWhere<RelatedModel<T, K>>; order?: TypedOrder<RelatedModel<T, K>> };
|
|
284
|
+
}[RelationKeysOf<T>];
|
|
285
|
+
|
|
286
|
+
type StrictTypedIncludeMap<T extends Ad4mModel> =
|
|
287
|
+
& { [K in RelationKeysOf<T>]?: boolean | TypedRelationSubQuery<RelatedModel<T, K>> }
|
|
288
|
+
& { [K in `$${string}`]?: TypedIncludeProjection<T> };
|
|
289
|
+
|
|
290
|
+
export type TypedIncludeMap<T extends Ad4mModel> =
|
|
291
|
+
HasNoTypedFields<T> extends true ? IncludeMap : StrictTypedIncludeMap<T>;
|
|
292
|
+
|
|
293
|
+
// ---- Result-side: project $-keys into the returned row type ------------------
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Given a model T and an `include` literal I, compute the extra fields
|
|
297
|
+
* contributed by `$`-prefixed projection keys.
|
|
298
|
+
*
|
|
299
|
+
* - `{ count: true }` → `number`
|
|
300
|
+
* - `{ from: R, limit: 1 }` → `RelatedModel<T,R> | null`
|
|
301
|
+
* - `{ from: R }` (no limit/1) → `RelatedModel<T,R>[]`
|
|
302
|
+
*
|
|
303
|
+
* Returns `unknown` (intersection-neutral) when `I` has no `$`-keys, so that
|
|
304
|
+
* `T & IncludeExtras<T, I>` collapses back to `T` and downstream type
|
|
305
|
+
* predicates (`(x): x is T => ...`) keep working unchanged.
|
|
306
|
+
*/
|
|
307
|
+
export type IncludeExtras<T extends Ad4mModel, I> =
|
|
308
|
+
I extends Record<string, any>
|
|
309
|
+
? Extract<keyof I, `$${string}`> extends never
|
|
310
|
+
? unknown
|
|
311
|
+
: {
|
|
312
|
+
[K in Extract<keyof I, `$${string}`>]:
|
|
313
|
+
I[K] extends { count: true } ? number
|
|
314
|
+
: I[K] extends { from: infer R; limit: 1 }
|
|
315
|
+
? (R extends RelationKeysOf<T> ? RelatedModel<T, R> | null : never)
|
|
316
|
+
: I[K] extends { from: infer R }
|
|
317
|
+
? (R extends RelationKeysOf<T> ? RelatedModel<T, R>[] : never)
|
|
318
|
+
: unknown;
|
|
319
|
+
}
|
|
320
|
+
: unknown;
|
|
321
|
+
|
|
322
|
+
// ---- Typed Query -------------------------------------------------------------
|
|
323
|
+
|
|
324
|
+
type StrictTypedQuery<T extends Ad4mModel> = {
|
|
325
|
+
parent?: ParentScope;
|
|
326
|
+
properties?: PropertyKeysOf<T>[];
|
|
327
|
+
include?: TypedIncludeMap<T>;
|
|
328
|
+
includeAll?: boolean;
|
|
329
|
+
where?: TypedWhere<T>;
|
|
330
|
+
order?: TypedOrder<T>;
|
|
331
|
+
offset?: number;
|
|
332
|
+
limit?: number;
|
|
333
|
+
count?: boolean;
|
|
334
|
+
deepQuery?: boolean;
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
export type TypedQuery<T extends Ad4mModel> =
|
|
338
|
+
HasNoTypedFields<T> extends true ? Query : StrictTypedQuery<T>;
|
|
339
|
+
|
|
340
|
+
/** Helper that extracts the `include` literal from a TypedQuery for use with IncludeExtras. */
|
|
341
|
+
export type IncludeOf<Q> = Q extends { include?: infer I } ? I : undefined;
|
|
342
|
+
|
|
152
343
|
/**
|
|
153
344
|
* Options accepted by the instance `get()` method.
|
|
154
345
|
*
|
|
@@ -116,9 +116,9 @@ export class PerspectiveClient {
|
|
|
116
116
|
return JSON.parse(result)
|
|
117
117
|
}
|
|
118
118
|
|
|
119
|
-
async querySparql(uuid: string, query: string): Promise<
|
|
119
|
+
async querySparql<T = any>(uuid: string, query: string): Promise<T> {
|
|
120
120
|
const result = await this.#apiClient.call<string>('perspective.querySparql', { uuid, engine: 'sparql', query })
|
|
121
|
-
return JSON.parse(result)
|
|
121
|
+
return JSON.parse(result) as T
|
|
122
122
|
}
|
|
123
123
|
|
|
124
124
|
async subscribeQuery(uuid: string, query: string): Promise<{ subscriptionId: string, result: AllInstancesResult }> {
|
|
@@ -176,9 +176,9 @@ export class PerspectiveClient {
|
|
|
176
176
|
)
|
|
177
177
|
}
|
|
178
178
|
|
|
179
|
-
async modelQuery(uuid: string, className: string, queryJson: string
|
|
179
|
+
async modelQuery(uuid: string, className: string, queryJson: string): Promise<any> {
|
|
180
180
|
const resultJson = await this.#apiClient.call<string>(
|
|
181
|
-
'perspective.modelQuery', { uuid, class_name: className, query_json: queryJson
|
|
181
|
+
'perspective.modelQuery', { uuid, class_name: className, query_json: queryJson }
|
|
182
182
|
)
|
|
183
183
|
return JSON.parse(resultJson)
|
|
184
184
|
}
|
|
@@ -187,7 +187,6 @@ export class PerspectiveClient {
|
|
|
187
187
|
uuid: string,
|
|
188
188
|
className: string,
|
|
189
189
|
instanceIds: string[],
|
|
190
|
-
shapeJson: string,
|
|
191
190
|
propertyNames?: string[],
|
|
192
191
|
): Promise<Record<string, Record<string, any>>> {
|
|
193
192
|
const resultJson = await this.#apiClient.call<string>(
|
|
@@ -195,16 +194,15 @@ export class PerspectiveClient {
|
|
|
195
194
|
uuid,
|
|
196
195
|
class_name: className,
|
|
197
196
|
instance_ids: instanceIds,
|
|
198
|
-
shape_json: shapeJson,
|
|
199
197
|
...(propertyNames && { property_names: propertyNames }),
|
|
200
198
|
}
|
|
201
199
|
)
|
|
202
200
|
return JSON.parse(resultJson)
|
|
203
201
|
}
|
|
204
202
|
|
|
205
|
-
async modelSubscribe(uuid: string, className: string, queryJson: string
|
|
203
|
+
async modelSubscribe(uuid: string, className: string, queryJson: string): Promise<{ subscriptionId: string, result: any }> {
|
|
206
204
|
const response = await this.#apiClient.call<{ subscription_id: string, result: string }>(
|
|
207
|
-
'perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson
|
|
205
|
+
'perspective.modelSubscribe', { uuid, class_name: className, query_json: queryJson }
|
|
208
206
|
)
|
|
209
207
|
return {
|
|
210
208
|
subscriptionId: response.subscription_id,
|