foldkit-entity 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +177 -6
- package/dist/index.d.mts +253 -21
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +281 -6
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -8,8 +8,8 @@ packages interpret that declaration; this one only describes.
|
|
|
8
8
|
> [registers Entities and reads Selections as they are](../remote/README.md#entities-declared-with-foldkit-entity).
|
|
9
9
|
> `foldkit-remote-drizzle` binds a related set to tables with
|
|
10
10
|
> [`bind`](../remote-drizzle/README.md#binding-a-foldkit-entity-domain), and
|
|
11
|
-
> [`foldkit-form`](../form/README.md) builds a form from `Entity.input
|
|
12
|
-
>
|
|
11
|
+
> [`foldkit-form`](../form/README.md) builds a form from `Entity.input`, and
|
|
12
|
+
> [`foldkit-crud`](../crud/README.md) joins one to a Remote operation.
|
|
13
13
|
|
|
14
14
|
For the whole path in one runnable trace, domain to client to SQL, see
|
|
15
15
|
[`examples/entity`](../../examples/entity).
|
|
@@ -110,6 +110,43 @@ each entity declared its own relations, `Post` would be typed in terms of
|
|
|
110
110
|
constants that way. Declaring the relations over entities that already exist
|
|
111
111
|
avoids the cycle, and lets `relate` check every target up front.
|
|
112
112
|
|
|
113
|
+
## Ids of their own
|
|
114
|
+
|
|
115
|
+
An Entity is identified by its `id` field, and the id keeps the type you give
|
|
116
|
+
it. Brand it, and a ref to an Author can no longer stand in for a Post's:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
const AuthorId = Schema.String.pipe(Schema.brand('AuthorId'))
|
|
120
|
+
const PostId = Schema.String.pipe(Schema.brand('PostId'))
|
|
121
|
+
|
|
122
|
+
const Writer = Entity.define('Author', Schema.Struct({ id: AuthorId, name: Schema.String }))
|
|
123
|
+
const Article = Entity.define('Post', Schema.Struct({ id: PostId, title: Schema.String }))
|
|
124
|
+
const Press = Entity.relate({ Writer, Article }, { Article: { author: Relation.one(Writer) } })
|
|
125
|
+
|
|
126
|
+
type WriterId = IdOf<typeof Press.Writer> // AuthorId
|
|
127
|
+
|
|
128
|
+
const ByLine = Entity.select(Press.Article, { author: true })
|
|
129
|
+
// { author: EntityRef<'Author', AuthorId> }
|
|
130
|
+
|
|
131
|
+
Entity.input(Press.Article, Schema.Struct({ authorId: AuthorId }), {
|
|
132
|
+
authorId: Relation.input(Press.Article.relations.author), // a PostId, or any text, is a type error
|
|
133
|
+
})
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
- `IdOf<E>` is the type of the `id` field; `EntityRef<Name, Id>` carries it, and
|
|
137
|
+
`Relation.input` takes it (`Id | null` for an optional `one`, a list for a
|
|
138
|
+
`many`).
|
|
139
|
+
- A ref's schema is the id's own, so a pattern or a check on the id holds for
|
|
140
|
+
every ref to it.
|
|
141
|
+
- **An id is text.** A ref travels and is stored as text, so an Entity whose `id`
|
|
142
|
+
is a number (or has no `id` field) has refs with a plain `string` id: the
|
|
143
|
+
number as text.
|
|
144
|
+
- A Selection carries its Entity's id type, so `foldkit-remote`'s
|
|
145
|
+
`Data.get(PostPage, id)` takes a `PostId` and refuses an `AuthorId`, or plain
|
|
146
|
+
text.
|
|
147
|
+
- Nothing here is new API to opt into. An Entity with `id: Schema.String` types
|
|
148
|
+
exactly as before.
|
|
149
|
+
|
|
113
150
|
## Selecting a view
|
|
114
151
|
|
|
115
152
|
A Selection names the members a consumer wants and carries the schema of the
|
|
@@ -142,7 +179,7 @@ PostRow.schema.Type
|
|
|
142
179
|
| Field, Derived | `true` | the member's own schema, checks included |
|
|
143
180
|
| Relation | `true` | an `EntityRef`: `{ entity, id }` |
|
|
144
181
|
| Relation | a Selection of its target | that Selection's value |
|
|
145
|
-
| `many` Relation | `Entity.page(selection, window)` | a
|
|
182
|
+
| `many` Relation | `Entity.page(selection, window)` | a page of that Selection's values: `{ items, hasNext, hasPrevious }` |
|
|
146
183
|
|
|
147
184
|
A `many` relation yields an array, and an optional `one` is nullable. A
|
|
148
185
|
Selection is an ordinary value, so `AuthorOption` above is declared once and
|
|
@@ -206,6 +243,12 @@ CreatePost.members.notify // Entity.unmapped: about the operation, not the Post
|
|
|
206
243
|
- Every other key needs an entry: a Field under another name, a relation's ids
|
|
207
244
|
with `Relation.input(relation)`, or `Entity.unmapped`. Nothing is inferred
|
|
208
245
|
from a name like `authorId`.
|
|
246
|
+
- An entry may name the member by its key: `{ headline: 'title', authorId: 'author' }`
|
|
247
|
+
is the `title` Field and `Relation.input` of `author`. It is the same reading,
|
|
248
|
+
checked the same way; a name that is no field or relation is a type error.
|
|
249
|
+
- `Entity.fields(Post, 'id', 'title')` is those fields' schemas, to spread into
|
|
250
|
+
the input's struct, so the input keeps the field's rules without repeating
|
|
251
|
+
`Post.fields.title.schema` per key.
|
|
209
252
|
- `Relation.input` expects one id for a `one`, `id | null` for an optional
|
|
210
253
|
`one`, and an array of ids for a `many`.
|
|
211
254
|
- A derived member cannot be written, and a member of another Entity cannot be
|
|
@@ -280,6 +323,121 @@ Entity.same(CmsPost, Blog.Post) // true: the metadata changed, the entity did no
|
|
|
280
323
|
|
|
281
324
|
Annotating again combines with what is there, using the key's own `merge`.
|
|
282
325
|
|
|
326
|
+
## Saying something about a row: `Expr`
|
|
327
|
+
|
|
328
|
+
An Entity says what a domain has. An `Expr` says something about one row of it,
|
|
329
|
+
as a value:
|
|
330
|
+
|
|
331
|
+
> **Why query semantics live in this package.** They describe and interpret
|
|
332
|
+
> nothing, which is the line this package already draws: an `Expr` says which
|
|
333
|
+
> rows and fetches none of them, and the interpreters that run one live
|
|
334
|
+
> elsewhere — `foldkit-remote-drizzle` compiles a body to SQL,
|
|
335
|
+
> `foldkit-remote-server` evaluates one over rows. Nothing that imports only
|
|
336
|
+
> `Entity` pays for them: they are ordinary consts in a `sideEffects: false`
|
|
337
|
+
> package, so a bundler drops them, and a package like `foldkit-form` imports
|
|
338
|
+
> only types from here in any case.
|
|
339
|
+
|
|
340
|
+
```ts
|
|
341
|
+
import { Expr, Order } from 'foldkit-entity'
|
|
342
|
+
|
|
343
|
+
const byTitle = Expr.eq(Blog.Post.fields.title, Expr.input('title', Schema.String))
|
|
344
|
+
const published = Expr.eq(Blog.Post.fields.published, true)
|
|
345
|
+
const newest = [Order.desc(Blog.Post.fields.title), Order.asc(Blog.Post.fields.id)]
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
Building one performs no work: it reads nothing, names no database, and runs no
|
|
349
|
+
query. An interpreter compiles it — `foldkit-remote-drizzle` to SQL, an
|
|
350
|
+
in-memory evaluator to a predicate over rows — which is what lets one query mean
|
|
351
|
+
the same thing in more than one place.
|
|
352
|
+
|
|
353
|
+
A comparison coerces what it is given, so the common forms read as they mean: a
|
|
354
|
+
field becomes a reference, a plain value becomes a literal, and an `Expr` is
|
|
355
|
+
already one. What it will not do is compare a field to the wrong kind of value —
|
|
356
|
+
`Expr.eq(Blog.Post.fields.title, 42)` is an error where it is written, rather
|
|
357
|
+
than a row that never matches.
|
|
358
|
+
|
|
359
|
+
**An input is a placeholder, not a value.** A query's body is built once, so
|
|
360
|
+
`Expr.input('title', …)` stands for whatever the query is given when it runs —
|
|
361
|
+
there is nothing there yet to branch on. An `InputExpr` is an object, so a
|
|
362
|
+
`condition ? a : b` over one is always truthy and decides itself once, forever.
|
|
363
|
+
A query that depends on what it was passed says so with a comparison over the
|
|
364
|
+
placeholder instead of a branch around it.
|
|
365
|
+
|
|
366
|
+
`dependenciesOf(...)` says which fields and inputs an expression reads and which
|
|
367
|
+
operations it uses, so a planner knows what it needs and an interpreter can
|
|
368
|
+
refuse a query it cannot run.
|
|
369
|
+
|
|
370
|
+
### Asking a question that depends on an input, without branching on it
|
|
371
|
+
|
|
372
|
+
Since an input is a placeholder, a query cannot choose between two shapes based
|
|
373
|
+
on what it was given. It does not need to: a question that looks like a branch
|
|
374
|
+
is usually a comparison waiting to be written.
|
|
375
|
+
|
|
376
|
+
```ts
|
|
377
|
+
// A list that shows archived entries or unarchived ones, as the reader asks:
|
|
378
|
+
Expr.eq(Expr.isNotNull(Entry.fields.archivedAt), input.archived)
|
|
379
|
+
|
|
380
|
+
// A search box that filters when something is typed and not when nothing is:
|
|
381
|
+
Expr.contains(Entry.fields.label, input.search)
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
The first is "is-archived equals what you asked for". The second relies on
|
|
385
|
+
everything containing the empty string. Both are one static body, and both ask
|
|
386
|
+
exactly what `archived ? … : …` and `search === '' ? … : …` asked.
|
|
387
|
+
|
|
388
|
+
`isNull` and `isNotNull` are the same node with the answer absence gives
|
|
389
|
+
flipped, so nothing has to negate a predicate to get the other.
|
|
390
|
+
|
|
391
|
+
**`contains` is case-insensitive**, which is what a search means — and which
|
|
392
|
+
has to be said, not left to the interpreter: SQLite's `like` ignores case and
|
|
393
|
+
Postgres's does not, so a body that left it open would mean two things. Folding
|
|
394
|
+
is ASCII-only, since that is what `lower` does in SQLite without ICU.
|
|
395
|
+
|
|
396
|
+
**Over a column that can be null it is not the same as no filter.** A null
|
|
397
|
+
contains nothing, not even the empty string, so its rows drop out. The column
|
|
398
|
+
the CMS searches is declared not-null, which is what makes an empty search
|
|
399
|
+
exactly everything there.
|
|
400
|
+
|
|
401
|
+
### Which rows: `Query`
|
|
402
|
+
|
|
403
|
+
A `Query` is an Entity to read, the predicates every row must hold, and the
|
|
404
|
+
order to read them in — composed with `pipe`, one immutable value per step:
|
|
405
|
+
|
|
406
|
+
```ts
|
|
407
|
+
const published = Query.where(Expr.eq(Blog.Post.fields.published, true))
|
|
408
|
+
const newest = Query.orderBy(Order.desc(Blog.Post.fields.title))
|
|
409
|
+
|
|
410
|
+
const recent = Query.from(Blog.Post).pipe(published, newest)
|
|
411
|
+
const oneOf = Query.from(Blog.Post).pipe(published, Query.where(byTitle))
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
`published` and `newest` are fragments: written once, piped into any query over
|
|
415
|
+
the same Entity. Composing performs no work — no table is named, no connection
|
|
416
|
+
opened, nothing read.
|
|
417
|
+
|
|
418
|
+
**Two `where`s conjoin and two `orderBy`s append.** Neither replaces what came
|
|
419
|
+
before, so piping a fragment can only ever narrow a query, never silently undo
|
|
420
|
+
part of it. An earlier ordering term stays the more significant one, which is
|
|
421
|
+
what makes a later `Query.orderBy(Order.asc(id))` a tie-breaker. Neither ever replaces what a fragment added.
|
|
422
|
+
|
|
423
|
+
The list of predicates **is** the conjunction — which is why no `Expr.and`
|
|
424
|
+
exists. A query wanting three conditions writes three `where`s. An `and`
|
|
425
|
+
operator is only needed for a conjunction nested inside something else, and no
|
|
426
|
+
query here has one yet.
|
|
427
|
+
|
|
428
|
+
A query reads one Entity, so a predicate or ordering term naming a different
|
|
429
|
+
one is refused where it is piped: an interpreter would otherwise be asked for a
|
|
430
|
+
column of a table it was never told to read. Entities are compared by identity,
|
|
431
|
+
so two declared with the same name are two Entities here as everywhere else.
|
|
432
|
+
|
|
433
|
+
A `Query` says which rows. It does not say which fields — that is a Selection —
|
|
434
|
+
and it does not say how many, whether absence is an error, or whether to watch
|
|
435
|
+
for changes: those belong to the consumer doing the reading, not to the
|
|
436
|
+
relation.
|
|
437
|
+
|
|
438
|
+
Only the operations a real query in this repository needs exist. The set grows
|
|
439
|
+
from queries, not from what a database could express.
|
|
440
|
+
|
|
283
441
|
## API
|
|
284
442
|
|
|
285
443
|
| Call | Meaning |
|
|
@@ -287,7 +445,8 @@ Annotating again combines with what is there, using the key's own `merge`.
|
|
|
287
445
|
| `Entity.define(name, struct)` | A new Entity with a Field per property. |
|
|
288
446
|
| `Entity.relate(entities, { Owner: { key: Relation.one(Target) } })` | The entities with their relations declared; targets resolve to the returned entities. |
|
|
289
447
|
| `Entity.select(entity, { key: true or Selection })` | A Selection: what was selected (`members`) and the `schema` of the result. |
|
|
290
|
-
| `Entity.page(selection, { first, after } or { last, before })` | In a Selection, a `many` relation read as a
|
|
448
|
+
| `Entity.page(selection, { first, after } or { last, before })` | In a Selection, a `many` relation read as a page: `items`, `hasNext`, `hasPrevious`. |
|
|
449
|
+
| `Entity.fields(entity, ...keys)` | The schemas of those fields, by key, to spread into an input's struct. |
|
|
291
450
|
| `Entity.input(entity, struct, mapping?)` | Experimental. Which member each key of an operation's input writes. |
|
|
292
451
|
| `Relation.nested(relation, input)` | In an input mapping: the key holds the target itself, written through `input`. |
|
|
293
452
|
| `Entity.selectFor(input)` | The Selection of the members an input writes: what an edit screen loads. |
|
|
@@ -297,11 +456,23 @@ Annotating again combines with what is there, using the key's own `merge`.
|
|
|
297
456
|
| `Entity.annotateMembers({ key: metadata })` | Pipe step attaching metadata to members by key. |
|
|
298
457
|
| `Entity.same(a, b)` | Whether two descriptors are versions of one Entity. |
|
|
299
458
|
| `Entity.is(value)` | Whether a value is an Entity descriptor. |
|
|
459
|
+
| `Expr.eq(left, right)` | Two values are the same; a field or a plain value on either side is coerced, and a predicate may stand where a boolean is wanted. |
|
|
460
|
+
| `Expr.isNull(field)` / `Expr.isNotNull(field)` | Whether a value is absent; one node, with the answer absence gives flipped. |
|
|
461
|
+
| `Expr.contains(field, search)` | Whether text contains text. Containing the empty string is everything, but a null contains nothing. |
|
|
462
|
+
| `Expr.field(field)` | One field of one Entity, as a scalar. |
|
|
463
|
+
| `Expr.input(key, schema)` | A value the query is given when it runs, as a placeholder. |
|
|
464
|
+
| `Expr.literal(value)` | A constant. Comparisons coerce one, so this is rarely written. |
|
|
465
|
+
| `Order.asc(expr)` / `Order.desc(expr)` | One term of an ordering, over a field or a scalar. |
|
|
466
|
+
| `dependenciesOf(...nodes)` | The distinct fields, inputs, and operations those expressions use. |
|
|
467
|
+
| `Query.from(entity)` | Every row of an Entity: the query each step narrows. |
|
|
468
|
+
| `Query.where(...predicates)` | Pipe step keeping the rows those hold for; conjoins with what is there. |
|
|
469
|
+
| `Query.orderBy(...terms)` | Pipe step reading in that order; appends after existing terms. |
|
|
470
|
+
| `Query.dependencies(query)` | What the whole query reads: every predicate and ordering term. |
|
|
300
471
|
|
|
301
472
|
## Limits
|
|
302
473
|
|
|
303
|
-
-
|
|
304
|
-
|
|
474
|
+
- The identifier is the field named `id`; no other field can be declared as it,
|
|
475
|
+
because Remote keys its store by `id`.
|
|
305
476
|
- A Selection has no filtering or ordering, and a page has no total; those
|
|
306
477
|
belong to the interpreter that fetches.
|
|
307
478
|
- Relations reach only the entities of one `Entity.relate` call; relating the
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,211 @@
|
|
|
1
1
|
import { Pipeable, Schema } from "effect";
|
|
2
2
|
import { Metadata } from "foldkit-metadata";
|
|
3
|
+
//#region src/expr.d.ts
|
|
4
|
+
/** A constant the query was written with. */
|
|
5
|
+
export interface LiteralExpr<T> {
|
|
6
|
+
readonly _tag: 'Literal';
|
|
7
|
+
readonly value: T;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* One field of one Entity. `owner` is the Entity's identity rather than its
|
|
11
|
+
* name, so two Entities defined with the same name are not one column.
|
|
12
|
+
*/
|
|
13
|
+
export interface FieldExpr<T> {
|
|
14
|
+
readonly _tag: 'Field';
|
|
15
|
+
readonly owner: EntityIdentity<string>;
|
|
16
|
+
readonly key: string;
|
|
17
|
+
readonly schema: Schema.Codec<T, unknown>;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* A value the query is given when it runs. A definition's body is built once,
|
|
21
|
+
* so inside it an input is this placeholder and never the value: there is
|
|
22
|
+
* nothing yet to branch on, and a query that wants to depend on what was passed
|
|
23
|
+
* says so with an operation over the placeholder.
|
|
24
|
+
*/
|
|
25
|
+
export interface InputExpr<T> {
|
|
26
|
+
readonly _tag: 'Input';
|
|
27
|
+
readonly key: string;
|
|
28
|
+
readonly schema: Schema.Codec<T, unknown>;
|
|
29
|
+
}
|
|
30
|
+
/** A typed scalar: what a comparison compares. */
|
|
31
|
+
export type Expr<T> = LiteralExpr<T> | FieldExpr<T> | InputExpr<T>;
|
|
32
|
+
/** Any scalar, for the places that hold operands without caring what they are. */
|
|
33
|
+
export type AnyExpr = Expr<unknown>;
|
|
34
|
+
/**
|
|
35
|
+
* `Expr<boolean>`, in the shape the operations that exist can actually take.
|
|
36
|
+
* The design's kernel is all boolean-valued (`eq`, `and`, `isNull`,
|
|
37
|
+
* `contains`, …), so a predicate is its own type rather than a phantom
|
|
38
|
+
* parameter on a general operation node: `Predicate` and `Expr<string>` cannot
|
|
39
|
+
* then be confused, which a structural phantom would allow. A scalar-valued
|
|
40
|
+
* operation, if one is ever needed, joins `Expr` instead.
|
|
41
|
+
*/
|
|
42
|
+
export type Predicate = EqPredicate | NullPredicate | ContainsPredicate;
|
|
43
|
+
/** Two values are the same. */
|
|
44
|
+
export interface EqPredicate {
|
|
45
|
+
readonly _tag: 'Eq';
|
|
46
|
+
readonly left: Operandish;
|
|
47
|
+
readonly right: Operandish;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Whether a value is absent. `present` says which answer absence gives, so one
|
|
51
|
+
* node covers `is null` and `is not null` rather than two that differ by a
|
|
52
|
+
* negation nothing else can express.
|
|
53
|
+
*/
|
|
54
|
+
export interface NullPredicate {
|
|
55
|
+
readonly _tag: 'Null';
|
|
56
|
+
readonly operand: AnyExpr;
|
|
57
|
+
readonly present: boolean;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Whether a text value contains another. Containing the empty string is
|
|
61
|
+
* everything, which is what lets a search box with nothing typed in it be the
|
|
62
|
+
* same query as one with something — see `Expr.contains`.
|
|
63
|
+
*/
|
|
64
|
+
export interface ContainsPredicate {
|
|
65
|
+
readonly _tag: 'Contains';
|
|
66
|
+
readonly value: AnyExpr;
|
|
67
|
+
readonly search: Operandish;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Anything an operation can be given: a scalar, or a predicate where a boolean
|
|
71
|
+
* is wanted. `Expr.eq(Expr.isNotNull(archivedAt), input.archived)` is the
|
|
72
|
+
* second case, and it is how a query depends on an input without branching on
|
|
73
|
+
* it.
|
|
74
|
+
*/
|
|
75
|
+
export type Operandish = AnyExpr | Predicate;
|
|
76
|
+
/** A field, a scalar already built from one, or a predicate used as a boolean. */
|
|
77
|
+
type Operand<T> = EntityField<string, string, Schema.Constraint> | Expr<T> | Predicate;
|
|
78
|
+
/** What an operand is worth, so a comparison's other side is checked against it. */
|
|
79
|
+
export type ValueOf<E> = E extends EntityField<string, string, infer S> ? Schema.Schema.Type<S> : E extends Predicate ? boolean : E extends Expr<infer T> ? T : never;
|
|
80
|
+
/** Whether a value is a predicate, and so usable where a boolean is wanted. */
|
|
81
|
+
export declare const isPredicate: (value: unknown) => value is Predicate;
|
|
82
|
+
/** Which fields and inputs an expression reads, and which operations it uses. */
|
|
83
|
+
export interface Dependencies {
|
|
84
|
+
/** One entry per distinct field, as `Entity.key`. */
|
|
85
|
+
readonly fields: ReadonlyArray<{
|
|
86
|
+
readonly entity: string;
|
|
87
|
+
readonly key: string;
|
|
88
|
+
}>;
|
|
89
|
+
/** One entry per distinct input key. */
|
|
90
|
+
readonly inputs: ReadonlyArray<string>;
|
|
91
|
+
/** One entry per distinct operation, so an interpreter can refuse what it cannot run. */
|
|
92
|
+
readonly operations: ReadonlyArray<string>;
|
|
93
|
+
}
|
|
94
|
+
export declare const Expr: {
|
|
95
|
+
/** A constant. Comparisons coerce a plain value, so this is rarely written. */
|
|
96
|
+
literal: <T>(value: T) => LiteralExpr<T>;
|
|
97
|
+
/**
|
|
98
|
+
* A value the query is given when it runs. A definition builds these from its
|
|
99
|
+
* `Input` schema; written by hand only when constructing a body directly.
|
|
100
|
+
*/
|
|
101
|
+
input: <T>(key: string, schema: Schema.Codec<T, unknown>) => InputExpr<T>;
|
|
102
|
+
/** One field of one Entity, as a scalar. */
|
|
103
|
+
field: <Name extends string, Key extends string, S extends Schema.Constraint>(field: EntityField<Name, Key, S>) => FieldExpr<Schema.Schema.Type<S>>;
|
|
104
|
+
/**
|
|
105
|
+
* Two scalars are the same value. A field or a plain value on either side is
|
|
106
|
+
* coerced, so the common form reads as it means:
|
|
107
|
+
*
|
|
108
|
+
* ```ts
|
|
109
|
+
* Expr.eq(Post.fields.slug, input.slug)
|
|
110
|
+
* Expr.eq(Post.fields.status, 'active')
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
eq: <L extends Operand<any>>(left: L, right: ValueOf<L> | Expr<ValueOf<L>> | (boolean extends ValueOf<L> ? Predicate : never)) => EqPredicate;
|
|
114
|
+
/**
|
|
115
|
+
* Whether a field holds no value. Its opposite is `isNotNull`; both are the
|
|
116
|
+
* one node, because a query asks which of the two it means and nothing here
|
|
117
|
+
* can negate a predicate.
|
|
118
|
+
*/
|
|
119
|
+
isNull: <L extends Operand<any>>(operand: L) => NullPredicate;
|
|
120
|
+
/** Whether a field holds a value. */
|
|
121
|
+
isNotNull: <L extends Operand<any>>(operand: L) => NullPredicate;
|
|
122
|
+
/**
|
|
123
|
+
* Whether a text value contains `search`, anywhere in it. Containing the
|
|
124
|
+
* empty string is everything, so a search box with nothing typed in it is the
|
|
125
|
+
* same query as one with something — no branch, and no second query.
|
|
126
|
+
*
|
|
127
|
+
* **Case-insensitive**, which is what a search means, and which has to be
|
|
128
|
+
* said rather than left to the interpreter: SQLite's `like` ignores case and
|
|
129
|
+
* Postgres's does not, so a body that left it open would mean two things.
|
|
130
|
+
* Folding is ASCII-only, because that is what `lower` does in SQLite without
|
|
131
|
+
* ICU.
|
|
132
|
+
*
|
|
133
|
+
* **Over a column that can be null this is not the same as no filter.** A
|
|
134
|
+
* null contains nothing, not even the empty string, so its rows drop out. A
|
|
135
|
+
* nullable column that should match everything on an empty search says so:
|
|
136
|
+
* `Expr.or` does not exist yet, so for now such a column needs its own
|
|
137
|
+
* predicate or a native escape hatch.
|
|
138
|
+
*/
|
|
139
|
+
contains: <L extends Operand<any>>(value: L, search: string | Expr<string>) => ContainsPredicate;
|
|
140
|
+
};
|
|
141
|
+
/** One term of an ordering: a scalar and the direction to read it in. */
|
|
142
|
+
export interface OrderTerm {
|
|
143
|
+
readonly direction: 'asc' | 'desc';
|
|
144
|
+
readonly expr: AnyExpr;
|
|
145
|
+
}
|
|
146
|
+
export declare const Order: {
|
|
147
|
+
asc: <E extends Operand<any>>(expr: E) => OrderTerm;
|
|
148
|
+
desc: <E extends Operand<any>>(expr: E) => OrderTerm;
|
|
149
|
+
};
|
|
150
|
+
/**
|
|
151
|
+
* What an expression reads and uses, for the planner and for an interpreter
|
|
152
|
+
* deciding whether it can run this query at all. Distinct entries only, in the
|
|
153
|
+
* order first seen, so the answer is stable enough to assert on.
|
|
154
|
+
*/
|
|
155
|
+
export declare const dependenciesOf: (...nodes: ReadonlyArray<AnyExpr | Predicate | OrderTerm>) => Dependencies;
|
|
156
|
+
/**
|
|
157
|
+
* Which rows a query is about, as a value: an Entity to read, the predicates
|
|
158
|
+
* every row must satisfy, and the order to read them in. It says nothing about
|
|
159
|
+
* which fields to return — that is a Selection — and nothing about pagination,
|
|
160
|
+
* liveness, or whether absence is an error, which belong to the consumer's read
|
|
161
|
+
* rather than to the relation.
|
|
162
|
+
*
|
|
163
|
+
* Composing one performs no work. `Query.from(Post)` names no table and opens
|
|
164
|
+
* no connection; an interpreter turns the value into a query when something
|
|
165
|
+
* asks it to.
|
|
166
|
+
*/
|
|
167
|
+
export interface Query<E extends AnyEntity> extends Pipeable.Pipeable {
|
|
168
|
+
readonly _tag: 'Query';
|
|
169
|
+
readonly entity: E;
|
|
170
|
+
/**
|
|
171
|
+
* Every predicate holds: the list *is* the conjunction. Keeping it a list
|
|
172
|
+
* rather than folding it into one `and` is what makes each `where` a reusable
|
|
173
|
+
* fragment, and it means no `Expr.and` exists until a query needs a
|
|
174
|
+
* conjunction nested inside something else.
|
|
175
|
+
*/
|
|
176
|
+
readonly where: ReadonlyArray<Predicate>;
|
|
177
|
+
/** In order of significance; a later `orderBy` appends less significant terms. */
|
|
178
|
+
readonly orderBy: ReadonlyArray<OrderTerm>;
|
|
179
|
+
}
|
|
180
|
+
/** A `Query` over any Entity, for the places that hold one without caring which. */
|
|
181
|
+
export type AnyQuery = Query<AnyEntity>;
|
|
182
|
+
export declare const Query: {
|
|
183
|
+
/** Every row of an Entity: the query each transformation narrows. */
|
|
184
|
+
from: <E extends AnyEntity>(entity: E) => Query<E>;
|
|
185
|
+
/**
|
|
186
|
+
* Narrows to the rows the predicate holds for. Two `where`s conjoin — the
|
|
187
|
+
* second never replaces the first — so a fragment can be written once and
|
|
188
|
+
* piped into any query over the same Entity:
|
|
189
|
+
*
|
|
190
|
+
* ```ts
|
|
191
|
+
* const published = Query.where(Expr.eq(Post.fields.published, true))
|
|
192
|
+
* Query.from(Post).pipe(published, Query.where(byTitle))
|
|
193
|
+
* ```
|
|
194
|
+
*/
|
|
195
|
+
where: (...predicates: ReadonlyArray<Predicate>) => <E extends AnyEntity>(self: Query<E>) => Query<E>;
|
|
196
|
+
/**
|
|
197
|
+
* Reads the rows in this order. Two `orderBy`s append, so an earlier term
|
|
198
|
+
* stays the more significant one and a later call adds a tie-breaker rather
|
|
199
|
+
* than silently winning.
|
|
200
|
+
*/
|
|
201
|
+
orderBy: (...terms: ReadonlyArray<OrderTerm>) => <E extends AnyEntity>(self: Query<E>) => Query<E>;
|
|
202
|
+
/**
|
|
203
|
+
* What the whole query reads: the fields and inputs of every predicate and
|
|
204
|
+
* every ordering term, and the operations it uses.
|
|
205
|
+
*/
|
|
206
|
+
dependencies: (self: AnyQuery) => Dependencies;
|
|
207
|
+
};
|
|
208
|
+
//#endregion
|
|
3
209
|
//#region src/index.d.ts
|
|
4
210
|
export declare const EntityTypeId: unique symbol;
|
|
5
211
|
export type EntityTypeId = typeof EntityTypeId;
|
|
@@ -97,21 +303,41 @@ export type Related<Es extends Entities, Rs extends RelationMap<Es>, K extends k
|
|
|
97
303
|
type CheckRelations<Es extends Entities, Rs> = { readonly [K in keyof Rs]: K extends keyof Es ? { readonly [R in keyof Rs[K]]: R extends keyof Es[K]['members'] ? `"${R & string}" is already a member of ${Es[K]['name']}` : Rs[K][R]; } : 'not one of the entities being related'; };
|
|
98
304
|
export declare const SelectionTypeId: unique symbol;
|
|
99
305
|
export type SelectionTypeId = typeof SelectionTypeId;
|
|
100
|
-
/**
|
|
101
|
-
|
|
306
|
+
/**
|
|
307
|
+
* The schema that identifies one of an Entity: its `id` field when that is text
|
|
308
|
+
* (a plain string, a brand, a pattern), and plain text otherwise. An id is text
|
|
309
|
+
* because a ref travels and is stored as text; an Entity keyed by a number still
|
|
310
|
+
* has refs, and their ids are the number as text.
|
|
311
|
+
*/
|
|
312
|
+
export type IdSchemaOf<E> = E extends {
|
|
313
|
+
readonly fields: {
|
|
314
|
+
readonly id: {
|
|
315
|
+
readonly schema: infer S;
|
|
316
|
+
};
|
|
317
|
+
};
|
|
318
|
+
} ? S extends Schema.Constraint ? [S['Type']] extends [string] ? S : Schema.String : Schema.String : Schema.String;
|
|
319
|
+
/** What identifies one of an Entity: `IdOf<typeof Blog.Post>` is `PostId` when its `id` field is one. */
|
|
320
|
+
export type IdOf<E> = IdSchemaOf<E>['Type'];
|
|
321
|
+
/**
|
|
322
|
+
* What a relation selected with `true` yields: which Entity, and which one. `Id`
|
|
323
|
+
* is the target's own id type, so a ref to an Author cannot be used as a Post's.
|
|
324
|
+
*/
|
|
325
|
+
export interface EntityRef<Name extends string = string, Id extends string = string> {
|
|
102
326
|
readonly entity: Name;
|
|
103
|
-
readonly id:
|
|
327
|
+
readonly id: Id;
|
|
104
328
|
}
|
|
105
|
-
type RefSchema<
|
|
106
|
-
readonly entity: Schema.Literal<
|
|
107
|
-
readonly id:
|
|
329
|
+
type RefSchema<Target extends AnyEntity> = Schema.Struct<{
|
|
330
|
+
readonly entity: Schema.Literal<Target['name']>;
|
|
331
|
+
readonly id: IdSchemaOf<Target>;
|
|
108
332
|
}>;
|
|
109
333
|
/**
|
|
110
334
|
* A view of the Entity graph: which members to read, and the schema of the
|
|
111
335
|
* value that results. It says nothing about where the value comes from.
|
|
112
336
|
*/
|
|
113
|
-
export interface Selection<Name extends string, Members, S extends Schema.Constraint> {
|
|
337
|
+
export interface Selection<Name extends string, Members, S extends Schema.Constraint, Id extends string = string> {
|
|
114
338
|
readonly [SelectionTypeId]: SelectionTypeId;
|
|
339
|
+
/** Type-only: the id type of the Entity selected, so a reader can ask for the right one. Never set. */
|
|
340
|
+
readonly Id?: Id;
|
|
115
341
|
readonly entity: Entity<Name, any, any, any>;
|
|
116
342
|
/** What was selected, by member key: `true`, or a relation's nested Selection. */
|
|
117
343
|
readonly members: Members;
|
|
@@ -130,12 +356,6 @@ export interface PageWindow {
|
|
|
130
356
|
readonly after?: string | undefined;
|
|
131
357
|
readonly before?: string | undefined;
|
|
132
358
|
}
|
|
133
|
-
/** One page of a `many` relation: the items read, and whether more lie on either side. */
|
|
134
|
-
export interface Page<Item> {
|
|
135
|
-
readonly items: ReadonlyArray<Item>;
|
|
136
|
-
readonly hasNext: boolean;
|
|
137
|
-
readonly hasPrevious: boolean;
|
|
138
|
-
}
|
|
139
359
|
export declare const SelectionPageTypeId: unique symbol;
|
|
140
360
|
export type SelectionPageTypeId = typeof SelectionPageTypeId;
|
|
141
361
|
/** A Selection of a `many` relation's target, read a page at a time. */
|
|
@@ -151,7 +371,7 @@ type PageSchema<S extends Schema.Constraint> = Schema.Struct<{
|
|
|
151
371
|
}>;
|
|
152
372
|
type SelectionSpec<E extends AnyEntity, Spec> = { readonly [K in keyof Spec]: K extends keyof E['relations'] ? E['relations'][K] extends EntityRelation<any, any, infer Target, infer C, any> ? true | AnySelection<Target['name']> | (C extends 'many' ? SelectionPage<Target['name'], any> : never) : never : K extends keyof E['members'] ? true : `"${K & string}" is not a member of ${E['name']}`; };
|
|
153
373
|
type RelationShape<C extends Cardinality, Optional extends boolean, S extends Schema.Constraint> = C extends 'many' ? Schema.$Array<S> : Optional extends true ? Schema.NullOr<S> : S;
|
|
154
|
-
type SelectedSchema<Member, Selected> = Member extends EntityField<any, any, infer S> | EntityDerived<any, any, infer S> ? S : Member extends EntityRelation<any, any, infer Target, infer C, infer Optional> ? Selected extends SelectionPage<any, infer S> ? PageSchema<S> : RelationShape<C, Optional, Selected extends Selection<any, any, infer S> ? S : RefSchema<Target
|
|
374
|
+
type SelectedSchema<Member, Selected> = Member extends EntityField<any, any, infer S> | EntityDerived<any, any, infer S> ? S : Member extends EntityRelation<any, any, infer Target, infer C, infer Optional> ? Selected extends SelectionPage<any, infer S> ? PageSchema<S> : RelationShape<C, Optional, Selected extends Selection<any, any, infer S> ? S : RefSchema<Target>> : never;
|
|
155
375
|
type SelectionSchema<E extends AnyEntity, Spec> = Schema.Struct<{ readonly [K in keyof Spec & keyof E['members']]: SelectedSchema<E['members'][K], Spec[K]>; }>;
|
|
156
376
|
/** An input key that carries a relation's target: the id of a `one`, the ids of a `many`. */
|
|
157
377
|
export interface RelationInput<R extends EntityRelation<any, any, any, any, any>> {
|
|
@@ -175,7 +395,7 @@ export interface Unmapped {
|
|
|
175
395
|
/** What one key of an operation's input means in terms of the Entity. */
|
|
176
396
|
export type InputMember = EntityField<string, string, Schema.Constraint> | RelationInput<EntityRelation<string, string, AnyEntity, Cardinality, boolean>> | NestedInput<EntityRelation<string, string, AnyEntity, Cardinality, boolean>, EntityInput<AnyEntity, any, any>> | Unmapped;
|
|
177
397
|
/** The ids a relation takes as input: one id, a nullable id, or a list of ids. */
|
|
178
|
-
type RelationIds<R> = R extends EntityRelation<any, any,
|
|
398
|
+
type RelationIds<R> = R extends EntityRelation<any, any, infer Target, infer C, infer Optional> ? C extends 'many' ? ReadonlyArray<IdOf<Target>> : Optional extends true ? IdOf<Target> | null : IdOf<Target> : never;
|
|
179
399
|
/** What a nested input takes: the value of the target's input, or a list of them for a `many`. */
|
|
180
400
|
type NestedValues<R, I> = I extends EntityInput<any, infer Fields, any> ? R extends EntityRelation<any, any, any, 'many', any> ? ReadonlyArray<Schema.Struct.Type<Fields>> : Schema.Struct.Type<Fields> : never;
|
|
181
401
|
/**
|
|
@@ -187,8 +407,14 @@ type Present<T> = Exclude<T, null | undefined>;
|
|
|
187
407
|
type MappingFor<Name extends string, Input, M> = M extends Unmapped ? M : M extends EntityField<infer Owner, any, any> | RelationInput<EntityRelation<infer Owner, any, any, any, any>> | NestedInput<EntityRelation<infer Owner, any, any, any, any>, any> ? [Owner] extends [Name] ? M extends EntityField<any, any, infer S> ? Present<Input> extends Schema.Schema.Type<S> ? M : 'the input value does not fit this field' : M extends RelationInput<infer R> ? Present<Input> extends RelationIds<R> ? M : 'the input value is not the id shape of this relation' : M extends NestedInput<infer R, infer I> ? R extends EntityRelation<any, any, infer Target, any, any> ? I extends EntityInput<infer Of, any, any> ? [Of['name']] extends [Target['name']] ? Present<Input> extends NestedValues<R, I> ? M : 'the input value is not the value of the nested input' : `the nested input is of ${Of['name']}, not ${Target['name']}` : never : never : never : `this member belongs to ${Owner}` : 'map an input key to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped';
|
|
188
408
|
/** A key that names a field whose value it fits maps itself; every other key needs an entry. */
|
|
189
409
|
type SelfMapped<E extends AnyEntity, Fields extends Schema.Struct.Fields> = { [K in keyof Fields]: K extends keyof E['fields'] ? Present<Schema.Schema.Type<Fields[K]>> extends Schema.Schema.Type<E['fields'][K]['schema']> ? K : never : never; }[keyof Fields];
|
|
190
|
-
|
|
191
|
-
|
|
410
|
+
/**
|
|
411
|
+
* A mapping written as a member's key: `'title'` is that Field, and `'author'` is
|
|
412
|
+
* `Relation.input` of that relation. Nothing is inferred from the input key's own
|
|
413
|
+
* name; the member is still named, only more briefly.
|
|
414
|
+
*/
|
|
415
|
+
type Named<E extends AnyEntity, M> = M extends string ? M extends keyof E['fields'] ? E['fields'][M] : M extends keyof E['relations'] ? RelationInput<E['relations'][M]> : `"${M}" names no field or relation of ${E['name']}` : M;
|
|
416
|
+
type InputMapping<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = { readonly [K in Exclude<keyof Fields, SelfMapped<E, Fields>>]: unknown; } & { readonly [K in keyof Mapping]: K extends keyof Fields ? Named<E, Mapping[K]> extends (infer Member) ? Member extends string ? Member : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member> extends Member ? Mapping[K] : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member> : never : `"${K & string}" is not a key of the input`; };
|
|
417
|
+
type InputMembers<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = { readonly [K in keyof Fields]: K extends keyof Mapping ? Named<E, Mapping[K]> : K extends keyof E['fields'] ? E['fields'][K] : never; };
|
|
192
418
|
/**
|
|
193
419
|
* An operation's input read against an Entity: which member each input key
|
|
194
420
|
* writes. The operation decides what may be submitted; the Entity only says
|
|
@@ -220,11 +446,11 @@ export declare const Entity: {
|
|
|
220
446
|
* target, that Selection's value. `many` yields an array, an optional `one`
|
|
221
447
|
* is nullable.
|
|
222
448
|
*/
|
|
223
|
-
select: <E extends AnyEntity, const Spec>(entity: E, spec: Spec & SelectionSpec<E, Spec>) => Selection<E["name"], Spec, SelectionSchema<E, Spec>>;
|
|
449
|
+
select: <E extends AnyEntity, const Spec>(entity: E, spec: Spec & SelectionSpec<E, Spec>) => Selection<E["name"], Spec, SelectionSchema<E, Spec>, IdOf<E>>;
|
|
224
450
|
/**
|
|
225
451
|
* A `many` relation read a page at a time, in place of its Selection:
|
|
226
|
-
* `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a
|
|
227
|
-
* of the Selection's values
|
|
452
|
+
* `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page
|
|
453
|
+
* of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.
|
|
228
454
|
*/
|
|
229
455
|
page: <Name extends string, S extends Schema.Constraint>(selection: Selection<Name, any, S>, window: PageWindow) => SelectionPage<Name, S>;
|
|
230
456
|
/** Adds readable members that are not part of `entity.schema`. */
|
|
@@ -242,11 +468,17 @@ export declare const Entity: {
|
|
|
242
468
|
input: <E extends AnyEntity, Fields extends Schema.Struct.Fields, const Mapping = {}>(entity: E, schema: Schema.Struct<Fields>, ...mapping: keyof InputMapping<E, Fields, Mapping> extends never ? [mapping?: Mapping & InputMapping<E, Fields, Mapping>] : [mapping: Mapping & InputMapping<E, Fields, Mapping>]) => EntityInput<E, Fields, InputMembers<E, Fields, Mapping>>;
|
|
243
469
|
/** For an input key that is about the operation rather than the Entity. */
|
|
244
470
|
unmapped: Unmapped;
|
|
471
|
+
/**
|
|
472
|
+
* The schemas of some of an Entity's fields, by key, to spread into an input's
|
|
473
|
+
* struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.
|
|
474
|
+
* The input then keeps the field's own rules, and its keys map themselves.
|
|
475
|
+
*/
|
|
476
|
+
fields: <E extends AnyEntity, const Keys extends ReadonlyArray<keyof E["fields"] & string>>(entity: E, ...keys: Keys) => { readonly [K in Keys[number]]: E["fields"][K]["schema"]; };
|
|
245
477
|
/**
|
|
246
478
|
* The Selection of every member an input writes, with each relation as refs:
|
|
247
479
|
* what an edit screen loads before it shows the input's current values.
|
|
248
480
|
*/
|
|
249
|
-
selectFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(input: EntityInput<E, Fields, Members>) => Selection<E["name"], WrittenSpec<Members>, SelectionSchema<E, WrittenSpec<Members
|
|
481
|
+
selectFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(input: EntityInput<E, Fields, Members>) => Selection<E["name"], WrittenSpec<Members>, SelectionSchema<E, WrittenSpec<Members>>, IdOf<E>>;
|
|
250
482
|
/**
|
|
251
483
|
* The input values that reproduce `value`, a value read through `selectFor`
|
|
252
484
|
* (or any Selection with those members): a field as it is, a relation as the
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/expr.ts","../src/index.ts"],"mappings":";;;;iBAiBiB,YAAY;WAClB;WACA,OAAO;;;;;;iBAOD,UAAU;WAChB;WACA,OAAO;WACP;WACA,QAAQ,OAA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
5
|
+
* `Expr` — a query's scalar computations as typed values.
|
|
6
|
+
*
|
|
7
|
+
* An Entity says what a domain has; an `Expr` says something about one row of
|
|
8
|
+
* it. A field reference, an input placeholder, a literal, and comparisons of
|
|
9
|
+
* those are all immutable data: building one performs no work, reads nothing,
|
|
10
|
+
* and names no database. An interpreter compiles it — `foldkit-remote-drizzle`
|
|
11
|
+
* to SQL, an in-memory evaluator to a predicate over rows.
|
|
12
|
+
*
|
|
13
|
+
* This is deliberately not SQL and deliberately not arbitrary JavaScript. Every
|
|
14
|
+
* operation here is one a real query in this repository needs; the set grows
|
|
15
|
+
* from queries, not from what a database could express.
|
|
16
|
+
*/
|
|
17
|
+
const tagOf = (value) => typeof value === "object" && value !== null ? value._tag : void 0;
|
|
18
|
+
/**
|
|
19
|
+
* An Entity's field and a `FieldExpr` are the same three members under the same
|
|
20
|
+
* tag — the Entity's carries `metadata` besides — so this reads either and is
|
|
21
|
+
* idempotent on its own output. Nothing needs to tell them apart, which is
|
|
22
|
+
* better than telling them apart by which extra member happens to be present.
|
|
23
|
+
*/
|
|
24
|
+
const literal = (value) => ({
|
|
25
|
+
_tag: "Literal",
|
|
26
|
+
value
|
|
27
|
+
});
|
|
28
|
+
const fieldExpr = (field) => ({
|
|
29
|
+
_tag: "Field",
|
|
30
|
+
owner: field.owner,
|
|
31
|
+
key: field.key,
|
|
32
|
+
schema: field.schema
|
|
33
|
+
});
|
|
34
|
+
const predicateTags = /* @__PURE__ */ new Set([
|
|
35
|
+
"Eq",
|
|
36
|
+
"Null",
|
|
37
|
+
"Contains"
|
|
38
|
+
]);
|
|
39
|
+
/** Whether a value is a predicate, and so usable where a boolean is wanted. */
|
|
40
|
+
const isPredicate = (value) => predicateTags.has(tagOf(value));
|
|
41
|
+
/**
|
|
42
|
+
* A field of either kind becomes a `FieldExpr`, a scalar or a predicate is
|
|
43
|
+
* itself, and anything else is the constant it is.
|
|
44
|
+
*/
|
|
45
|
+
const toOperand = (value) => {
|
|
46
|
+
const tag = tagOf(value);
|
|
47
|
+
if (tag === "Field") return fieldExpr(value);
|
|
48
|
+
if (tag === "Literal" || tag === "Input" || predicateTags.has(tag)) return value;
|
|
49
|
+
return literal(value);
|
|
50
|
+
};
|
|
51
|
+
/** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */
|
|
52
|
+
const toExpr = (value, step) => {
|
|
53
|
+
const operand = toOperand(value);
|
|
54
|
+
if (isPredicate(operand)) throw new Error(`[foldkit-entity] Expr.${step}: a predicate is already an answer, so asking this of one is not a question`);
|
|
55
|
+
return operand;
|
|
56
|
+
};
|
|
57
|
+
const Expr = {
|
|
58
|
+
/** A constant. Comparisons coerce a plain value, so this is rarely written. */
|
|
59
|
+
literal,
|
|
60
|
+
/**
|
|
61
|
+
* A value the query is given when it runs. A definition builds these from its
|
|
62
|
+
* `Input` schema; written by hand only when constructing a body directly.
|
|
63
|
+
*/
|
|
64
|
+
input: (key, schema) => ({
|
|
65
|
+
_tag: "Input",
|
|
66
|
+
key,
|
|
67
|
+
schema
|
|
68
|
+
}),
|
|
69
|
+
/** One field of one Entity, as a scalar. */
|
|
70
|
+
field: (field) => fieldExpr(field),
|
|
71
|
+
/**
|
|
72
|
+
* Two scalars are the same value. A field or a plain value on either side is
|
|
73
|
+
* coerced, so the common form reads as it means:
|
|
74
|
+
*
|
|
75
|
+
* ```ts
|
|
76
|
+
* Expr.eq(Post.fields.slug, input.slug)
|
|
77
|
+
* Expr.eq(Post.fields.status, 'active')
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
eq: (left, right) => ({
|
|
81
|
+
_tag: "Eq",
|
|
82
|
+
left: toOperand(left),
|
|
83
|
+
right: toOperand(right)
|
|
84
|
+
}),
|
|
85
|
+
/**
|
|
86
|
+
* Whether a field holds no value. Its opposite is `isNotNull`; both are the
|
|
87
|
+
* one node, because a query asks which of the two it means and nothing here
|
|
88
|
+
* can negate a predicate.
|
|
89
|
+
*/
|
|
90
|
+
isNull: (operand) => ({
|
|
91
|
+
_tag: "Null",
|
|
92
|
+
operand: toExpr(operand, "isNull"),
|
|
93
|
+
present: false
|
|
94
|
+
}),
|
|
95
|
+
/** Whether a field holds a value. */
|
|
96
|
+
isNotNull: (operand) => ({
|
|
97
|
+
_tag: "Null",
|
|
98
|
+
operand: toExpr(operand, "isNotNull"),
|
|
99
|
+
present: true
|
|
100
|
+
}),
|
|
101
|
+
/**
|
|
102
|
+
* Whether a text value contains `search`, anywhere in it. Containing the
|
|
103
|
+
* empty string is everything, so a search box with nothing typed in it is the
|
|
104
|
+
* same query as one with something — no branch, and no second query.
|
|
105
|
+
*
|
|
106
|
+
* **Case-insensitive**, which is what a search means, and which has to be
|
|
107
|
+
* said rather than left to the interpreter: SQLite's `like` ignores case and
|
|
108
|
+
* Postgres's does not, so a body that left it open would mean two things.
|
|
109
|
+
* Folding is ASCII-only, because that is what `lower` does in SQLite without
|
|
110
|
+
* ICU.
|
|
111
|
+
*
|
|
112
|
+
* **Over a column that can be null this is not the same as no filter.** A
|
|
113
|
+
* null contains nothing, not even the empty string, so its rows drop out. A
|
|
114
|
+
* nullable column that should match everything on an empty search says so:
|
|
115
|
+
* `Expr.or` does not exist yet, so for now such a column needs its own
|
|
116
|
+
* predicate or a native escape hatch.
|
|
117
|
+
*/
|
|
118
|
+
contains: (value, search) => ({
|
|
119
|
+
_tag: "Contains",
|
|
120
|
+
value: toExpr(value, "contains"),
|
|
121
|
+
search: toOperand(search)
|
|
122
|
+
})
|
|
123
|
+
};
|
|
124
|
+
const Order = {
|
|
125
|
+
asc: (expr) => ({
|
|
126
|
+
direction: "asc",
|
|
127
|
+
expr: toExpr(expr, "asc")
|
|
128
|
+
}),
|
|
129
|
+
desc: (expr) => ({
|
|
130
|
+
direction: "desc",
|
|
131
|
+
expr: toExpr(expr, "desc")
|
|
132
|
+
})
|
|
133
|
+
};
|
|
134
|
+
const walk = (node, fields, inputs, operations) => {
|
|
135
|
+
switch (node._tag) {
|
|
136
|
+
case "Literal": return;
|
|
137
|
+
case "Field":
|
|
138
|
+
fields.set(`${node.owner.name}.${node.key}`, {
|
|
139
|
+
entity: node.owner.name,
|
|
140
|
+
key: node.key
|
|
141
|
+
});
|
|
142
|
+
return;
|
|
143
|
+
case "Input":
|
|
144
|
+
inputs.add(node.key);
|
|
145
|
+
return;
|
|
146
|
+
case "Eq":
|
|
147
|
+
operations.add("eq");
|
|
148
|
+
walk(node.left, fields, inputs, operations);
|
|
149
|
+
walk(node.right, fields, inputs, operations);
|
|
150
|
+
return;
|
|
151
|
+
case "Null":
|
|
152
|
+
operations.add(node.present ? "isNotNull" : "isNull");
|
|
153
|
+
walk(node.operand, fields, inputs, operations);
|
|
154
|
+
return;
|
|
155
|
+
case "Contains":
|
|
156
|
+
operations.add("contains");
|
|
157
|
+
walk(node.value, fields, inputs, operations);
|
|
158
|
+
walk(node.search, fields, inputs, operations);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
/**
|
|
163
|
+
* What an expression reads and uses, for the planner and for an interpreter
|
|
164
|
+
* deciding whether it can run this query at all. Distinct entries only, in the
|
|
165
|
+
* order first seen, so the answer is stable enough to assert on.
|
|
166
|
+
*/
|
|
167
|
+
const dependenciesOf = (...nodes) => {
|
|
168
|
+
const fields = /* @__PURE__ */ new Map();
|
|
169
|
+
const inputs = /* @__PURE__ */ new Set();
|
|
170
|
+
const operations = /* @__PURE__ */ new Set();
|
|
171
|
+
for (const node of nodes) walk("direction" in node ? node.expr : node, fields, inputs, operations);
|
|
172
|
+
return {
|
|
173
|
+
fields: [...fields.values()],
|
|
174
|
+
inputs: [...inputs],
|
|
175
|
+
operations: [...operations]
|
|
176
|
+
};
|
|
177
|
+
};
|
|
178
|
+
/** Every field an expression reads, as the nodes themselves. */
|
|
179
|
+
const fieldsIn = function* (node) {
|
|
180
|
+
switch (node._tag) {
|
|
181
|
+
case "Field":
|
|
182
|
+
yield node;
|
|
183
|
+
return;
|
|
184
|
+
case "Literal":
|
|
185
|
+
case "Input": return;
|
|
186
|
+
case "Eq":
|
|
187
|
+
yield* fieldsIn(node.left);
|
|
188
|
+
yield* fieldsIn(node.right);
|
|
189
|
+
return;
|
|
190
|
+
case "Null":
|
|
191
|
+
yield* fieldsIn(node.operand);
|
|
192
|
+
return;
|
|
193
|
+
case "Contains":
|
|
194
|
+
yield* fieldsIn(node.value);
|
|
195
|
+
yield* fieldsIn(node.search);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
/**
|
|
200
|
+
* A query reads one Entity, so a predicate or ordering term naming a different
|
|
201
|
+
* one cannot be answered — an interpreter would be asked for a column of a
|
|
202
|
+
* table it was never told to read. Compared by identity, not by name, because
|
|
203
|
+
* two Entities defined with the same name are two Entities.
|
|
204
|
+
*/
|
|
205
|
+
const checkOwnership = (step, what, entity, nodes) => {
|
|
206
|
+
for (const node of nodes) for (const field of fieldsIn("direction" in node ? node.expr : node)) if (field.owner.token !== entity.identity.token) throw new Error(`[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}`);
|
|
207
|
+
};
|
|
208
|
+
const QueryProto = {
|
|
209
|
+
_tag: "Query",
|
|
210
|
+
pipe() {
|
|
211
|
+
return Pipeable.pipeArguments(this, arguments);
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
const query = (entity, where, orderBy) => Object.freeze(Object.assign(Object.create(QueryProto), {
|
|
215
|
+
entity,
|
|
216
|
+
where: Object.freeze(where),
|
|
217
|
+
orderBy: Object.freeze(orderBy)
|
|
218
|
+
}));
|
|
219
|
+
const Query = {
|
|
220
|
+
/** Every row of an Entity: the query each transformation narrows. */
|
|
221
|
+
from: (entity) => query(entity, [], []),
|
|
222
|
+
/**
|
|
223
|
+
* Narrows to the rows the predicate holds for. Two `where`s conjoin — the
|
|
224
|
+
* second never replaces the first — so a fragment can be written once and
|
|
225
|
+
* piped into any query over the same Entity:
|
|
226
|
+
*
|
|
227
|
+
* ```ts
|
|
228
|
+
* const published = Query.where(Expr.eq(Post.fields.published, true))
|
|
229
|
+
* Query.from(Post).pipe(published, Query.where(byTitle))
|
|
230
|
+
* ```
|
|
231
|
+
*/
|
|
232
|
+
where: (...predicates) => (self) => {
|
|
233
|
+
if (predicates.length === 0) return self;
|
|
234
|
+
checkOwnership("where", "a predicate", self.entity, predicates);
|
|
235
|
+
return query(self.entity, [...self.where, ...predicates], self.orderBy);
|
|
236
|
+
},
|
|
237
|
+
/**
|
|
238
|
+
* Reads the rows in this order. Two `orderBy`s append, so an earlier term
|
|
239
|
+
* stays the more significant one and a later call adds a tie-breaker rather
|
|
240
|
+
* than silently winning.
|
|
241
|
+
*/
|
|
242
|
+
orderBy: (...terms) => (self) => {
|
|
243
|
+
if (terms.length === 0) return self;
|
|
244
|
+
checkOwnership("orderBy", "a term", self.entity, terms);
|
|
245
|
+
return query(self.entity, self.where, [...self.orderBy, ...terms]);
|
|
246
|
+
},
|
|
247
|
+
/**
|
|
248
|
+
* What the whole query reads: the fields and inputs of every predicate and
|
|
249
|
+
* every ordering term, and the operations it uses.
|
|
250
|
+
*/
|
|
251
|
+
dependencies: (self) => dependenciesOf(...self.where, ...self.orderBy)
|
|
252
|
+
};
|
|
253
|
+
//#endregion
|
|
3
254
|
//#region src/index.ts
|
|
4
255
|
/**
|
|
5
256
|
* `foldkit-entity` — domain structure as typed values.
|
|
@@ -13,6 +264,14 @@ import { Metadata } from "foldkit-metadata";
|
|
|
13
264
|
const EntityTypeId = Symbol.for("foldkit-entity/Entity");
|
|
14
265
|
const SelectionTypeId = Symbol.for("foldkit-entity/Selection");
|
|
15
266
|
const SelectionPageTypeId = Symbol.for("foldkit-entity/SelectionPage");
|
|
267
|
+
const isText = (ast) => ast._tag === "String" || ast._tag === "TemplateLiteral" || ast._tag === "Literal" && typeof ast.literal === "string" || ast._tag === "Union" && (ast.types ?? []).length > 0 && (ast.types ?? []).every(isText);
|
|
268
|
+
/** The `id` field's schema when it is text, so a ref's id keeps its brand and its checks; else text. */
|
|
269
|
+
const idSchemaOf = (entity) => {
|
|
270
|
+
const id = entity.fields.id;
|
|
271
|
+
if (id === void 0 || id._tag !== "Field") return Schema.String;
|
|
272
|
+
const type = Schema.toType(id.schema);
|
|
273
|
+
return isText(type.ast) ? type : Schema.String;
|
|
274
|
+
};
|
|
16
275
|
const isSelectionPage = (value) => typeof value === "object" && value !== null && SelectionPageTypeId in value;
|
|
17
276
|
const isSelection = (value) => typeof value === "object" && value !== null && SelectionTypeId in value;
|
|
18
277
|
const unmapped = Object.freeze({ _tag: "Unmapped" });
|
|
@@ -146,7 +405,7 @@ const Entity = {
|
|
|
146
405
|
let item;
|
|
147
406
|
if (selected === true) item = Schema.Struct({
|
|
148
407
|
entity: Schema.Literal(target.name),
|
|
149
|
-
id:
|
|
408
|
+
id: idSchemaOf(target)
|
|
150
409
|
});
|
|
151
410
|
else if (isSelection(selected) && isSameEntity(selected.entity, target)) item = selected.schema;
|
|
152
411
|
else throw new Error(`Entity "${entity.name}": "${key}" takes true or a Selection of ${target.name}`);
|
|
@@ -161,8 +420,8 @@ const Entity = {
|
|
|
161
420
|
},
|
|
162
421
|
/**
|
|
163
422
|
* A `many` relation read a page at a time, in place of its Selection:
|
|
164
|
-
* `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a
|
|
165
|
-
* of the Selection's values
|
|
423
|
+
* `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page
|
|
424
|
+
* of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.
|
|
166
425
|
*/
|
|
167
426
|
page: (selection, window) => {
|
|
168
427
|
const sides = [window.first, window.last].filter((size) => size !== void 0);
|
|
@@ -222,8 +481,18 @@ const Entity = {
|
|
|
222
481
|
* from a naming convention such as `authorId`.
|
|
223
482
|
*/
|
|
224
483
|
input: (entity, schema, ...mapping) => {
|
|
225
|
-
const
|
|
226
|
-
for (const key of Object.keys(
|
|
484
|
+
const written = mapping[0] ?? {};
|
|
485
|
+
for (const key of Object.keys(written)) if (!(key in schema.fields)) throw new Error(`Entity "${entity.name}": "${key}" is mapped but is not a key of the input`);
|
|
486
|
+
const named = (key, name) => {
|
|
487
|
+
const member = entity.members[name];
|
|
488
|
+
if (member?._tag === "Field") return member;
|
|
489
|
+
if (member?._tag === "Relation") return Object.freeze({
|
|
490
|
+
_tag: "RelationInput",
|
|
491
|
+
relation: member
|
|
492
|
+
});
|
|
493
|
+
return fail(entity, `input key "${key}" is mapped to "${name}", which names no field or relation`);
|
|
494
|
+
};
|
|
495
|
+
const given = mapValues(written, (member, key) => typeof member === "string" ? named(key, member) : member);
|
|
227
496
|
const fields = entity.fields;
|
|
228
497
|
const members = mapValues(schema.fields, (_, key) => {
|
|
229
498
|
const member = given[key] ?? fields[key] ?? fail(entity, `input key "${key}" names no field; map it to a member or Entity.unmapped`);
|
|
@@ -241,6 +510,12 @@ const Entity = {
|
|
|
241
510
|
/** For an input key that is about the operation rather than the Entity. */
|
|
242
511
|
unmapped,
|
|
243
512
|
/**
|
|
513
|
+
* The schemas of some of an Entity's fields, by key, to spread into an input's
|
|
514
|
+
* struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.
|
|
515
|
+
* The input then keeps the field's own rules, and its keys map themselves.
|
|
516
|
+
*/
|
|
517
|
+
fields: (entity, ...keys) => Object.fromEntries(keys.map((key) => [key, (entity.fields[key] ?? fail(entity, `"${key}" is not a field`)).schema])),
|
|
518
|
+
/**
|
|
244
519
|
* The Selection of every member an input writes, with each relation as refs:
|
|
245
520
|
* what an edit screen loads before it shows the input's current values.
|
|
246
521
|
*/
|
|
@@ -309,6 +584,6 @@ const Relation = {
|
|
|
309
584
|
};
|
|
310
585
|
const Derived = { make: (schema) => ({ schema }) };
|
|
311
586
|
//#endregion
|
|
312
|
-
export { Derived, Entity, EntityTypeId, Relation, SelectionPageTypeId, SelectionTypeId };
|
|
587
|
+
export { Derived, Entity, EntityTypeId, Expr, Order, Query, Relation, SelectionPageTypeId, SelectionTypeId, dependenciesOf, isPredicate };
|
|
313
588
|
|
|
314
589
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-entity` — domain structure as typed values.\n *\n * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations\n * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable\n * values an interpreter supplies). It describes; it fetches, stores, and\n * renders nothing. Remote, Drizzle, and form packages interpret it and attach\n * what they need as `foldkit-metadata`.\n */\nimport { Pipeable, Schema } from 'effect'\nimport { Metadata } from 'foldkit-metadata'\n\nexport const EntityTypeId: unique symbol = Symbol.for('foldkit-entity/Entity')\nexport type EntityTypeId = typeof EntityTypeId\n\n/**\n * What makes two descriptors the same Entity. A pipe step returns a new\n * descriptor with the same identity, so compare `identity`, never the objects.\n */\nexport interface EntityIdentity<Name extends string> {\n readonly name: Name\n /** Distinguishes two Entities that were defined with the same name. */\n readonly token: symbol\n}\n\n/** An intrinsic value of the Entity: one property of `entity.schema`. */\nexport interface EntityField<Name extends string, Key extends string, S extends Schema.Constraint> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type Cardinality = 'one' | 'many'\n\n/** What `Relation.one` / `Relation.many` return, before `Entity.relate` binds it to an owner. */\nexport interface RelationSpec<\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly target: Target\n readonly cardinality: C\n readonly optional: Optional\n}\n\n/**\n * A navigation edge as its owner sees it: one or many of `target`. How the edge\n * is stored (a foreign key, a join table, a nested document) is the\n * interpreter's concern.\n */\nexport interface EntityRelation<\n Name extends string,\n Key extends string,\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly _tag: 'Relation'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n /** The target as `Entity.relate` returned it, so its own relations can be followed. */\n readonly target: () => Target\n readonly cardinality: C\n readonly optional: Optional\n readonly metadata: Metadata\n}\n\n/** What `Derived.make` returns, before an Entity owns it. */\nexport interface DerivedSpec<S extends Schema.Constraint> {\n readonly schema: S\n}\n\n/**\n * A value consumers may read that is not part of `entity.schema`. It says\n * nothing about how the value is computed; an interpreter supplies it.\n */\nexport interface EntityDerived<\n Name extends string,\n Key extends string,\n S extends Schema.Constraint,\n> {\n readonly _tag: 'Derived'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type EntityMember =\n | EntityField<string, string, Schema.Constraint>\n | EntityRelation<string, string, AnyEntity, Cardinality, boolean>\n | EntityDerived<string, string, Schema.Constraint>\n\nexport type RelationSpecs = Readonly<Record<string, RelationSpec<AnyEntity, Cardinality, boolean>>>\nexport type DerivedSpecs = Readonly<Record<string, DerivedSpec<Schema.Constraint>>>\n\ntype FieldsOf<Name extends string, Fields extends Schema.Struct.Fields> = {\n readonly [K in keyof Fields & string]: EntityField<Name, K, Fields[K]>\n}\ntype RelationsOf<Name extends string, Relations extends RelationSpecs> = {\n readonly [K in keyof Relations & string]: Relations[K] extends RelationSpec<\n infer Target,\n infer C,\n infer Optional\n >\n ? EntityRelation<Name, K, Target, C, Optional>\n : never\n}\ntype DerivedOf<Name extends string, Derived extends DerivedSpecs> = {\n readonly [K in keyof Derived & string]: EntityDerived<Name, K, Derived[K]['schema']>\n}\n\nexport interface Entity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n>\n extends Pipeable.Pipeable {\n readonly [EntityTypeId]: EntityTypeId\n readonly identity: EntityIdentity<Name>\n readonly name: Name\n /** The intrinsic value only: no relations, no derived members. */\n readonly schema: Schema.Struct<Fields>\n readonly fields: FieldsOf<Name, Fields>\n readonly relations: RelationsOf<Name, Relations>\n readonly derived: DerivedOf<Name, Derived>\n /** Every readable member under one namespace; keys never collide. */\n readonly members: FieldsOf<Name, Fields> & RelationsOf<Name, Relations> & DerivedOf<Name, Derived>\n readonly metadata: Metadata\n}\n\nexport type AnyEntity = Entity<string, any, any, any>\n\n/** Unsatisfiable when a new key is already a member, so the pipe step is the error site. */\ntype Free<E extends AnyEntity, New> = keyof New & keyof E['members'] extends never\n ? unknown\n : { readonly alreadyAMember: keyof New & keyof E['members'] }\n\ntype WithDerived<E, New extends DerivedSpecs> =\n E extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R, D & New>\n : never\n\nexport type Entities = Readonly<Record<string, AnyEntity>>\nexport type RelationMap<Es extends Entities> = { readonly [K in keyof Es]?: RelationSpecs }\n\n/** The key in `Es` of the Entity a spec targets, matched by name. */\nexport type TargetKey<Es extends Entities, Target extends AnyEntity> = {\n [K in keyof Es]: [Es[K]['name'], Target['name']] extends [Target['name'], Es[K]['name']]\n ? K\n : never\n}[keyof Es]\n\nexport type RelatedSpecs<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> = {\n readonly [R in keyof Rs[K]]: Rs[K][R] extends RelationSpec<infer Target, infer C, infer Optional>\n ? RelationSpec<Related<Es, Rs, TargetKey<Es, Target>>, C, Optional>\n : never\n}\n\n/**\n * One Entity of an `Entity.relate` result. A relation's target is again a\n * `Related`, so relations can be followed through a cycle; the recursion goes\n * through type arguments, which TypeScript resolves only when asked.\n */\nexport type Related<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> =\n Es[K] extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D>\n : never\n\n/** Marks a relation key that is already a member of its owner, or an owner that is not listed. */\ntype CheckRelations<Es extends Entities, Rs> = {\n readonly [K in keyof Rs]: K extends keyof Es\n ? {\n readonly [R in keyof Rs[K]]: R extends keyof Es[K]['members']\n ? `\"${R & string}\" is already a member of ${Es[K]['name']}`\n : Rs[K][R]\n }\n : 'not one of the entities being related'\n}\n\nexport const SelectionTypeId: unique symbol = Symbol.for('foldkit-entity/Selection')\nexport type SelectionTypeId = typeof SelectionTypeId\n\n/** What a relation selected with `true` yields: which Entity, and which one. */\nexport interface EntityRef<Name extends string = string> {\n readonly entity: Name\n readonly id: string\n}\n\ntype RefSchema<Name extends string> = Schema.Struct<{\n readonly entity: Schema.Literal<Name>\n readonly id: Schema.String\n}>\n\n/**\n * A view of the Entity graph: which members to read, and the schema of the\n * value that results. It says nothing about where the value comes from.\n */\nexport interface Selection<Name extends string, Members, S extends Schema.Constraint> {\n readonly [SelectionTypeId]: SelectionTypeId\n readonly entity: Entity<Name, any, any, any>\n /** What was selected, by member key: `true`, or a relation's nested Selection. */\n readonly members: Members\n readonly schema: S\n}\n\ntype AnySelection<Name extends string = string> = Selection<Name, any, any>\n\n/** `true` for any member; a relation also takes a Selection of its target. */\n/**\n * Which part of a `many` relation to read: the first or last so many, from a\n * cursor or from the end. A cursor is whatever the interpreter handed out with an\n * earlier page; nothing here looks inside it.\n */\nexport interface PageWindow {\n readonly first?: number | undefined\n readonly last?: number | undefined\n readonly after?: string | undefined\n readonly before?: string | undefined\n}\n\n/** One page of a `many` relation: the items read, and whether more lie on either side. */\nexport interface Page<Item> {\n readonly items: ReadonlyArray<Item>\n readonly hasNext: boolean\n readonly hasPrevious: boolean\n}\n\nexport const SelectionPageTypeId: unique symbol = Symbol.for('foldkit-entity/SelectionPage')\nexport type SelectionPageTypeId = typeof SelectionPageTypeId\n\n/** A Selection of a `many` relation's target, read a page at a time. */\nexport interface SelectionPage<Name extends string, S extends Schema.Constraint> {\n readonly [SelectionPageTypeId]: SelectionPageTypeId\n readonly selection: Selection<Name, any, S>\n readonly window: PageWindow\n}\n\ntype PageSchema<S extends Schema.Constraint> = Schema.Struct<{\n readonly items: Schema.$Array<S>\n readonly hasNext: Schema.Boolean\n readonly hasPrevious: Schema.Boolean\n}>\n\ntype SelectionSpec<E extends AnyEntity, Spec> = {\n readonly [K in keyof Spec]: K extends keyof E['relations']\n ? E['relations'][K] extends EntityRelation<any, any, infer Target, infer C, any>\n ? | true\n | AnySelection<Target['name']>\n // Only a `many` relation has pages.\n | (C extends 'many' ? SelectionPage<Target['name'], any> : never)\n : never\n : K extends keyof E['members']\n ? true\n : `\"${K & string}\" is not a member of ${E['name']}`\n}\n\ntype RelationShape<\n C extends Cardinality,\n Optional extends boolean,\n S extends Schema.Constraint,\n> = C extends 'many' ? Schema.$Array<S> : Optional extends true ? Schema.NullOr<S> : S\n\ntype SelectedSchema<Member, Selected> = Member extends\n EntityField<any, any, infer S> | EntityDerived<any, any, infer S>\n ? S\n : Member extends EntityRelation<any, any, infer Target, infer C, infer Optional>\n ? Selected extends SelectionPage<any, infer S>\n ? PageSchema<S>\n : RelationShape<\n C,\n Optional,\n Selected extends Selection<any, any, infer S> ? S : RefSchema<Target['name']>\n >\n : never\n\ntype SelectionSchema<E extends AnyEntity, Spec> = Schema.Struct<{\n readonly [K in keyof Spec & keyof E['members']]: SelectedSchema<E['members'][K], Spec[K]>\n}>\n\nconst isSelectionPage = (value: unknown): value is SelectionPage<string, Schema.Constraint> =>\n typeof value === 'object' && value !== null && SelectionPageTypeId in value\n\nconst isSelection = (value: unknown): value is AnySelection =>\n typeof value === 'object' && value !== null && SelectionTypeId in value\n\n/** An input key that carries a relation's target: the id of a `one`, the ids of a `many`. */\nexport interface RelationInput<R extends EntityRelation<any, any, any, any, any>> {\n readonly _tag: 'RelationInput'\n readonly relation: R\n}\n\n/**\n * An input key that carries the relation's target itself, written through an\n * input of its own: a post created with a new author, an order with its lines.\n * A `one` holds that input's value, a `many` a list of them.\n */\nexport interface NestedInput<\n R extends EntityRelation<any, any, any, any, any>,\n I extends EntityInput<any, any, any>,\n> {\n readonly _tag: 'NestedInput'\n readonly relation: R\n readonly input: I\n}\n\n/** An input key that is about the operation, not the Entity: a reason, a flag, a confirmation. */\nexport interface Unmapped {\n readonly _tag: 'Unmapped'\n}\n\n/** What one key of an operation's input means in terms of the Entity. */\nexport type InputMember =\n | EntityField<string, string, Schema.Constraint>\n | RelationInput<EntityRelation<string, string, AnyEntity, Cardinality, boolean>>\n | NestedInput<\n EntityRelation<string, string, AnyEntity, Cardinality, boolean>,\n EntityInput<AnyEntity, any, any>\n >\n | Unmapped\n\n/** The ids a relation takes as input: one id, a nullable id, or a list of ids. */\ntype RelationIds<R> =\n R extends EntityRelation<any, any, any, infer C, infer Optional>\n ? C extends 'many'\n ? ReadonlyArray<string>\n : Optional extends true\n ? string | null\n : string\n : never\n\n/** What a nested input takes: the value of the target's input, or a list of them for a `many`. */\ntype NestedValues<R, I> =\n I extends EntityInput<any, infer Fields, any>\n ? R extends EntityRelation<any, any, any, 'many', any>\n ? ReadonlyArray<Schema.Struct.Type<Fields>>\n : Schema.Struct.Type<Fields>\n : never\n\n/**\n * Only the value that is present has to fit: an input may leave a key out (a\n * partial update) or send `null` to clear it. Whether it may is the input\n * schema's rule; the fit only guards against mapping the wrong member.\n */\ntype Present<T> = Exclude<T, null | undefined>\n\ntype MappingFor<Name extends string, Input, M> = M extends Unmapped\n ? M\n : M extends\n | EntityField<infer Owner, any, any>\n | RelationInput<EntityRelation<infer Owner, any, any, any, any>>\n | NestedInput<EntityRelation<infer Owner, any, any, any, any>, any>\n ? [Owner] extends [Name]\n ? M extends EntityField<any, any, infer S>\n ? Present<Input> extends Schema.Schema.Type<S>\n ? M\n : 'the input value does not fit this field'\n : M extends RelationInput<infer R>\n ? Present<Input> extends RelationIds<R>\n ? M\n : 'the input value is not the id shape of this relation'\n : M extends NestedInput<infer R, infer I>\n ? R extends EntityRelation<any, any, infer Target, any, any>\n ? I extends EntityInput<infer Of, any, any>\n ? [Of['name']] extends [Target['name']]\n ? Present<Input> extends NestedValues<R, I>\n ? M\n : 'the input value is not the value of the nested input'\n : `the nested input is of ${Of['name']}, not ${Target['name']}`\n : never\n : never\n : never\n : `this member belongs to ${Owner}`\n : 'map an input key to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped'\n\n/** A key that names a field whose value it fits maps itself; every other key needs an entry. */\ntype SelfMapped<E extends AnyEntity, Fields extends Schema.Struct.Fields> = {\n [K in keyof Fields]: K extends keyof E['fields']\n ? Present<Schema.Schema.Type<Fields[K]>> extends Schema.Schema.Type<E['fields'][K]['schema']>\n ? K\n : never\n : never\n}[keyof Fields]\n\ntype InputMapping<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = {\n readonly [K in Exclude<keyof Fields, SelfMapped<E, Fields>>]: unknown\n} & {\n readonly [K in keyof Mapping]: K extends keyof Fields\n ? MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Mapping[K]>\n : `\"${K & string}\" is not a key of the input`\n}\n\ntype InputMembers<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = {\n readonly [K in keyof Fields]: K extends keyof Mapping\n ? Mapping[K]\n : K extends keyof E['fields']\n ? E['fields'][K]\n : never\n}\n\n/**\n * An operation's input read against an Entity: which member each input key\n * writes. The operation decides what may be submitted; the Entity only says\n * what each submitted key means.\n */\nexport interface EntityInput<E extends AnyEntity, Fields extends Schema.Struct.Fields, Members> {\n readonly entity: E\n readonly schema: Schema.Struct<Fields>\n readonly members: Members\n}\n\n/** The Entity member an input key writes, by its key; nothing for an unmapped key. */\nexport type WrittenKey<M> =\n M extends EntityField<any, infer Key, any>\n ? Key\n : M extends\n | RelationInput<EntityRelation<any, infer Key, any, any, any>>\n | NestedInput<EntityRelation<any, infer Key, any, any, any>, any>\n ? Key\n : never\n\n/** A nested input reads what it writes of the target; every other member reads as it is. */\nexport type WrittenAs<M> =\n M extends NestedInput<any, EntityInput<infer Of, any, infer Members>>\n ? Selection<Of['name'], WrittenSpec<Members>, SelectionSchema<Of, WrittenSpec<Members>>>\n : true\n\n/** Every member the input writes: what to read to show the input's current values. */\nexport type WrittenSpec<Members> = {\n readonly [K in keyof Members as WrittenKey<Members[K]>]: WrittenAs<Members[K]>\n}\n\nconst unmapped: Unmapped = Object.freeze({ _tag: 'Unmapped' })\n\ninterface Parts {\n readonly identity: EntityIdentity<string>\n readonly schema: Schema.Struct<Schema.Struct.Fields>\n readonly fields: Readonly<Record<string, EntityMember>>\n readonly relations: Readonly<Record<string, EntityMember>>\n readonly derived: Readonly<Record<string, EntityMember>>\n readonly metadata: Metadata\n}\n\nconst EntityProto = {\n [EntityTypeId]: EntityTypeId,\n pipe() {\n return Pipeable.pipeArguments(this, arguments)\n },\n}\n\nconst make = (parts: Parts): AnyEntity =>\n Object.freeze(\n Object.assign(Object.create(EntityProto), parts, {\n name: parts.identity.name,\n fields: Object.freeze(parts.fields),\n relations: Object.freeze(parts.relations),\n derived: Object.freeze(parts.derived),\n members: Object.freeze({ ...parts.fields, ...parts.relations, ...parts.derived }),\n }),\n )\n\nconst isSameEntity = (left: AnyEntity, right: AnyEntity): boolean =>\n left.identity.token === right.identity.token\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`Entity \"${entity.name}\": ${message}`)\n}\n\nconst isEntity = (value: unknown): value is AnyEntity =>\n typeof value === 'object' && value !== null && EntityTypeId in value\n\nconst kindName = { Field: 'field', Relation: 'relation', Derived: 'derived member' } as const\n\nconst kindOf = (entity: AnyEntity, key: string): string | undefined => {\n const member = (entity.members as Readonly<Record<string, EntityMember>>)[key]\n return member && kindName[member._tag]\n}\n\nconst assertFree = (entity: AnyEntity, keys: ReadonlyArray<string>, adding: string): void => {\n for (const key of keys) {\n const kind = kindOf(entity, key)\n if (kind !== undefined)\n throw new Error(\n `Entity \"${entity.name}\": cannot add ${adding} \"${key}\", it is already a ${kind}`,\n )\n }\n}\n\nconst mapValues = <A, B>(\n record: Readonly<Record<string, A>>,\n f: (value: A, key: string) => B,\n): Record<string, B> =>\n Object.fromEntries(Object.entries(record).map(([key, value]) => [key, f(value, key)]))\n\nexport const Entity = {\n /** Declares an Entity from its intrinsic fields. Each call is a new identity. */\n define: <const Name extends string, Fields extends Schema.Struct.Fields>(\n name: Name,\n schema: Schema.Struct<Fields>,\n ): Entity<Name, Fields> => {\n const identity: EntityIdentity<Name> = Object.freeze({ name, token: Symbol(name) })\n return make({\n identity,\n schema,\n fields: mapValues(schema.fields, (fieldSchema, key) =>\n Object.freeze({\n _tag: 'Field',\n owner: identity,\n key,\n schema: fieldSchema,\n metadata: Metadata.empty,\n }),\n ),\n relations: {},\n derived: {},\n metadata: Metadata.empty,\n }) as Entity<Name, Fields>\n },\n\n /**\n * Declares the relations between a set of Entities in one step, and returns\n * them related. One step, because Entities that point at each other cannot\n * each be declared in terms of the other.\n */\n relate: <const Es extends Entities, const Rs extends RelationMap<Es>>(\n entities: Es,\n relations: Rs & CheckRelations<Es, Rs>,\n ): { readonly [K in keyof Es]: Related<Es, Rs, K> } => {\n const keyByToken = new Map<symbol, string>()\n for (const [key, entity] of Object.entries(entities)) {\n if (!isEntity(entity)) throw new Error(`Entity.relate: \"${key}\" is not an Entity`)\n const earlier = keyByToken.get(entity.identity.token)\n if (earlier !== undefined)\n throw new Error(`Entity.relate: \"${earlier}\" and \"${key}\" are the same Entity`)\n keyByToken.set(entity.identity.token, key)\n }\n const given: Readonly<Record<string, RelationSpecs | undefined>> = relations\n for (const owner of Object.keys(given))\n if (!(owner in entities))\n throw new Error(`Entity.relate: relations given for \"${owner}\", which is not being related`)\n\n const related: Record<string, AnyEntity> = {}\n for (const [ownerKey, entity] of Object.entries(entities)) {\n const specs = given[ownerKey] ?? {}\n assertFree(entity, Object.keys(specs), 'relation')\n const added = mapValues<RelationSpec<AnyEntity, Cardinality, boolean>, EntityMember>(\n specs,\n (spec, key) => {\n const targetKey = isEntity(spec.target)\n ? keyByToken.get(spec.target.identity.token)\n : undefined\n if (targetKey === undefined)\n throw new Error(\n `Entity \"${entity.name}\": relation \"${key}\" targets an Entity that is not being related`,\n )\n return Object.freeze({\n _tag: 'Relation',\n owner: entity.identity,\n key,\n // Read on call: the target may come later in `entities` than its owner.\n target: () => related[targetKey]!,\n cardinality: spec.cardinality,\n optional: spec.optional,\n metadata: Metadata.empty,\n })\n },\n )\n related[ownerKey] = make({ ...entity, relations: { ...entity.relations, ...added } })\n }\n return Object.freeze(related) as never\n },\n\n /**\n * Selects members of an Entity and assembles the schema of the result. A\n * relation selected with `true` yields an `EntityRef`; with a Selection of its\n * target, that Selection's value. `many` yields an array, an optional `one`\n * is nullable.\n */\n select: <E extends AnyEntity, const Spec>(\n entity: E,\n spec: Spec & SelectionSpec<E, Spec>,\n ): Selection<E['name'], Spec, SelectionSchema<E, Spec>> => {\n const members: Readonly<Record<string, EntityMember>> = entity.members\n const fields = mapValues<unknown, Schema.Constraint>(spec, (selected, key) => {\n const member = members[key]\n if (member === undefined)\n throw new Error(`Entity \"${entity.name}\": cannot select \"${key}\", it is not a member`)\n if (member._tag !== 'Relation') {\n if (selected !== true)\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" is a ${kindName[member._tag]}, select it with true`,\n )\n return member.schema\n }\n const target = member.target()\n if (isSelectionPage(selected)) {\n if (member.cardinality !== 'many')\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" is one ${target.name}, so it has no pages`,\n )\n if (!isSameEntity(selected.selection.entity, target))\n throw new Error(`Entity \"${entity.name}\": \"${key}\" pages a Selection of ${target.name}`)\n return Schema.Struct({\n items: Schema.Array(selected.selection.schema as Schema.Top),\n hasNext: Schema.Boolean,\n hasPrevious: Schema.Boolean,\n })\n }\n let item: Schema.Top\n if (selected === true)\n item = Schema.Struct({ entity: Schema.Literal(target.name), id: Schema.String })\n else if (isSelection(selected) && isSameEntity(selected.entity, target))\n item = selected.schema\n else\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" takes true or a Selection of ${target.name}`,\n )\n return member.cardinality === 'many'\n ? Schema.Array(item)\n : member.optional\n ? Schema.NullOr(item)\n : item\n })\n return Object.freeze({\n [SelectionTypeId]: SelectionTypeId,\n entity,\n members: spec,\n schema: Schema.Struct(fields),\n }) as never\n },\n\n /**\n * A `many` relation read a page at a time, in place of its Selection:\n * `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a `Page`\n * of the Selection's values. Reading on from a cursor is another window.\n */\n page: <Name extends string, S extends Schema.Constraint>(\n selection: Selection<Name, any, S>,\n window: PageWindow,\n ): SelectionPage<Name, S> => {\n const sides = [window.first, window.last].filter(size => size !== undefined)\n if (sides.length !== 1 || !sides.every(size => Number.isInteger(size) && size >= 0))\n throw new Error(\n `Entity.page: a window of ${selection.entity.name} takes first or last, a non-negative integer`,\n )\n if (\n (window.first !== undefined && window.before !== undefined) ||\n (window.last !== undefined && window.after !== undefined)\n )\n throw new Error(\n `Entity.page: a window of ${selection.entity.name} reads first after a cursor, or last before one`,\n )\n const page: SelectionPage<Name, S> = {\n [SelectionPageTypeId]: SelectionPageTypeId,\n selection,\n window,\n }\n return Object.freeze(page)\n },\n\n /** Adds readable members that are not part of `entity.schema`. */\n derived:\n <const New extends DerivedSpecs>(specs: New) =>\n <E extends AnyEntity>(entity: E & Free<E, New>): WithDerived<E, New> => {\n assertFree(entity, Object.keys(specs), 'derived member')\n const added = mapValues<DerivedSpec<Schema.Constraint>, EntityMember>(specs, (spec, key) =>\n Object.freeze({\n _tag: 'Derived',\n owner: entity.identity,\n key,\n schema: spec.schema,\n metadata: Metadata.empty,\n }),\n )\n return make({ ...entity, derived: { ...entity.derived, ...added } }) as never\n },\n\n /** Attaches an interpreter's metadata to the Entity itself. */\n annotate:\n (metadata: Metadata) =>\n <E extends AnyEntity>(entity: E): E =>\n make({ ...entity, metadata: Metadata.combine([entity.metadata, metadata]) }) as E,\n\n /** Attaches an interpreter's metadata to members, by key. */\n annotateMembers:\n <E extends AnyEntity>(metadata: { readonly [K in keyof E['members']]?: Metadata }) =>\n (entity: E): E => {\n const given = metadata as Readonly<Record<string, Metadata | undefined>>\n for (const key of Object.keys(given))\n if (kindOf(entity, key) === undefined)\n throw new Error(`Entity \"${entity.name}\": cannot annotate \"${key}\", it is not a member`)\n const annotate = (members: Readonly<Record<string, EntityMember>>) =>\n mapValues(members, (member, key) => {\n const extra = given[key]\n return extra === undefined\n ? member\n : Object.freeze({ ...member, metadata: Metadata.combine([member.metadata, extra]) })\n })\n return make({\n ...entity,\n fields: annotate(entity.fields),\n relations: annotate(entity.relations),\n derived: annotate(entity.derived),\n }) as E\n },\n\n /**\n * Reads an operation's input schema against an Entity. A key that names a\n * field maps to it; any other key is mapped explicitly, to a Field, to\n * `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred\n * from a naming convention such as `authorId`.\n */\n input: <\n E extends AnyEntity,\n Fields extends Schema.Struct.Fields,\n // `{}` when every key maps itself, so the argument can be omitted.\n const Mapping = {},\n >(\n entity: E,\n schema: Schema.Struct<Fields>,\n ...mapping: keyof InputMapping<E, Fields, Mapping> extends never\n ? [mapping?: Mapping & InputMapping<E, Fields, Mapping>]\n : [mapping: Mapping & InputMapping<E, Fields, Mapping>]\n ): EntityInput<E, Fields, InputMembers<E, Fields, Mapping>> => {\n const given: Readonly<Record<string, InputMember | undefined>> = mapping[0] ?? {}\n for (const key of Object.keys(given))\n if (!(key in schema.fields))\n throw new Error(`Entity \"${entity.name}\": \"${key}\" is mapped but is not a key of the input`)\n const fields: Readonly<Record<string, InputMember | undefined>> = entity.fields\n const members = mapValues(schema.fields, (_, key) => {\n const member =\n given[key] ??\n fields[key] ??\n fail(entity, `input key \"${key}\" names no field; map it to a member or Entity.unmapped`)\n const owned =\n member._tag === 'Field'\n ? member\n : member._tag === 'RelationInput' || member._tag === 'NestedInput'\n ? member.relation\n : member._tag === 'Unmapped'\n ? undefined\n : fail(\n entity,\n `input key \"${key}\" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`,\n )\n if (owned !== undefined && owned.owner.token !== entity.identity.token)\n fail(entity, `input key \"${key}\" is mapped to a member of \"${owned.owner.name}\"`)\n if (\n member._tag === 'NestedInput' &&\n !isSameEntity(member.input.entity, member.relation.target())\n )\n fail(\n entity,\n `input key \"${key}\" nests an input of \"${member.input.entity.name}\", but \"${member.relation.key}\" is of \"${member.relation.target().name}\"`,\n )\n return member\n })\n return Object.freeze({ entity, schema, members: Object.freeze(members) }) as never\n },\n\n /** For an input key that is about the operation rather than the Entity. */\n unmapped,\n\n /**\n * The Selection of every member an input writes, with each relation as refs:\n * what an edit screen loads before it shows the input's current values.\n */\n selectFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n ): Selection<E['name'], WrittenSpec<Members>, SelectionSchema<E, WrittenSpec<Members>>> => {\n const members: Readonly<Record<string, InputMember>> = input.members as never\n const spec = Object.fromEntries(\n Object.values(members).flatMap((member): ReadonlyArray<readonly [string, unknown]> =>\n member._tag === 'Field'\n ? [[member.key, true]]\n : member._tag === 'RelationInput'\n ? [[member.relation.key, true]]\n : member._tag === 'NestedInput'\n ? // What the nested input writes of the target, so its keys can be shown too.\n [[member.relation.key, Entity.selectFor(member.input)]]\n : [],\n ),\n )\n return Entity.select(input.entity, spec as never) as never\n },\n\n /**\n * The input values that reproduce `value`, a value read through `selectFor`\n * (or any Selection with those members): a field as it is, a relation as the\n * id or ids of its refs. A key whose member `value` lacks is left out, as is\n * an unmapped key, which the Entity knows nothing about.\n */\n valuesFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n value: Readonly<Record<string, unknown>>,\n ): Partial<Schema.Struct.Type<Fields>> => {\n const members: Readonly<Record<string, InputMember>> = input.members as never\n // The id of a ref or of a nested Selection's value; `undefined` when it has none.\n const idOf = (held: unknown): unknown =>\n held === null\n ? null\n : typeof held === 'object' && 'id' in held\n ? held.id\n : typeof held === 'string'\n ? held\n : undefined\n const entries = Object.entries(members).flatMap(([key, member]) => {\n if (member._tag === 'Unmapped') return []\n const written = member._tag === 'Field' ? member.key : member.relation.key\n if (!(written in value)) return []\n const read = value[written]\n if (member._tag === 'Field') return [[key, read] as const]\n if (member._tag === 'NestedInput') {\n const nested = (held: unknown): unknown =>\n typeof held === 'object' && held !== null\n ? Entity.valuesFor(member.input, held as Readonly<Record<string, unknown>>)\n : null\n return [[key, Array.isArray(read) ? read.map(nested) : nested(read)] as const]\n }\n const ids = Array.isArray(read) ? read.map(idOf) : idOf(read)\n // A relation read without its ids (a nested Selection that left `id` out) fills nothing.\n const known = Array.isArray(ids) ? !ids.includes(undefined) : ids !== undefined\n return known ? [[key, ids] as const] : []\n })\n return Object.fromEntries(entries) as Partial<Schema.Struct.Type<Fields>>\n },\n\n is: isEntity,\n\n /** True when both descriptors are versions of one Entity. */\n same: isSameEntity,\n}\n\nfunction one<Target extends AnyEntity>(target: Target): RelationSpec<Target, 'one', false>\nfunction one<Target extends AnyEntity, const Optional extends boolean>(\n target: Target,\n options: { readonly optional: Optional },\n): RelationSpec<Target, 'one', Optional>\nfunction one(\n target: AnyEntity,\n options?: { readonly optional: boolean },\n): RelationSpec<AnyEntity, 'one', boolean> {\n return { target, cardinality: 'one', optional: options?.optional ?? false }\n}\n\n/** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */\nexport const Relation = {\n one,\n\n /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */\n input: <R extends EntityRelation<any, any, any, any, any>>(relation: R): RelationInput<R> =>\n Object.freeze({ _tag: 'RelationInput', relation }),\n\n /**\n * For `Entity.input`: the input key holds the relation's target itself, written\n * through `input`, an `Entity.input` of the target. A `many` holds a list.\n */\n nested: <R extends EntityRelation<any, any, any, any, any>, I extends EntityInput<any, any, any>>(\n relation: R,\n input: I,\n ): NestedInput<R, I> => Object.freeze({ _tag: 'NestedInput', relation, input }),\n\n many: <Target extends AnyEntity>(target: Target): RelationSpec<Target, 'many', false> => ({\n target,\n cardinality: 'many',\n optional: false,\n }),\n}\n\nexport const Derived = {\n make: <S extends Schema.Constraint>(schema: S): DerivedSpec<S> => ({ schema }),\n}\n"],"mappings":";;;;;;;;;;;;AAYA,MAAa,eAA8B,OAAO,IAAI,uBAAuB;AA2K7E,MAAa,kBAAiC,OAAO,IAAI,0BAA0B;AAgDnF,MAAa,sBAAqC,OAAO,IAAI,8BAA8B;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O,CAAC;GACjC,MAAM,OAAO,MAAM;GACnB,IAAI,OAAO,SAAS,SAAS,OAAO,CAAC,CAAC,KAAK,IAAI,CAAU;GACzD,IAAI,OAAO,SAAS,eAAe;IACjC,MAAM,UAAU,SACd,OAAO,SAAS,YAAY,SAAS,OACjC,OAAO,UAAU,OAAO,OAAO,IAAyC,IACxE;IACN,OAAO,CAAC,CAAC,KAAK,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,MAAM,IAAI,OAAO,IAAI,CAAC,CAAU;GAC/E;GACA,MAAM,MAAM,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI;GAG5D,QADc,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,SAAS,KAAA,CAAS,IAAI,QAAQ,KAAA,KACvD,CAAC,CAAC,KAAK,GAAG,CAAU,IAAI,CAAC;EAC1C,CAAC;EACD,OAAO,OAAO,YAAY,OAAO;CACnC;CAEA,IAAI;;CAGJ,MAAM;AACR;AAOA,SAAS,IACP,QACA,SACyC;CACzC,OAAO;EAAE;EAAQ,aAAa;EAAO,UAAU,SAAS,YAAY;CAAM;AAC5E;;AAGA,MAAa,WAAW;CACtB;;CAGA,QAA2D,aACzD,OAAO,OAAO;EAAE,MAAM;EAAiB;CAAS,CAAC;;;;;CAMnD,SACE,UACA,UACsB,OAAO,OAAO;EAAE,MAAM;EAAe;EAAU;CAAM,CAAC;CAE9E,OAAiC,YAAyD;EACxF;EACA,aAAa;EACb,UAAU;CACZ;AACF;AAEA,MAAa,UAAU,EACrB,OAAoC,YAA+B,EAAE,OAAO,GAC9E"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/expr.ts","../src/index.ts"],"sourcesContent":["/**\n * `Expr` — a query's scalar computations as typed values.\n *\n * An Entity says what a domain has; an `Expr` says something about one row of\n * it. A field reference, an input placeholder, a literal, and comparisons of\n * those are all immutable data: building one performs no work, reads nothing,\n * and names no database. An interpreter compiles it — `foldkit-remote-drizzle`\n * to SQL, an in-memory evaluator to a predicate over rows.\n *\n * This is deliberately not SQL and deliberately not arbitrary JavaScript. Every\n * operation here is one a real query in this repository needs; the set grows\n * from queries, not from what a database could express.\n */\nimport { Pipeable, Schema } from 'effect'\nimport type { AnyEntity, EntityField, EntityIdentity } from './index.js'\n\n/** A constant the query was written with. */\nexport interface LiteralExpr<T> {\n readonly _tag: 'Literal'\n readonly value: T\n}\n\n/**\n * One field of one Entity. `owner` is the Entity's identity rather than its\n * name, so two Entities defined with the same name are not one column.\n */\nexport interface FieldExpr<T> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<string>\n readonly key: string\n readonly schema: Schema.Codec<T, unknown>\n}\n\n/**\n * A value the query is given when it runs. A definition's body is built once,\n * so inside it an input is this placeholder and never the value: there is\n * nothing yet to branch on, and a query that wants to depend on what was passed\n * says so with an operation over the placeholder.\n */\nexport interface InputExpr<T> {\n readonly _tag: 'Input'\n readonly key: string\n readonly schema: Schema.Codec<T, unknown>\n}\n\n/** A typed scalar: what a comparison compares. */\nexport type Expr<T> = LiteralExpr<T> | FieldExpr<T> | InputExpr<T>\n\n/** Any scalar, for the places that hold operands without caring what they are. */\nexport type AnyExpr = Expr<unknown>\n\n/**\n * `Expr<boolean>`, in the shape the operations that exist can actually take.\n * The design's kernel is all boolean-valued (`eq`, `and`, `isNull`,\n * `contains`, …), so a predicate is its own type rather than a phantom\n * parameter on a general operation node: `Predicate` and `Expr<string>` cannot\n * then be confused, which a structural phantom would allow. A scalar-valued\n * operation, if one is ever needed, joins `Expr` instead.\n */\nexport type Predicate = EqPredicate | NullPredicate | ContainsPredicate\n\n/** Two values are the same. */\nexport interface EqPredicate {\n readonly _tag: 'Eq'\n readonly left: Operandish\n readonly right: Operandish\n}\n\n/**\n * Whether a value is absent. `present` says which answer absence gives, so one\n * node covers `is null` and `is not null` rather than two that differ by a\n * negation nothing else can express.\n */\nexport interface NullPredicate {\n readonly _tag: 'Null'\n readonly operand: AnyExpr\n readonly present: boolean\n}\n\n/**\n * Whether a text value contains another. Containing the empty string is\n * everything, which is what lets a search box with nothing typed in it be the\n * same query as one with something — see `Expr.contains`.\n */\nexport interface ContainsPredicate {\n readonly _tag: 'Contains'\n readonly value: AnyExpr\n readonly search: Operandish\n}\n\n/**\n * Anything an operation can be given: a scalar, or a predicate where a boolean\n * is wanted. `Expr.eq(Expr.isNotNull(archivedAt), input.archived)` is the\n * second case, and it is how a query depends on an input without branching on\n * it.\n */\nexport type Operandish = AnyExpr | Predicate\n\n/** A field, a scalar already built from one, or a predicate used as a boolean. */\ntype Operand<T> = EntityField<string, string, Schema.Constraint> | Expr<T> | Predicate\n\n/** What an operand is worth, so a comparison's other side is checked against it. */\nexport type ValueOf<E> =\n E extends EntityField<string, string, infer S>\n ? Schema.Schema.Type<S>\n : E extends Predicate\n ? boolean\n : E extends Expr<infer T>\n ? T\n : never\n\nconst tagOf = (value: unknown): unknown =>\n typeof value === 'object' && value !== null\n ? (value as { readonly _tag?: unknown })._tag\n : undefined\n\n/**\n * An Entity's field and a `FieldExpr` are the same three members under the same\n * tag — the Entity's carries `metadata` besides — so this reads either and is\n * idempotent on its own output. Nothing needs to tell them apart, which is\n * better than telling them apart by which extra member happens to be present.\n */\nconst literal = <T>(value: T): LiteralExpr<T> => ({ _tag: 'Literal', value })\n\nconst fieldExpr = (field: EntityField<string, string, Schema.Constraint>): FieldExpr<unknown> => ({\n _tag: 'Field',\n owner: field.owner,\n key: field.key,\n schema: field.schema as unknown as Schema.Codec<unknown, unknown>,\n})\n\nconst predicateTags = new Set(['Eq', 'Null', 'Contains'])\n\n/** Whether a value is a predicate, and so usable where a boolean is wanted. */\nexport const isPredicate = (value: unknown): value is Predicate =>\n predicateTags.has(tagOf(value) as string)\n\n/**\n * A field of either kind becomes a `FieldExpr`, a scalar or a predicate is\n * itself, and anything else is the constant it is.\n */\nconst toOperand = <T>(value: Operand<T> | T): Operandish => {\n const tag = tagOf(value)\n if (tag === 'Field') {\n return fieldExpr(value as EntityField<string, string, Schema.Constraint>)\n }\n if (tag === 'Literal' || tag === 'Input' || predicateTags.has(tag as string)) {\n return value as Operandish\n }\n return literal(value)\n}\n\n/** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */\nconst toExpr = <T>(value: Operand<T> | T, step: string): AnyExpr => {\n const operand = toOperand(value)\n if (isPredicate(operand)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: a predicate is already an answer, so asking this of one is not a question`,\n )\n }\n return operand\n}\n\n/** Which fields and inputs an expression reads, and which operations it uses. */\nexport interface Dependencies {\n /** One entry per distinct field, as `Entity.key`. */\n readonly fields: ReadonlyArray<{ readonly entity: string; readonly key: string }>\n /** One entry per distinct input key. */\n readonly inputs: ReadonlyArray<string>\n /** One entry per distinct operation, so an interpreter can refuse what it cannot run. */\n readonly operations: ReadonlyArray<string>\n}\n\nexport const Expr = {\n /** A constant. Comparisons coerce a plain value, so this is rarely written. */\n literal,\n\n /**\n * A value the query is given when it runs. A definition builds these from its\n * `Input` schema; written by hand only when constructing a body directly.\n */\n input: <T>(key: string, schema: Schema.Codec<T, unknown>): InputExpr<T> => ({\n _tag: 'Input',\n key,\n schema,\n }),\n\n /** One field of one Entity, as a scalar. */\n field: <Name extends string, Key extends string, S extends Schema.Constraint>(\n field: EntityField<Name, Key, S>,\n ): FieldExpr<Schema.Schema.Type<S>> => fieldExpr(field) as FieldExpr<Schema.Schema.Type<S>>,\n\n /**\n * Two scalars are the same value. A field or a plain value on either side is\n * coerced, so the common form reads as it means:\n *\n * ```ts\n * Expr.eq(Post.fields.slug, input.slug)\n * Expr.eq(Post.fields.status, 'active')\n * ```\n */\n eq: <L extends Operand<any>>(\n left: L,\n right: ValueOf<L> | Expr<ValueOf<L>> | (boolean extends ValueOf<L> ? Predicate : never),\n ): EqPredicate => ({\n _tag: 'Eq',\n left: toOperand(left),\n right: toOperand(right as never),\n }),\n\n /**\n * Whether a field holds no value. Its opposite is `isNotNull`; both are the\n * one node, because a query asks which of the two it means and nothing here\n * can negate a predicate.\n */\n isNull: <L extends Operand<any>>(operand: L): NullPredicate => ({\n _tag: 'Null',\n operand: toExpr(operand, 'isNull'),\n present: false,\n }),\n\n /** Whether a field holds a value. */\n isNotNull: <L extends Operand<any>>(operand: L): NullPredicate => ({\n _tag: 'Null',\n operand: toExpr(operand, 'isNotNull'),\n present: true,\n }),\n\n /**\n * Whether a text value contains `search`, anywhere in it. Containing the\n * empty string is everything, so a search box with nothing typed in it is the\n * same query as one with something — no branch, and no second query.\n *\n * **Case-insensitive**, which is what a search means, and which has to be\n * said rather than left to the interpreter: SQLite's `like` ignores case and\n * Postgres's does not, so a body that left it open would mean two things.\n * Folding is ASCII-only, because that is what `lower` does in SQLite without\n * ICU.\n *\n * **Over a column that can be null this is not the same as no filter.** A\n * null contains nothing, not even the empty string, so its rows drop out. A\n * nullable column that should match everything on an empty search says so:\n * `Expr.or` does not exist yet, so for now such a column needs its own\n * predicate or a native escape hatch.\n */\n contains: <L extends Operand<any>>(\n value: L,\n search: string | Expr<string>,\n ): ContainsPredicate => ({\n _tag: 'Contains',\n value: toExpr(value, 'contains'),\n search: toOperand(search as never),\n }),\n}\n\n/** One term of an ordering: a scalar and the direction to read it in. */\nexport interface OrderTerm {\n readonly direction: 'asc' | 'desc'\n readonly expr: AnyExpr\n}\n\nexport const Order = {\n asc: <E extends Operand<any>>(expr: E): OrderTerm => ({\n direction: 'asc',\n expr: toExpr(expr as never, 'asc'),\n }),\n desc: <E extends Operand<any>>(expr: E): OrderTerm => ({\n direction: 'desc',\n expr: toExpr(expr as never, 'desc'),\n }),\n}\n\nconst walk = (\n node: AnyExpr | Predicate,\n fields: Map<string, { readonly entity: string; readonly key: string }>,\n inputs: Set<string>,\n operations: Set<string>,\n): void => {\n switch (node._tag) {\n case 'Literal':\n return\n case 'Field':\n fields.set(`${node.owner.name}.${node.key}`, { entity: node.owner.name, key: node.key })\n return\n case 'Input':\n inputs.add(node.key)\n return\n case 'Eq':\n operations.add('eq')\n walk(node.left, fields, inputs, operations)\n walk(node.right, fields, inputs, operations)\n return\n case 'Null':\n operations.add(node.present ? 'isNotNull' : 'isNull')\n walk(node.operand, fields, inputs, operations)\n return\n case 'Contains':\n operations.add('contains')\n walk(node.value, fields, inputs, operations)\n walk(node.search, fields, inputs, operations)\n return\n }\n}\n\n/**\n * What an expression reads and uses, for the planner and for an interpreter\n * deciding whether it can run this query at all. Distinct entries only, in the\n * order first seen, so the answer is stable enough to assert on.\n */\nexport const dependenciesOf = (\n ...nodes: ReadonlyArray<AnyExpr | Predicate | OrderTerm>\n): Dependencies => {\n const fields = new Map<string, { readonly entity: string; readonly key: string }>()\n const inputs = new Set<string>()\n const operations = new Set<string>()\n for (const node of nodes) {\n walk('direction' in node ? node.expr : node, fields, inputs, operations)\n }\n return { fields: [...fields.values()], inputs: [...inputs], operations: [...operations] }\n}\n\n/**\n * Which rows a query is about, as a value: an Entity to read, the predicates\n * every row must satisfy, and the order to read them in. It says nothing about\n * which fields to return — that is a Selection — and nothing about pagination,\n * liveness, or whether absence is an error, which belong to the consumer's read\n * rather than to the relation.\n *\n * Composing one performs no work. `Query.from(Post)` names no table and opens\n * no connection; an interpreter turns the value into a query when something\n * asks it to.\n */\nexport interface Query<E extends AnyEntity> extends Pipeable.Pipeable {\n readonly _tag: 'Query'\n readonly entity: E\n /**\n * Every predicate holds: the list *is* the conjunction. Keeping it a list\n * rather than folding it into one `and` is what makes each `where` a reusable\n * fragment, and it means no `Expr.and` exists until a query needs a\n * conjunction nested inside something else.\n */\n readonly where: ReadonlyArray<Predicate>\n /** In order of significance; a later `orderBy` appends less significant terms. */\n readonly orderBy: ReadonlyArray<OrderTerm>\n}\n\n/** A `Query` over any Entity, for the places that hold one without caring which. */\nexport type AnyQuery = Query<AnyEntity>\n\n/** Every field an expression reads, as the nodes themselves. */\nconst fieldsIn = function* (node: AnyExpr | Predicate): Generator<FieldExpr<unknown>> {\n switch (node._tag) {\n case 'Field':\n yield node\n return\n case 'Literal':\n case 'Input':\n return\n case 'Eq':\n yield* fieldsIn(node.left)\n yield* fieldsIn(node.right)\n return\n case 'Null':\n yield* fieldsIn(node.operand)\n return\n case 'Contains':\n yield* fieldsIn(node.value)\n yield* fieldsIn(node.search)\n return\n }\n}\n\n/**\n * A query reads one Entity, so a predicate or ordering term naming a different\n * one cannot be answered — an interpreter would be asked for a column of a\n * table it was never told to read. Compared by identity, not by name, because\n * two Entities defined with the same name are two Entities.\n */\nconst checkOwnership = (\n step: string,\n what: string,\n entity: AnyEntity,\n nodes: ReadonlyArray<AnyExpr | Predicate | OrderTerm>,\n): void => {\n for (const node of nodes) {\n for (const field of fieldsIn('direction' in node ? node.expr : node)) {\n if (field.owner.token !== entity.identity.token) {\n throw new Error(\n `[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}`,\n )\n }\n }\n }\n}\n\nconst QueryProto = {\n _tag: 'Query' as const,\n pipe() {\n return Pipeable.pipeArguments(this, arguments)\n },\n}\n\nconst query = <E extends AnyEntity>(\n entity: E,\n where: ReadonlyArray<Predicate>,\n orderBy: ReadonlyArray<OrderTerm>,\n): Query<E> =>\n Object.freeze(\n Object.assign(Object.create(QueryProto), {\n entity,\n where: Object.freeze(where),\n orderBy: Object.freeze(orderBy),\n }),\n ) as Query<E>\n\nexport const Query = {\n /** Every row of an Entity: the query each transformation narrows. */\n from: <E extends AnyEntity>(entity: E): Query<E> => query(entity, [], []),\n\n /**\n * Narrows to the rows the predicate holds for. Two `where`s conjoin — the\n * second never replaces the first — so a fragment can be written once and\n * piped into any query over the same Entity:\n *\n * ```ts\n * const published = Query.where(Expr.eq(Post.fields.published, true))\n * Query.from(Post).pipe(published, Query.where(byTitle))\n * ```\n */\n where:\n (...predicates: ReadonlyArray<Predicate>) =>\n <E extends AnyEntity>(self: Query<E>): Query<E> => {\n if (predicates.length === 0) return self\n checkOwnership('where', 'a predicate', self.entity, predicates)\n return query(self.entity, [...self.where, ...predicates], self.orderBy)\n },\n\n /**\n * Reads the rows in this order. Two `orderBy`s append, so an earlier term\n * stays the more significant one and a later call adds a tie-breaker rather\n * than silently winning.\n */\n orderBy:\n (...terms: ReadonlyArray<OrderTerm>) =>\n <E extends AnyEntity>(self: Query<E>): Query<E> => {\n if (terms.length === 0) return self\n checkOwnership('orderBy', 'a term', self.entity, terms)\n return query(self.entity, self.where, [...self.orderBy, ...terms])\n },\n\n /**\n * What the whole query reads: the fields and inputs of every predicate and\n * every ordering term, and the operations it uses.\n */\n dependencies: (self: AnyQuery): Dependencies => dependenciesOf(...self.where, ...self.orderBy),\n}\n","/**\n * `foldkit-entity` — domain structure as typed values.\n *\n * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations\n * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable\n * values an interpreter supplies). It describes; it fetches, stores, and\n * renders nothing. Remote, Drizzle, and form packages interpret it and attach\n * what they need as `foldkit-metadata`.\n */\nimport { Pipeable, Schema } from 'effect'\nimport { Metadata } from 'foldkit-metadata'\n\nexport const EntityTypeId: unique symbol = Symbol.for('foldkit-entity/Entity')\nexport type EntityTypeId = typeof EntityTypeId\n\n/**\n * What makes two descriptors the same Entity. A pipe step returns a new\n * descriptor with the same identity, so compare `identity`, never the objects.\n */\nexport interface EntityIdentity<Name extends string> {\n readonly name: Name\n /** Distinguishes two Entities that were defined with the same name. */\n readonly token: symbol\n}\n\n/** An intrinsic value of the Entity: one property of `entity.schema`. */\nexport interface EntityField<Name extends string, Key extends string, S extends Schema.Constraint> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type Cardinality = 'one' | 'many'\n\n/** What `Relation.one` / `Relation.many` return, before `Entity.relate` binds it to an owner. */\nexport interface RelationSpec<\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly target: Target\n readonly cardinality: C\n readonly optional: Optional\n}\n\n/**\n * A navigation edge as its owner sees it: one or many of `target`. How the edge\n * is stored (a foreign key, a join table, a nested document) is the\n * interpreter's concern.\n */\nexport interface EntityRelation<\n Name extends string,\n Key extends string,\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly _tag: 'Relation'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n /** The target as `Entity.relate` returned it, so its own relations can be followed. */\n readonly target: () => Target\n readonly cardinality: C\n readonly optional: Optional\n readonly metadata: Metadata\n}\n\n/** What `Derived.make` returns, before an Entity owns it. */\nexport interface DerivedSpec<S extends Schema.Constraint> {\n readonly schema: S\n}\n\n/**\n * A value consumers may read that is not part of `entity.schema`. It says\n * nothing about how the value is computed; an interpreter supplies it.\n */\nexport interface EntityDerived<\n Name extends string,\n Key extends string,\n S extends Schema.Constraint,\n> {\n readonly _tag: 'Derived'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type EntityMember =\n | EntityField<string, string, Schema.Constraint>\n | EntityRelation<string, string, AnyEntity, Cardinality, boolean>\n | EntityDerived<string, string, Schema.Constraint>\n\nexport type RelationSpecs = Readonly<Record<string, RelationSpec<AnyEntity, Cardinality, boolean>>>\nexport type DerivedSpecs = Readonly<Record<string, DerivedSpec<Schema.Constraint>>>\n\ntype FieldsOf<Name extends string, Fields extends Schema.Struct.Fields> = {\n readonly [K in keyof Fields & string]: EntityField<Name, K, Fields[K]>\n}\ntype RelationsOf<Name extends string, Relations extends RelationSpecs> = {\n readonly [K in keyof Relations & string]: Relations[K] extends RelationSpec<\n infer Target,\n infer C,\n infer Optional\n >\n ? EntityRelation<Name, K, Target, C, Optional>\n : never\n}\ntype DerivedOf<Name extends string, Derived extends DerivedSpecs> = {\n readonly [K in keyof Derived & string]: EntityDerived<Name, K, Derived[K]['schema']>\n}\n\nexport interface Entity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n>\n extends Pipeable.Pipeable {\n readonly [EntityTypeId]: EntityTypeId\n readonly identity: EntityIdentity<Name>\n readonly name: Name\n /** The intrinsic value only: no relations, no derived members. */\n readonly schema: Schema.Struct<Fields>\n readonly fields: FieldsOf<Name, Fields>\n readonly relations: RelationsOf<Name, Relations>\n readonly derived: DerivedOf<Name, Derived>\n /** Every readable member under one namespace; keys never collide. */\n readonly members: FieldsOf<Name, Fields> & RelationsOf<Name, Relations> & DerivedOf<Name, Derived>\n readonly metadata: Metadata\n}\n\nexport type AnyEntity = Entity<string, any, any, any>\n\n/** Unsatisfiable when a new key is already a member, so the pipe step is the error site. */\ntype Free<E extends AnyEntity, New> = keyof New & keyof E['members'] extends never\n ? unknown\n : { readonly alreadyAMember: keyof New & keyof E['members'] }\n\ntype WithDerived<E, New extends DerivedSpecs> =\n E extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R, D & New>\n : never\n\nexport type Entities = Readonly<Record<string, AnyEntity>>\nexport type RelationMap<Es extends Entities> = { readonly [K in keyof Es]?: RelationSpecs }\n\n/** The key in `Es` of the Entity a spec targets, matched by name. */\nexport type TargetKey<Es extends Entities, Target extends AnyEntity> = {\n [K in keyof Es]: [Es[K]['name'], Target['name']] extends [Target['name'], Es[K]['name']]\n ? K\n : never\n}[keyof Es]\n\nexport type RelatedSpecs<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> = {\n readonly [R in keyof Rs[K]]: Rs[K][R] extends RelationSpec<infer Target, infer C, infer Optional>\n ? RelationSpec<Related<Es, Rs, TargetKey<Es, Target>>, C, Optional>\n : never\n}\n\n/**\n * One Entity of an `Entity.relate` result. A relation's target is again a\n * `Related`, so relations can be followed through a cycle; the recursion goes\n * through type arguments, which TypeScript resolves only when asked.\n */\nexport type Related<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> =\n Es[K] extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D>\n : never\n\n/** Marks a relation key that is already a member of its owner, or an owner that is not listed. */\ntype CheckRelations<Es extends Entities, Rs> = {\n readonly [K in keyof Rs]: K extends keyof Es\n ? {\n readonly [R in keyof Rs[K]]: R extends keyof Es[K]['members']\n ? `\"${R & string}\" is already a member of ${Es[K]['name']}`\n : Rs[K][R]\n }\n : 'not one of the entities being related'\n}\n\nexport const SelectionTypeId: unique symbol = Symbol.for('foldkit-entity/Selection')\nexport type SelectionTypeId = typeof SelectionTypeId\n\n/**\n * The schema that identifies one of an Entity: its `id` field when that is text\n * (a plain string, a brand, a pattern), and plain text otherwise. An id is text\n * because a ref travels and is stored as text; an Entity keyed by a number still\n * has refs, and their ids are the number as text.\n */\nexport type IdSchemaOf<E> = E extends {\n readonly fields: { readonly id: { readonly schema: infer S } }\n}\n ? S extends Schema.Constraint\n ? [S['Type']] extends [string]\n ? S\n : Schema.String\n : Schema.String\n : Schema.String\n\n/** What identifies one of an Entity: `IdOf<typeof Blog.Post>` is `PostId` when its `id` field is one. */\nexport type IdOf<E> = IdSchemaOf<E>['Type']\n\n/**\n * What a relation selected with `true` yields: which Entity, and which one. `Id`\n * is the target's own id type, so a ref to an Author cannot be used as a Post's.\n */\nexport interface EntityRef<Name extends string = string, Id extends string = string> {\n readonly entity: Name\n readonly id: Id\n}\n\ntype RefSchema<Target extends AnyEntity> = Schema.Struct<{\n readonly entity: Schema.Literal<Target['name']>\n readonly id: IdSchemaOf<Target>\n}>\n\n/**\n * A view of the Entity graph: which members to read, and the schema of the\n * value that results. It says nothing about where the value comes from.\n */\nexport interface Selection<\n Name extends string,\n Members,\n S extends Schema.Constraint,\n Id extends string = string,\n> {\n readonly [SelectionTypeId]: SelectionTypeId\n /** Type-only: the id type of the Entity selected, so a reader can ask for the right one. Never set. */\n readonly Id?: Id\n readonly entity: Entity<Name, any, any, any>\n /** What was selected, by member key: `true`, or a relation's nested Selection. */\n readonly members: Members\n readonly schema: S\n}\n\ntype AnySelection<Name extends string = string> = Selection<Name, any, any>\n\n/** `true` for any member; a relation also takes a Selection of its target. */\n/**\n * Which part of a `many` relation to read: the first or last so many, from a\n * cursor or from the end. A cursor is whatever the interpreter handed out with an\n * earlier page; nothing here looks inside it.\n */\nexport interface PageWindow {\n readonly first?: number | undefined\n readonly last?: number | undefined\n readonly after?: string | undefined\n readonly before?: string | undefined\n}\n\nexport const SelectionPageTypeId: unique symbol = Symbol.for('foldkit-entity/SelectionPage')\nexport type SelectionPageTypeId = typeof SelectionPageTypeId\n\n/** A Selection of a `many` relation's target, read a page at a time. */\nexport interface SelectionPage<Name extends string, S extends Schema.Constraint> {\n readonly [SelectionPageTypeId]: SelectionPageTypeId\n readonly selection: Selection<Name, any, S>\n readonly window: PageWindow\n}\n\ntype PageSchema<S extends Schema.Constraint> = Schema.Struct<{\n readonly items: Schema.$Array<S>\n readonly hasNext: Schema.Boolean\n readonly hasPrevious: Schema.Boolean\n}>\n\ntype SelectionSpec<E extends AnyEntity, Spec> = {\n readonly [K in keyof Spec]: K extends keyof E['relations']\n ? E['relations'][K] extends EntityRelation<any, any, infer Target, infer C, any>\n ? | true\n | AnySelection<Target['name']>\n // Only a `many` relation has pages.\n | (C extends 'many' ? SelectionPage<Target['name'], any> : never)\n : never\n : K extends keyof E['members']\n ? true\n : `\"${K & string}\" is not a member of ${E['name']}`\n}\n\ntype RelationShape<\n C extends Cardinality,\n Optional extends boolean,\n S extends Schema.Constraint,\n> = C extends 'many' ? Schema.$Array<S> : Optional extends true ? Schema.NullOr<S> : S\n\ntype SelectedSchema<Member, Selected> = Member extends\n EntityField<any, any, infer S> | EntityDerived<any, any, infer S>\n ? S\n : Member extends EntityRelation<any, any, infer Target, infer C, infer Optional>\n ? Selected extends SelectionPage<any, infer S>\n ? PageSchema<S>\n : RelationShape<\n C,\n Optional,\n Selected extends Selection<any, any, infer S> ? S : RefSchema<Target>\n >\n : never\n\ntype SelectionSchema<E extends AnyEntity, Spec> = Schema.Struct<{\n readonly [K in keyof Spec & keyof E['members']]: SelectedSchema<E['members'][K], Spec[K]>\n}>\n\ninterface AstLike {\n readonly _tag: string\n readonly literal?: unknown\n readonly types?: ReadonlyArray<AstLike>\n}\n\nconst isText = (ast: AstLike): boolean =>\n ast._tag === 'String' ||\n ast._tag === 'TemplateLiteral' ||\n (ast._tag === 'Literal' && typeof ast.literal === 'string') ||\n (ast._tag === 'Union' && (ast.types ?? []).length > 0 && (ast.types ?? []).every(isText))\n\n/** The `id` field's schema when it is text, so a ref's id keeps its brand and its checks; else text. */\nconst idSchemaOf = (entity: AnyEntity): Schema.Top => {\n const fields: Readonly<Record<string, EntityMember | undefined>> = entity.fields\n const id = fields.id\n if (id === undefined || id._tag !== 'Field') return Schema.String\n const type = Schema.toType(id.schema as Schema.Top)\n return isText(type.ast as unknown as AstLike) ? type : Schema.String\n}\n\nconst isSelectionPage = (value: unknown): value is SelectionPage<string, Schema.Constraint> =>\n typeof value === 'object' && value !== null && SelectionPageTypeId in value\n\nconst isSelection = (value: unknown): value is AnySelection =>\n typeof value === 'object' && value !== null && SelectionTypeId in value\n\n/** An input key that carries a relation's target: the id of a `one`, the ids of a `many`. */\nexport interface RelationInput<R extends EntityRelation<any, any, any, any, any>> {\n readonly _tag: 'RelationInput'\n readonly relation: R\n}\n\n/**\n * An input key that carries the relation's target itself, written through an\n * input of its own: a post created with a new author, an order with its lines.\n * A `one` holds that input's value, a `many` a list of them.\n */\nexport interface NestedInput<\n R extends EntityRelation<any, any, any, any, any>,\n I extends EntityInput<any, any, any>,\n> {\n readonly _tag: 'NestedInput'\n readonly relation: R\n readonly input: I\n}\n\n/** An input key that is about the operation, not the Entity: a reason, a flag, a confirmation. */\nexport interface Unmapped {\n readonly _tag: 'Unmapped'\n}\n\n/** What one key of an operation's input means in terms of the Entity. */\nexport type InputMember =\n | EntityField<string, string, Schema.Constraint>\n | RelationInput<EntityRelation<string, string, AnyEntity, Cardinality, boolean>>\n | NestedInput<\n EntityRelation<string, string, AnyEntity, Cardinality, boolean>,\n EntityInput<AnyEntity, any, any>\n >\n | Unmapped\n\n/** The ids a relation takes as input: one id, a nullable id, or a list of ids. */\ntype RelationIds<R> =\n R extends EntityRelation<any, any, infer Target, infer C, infer Optional>\n ? C extends 'many'\n ? ReadonlyArray<IdOf<Target>>\n : Optional extends true\n ? IdOf<Target> | null\n : IdOf<Target>\n : never\n\n/** What a nested input takes: the value of the target's input, or a list of them for a `many`. */\ntype NestedValues<R, I> =\n I extends EntityInput<any, infer Fields, any>\n ? R extends EntityRelation<any, any, any, 'many', any>\n ? ReadonlyArray<Schema.Struct.Type<Fields>>\n : Schema.Struct.Type<Fields>\n : never\n\n/**\n * Only the value that is present has to fit: an input may leave a key out (a\n * partial update) or send `null` to clear it. Whether it may is the input\n * schema's rule; the fit only guards against mapping the wrong member.\n */\ntype Present<T> = Exclude<T, null | undefined>\n\ntype MappingFor<Name extends string, Input, M> = M extends Unmapped\n ? M\n : M extends\n | EntityField<infer Owner, any, any>\n | RelationInput<EntityRelation<infer Owner, any, any, any, any>>\n | NestedInput<EntityRelation<infer Owner, any, any, any, any>, any>\n ? [Owner] extends [Name]\n ? M extends EntityField<any, any, infer S>\n ? Present<Input> extends Schema.Schema.Type<S>\n ? M\n : 'the input value does not fit this field'\n : M extends RelationInput<infer R>\n ? Present<Input> extends RelationIds<R>\n ? M\n : 'the input value is not the id shape of this relation'\n : M extends NestedInput<infer R, infer I>\n ? R extends EntityRelation<any, any, infer Target, any, any>\n ? I extends EntityInput<infer Of, any, any>\n ? [Of['name']] extends [Target['name']]\n ? Present<Input> extends NestedValues<R, I>\n ? M\n : 'the input value is not the value of the nested input'\n : `the nested input is of ${Of['name']}, not ${Target['name']}`\n : never\n : never\n : never\n : `this member belongs to ${Owner}`\n : 'map an input key to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped'\n\n/** A key that names a field whose value it fits maps itself; every other key needs an entry. */\ntype SelfMapped<E extends AnyEntity, Fields extends Schema.Struct.Fields> = {\n [K in keyof Fields]: K extends keyof E['fields']\n ? Present<Schema.Schema.Type<Fields[K]>> extends Schema.Schema.Type<E['fields'][K]['schema']>\n ? K\n : never\n : never\n}[keyof Fields]\n\n/**\n * A mapping written as a member's key: `'title'` is that Field, and `'author'` is\n * `Relation.input` of that relation. Nothing is inferred from the input key's own\n * name; the member is still named, only more briefly.\n */\ntype Named<E extends AnyEntity, M> = M extends string\n ? M extends keyof E['fields']\n ? E['fields'][M]\n : M extends keyof E['relations']\n ? RelationInput<E['relations'][M]>\n : `\"${M}\" names no field or relation of ${E['name']}`\n : M\n\ntype InputMapping<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = {\n readonly [K in Exclude<keyof Fields, SelfMapped<E, Fields>>]: unknown\n} & {\n readonly [K in keyof Mapping]: K extends keyof Fields\n ? Named<E, Mapping[K]> extends infer Member\n ? Member extends string\n ? Member\n : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member> extends Member\n ? Mapping[K]\n : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member>\n : never\n : `\"${K & string}\" is not a key of the input`\n}\n\ntype InputMembers<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = {\n readonly [K in keyof Fields]: K extends keyof Mapping\n ? Named<E, Mapping[K]>\n : K extends keyof E['fields']\n ? E['fields'][K]\n : never\n}\n\n/**\n * An operation's input read against an Entity: which member each input key\n * writes. The operation decides what may be submitted; the Entity only says\n * what each submitted key means.\n */\nexport interface EntityInput<E extends AnyEntity, Fields extends Schema.Struct.Fields, Members> {\n readonly entity: E\n readonly schema: Schema.Struct<Fields>\n readonly members: Members\n}\n\n/** The Entity member an input key writes, by its key; nothing for an unmapped key. */\nexport type WrittenKey<M> =\n M extends EntityField<any, infer Key, any>\n ? Key\n : M extends\n | RelationInput<EntityRelation<any, infer Key, any, any, any>>\n | NestedInput<EntityRelation<any, infer Key, any, any, any>, any>\n ? Key\n : never\n\n/** A nested input reads what it writes of the target; every other member reads as it is. */\nexport type WrittenAs<M> =\n M extends NestedInput<any, EntityInput<infer Of, any, infer Members>>\n ? Selection<Of['name'], WrittenSpec<Members>, SelectionSchema<Of, WrittenSpec<Members>>>\n : true\n\n/** Every member the input writes: what to read to show the input's current values. */\nexport type WrittenSpec<Members> = {\n readonly [K in keyof Members as WrittenKey<Members[K]>]: WrittenAs<Members[K]>\n}\n\nconst unmapped: Unmapped = Object.freeze({ _tag: 'Unmapped' })\n\ninterface Parts {\n readonly identity: EntityIdentity<string>\n readonly schema: Schema.Struct<Schema.Struct.Fields>\n readonly fields: Readonly<Record<string, EntityMember>>\n readonly relations: Readonly<Record<string, EntityMember>>\n readonly derived: Readonly<Record<string, EntityMember>>\n readonly metadata: Metadata\n}\n\nconst EntityProto = {\n [EntityTypeId]: EntityTypeId,\n pipe() {\n return Pipeable.pipeArguments(this, arguments)\n },\n}\n\nconst make = (parts: Parts): AnyEntity =>\n Object.freeze(\n Object.assign(Object.create(EntityProto), parts, {\n name: parts.identity.name,\n fields: Object.freeze(parts.fields),\n relations: Object.freeze(parts.relations),\n derived: Object.freeze(parts.derived),\n members: Object.freeze({ ...parts.fields, ...parts.relations, ...parts.derived }),\n }),\n )\n\nconst isSameEntity = (left: AnyEntity, right: AnyEntity): boolean =>\n left.identity.token === right.identity.token\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`Entity \"${entity.name}\": ${message}`)\n}\n\nconst isEntity = (value: unknown): value is AnyEntity =>\n typeof value === 'object' && value !== null && EntityTypeId in value\n\nconst kindName = { Field: 'field', Relation: 'relation', Derived: 'derived member' } as const\n\nconst kindOf = (entity: AnyEntity, key: string): string | undefined => {\n const member = (entity.members as Readonly<Record<string, EntityMember>>)[key]\n return member && kindName[member._tag]\n}\n\nconst assertFree = (entity: AnyEntity, keys: ReadonlyArray<string>, adding: string): void => {\n for (const key of keys) {\n const kind = kindOf(entity, key)\n if (kind !== undefined)\n throw new Error(\n `Entity \"${entity.name}\": cannot add ${adding} \"${key}\", it is already a ${kind}`,\n )\n }\n}\n\nconst mapValues = <A, B>(\n record: Readonly<Record<string, A>>,\n f: (value: A, key: string) => B,\n): Record<string, B> =>\n Object.fromEntries(Object.entries(record).map(([key, value]) => [key, f(value, key)]))\n\nexport const Entity = {\n /** Declares an Entity from its intrinsic fields. Each call is a new identity. */\n define: <const Name extends string, Fields extends Schema.Struct.Fields>(\n name: Name,\n schema: Schema.Struct<Fields>,\n ): Entity<Name, Fields> => {\n const identity: EntityIdentity<Name> = Object.freeze({ name, token: Symbol(name) })\n return make({\n identity,\n schema,\n fields: mapValues(schema.fields, (fieldSchema, key) =>\n Object.freeze({\n _tag: 'Field',\n owner: identity,\n key,\n schema: fieldSchema,\n metadata: Metadata.empty,\n }),\n ),\n relations: {},\n derived: {},\n metadata: Metadata.empty,\n }) as Entity<Name, Fields>\n },\n\n /**\n * Declares the relations between a set of Entities in one step, and returns\n * them related. One step, because Entities that point at each other cannot\n * each be declared in terms of the other.\n */\n relate: <const Es extends Entities, const Rs extends RelationMap<Es>>(\n entities: Es,\n relations: Rs & CheckRelations<Es, Rs>,\n ): { readonly [K in keyof Es]: Related<Es, Rs, K> } => {\n const keyByToken = new Map<symbol, string>()\n for (const [key, entity] of Object.entries(entities)) {\n if (!isEntity(entity)) throw new Error(`Entity.relate: \"${key}\" is not an Entity`)\n const earlier = keyByToken.get(entity.identity.token)\n if (earlier !== undefined)\n throw new Error(`Entity.relate: \"${earlier}\" and \"${key}\" are the same Entity`)\n keyByToken.set(entity.identity.token, key)\n }\n const given: Readonly<Record<string, RelationSpecs | undefined>> = relations\n for (const owner of Object.keys(given))\n if (!(owner in entities))\n throw new Error(`Entity.relate: relations given for \"${owner}\", which is not being related`)\n\n const related: Record<string, AnyEntity> = {}\n for (const [ownerKey, entity] of Object.entries(entities)) {\n const specs = given[ownerKey] ?? {}\n assertFree(entity, Object.keys(specs), 'relation')\n const added = mapValues<RelationSpec<AnyEntity, Cardinality, boolean>, EntityMember>(\n specs,\n (spec, key) => {\n const targetKey = isEntity(spec.target)\n ? keyByToken.get(spec.target.identity.token)\n : undefined\n if (targetKey === undefined)\n throw new Error(\n `Entity \"${entity.name}\": relation \"${key}\" targets an Entity that is not being related`,\n )\n return Object.freeze({\n _tag: 'Relation',\n owner: entity.identity,\n key,\n // Read on call: the target may come later in `entities` than its owner.\n target: () => related[targetKey]!,\n cardinality: spec.cardinality,\n optional: spec.optional,\n metadata: Metadata.empty,\n })\n },\n )\n related[ownerKey] = make({ ...entity, relations: { ...entity.relations, ...added } })\n }\n return Object.freeze(related) as never\n },\n\n /**\n * Selects members of an Entity and assembles the schema of the result. A\n * relation selected with `true` yields an `EntityRef`; with a Selection of its\n * target, that Selection's value. `many` yields an array, an optional `one`\n * is nullable.\n */\n select: <E extends AnyEntity, const Spec>(\n entity: E,\n spec: Spec & SelectionSpec<E, Spec>,\n ): Selection<E['name'], Spec, SelectionSchema<E, Spec>, IdOf<E>> => {\n const members: Readonly<Record<string, EntityMember>> = entity.members\n const fields = mapValues<unknown, Schema.Constraint>(spec, (selected, key) => {\n const member = members[key]\n if (member === undefined)\n throw new Error(`Entity \"${entity.name}\": cannot select \"${key}\", it is not a member`)\n if (member._tag !== 'Relation') {\n if (selected !== true)\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" is a ${kindName[member._tag]}, select it with true`,\n )\n return member.schema\n }\n const target = member.target()\n if (isSelectionPage(selected)) {\n if (member.cardinality !== 'many')\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" is one ${target.name}, so it has no pages`,\n )\n if (!isSameEntity(selected.selection.entity, target))\n throw new Error(`Entity \"${entity.name}\": \"${key}\" pages a Selection of ${target.name}`)\n return Schema.Struct({\n items: Schema.Array(selected.selection.schema as Schema.Top),\n hasNext: Schema.Boolean,\n hasPrevious: Schema.Boolean,\n })\n }\n let item: Schema.Top\n if (selected === true)\n item = Schema.Struct({ entity: Schema.Literal(target.name), id: idSchemaOf(target) })\n else if (isSelection(selected) && isSameEntity(selected.entity, target))\n item = selected.schema\n else\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" takes true or a Selection of ${target.name}`,\n )\n return member.cardinality === 'many'\n ? Schema.Array(item)\n : member.optional\n ? Schema.NullOr(item)\n : item\n })\n return Object.freeze({\n [SelectionTypeId]: SelectionTypeId,\n entity,\n members: spec,\n schema: Schema.Struct(fields),\n }) as never\n },\n\n /**\n * A `many` relation read a page at a time, in place of its Selection:\n * `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page\n * of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.\n */\n page: <Name extends string, S extends Schema.Constraint>(\n selection: Selection<Name, any, S>,\n window: PageWindow,\n ): SelectionPage<Name, S> => {\n const sides = [window.first, window.last].filter(size => size !== undefined)\n if (sides.length !== 1 || !sides.every(size => Number.isInteger(size) && size >= 0))\n throw new Error(\n `Entity.page: a window of ${selection.entity.name} takes first or last, a non-negative integer`,\n )\n if (\n (window.first !== undefined && window.before !== undefined) ||\n (window.last !== undefined && window.after !== undefined)\n )\n throw new Error(\n `Entity.page: a window of ${selection.entity.name} reads first after a cursor, or last before one`,\n )\n const page: SelectionPage<Name, S> = {\n [SelectionPageTypeId]: SelectionPageTypeId,\n selection,\n window,\n }\n return Object.freeze(page)\n },\n\n /** Adds readable members that are not part of `entity.schema`. */\n derived:\n <const New extends DerivedSpecs>(specs: New) =>\n <E extends AnyEntity>(entity: E & Free<E, New>): WithDerived<E, New> => {\n assertFree(entity, Object.keys(specs), 'derived member')\n const added = mapValues<DerivedSpec<Schema.Constraint>, EntityMember>(specs, (spec, key) =>\n Object.freeze({\n _tag: 'Derived',\n owner: entity.identity,\n key,\n schema: spec.schema,\n metadata: Metadata.empty,\n }),\n )\n return make({ ...entity, derived: { ...entity.derived, ...added } }) as never\n },\n\n /** Attaches an interpreter's metadata to the Entity itself. */\n annotate:\n (metadata: Metadata) =>\n <E extends AnyEntity>(entity: E): E =>\n make({ ...entity, metadata: Metadata.combine([entity.metadata, metadata]) }) as E,\n\n /** Attaches an interpreter's metadata to members, by key. */\n annotateMembers:\n <E extends AnyEntity>(metadata: { readonly [K in keyof E['members']]?: Metadata }) =>\n (entity: E): E => {\n const given = metadata as Readonly<Record<string, Metadata | undefined>>\n for (const key of Object.keys(given))\n if (kindOf(entity, key) === undefined)\n throw new Error(`Entity \"${entity.name}\": cannot annotate \"${key}\", it is not a member`)\n const annotate = (members: Readonly<Record<string, EntityMember>>) =>\n mapValues(members, (member, key) => {\n const extra = given[key]\n return extra === undefined\n ? member\n : Object.freeze({ ...member, metadata: Metadata.combine([member.metadata, extra]) })\n })\n return make({\n ...entity,\n fields: annotate(entity.fields),\n relations: annotate(entity.relations),\n derived: annotate(entity.derived),\n }) as E\n },\n\n /**\n * Reads an operation's input schema against an Entity. A key that names a\n * field maps to it; any other key is mapped explicitly, to a Field, to\n * `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred\n * from a naming convention such as `authorId`.\n */\n input: <\n E extends AnyEntity,\n Fields extends Schema.Struct.Fields,\n // `{}` when every key maps itself, so the argument can be omitted.\n const Mapping = {},\n >(\n entity: E,\n schema: Schema.Struct<Fields>,\n ...mapping: keyof InputMapping<E, Fields, Mapping> extends never\n ? [mapping?: Mapping & InputMapping<E, Fields, Mapping>]\n : [mapping: Mapping & InputMapping<E, Fields, Mapping>]\n ): EntityInput<E, Fields, InputMembers<E, Fields, Mapping>> => {\n const written: Readonly<Record<string, InputMember | string | undefined>> = mapping[0] ?? {}\n for (const key of Object.keys(written))\n if (!(key in schema.fields))\n throw new Error(`Entity \"${entity.name}\": \"${key}\" is mapped but is not a key of the input`)\n // A member named by its key: a Field as it is, a relation as its ids.\n const named = (key: string, name: string): InputMember => {\n const member = (entity.members as Readonly<Record<string, EntityMember | undefined>>)[name]\n if (member?._tag === 'Field') return member\n if (member?._tag === 'Relation')\n return Object.freeze({ _tag: 'RelationInput', relation: member })\n return fail(\n entity,\n `input key \"${key}\" is mapped to \"${name}\", which names no field or relation`,\n )\n }\n const given: Readonly<Record<string, InputMember | undefined>> = mapValues(\n written,\n (member, key) => (typeof member === 'string' ? named(key, member) : member),\n )\n const fields: Readonly<Record<string, InputMember | undefined>> = entity.fields\n const members = mapValues(schema.fields, (_, key) => {\n const member =\n given[key] ??\n fields[key] ??\n fail(entity, `input key \"${key}\" names no field; map it to a member or Entity.unmapped`)\n const owned =\n member._tag === 'Field'\n ? member\n : member._tag === 'RelationInput' || member._tag === 'NestedInput'\n ? member.relation\n : member._tag === 'Unmapped'\n ? undefined\n : fail(\n entity,\n `input key \"${key}\" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`,\n )\n if (owned !== undefined && owned.owner.token !== entity.identity.token)\n fail(entity, `input key \"${key}\" is mapped to a member of \"${owned.owner.name}\"`)\n if (\n member._tag === 'NestedInput' &&\n !isSameEntity(member.input.entity, member.relation.target())\n )\n fail(\n entity,\n `input key \"${key}\" nests an input of \"${member.input.entity.name}\", but \"${member.relation.key}\" is of \"${member.relation.target().name}\"`,\n )\n return member\n })\n return Object.freeze({ entity, schema, members: Object.freeze(members) }) as never\n },\n\n /** For an input key that is about the operation rather than the Entity. */\n unmapped,\n\n /**\n * The schemas of some of an Entity's fields, by key, to spread into an input's\n * struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.\n * The input then keeps the field's own rules, and its keys map themselves.\n */\n fields: <E extends AnyEntity, const Keys extends ReadonlyArray<keyof E['fields'] & string>>(\n entity: E,\n ...keys: Keys\n ): { readonly [K in Keys[number]]: E['fields'][K]['schema'] } =>\n Object.fromEntries(\n keys.map(key => [\n key,\n (\n (\n entity.fields as Readonly<\n Record<string, EntityField<string, string, Schema.Constraint> | undefined>\n >\n )[key] ?? fail(entity, `\"${key}\" is not a field`)\n ).schema,\n ]),\n ) as never,\n\n /**\n * The Selection of every member an input writes, with each relation as refs:\n * what an edit screen loads before it shows the input's current values.\n */\n selectFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n ): Selection<\n E['name'],\n WrittenSpec<Members>,\n SelectionSchema<E, WrittenSpec<Members>>,\n IdOf<E>\n > => {\n const members: Readonly<Record<string, InputMember>> = input.members as never\n const spec = Object.fromEntries(\n Object.values(members).flatMap((member): ReadonlyArray<readonly [string, unknown]> =>\n member._tag === 'Field'\n ? [[member.key, true]]\n : member._tag === 'RelationInput'\n ? [[member.relation.key, true]]\n : member._tag === 'NestedInput'\n ? // What the nested input writes of the target, so its keys can be shown too.\n [[member.relation.key, Entity.selectFor(member.input)]]\n : [],\n ),\n )\n return Entity.select(input.entity, spec as never) as never\n },\n\n /**\n * The input values that reproduce `value`, a value read through `selectFor`\n * (or any Selection with those members): a field as it is, a relation as the\n * id or ids of its refs. A key whose member `value` lacks is left out, as is\n * an unmapped key, which the Entity knows nothing about.\n */\n valuesFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n value: Readonly<Record<string, unknown>>,\n ): Partial<Schema.Struct.Type<Fields>> => {\n const members: Readonly<Record<string, InputMember>> = input.members as never\n // The id of a ref or of a nested Selection's value; `undefined` when it has none.\n const idOf = (held: unknown): unknown =>\n held === null\n ? null\n : typeof held === 'object' && 'id' in held\n ? held.id\n : typeof held === 'string'\n ? held\n : undefined\n const entries = Object.entries(members).flatMap(([key, member]) => {\n if (member._tag === 'Unmapped') return []\n const written = member._tag === 'Field' ? member.key : member.relation.key\n if (!(written in value)) return []\n const read = value[written]\n if (member._tag === 'Field') return [[key, read] as const]\n if (member._tag === 'NestedInput') {\n const nested = (held: unknown): unknown =>\n typeof held === 'object' && held !== null\n ? Entity.valuesFor(member.input, held as Readonly<Record<string, unknown>>)\n : null\n return [[key, Array.isArray(read) ? read.map(nested) : nested(read)] as const]\n }\n const ids = Array.isArray(read) ? read.map(idOf) : idOf(read)\n // A relation read without its ids (a nested Selection that left `id` out) fills nothing.\n const known = Array.isArray(ids) ? !ids.includes(undefined) : ids !== undefined\n return known ? [[key, ids] as const] : []\n })\n return Object.fromEntries(entries) as Partial<Schema.Struct.Type<Fields>>\n },\n\n is: isEntity,\n\n /** True when both descriptors are versions of one Entity. */\n same: isSameEntity,\n}\n\nfunction one<Target extends AnyEntity>(target: Target): RelationSpec<Target, 'one', false>\nfunction one<Target extends AnyEntity, const Optional extends boolean>(\n target: Target,\n options: { readonly optional: Optional },\n): RelationSpec<Target, 'one', Optional>\nfunction one(\n target: AnyEntity,\n options?: { readonly optional: boolean },\n): RelationSpec<AnyEntity, 'one', boolean> {\n return { target, cardinality: 'one', optional: options?.optional ?? false }\n}\n\n/** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */\nexport const Relation = {\n one,\n\n /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */\n input: <R extends EntityRelation<any, any, any, any, any>>(relation: R): RelationInput<R> =>\n Object.freeze({ _tag: 'RelationInput', relation }),\n\n /**\n * For `Entity.input`: the input key holds the relation's target itself, written\n * through `input`, an `Entity.input` of the target. A `many` holds a list.\n */\n nested: <R extends EntityRelation<any, any, any, any, any>, I extends EntityInput<any, any, any>>(\n relation: R,\n input: I,\n ): NestedInput<R, I> => Object.freeze({ _tag: 'NestedInput', relation, input }),\n\n many: <Target extends AnyEntity>(target: Target): RelationSpec<Target, 'many', false> => ({\n target,\n cardinality: 'many',\n optional: false,\n }),\n}\n\nexport const Derived = {\n make: <S extends Schema.Constraint>(schema: S): DerivedSpec<S> => ({ schema }),\n}\n\nexport * from './expr.js'\n"],"mappings":";;;;;;;;;;;;;;;;AA+GA,MAAM,SAAS,UACb,OAAO,UAAU,YAAY,UAAU,OAClC,MAAsC,OACvC,KAAA;;;;;;;AAQN,MAAM,WAAc,WAA8B;CAAE,MAAM;CAAW;AAAM;AAE3E,MAAM,aAAa,WAA+E;CAChG,MAAM;CACN,OAAO,MAAM;CACb,KAAK,MAAM;CACX,QAAQ,MAAM;AAChB;AAEA,MAAM,gCAAgB,IAAI,IAAI;CAAC;CAAM;CAAQ;AAAU,CAAC;;AAGxD,MAAa,eAAe,UAC1B,cAAc,IAAI,MAAM,KAAK,CAAW;;;;;AAM1C,MAA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