foldkit-entity 0.1.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/LICENSE +21 -0
- package/README.md +313 -0
- package/dist/index.d.mts +281 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +314 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +54 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Patrick Glenn
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
# foldkit-entity
|
|
2
|
+
|
|
3
|
+
A domain entity declared once as a typed value: its intrinsic fields, its
|
|
4
|
+
relations to other entities, and the derived values consumers may read. Other
|
|
5
|
+
packages interpret that declaration; this one only describes.
|
|
6
|
+
|
|
7
|
+
> **Status:** declaration and selection. `foldkit-remote`
|
|
8
|
+
> [registers Entities and reads Selections as they are](../remote/README.md#entities-declared-with-foldkit-entity).
|
|
9
|
+
> `foldkit-remote-drizzle` binds a related set to tables with
|
|
10
|
+
> [`bind`](../remote-drizzle/README.md#binding-a-foldkit-entity-domain), and
|
|
11
|
+
> [`foldkit-form`](../form/README.md) builds a form from `Entity.input`. Admin
|
|
12
|
+
> is planned in [entity-DESIGN.md](../../docs/design/entity-DESIGN.md).
|
|
13
|
+
|
|
14
|
+
For the whole path in one runnable trace, domain to client to SQL, see
|
|
15
|
+
[`examples/entity`](../../examples/entity).
|
|
16
|
+
|
|
17
|
+
## What it owns
|
|
18
|
+
|
|
19
|
+
`foldkit-entity` owns **domain structure**: which members an entity has, what
|
|
20
|
+
kind each is, and which entity a relation points to.
|
|
21
|
+
|
|
22
|
+
It does not own:
|
|
23
|
+
|
|
24
|
+
- **Validation.** `entity.schema` is an ordinary Effect `Schema.Struct` and
|
|
25
|
+
stays the only validity rule.
|
|
26
|
+
- **Storage or fetching.** A relation says "one Author", not "a foreign key" or
|
|
27
|
+
"a join table". How a derived value is computed is the interpreter's business.
|
|
28
|
+
- **Operations.** An Entity implies no create, update, or delete.
|
|
29
|
+
- **Application state.** Nothing here touches a Model or dispatches a Message.
|
|
30
|
+
|
|
31
|
+
## Mental model
|
|
32
|
+
|
|
33
|
+
```text
|
|
34
|
+
Entity
|
|
35
|
+
├── fields intrinsic values: the properties of entity.schema
|
|
36
|
+
├── relations navigation edges: one / many of another Entity (Entity.relate)
|
|
37
|
+
├── derived readable values an interpreter supplies
|
|
38
|
+
└── members all three under one namespace; keys never collide
|
|
39
|
+
|
|
40
|
+
interpreter ──(foldkit-metadata)──► Entity / member attaches what it needs
|
|
41
|
+
interpreter ◄── reads fields, relations, derived, metadata
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Each pipe step, and `Entity.relate`, returns a new frozen descriptor with the
|
|
45
|
+
**same identity**. Two descriptors are the same entity when `Entity.same(a, b)`,
|
|
46
|
+
not when `a === b`.
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
pnpm add effect foldkit-entity
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Example
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { Schema } from 'effect'
|
|
58
|
+
import { Derived, Entity, Relation } from 'foldkit-entity'
|
|
59
|
+
|
|
60
|
+
const Author = Entity.define('Author', Schema.Struct({ id: Schema.String, name: Schema.String }))
|
|
61
|
+
const Comment = Entity.define('Comment', Schema.Struct({ id: Schema.String, body: Schema.String }))
|
|
62
|
+
const Post = Entity.define(
|
|
63
|
+
'Post',
|
|
64
|
+
Schema.Struct({ id: Schema.String, title: Schema.String, published: Schema.Boolean }),
|
|
65
|
+
).pipe(Entity.derived({ commentCount: Derived.make(Schema.Number) }))
|
|
66
|
+
|
|
67
|
+
const Blog = Entity.relate(
|
|
68
|
+
{ Author, Post, Comment },
|
|
69
|
+
{
|
|
70
|
+
Post: {
|
|
71
|
+
author: Relation.one(Author),
|
|
72
|
+
editor: Relation.one(Author, { optional: true }),
|
|
73
|
+
comments: Relation.many(Comment),
|
|
74
|
+
},
|
|
75
|
+
Comment: { post: Relation.one(Post) },
|
|
76
|
+
},
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
Blog.Post.schema // Schema.Struct of id, title, published: relations are not in it
|
|
80
|
+
Blog.Post.fields.title.schema // Schema.String
|
|
81
|
+
Blog.Post.relations.editor.optional // true
|
|
82
|
+
Blog.Post.derived.commentCount.schema // Schema.Number
|
|
83
|
+
Blog.Post.relations.comments.target() // Blog.Comment
|
|
84
|
+
Blog.Post.relations.comments.target().relations.post.target() // Blog.Post, fully typed
|
|
85
|
+
Object.keys(Blog.Post.members) // id, title, published, commentCount, author, editor, comments
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
- `Entity.define` generates one `Field` per schema property and creates the
|
|
89
|
+
identity. Calling it twice with the same name makes two different entities.
|
|
90
|
+
- `Derived.make` states a readable value's schema and nothing about how it is
|
|
91
|
+
produced. `Entity.derived` is a pipe step because it concerns one entity.
|
|
92
|
+
- `Entity.relate` takes the entities and every relation between them, and
|
|
93
|
+
returns the same entities with `relations` filled in. Use the returned ones
|
|
94
|
+
(`Blog.Post`); the `Post` you passed in still has no relations.
|
|
95
|
+
- `Relation.one` / `Relation.many` state what the owner sees. `Post.author: one`
|
|
96
|
+
and `Author.posts: many` together are the familiar one-to-many; neither side
|
|
97
|
+
names it.
|
|
98
|
+
- `target()` returns the related entity, so relations can be followed from
|
|
99
|
+
there, around a cycle too.
|
|
100
|
+
|
|
101
|
+
`Entity.relate` throws, and the types reject, a relation key that is already a
|
|
102
|
+
member, an owner that is not in the first argument, and a target that is not
|
|
103
|
+
in the first argument.
|
|
104
|
+
|
|
105
|
+
### Why relations are declared in one step
|
|
106
|
+
|
|
107
|
+
Entities point at each other: a Post has Comments and a Comment has a Post. If
|
|
108
|
+
each entity declared its own relations, `Post` would be typed in terms of
|
|
109
|
+
`Comment` and `Comment` in terms of `Post`, and TypeScript cannot infer two
|
|
110
|
+
constants that way. Declaring the relations over entities that already exist
|
|
111
|
+
avoids the cycle, and lets `relate` check every target up front.
|
|
112
|
+
|
|
113
|
+
## Selecting a view
|
|
114
|
+
|
|
115
|
+
A Selection names the members a consumer wants and carries the schema of the
|
|
116
|
+
value that results. It does not fetch that value; whoever produces it (a server
|
|
117
|
+
adapter, a test, a form) decodes against `selection.schema`.
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
const AuthorOption = Entity.select(Blog.Author, { id: true, name: true })
|
|
121
|
+
|
|
122
|
+
const PostRow = Entity.select(Blog.Post, {
|
|
123
|
+
title: true,
|
|
124
|
+
commentCount: true,
|
|
125
|
+
author: AuthorOption,
|
|
126
|
+
editor: AuthorOption,
|
|
127
|
+
comments: true,
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
PostRow.schema.Type
|
|
131
|
+
// {
|
|
132
|
+
// title: string
|
|
133
|
+
// commentCount: number
|
|
134
|
+
// author: { id: string; name: string }
|
|
135
|
+
// editor: { id: string; name: string } | null
|
|
136
|
+
// comments: ReadonlyArray<{ entity: 'Comment'; id: string }>
|
|
137
|
+
// }
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
| Member | Select with | Yields |
|
|
141
|
+
| --- | --- | --- |
|
|
142
|
+
| Field, Derived | `true` | the member's own schema, checks included |
|
|
143
|
+
| Relation | `true` | an `EntityRef`: `{ entity, id }` |
|
|
144
|
+
| Relation | a Selection of its target | that Selection's value |
|
|
145
|
+
| `many` Relation | `Entity.page(selection, window)` | a `Page` of that Selection's values |
|
|
146
|
+
|
|
147
|
+
A `many` relation yields an array, and an optional `one` is nullable. A
|
|
148
|
+
Selection is an ordinary value, so `AuthorOption` above is declared once and
|
|
149
|
+
reused. Nesting is always explicit, which is what keeps a cycle finite.
|
|
150
|
+
|
|
151
|
+
### A page of a relation
|
|
152
|
+
|
|
153
|
+
A post may have ten thousand comments. `Entity.page` reads a `many` relation a
|
|
154
|
+
page at a time:
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
const CommentBody = Entity.select(Blog.Comment, { body: true })
|
|
158
|
+
|
|
159
|
+
const PostWithComments = Entity.select(Blog.Post, {
|
|
160
|
+
title: true,
|
|
161
|
+
comments: Entity.page(CommentBody, { first: 10 }),
|
|
162
|
+
})
|
|
163
|
+
// { title: string, comments: { items: { body: string }[], hasNext: boolean, hasPrevious: boolean } }
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
The window is `first` or `last`, with `after` or `before` a cursor. A page is a
|
|
167
|
+
view's shape, as neutral as "`many` means an array", so it is declared here.
|
|
168
|
+
What a cursor is and how the rows are ordered belong to whoever fetches: the
|
|
169
|
+
cursor is an opaque string an earlier answer handed out. Reading on is another
|
|
170
|
+
Selection with another window.
|
|
171
|
+
|
|
172
|
+
An unknown member, a nested Selection on a field, a page of a `one` relation,
|
|
173
|
+
and a Selection of the wrong
|
|
174
|
+
Entity are type errors, and `Entity.select` throws for untyped callers.
|
|
175
|
+
|
|
176
|
+
## Reading an operation's input
|
|
177
|
+
|
|
178
|
+
> Experimental: the smallest mapping that several operation shapes and
|
|
179
|
+
> [`foldkit-form`](../form/README.md) needed.
|
|
180
|
+
|
|
181
|
+
An Entity does not decide what may be written; an operation does (a Remote
|
|
182
|
+
mutation, an RPC, a form). `Entity.input` takes that operation's input schema
|
|
183
|
+
and says what each key means in terms of the Entity, so a consumer can find the
|
|
184
|
+
field's metadata for a label, or the relation's target for a picker.
|
|
185
|
+
|
|
186
|
+
```ts
|
|
187
|
+
const CreatePostInput = Schema.Struct({
|
|
188
|
+
title: Schema.String,
|
|
189
|
+
authorId: Schema.String,
|
|
190
|
+
notify: Schema.Boolean,
|
|
191
|
+
})
|
|
192
|
+
|
|
193
|
+
const CreatePost = Entity.input(Blog.Post, CreatePostInput, {
|
|
194
|
+
authorId: Relation.input(Blog.Post.relations.author),
|
|
195
|
+
notify: Entity.unmapped,
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
CreatePost.members.title // Blog.Post.fields.title: it names a field, so it maps itself
|
|
199
|
+
CreatePost.members.authorId.relation.target() // Blog.Author: what a picker chooses from
|
|
200
|
+
CreatePost.members.notify // Entity.unmapped: about the operation, not the Post
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
- A key that names a field, with a value that fits it, maps itself. Only the
|
|
204
|
+
present value has to fit: a key may be optional (a partial update) or admit
|
|
205
|
+
`null` (clearing it), which is the input schema's rule to make.
|
|
206
|
+
- Every other key needs an entry: a Field under another name, a relation's ids
|
|
207
|
+
with `Relation.input(relation)`, or `Entity.unmapped`. Nothing is inferred
|
|
208
|
+
from a name like `authorId`.
|
|
209
|
+
- `Relation.input` expects one id for a `one`, `id | null` for an optional
|
|
210
|
+
`one`, and an array of ids for a `many`.
|
|
211
|
+
- A derived member cannot be written, and a member of another Entity cannot be
|
|
212
|
+
mapped. Both are type errors and throw.
|
|
213
|
+
|
|
214
|
+
### An input that holds the target itself
|
|
215
|
+
|
|
216
|
+
A post created together with a new author carries the author, not an id.
|
|
217
|
+
`Relation.nested` maps the key to the relation and to an input of its target:
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
const NewAuthor = Entity.input(Blog.Author, Schema.Struct({ name: Schema.String }))
|
|
221
|
+
|
|
222
|
+
const CreatePost = Entity.input(
|
|
223
|
+
Blog.Post,
|
|
224
|
+
Schema.Struct({ title: Schema.String, author: NewAuthor.schema }),
|
|
225
|
+
{ author: Relation.nested(Blog.Post.relations.author, NewAuthor) },
|
|
226
|
+
)
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
A `one` holds the nested input's value, a `many` a list of them; the nested
|
|
230
|
+
input must be of the relation's target, and both are checked by type and at
|
|
231
|
+
runtime. `Entity.selectFor` then loads what the nested input writes of the
|
|
232
|
+
target, and `Entity.valuesFor` turns the loaded target back into nested values.
|
|
233
|
+
What a nested write *does* (insert, update, replace the list) is the
|
|
234
|
+
operation's handler to decide.
|
|
235
|
+
|
|
236
|
+
### Showing what is there
|
|
237
|
+
|
|
238
|
+
An edit screen has to load the current values and turn them into input values.
|
|
239
|
+
Both follow from the reading, so neither is written by hand:
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
const PostForEdit = Entity.selectFor(CreatePost)
|
|
243
|
+
// a Selection of `title` and `author`, the members the input writes; `author` as a ref
|
|
244
|
+
|
|
245
|
+
Entity.valuesFor(CreatePost, { title: 'Hello', author: { entity: 'Author', id: 'a1' } })
|
|
246
|
+
// { title: 'Hello', authorId: 'a1' }
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
`selectFor` selects every member the input writes, by the member's key, with
|
|
250
|
+
each relation as refs. `valuesFor` reads such a value back under the input's
|
|
251
|
+
keys: a field as it is, a relation as the id or ids of what it holds. A relation
|
|
252
|
+
read without its ids (a nested Selection that left `id` out) fills nothing. An
|
|
253
|
+
unmapped key appears in neither, since the Entity knows nothing about it.
|
|
254
|
+
|
|
255
|
+
The schema is an ordinary `Schema.Struct`, so declare it once and give the same
|
|
256
|
+
value to the operation, for example `Mutation.make('CreatePost', { Input:
|
|
257
|
+
CreatePostInput, … })` in `foldkit-remote`.
|
|
258
|
+
|
|
259
|
+
## Attaching metadata
|
|
260
|
+
|
|
261
|
+
An interpreter declares a [`foldkit-metadata`](../metadata/README.md) key and
|
|
262
|
+
attaches entries to the entity or to members. Entity core never reads them.
|
|
263
|
+
|
|
264
|
+
```ts
|
|
265
|
+
import { Metadata } from 'foldkit-metadata'
|
|
266
|
+
|
|
267
|
+
const Labels = Metadata.key<string>('my-admin/labels', {
|
|
268
|
+
merge: labels => [...new Set(labels)],
|
|
269
|
+
summarize: label => label,
|
|
270
|
+
})
|
|
271
|
+
|
|
272
|
+
const CmsPost = Blog.Post.pipe(
|
|
273
|
+
Entity.annotate(Labels.of('Post')),
|
|
274
|
+
Entity.annotateMembers({ title: Labels.of('Title'), author: Labels.of('Byline') }),
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
Labels.get(CmsPost.fields.title.metadata) // ['Title']
|
|
278
|
+
Entity.same(CmsPost, Blog.Post) // true: the metadata changed, the entity did not
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
Annotating again combines with what is there, using the key's own `merge`.
|
|
282
|
+
|
|
283
|
+
## API
|
|
284
|
+
|
|
285
|
+
| Call | Meaning |
|
|
286
|
+
| --- | --- |
|
|
287
|
+
| `Entity.define(name, struct)` | A new Entity with a Field per property. |
|
|
288
|
+
| `Entity.relate(entities, { Owner: { key: Relation.one(Target) } })` | The entities with their relations declared; targets resolve to the returned entities. |
|
|
289
|
+
| `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 `Page`: `items`, `hasNext`, `hasPrevious`. |
|
|
291
|
+
| `Entity.input(entity, struct, mapping?)` | Experimental. Which member each key of an operation's input writes. |
|
|
292
|
+
| `Relation.nested(relation, input)` | In an input mapping: the key holds the target itself, written through `input`. |
|
|
293
|
+
| `Entity.selectFor(input)` | The Selection of the members an input writes: what an edit screen loads. |
|
|
294
|
+
| `Entity.valuesFor(input, value)` | The input values that reproduce a loaded value: fields as they are, refs as ids. |
|
|
295
|
+
| `Entity.derived({ key: Derived.make(schema) })` | Pipe step adding readable, externally supplied members. |
|
|
296
|
+
| `Entity.annotate(metadata)` | Pipe step attaching metadata to the Entity. |
|
|
297
|
+
| `Entity.annotateMembers({ key: metadata })` | Pipe step attaching metadata to members by key. |
|
|
298
|
+
| `Entity.same(a, b)` | Whether two descriptors are versions of one Entity. |
|
|
299
|
+
| `Entity.is(value)` | Whether a value is an Entity descriptor. |
|
|
300
|
+
|
|
301
|
+
## Limits
|
|
302
|
+
|
|
303
|
+
- IDs are untyped; nothing marks which field is the identifier yet, and an
|
|
304
|
+
`EntityRef` id is a `string`.
|
|
305
|
+
- A Selection has no filtering or ordering, and a page has no total; those
|
|
306
|
+
belong to the interpreter that fetches.
|
|
307
|
+
- Relations reach only the entities of one `Entity.relate` call; relating the
|
|
308
|
+
result again adds relations but earlier targets keep pointing at the earlier
|
|
309
|
+
result.
|
|
310
|
+
- `target()` returns the entity as `relate` returned it. Metadata attached
|
|
311
|
+
afterwards (`CmsPost` above) is on the new descriptor only, so annotate before
|
|
312
|
+
relating when a target should carry it.
|
|
313
|
+
- No registry: nothing checks that two different entities share a name.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { Pipeable, Schema } from "effect";
|
|
2
|
+
import { Metadata } from "foldkit-metadata";
|
|
3
|
+
//#region src/index.d.ts
|
|
4
|
+
export declare const EntityTypeId: unique symbol;
|
|
5
|
+
export type EntityTypeId = typeof EntityTypeId;
|
|
6
|
+
/**
|
|
7
|
+
* What makes two descriptors the same Entity. A pipe step returns a new
|
|
8
|
+
* descriptor with the same identity, so compare `identity`, never the objects.
|
|
9
|
+
*/
|
|
10
|
+
export interface EntityIdentity<Name extends string> {
|
|
11
|
+
readonly name: Name;
|
|
12
|
+
/** Distinguishes two Entities that were defined with the same name. */
|
|
13
|
+
readonly token: symbol;
|
|
14
|
+
}
|
|
15
|
+
/** An intrinsic value of the Entity: one property of `entity.schema`. */
|
|
16
|
+
export interface EntityField<Name extends string, Key extends string, S extends Schema.Constraint> {
|
|
17
|
+
readonly _tag: 'Field';
|
|
18
|
+
readonly owner: EntityIdentity<Name>;
|
|
19
|
+
readonly key: Key;
|
|
20
|
+
readonly schema: S;
|
|
21
|
+
readonly metadata: Metadata;
|
|
22
|
+
}
|
|
23
|
+
export type Cardinality = 'one' | 'many';
|
|
24
|
+
/** What `Relation.one` / `Relation.many` return, before `Entity.relate` binds it to an owner. */
|
|
25
|
+
export interface RelationSpec<Target extends AnyEntity, C extends Cardinality, Optional extends boolean> {
|
|
26
|
+
readonly target: Target;
|
|
27
|
+
readonly cardinality: C;
|
|
28
|
+
readonly optional: Optional;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* A navigation edge as its owner sees it: one or many of `target`. How the edge
|
|
32
|
+
* is stored (a foreign key, a join table, a nested document) is the
|
|
33
|
+
* interpreter's concern.
|
|
34
|
+
*/
|
|
35
|
+
export interface EntityRelation<Name extends string, Key extends string, Target extends AnyEntity, C extends Cardinality, Optional extends boolean> {
|
|
36
|
+
readonly _tag: 'Relation';
|
|
37
|
+
readonly owner: EntityIdentity<Name>;
|
|
38
|
+
readonly key: Key;
|
|
39
|
+
/** The target as `Entity.relate` returned it, so its own relations can be followed. */
|
|
40
|
+
readonly target: () => Target;
|
|
41
|
+
readonly cardinality: C;
|
|
42
|
+
readonly optional: Optional;
|
|
43
|
+
readonly metadata: Metadata;
|
|
44
|
+
}
|
|
45
|
+
/** What `Derived.make` returns, before an Entity owns it. */
|
|
46
|
+
export interface DerivedSpec<S extends Schema.Constraint> {
|
|
47
|
+
readonly schema: S;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* A value consumers may read that is not part of `entity.schema`. It says
|
|
51
|
+
* nothing about how the value is computed; an interpreter supplies it.
|
|
52
|
+
*/
|
|
53
|
+
export interface EntityDerived<Name extends string, Key extends string, S extends Schema.Constraint> {
|
|
54
|
+
readonly _tag: 'Derived';
|
|
55
|
+
readonly owner: EntityIdentity<Name>;
|
|
56
|
+
readonly key: Key;
|
|
57
|
+
readonly schema: S;
|
|
58
|
+
readonly metadata: Metadata;
|
|
59
|
+
}
|
|
60
|
+
export type EntityMember = EntityField<string, string, Schema.Constraint> | EntityRelation<string, string, AnyEntity, Cardinality, boolean> | EntityDerived<string, string, Schema.Constraint>;
|
|
61
|
+
export type RelationSpecs = Readonly<Record<string, RelationSpec<AnyEntity, Cardinality, boolean>>>;
|
|
62
|
+
export type DerivedSpecs = Readonly<Record<string, DerivedSpec<Schema.Constraint>>>;
|
|
63
|
+
type FieldsOf<Name extends string, Fields extends Schema.Struct.Fields> = { readonly [K in keyof Fields & string]: EntityField<Name, K, Fields[K]>; };
|
|
64
|
+
type RelationsOf<Name extends string, Relations extends RelationSpecs> = { readonly [K in keyof Relations & string]: Relations[K] extends RelationSpec<infer Target, infer C, infer Optional> ? EntityRelation<Name, K, Target, C, Optional> : never; };
|
|
65
|
+
type DerivedOf<Name extends string, Derived extends DerivedSpecs> = { readonly [K in keyof Derived & string]: EntityDerived<Name, K, Derived[K]['schema']>; };
|
|
66
|
+
export interface Entity<Name extends string, Fields extends Schema.Struct.Fields, Relations extends RelationSpecs = {}, Derived extends DerivedSpecs = {}> extends Pipeable.Pipeable {
|
|
67
|
+
readonly [EntityTypeId]: EntityTypeId;
|
|
68
|
+
readonly identity: EntityIdentity<Name>;
|
|
69
|
+
readonly name: Name;
|
|
70
|
+
/** The intrinsic value only: no relations, no derived members. */
|
|
71
|
+
readonly schema: Schema.Struct<Fields>;
|
|
72
|
+
readonly fields: FieldsOf<Name, Fields>;
|
|
73
|
+
readonly relations: RelationsOf<Name, Relations>;
|
|
74
|
+
readonly derived: DerivedOf<Name, Derived>;
|
|
75
|
+
/** Every readable member under one namespace; keys never collide. */
|
|
76
|
+
readonly members: FieldsOf<Name, Fields> & RelationsOf<Name, Relations> & DerivedOf<Name, Derived>;
|
|
77
|
+
readonly metadata: Metadata;
|
|
78
|
+
}
|
|
79
|
+
export type AnyEntity = Entity<string, any, any, any>;
|
|
80
|
+
/** Unsatisfiable when a new key is already a member, so the pipe step is the error site. */
|
|
81
|
+
type Free<E extends AnyEntity, New> = keyof New & keyof E['members'] extends never ? unknown : {
|
|
82
|
+
readonly alreadyAMember: keyof New & keyof E['members'];
|
|
83
|
+
};
|
|
84
|
+
type WithDerived<E, New extends DerivedSpecs> = E extends Entity<infer Name, infer Fields, infer R, infer D> ? Entity<Name, Fields, R, D & New> : never;
|
|
85
|
+
export type Entities = Readonly<Record<string, AnyEntity>>;
|
|
86
|
+
export type RelationMap<Es extends Entities> = { readonly [K in keyof Es]?: RelationSpecs; };
|
|
87
|
+
/** The key in `Es` of the Entity a spec targets, matched by name. */
|
|
88
|
+
export type TargetKey<Es extends Entities, Target extends AnyEntity> = { [K in keyof Es]: [Es[K]['name'], Target['name']] extends [Target['name'], Es[K]['name']] ? K : never; }[keyof Es];
|
|
89
|
+
export type RelatedSpecs<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> = { readonly [R in keyof Rs[K]]: Rs[K][R] extends RelationSpec<infer Target, infer C, infer Optional> ? RelationSpec<Related<Es, Rs, TargetKey<Es, Target>>, C, Optional> : never; };
|
|
90
|
+
/**
|
|
91
|
+
* One Entity of an `Entity.relate` result. A relation's target is again a
|
|
92
|
+
* `Related`, so relations can be followed through a cycle; the recursion goes
|
|
93
|
+
* through type arguments, which TypeScript resolves only when asked.
|
|
94
|
+
*/
|
|
95
|
+
export type Related<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> = Es[K] extends Entity<infer Name, infer Fields, infer R, infer D> ? Entity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D> : never;
|
|
96
|
+
/** Marks a relation key that is already a member of its owner, or an owner that is not listed. */
|
|
97
|
+
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
|
+
export declare const SelectionTypeId: unique symbol;
|
|
99
|
+
export type SelectionTypeId = typeof SelectionTypeId;
|
|
100
|
+
/** What a relation selected with `true` yields: which Entity, and which one. */
|
|
101
|
+
export interface EntityRef<Name extends string = string> {
|
|
102
|
+
readonly entity: Name;
|
|
103
|
+
readonly id: string;
|
|
104
|
+
}
|
|
105
|
+
type RefSchema<Name extends string> = Schema.Struct<{
|
|
106
|
+
readonly entity: Schema.Literal<Name>;
|
|
107
|
+
readonly id: Schema.String;
|
|
108
|
+
}>;
|
|
109
|
+
/**
|
|
110
|
+
* A view of the Entity graph: which members to read, and the schema of the
|
|
111
|
+
* value that results. It says nothing about where the value comes from.
|
|
112
|
+
*/
|
|
113
|
+
export interface Selection<Name extends string, Members, S extends Schema.Constraint> {
|
|
114
|
+
readonly [SelectionTypeId]: SelectionTypeId;
|
|
115
|
+
readonly entity: Entity<Name, any, any, any>;
|
|
116
|
+
/** What was selected, by member key: `true`, or a relation's nested Selection. */
|
|
117
|
+
readonly members: Members;
|
|
118
|
+
readonly schema: S;
|
|
119
|
+
}
|
|
120
|
+
type AnySelection<Name extends string = string> = Selection<Name, any, any>;
|
|
121
|
+
/** `true` for any member; a relation also takes a Selection of its target. */
|
|
122
|
+
/**
|
|
123
|
+
* Which part of a `many` relation to read: the first or last so many, from a
|
|
124
|
+
* cursor or from the end. A cursor is whatever the interpreter handed out with an
|
|
125
|
+
* earlier page; nothing here looks inside it.
|
|
126
|
+
*/
|
|
127
|
+
export interface PageWindow {
|
|
128
|
+
readonly first?: number | undefined;
|
|
129
|
+
readonly last?: number | undefined;
|
|
130
|
+
readonly after?: string | undefined;
|
|
131
|
+
readonly before?: string | undefined;
|
|
132
|
+
}
|
|
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
|
+
export declare const SelectionPageTypeId: unique symbol;
|
|
140
|
+
export type SelectionPageTypeId = typeof SelectionPageTypeId;
|
|
141
|
+
/** A Selection of a `many` relation's target, read a page at a time. */
|
|
142
|
+
export interface SelectionPage<Name extends string, S extends Schema.Constraint> {
|
|
143
|
+
readonly [SelectionPageTypeId]: SelectionPageTypeId;
|
|
144
|
+
readonly selection: Selection<Name, any, S>;
|
|
145
|
+
readonly window: PageWindow;
|
|
146
|
+
}
|
|
147
|
+
type PageSchema<S extends Schema.Constraint> = Schema.Struct<{
|
|
148
|
+
readonly items: Schema.$Array<S>;
|
|
149
|
+
readonly hasNext: Schema.Boolean;
|
|
150
|
+
readonly hasPrevious: Schema.Boolean;
|
|
151
|
+
}>;
|
|
152
|
+
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
|
+
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['name']>> : never;
|
|
155
|
+
type SelectionSchema<E extends AnyEntity, Spec> = Schema.Struct<{ readonly [K in keyof Spec & keyof E['members']]: SelectedSchema<E['members'][K], Spec[K]>; }>;
|
|
156
|
+
/** An input key that carries a relation's target: the id of a `one`, the ids of a `many`. */
|
|
157
|
+
export interface RelationInput<R extends EntityRelation<any, any, any, any, any>> {
|
|
158
|
+
readonly _tag: 'RelationInput';
|
|
159
|
+
readonly relation: R;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* An input key that carries the relation's target itself, written through an
|
|
163
|
+
* input of its own: a post created with a new author, an order with its lines.
|
|
164
|
+
* A `one` holds that input's value, a `many` a list of them.
|
|
165
|
+
*/
|
|
166
|
+
export interface NestedInput<R extends EntityRelation<any, any, any, any, any>, I extends EntityInput<any, any, any>> {
|
|
167
|
+
readonly _tag: 'NestedInput';
|
|
168
|
+
readonly relation: R;
|
|
169
|
+
readonly input: I;
|
|
170
|
+
}
|
|
171
|
+
/** An input key that is about the operation, not the Entity: a reason, a flag, a confirmation. */
|
|
172
|
+
export interface Unmapped {
|
|
173
|
+
readonly _tag: 'Unmapped';
|
|
174
|
+
}
|
|
175
|
+
/** What one key of an operation's input means in terms of the Entity. */
|
|
176
|
+
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
|
+
/** 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, any, infer C, infer Optional> ? C extends 'many' ? ReadonlyArray<string> : Optional extends true ? string | null : string : never;
|
|
179
|
+
/** What a nested input takes: the value of the target's input, or a list of them for a `many`. */
|
|
180
|
+
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
|
+
/**
|
|
182
|
+
* Only the value that is present has to fit: an input may leave a key out (a
|
|
183
|
+
* partial update) or send `null` to clear it. Whether it may is the input
|
|
184
|
+
* schema's rule; the fit only guards against mapping the wrong member.
|
|
185
|
+
*/
|
|
186
|
+
type Present<T> = Exclude<T, null | undefined>;
|
|
187
|
+
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
|
+
/** A key that names a field whose value it fits maps itself; every other key needs an entry. */
|
|
189
|
+
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
|
+
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 ? MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Mapping[K]> : `"${K & string}" is not a key of the input`; };
|
|
191
|
+
type InputMembers<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = { readonly [K in keyof Fields]: K extends keyof Mapping ? Mapping[K] : K extends keyof E['fields'] ? E['fields'][K] : never; };
|
|
192
|
+
/**
|
|
193
|
+
* An operation's input read against an Entity: which member each input key
|
|
194
|
+
* writes. The operation decides what may be submitted; the Entity only says
|
|
195
|
+
* what each submitted key means.
|
|
196
|
+
*/
|
|
197
|
+
export interface EntityInput<E extends AnyEntity, Fields extends Schema.Struct.Fields, Members> {
|
|
198
|
+
readonly entity: E;
|
|
199
|
+
readonly schema: Schema.Struct<Fields>;
|
|
200
|
+
readonly members: Members;
|
|
201
|
+
}
|
|
202
|
+
/** The Entity member an input key writes, by its key; nothing for an unmapped key. */
|
|
203
|
+
export type WrittenKey<M> = M extends EntityField<any, infer Key, any> ? Key : M extends RelationInput<EntityRelation<any, infer Key, any, any, any>> | NestedInput<EntityRelation<any, infer Key, any, any, any>, any> ? Key : never;
|
|
204
|
+
/** A nested input reads what it writes of the target; every other member reads as it is. */
|
|
205
|
+
export type WrittenAs<M> = M extends NestedInput<any, EntityInput<infer Of, any, infer Members>> ? Selection<Of['name'], WrittenSpec<Members>, SelectionSchema<Of, WrittenSpec<Members>>> : true;
|
|
206
|
+
/** Every member the input writes: what to read to show the input's current values. */
|
|
207
|
+
export type WrittenSpec<Members> = { readonly [K in keyof Members as WrittenKey<Members[K]>]: WrittenAs<Members[K]>; };
|
|
208
|
+
export declare const Entity: {
|
|
209
|
+
/** Declares an Entity from its intrinsic fields. Each call is a new identity. */
|
|
210
|
+
define: <const Name extends string, Fields extends Schema.Struct.Fields>(name: Name, schema: Schema.Struct<Fields>) => Entity<Name, Fields>;
|
|
211
|
+
/**
|
|
212
|
+
* Declares the relations between a set of Entities in one step, and returns
|
|
213
|
+
* them related. One step, because Entities that point at each other cannot
|
|
214
|
+
* each be declared in terms of the other.
|
|
215
|
+
*/
|
|
216
|
+
relate: <const Es extends Entities, const Rs extends RelationMap<Es>>(entities: Es, relations: Rs & CheckRelations<Es, Rs>) => { readonly [K in keyof Es]: Related<Es, Rs, K>; };
|
|
217
|
+
/**
|
|
218
|
+
* Selects members of an Entity and assembles the schema of the result. A
|
|
219
|
+
* relation selected with `true` yields an `EntityRef`; with a Selection of its
|
|
220
|
+
* target, that Selection's value. `many` yields an array, an optional `one`
|
|
221
|
+
* is nullable.
|
|
222
|
+
*/
|
|
223
|
+
select: <E extends AnyEntity, const Spec>(entity: E, spec: Spec & SelectionSpec<E, Spec>) => Selection<E["name"], Spec, SelectionSchema<E, Spec>>;
|
|
224
|
+
/**
|
|
225
|
+
* 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 `Page`
|
|
227
|
+
* of the Selection's values. Reading on from a cursor is another window.
|
|
228
|
+
*/
|
|
229
|
+
page: <Name extends string, S extends Schema.Constraint>(selection: Selection<Name, any, S>, window: PageWindow) => SelectionPage<Name, S>;
|
|
230
|
+
/** Adds readable members that are not part of `entity.schema`. */
|
|
231
|
+
derived: <const New extends DerivedSpecs>(specs: New) => <E extends AnyEntity>(entity: E & Free<E, New>) => WithDerived<E, New>;
|
|
232
|
+
/** Attaches an interpreter's metadata to the Entity itself. */
|
|
233
|
+
annotate: (metadata: Metadata) => <E extends AnyEntity>(entity: E) => E;
|
|
234
|
+
/** Attaches an interpreter's metadata to members, by key. */
|
|
235
|
+
annotateMembers: <E extends AnyEntity>(metadata: { readonly [K in keyof E["members"]]?: Metadata; }) => (entity: E) => E;
|
|
236
|
+
/**
|
|
237
|
+
* Reads an operation's input schema against an Entity. A key that names a
|
|
238
|
+
* field maps to it; any other key is mapped explicitly, to a Field, to
|
|
239
|
+
* `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred
|
|
240
|
+
* from a naming convention such as `authorId`.
|
|
241
|
+
*/
|
|
242
|
+
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
|
+
/** For an input key that is about the operation rather than the Entity. */
|
|
244
|
+
unmapped: Unmapped;
|
|
245
|
+
/**
|
|
246
|
+
* The Selection of every member an input writes, with each relation as refs:
|
|
247
|
+
* what an edit screen loads before it shows the input's current values.
|
|
248
|
+
*/
|
|
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>>>;
|
|
250
|
+
/**
|
|
251
|
+
* The input values that reproduce `value`, a value read through `selectFor`
|
|
252
|
+
* (or any Selection with those members): a field as it is, a relation as the
|
|
253
|
+
* id or ids of its refs. A key whose member `value` lacks is left out, as is
|
|
254
|
+
* an unmapped key, which the Entity knows nothing about.
|
|
255
|
+
*/
|
|
256
|
+
valuesFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(input: EntityInput<E, Fields, Members>, value: Readonly<Record<string, unknown>>) => Partial<Schema.Struct.Type<Fields>>;
|
|
257
|
+
is: (value: unknown) => value is AnyEntity;
|
|
258
|
+
/** True when both descriptors are versions of one Entity. */
|
|
259
|
+
same: (left: AnyEntity, right: AnyEntity) => boolean;
|
|
260
|
+
};
|
|
261
|
+
declare function one<Target extends AnyEntity>(target: Target): RelationSpec<Target, 'one', false>;
|
|
262
|
+
declare function one<Target extends AnyEntity, const Optional extends boolean>(target: Target, options: {
|
|
263
|
+
readonly optional: Optional;
|
|
264
|
+
}): RelationSpec<Target, 'one', Optional>;
|
|
265
|
+
/** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */
|
|
266
|
+
export declare const Relation: {
|
|
267
|
+
one: typeof one;
|
|
268
|
+
/** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */
|
|
269
|
+
input: <R extends EntityRelation<any, any, any, any, any>>(relation: R) => RelationInput<R>;
|
|
270
|
+
/**
|
|
271
|
+
* For `Entity.input`: the input key holds the relation's target itself, written
|
|
272
|
+
* through `input`, an `Entity.input` of the target. A `many` holds a list.
|
|
273
|
+
*/
|
|
274
|
+
nested: <R extends EntityRelation<any, any, any, any, any>, I extends EntityInput<any, any, any>>(relation: R, input: I) => NestedInput<R, I>;
|
|
275
|
+
many: <Target extends AnyEntity>(target: Target) => RelationSpec<Target, "many", false>;
|
|
276
|
+
};
|
|
277
|
+
export declare const Derived: {
|
|
278
|
+
make: <S extends Schema.Constraint>(schema: S) => DerivedSpec<S>;
|
|
279
|
+
};
|
|
280
|
+
//#endregion
|
|
281
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;qBAYa;YACD,sBAAsB;;;;;iBAMjB,eAAe;WACrB,MAAM;;WAEN;;;iBAIM,YAAY,qBAAqB,oBAAoB,UAAU,OAAO;WAC5E;WACA,OAAO,eAAe;WACtB,KAAK;WACL,QAAQ;WACR,UAAU;;YAGT;;iBAGK,aACf,eAAe,WACf,UAAU,aACV;WAES,QAAQ;WACR,aAAa;WACb,UAAU;;;;;;;iBAQJ,eACf,qBACA,oBACA,eAAe,WACf,UAAU,aACV;WAES;WACA,OAAO,eAAe;WACtB,KAAK;;WAEL,cAAc;WACd,aAAa;WACb,UAAU;WACV,UAAU;;;iBAIJ,YAAY,UAAU,OAAO;WACnC,QAAQ;;;;;;iBAOF,cACf,qBACA,oBACA,UAAU,OAAO;WAER;WACA,OAAO,eAAe;WACtB,KAAK;WACL,QAAQ;WACR,UAAU;;YAGT,eACR,4BAA4B,OAAO,cACnC,+B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ACD,OAAO,OAAO,YAAO,eACX,aAAa,GAAG,QAAQ,0BACrC,UAAU,UAAU,aAAa,GAAG,QAAQ,aAC5C,SAAS,UAAU,aAAa,GAAG,QAAQ,cAC/C,YAAY,GAAG,QAAQ,aAAa,GAAG,QAAQ;;;;;;;EA4CtC,YAAA,UAAU,WAAW,eAAe,OAAO,OAAO,QAAQ,SAAO,OACpE,YAAY,GAAG,QAAQ,aAC7B,UAAU,WAAW,YAAY,UAAU,gBAAgB,GAAG,YAAY;;;;;;;EAuBjE,YAAA,UAAU,WAAW,eAAe,OAAO,OAAO,QAAQ,SAAO,OACpE,YAAY,GAAG,QAAQ,UAAQ,OAC/B,SAAS,6BACf,QAAQ,OAAO,OAAO,KAAK;EAvUP,KAAA,mBAAU,SAAS;;EAPhB,OAAA,MAAA,WAAS,OAAS;;iBAoXrC,IAAI,eAAe,WAAW,QAAQ,SAAS,aAAa;iBAC5D,IAAI,eAAe,iBAAiB,0BAC3C,QAAQ,QACR;WAAoB,UAAU;IAC7B,aAAa,eAAe;;qBASlB;;;EAIH,QAAA,UAAU,yCAAuC,UAAY,MAAI,cAAc;;;;;EAO9E,SAAA,UAAU,yCAAyC,UAAU,4BAA0B,UACpF,GAAC,OACJ,MACN,YAAY,GAAG;EAEX,OAAA,eAAe,WAAS,QAAU,WAAS,aAAa;;qBAOpD;EACJ,OAAA,UAAU,OAAO,YAAU,QAAU,MAAI,YAAY"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { Pipeable, Schema } from "effect";
|
|
2
|
+
import { Metadata } from "foldkit-metadata";
|
|
3
|
+
//#region src/index.ts
|
|
4
|
+
/**
|
|
5
|
+
* `foldkit-entity` — domain structure as typed values.
|
|
6
|
+
*
|
|
7
|
+
* An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations
|
|
8
|
+
* (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable
|
|
9
|
+
* values an interpreter supplies). It describes; it fetches, stores, and
|
|
10
|
+
* renders nothing. Remote, Drizzle, and form packages interpret it and attach
|
|
11
|
+
* what they need as `foldkit-metadata`.
|
|
12
|
+
*/
|
|
13
|
+
const EntityTypeId = Symbol.for("foldkit-entity/Entity");
|
|
14
|
+
const SelectionTypeId = Symbol.for("foldkit-entity/Selection");
|
|
15
|
+
const SelectionPageTypeId = Symbol.for("foldkit-entity/SelectionPage");
|
|
16
|
+
const isSelectionPage = (value) => typeof value === "object" && value !== null && SelectionPageTypeId in value;
|
|
17
|
+
const isSelection = (value) => typeof value === "object" && value !== null && SelectionTypeId in value;
|
|
18
|
+
const unmapped = Object.freeze({ _tag: "Unmapped" });
|
|
19
|
+
const EntityProto = {
|
|
20
|
+
[EntityTypeId]: EntityTypeId,
|
|
21
|
+
pipe() {
|
|
22
|
+
return Pipeable.pipeArguments(this, arguments);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
const make = (parts) => Object.freeze(Object.assign(Object.create(EntityProto), parts, {
|
|
26
|
+
name: parts.identity.name,
|
|
27
|
+
fields: Object.freeze(parts.fields),
|
|
28
|
+
relations: Object.freeze(parts.relations),
|
|
29
|
+
derived: Object.freeze(parts.derived),
|
|
30
|
+
members: Object.freeze({
|
|
31
|
+
...parts.fields,
|
|
32
|
+
...parts.relations,
|
|
33
|
+
...parts.derived
|
|
34
|
+
})
|
|
35
|
+
}));
|
|
36
|
+
const isSameEntity = (left, right) => left.identity.token === right.identity.token;
|
|
37
|
+
const fail = (entity, message) => {
|
|
38
|
+
throw new Error(`Entity "${entity.name}": ${message}`);
|
|
39
|
+
};
|
|
40
|
+
const isEntity = (value) => typeof value === "object" && value !== null && EntityTypeId in value;
|
|
41
|
+
const kindName = {
|
|
42
|
+
Field: "field",
|
|
43
|
+
Relation: "relation",
|
|
44
|
+
Derived: "derived member"
|
|
45
|
+
};
|
|
46
|
+
const kindOf = (entity, key) => {
|
|
47
|
+
const member = entity.members[key];
|
|
48
|
+
return member && kindName[member._tag];
|
|
49
|
+
};
|
|
50
|
+
const assertFree = (entity, keys, adding) => {
|
|
51
|
+
for (const key of keys) {
|
|
52
|
+
const kind = kindOf(entity, key);
|
|
53
|
+
if (kind !== void 0) throw new Error(`Entity "${entity.name}": cannot add ${adding} "${key}", it is already a ${kind}`);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
const mapValues = (record, f) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, f(value, key)]));
|
|
57
|
+
const Entity = {
|
|
58
|
+
/** Declares an Entity from its intrinsic fields. Each call is a new identity. */
|
|
59
|
+
define: (name, schema) => {
|
|
60
|
+
const identity = Object.freeze({
|
|
61
|
+
name,
|
|
62
|
+
token: Symbol(name)
|
|
63
|
+
});
|
|
64
|
+
return make({
|
|
65
|
+
identity,
|
|
66
|
+
schema,
|
|
67
|
+
fields: mapValues(schema.fields, (fieldSchema, key) => Object.freeze({
|
|
68
|
+
_tag: "Field",
|
|
69
|
+
owner: identity,
|
|
70
|
+
key,
|
|
71
|
+
schema: fieldSchema,
|
|
72
|
+
metadata: Metadata.empty
|
|
73
|
+
})),
|
|
74
|
+
relations: {},
|
|
75
|
+
derived: {},
|
|
76
|
+
metadata: Metadata.empty
|
|
77
|
+
});
|
|
78
|
+
},
|
|
79
|
+
/**
|
|
80
|
+
* Declares the relations between a set of Entities in one step, and returns
|
|
81
|
+
* them related. One step, because Entities that point at each other cannot
|
|
82
|
+
* each be declared in terms of the other.
|
|
83
|
+
*/
|
|
84
|
+
relate: (entities, relations) => {
|
|
85
|
+
const keyByToken = /* @__PURE__ */ new Map();
|
|
86
|
+
for (const [key, entity] of Object.entries(entities)) {
|
|
87
|
+
if (!isEntity(entity)) throw new Error(`Entity.relate: "${key}" is not an Entity`);
|
|
88
|
+
const earlier = keyByToken.get(entity.identity.token);
|
|
89
|
+
if (earlier !== void 0) throw new Error(`Entity.relate: "${earlier}" and "${key}" are the same Entity`);
|
|
90
|
+
keyByToken.set(entity.identity.token, key);
|
|
91
|
+
}
|
|
92
|
+
const given = relations;
|
|
93
|
+
for (const owner of Object.keys(given)) if (!(owner in entities)) throw new Error(`Entity.relate: relations given for "${owner}", which is not being related`);
|
|
94
|
+
const related = {};
|
|
95
|
+
for (const [ownerKey, entity] of Object.entries(entities)) {
|
|
96
|
+
const specs = given[ownerKey] ?? {};
|
|
97
|
+
assertFree(entity, Object.keys(specs), "relation");
|
|
98
|
+
const added = mapValues(specs, (spec, key) => {
|
|
99
|
+
const targetKey = isEntity(spec.target) ? keyByToken.get(spec.target.identity.token) : void 0;
|
|
100
|
+
if (targetKey === void 0) throw new Error(`Entity "${entity.name}": relation "${key}" targets an Entity that is not being related`);
|
|
101
|
+
return Object.freeze({
|
|
102
|
+
_tag: "Relation",
|
|
103
|
+
owner: entity.identity,
|
|
104
|
+
key,
|
|
105
|
+
target: () => related[targetKey],
|
|
106
|
+
cardinality: spec.cardinality,
|
|
107
|
+
optional: spec.optional,
|
|
108
|
+
metadata: Metadata.empty
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
related[ownerKey] = make({
|
|
112
|
+
...entity,
|
|
113
|
+
relations: {
|
|
114
|
+
...entity.relations,
|
|
115
|
+
...added
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
return Object.freeze(related);
|
|
120
|
+
},
|
|
121
|
+
/**
|
|
122
|
+
* Selects members of an Entity and assembles the schema of the result. A
|
|
123
|
+
* relation selected with `true` yields an `EntityRef`; with a Selection of its
|
|
124
|
+
* target, that Selection's value. `many` yields an array, an optional `one`
|
|
125
|
+
* is nullable.
|
|
126
|
+
*/
|
|
127
|
+
select: (entity, spec) => {
|
|
128
|
+
const members = entity.members;
|
|
129
|
+
const fields = mapValues(spec, (selected, key) => {
|
|
130
|
+
const member = members[key];
|
|
131
|
+
if (member === void 0) throw new Error(`Entity "${entity.name}": cannot select "${key}", it is not a member`);
|
|
132
|
+
if (member._tag !== "Relation") {
|
|
133
|
+
if (selected !== true) throw new Error(`Entity "${entity.name}": "${key}" is a ${kindName[member._tag]}, select it with true`);
|
|
134
|
+
return member.schema;
|
|
135
|
+
}
|
|
136
|
+
const target = member.target();
|
|
137
|
+
if (isSelectionPage(selected)) {
|
|
138
|
+
if (member.cardinality !== "many") throw new Error(`Entity "${entity.name}": "${key}" is one ${target.name}, so it has no pages`);
|
|
139
|
+
if (!isSameEntity(selected.selection.entity, target)) throw new Error(`Entity "${entity.name}": "${key}" pages a Selection of ${target.name}`);
|
|
140
|
+
return Schema.Struct({
|
|
141
|
+
items: Schema.Array(selected.selection.schema),
|
|
142
|
+
hasNext: Schema.Boolean,
|
|
143
|
+
hasPrevious: Schema.Boolean
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
let item;
|
|
147
|
+
if (selected === true) item = Schema.Struct({
|
|
148
|
+
entity: Schema.Literal(target.name),
|
|
149
|
+
id: Schema.String
|
|
150
|
+
});
|
|
151
|
+
else if (isSelection(selected) && isSameEntity(selected.entity, target)) item = selected.schema;
|
|
152
|
+
else throw new Error(`Entity "${entity.name}": "${key}" takes true or a Selection of ${target.name}`);
|
|
153
|
+
return member.cardinality === "many" ? Schema.Array(item) : member.optional ? Schema.NullOr(item) : item;
|
|
154
|
+
});
|
|
155
|
+
return Object.freeze({
|
|
156
|
+
[SelectionTypeId]: SelectionTypeId,
|
|
157
|
+
entity,
|
|
158
|
+
members: spec,
|
|
159
|
+
schema: Schema.Struct(fields)
|
|
160
|
+
});
|
|
161
|
+
},
|
|
162
|
+
/**
|
|
163
|
+
* 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 `Page`
|
|
165
|
+
* of the Selection's values. Reading on from a cursor is another window.
|
|
166
|
+
*/
|
|
167
|
+
page: (selection, window) => {
|
|
168
|
+
const sides = [window.first, window.last].filter((size) => size !== void 0);
|
|
169
|
+
if (sides.length !== 1 || !sides.every((size) => Number.isInteger(size) && size >= 0)) throw new Error(`Entity.page: a window of ${selection.entity.name} takes first or last, a non-negative integer`);
|
|
170
|
+
if (window.first !== void 0 && window.before !== void 0 || window.last !== void 0 && window.after !== void 0) throw new Error(`Entity.page: a window of ${selection.entity.name} reads first after a cursor, or last before one`);
|
|
171
|
+
return Object.freeze({
|
|
172
|
+
[SelectionPageTypeId]: SelectionPageTypeId,
|
|
173
|
+
selection,
|
|
174
|
+
window
|
|
175
|
+
});
|
|
176
|
+
},
|
|
177
|
+
/** Adds readable members that are not part of `entity.schema`. */
|
|
178
|
+
derived: (specs) => (entity) => {
|
|
179
|
+
assertFree(entity, Object.keys(specs), "derived member");
|
|
180
|
+
const added = mapValues(specs, (spec, key) => Object.freeze({
|
|
181
|
+
_tag: "Derived",
|
|
182
|
+
owner: entity.identity,
|
|
183
|
+
key,
|
|
184
|
+
schema: spec.schema,
|
|
185
|
+
metadata: Metadata.empty
|
|
186
|
+
}));
|
|
187
|
+
return make({
|
|
188
|
+
...entity,
|
|
189
|
+
derived: {
|
|
190
|
+
...entity.derived,
|
|
191
|
+
...added
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
},
|
|
195
|
+
/** Attaches an interpreter's metadata to the Entity itself. */
|
|
196
|
+
annotate: (metadata) => (entity) => make({
|
|
197
|
+
...entity,
|
|
198
|
+
metadata: Metadata.combine([entity.metadata, metadata])
|
|
199
|
+
}),
|
|
200
|
+
/** Attaches an interpreter's metadata to members, by key. */
|
|
201
|
+
annotateMembers: (metadata) => (entity) => {
|
|
202
|
+
const given = metadata;
|
|
203
|
+
for (const key of Object.keys(given)) if (kindOf(entity, key) === void 0) throw new Error(`Entity "${entity.name}": cannot annotate "${key}", it is not a member`);
|
|
204
|
+
const annotate = (members) => mapValues(members, (member, key) => {
|
|
205
|
+
const extra = given[key];
|
|
206
|
+
return extra === void 0 ? member : Object.freeze({
|
|
207
|
+
...member,
|
|
208
|
+
metadata: Metadata.combine([member.metadata, extra])
|
|
209
|
+
});
|
|
210
|
+
});
|
|
211
|
+
return make({
|
|
212
|
+
...entity,
|
|
213
|
+
fields: annotate(entity.fields),
|
|
214
|
+
relations: annotate(entity.relations),
|
|
215
|
+
derived: annotate(entity.derived)
|
|
216
|
+
});
|
|
217
|
+
},
|
|
218
|
+
/**
|
|
219
|
+
* Reads an operation's input schema against an Entity. A key that names a
|
|
220
|
+
* field maps to it; any other key is mapped explicitly, to a Field, to
|
|
221
|
+
* `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred
|
|
222
|
+
* from a naming convention such as `authorId`.
|
|
223
|
+
*/
|
|
224
|
+
input: (entity, schema, ...mapping) => {
|
|
225
|
+
const given = mapping[0] ?? {};
|
|
226
|
+
for (const key of Object.keys(given)) if (!(key in schema.fields)) throw new Error(`Entity "${entity.name}": "${key}" is mapped but is not a key of the input`);
|
|
227
|
+
const fields = entity.fields;
|
|
228
|
+
const members = mapValues(schema.fields, (_, key) => {
|
|
229
|
+
const member = given[key] ?? fields[key] ?? fail(entity, `input key "${key}" names no field; map it to a member or Entity.unmapped`);
|
|
230
|
+
const owned = member._tag === "Field" ? member : member._tag === "RelationInput" || member._tag === "NestedInput" ? member.relation : member._tag === "Unmapped" ? void 0 : fail(entity, `input key "${key}" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`);
|
|
231
|
+
if (owned !== void 0 && owned.owner.token !== entity.identity.token) fail(entity, `input key "${key}" is mapped to a member of "${owned.owner.name}"`);
|
|
232
|
+
if (member._tag === "NestedInput" && !isSameEntity(member.input.entity, member.relation.target())) fail(entity, `input key "${key}" nests an input of "${member.input.entity.name}", but "${member.relation.key}" is of "${member.relation.target().name}"`);
|
|
233
|
+
return member;
|
|
234
|
+
});
|
|
235
|
+
return Object.freeze({
|
|
236
|
+
entity,
|
|
237
|
+
schema,
|
|
238
|
+
members: Object.freeze(members)
|
|
239
|
+
});
|
|
240
|
+
},
|
|
241
|
+
/** For an input key that is about the operation rather than the Entity. */
|
|
242
|
+
unmapped,
|
|
243
|
+
/**
|
|
244
|
+
* The Selection of every member an input writes, with each relation as refs:
|
|
245
|
+
* what an edit screen loads before it shows the input's current values.
|
|
246
|
+
*/
|
|
247
|
+
selectFor: (input) => {
|
|
248
|
+
const members = input.members;
|
|
249
|
+
const spec = Object.fromEntries(Object.values(members).flatMap((member) => member._tag === "Field" ? [[member.key, true]] : member._tag === "RelationInput" ? [[member.relation.key, true]] : member._tag === "NestedInput" ? [[member.relation.key, Entity.selectFor(member.input)]] : []));
|
|
250
|
+
return Entity.select(input.entity, spec);
|
|
251
|
+
},
|
|
252
|
+
/**
|
|
253
|
+
* The input values that reproduce `value`, a value read through `selectFor`
|
|
254
|
+
* (or any Selection with those members): a field as it is, a relation as the
|
|
255
|
+
* id or ids of its refs. A key whose member `value` lacks is left out, as is
|
|
256
|
+
* an unmapped key, which the Entity knows nothing about.
|
|
257
|
+
*/
|
|
258
|
+
valuesFor: (input, value) => {
|
|
259
|
+
const members = input.members;
|
|
260
|
+
const idOf = (held) => held === null ? null : typeof held === "object" && "id" in held ? held.id : typeof held === "string" ? held : void 0;
|
|
261
|
+
const entries = Object.entries(members).flatMap(([key, member]) => {
|
|
262
|
+
if (member._tag === "Unmapped") return [];
|
|
263
|
+
const written = member._tag === "Field" ? member.key : member.relation.key;
|
|
264
|
+
if (!(written in value)) return [];
|
|
265
|
+
const read = value[written];
|
|
266
|
+
if (member._tag === "Field") return [[key, read]];
|
|
267
|
+
if (member._tag === "NestedInput") {
|
|
268
|
+
const nested = (held) => typeof held === "object" && held !== null ? Entity.valuesFor(member.input, held) : null;
|
|
269
|
+
return [[key, Array.isArray(read) ? read.map(nested) : nested(read)]];
|
|
270
|
+
}
|
|
271
|
+
const ids = Array.isArray(read) ? read.map(idOf) : idOf(read);
|
|
272
|
+
return (Array.isArray(ids) ? !ids.includes(void 0) : ids !== void 0) ? [[key, ids]] : [];
|
|
273
|
+
});
|
|
274
|
+
return Object.fromEntries(entries);
|
|
275
|
+
},
|
|
276
|
+
is: isEntity,
|
|
277
|
+
/** True when both descriptors are versions of one Entity. */
|
|
278
|
+
same: isSameEntity
|
|
279
|
+
};
|
|
280
|
+
function one(target, options) {
|
|
281
|
+
return {
|
|
282
|
+
target,
|
|
283
|
+
cardinality: "one",
|
|
284
|
+
optional: options?.optional ?? false
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
/** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */
|
|
288
|
+
const Relation = {
|
|
289
|
+
one,
|
|
290
|
+
/** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */
|
|
291
|
+
input: (relation) => Object.freeze({
|
|
292
|
+
_tag: "RelationInput",
|
|
293
|
+
relation
|
|
294
|
+
}),
|
|
295
|
+
/**
|
|
296
|
+
* For `Entity.input`: the input key holds the relation's target itself, written
|
|
297
|
+
* through `input`, an `Entity.input` of the target. A `many` holds a list.
|
|
298
|
+
*/
|
|
299
|
+
nested: (relation, input) => Object.freeze({
|
|
300
|
+
_tag: "NestedInput",
|
|
301
|
+
relation,
|
|
302
|
+
input
|
|
303
|
+
}),
|
|
304
|
+
many: (target) => ({
|
|
305
|
+
target,
|
|
306
|
+
cardinality: "many",
|
|
307
|
+
optional: false
|
|
308
|
+
})
|
|
309
|
+
};
|
|
310
|
+
const Derived = { make: (schema) => ({ schema }) };
|
|
311
|
+
//#endregion
|
|
312
|
+
export { Derived, Entity, EntityTypeId, Relation, SelectionPageTypeId, SelectionTypeId };
|
|
313
|
+
|
|
314
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +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;AAoD3F,MAAM,mBAAmB,UACvB,OAAO,UAAU,YAAY,UAAU,QAAQ,uBAAuB;AAExE,MAAM,eAAe,UACnB,OAAO,UAAU,YAAY,UAAU,QAAQ,mBAAmB;AAoJpE,MAAM,WAAqB,OAAO,OAAO,EAAE,MAAM,WAAW,CAAC;AAW7D,MAAM,cAAc;EACjB,eAAe;CAChB,OAAO;EACL,OAAO,SAAS,cAAc,MAAM,SAAS;CAC/C;AACF;AAEA,MAAM,QAAQ,UACZ,OAAO,OACL,OAAO,OAAO,OAAO,OAAO,WAAW,GAAG,OAAO;CAC/C,MAAM,MAAM,SAAS;CACrB,QAAQ,OAAO,OAAO,MAAM,MAAM;C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M,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"}
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "foldkit-entity",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Domain structure for Foldkit Plus: an Entity's fields, relations, and derived members as typed values, and Selections of them.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"foldkit",
|
|
7
|
+
"effect",
|
|
8
|
+
"entity",
|
|
9
|
+
"schema",
|
|
10
|
+
"typescript"
|
|
11
|
+
],
|
|
12
|
+
"type": "module",
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"publishConfig": {
|
|
15
|
+
"access": "public"
|
|
16
|
+
},
|
|
17
|
+
"author": "Patrick Glenn <doeixd@gmail.com>",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/doeixd/foldkit-plus.git",
|
|
21
|
+
"directory": "packages/entity"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://github.com/doeixd/foldkit-plus/tree/main/packages/entity#readme",
|
|
24
|
+
"bugs": {
|
|
25
|
+
"url": "https://github.com/doeixd/foldkit-plus/issues"
|
|
26
|
+
},
|
|
27
|
+
"sideEffects": false,
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./dist/index.d.mts",
|
|
31
|
+
"import": "./dist/index.mjs"
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"files": [
|
|
35
|
+
"dist",
|
|
36
|
+
"README.md",
|
|
37
|
+
"LICENSE"
|
|
38
|
+
],
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"foldkit-metadata": "0.1.0"
|
|
41
|
+
},
|
|
42
|
+
"peerDependencies": {
|
|
43
|
+
"effect": "^4.0.0-rc.112"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"effect": "4.0.0-rc.112",
|
|
47
|
+
"tsdown": "^0.23.0",
|
|
48
|
+
"typescript": "5.9.3"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"build": "tsdown",
|
|
52
|
+
"typecheck": "tsc -b"
|
|
53
|
+
}
|
|
54
|
+
}
|