foldkit-entity 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -3
- package/dist/index.d.mts +34 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +58 -17
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -55,7 +55,7 @@ pnpm add effect foldkit-entity
|
|
|
55
55
|
|
|
56
56
|
```ts
|
|
57
57
|
import { Schema } from 'effect'
|
|
58
|
-
import { Entity } from 'foldkit-entity'
|
|
58
|
+
import { Entity, type Selected } from 'foldkit-entity'
|
|
59
59
|
|
|
60
60
|
const Task = Entity.define('Task', Schema.Struct({
|
|
61
61
|
id: Schema.String,
|
|
@@ -63,7 +63,7 @@ const Task = Entity.define('Task', Schema.Struct({
|
|
|
63
63
|
done: Schema.Boolean,
|
|
64
64
|
}))
|
|
65
65
|
const TaskTitle = Entity.select(Task, { id: true, title: true })
|
|
66
|
-
type TaskTitle = typeof TaskTitle
|
|
66
|
+
type TaskTitle = Selected<typeof TaskTitle> // the value it reads
|
|
67
67
|
const value: TaskTitle = { id: 't1', title: 'Read the guide' }
|
|
68
68
|
```
|
|
69
69
|
|
|
@@ -189,7 +189,7 @@ const PostRow = Entity.select(Blog.Post, {
|
|
|
189
189
|
comments: true,
|
|
190
190
|
})
|
|
191
191
|
|
|
192
|
-
PostRow
|
|
192
|
+
type PostRow = Selected<typeof PostRow>
|
|
193
193
|
// {
|
|
194
194
|
// title: string
|
|
195
195
|
// commentCount: number
|
|
@@ -348,6 +348,25 @@ Entity.same(CmsPost, Blog.Post) // true: the metadata changed, the entity did no
|
|
|
348
348
|
|
|
349
349
|
Annotating again combines with what is there, using the key's own `merge`.
|
|
350
350
|
|
|
351
|
+
### A schema's own words
|
|
352
|
+
|
|
353
|
+
A label or a help text written on a schema (`annotate({ title, description })`)
|
|
354
|
+
is read with `Words.of(schema)`, which gives each as an `Option`. Under Effect 4 a
|
|
355
|
+
schema with checks resolves to its **last check's** annotations, which say what
|
|
356
|
+
the check expects and carry no title, so
|
|
357
|
+
`Schema.String.annotate({ title: 'Name' }).check(Schema.isMinLength(1))` resolved
|
|
358
|
+
directly has no title. `Words.of` falls back to the schema's own annotations. A
|
|
359
|
+
form's labels, Crud's columns and the page Builder's inspector read words
|
|
360
|
+
through it.
|
|
361
|
+
|
|
362
|
+
```ts
|
|
363
|
+
import { Schema } from 'effect'
|
|
364
|
+
import { Words } from 'foldkit-entity'
|
|
365
|
+
|
|
366
|
+
Words.of(Schema.String.annotate({ title: 'Name' }).check(Schema.isMinLength(1))).title
|
|
367
|
+
// Option.some('Name')
|
|
368
|
+
```
|
|
369
|
+
|
|
351
370
|
## Saying something about a row: `Expr`
|
|
352
371
|
|
|
353
372
|
An Entity says what a domain has. An `Expr` says something about one row of it,
|
|
@@ -531,6 +550,8 @@ from queries, not from what a database could express.
|
|
|
531
550
|
| `Entity.annotate(metadata)` | Pipe step attaching metadata to the Entity. |
|
|
532
551
|
| `Entity.annotateMembers({ key: metadata })` | Pipe step attaching metadata to members by key. |
|
|
533
552
|
| `Entity.same(a, b)` | Whether two descriptors are versions of one Entity. |
|
|
553
|
+
| `Selected<typeof selection>` | Type: the value a Selection reads (its `schema`'s `Type`). |
|
|
554
|
+
| `Words.of(schema)` | A schema's `title` and `description`, each an `Option`, including a title given before a check. |
|
|
534
555
|
| `Entity.is(value)` | Whether a value is an Entity descriptor. |
|
|
535
556
|
| `Expr.eq(left, right)` | Two values are the same; a field or a plain value on either side is coerced, and a predicate may stand where a boolean is wanted. |
|
|
536
557
|
| `Expr.isNull(field)` / `Expr.isNotNull(field)` | Whether a value is absent; one node, with the answer absence gives flipped. |
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Pipeable, Schema } from "effect";
|
|
1
|
+
import { Option, Pipeable, Schema, SchemaAST } from "effect";
|
|
2
2
|
import { Metadata } from "foldkit-metadata";
|
|
3
3
|
//#region src/expr.d.ts
|
|
4
4
|
/** A constant the query was written with. */
|
|
@@ -268,6 +268,37 @@ export declare const Query: {
|
|
|
268
268
|
show: (self: AnyQuery) => string;
|
|
269
269
|
};
|
|
270
270
|
//#endregion
|
|
271
|
+
//#region src/words.d.ts
|
|
272
|
+
/** What a schema says of itself to a person: its `title` and `description`. */
|
|
273
|
+
export interface SchemaWords {
|
|
274
|
+
readonly title: Option.Option<string>;
|
|
275
|
+
readonly description: Option.Option<string>;
|
|
276
|
+
}
|
|
277
|
+
export declare const Words: {
|
|
278
|
+
/**
|
|
279
|
+
* A schema's words, as a label and its help text. Under Effect 4 a checked
|
|
280
|
+
* schema resolves to its last check's annotations, which say what the check
|
|
281
|
+
* expects and carry no `title`, so a title given before the check is read from
|
|
282
|
+
* the schema's own annotations. Read words through this, never through
|
|
283
|
+
* `Schema.resolveAnnotations` directly.
|
|
284
|
+
*/
|
|
285
|
+
of: (schema: Schema.Top) => SchemaWords;
|
|
286
|
+
};
|
|
287
|
+
//#endregion
|
|
288
|
+
//#region src/shape.d.ts
|
|
289
|
+
/** What a schema's AST holds, read through Effect's own guards. */
|
|
290
|
+
export declare const SchemaShape: {
|
|
291
|
+
/** True for the `null` and `undefined` members that make a schema optional. */
|
|
292
|
+
isNullish: (ast: SchemaAST.AST) => boolean;
|
|
293
|
+
/**
|
|
294
|
+
* The members of a schema with `null` and `undefined` set aside, so optional
|
|
295
|
+
* text is still text; a schema that is not a union is its one member.
|
|
296
|
+
*/
|
|
297
|
+
present: (ast: SchemaAST.AST) => ReadonlyArray<SchemaAST.AST>;
|
|
298
|
+
/** True when every value the schema admits is a string. */
|
|
299
|
+
isText: (ast: SchemaAST.AST) => boolean;
|
|
300
|
+
};
|
|
301
|
+
//#endregion
|
|
271
302
|
//#region src/evaluate.d.ts
|
|
272
303
|
/** A row as this interpreter reads one: values by field key. */
|
|
273
304
|
export type Row = Readonly<Record<string, unknown>>;
|
|
@@ -435,6 +466,8 @@ export interface Selection<Name extends string, Members, S extends Schema.Constr
|
|
|
435
466
|
readonly schema: S;
|
|
436
467
|
}
|
|
437
468
|
type AnySelection<Name extends string = string> = Selection<Name, any, any>;
|
|
469
|
+
/** The value a Selection reads: `Selected<typeof PostCard>` is one card's fields. */
|
|
470
|
+
export type Selected<S extends Selection<string, unknown, Schema.Constraint>> = S['schema']['Type'];
|
|
438
471
|
/** `true` for any member; a relation also takes a Selection of its target. */
|
|
439
472
|
/**
|
|
440
473
|
* Which part of a `many` relation to read: the first or last so many, from a
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/expr.ts","../src/evaluate.ts","../src/index.ts"],"mappings":";;;;iBAiBiB,YAAY;WAClB;WACA,OAAO;;;;;;iBAOD,UAAU;WAChB;WACA,OAAO;WACP;WACA,QAAQ,OAAO,MAAM;;;;;;;;iBASf,UAAU;WAChB;WACA;WACA,QAAQ,OAAO,MAAM;;;YAIpB,KAAK,KAAK,YAAY,KAAK,UAAU,KAAK,UAAU;;YAGpD,UAAU;;;;;;;;;YAUV,YAAY,cAAc,gBAAgB;;iBAGrC;WACN;WACA,MAAM;WACN,OAAO;;;;;;;iBAQD;WACN;WACA,SAAS;WACT;;;;;;;iBAQM;WACN;WACA,OAAO;WACP,QAAQ;;;;;;;;YASP,aAAa,UAAU;;KAG9B,QAAQ,KAAK,4BAA4B,OAAO,cAAc,KAAK,KAAK;;YAGjE,QAAQ,KAClB,UAAU,kCAAkC,KACxC,OAAO,OAAO,KAAK,KACnB,UAAU,sBAER,UAAU,WAAW,KACnB;;;;;;;;;;;;;;;;;;;;;YAuBE,cACR,4BAA4B,OAAO,aAAa,OAAO,uCACvD,eACA;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/expr.ts","../src/words.ts","../src/shape.ts","../src/evaluate.ts","../src/index.ts"],"mappings":";;;;iBAiBiB,YAAY;WAClB;WACA,OAA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AA,UAAU,WAAW,eAAe,OAAO,OAAO,QAAQ,SAAO,OACpE,YAAY,GAAG,QAAQ,UAAQ,OAC/B,SAAS,6BACf,QAAQ,OAAO,OAAO,KAAK;EAtXP,KAAA,mBAAU,SAAS;;EAPhB,OAAA,MAAA,WAAS,OAAS;;iBAwarC,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
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
|
-
import { Pipeable, Schema } from "effect";
|
|
1
|
+
import { Option, Pipeable, Schema, SchemaAST } from "effect";
|
|
2
2
|
import { Metadata } from "foldkit-metadata";
|
|
3
|
+
//#region src/shape.ts
|
|
4
|
+
const isNullish = (ast) => SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast);
|
|
5
|
+
const isText = (ast) => SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal === "string" || SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText);
|
|
6
|
+
/** What a schema's AST holds, read through Effect's own guards. */
|
|
7
|
+
const SchemaShape = {
|
|
8
|
+
/** True for the `null` and `undefined` members that make a schema optional. */
|
|
9
|
+
isNullish,
|
|
10
|
+
/**
|
|
11
|
+
* The members of a schema with `null` and `undefined` set aside, so optional
|
|
12
|
+
* text is still text; a schema that is not a union is its one member.
|
|
13
|
+
*/
|
|
14
|
+
present: (ast) => SchemaAST.isUnion(ast) ? ast.types.filter((member) => !isNullish(member)) : [ast],
|
|
15
|
+
/** True when every value the schema admits is a string. */
|
|
16
|
+
isText
|
|
17
|
+
};
|
|
18
|
+
//#endregion
|
|
3
19
|
//#region src/expr.ts
|
|
4
20
|
/**
|
|
5
21
|
* `Expr` — a query's scalar computations as typed values.
|
|
@@ -14,7 +30,7 @@ import { Metadata } from "foldkit-metadata";
|
|
|
14
30
|
* operation here is one a real query in this repository needs; the set grows
|
|
15
31
|
* from queries, not from what a database could express.
|
|
16
32
|
*/
|
|
17
|
-
const tagOf = (value) => typeof value === "object" && value !== null ? value._tag : void 0;
|
|
33
|
+
const tagOf = (value) => typeof value === "object" && value !== null && "_tag" in value ? value._tag : void 0;
|
|
18
34
|
/**
|
|
19
35
|
* An Entity's field and a `FieldExpr` are the same three members under the same
|
|
20
36
|
* tag — the Entity's carries `metadata` besides — so this reads either and is
|
|
@@ -319,6 +335,25 @@ const showExpr = (node) => {
|
|
|
319
335
|
};
|
|
320
336
|
const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
|
|
321
337
|
//#endregion
|
|
338
|
+
//#region src/words.ts
|
|
339
|
+
const text = (value) => typeof value === "string" ? Option.some(value) : Option.none();
|
|
340
|
+
const Words = {
|
|
341
|
+
/**
|
|
342
|
+
* A schema's words, as a label and its help text. Under Effect 4 a checked
|
|
343
|
+
* schema resolves to its last check's annotations, which say what the check
|
|
344
|
+
* expects and carry no `title`, so a title given before the check is read from
|
|
345
|
+
* the schema's own annotations. Read words through this, never through
|
|
346
|
+
* `Schema.resolveAnnotations` directly.
|
|
347
|
+
*/
|
|
348
|
+
of: (schema) => {
|
|
349
|
+
const resolved = Schema.resolveAnnotations(schema) ?? {};
|
|
350
|
+
const own = schema.ast.annotations ?? {};
|
|
351
|
+
return {
|
|
352
|
+
title: Option.orElse(text(resolved.title), () => text(own["title"])),
|
|
353
|
+
description: Option.orElse(text(resolved.description), () => text(own["description"]))
|
|
354
|
+
};
|
|
355
|
+
} };
|
|
356
|
+
//#endregion
|
|
322
357
|
//#region src/evaluate.ts
|
|
323
358
|
/**
|
|
324
359
|
* The reference interpreter: a query body run over rows already in memory.
|
|
@@ -452,13 +487,12 @@ const evaluate = (body, input, rows) => {
|
|
|
452
487
|
const EntityTypeId = Symbol.for("foldkit-entity/Entity");
|
|
453
488
|
const SelectionTypeId = Symbol.for("foldkit-entity/Selection");
|
|
454
489
|
const SelectionPageTypeId = Symbol.for("foldkit-entity/SelectionPage");
|
|
455
|
-
const isText = (ast) => ast._tag === "String" || ast._tag === "TemplateLiteral" || ast._tag === "Literal" && typeof ast.literal === "string" || ast._tag === "Union" && (ast.types ?? []).length > 0 && (ast.types ?? []).every(isText);
|
|
456
490
|
/** The `id` field's schema when it is text, so a ref's id keeps its brand and its checks; else text. */
|
|
457
491
|
const idSchemaOf = (entity) => {
|
|
458
492
|
const id = entity.fields.id;
|
|
459
493
|
if (id === void 0 || id._tag !== "Field") return Schema.String;
|
|
460
494
|
const type = Schema.toType(id.schema);
|
|
461
|
-
return isText(type.ast) ? type : Schema.String;
|
|
495
|
+
return SchemaShape.isText(type.ast) ? type : Schema.String;
|
|
462
496
|
};
|
|
463
497
|
const isSelectionPage = (value) => typeof value === "object" && value !== null && SelectionPageTypeId in value;
|
|
464
498
|
const isSelection = (value) => typeof value === "object" && value !== null && SelectionTypeId in value;
|
|
@@ -673,12 +707,15 @@ const Entity = {
|
|
|
673
707
|
for (const key of Object.keys(written)) if (!(key in schema.fields)) throw new Error(`Entity "${entity.name}": "${key}" is mapped but is not a key of the input`);
|
|
674
708
|
const named = (key, name) => {
|
|
675
709
|
const member = entity.members[name];
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
710
|
+
switch (member?._tag) {
|
|
711
|
+
case "Field": return member;
|
|
712
|
+
case "Relation": return Object.freeze({
|
|
713
|
+
_tag: "RelationInput",
|
|
714
|
+
relation: member
|
|
715
|
+
});
|
|
716
|
+
case "Derived":
|
|
717
|
+
case void 0: return fail(entity, `input key "${key}" is mapped to "${name}", which names no field or relation`);
|
|
718
|
+
}
|
|
682
719
|
};
|
|
683
720
|
const given = mapValues(written, (member, key) => typeof member === "string" ? named(key, member) : member);
|
|
684
721
|
const fields = entity.fields;
|
|
@@ -726,13 +763,17 @@ const Entity = {
|
|
|
726
763
|
const written = member._tag === "Field" ? member.key : member.relation.key;
|
|
727
764
|
if (!(written in value)) return [];
|
|
728
765
|
const read = value[written];
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
766
|
+
switch (member._tag) {
|
|
767
|
+
case "Field": return [[key, read]];
|
|
768
|
+
case "NestedInput": {
|
|
769
|
+
const nested = (held) => typeof held === "object" && held !== null ? Entity.valuesFor(member.input, held) : null;
|
|
770
|
+
return [[key, Array.isArray(read) ? read.map(nested) : nested(read)]];
|
|
771
|
+
}
|
|
772
|
+
case "RelationInput": {
|
|
773
|
+
const ids = Array.isArray(read) ? read.map(idOf) : idOf(read);
|
|
774
|
+
return (Array.isArray(ids) ? !ids.includes(void 0) : ids !== void 0) ? [[key, ids]] : [];
|
|
775
|
+
}
|
|
733
776
|
}
|
|
734
|
-
const ids = Array.isArray(read) ? read.map(idOf) : idOf(read);
|
|
735
|
-
return (Array.isArray(ids) ? !ids.includes(void 0) : ids !== void 0) ? [[key, ids]] : [];
|
|
736
777
|
});
|
|
737
778
|
return Object.fromEntries(entries);
|
|
738
779
|
},
|
|
@@ -772,6 +813,6 @@ const Relation = {
|
|
|
772
813
|
};
|
|
773
814
|
const Derived = { make: (schema) => ({ schema }) };
|
|
774
815
|
//#endregion
|
|
775
|
-
export { Derived, Entity, EntityTypeId, Expr, Order, Query, QueryEvaluateError, Relation, SelectionPageTypeId, SelectionTypeId, assertSupported, dependenciesOf, evaluate, isPredicate, supported };
|
|
816
|
+
export { Derived, Entity, EntityTypeId, Expr, Order, Query, QueryEvaluateError, Relation, SchemaShape, SelectionPageTypeId, SelectionTypeId, Words, assertSupported, dependenciesOf, evaluate, isPredicate, supported };
|
|
776
817
|
|
|
777
818
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/expr.ts","../src/evaluate.ts","../src/index.ts"],"sourcesContent":["/**\n * `Expr` — a query's scalar computations as typed values.\n *\n * An Entity says what a domain has; an `Expr` says something about one row of\n * it. A field reference, an input placeholder, a literal, and comparisons of\n * those are all immutable data: building one performs no work, reads nothing,\n * and names no database. An interpreter compiles it — `foldkit-remote-drizzle`\n * to SQL, an in-memory evaluator to a predicate over rows.\n *\n * This is deliberately not SQL and deliberately not arbitrary JavaScript. Every\n * operation here is one a real query in this repository needs; the set grows\n * from queries, not from what a database could express.\n */\nimport { Pipeable, Schema } from 'effect'\nimport type { AnyEntity, EntityField, EntityIdentity } from './index.js'\n\n/** A constant the query was written with. */\nexport interface LiteralExpr<T> {\n readonly _tag: 'Literal'\n readonly value: T\n}\n\n/**\n * One field of one Entity. `owner` is the Entity's identity rather than its\n * name, so two Entities defined with the same name are not one column.\n */\nexport interface FieldExpr<T> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<string>\n readonly key: string\n readonly schema: Schema.Codec<T, unknown>\n}\n\n/**\n * A value the query is given when it runs. A definition's body is built once,\n * so inside it an input is this placeholder and never the value: there is\n * nothing yet to branch on, and a query that wants to depend on what was passed\n * says so with an operation over the placeholder.\n */\nexport interface InputExpr<T> {\n readonly _tag: 'Input'\n readonly key: string\n readonly schema: Schema.Codec<T, unknown>\n}\n\n/** A typed scalar: what a comparison compares. */\nexport type Expr<T> = LiteralExpr<T> | FieldExpr<T> | InputExpr<T>\n\n/** Any scalar, for the places that hold operands without caring what they are. */\nexport type AnyExpr = Expr<unknown>\n\n/**\n * `Expr<boolean>`, in the shape the operations that exist can actually take.\n * The design's kernel is all boolean-valued (`eq`, `and`, `isNull`,\n * `contains`, …), so a predicate is its own type rather than a phantom\n * parameter on a general operation node: `Predicate` and `Expr<string>` cannot\n * then be confused, which a structural phantom would allow. A scalar-valued\n * operation, if one is ever needed, joins `Expr` instead.\n */\nexport type Predicate = EqPredicate | NullPredicate | ContainsPredicate\n\n/** Two values are the same. */\nexport interface EqPredicate {\n readonly _tag: 'Eq'\n readonly left: Operandish\n readonly right: Operandish\n}\n\n/**\n * Whether a value is absent. `present` says which answer absence gives, so one\n * node covers `is null` and `is not null` rather than two that differ by a\n * negation nothing else can express.\n */\nexport interface NullPredicate {\n readonly _tag: 'Null'\n readonly operand: AnyExpr\n readonly present: boolean\n}\n\n/**\n * Whether a text value contains another. Containing the empty string is\n * everything, which is what lets a search box with nothing typed in it be the\n * same query as one with something — see `Expr.contains`.\n */\nexport interface ContainsPredicate {\n readonly _tag: 'Contains'\n readonly value: AnyExpr\n readonly search: Operandish\n}\n\n/**\n * Anything an operation can be given: a scalar, or a predicate where a boolean\n * is wanted. `Expr.eq(Expr.isNotNull(archivedAt), input.archived)` is the\n * second case, and it is how a query depends on an input without branching on\n * it.\n */\nexport type Operandish = AnyExpr | Predicate\n\n/** A field, a scalar already built from one, or a predicate used as a boolean. */\ntype Operand<T> = EntityField<string, string, Schema.Constraint> | Expr<T> | Predicate\n\n/** What an operand is worth, so a comparison's other side is checked against it. */\nexport type ValueOf<E> =\n E extends EntityField<string, string, infer S>\n ? Schema.Schema.Type<S>\n : E extends Predicate\n ? boolean\n : E extends Expr<infer T>\n ? T\n : never\n\n/**\n * A field or scalar whose value is text, or absent text.\n *\n * `Expr.contains` is a case-insensitive **text** search that compiles to\n * `lower(column) like lower(?)`. Over a number that is nonsense which reaches\n * the database — SQLite coerces and answers something, Postgres raises — so\n * the operand is constrained here rather than discovered there.\n *\n * Null belongs in the type, because a nullable text column is a real and\n * documented case: a null contains nothing, not even the empty string, so its\n * rows drop out of a search that would otherwise match everything.\n *\n * Written as a **constraint on the type parameter** rather than as a check\n * intersected onto the parameter (the `Invalid` idiom `foldkit-remote` uses for\n * an unregistered descriptor). That idiom compares an already-resolved indexed\n * access; here the check would be a conditional over the type being inferred,\n * and inference falls back to the constraint — whose `Expr<any>` branch makes\n * the check vacuously true, so every operand passes. A constraint cannot be\n * defeated that way.\n */\nexport type TextOperand =\n | EntityField<string, string, Schema.Constraint & Schema.Codec<string | null, any, any, any>>\n | Expr<string>\n | Expr<string | null>\n\nconst tagOf = (value: unknown): unknown =>\n typeof value === 'object' && value !== null\n ? (value as { readonly _tag?: unknown })._tag\n : undefined\n\n/**\n * An Entity's field and a `FieldExpr` are the same three members under the same\n * tag — the Entity's carries `metadata` besides — so this reads either and is\n * idempotent on its own output. Nothing needs to tell them apart, which is\n * better than telling them apart by which extra member happens to be present.\n */\nconst literal = <T>(value: T): LiteralExpr<T> => ({ _tag: 'Literal', value })\n\nconst fieldExpr = (field: EntityField<string, string, Schema.Constraint>): FieldExpr<unknown> => ({\n _tag: 'Field',\n owner: field.owner,\n key: field.key,\n schema: field.schema as unknown as Schema.Codec<unknown, unknown>,\n})\n\nconst predicateTags = new Set(['Eq', 'Null', 'Contains'])\n\n/** Whether a value is a predicate, and so usable where a boolean is wanted. */\nexport const isPredicate = (value: unknown): value is Predicate =>\n predicateTags.has(tagOf(value) as string)\n\n/**\n * A field of either kind becomes a `FieldExpr`, a scalar or a predicate is\n * itself, and anything else is the constant it is.\n */\nconst toOperand = <T>(value: Operand<T> | T): Operandish => {\n const tag = tagOf(value)\n if (tag === 'Field') {\n return fieldExpr(value as EntityField<string, string, Schema.Constraint>)\n }\n if (tag === 'Literal' || tag === 'Input' || predicateTags.has(tag as string)) {\n return value as Operandish\n }\n return literal(value)\n}\n\n/** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */\nconst toExpr = <T>(value: Operand<T> | T, step: string): AnyExpr => {\n const operand = toOperand(value)\n if (isPredicate(operand)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: a predicate is already an answer, so asking this of one is not a question`,\n )\n }\n return operand\n}\n\n/**\n * Every operation the kernel has. An interpreter declares which of them it\n * runs, and a body needing one it does not is refused rather than answered\n * wrongly — see `Query.unsupported`.\n */\nexport type Operation = 'eq' | 'isNull' | 'isNotNull' | 'contains'\n\n/** Which fields and inputs an expression reads, and which operations it uses. */\nexport interface Dependencies {\n /** One entry per distinct field, as `Entity.key`. */\n readonly fields: ReadonlyArray<{ readonly entity: string; readonly key: string }>\n /** One entry per distinct input key. */\n readonly inputs: ReadonlyArray<string>\n /** One entry per distinct operation, so an interpreter can refuse what it cannot run. */\n readonly operations: ReadonlyArray<Operation>\n}\n\nexport const Expr = {\n /** A constant. Comparisons coerce a plain value, so this is rarely written. */\n literal,\n\n /**\n * A value the query is given when it runs. A definition builds these from its\n * `Input` schema; written by hand only when constructing a body directly.\n */\n input: <T>(key: string, schema: Schema.Codec<T, unknown>): InputExpr<T> => ({\n _tag: 'Input',\n key,\n schema,\n }),\n\n /** One field of one Entity, as a scalar. */\n field: <Name extends string, Key extends string, S extends Schema.Constraint>(\n field: EntityField<Name, Key, S>,\n ): FieldExpr<Schema.Schema.Type<S>> => fieldExpr(field) as FieldExpr<Schema.Schema.Type<S>>,\n\n /**\n * Two scalars are the same value. A field or a plain value on either side is\n * coerced, so the common form reads as it means:\n *\n * ```ts\n * Expr.eq(Post.fields.slug, input.slug)\n * Expr.eq(Post.fields.status, 'active')\n * ```\n */\n eq: <L extends Operand<any>>(\n left: L,\n right: ValueOf<L> | Expr<ValueOf<L>> | (boolean extends ValueOf<L> ? Predicate : never),\n ): EqPredicate => ({\n _tag: 'Eq',\n left: toOperand(left),\n right: toOperand(right as never),\n }),\n\n /**\n * Whether a field holds no value. Its opposite is `isNotNull`; both are the\n * one node, because a query asks which of the two it means and nothing here\n * can negate a predicate.\n */\n isNull: <L extends Operand<any>>(operand: L): NullPredicate => ({\n _tag: 'Null',\n operand: toExpr(operand, 'isNull'),\n present: false,\n }),\n\n /** Whether a field holds a value. */\n isNotNull: <L extends Operand<any>>(operand: L): NullPredicate => ({\n _tag: 'Null',\n operand: toExpr(operand, 'isNotNull'),\n present: true,\n }),\n\n /**\n * Whether a text value contains `search`, anywhere in it. Containing the\n * empty string is everything, so a search box with nothing typed in it is the\n * same query as one with something — no branch, and no second query.\n *\n * **Case-insensitive**, which is what a search means, and which has to be\n * said rather than left to the interpreter: SQLite's `like` ignores case and\n * Postgres's does not, so a body that left it open would mean two things.\n * Folding is ASCII-only, because that is what `lower` does in SQLite without\n * ICU.\n *\n * **Over a column that can be null this is not the same as no filter.** A\n * null contains nothing, not even the empty string, so its rows drop out. A\n * nullable column that should match everything on an empty search says so:\n * `Expr.or` does not exist yet, so for now such a column needs its own\n * predicate or a native escape hatch.\n */\n contains: <L extends TextOperand>(\n value: L,\n search: string | Expr<string>,\n ): ContainsPredicate => ({\n _tag: 'Contains',\n value: toExpr(value, 'contains'),\n search: toOperand(search as never),\n }),\n\n /** An expression as readable text; see `showExpr` for what it is and is not. */\n show: (node: Operandish): string => showExpr(node),\n}\n\n/** One term of an ordering: a scalar and the direction to read it in. */\nexport interface OrderTerm {\n readonly direction: 'asc' | 'desc'\n readonly expr: AnyExpr\n}\n\nexport const Order = {\n asc: <E extends Operand<any>>(expr: E): OrderTerm => ({\n direction: 'asc',\n expr: toExpr(expr as never, 'asc'),\n }),\n desc: <E extends Operand<any>>(expr: E): OrderTerm => ({\n direction: 'desc',\n expr: toExpr(expr as never, 'desc'),\n }),\n}\n\nconst walk = (\n node: AnyExpr | Predicate,\n fields: Map<string, { readonly entity: string; readonly key: string }>,\n inputs: Set<string>,\n operations: Set<Operation>,\n): void => {\n switch (node._tag) {\n case 'Literal':\n return\n case 'Field':\n fields.set(`${node.owner.name}.${node.key}`, { entity: node.owner.name, key: node.key })\n return\n case 'Input':\n inputs.add(node.key)\n return\n case 'Eq':\n operations.add('eq')\n walk(node.left, fields, inputs, operations)\n walk(node.right, fields, inputs, operations)\n return\n case 'Null':\n operations.add(node.present ? 'isNotNull' : 'isNull')\n walk(node.operand, fields, inputs, operations)\n return\n case 'Contains':\n operations.add('contains')\n walk(node.value, fields, inputs, operations)\n walk(node.search, fields, inputs, operations)\n return\n }\n}\n\n/**\n * What an expression reads and uses, for the planner and for an interpreter\n * deciding whether it can run this query at all. Distinct entries only, in the\n * order first seen, so the answer is stable enough to assert on.\n */\nexport const dependenciesOf = (\n ...nodes: ReadonlyArray<AnyExpr | Predicate | OrderTerm>\n): Dependencies => {\n const fields = new Map<string, { readonly entity: string; readonly key: string }>()\n const inputs = new Set<string>()\n const operations = new Set<Operation>()\n for (const node of nodes) {\n walk('direction' in node ? node.expr : node, fields, inputs, operations)\n }\n return { fields: [...fields.values()], inputs: [...inputs], operations: [...operations] }\n}\n\n/**\n * Which rows a query is about, as a value: an Entity to read, the predicates\n * every row must satisfy, and the order to read them in. It says nothing about\n * which fields to return — that is a Selection — and nothing about pagination,\n * liveness, or whether absence is an error, which belong to the consumer's read\n * rather than to the relation.\n *\n * Composing one performs no work. `Query.from(Post)` names no table and opens\n * no connection; an interpreter turns the value into a query when something\n * asks it to.\n */\nexport interface Query<E extends AnyEntity> extends Pipeable.Pipeable {\n readonly _tag: 'Query'\n readonly entity: E\n /**\n * Every predicate holds: the list *is* the conjunction. Keeping it a list\n * rather than folding it into one `and` is what makes each `where` a reusable\n * fragment, and it means no `Expr.and` exists until a query needs a\n * conjunction nested inside something else.\n */\n readonly where: ReadonlyArray<Predicate>\n /** In order of significance; a later `orderBy` appends less significant terms. */\n readonly orderBy: ReadonlyArray<OrderTerm>\n}\n\n/** A `Query` over any Entity, for the places that hold one without caring which. */\nexport type AnyQuery = Query<AnyEntity>\n\n/** Every field an expression reads, as the nodes themselves. */\nconst fieldsIn = function* (node: AnyExpr | Predicate): Generator<FieldExpr<unknown>> {\n switch (node._tag) {\n case 'Field':\n yield node\n return\n case 'Literal':\n case 'Input':\n return\n case 'Eq':\n yield* fieldsIn(node.left)\n yield* fieldsIn(node.right)\n return\n case 'Null':\n yield* fieldsIn(node.operand)\n return\n case 'Contains':\n yield* fieldsIn(node.value)\n yield* fieldsIn(node.search)\n return\n }\n}\n\n/**\n * A query reads one Entity, so a predicate or ordering term naming a different\n * one cannot be answered — an interpreter would be asked for a column of a\n * table it was never told to read. Compared by identity, not by name, because\n * two Entities defined with the same name are two Entities.\n */\nconst checkOwnership = (\n step: string,\n what: string,\n entity: AnyEntity,\n nodes: ReadonlyArray<AnyExpr | Predicate | OrderTerm>,\n): void => {\n for (const node of nodes) {\n for (const field of fieldsIn('direction' in node ? node.expr : node)) {\n if (field.owner.token !== entity.identity.token) {\n throw new Error(\n `[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}`,\n )\n }\n }\n }\n}\n\nconst QueryProto = {\n _tag: 'Query' as const,\n pipe() {\n return Pipeable.pipeArguments(this, arguments)\n },\n}\n\nconst query = <E extends AnyEntity>(\n entity: E,\n where: ReadonlyArray<Predicate>,\n orderBy: ReadonlyArray<OrderTerm>,\n): Query<E> =>\n Object.freeze(\n Object.assign(Object.create(QueryProto), {\n entity,\n where: Object.freeze(where),\n orderBy: Object.freeze(orderBy),\n }),\n ) as Query<E>\n\nexport const Query = {\n /** Every row of an Entity: the query each transformation narrows. */\n from: <E extends AnyEntity>(entity: E): Query<E> => query(entity, [], []),\n\n /**\n * Narrows to the rows the predicate holds for. Two `where`s conjoin — the\n * second never replaces the first — so a fragment can be written once and\n * piped into any query over the same Entity:\n *\n * ```ts\n * const published = Query.where(Expr.eq(Post.fields.published, true))\n * Query.from(Post).pipe(published, Query.where(byTitle))\n * ```\n */\n where:\n (...predicates: ReadonlyArray<Predicate>) =>\n <E extends AnyEntity>(self: Query<E>): Query<E> => {\n if (predicates.length === 0) return self\n checkOwnership('where', 'a predicate', self.entity, predicates)\n return query(self.entity, [...self.where, ...predicates], self.orderBy)\n },\n\n /**\n * Reads the rows in this order. Two `orderBy`s append, so an earlier term\n * stays the more significant one and a later call adds a tie-breaker rather\n * than silently winning.\n */\n orderBy:\n (...terms: ReadonlyArray<OrderTerm>) =>\n <E extends AnyEntity>(self: Query<E>): Query<E> => {\n if (terms.length === 0) return self\n checkOwnership('orderBy', 'a term', self.entity, terms)\n return query(self.entity, self.where, [...self.orderBy, ...terms])\n },\n\n /**\n * What the whole query reads: the fields and inputs of every predicate and\n * every ordering term, and the operations it uses.\n */\n dependencies: (self: AnyQuery): Dependencies => dependenciesOf(...self.where, ...self.orderBy),\n\n /**\n * The operations this query needs that `supported` does not list, in the\n * order the query uses them. Empty means an interpreter declaring\n * `supported` can answer it.\n *\n * An interpreter declares what it runs and refuses the rest, rather than\n * ignoring an operation it does not implement — which would answer a\n * different question and say nothing. The refusal is the interpreter's to\n * raise: this only says what is missing, because what to do about it differs\n * between one that compiles at registration and one that runs a body\n * directly.\n *\n * ```ts\n * const missing = Query.unsupported(body, ['eq', 'isNull', 'isNotNull'])\n * if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)\n * ```\n */\n unsupported: (self: AnyQuery, supported: ReadonlyArray<Operation>): ReadonlyArray<Operation> => {\n const runs = new Set(supported)\n return Query.dependencies(self).operations.filter(operation => !runs.has(operation))\n },\n\n /**\n * The whole query as readable text, one clause per line:\n *\n * ```text\n * FROM Post\n * WHERE Post.slug = $slug\n * AND Post.published = true\n * ORDER BY Post.updatedAt DESC\n * ```\n *\n * For an explanation or a diagnostic, never for an interpreter — see\n * `Expr.show`. A query with no `where` or no `orderBy` omits that line rather\n * than printing an empty one, so what is shown is what was written.\n */\n show: (self: AnyQuery): string =>\n [\n `FROM ${self.entity.name}`,\n ...self.where.map(\n (predicate, index) => `${index === 0 ? 'WHERE' : ' AND'} ${Expr.show(predicate)}`,\n ),\n ...(self.orderBy.length === 0\n ? []\n : [\n `ORDER BY ${self.orderBy\n .map(term => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`)\n .join(', ')}`,\n ]),\n ].join('\\n'),\n}\n\n/**\n * An expression as readable text, in the IR's own terms.\n *\n * This is for a human — an explanation, a diagnostic, a test that wants to\n * assert on a whole predicate at once — and deliberately **not** for an\n * interpreter. It is close enough to SQL to read at a glance and unlike it\n * everywhere that matters: an input is `$slug` rather than a bound parameter,\n * `contains` is named rather than rendered as somebody's `like`, and no\n * dialect's escaping or collation is implied. What actually ran is whatever\n * that backend compiled, which is not this.\n *\n * A predicate standing where a value is wanted is parenthesised, because\n * `x is not null = $archived` reads as three operands and is two. A predicate\n * that *is* the whole expression is not: nothing encloses it.\n */\nconst showExpr = (node: AnyExpr | Predicate): string => {\n switch (node._tag) {\n case 'Literal':\n return JSON.stringify(node.value) ?? String(node.value)\n case 'Field':\n return `${node.owner.name}.${node.key}`\n case 'Input':\n return `$${node.key}`\n case 'Eq':\n return `${showOperand(node.left)} = ${showOperand(node.right)}`\n case 'Null':\n return `${showOperand(node.operand)} is ${node.present ? 'not null' : 'null'}`\n case 'Contains':\n return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`\n }\n}\n\nconst showOperand = (node: Operandish): string =>\n isPredicate(node) ? `(${showExpr(node)})` : showExpr(node)\n","/**\n * The reference interpreter: a query body run over rows already in memory.\n *\n * `foldkit-remote-drizzle` compiles a body to SQL. This runs the same body\n * directly, which is what makes \"source-neutral\" a fact rather than a claim —\n * the two are checked against each other over a real database, and a body that\n * means one thing here and another there is a bug in one of them.\n *\n * It is also the interpreter to reach for when there is no database: a test\n * that wants rows, a server assembling a page from values it already holds, or\n * a client judging rows it already has.\n *\n * It lives in `foldkit-entity` because it is the **reference semantics** of the\n * IR this package owns — what §6.0.1 means operationally rather than in prose —\n * and a specification's reference implementation belongs with the\n * specification. The rule that keeps it here: **it may depend on the IR and\n * nothing else.** The moment it wants a Remote concept it has moved to the\n * wrong place and should leave.\n *\n * **It follows SQL, not JavaScript.** Where the two disagree this follows SQL,\n * because SQL is what the other interpreter runs. The important case is null:\n * `null = null` is unknown in SQL and a row is not matched by it, where\n * JavaScript would happily call the two equal.\n */\nimport { Query, isPredicate } from './expr.js'\nimport type { AnyExpr, AnyQuery, Operandish, Operation, OrderTerm, Predicate } from './expr.js'\n\n/** A row as this interpreter reads one: values by field key. */\nexport type Row = Readonly<Record<string, unknown>>\n\nexport class QueryEvaluateError extends Error {\n constructor(message: string) {\n super(`[foldkit-entity] ${message}`)\n this.name = 'QueryEvaluateError'\n }\n}\n\nconst valueOf = (node: AnyExpr, row: Row, input: Row): unknown => {\n switch (node._tag) {\n case 'Field':\n return row[node.key]\n case 'Literal':\n return node.value\n case 'Input':\n return input[node.key]\n }\n}\n\n/** SQL's unknown: neither true nor false, and a row is kept only on true. */\ntype Truth = boolean | 'unknown'\n\nconst isNull = (value: unknown): boolean => value === null || value === undefined\n\n/** A predicate used as a value is its own truth; anything else is its value. */\nconst sideOf = (node: Operandish, row: Row, input: Row): unknown =>\n isPredicate(node) ? truthValue(holds(node, row, input)) : valueOf(node, row, input)\n\n/**\n * A predicate compared as a value. SQL's unknown is null there too, so an\n * unknown compared to anything stays unknown rather than becoming false.\n */\nconst truthValue = (truth: Truth): unknown => (truth === 'unknown' ? null : truth)\n\nconst holds = (node: Predicate, row: Row, input: Row): Truth => {\n switch (node._tag) {\n case 'Eq': {\n const left = sideOf(node.left, row, input)\n const right = sideOf(node.right, row, input)\n // `null = anything` is unknown in SQL, including `null = null`. A row is\n // kept only when a comparison is true, so an unknown drops it either way;\n // saying so explicitly is what keeps this honest about three-valued logic\n // rather than accidentally right about it.\n if (isNull(left) || isNull(right)) return 'unknown'\n return left === right\n }\n case 'Null':\n // The one comparison that is never unknown: asking whether a value is\n // absent always has an answer.\n return isNull(valueOf(node.operand, row, input)) !== node.present\n case 'Contains': {\n const value = valueOf(node.value, row, input)\n const search = sideOf(node.search, row, input)\n // `null like anything` is unknown, which is why an empty search is not\n // the same as no filter over a column that can be null.\n if (isNull(value) || isNull(search)) return 'unknown'\n if (typeof value !== 'string' || typeof search !== 'string') {\n throw new QueryEvaluateError('a containment test was given something that is not text')\n }\n // Case-insensitive, because that is what `Expr.contains` means and what\n // the compiled SQL folds both sides to. Plain `includes` would be\n // case-sensitive here and case-insensitive under SQLite's `like`, which\n // is a body meaning two things.\n return value.toLowerCase().includes(search.toLowerCase())\n }\n }\n}\n\n/** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */\nconst matches = (body: AnyQuery, row: Row, input: Row): boolean =>\n body.where.every(node => holds(node, row, input) === true)\n\nconst compare = (left: unknown, right: unknown, query: string): number => {\n if (typeof left === 'string' && typeof right === 'string') {\n return left < right ? -1 : left > right ? 1 : 0\n }\n if (typeof left === 'number' && typeof right === 'number') return left - right\n if (typeof left === 'boolean' && typeof right === 'boolean') {\n return Number(left) - Number(right)\n }\n throw new QueryEvaluateError(\n `query \"${query}\" orders by values this interpreter cannot compare (${typeof left} and ${typeof right})`,\n )\n}\n\nconst ordered = (rows: ReadonlyArray<Row>, terms: ReadonlyArray<OrderTerm>, query: string) => {\n if (terms.length === 0) return [...rows]\n return [...rows].sort((left, right) => {\n for (const term of terms) {\n if (term.expr._tag !== 'Field') {\n throw new QueryEvaluateError(\n `query \"${query}\" orders by something that is not a field, which this interpreter cannot run yet`,\n )\n }\n const a = left[term.expr.key]\n const b = right[term.expr.key]\n if (isNull(a) || isNull(b)) {\n throw new QueryEvaluateError(\n `query \"${query}\" orders by \"${term.expr.key}\", which is null in a row; where nulls sort is a thing databases disagree about, so it is outside what this interpreter will answer for`,\n )\n }\n const sign = compare(a, b, query)\n if (sign !== 0) return term.direction === 'asc' ? sign : -sign\n }\n return 0\n })\n}\n\n/**\n * The operations this interpreter runs. It is the reference, so this is the\n * whole kernel — but it is declared rather than assumed, because an\n * interpreter that gains an operator and forgets to say so is exactly what\n * `Query.unsupported` exists to catch.\n */\nexport const supported: ReadonlyArray<Operation> = ['eq', 'isNull', 'isNotNull', 'contains']\n\n/**\n * Refuses a body needing an operation this interpreter does not run, rather\n * than skipping it and answering a different question. Called by `evaluate`;\n * call it directly to check a body once instead of on every run.\n */\nexport const assertSupported = (body: AnyQuery): void => {\n const missing = Query.unsupported(body, supported)\n if (missing.length > 0) {\n throw new QueryEvaluateError(\n `this interpreter does not run ${missing.join(', ')}, which query \"${body.entity.name}\" needs`,\n )\n }\n}\n\n/**\n * The rows the body matches, in the order it asks for. Pure: it reads the rows\n * it is given and nothing else.\n *\n * `input` holds the values this run was given, by the keys the body's\n * placeholders were built with — the same record the query would be called\n * with anywhere else.\n */\nexport const evaluate = (\n body: AnyQuery,\n input: Row,\n rows: ReadonlyArray<Row>,\n): ReadonlyArray<Row> => {\n assertSupported(body)\n return ordered(\n rows.filter(row => matches(body, row, input)),\n body.orderBy,\n body.entity.name,\n )\n}\n","/**\n * `foldkit-entity` — domain structure as typed values.\n *\n * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations\n * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable\n * values an interpreter supplies). It describes; it fetches, stores, and\n * renders nothing. Remote, Drizzle, and form packages interpret it and attach\n * what they need as `foldkit-metadata`.\n */\nimport { Pipeable, Schema } from 'effect'\nimport { Metadata } from 'foldkit-metadata'\n\nexport const EntityTypeId: unique symbol = Symbol.for('foldkit-entity/Entity')\nexport type EntityTypeId = typeof EntityTypeId\n\n/**\n * What makes two descriptors the same Entity. A pipe step returns a new\n * descriptor with the same identity, so compare `identity`, never the objects.\n */\nexport interface EntityIdentity<Name extends string> {\n readonly name: Name\n /** Distinguishes two Entities that were defined with the same name. */\n readonly token: symbol\n}\n\n/** An intrinsic value of the Entity: one property of `entity.schema`. */\nexport interface EntityField<Name extends string, Key extends string, S extends Schema.Constraint> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type Cardinality = 'one' | 'many'\n\n/** What `Relation.one` / `Relation.many` return, before `Entity.relate` binds it to an owner. */\nexport interface RelationSpec<\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly target: Target\n readonly cardinality: C\n readonly optional: Optional\n}\n\n/**\n * A navigation edge as its owner sees it: one or many of `target`. How the edge\n * is stored (a foreign key, a join table, a nested document) is the\n * interpreter's concern.\n */\nexport interface EntityRelation<\n Name extends string,\n Key extends string,\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly _tag: 'Relation'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n /** The target as `Entity.relate` returned it, so its own relations can be followed. */\n readonly target: () => Target\n readonly cardinality: C\n readonly optional: Optional\n readonly metadata: Metadata\n}\n\n/** What `Derived.make` returns, before an Entity owns it. */\nexport interface DerivedSpec<S extends Schema.Constraint> {\n readonly schema: S\n}\n\n/**\n * A value consumers may read that is not part of `entity.schema`. It says\n * nothing about how the value is computed; an interpreter supplies it.\n */\nexport interface EntityDerived<\n Name extends string,\n Key extends string,\n S extends Schema.Constraint,\n> {\n readonly _tag: 'Derived'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type EntityMember =\n | EntityField<string, string, Schema.Constraint>\n | EntityRelation<string, string, AnyEntity, Cardinality, boolean>\n | EntityDerived<string, string, Schema.Constraint>\n\nexport type RelationSpecs = Readonly<Record<string, RelationSpec<AnyEntity, Cardinality, boolean>>>\nexport type DerivedSpecs = Readonly<Record<string, DerivedSpec<Schema.Constraint>>>\n\ntype FieldsOf<Name extends string, Fields extends Schema.Struct.Fields> = {\n readonly [K in keyof Fields & string]: EntityField<Name, K, Fields[K]>\n}\ntype RelationsOf<Name extends string, Relations extends RelationSpecs> = {\n readonly [K in keyof Relations & string]: Relations[K] extends RelationSpec<\n infer Target,\n infer C,\n infer Optional\n >\n ? EntityRelation<Name, K, Target, C, Optional>\n : never\n}\ntype DerivedOf<Name extends string, Derived extends DerivedSpecs> = {\n readonly [K in keyof Derived & string]: EntityDerived<Name, K, Derived[K]['schema']>\n}\n\nexport interface Entity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n>\n extends Pipeable.Pipeable {\n readonly [EntityTypeId]: EntityTypeId\n readonly identity: EntityIdentity<Name>\n readonly name: Name\n /** The intrinsic value only: no relations, no derived members. */\n readonly schema: Schema.Struct<Fields>\n readonly fields: FieldsOf<Name, Fields>\n readonly relations: RelationsOf<Name, Relations>\n readonly derived: DerivedOf<Name, Derived>\n /** Every readable member under one namespace; keys never collide. */\n readonly members: FieldsOf<Name, Fields> & RelationsOf<Name, Relations> & DerivedOf<Name, Derived>\n readonly metadata: Metadata\n}\n\nexport type AnyEntity = Entity<string, any, any, any>\n\n/** Unsatisfiable when a new key is already a member, so the pipe step is the error site. */\ntype Free<E extends AnyEntity, New> = keyof New & keyof E['members'] extends never\n ? unknown\n : { readonly alreadyAMember: keyof New & keyof E['members'] }\n\ntype WithDerived<E, New extends DerivedSpecs> =\n E extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R, D & New>\n : never\n\nexport type Entities = Readonly<Record<string, AnyEntity>>\nexport type RelationMap<Es extends Entities> = { readonly [K in keyof Es]?: RelationSpecs }\n\n/** The key in `Es` of the Entity a spec targets, matched by name. */\nexport type TargetKey<Es extends Entities, Target extends AnyEntity> = {\n [K in keyof Es]: [Es[K]['name'], Target['name']] extends [Target['name'], Es[K]['name']]\n ? K\n : never\n}[keyof Es]\n\nexport type RelatedSpecs<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> = {\n readonly [R in keyof Rs[K]]: Rs[K][R] extends RelationSpec<infer Target, infer C, infer Optional>\n ? RelationSpec<Related<Es, Rs, TargetKey<Es, Target>>, C, Optional>\n : never\n}\n\n/**\n * One Entity of an `Entity.relate` result. A relation's target is again a\n * `Related`, so relations can be followed through a cycle; the recursion goes\n * through type arguments, which TypeScript resolves only when asked.\n */\nexport type Related<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> =\n Es[K] extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D>\n : never\n\n/** Marks a relation key that is already a member of its owner, or an owner that is not listed. */\ntype CheckRelations<Es extends Entities, Rs> = {\n readonly [K in keyof Rs]: K extends keyof Es\n ? {\n readonly [R in keyof Rs[K]]: R extends keyof Es[K]['members']\n ? `\"${R & string}\" is already a member of ${Es[K]['name']}`\n : Rs[K][R]\n }\n : 'not one of the entities being related'\n}\n\nexport const SelectionTypeId: unique symbol = Symbol.for('foldkit-entity/Selection')\nexport type SelectionTypeId = typeof SelectionTypeId\n\n/**\n * The schema that identifies one of an Entity: its `id` field when that is text\n * (a plain string, a brand, a pattern), and plain text otherwise. An id is text\n * because a ref travels and is stored as text; an Entity keyed by a number still\n * has refs, and their ids are the number as text.\n */\nexport type IdSchemaOf<E> = E extends {\n readonly fields: { readonly id: { readonly schema: infer S } }\n}\n ? S extends Schema.Constraint\n ? [S['Type']] extends [string]\n ? S\n : Schema.String\n : Schema.String\n : Schema.String\n\n/** What identifies one of an Entity: `IdOf<typeof Blog.Post>` is `PostId` when its `id` field is one. */\nexport type IdOf<E> = IdSchemaOf<E>['Type']\n\n/**\n * What a relation selected with `true` yields: which Entity, and which one. `Id`\n * is the target's own id type, so a ref to an Author cannot be used as a Post's.\n */\nexport interface EntityRef<Name extends string = string, Id extends string = string> {\n readonly entity: Name\n readonly id: Id\n}\n\ntype RefSchema<Target extends AnyEntity> = Schema.Struct<{\n readonly entity: Schema.Literal<Target['name']>\n readonly id: IdSchemaOf<Target>\n}>\n\n/**\n * A view of the Entity graph: which members to read, and the schema of the\n * value that results. It says nothing about where the value comes from.\n */\nexport interface Selection<\n Name extends string,\n Members,\n S extends Schema.Constraint,\n Id extends string = string,\n> {\n readonly [SelectionTypeId]: SelectionTypeId\n /** Type-only: the id type of the Entity selected, so a reader can ask for the right one. Never set. */\n readonly Id?: Id\n readonly entity: Entity<Name, any, any, any>\n /** What was selected, by member key: `true`, or a relation's nested Selection. */\n readonly members: Members\n readonly schema: S\n}\n\ntype AnySelection<Name extends string = string> = Selection<Name, any, any>\n\n/** `true` for any member; a relation also takes a Selection of its target. */\n/**\n * Which part of a `many` relation to read: the first or last so many, from a\n * cursor or from the end. A cursor is whatever the interpreter handed out with an\n * earlier page; nothing here looks inside it.\n */\nexport interface PageWindow {\n readonly first?: number | undefined\n readonly last?: number | undefined\n readonly after?: string | undefined\n readonly before?: string | undefined\n}\n\nexport const SelectionPageTypeId: unique symbol = Symbol.for('foldkit-entity/SelectionPage')\nexport type SelectionPageTypeId = typeof SelectionPageTypeId\n\n/** A Selection of a `many` relation's target, read a page at a time. */\nexport interface SelectionPage<Name extends string, S extends Schema.Constraint> {\n readonly [SelectionPageTypeId]: SelectionPageTypeId\n readonly selection: Selection<Name, any, S>\n readonly window: PageWindow\n}\n\ntype PageSchema<S extends Schema.Constraint> = Schema.Struct<{\n readonly items: Schema.$Array<S>\n readonly hasNext: Schema.Boolean\n readonly hasPrevious: Schema.Boolean\n}>\n\ntype SelectionSpec<E extends AnyEntity, Spec> = {\n readonly [K in keyof Spec]: K extends keyof E['relations']\n ? E['relations'][K] extends EntityRelation<any, any, infer Target, infer C, any>\n ? | true\n | AnySelection<Target['name']>\n // Only a `many` relation has pages.\n | (C extends 'many' ? SelectionPage<Target['name'], any> : never)\n : never\n : K extends keyof E['members']\n ? true\n : `\"${K & string}\" is not a member of ${E['name']}`\n}\n\ntype RelationShape<\n C extends Cardinality,\n Optional extends boolean,\n S extends Schema.Constraint,\n> = C extends 'many' ? Schema.$Array<S> : Optional extends true ? Schema.NullOr<S> : S\n\ntype SelectedSchema<Member, Selected> = Member extends\n EntityField<any, any, infer S> | EntityDerived<any, any, infer S>\n ? S\n : Member extends EntityRelation<any, any, infer Target, infer C, infer Optional>\n ? Selected extends SelectionPage<any, infer S>\n ? PageSchema<S>\n : RelationShape<\n C,\n Optional,\n Selected extends Selection<any, any, infer S> ? S : RefSchema<Target>\n >\n : never\n\ntype SelectionSchema<E extends AnyEntity, Spec> = Schema.Struct<{\n readonly [K in keyof Spec & keyof E['members']]: SelectedSchema<E['members'][K], Spec[K]>\n}>\n\ninterface AstLike {\n readonly _tag: string\n readonly literal?: unknown\n readonly types?: ReadonlyArray<AstLike>\n}\n\nconst isText = (ast: AstLike): boolean =>\n ast._tag === 'String' ||\n ast._tag === 'TemplateLiteral' ||\n (ast._tag === 'Literal' && typeof ast.literal === 'string') ||\n (ast._tag === 'Union' && (ast.types ?? []).length > 0 && (ast.types ?? []).every(isText))\n\n/** The `id` field's schema when it is text, so a ref's id keeps its brand and its checks; else text. */\nconst idSchemaOf = (entity: AnyEntity): Schema.Top => {\n const fields: Readonly<Record<string, EntityMember | undefined>> = entity.fields\n const id = fields.id\n if (id === undefined || id._tag !== 'Field') return Schema.String\n const type = Schema.toType(id.schema as Schema.Top)\n return isText(type.ast as unknown as AstLike) ? type : Schema.String\n}\n\nconst isSelectionPage = (value: unknown): value is SelectionPage<string, Schema.Constraint> =>\n typeof value === 'object' && value !== null && SelectionPageTypeId in value\n\nconst isSelection = (value: unknown): value is AnySelection =>\n typeof value === 'object' && value !== null && SelectionTypeId in value\n\n/** An input key that carries a relation's target: the id of a `one`, the ids of a `many`. */\nexport interface RelationInput<R extends EntityRelation<any, any, any, any, any>> {\n readonly _tag: 'RelationInput'\n readonly relation: R\n}\n\n/**\n * An input key that carries the relation's target itself, written through an\n * input of its own: a post created with a new author, an order with its lines.\n * A `one` holds that input's value, a `many` a list of them.\n */\nexport interface NestedInput<\n R extends EntityRelation<any, any, any, any, any>,\n I extends EntityInput<any, any, any>,\n> {\n readonly _tag: 'NestedInput'\n readonly relation: R\n readonly input: I\n}\n\n/** An input key that is about the operation, not the Entity: a reason, a flag, a confirmation. */\nexport interface Unmapped {\n readonly _tag: 'Unmapped'\n}\n\n/** What one key of an operation's input means in terms of the Entity. */\nexport type InputMember =\n | EntityField<string, string, Schema.Constraint>\n | RelationInput<EntityRelation<string, string, AnyEntity, Cardinality, boolean>>\n | NestedInput<\n EntityRelation<string, string, AnyEntity, Cardinality, boolean>,\n EntityInput<AnyEntity, any, any>\n >\n | Unmapped\n\n/** The ids a relation takes as input: one id, a nullable id, or a list of ids. */\ntype RelationIds<R> =\n R extends EntityRelation<any, any, infer Target, infer C, infer Optional>\n ? C extends 'many'\n ? ReadonlyArray<IdOf<Target>>\n : Optional extends true\n ? IdOf<Target> | null\n : IdOf<Target>\n : never\n\n/** What a nested input takes: the value of the target's input, or a list of them for a `many`. */\ntype NestedValues<R, I> =\n I extends EntityInput<any, infer Fields, any>\n ? R extends EntityRelation<any, any, any, 'many', any>\n ? ReadonlyArray<Schema.Struct.Type<Fields>>\n : Schema.Struct.Type<Fields>\n : never\n\n/**\n * Only the value that is present has to fit: an input may leave a key out (a\n * partial update) or send `null` to clear it. Whether it may is the input\n * schema's rule; the fit only guards against mapping the wrong member.\n */\ntype Present<T> = Exclude<T, null | undefined>\n\ntype MappingFor<Name extends string, Input, M> = M extends Unmapped\n ? M\n : M extends\n | EntityField<infer Owner, any, any>\n | RelationInput<EntityRelation<infer Owner, any, any, any, any>>\n | NestedInput<EntityRelation<infer Owner, any, any, any, any>, any>\n ? [Owner] extends [Name]\n ? M extends EntityField<any, any, infer S>\n ? Present<Input> extends Schema.Schema.Type<S>\n ? M\n : 'the input value does not fit this field'\n : M extends RelationInput<infer R>\n ? Present<Input> extends RelationIds<R>\n ? M\n : 'the input value is not the id shape of this relation'\n : M extends NestedInput<infer R, infer I>\n ? R extends EntityRelation<any, any, infer Target, any, any>\n ? I extends EntityInput<infer Of, any, any>\n ? [Of['name']] extends [Target['name']]\n ? Present<Input> extends NestedValues<R, I>\n ? M\n : 'the input value is not the value of the nested input'\n : `the nested input is of ${Of['name']}, not ${Target['name']}`\n : never\n : never\n : never\n : `this member belongs to ${Owner}`\n : 'map an input key to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped'\n\n/** A key that names a field whose value it fits maps itself; every other key needs an entry. */\ntype SelfMapped<E extends AnyEntity, Fields extends Schema.Struct.Fields> = {\n [K in keyof Fields]: K extends keyof E['fields']\n ? Present<Schema.Schema.Type<Fields[K]>> extends Schema.Schema.Type<E['fields'][K]['schema']>\n ? K\n : never\n : never\n}[keyof Fields]\n\n/**\n * A mapping written as a member's key: `'title'` is that Field, and `'author'` is\n * `Relation.input` of that relation. Nothing is inferred from the input key's own\n * name; the member is still named, only more briefly.\n */\ntype Named<E extends AnyEntity, M> = M extends string\n ? M extends keyof E['fields']\n ? E['fields'][M]\n : M extends keyof E['relations']\n ? RelationInput<E['relations'][M]>\n : `\"${M}\" names no field or relation of ${E['name']}`\n : M\n\ntype InputMapping<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = {\n readonly [K in Exclude<keyof Fields, SelfMapped<E, Fields>>]: unknown\n} & {\n readonly [K in keyof Mapping]: K extends keyof Fields\n ? Named<E, Mapping[K]> extends infer Member\n ? Member extends string\n ? Member\n : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member> extends Member\n ? Mapping[K]\n : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member>\n : never\n : `\"${K & string}\" is not a key of the input`\n}\n\ntype InputMembers<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = {\n readonly [K in keyof Fields]: K extends keyof Mapping\n ? Named<E, Mapping[K]>\n : K extends keyof E['fields']\n ? E['fields'][K]\n : never\n}\n\n/**\n * An operation's input read against an Entity: which member each input key\n * writes. The operation decides what may be submitted; the Entity only says\n * what each submitted key means.\n */\nexport interface EntityInput<E extends AnyEntity, Fields extends Schema.Struct.Fields, Members> {\n readonly entity: E\n readonly schema: Schema.Struct<Fields>\n readonly members: Members\n}\n\n/** The Entity member an input key writes, by its key; nothing for an unmapped key. */\nexport type WrittenKey<M> =\n M extends EntityField<any, infer Key, any>\n ? Key\n : M extends\n | RelationInput<EntityRelation<any, infer Key, any, any, any>>\n | NestedInput<EntityRelation<any, infer Key, any, any, any>, any>\n ? Key\n : never\n\n/** A nested input reads what it writes of the target; every other member reads as it is. */\nexport type WrittenAs<M> =\n M extends NestedInput<any, EntityInput<infer Of, any, infer Members>>\n ? Selection<Of['name'], WrittenSpec<Members>, SelectionSchema<Of, WrittenSpec<Members>>>\n : true\n\n/** Every member the input writes: what to read to show the input's current values. */\nexport type WrittenSpec<Members> = {\n readonly [K in keyof Members as WrittenKey<Members[K]>]: WrittenAs<Members[K]>\n}\n\nconst unmapped: Unmapped = Object.freeze({ _tag: 'Unmapped' })\n\ninterface Parts {\n readonly identity: EntityIdentity<string>\n readonly schema: Schema.Struct<Schema.Struct.Fields>\n readonly fields: Readonly<Record<string, EntityMember>>\n readonly relations: Readonly<Record<string, EntityMember>>\n readonly derived: Readonly<Record<string, EntityMember>>\n readonly metadata: Metadata\n}\n\nconst EntityProto = {\n [EntityTypeId]: EntityTypeId,\n pipe() {\n return Pipeable.pipeArguments(this, arguments)\n },\n}\n\nconst make = (parts: Parts): AnyEntity =>\n Object.freeze(\n Object.assign(Object.create(EntityProto), parts, {\n name: parts.identity.name,\n fields: Object.freeze(parts.fields),\n relations: Object.freeze(parts.relations),\n derived: Object.freeze(parts.derived),\n members: Object.freeze({ ...parts.fields, ...parts.relations, ...parts.derived }),\n }),\n )\n\nconst isSameEntity = (left: AnyEntity, right: AnyEntity): boolean =>\n left.identity.token === right.identity.token\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`Entity \"${entity.name}\": ${message}`)\n}\n\nconst isEntity = (value: unknown): value is AnyEntity =>\n typeof value === 'object' && value !== null && EntityTypeId in value\n\nconst kindName = { Field: 'field', Relation: 'relation', Derived: 'derived member' } as const\n\nconst kindOf = (entity: AnyEntity, key: string): string | undefined => {\n const member = (entity.members as Readonly<Record<string, EntityMember>>)[key]\n return member && kindName[member._tag]\n}\n\nconst assertFree = (entity: AnyEntity, keys: ReadonlyArray<string>, adding: string): void => {\n for (const key of keys) {\n const kind = kindOf(entity, key)\n if (kind !== undefined)\n throw new Error(\n `Entity \"${entity.name}\": cannot add ${adding} \"${key}\", it is already a ${kind}`,\n )\n }\n}\n\nconst mapValues = <A, B>(\n record: Readonly<Record<string, A>>,\n f: (value: A, key: string) => B,\n): Record<string, B> =>\n Object.fromEntries(Object.entries(record).map(([key, value]) => [key, f(value, key)]))\n\nexport const Entity = {\n /** Declares an Entity from its intrinsic fields. Each call is a new identity. */\n define: <const Name extends string, Fields extends Schema.Struct.Fields>(\n name: Name,\n schema: Schema.Struct<Fields>,\n ): Entity<Name, Fields> => {\n const identity: EntityIdentity<Name> = Object.freeze({ name, token: Symbol(name) })\n return make({\n identity,\n schema,\n fields: mapValues(schema.fields, (fieldSchema, key) =>\n Object.freeze({\n _tag: 'Field',\n owner: identity,\n key,\n schema: fieldSchema,\n metadata: Metadata.empty,\n }),\n ),\n relations: {},\n derived: {},\n metadata: Metadata.empty,\n }) as Entity<Name, Fields>\n },\n\n /**\n * Declares the relations between a set of Entities in one step, and returns\n * them related. One step, because Entities that point at each other cannot\n * each be declared in terms of the other.\n */\n relate: <const Es extends Entities, const Rs extends RelationMap<Es>>(\n entities: Es,\n relations: Rs & CheckRelations<Es, Rs>,\n ): { readonly [K in keyof Es]: Related<Es, Rs, K> } => {\n const keyByToken = new Map<symbol, string>()\n for (const [key, entity] of Object.entries(entities)) {\n if (!isEntity(entity)) throw new Error(`Entity.relate: \"${key}\" is not an Entity`)\n const earlier = keyByToken.get(entity.identity.token)\n if (earlier !== undefined)\n throw new Error(`Entity.relate: \"${earlier}\" and \"${key}\" are the same Entity`)\n keyByToken.set(entity.identity.token, key)\n }\n const given: Readonly<Record<string, RelationSpecs | undefined>> = relations\n for (const owner of Object.keys(given))\n if (!(owner in entities))\n throw new Error(`Entity.relate: relations given for \"${owner}\", which is not being related`)\n\n const related: Record<string, AnyEntity> = {}\n for (const [ownerKey, entity] of Object.entries(entities)) {\n const specs = given[ownerKey] ?? {}\n assertFree(entity, Object.keys(specs), 'relation')\n const added = mapValues<RelationSpec<AnyEntity, Cardinality, boolean>, EntityMember>(\n specs,\n (spec, key) => {\n const targetKey = isEntity(spec.target)\n ? keyByToken.get(spec.target.identity.token)\n : undefined\n if (targetKey === undefined)\n throw new Error(\n `Entity \"${entity.name}\": relation \"${key}\" targets an Entity that is not being related`,\n )\n return Object.freeze({\n _tag: 'Relation',\n owner: entity.identity,\n key,\n // Read on call: the target may come later in `entities` than its owner.\n target: () => related[targetKey]!,\n cardinality: spec.cardinality,\n optional: spec.optional,\n metadata: Metadata.empty,\n })\n },\n )\n related[ownerKey] = make({ ...entity, relations: { ...entity.relations, ...added } })\n }\n return Object.freeze(related) as never\n },\n\n /**\n * Selects members of an Entity and assembles the schema of the result. A\n * relation selected with `true` yields an `EntityRef`; with a Selection of its\n * target, that Selection's value. `many` yields an array, an optional `one`\n * is nullable.\n */\n select: <E extends AnyEntity, const Spec>(\n entity: E,\n spec: Spec & SelectionSpec<E, Spec>,\n ): Selection<E['name'], Spec, SelectionSchema<E, Spec>, IdOf<E>> => {\n const members: Readonly<Record<string, EntityMember>> = entity.members\n const fields = mapValues<unknown, Schema.Constraint>(spec, (selected, key) => {\n const member = members[key]\n if (member === undefined)\n throw new Error(`Entity \"${entity.name}\": cannot select \"${key}\", it is not a member`)\n if (member._tag !== 'Relation') {\n if (selected !== true)\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" is a ${kindName[member._tag]}, select it with true`,\n )\n return member.schema\n }\n const target = member.target()\n if (isSelectionPage(selected)) {\n if (member.cardinality !== 'many')\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" is one ${target.name}, so it has no pages`,\n )\n if (!isSameEntity(selected.selection.entity, target))\n throw new Error(`Entity \"${entity.name}\": \"${key}\" pages a Selection of ${target.name}`)\n return Schema.Struct({\n items: Schema.Array(selected.selection.schema as Schema.Top),\n hasNext: Schema.Boolean,\n hasPrevious: Schema.Boolean,\n })\n }\n let item: Schema.Top\n if (selected === true)\n item = Schema.Struct({ entity: Schema.Literal(target.name), id: idSchemaOf(target) })\n else if (isSelection(selected) && isSameEntity(selected.entity, target))\n item = selected.schema\n else\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" takes true or a Selection of ${target.name}`,\n )\n return member.cardinality === 'many'\n ? Schema.Array(item)\n : member.optional\n ? Schema.NullOr(item)\n : item\n })\n return Object.freeze({\n [SelectionTypeId]: SelectionTypeId,\n entity,\n members: spec,\n schema: Schema.Struct(fields),\n }) as never\n },\n\n /**\n * A `many` relation read a page at a time, in place of its Selection:\n * `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page\n * of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.\n */\n page: <Name extends string, S extends Schema.Constraint>(\n selection: Selection<Name, any, S>,\n window: PageWindow,\n ): SelectionPage<Name, S> => {\n const sides = [window.first, window.last].filter(size => size !== undefined)\n if (sides.length !== 1 || !sides.every(size => Number.isInteger(size) && size >= 0))\n throw new Error(\n `Entity.page: a window of ${selection.entity.name} takes first or last, a non-negative integer`,\n )\n if (\n (window.first !== undefined && window.before !== undefined) ||\n (window.last !== undefined && window.after !== undefined)\n )\n throw new Error(\n `Entity.page: a window of ${selection.entity.name} reads first after a cursor, or last before one`,\n )\n const page: SelectionPage<Name, S> = {\n [SelectionPageTypeId]: SelectionPageTypeId,\n selection,\n window,\n }\n return Object.freeze(page)\n },\n\n /** Adds readable members that are not part of `entity.schema`. */\n derived:\n <const New extends DerivedSpecs>(specs: New) =>\n <E extends AnyEntity>(entity: E & Free<E, New>): WithDerived<E, New> => {\n assertFree(entity, Object.keys(specs), 'derived member')\n const added = mapValues<DerivedSpec<Schema.Constraint>, EntityMember>(specs, (spec, key) =>\n Object.freeze({\n _tag: 'Derived',\n owner: entity.identity,\n key,\n schema: spec.schema,\n metadata: Metadata.empty,\n }),\n )\n return make({ ...entity, derived: { ...entity.derived, ...added } }) as never\n },\n\n /** Attaches an interpreter's metadata to the Entity itself. */\n annotate:\n (metadata: Metadata) =>\n <E extends AnyEntity>(entity: E): E =>\n make({ ...entity, metadata: Metadata.combine([entity.metadata, metadata]) }) as E,\n\n /** Attaches an interpreter's metadata to members, by key. */\n annotateMembers:\n <E extends AnyEntity>(metadata: { readonly [K in keyof E['members']]?: Metadata }) =>\n (entity: E): E => {\n const given = metadata as Readonly<Record<string, Metadata | undefined>>\n for (const key of Object.keys(given))\n if (kindOf(entity, key) === undefined)\n throw new Error(`Entity \"${entity.name}\": cannot annotate \"${key}\", it is not a member`)\n const annotate = (members: Readonly<Record<string, EntityMember>>) =>\n mapValues(members, (member, key) => {\n const extra = given[key]\n return extra === undefined\n ? member\n : Object.freeze({ ...member, metadata: Metadata.combine([member.metadata, extra]) })\n })\n return make({\n ...entity,\n fields: annotate(entity.fields),\n relations: annotate(entity.relations),\n derived: annotate(entity.derived),\n }) as E\n },\n\n /**\n * Reads an operation's input schema against an Entity. A key that names a\n * field maps to it; any other key is mapped explicitly, to a Field, to\n * `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred\n * from a naming convention such as `authorId`.\n */\n input: <\n E extends AnyEntity,\n Fields extends Schema.Struct.Fields,\n // `{}` when every key maps itself, so the argument can be omitted.\n const Mapping = {},\n >(\n entity: E,\n schema: Schema.Struct<Fields>,\n ...mapping: keyof InputMapping<E, Fields, Mapping> extends never\n ? [mapping?: Mapping & InputMapping<E, Fields, Mapping>]\n : [mapping: Mapping & InputMapping<E, Fields, Mapping>]\n ): EntityInput<E, Fields, InputMembers<E, Fields, Mapping>> => {\n const written: Readonly<Record<string, InputMember | string | undefined>> = mapping[0] ?? {}\n for (const key of Object.keys(written))\n if (!(key in schema.fields))\n throw new Error(`Entity \"${entity.name}\": \"${key}\" is mapped but is not a key of the input`)\n // A member named by its key: a Field as it is, a relation as its ids.\n const named = (key: string, name: string): InputMember => {\n const member = (entity.members as Readonly<Record<string, EntityMember | undefined>>)[name]\n if (member?._tag === 'Field') return member\n if (member?._tag === 'Relation')\n return Object.freeze({ _tag: 'RelationInput', relation: member })\n return fail(\n entity,\n `input key \"${key}\" is mapped to \"${name}\", which names no field or relation`,\n )\n }\n const given: Readonly<Record<string, InputMember | undefined>> = mapValues(\n written,\n (member, key) => (typeof member === 'string' ? named(key, member) : member),\n )\n const fields: Readonly<Record<string, InputMember | undefined>> = entity.fields\n const members = mapValues(schema.fields, (_, key) => {\n const member =\n given[key] ??\n fields[key] ??\n fail(entity, `input key \"${key}\" names no field; map it to a member or Entity.unmapped`)\n const owned =\n member._tag === 'Field'\n ? member\n : member._tag === 'RelationInput' || member._tag === 'NestedInput'\n ? member.relation\n : member._tag === 'Unmapped'\n ? undefined\n : fail(\n entity,\n `input key \"${key}\" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`,\n )\n if (owned !== undefined && owned.owner.token !== entity.identity.token)\n fail(entity, `input key \"${key}\" is mapped to a member of \"${owned.owner.name}\"`)\n if (\n member._tag === 'NestedInput' &&\n !isSameEntity(member.input.entity, member.relation.target())\n )\n fail(\n entity,\n `input key \"${key}\" nests an input of \"${member.input.entity.name}\", but \"${member.relation.key}\" is of \"${member.relation.target().name}\"`,\n )\n return member\n })\n return Object.freeze({ entity, schema, members: Object.freeze(members) }) as never\n },\n\n /** For an input key that is about the operation rather than the Entity. */\n unmapped,\n\n /**\n * The schemas of some of an Entity's fields, by key, to spread into an input's\n * struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.\n * The input then keeps the field's own rules, and its keys map themselves.\n */\n fields: <E extends AnyEntity, const Keys extends ReadonlyArray<keyof E['fields'] & string>>(\n entity: E,\n ...keys: Keys\n ): { readonly [K in Keys[number]]: E['fields'][K]['schema'] } =>\n Object.fromEntries(\n keys.map(key => [\n key,\n (\n (\n entity.fields as Readonly<\n Record<string, EntityField<string, string, Schema.Constraint> | undefined>\n >\n )[key] ?? fail(entity, `\"${key}\" is not a field`)\n ).schema,\n ]),\n ) as never,\n\n /**\n * The Selection of every member an input writes, with each relation as refs:\n * what an edit screen loads before it shows the input's current values.\n */\n selectFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n ): Selection<\n E['name'],\n WrittenSpec<Members>,\n SelectionSchema<E, WrittenSpec<Members>>,\n IdOf<E>\n > => {\n const members: Readonly<Record<string, InputMember>> = input.members as never\n const spec = Object.fromEntries(\n Object.values(members).flatMap((member): ReadonlyArray<readonly [string, unknown]> =>\n member._tag === 'Field'\n ? [[member.key, true]]\n : member._tag === 'RelationInput'\n ? [[member.relation.key, true]]\n : member._tag === 'NestedInput'\n ? // What the nested input writes of the target, so its keys can be shown too.\n [[member.relation.key, Entity.selectFor(member.input)]]\n : [],\n ),\n )\n return Entity.select(input.entity, spec as never) as never\n },\n\n /**\n * The input values that reproduce `value`, a value read through `selectFor`\n * (or any Selection with those members): a field as it is, a relation as the\n * id or ids of its refs. A key whose member `value` lacks is left out, as is\n * an unmapped key, which the Entity knows nothing about.\n */\n valuesFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n value: Readonly<Record<string, unknown>>,\n ): Partial<Schema.Struct.Type<Fields>> => {\n const members: Readonly<Record<string, InputMember>> = input.members as never\n // The id of a ref or of a nested Selection's value; `undefined` when it has none.\n const idOf = (held: unknown): unknown =>\n held === null\n ? null\n : typeof held === 'object' && 'id' in held\n ? held.id\n : typeof held === 'string'\n ? held\n : undefined\n const entries = Object.entries(members).flatMap(([key, member]) => {\n if (member._tag === 'Unmapped') return []\n const written = member._tag === 'Field' ? member.key : member.relation.key\n if (!(written in value)) return []\n const read = value[written]\n if (member._tag === 'Field') return [[key, read] as const]\n if (member._tag === 'NestedInput') {\n const nested = (held: unknown): unknown =>\n typeof held === 'object' && held !== null\n ? Entity.valuesFor(member.input, held as Readonly<Record<string, unknown>>)\n : null\n return [[key, Array.isArray(read) ? read.map(nested) : nested(read)] as const]\n }\n const ids = Array.isArray(read) ? read.map(idOf) : idOf(read)\n // A relation read without its ids (a nested Selection that left `id` out) fills nothing.\n const known = Array.isArray(ids) ? !ids.includes(undefined) : ids !== undefined\n return known ? [[key, ids] as const] : []\n })\n return Object.fromEntries(entries) as Partial<Schema.Struct.Type<Fields>>\n },\n\n is: isEntity,\n\n /** True when both descriptors are versions of one Entity. */\n same: isSameEntity,\n}\n\nfunction one<Target extends AnyEntity>(target: Target): RelationSpec<Target, 'one', false>\nfunction one<Target extends AnyEntity, const Optional extends boolean>(\n target: Target,\n options: { readonly optional: Optional },\n): RelationSpec<Target, 'one', Optional>\nfunction one(\n target: AnyEntity,\n options?: { readonly optional: boolean },\n): RelationSpec<AnyEntity, 'one', boolean> {\n return { target, cardinality: 'one', optional: options?.optional ?? false }\n}\n\n/** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */\nexport const Relation = {\n one,\n\n /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */\n input: <R extends EntityRelation<any, any, any, any, any>>(relation: R): RelationInput<R> =>\n Object.freeze({ _tag: 'RelationInput', relation }),\n\n /**\n * For `Entity.input`: the input key holds the relation's target itself, written\n * through `input`, an `Entity.input` of the target. A `many` holds a list.\n */\n nested: <R extends EntityRelation<any, any, any, any, any>, I extends EntityInput<any, any, any>>(\n relation: R,\n input: I,\n ): NestedInput<R, I> => Object.freeze({ _tag: 'NestedInput', relation, input }),\n\n many: <Target extends AnyEntity>(target: Target): RelationSpec<Target, 'many', false> => ({\n target,\n cardinality: 'many',\n optional: false,\n }),\n}\n\nexport const Derived = {\n make: <S extends Schema.Constraint>(schema: S): DerivedSpec<S> => ({ schema }),\n}\n\nexport * from './expr.js'\n// The reference semantics of the IR above. The conformance suite that proves\n// an interpreter agrees with it is `foldkit-entity/conformance`, kept out of\n// this entry because it is fixture data every form and admin screen would\n// otherwise carry.\nexport * from './evaluate.js'\n"],"mappings":";;;;;;;;;;;;;;;;AAwIA,MAAM,SAAS,UACb,OAAO,UAAU,YAAY,UAAU,OAClC,MAAsC,OACvC,KAAA;;;;;;;AAQN,MAAM,WAAc,WAA8B;CAAE,MAAM;CAAW;AAAM;AAE3E,MAAM,aAAa,WAA+E;CAChG,MAAM;CACN,OAAO,MAAM;CACb,KAAK,MAAM;CACX,QAAQ,MAAM;AAChB;AAEA,MAAM,gCAAgB,IAAI,IAAI;CAAC;C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AyC,IACxE;IACN,OAAO,CAAC,CAAC,KAAK,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,MAAM,IAAI,OAAO,IAAI,CAAC,CAAU;GAC/E;GACA,MAAM,MAAM,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI;GAG5D,QADc,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,SAAS,KAAA,CAAS,IAAI,QAAQ,KAAA,KACvD,CAAC,CAAC,KAAK,GAAG,CAAU,IAAI,CAAC;EAC1C,CAAC;EACD,OAAO,OAAO,YAAY,OAAO;CACnC;CAEA,IAAI;;CAGJ,MAAM;AACR;AAOA,SAAS,IACP,QACA,SACyC;CACzC,OAAO;EAAE;EAAQ,aAAa;EAAO,UAAU,SAAS,YAAY;CAAM;AAC5E;;AAGA,MAAa,WAAW;CACtB;;CAGA,QAA2D,aACzD,OAAO,OAAO;EAAE,MAAM;EAAiB;CAAS,CAAC;;;;;CAMnD,SACE,UACA,UACsB,OAAO,OAAO;EAAE,MAAM;EAAe;EAAU;CAAM,CAAC;CAE9E,OAAiC,YAAyD;EACxF;EACA,aAAa;EACb,UAAU;CACZ;AACF;AAEA,MAAa,UAAU,EACrB,OAAoC,YAA+B,EAAE,OAAO,GAC9E"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/shape.ts","../src/expr.ts","../src/words.ts","../src/evaluate.ts","../src/index.ts"],"sourcesContent":["import { SchemaAST } from 'effect'\n\nconst isNullish = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast)\n\nconst isText = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isString(ast) ||\n SchemaAST.isTemplateLiteral(ast) ||\n (SchemaAST.isLiteral(ast) && typeof ast.literal === 'string') ||\n (SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText))\n\n/** What a schema's AST holds, read through Effect's own guards. */\nexport const SchemaShape = {\n /** True for the `null` and `undefined` members that make a schema optional. */\n isNullish,\n\n /**\n * The members of a schema with `null` and `undefined` set aside, so optional\n * text is still text; a schema that is not a union is its one member.\n */\n present: (ast: SchemaAST.AST): ReadonlyArray<SchemaAST.AST> =>\n SchemaAST.isUnion(ast) ? ast.types.filter(member => !isNullish(member)) : [ast],\n\n /** True when every value the schema admits is a string. */\n isText,\n}\n","/**\n * `Expr` — a query's scalar computations as typed values.\n *\n * An Entity says what a domain has; an `Expr` says something about one row of\n * it. A field reference, an input placeholder, a literal, and comparisons of\n * those are all immutable data: building one performs no work, reads nothing,\n * and names no database. An interpreter compiles it — `foldkit-remote-drizzle`\n * to SQL, an in-memory evaluator to a predicate over rows.\n *\n * This is deliberately not SQL and deliberately not arbitrary JavaScript. Every\n * operation here is one a real query in this repository needs; the set grows\n * from queries, not from what a database could express.\n */\nimport { Pipeable, Schema } from 'effect'\nimport type { AnyEntity, EntityField, EntityIdentity } from './index.js'\n\n/** A constant the query was written with. */\nexport interface LiteralExpr<T> {\n readonly _tag: 'Literal'\n readonly value: T\n}\n\n/**\n * One field of one Entity. `owner` is the Entity's identity rather than its\n * name, so two Entities defined with the same name are not one column.\n */\nexport interface FieldExpr<T> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<string>\n readonly key: string\n readonly schema: Schema.Codec<T, unknown>\n}\n\n/**\n * A value the query is given when it runs. A definition's body is built once,\n * so inside it an input is this placeholder and never the value: there is\n * nothing yet to branch on, and a query that wants to depend on what was passed\n * says so with an operation over the placeholder.\n */\nexport interface InputExpr<T> {\n readonly _tag: 'Input'\n readonly key: string\n readonly schema: Schema.Codec<T, unknown>\n}\n\n/** A typed scalar: what a comparison compares. */\nexport type Expr<T> = LiteralExpr<T> | FieldExpr<T> | InputExpr<T>\n\n/** Any scalar, for the places that hold operands without caring what they are. */\nexport type AnyExpr = Expr<unknown>\n\n/**\n * `Expr<boolean>`, in the shape the operations that exist can actually take.\n * The design's kernel is all boolean-valued (`eq`, `and`, `isNull`,\n * `contains`, …), so a predicate is its own type rather than a phantom\n * parameter on a general operation node: `Predicate` and `Expr<string>` cannot\n * then be confused, which a structural phantom would allow. A scalar-valued\n * operation, if one is ever needed, joins `Expr` instead.\n */\nexport type Predicate = EqPredicate | NullPredicate | ContainsPredicate\n\n/** Two values are the same. */\nexport interface EqPredicate {\n readonly _tag: 'Eq'\n readonly left: Operandish\n readonly right: Operandish\n}\n\n/**\n * Whether a value is absent. `present` says which answer absence gives, so one\n * node covers `is null` and `is not null` rather than two that differ by a\n * negation nothing else can express.\n */\nexport interface NullPredicate {\n readonly _tag: 'Null'\n readonly operand: AnyExpr\n readonly present: boolean\n}\n\n/**\n * Whether a text value contains another. Containing the empty string is\n * everything, which is what lets a search box with nothing typed in it be the\n * same query as one with something — see `Expr.contains`.\n */\nexport interface ContainsPredicate {\n readonly _tag: 'Contains'\n readonly value: AnyExpr\n readonly search: Operandish\n}\n\n/**\n * Anything an operation can be given: a scalar, or a predicate where a boolean\n * is wanted. `Expr.eq(Expr.isNotNull(archivedAt), input.archived)` is the\n * second case, and it is how a query depends on an input without branching on\n * it.\n */\nexport type Operandish = AnyExpr | Predicate\n\n/** A field, a scalar already built from one, or a predicate used as a boolean. */\ntype Operand<T> = EntityField<string, string, Schema.Constraint> | Expr<T> | Predicate\n\n/** What an operand is worth, so a comparison's other side is checked against it. */\nexport type ValueOf<E> =\n E extends EntityField<string, string, infer S>\n ? Schema.Schema.Type<S>\n : E extends Predicate\n ? boolean\n : E extends Expr<infer T>\n ? T\n : never\n\n/**\n * A field or scalar whose value is text, or absent text.\n *\n * `Expr.contains` is a case-insensitive **text** search that compiles to\n * `lower(column) like lower(?)`. Over a number that is nonsense which reaches\n * the database — SQLite coerces and answers something, Postgres raises — so\n * the operand is constrained here rather than discovered there.\n *\n * Null belongs in the type, because a nullable text column is a real and\n * documented case: a null contains nothing, not even the empty string, so its\n * rows drop out of a search that would otherwise match everything.\n *\n * Written as a **constraint on the type parameter** rather than as a check\n * intersected onto the parameter (the `Invalid` idiom `foldkit-remote` uses for\n * an unregistered descriptor). That idiom compares an already-resolved indexed\n * access; here the check would be a conditional over the type being inferred,\n * and inference falls back to the constraint — whose `Expr<any>` branch makes\n * the check vacuously true, so every operand passes. A constraint cannot be\n * defeated that way.\n */\nexport type TextOperand =\n | EntityField<string, string, Schema.Constraint & Schema.Codec<string | null, any, any, any>>\n | Expr<string>\n | Expr<string | null>\n\nconst tagOf = (value: unknown): unknown =>\n typeof value === 'object' && value !== null && '_tag' in value ? value._tag : undefined\n\n/**\n * An Entity's field and a `FieldExpr` are the same three members under the same\n * tag — the Entity's carries `metadata` besides — so this reads either and is\n * idempotent on its own output. Nothing needs to tell them apart, which is\n * better than telling them apart by which extra member happens to be present.\n */\nconst literal = <T>(value: T): LiteralExpr<T> => ({ _tag: 'Literal', value })\n\nconst fieldExpr = (field: EntityField<string, string, Schema.Constraint>): FieldExpr<unknown> => ({\n _tag: 'Field',\n owner: field.owner,\n key: field.key,\n schema: field.schema as unknown as Schema.Codec<unknown, unknown>,\n})\n\nconst predicateTags = new Set(['Eq', 'Null', 'Contains'])\n\n/** Whether a value is a predicate, and so usable where a boolean is wanted. */\nexport const isPredicate = (value: unknown): value is Predicate =>\n predicateTags.has(tagOf(value) as string)\n\n/**\n * A field of either kind becomes a `FieldExpr`, a scalar or a predicate is\n * itself, and anything else is the constant it is.\n */\nconst toOperand = <T>(value: Operand<T> | T): Operandish => {\n const tag = tagOf(value)\n if (tag === 'Field') {\n return fieldExpr(value as EntityField<string, string, Schema.Constraint>)\n }\n if (tag === 'Literal' || tag === 'Input' || predicateTags.has(tag as string)) {\n return value as Operandish\n }\n return literal(value)\n}\n\n/** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */\nconst toExpr = <T>(value: Operand<T> | T, step: string): AnyExpr => {\n const operand = toOperand(value)\n if (isPredicate(operand)) {\n throw new Error(\n `[foldkit-entity] Expr.${step}: a predicate is already an answer, so asking this of one is not a question`,\n )\n }\n return operand\n}\n\n/**\n * Every operation the kernel has. An interpreter declares which of them it\n * runs, and a body needing one it does not is refused rather than answered\n * wrongly — see `Query.unsupported`.\n */\nexport type Operation = 'eq' | 'isNull' | 'isNotNull' | 'contains'\n\n/** Which fields and inputs an expression reads, and which operations it uses. */\nexport interface Dependencies {\n /** One entry per distinct field, as `Entity.key`. */\n readonly fields: ReadonlyArray<{ readonly entity: string; readonly key: string }>\n /** One entry per distinct input key. */\n readonly inputs: ReadonlyArray<string>\n /** One entry per distinct operation, so an interpreter can refuse what it cannot run. */\n readonly operations: ReadonlyArray<Operation>\n}\n\nexport const Expr = {\n /** A constant. Comparisons coerce a plain value, so this is rarely written. */\n literal,\n\n /**\n * A value the query is given when it runs. A definition builds these from its\n * `Input` schema; written by hand only when constructing a body directly.\n */\n input: <T>(key: string, schema: Schema.Codec<T, unknown>): InputExpr<T> => ({\n _tag: 'Input',\n key,\n schema,\n }),\n\n /** One field of one Entity, as a scalar. */\n field: <Name extends string, Key extends string, S extends Schema.Constraint>(\n field: EntityField<Name, Key, S>,\n ): FieldExpr<Schema.Schema.Type<S>> => fieldExpr(field) as FieldExpr<Schema.Schema.Type<S>>,\n\n /**\n * Two scalars are the same value. A field or a plain value on either side is\n * coerced, so the common form reads as it means:\n *\n * ```ts\n * Expr.eq(Post.fields.slug, input.slug)\n * Expr.eq(Post.fields.status, 'active')\n * ```\n */\n eq: <L extends Operand<any>>(\n left: L,\n right: ValueOf<L> | Expr<ValueOf<L>> | (boolean extends ValueOf<L> ? Predicate : never),\n ): EqPredicate => ({\n _tag: 'Eq',\n left: toOperand(left),\n right: toOperand(right as never),\n }),\n\n /**\n * Whether a field holds no value. Its opposite is `isNotNull`; both are the\n * one node, because a query asks which of the two it means and nothing here\n * can negate a predicate.\n */\n isNull: <L extends Operand<any>>(operand: L): NullPredicate => ({\n _tag: 'Null',\n operand: toExpr(operand, 'isNull'),\n present: false,\n }),\n\n /** Whether a field holds a value. */\n isNotNull: <L extends Operand<any>>(operand: L): NullPredicate => ({\n _tag: 'Null',\n operand: toExpr(operand, 'isNotNull'),\n present: true,\n }),\n\n /**\n * Whether a text value contains `search`, anywhere in it. Containing the\n * empty string is everything, so a search box with nothing typed in it is the\n * same query as one with something — no branch, and no second query.\n *\n * **Case-insensitive**, which is what a search means, and which has to be\n * said rather than left to the interpreter: SQLite's `like` ignores case and\n * Postgres's does not, so a body that left it open would mean two things.\n * Folding is ASCII-only, because that is what `lower` does in SQLite without\n * ICU.\n *\n * **Over a column that can be null this is not the same as no filter.** A\n * null contains nothing, not even the empty string, so its rows drop out. A\n * nullable column that should match everything on an empty search says so:\n * `Expr.or` does not exist yet, so for now such a column needs its own\n * predicate or a native escape hatch.\n */\n contains: <L extends TextOperand>(\n value: L,\n search: string | Expr<string>,\n ): ContainsPredicate => ({\n _tag: 'Contains',\n value: toExpr(value, 'contains'),\n search: toOperand(search as never),\n }),\n\n /** An expression as readable text; see `showExpr` for what it is and is not. */\n show: (node: Operandish): string => showExpr(node),\n}\n\n/** One term of an ordering: a scalar and the direction to read it in. */\nexport interface OrderTerm {\n readonly direction: 'asc' | 'desc'\n readonly expr: AnyExpr\n}\n\nexport const Order = {\n asc: <E extends Operand<any>>(expr: E): OrderTerm => ({\n direction: 'asc',\n expr: toExpr(expr as never, 'asc'),\n }),\n desc: <E extends Operand<any>>(expr: E): OrderTerm => ({\n direction: 'desc',\n expr: toExpr(expr as never, 'desc'),\n }),\n}\n\nconst walk = (\n node: AnyExpr | Predicate,\n fields: Map<string, { readonly entity: string; readonly key: string }>,\n inputs: Set<string>,\n operations: Set<Operation>,\n): void => {\n switch (node._tag) {\n case 'Literal':\n return\n case 'Field':\n fields.set(`${node.owner.name}.${node.key}`, { entity: node.owner.name, key: node.key })\n return\n case 'Input':\n inputs.add(node.key)\n return\n case 'Eq':\n operations.add('eq')\n walk(node.left, fields, inputs, operations)\n walk(node.right, fields, inputs, operations)\n return\n case 'Null':\n operations.add(node.present ? 'isNotNull' : 'isNull')\n walk(node.operand, fields, inputs, operations)\n return\n case 'Contains':\n operations.add('contains')\n walk(node.value, fields, inputs, operations)\n walk(node.search, fields, inputs, operations)\n return\n }\n}\n\n/**\n * What an expression reads and uses, for the planner and for an interpreter\n * deciding whether it can run this query at all. Distinct entries only, in the\n * order first seen, so the answer is stable enough to assert on.\n */\nexport const dependenciesOf = (\n ...nodes: ReadonlyArray<AnyExpr | Predicate | OrderTerm>\n): Dependencies => {\n const fields = new Map<string, { readonly entity: string; readonly key: string }>()\n const inputs = new Set<string>()\n const operations = new Set<Operation>()\n for (const node of nodes) {\n walk('direction' in node ? node.expr : node, fields, inputs, operations)\n }\n return { fields: [...fields.values()], inputs: [...inputs], operations: [...operations] }\n}\n\n/**\n * Which rows a query is about, as a value: an Entity to read, the predicates\n * every row must satisfy, and the order to read them in. It says nothing about\n * which fields to return — that is a Selection — and nothing about pagination,\n * liveness, or whether absence is an error, which belong to the consumer's read\n * rather than to the relation.\n *\n * Composing one performs no work. `Query.from(Post)` names no table and opens\n * no connection; an interpreter turns the value into a query when something\n * asks it to.\n */\nexport interface Query<E extends AnyEntity> extends Pipeable.Pipeable {\n readonly _tag: 'Query'\n readonly entity: E\n /**\n * Every predicate holds: the list *is* the conjunction. Keeping it a list\n * rather than folding it into one `and` is what makes each `where` a reusable\n * fragment, and it means no `Expr.and` exists until a query needs a\n * conjunction nested inside something else.\n */\n readonly where: ReadonlyArray<Predicate>\n /** In order of significance; a later `orderBy` appends less significant terms. */\n readonly orderBy: ReadonlyArray<OrderTerm>\n}\n\n/** A `Query` over any Entity, for the places that hold one without caring which. */\nexport type AnyQuery = Query<AnyEntity>\n\n/** Every field an expression reads, as the nodes themselves. */\nconst fieldsIn = function* (node: AnyExpr | Predicate): Generator<FieldExpr<unknown>> {\n switch (node._tag) {\n case 'Field':\n yield node\n return\n case 'Literal':\n case 'Input':\n return\n case 'Eq':\n yield* fieldsIn(node.left)\n yield* fieldsIn(node.right)\n return\n case 'Null':\n yield* fieldsIn(node.operand)\n return\n case 'Contains':\n yield* fieldsIn(node.value)\n yield* fieldsIn(node.search)\n return\n }\n}\n\n/**\n * A query reads one Entity, so a predicate or ordering term naming a different\n * one cannot be answered — an interpreter would be asked for a column of a\n * table it was never told to read. Compared by identity, not by name, because\n * two Entities defined with the same name are two Entities.\n */\nconst checkOwnership = (\n step: string,\n what: string,\n entity: AnyEntity,\n nodes: ReadonlyArray<AnyExpr | Predicate | OrderTerm>,\n): void => {\n for (const node of nodes) {\n for (const field of fieldsIn('direction' in node ? node.expr : node)) {\n if (field.owner.token !== entity.identity.token) {\n throw new Error(\n `[foldkit-entity] Query.${step}: ${what} reads ${field.owner.name}.${field.key}, but the query is from ${entity.name}`,\n )\n }\n }\n }\n}\n\nconst QueryProto = {\n _tag: 'Query' as const,\n pipe() {\n return Pipeable.pipeArguments(this, arguments)\n },\n}\n\nconst query = <E extends AnyEntity>(\n entity: E,\n where: ReadonlyArray<Predicate>,\n orderBy: ReadonlyArray<OrderTerm>,\n): Query<E> =>\n Object.freeze(\n Object.assign(Object.create(QueryProto), {\n entity,\n where: Object.freeze(where),\n orderBy: Object.freeze(orderBy),\n }),\n ) as Query<E>\n\nexport const Query = {\n /** Every row of an Entity: the query each transformation narrows. */\n from: <E extends AnyEntity>(entity: E): Query<E> => query(entity, [], []),\n\n /**\n * Narrows to the rows the predicate holds for. Two `where`s conjoin — the\n * second never replaces the first — so a fragment can be written once and\n * piped into any query over the same Entity:\n *\n * ```ts\n * const published = Query.where(Expr.eq(Post.fields.published, true))\n * Query.from(Post).pipe(published, Query.where(byTitle))\n * ```\n */\n where:\n (...predicates: ReadonlyArray<Predicate>) =>\n <E extends AnyEntity>(self: Query<E>): Query<E> => {\n if (predicates.length === 0) return self\n checkOwnership('where', 'a predicate', self.entity, predicates)\n return query(self.entity, [...self.where, ...predicates], self.orderBy)\n },\n\n /**\n * Reads the rows in this order. Two `orderBy`s append, so an earlier term\n * stays the more significant one and a later call adds a tie-breaker rather\n * than silently winning.\n */\n orderBy:\n (...terms: ReadonlyArray<OrderTerm>) =>\n <E extends AnyEntity>(self: Query<E>): Query<E> => {\n if (terms.length === 0) return self\n checkOwnership('orderBy', 'a term', self.entity, terms)\n return query(self.entity, self.where, [...self.orderBy, ...terms])\n },\n\n /**\n * What the whole query reads: the fields and inputs of every predicate and\n * every ordering term, and the operations it uses.\n */\n dependencies: (self: AnyQuery): Dependencies => dependenciesOf(...self.where, ...self.orderBy),\n\n /**\n * The operations this query needs that `supported` does not list, in the\n * order the query uses them. Empty means an interpreter declaring\n * `supported` can answer it.\n *\n * An interpreter declares what it runs and refuses the rest, rather than\n * ignoring an operation it does not implement — which would answer a\n * different question and say nothing. The refusal is the interpreter's to\n * raise: this only says what is missing, because what to do about it differs\n * between one that compiles at registration and one that runs a body\n * directly.\n *\n * ```ts\n * const missing = Query.unsupported(body, ['eq', 'isNull', 'isNotNull'])\n * if (missing.length > 0) throw new Error(`cannot run ${missing.join(', ')}`)\n * ```\n */\n unsupported: (self: AnyQuery, supported: ReadonlyArray<Operation>): ReadonlyArray<Operation> => {\n const runs = new Set(supported)\n return Query.dependencies(self).operations.filter(operation => !runs.has(operation))\n },\n\n /**\n * The whole query as readable text, one clause per line:\n *\n * ```text\n * FROM Post\n * WHERE Post.slug = $slug\n * AND Post.published = true\n * ORDER BY Post.updatedAt DESC\n * ```\n *\n * For an explanation or a diagnostic, never for an interpreter — see\n * `Expr.show`. A query with no `where` or no `orderBy` omits that line rather\n * than printing an empty one, so what is shown is what was written.\n */\n show: (self: AnyQuery): string =>\n [\n `FROM ${self.entity.name}`,\n ...self.where.map(\n (predicate, index) => `${index === 0 ? 'WHERE' : ' AND'} ${Expr.show(predicate)}`,\n ),\n ...(self.orderBy.length === 0\n ? []\n : [\n `ORDER BY ${self.orderBy\n .map(term => `${Expr.show(term.expr)} ${term.direction.toUpperCase()}`)\n .join(', ')}`,\n ]),\n ].join('\\n'),\n}\n\n/**\n * An expression as readable text, in the IR's own terms.\n *\n * This is for a human — an explanation, a diagnostic, a test that wants to\n * assert on a whole predicate at once — and deliberately **not** for an\n * interpreter. It is close enough to SQL to read at a glance and unlike it\n * everywhere that matters: an input is `$slug` rather than a bound parameter,\n * `contains` is named rather than rendered as somebody's `like`, and no\n * dialect's escaping or collation is implied. What actually ran is whatever\n * that backend compiled, which is not this.\n *\n * A predicate standing where a value is wanted is parenthesised, because\n * `x is not null = $archived` reads as three operands and is two. A predicate\n * that *is* the whole expression is not: nothing encloses it.\n */\nconst showExpr = (node: AnyExpr | Predicate): string => {\n switch (node._tag) {\n case 'Literal':\n return JSON.stringify(node.value) ?? String(node.value)\n case 'Field':\n return `${node.owner.name}.${node.key}`\n case 'Input':\n return `$${node.key}`\n case 'Eq':\n return `${showOperand(node.left)} = ${showOperand(node.right)}`\n case 'Null':\n return `${showOperand(node.operand)} is ${node.present ? 'not null' : 'null'}`\n case 'Contains':\n return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`\n }\n}\n\nconst showOperand = (node: Operandish): string =>\n isPredicate(node) ? `(${showExpr(node)})` : showExpr(node)\n","import { Option, Schema } from 'effect'\n\n/** What a schema says of itself to a person: its `title` and `description`. */\nexport interface SchemaWords {\n readonly title: Option.Option<string>\n readonly description: Option.Option<string>\n}\n\nconst text = (value: unknown): Option.Option<string> =>\n typeof value === 'string' ? Option.some(value) : Option.none()\n\nexport const Words = {\n /**\n * A schema's words, as a label and its help text. Under Effect 4 a checked\n * schema resolves to its last check's annotations, which say what the check\n * expects and carry no `title`, so a title given before the check is read from\n * the schema's own annotations. Read words through this, never through\n * `Schema.resolveAnnotations` directly.\n */\n of: (schema: Schema.Top): SchemaWords => {\n const resolved = Schema.resolveAnnotations(schema) ?? {}\n const own = schema.ast.annotations ?? {}\n return {\n title: Option.orElse(text(resolved.title), () => text(own['title'])),\n description: Option.orElse(text(resolved.description), () => text(own['description'])),\n }\n },\n}\n","/**\n * The reference interpreter: a query body run over rows already in memory.\n *\n * `foldkit-remote-drizzle` compiles a body to SQL. This runs the same body\n * directly, which is what makes \"source-neutral\" a fact rather than a claim —\n * the two are checked against each other over a real database, and a body that\n * means one thing here and another there is a bug in one of them.\n *\n * It is also the interpreter to reach for when there is no database: a test\n * that wants rows, a server assembling a page from values it already holds, or\n * a client judging rows it already has.\n *\n * It lives in `foldkit-entity` because it is the **reference semantics** of the\n * IR this package owns — what §6.0.1 means operationally rather than in prose —\n * and a specification's reference implementation belongs with the\n * specification. The rule that keeps it here: **it may depend on the IR and\n * nothing else.** The moment it wants a Remote concept it has moved to the\n * wrong place and should leave.\n *\n * **It follows SQL, not JavaScript.** Where the two disagree this follows SQL,\n * because SQL is what the other interpreter runs. The important case is null:\n * `null = null` is unknown in SQL and a row is not matched by it, where\n * JavaScript would happily call the two equal.\n */\nimport { Query, isPredicate } from './expr.js'\nimport type { AnyExpr, AnyQuery, Operandish, Operation, OrderTerm, Predicate } from './expr.js'\n\n/** A row as this interpreter reads one: values by field key. */\nexport type Row = Readonly<Record<string, unknown>>\n\nexport class QueryEvaluateError extends Error {\n constructor(message: string) {\n super(`[foldkit-entity] ${message}`)\n this.name = 'QueryEvaluateError'\n }\n}\n\nconst valueOf = (node: AnyExpr, row: Row, input: Row): unknown => {\n switch (node._tag) {\n case 'Field':\n return row[node.key]\n case 'Literal':\n return node.value\n case 'Input':\n return input[node.key]\n }\n}\n\n/** SQL's unknown: neither true nor false, and a row is kept only on true. */\ntype Truth = boolean | 'unknown'\n\nconst isNull = (value: unknown): boolean => value === null || value === undefined\n\n/** A predicate used as a value is its own truth; anything else is its value. */\nconst sideOf = (node: Operandish, row: Row, input: Row): unknown =>\n isPredicate(node) ? truthValue(holds(node, row, input)) : valueOf(node, row, input)\n\n/**\n * A predicate compared as a value. SQL's unknown is null there too, so an\n * unknown compared to anything stays unknown rather than becoming false.\n */\nconst truthValue = (truth: Truth): unknown => (truth === 'unknown' ? null : truth)\n\nconst holds = (node: Predicate, row: Row, input: Row): Truth => {\n switch (node._tag) {\n case 'Eq': {\n const left = sideOf(node.left, row, input)\n const right = sideOf(node.right, row, input)\n // `null = anything` is unknown in SQL, including `null = null`. A row is\n // kept only when a comparison is true, so an unknown drops it either way;\n // saying so explicitly is what keeps this honest about three-valued logic\n // rather than accidentally right about it.\n if (isNull(left) || isNull(right)) return 'unknown'\n return left === right\n }\n case 'Null':\n // The one comparison that is never unknown: asking whether a value is\n // absent always has an answer.\n return isNull(valueOf(node.operand, row, input)) !== node.present\n case 'Contains': {\n const value = valueOf(node.value, row, input)\n const search = sideOf(node.search, row, input)\n // `null like anything` is unknown, which is why an empty search is not\n // the same as no filter over a column that can be null.\n if (isNull(value) || isNull(search)) return 'unknown'\n if (typeof value !== 'string' || typeof search !== 'string') {\n throw new QueryEvaluateError('a containment test was given something that is not text')\n }\n // Case-insensitive, because that is what `Expr.contains` means and what\n // the compiled SQL folds both sides to. Plain `includes` would be\n // case-sensitive here and case-insensitive under SQLite's `like`, which\n // is a body meaning two things.\n return value.toLowerCase().includes(search.toLowerCase())\n }\n }\n}\n\n/** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */\nconst matches = (body: AnyQuery, row: Row, input: Row): boolean =>\n body.where.every(node => holds(node, row, input) === true)\n\nconst compare = (left: unknown, right: unknown, query: string): number => {\n if (typeof left === 'string' && typeof right === 'string') {\n return left < right ? -1 : left > right ? 1 : 0\n }\n if (typeof left === 'number' && typeof right === 'number') return left - right\n if (typeof left === 'boolean' && typeof right === 'boolean') {\n return Number(left) - Number(right)\n }\n throw new QueryEvaluateError(\n `query \"${query}\" orders by values this interpreter cannot compare (${typeof left} and ${typeof right})`,\n )\n}\n\nconst ordered = (rows: ReadonlyArray<Row>, terms: ReadonlyArray<OrderTerm>, query: string) => {\n if (terms.length === 0) return [...rows]\n return [...rows].sort((left, right) => {\n for (const term of terms) {\n if (term.expr._tag !== 'Field') {\n throw new QueryEvaluateError(\n `query \"${query}\" orders by something that is not a field, which this interpreter cannot run yet`,\n )\n }\n const a = left[term.expr.key]\n const b = right[term.expr.key]\n if (isNull(a) || isNull(b)) {\n throw new QueryEvaluateError(\n `query \"${query}\" orders by \"${term.expr.key}\", which is null in a row; where nulls sort is a thing databases disagree about, so it is outside what this interpreter will answer for`,\n )\n }\n const sign = compare(a, b, query)\n if (sign !== 0) return term.direction === 'asc' ? sign : -sign\n }\n return 0\n })\n}\n\n/**\n * The operations this interpreter runs. It is the reference, so this is the\n * whole kernel — but it is declared rather than assumed, because an\n * interpreter that gains an operator and forgets to say so is exactly what\n * `Query.unsupported` exists to catch.\n */\nexport const supported: ReadonlyArray<Operation> = ['eq', 'isNull', 'isNotNull', 'contains']\n\n/**\n * Refuses a body needing an operation this interpreter does not run, rather\n * than skipping it and answering a different question. Called by `evaluate`;\n * call it directly to check a body once instead of on every run.\n */\nexport const assertSupported = (body: AnyQuery): void => {\n const missing = Query.unsupported(body, supported)\n if (missing.length > 0) {\n throw new QueryEvaluateError(\n `this interpreter does not run ${missing.join(', ')}, which query \"${body.entity.name}\" needs`,\n )\n }\n}\n\n/**\n * The rows the body matches, in the order it asks for. Pure: it reads the rows\n * it is given and nothing else.\n *\n * `input` holds the values this run was given, by the keys the body's\n * placeholders were built with — the same record the query would be called\n * with anywhere else.\n */\nexport const evaluate = (\n body: AnyQuery,\n input: Row,\n rows: ReadonlyArray<Row>,\n): ReadonlyArray<Row> => {\n assertSupported(body)\n return ordered(\n rows.filter(row => matches(body, row, input)),\n body.orderBy,\n body.entity.name,\n )\n}\n","/**\n * `foldkit-entity` — domain structure as typed values.\n *\n * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations\n * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable\n * values an interpreter supplies). It describes; it fetches, stores, and\n * renders nothing. Remote, Drizzle, and form packages interpret it and attach\n * what they need as `foldkit-metadata`.\n */\nimport { Pipeable, Schema } from 'effect'\nimport { Metadata } from 'foldkit-metadata'\nimport { SchemaShape } from './shape.js'\n\nexport const EntityTypeId: unique symbol = Symbol.for('foldkit-entity/Entity')\nexport type EntityTypeId = typeof EntityTypeId\n\n/**\n * What makes two descriptors the same Entity. A pipe step returns a new\n * descriptor with the same identity, so compare `identity`, never the objects.\n */\nexport interface EntityIdentity<Name extends string> {\n readonly name: Name\n /** Distinguishes two Entities that were defined with the same name. */\n readonly token: symbol\n}\n\n/** An intrinsic value of the Entity: one property of `entity.schema`. */\nexport interface EntityField<Name extends string, Key extends string, S extends Schema.Constraint> {\n readonly _tag: 'Field'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type Cardinality = 'one' | 'many'\n\n/** What `Relation.one` / `Relation.many` return, before `Entity.relate` binds it to an owner. */\nexport interface RelationSpec<\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly target: Target\n readonly cardinality: C\n readonly optional: Optional\n}\n\n/**\n * A navigation edge as its owner sees it: one or many of `target`. How the edge\n * is stored (a foreign key, a join table, a nested document) is the\n * interpreter's concern.\n */\nexport interface EntityRelation<\n Name extends string,\n Key extends string,\n Target extends AnyEntity,\n C extends Cardinality,\n Optional extends boolean,\n> {\n readonly _tag: 'Relation'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n /** The target as `Entity.relate` returned it, so its own relations can be followed. */\n readonly target: () => Target\n readonly cardinality: C\n readonly optional: Optional\n readonly metadata: Metadata\n}\n\n/** What `Derived.make` returns, before an Entity owns it. */\nexport interface DerivedSpec<S extends Schema.Constraint> {\n readonly schema: S\n}\n\n/**\n * A value consumers may read that is not part of `entity.schema`. It says\n * nothing about how the value is computed; an interpreter supplies it.\n */\nexport interface EntityDerived<\n Name extends string,\n Key extends string,\n S extends Schema.Constraint,\n> {\n readonly _tag: 'Derived'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly metadata: Metadata\n}\n\nexport type EntityMember =\n | EntityField<string, string, Schema.Constraint>\n | EntityRelation<string, string, AnyEntity, Cardinality, boolean>\n | EntityDerived<string, string, Schema.Constraint>\n\nexport type RelationSpecs = Readonly<Record<string, RelationSpec<AnyEntity, Cardinality, boolean>>>\nexport type DerivedSpecs = Readonly<Record<string, DerivedSpec<Schema.Constraint>>>\n\ntype FieldsOf<Name extends string, Fields extends Schema.Struct.Fields> = {\n readonly [K in keyof Fields & string]: EntityField<Name, K, Fields[K]>\n}\ntype RelationsOf<Name extends string, Relations extends RelationSpecs> = {\n readonly [K in keyof Relations & string]: Relations[K] extends RelationSpec<\n infer Target,\n infer C,\n infer Optional\n >\n ? EntityRelation<Name, K, Target, C, Optional>\n : never\n}\ntype DerivedOf<Name extends string, Derived extends DerivedSpecs> = {\n readonly [K in keyof Derived & string]: EntityDerived<Name, K, Derived[K]['schema']>\n}\n\nexport interface Entity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n>\n extends Pipeable.Pipeable {\n readonly [EntityTypeId]: EntityTypeId\n readonly identity: EntityIdentity<Name>\n readonly name: Name\n /** The intrinsic value only: no relations, no derived members. */\n readonly schema: Schema.Struct<Fields>\n readonly fields: FieldsOf<Name, Fields>\n readonly relations: RelationsOf<Name, Relations>\n readonly derived: DerivedOf<Name, Derived>\n /** Every readable member under one namespace; keys never collide. */\n readonly members: FieldsOf<Name, Fields> & RelationsOf<Name, Relations> & DerivedOf<Name, Derived>\n readonly metadata: Metadata\n}\n\nexport type AnyEntity = Entity<string, any, any, any>\n\n/** Unsatisfiable when a new key is already a member, so the pipe step is the error site. */\ntype Free<E extends AnyEntity, New> = keyof New & keyof E['members'] extends never\n ? unknown\n : { readonly alreadyAMember: keyof New & keyof E['members'] }\n\ntype WithDerived<E, New extends DerivedSpecs> =\n E extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R, D & New>\n : never\n\nexport type Entities = Readonly<Record<string, AnyEntity>>\nexport type RelationMap<Es extends Entities> = { readonly [K in keyof Es]?: RelationSpecs }\n\n/** The key in `Es` of the Entity a spec targets, matched by name. */\nexport type TargetKey<Es extends Entities, Target extends AnyEntity> = {\n [K in keyof Es]: [Es[K]['name'], Target['name']] extends [Target['name'], Es[K]['name']]\n ? K\n : never\n}[keyof Es]\n\nexport type RelatedSpecs<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> = {\n readonly [R in keyof Rs[K]]: Rs[K][R] extends RelationSpec<infer Target, infer C, infer Optional>\n ? RelationSpec<Related<Es, Rs, TargetKey<Es, Target>>, C, Optional>\n : never\n}\n\n/**\n * One Entity of an `Entity.relate` result. A relation's target is again a\n * `Related`, so relations can be followed through a cycle; the recursion goes\n * through type arguments, which TypeScript resolves only when asked.\n */\nexport type Related<Es extends Entities, Rs extends RelationMap<Es>, K extends keyof Es> =\n Es[K] extends Entity<infer Name, infer Fields, infer R, infer D>\n ? Entity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D>\n : never\n\n/** Marks a relation key that is already a member of its owner, or an owner that is not listed. */\ntype CheckRelations<Es extends Entities, Rs> = {\n readonly [K in keyof Rs]: K extends keyof Es\n ? {\n readonly [R in keyof Rs[K]]: R extends keyof Es[K]['members']\n ? `\"${R & string}\" is already a member of ${Es[K]['name']}`\n : Rs[K][R]\n }\n : 'not one of the entities being related'\n}\n\nexport const SelectionTypeId: unique symbol = Symbol.for('foldkit-entity/Selection')\nexport type SelectionTypeId = typeof SelectionTypeId\n\n/**\n * The schema that identifies one of an Entity: its `id` field when that is text\n * (a plain string, a brand, a pattern), and plain text otherwise. An id is text\n * because a ref travels and is stored as text; an Entity keyed by a number still\n * has refs, and their ids are the number as text.\n */\nexport type IdSchemaOf<E> = E extends {\n readonly fields: { readonly id: { readonly schema: infer S } }\n}\n ? S extends Schema.Constraint\n ? [S['Type']] extends [string]\n ? S\n : Schema.String\n : Schema.String\n : Schema.String\n\n/** What identifies one of an Entity: `IdOf<typeof Blog.Post>` is `PostId` when its `id` field is one. */\nexport type IdOf<E> = IdSchemaOf<E>['Type']\n\n/**\n * What a relation selected with `true` yields: which Entity, and which one. `Id`\n * is the target's own id type, so a ref to an Author cannot be used as a Post's.\n */\nexport interface EntityRef<Name extends string = string, Id extends string = string> {\n readonly entity: Name\n readonly id: Id\n}\n\ntype RefSchema<Target extends AnyEntity> = Schema.Struct<{\n readonly entity: Schema.Literal<Target['name']>\n readonly id: IdSchemaOf<Target>\n}>\n\n/**\n * A view of the Entity graph: which members to read, and the schema of the\n * value that results. It says nothing about where the value comes from.\n */\nexport interface Selection<\n Name extends string,\n Members,\n S extends Schema.Constraint,\n Id extends string = string,\n> {\n readonly [SelectionTypeId]: SelectionTypeId\n /** Type-only: the id type of the Entity selected, so a reader can ask for the right one. Never set. */\n readonly Id?: Id\n readonly entity: Entity<Name, any, any, any>\n /** What was selected, by member key: `true`, or a relation's nested Selection. */\n readonly members: Members\n readonly schema: S\n}\n\ntype AnySelection<Name extends string = string> = Selection<Name, any, any>\n\n/** The value a Selection reads: `Selected<typeof PostCard>` is one card's fields. */\nexport type Selected<S extends Selection<string, unknown, Schema.Constraint>> = S['schema']['Type']\n\n/** `true` for any member; a relation also takes a Selection of its target. */\n/**\n * Which part of a `many` relation to read: the first or last so many, from a\n * cursor or from the end. A cursor is whatever the interpreter handed out with an\n * earlier page; nothing here looks inside it.\n */\nexport interface PageWindow {\n readonly first?: number | undefined\n readonly last?: number | undefined\n readonly after?: string | undefined\n readonly before?: string | undefined\n}\n\nexport const SelectionPageTypeId: unique symbol = Symbol.for('foldkit-entity/SelectionPage')\nexport type SelectionPageTypeId = typeof SelectionPageTypeId\n\n/** A Selection of a `many` relation's target, read a page at a time. */\nexport interface SelectionPage<Name extends string, S extends Schema.Constraint> {\n readonly [SelectionPageTypeId]: SelectionPageTypeId\n readonly selection: Selection<Name, any, S>\n readonly window: PageWindow\n}\n\ntype PageSchema<S extends Schema.Constraint> = Schema.Struct<{\n readonly items: Schema.$Array<S>\n readonly hasNext: Schema.Boolean\n readonly hasPrevious: Schema.Boolean\n}>\n\ntype SelectionSpec<E extends AnyEntity, Spec> = {\n readonly [K in keyof Spec]: K extends keyof E['relations']\n ? E['relations'][K] extends EntityRelation<any, any, infer Target, infer C, any>\n ? | true\n | AnySelection<Target['name']>\n // Only a `many` relation has pages.\n | (C extends 'many' ? SelectionPage<Target['name'], any> : never)\n : never\n : K extends keyof E['members']\n ? true\n : `\"${K & string}\" is not a member of ${E['name']}`\n}\n\ntype RelationShape<\n C extends Cardinality,\n Optional extends boolean,\n S extends Schema.Constraint,\n> = C extends 'many' ? Schema.$Array<S> : Optional extends true ? Schema.NullOr<S> : S\n\ntype SelectedSchema<Member, Selected> = Member extends\n EntityField<any, any, infer S> | EntityDerived<any, any, infer S>\n ? S\n : Member extends EntityRelation<any, any, infer Target, infer C, infer Optional>\n ? Selected extends SelectionPage<any, infer S>\n ? PageSchema<S>\n : RelationShape<\n C,\n Optional,\n Selected extends Selection<any, any, infer S> ? S : RefSchema<Target>\n >\n : never\n\ntype SelectionSchema<E extends AnyEntity, Spec> = Schema.Struct<{\n readonly [K in keyof Spec & keyof E['members']]: SelectedSchema<E['members'][K], Spec[K]>\n}>\n\n/** The `id` field's schema when it is text, so a ref's id keeps its brand and its checks; else text. */\nconst idSchemaOf = (entity: AnyEntity): Schema.Top => {\n const fields: Readonly<Record<string, EntityMember | undefined>> = entity.fields\n const id = fields.id\n if (id === undefined || id._tag !== 'Field') return Schema.String\n const type = Schema.toType(id.schema as Schema.Top)\n return SchemaShape.isText(type.ast) ? type : Schema.String\n}\n\nconst isSelectionPage = (value: unknown): value is SelectionPage<string, Schema.Constraint> =>\n typeof value === 'object' && value !== null && SelectionPageTypeId in value\n\nconst isSelection = (value: unknown): value is AnySelection =>\n typeof value === 'object' && value !== null && SelectionTypeId in value\n\n/** An input key that carries a relation's target: the id of a `one`, the ids of a `many`. */\nexport interface RelationInput<R extends EntityRelation<any, any, any, any, any>> {\n readonly _tag: 'RelationInput'\n readonly relation: R\n}\n\n/**\n * An input key that carries the relation's target itself, written through an\n * input of its own: a post created with a new author, an order with its lines.\n * A `one` holds that input's value, a `many` a list of them.\n */\nexport interface NestedInput<\n R extends EntityRelation<any, any, any, any, any>,\n I extends EntityInput<any, any, any>,\n> {\n readonly _tag: 'NestedInput'\n readonly relation: R\n readonly input: I\n}\n\n/** An input key that is about the operation, not the Entity: a reason, a flag, a confirmation. */\nexport interface Unmapped {\n readonly _tag: 'Unmapped'\n}\n\n/** What one key of an operation's input means in terms of the Entity. */\nexport type InputMember =\n | EntityField<string, string, Schema.Constraint>\n | RelationInput<EntityRelation<string, string, AnyEntity, Cardinality, boolean>>\n | NestedInput<\n EntityRelation<string, string, AnyEntity, Cardinality, boolean>,\n EntityInput<AnyEntity, any, any>\n >\n | Unmapped\n\n/** The ids a relation takes as input: one id, a nullable id, or a list of ids. */\ntype RelationIds<R> =\n R extends EntityRelation<any, any, infer Target, infer C, infer Optional>\n ? C extends 'many'\n ? ReadonlyArray<IdOf<Target>>\n : Optional extends true\n ? IdOf<Target> | null\n : IdOf<Target>\n : never\n\n/** What a nested input takes: the value of the target's input, or a list of them for a `many`. */\ntype NestedValues<R, I> =\n I extends EntityInput<any, infer Fields, any>\n ? R extends EntityRelation<any, any, any, 'many', any>\n ? ReadonlyArray<Schema.Struct.Type<Fields>>\n : Schema.Struct.Type<Fields>\n : never\n\n/**\n * Only the value that is present has to fit: an input may leave a key out (a\n * partial update) or send `null` to clear it. Whether it may is the input\n * schema's rule; the fit only guards against mapping the wrong member.\n */\ntype Present<T> = Exclude<T, null | undefined>\n\ntype MappingFor<Name extends string, Input, M> = M extends Unmapped\n ? M\n : M extends\n | EntityField<infer Owner, any, any>\n | RelationInput<EntityRelation<infer Owner, any, any, any, any>>\n | NestedInput<EntityRelation<infer Owner, any, any, any, any>, any>\n ? [Owner] extends [Name]\n ? M extends EntityField<any, any, infer S>\n ? Present<Input> extends Schema.Schema.Type<S>\n ? M\n : 'the input value does not fit this field'\n : M extends RelationInput<infer R>\n ? Present<Input> extends RelationIds<R>\n ? M\n : 'the input value is not the id shape of this relation'\n : M extends NestedInput<infer R, infer I>\n ? R extends EntityRelation<any, any, infer Target, any, any>\n ? I extends EntityInput<infer Of, any, any>\n ? [Of['name']] extends [Target['name']]\n ? Present<Input> extends NestedValues<R, I>\n ? M\n : 'the input value is not the value of the nested input'\n : `the nested input is of ${Of['name']}, not ${Target['name']}`\n : never\n : never\n : never\n : `this member belongs to ${Owner}`\n : 'map an input key to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped'\n\n/** A key that names a field whose value it fits maps itself; every other key needs an entry. */\ntype SelfMapped<E extends AnyEntity, Fields extends Schema.Struct.Fields> = {\n [K in keyof Fields]: K extends keyof E['fields']\n ? Present<Schema.Schema.Type<Fields[K]>> extends Schema.Schema.Type<E['fields'][K]['schema']>\n ? K\n : never\n : never\n}[keyof Fields]\n\n/**\n * A mapping written as a member's key: `'title'` is that Field, and `'author'` is\n * `Relation.input` of that relation. Nothing is inferred from the input key's own\n * name; the member is still named, only more briefly.\n */\ntype Named<E extends AnyEntity, M> = M extends string\n ? M extends keyof E['fields']\n ? E['fields'][M]\n : M extends keyof E['relations']\n ? RelationInput<E['relations'][M]>\n : `\"${M}\" names no field or relation of ${E['name']}`\n : M\n\ntype InputMapping<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = {\n readonly [K in Exclude<keyof Fields, SelfMapped<E, Fields>>]: unknown\n} & {\n readonly [K in keyof Mapping]: K extends keyof Fields\n ? Named<E, Mapping[K]> extends infer Member\n ? Member extends string\n ? Member\n : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member> extends Member\n ? Mapping[K]\n : MappingFor<E['name'], Schema.Schema.Type<Fields[K]>, Member>\n : never\n : `\"${K & string}\" is not a key of the input`\n}\n\ntype InputMembers<E extends AnyEntity, Fields extends Schema.Struct.Fields, Mapping> = {\n readonly [K in keyof Fields]: K extends keyof Mapping\n ? Named<E, Mapping[K]>\n : K extends keyof E['fields']\n ? E['fields'][K]\n : never\n}\n\n/**\n * An operation's input read against an Entity: which member each input key\n * writes. The operation decides what may be submitted; the Entity only says\n * what each submitted key means.\n */\nexport interface EntityInput<E extends AnyEntity, Fields extends Schema.Struct.Fields, Members> {\n readonly entity: E\n readonly schema: Schema.Struct<Fields>\n readonly members: Members\n}\n\n/** The Entity member an input key writes, by its key; nothing for an unmapped key. */\nexport type WrittenKey<M> =\n M extends EntityField<any, infer Key, any>\n ? Key\n : M extends\n | RelationInput<EntityRelation<any, infer Key, any, any, any>>\n | NestedInput<EntityRelation<any, infer Key, any, any, any>, any>\n ? Key\n : never\n\n/** A nested input reads what it writes of the target; every other member reads as it is. */\nexport type WrittenAs<M> =\n M extends NestedInput<any, EntityInput<infer Of, any, infer Members>>\n ? Selection<Of['name'], WrittenSpec<Members>, SelectionSchema<Of, WrittenSpec<Members>>>\n : true\n\n/** Every member the input writes: what to read to show the input's current values. */\nexport type WrittenSpec<Members> = {\n readonly [K in keyof Members as WrittenKey<Members[K]>]: WrittenAs<Members[K]>\n}\n\nconst unmapped: Unmapped = Object.freeze({ _tag: 'Unmapped' })\n\ninterface Parts {\n readonly identity: EntityIdentity<string>\n readonly schema: Schema.Struct<Schema.Struct.Fields>\n readonly fields: Readonly<Record<string, EntityMember>>\n readonly relations: Readonly<Record<string, EntityMember>>\n readonly derived: Readonly<Record<string, EntityMember>>\n readonly metadata: Metadata\n}\n\nconst EntityProto = {\n [EntityTypeId]: EntityTypeId,\n pipe() {\n return Pipeable.pipeArguments(this, arguments)\n },\n}\n\nconst make = (parts: Parts): AnyEntity =>\n Object.freeze(\n Object.assign(Object.create(EntityProto), parts, {\n name: parts.identity.name,\n fields: Object.freeze(parts.fields),\n relations: Object.freeze(parts.relations),\n derived: Object.freeze(parts.derived),\n members: Object.freeze({ ...parts.fields, ...parts.relations, ...parts.derived }),\n }),\n )\n\nconst isSameEntity = (left: AnyEntity, right: AnyEntity): boolean =>\n left.identity.token === right.identity.token\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`Entity \"${entity.name}\": ${message}`)\n}\n\nconst isEntity = (value: unknown): value is AnyEntity =>\n typeof value === 'object' && value !== null && EntityTypeId in value\n\nconst kindName = { Field: 'field', Relation: 'relation', Derived: 'derived member' } as const\n\nconst kindOf = (entity: AnyEntity, key: string): string | undefined => {\n const member = (entity.members as Readonly<Record<string, EntityMember>>)[key]\n return member && kindName[member._tag]\n}\n\nconst assertFree = (entity: AnyEntity, keys: ReadonlyArray<string>, adding: string): void => {\n for (const key of keys) {\n const kind = kindOf(entity, key)\n if (kind !== undefined)\n throw new Error(\n `Entity \"${entity.name}\": cannot add ${adding} \"${key}\", it is already a ${kind}`,\n )\n }\n}\n\nconst mapValues = <A, B>(\n record: Readonly<Record<string, A>>,\n f: (value: A, key: string) => B,\n): Record<string, B> =>\n Object.fromEntries(Object.entries(record).map(([key, value]) => [key, f(value, key)]))\n\nexport const Entity = {\n /** Declares an Entity from its intrinsic fields. Each call is a new identity. */\n define: <const Name extends string, Fields extends Schema.Struct.Fields>(\n name: Name,\n schema: Schema.Struct<Fields>,\n ): Entity<Name, Fields> => {\n const identity: EntityIdentity<Name> = Object.freeze({ name, token: Symbol(name) })\n return make({\n identity,\n schema,\n fields: mapValues(schema.fields, (fieldSchema, key) =>\n Object.freeze({\n _tag: 'Field',\n owner: identity,\n key,\n schema: fieldSchema,\n metadata: Metadata.empty,\n }),\n ),\n relations: {},\n derived: {},\n metadata: Metadata.empty,\n }) as Entity<Name, Fields>\n },\n\n /**\n * Declares the relations between a set of Entities in one step, and returns\n * them related. One step, because Entities that point at each other cannot\n * each be declared in terms of the other.\n */\n relate: <const Es extends Entities, const Rs extends RelationMap<Es>>(\n entities: Es,\n relations: Rs & CheckRelations<Es, Rs>,\n ): { readonly [K in keyof Es]: Related<Es, Rs, K> } => {\n const keyByToken = new Map<symbol, string>()\n for (const [key, entity] of Object.entries(entities)) {\n if (!isEntity(entity)) throw new Error(`Entity.relate: \"${key}\" is not an Entity`)\n const earlier = keyByToken.get(entity.identity.token)\n if (earlier !== undefined)\n throw new Error(`Entity.relate: \"${earlier}\" and \"${key}\" are the same Entity`)\n keyByToken.set(entity.identity.token, key)\n }\n const given: Readonly<Record<string, RelationSpecs | undefined>> = relations\n for (const owner of Object.keys(given))\n if (!(owner in entities))\n throw new Error(`Entity.relate: relations given for \"${owner}\", which is not being related`)\n\n const related: Record<string, AnyEntity> = {}\n for (const [ownerKey, entity] of Object.entries(entities)) {\n const specs = given[ownerKey] ?? {}\n assertFree(entity, Object.keys(specs), 'relation')\n const added = mapValues<RelationSpec<AnyEntity, Cardinality, boolean>, EntityMember>(\n specs,\n (spec, key) => {\n const targetKey = isEntity(spec.target)\n ? keyByToken.get(spec.target.identity.token)\n : undefined\n if (targetKey === undefined)\n throw new Error(\n `Entity \"${entity.name}\": relation \"${key}\" targets an Entity that is not being related`,\n )\n return Object.freeze({\n _tag: 'Relation',\n owner: entity.identity,\n key,\n // Read on call: the target may come later in `entities` than its owner.\n target: () => related[targetKey]!,\n cardinality: spec.cardinality,\n optional: spec.optional,\n metadata: Metadata.empty,\n })\n },\n )\n related[ownerKey] = make({ ...entity, relations: { ...entity.relations, ...added } })\n }\n return Object.freeze(related) as never\n },\n\n /**\n * Selects members of an Entity and assembles the schema of the result. A\n * relation selected with `true` yields an `EntityRef`; with a Selection of its\n * target, that Selection's value. `many` yields an array, an optional `one`\n * is nullable.\n */\n select: <E extends AnyEntity, const Spec>(\n entity: E,\n spec: Spec & SelectionSpec<E, Spec>,\n ): Selection<E['name'], Spec, SelectionSchema<E, Spec>, IdOf<E>> => {\n const members: Readonly<Record<string, EntityMember>> = entity.members\n const fields = mapValues<unknown, Schema.Constraint>(spec, (selected, key) => {\n const member = members[key]\n if (member === undefined)\n throw new Error(`Entity \"${entity.name}\": cannot select \"${key}\", it is not a member`)\n if (member._tag !== 'Relation') {\n if (selected !== true)\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" is a ${kindName[member._tag]}, select it with true`,\n )\n return member.schema\n }\n const target = member.target()\n if (isSelectionPage(selected)) {\n if (member.cardinality !== 'many')\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" is one ${target.name}, so it has no pages`,\n )\n if (!isSameEntity(selected.selection.entity, target))\n throw new Error(`Entity \"${entity.name}\": \"${key}\" pages a Selection of ${target.name}`)\n return Schema.Struct({\n items: Schema.Array(selected.selection.schema as Schema.Top),\n hasNext: Schema.Boolean,\n hasPrevious: Schema.Boolean,\n })\n }\n let item: Schema.Top\n if (selected === true)\n item = Schema.Struct({ entity: Schema.Literal(target.name), id: idSchemaOf(target) })\n else if (isSelection(selected) && isSameEntity(selected.entity, target))\n item = selected.schema\n else\n throw new Error(\n `Entity \"${entity.name}\": \"${key}\" takes true or a Selection of ${target.name}`,\n )\n return member.cardinality === 'many'\n ? Schema.Array(item)\n : member.optional\n ? Schema.NullOr(item)\n : item\n })\n return Object.freeze({\n [SelectionTypeId]: SelectionTypeId,\n entity,\n members: spec,\n schema: Schema.Struct(fields),\n }) as never\n },\n\n /**\n * A `many` relation read a page at a time, in place of its Selection:\n * `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page\n * of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.\n */\n page: <Name extends string, S extends Schema.Constraint>(\n selection: Selection<Name, any, S>,\n window: PageWindow,\n ): SelectionPage<Name, S> => {\n const sides = [window.first, window.last].filter(size => size !== undefined)\n if (sides.length !== 1 || !sides.every(size => Number.isInteger(size) && size >= 0))\n throw new Error(\n `Entity.page: a window of ${selection.entity.name} takes first or last, a non-negative integer`,\n )\n if (\n (window.first !== undefined && window.before !== undefined) ||\n (window.last !== undefined && window.after !== undefined)\n )\n throw new Error(\n `Entity.page: a window of ${selection.entity.name} reads first after a cursor, or last before one`,\n )\n const page: SelectionPage<Name, S> = {\n [SelectionPageTypeId]: SelectionPageTypeId,\n selection,\n window,\n }\n return Object.freeze(page)\n },\n\n /** Adds readable members that are not part of `entity.schema`. */\n derived:\n <const New extends DerivedSpecs>(specs: New) =>\n <E extends AnyEntity>(entity: E & Free<E, New>): WithDerived<E, New> => {\n assertFree(entity, Object.keys(specs), 'derived member')\n const added = mapValues<DerivedSpec<Schema.Constraint>, EntityMember>(specs, (spec, key) =>\n Object.freeze({\n _tag: 'Derived',\n owner: entity.identity,\n key,\n schema: spec.schema,\n metadata: Metadata.empty,\n }),\n )\n return make({ ...entity, derived: { ...entity.derived, ...added } }) as never\n },\n\n /** Attaches an interpreter's metadata to the Entity itself. */\n annotate:\n (metadata: Metadata) =>\n <E extends AnyEntity>(entity: E): E =>\n make({ ...entity, metadata: Metadata.combine([entity.metadata, metadata]) }) as E,\n\n /** Attaches an interpreter's metadata to members, by key. */\n annotateMembers:\n <E extends AnyEntity>(metadata: { readonly [K in keyof E['members']]?: Metadata }) =>\n (entity: E): E => {\n const given = metadata as Readonly<Record<string, Metadata | undefined>>\n for (const key of Object.keys(given))\n if (kindOf(entity, key) === undefined)\n throw new Error(`Entity \"${entity.name}\": cannot annotate \"${key}\", it is not a member`)\n const annotate = (members: Readonly<Record<string, EntityMember>>) =>\n mapValues(members, (member, key) => {\n const extra = given[key]\n return extra === undefined\n ? member\n : Object.freeze({ ...member, metadata: Metadata.combine([member.metadata, extra]) })\n })\n return make({\n ...entity,\n fields: annotate(entity.fields),\n relations: annotate(entity.relations),\n derived: annotate(entity.derived),\n }) as E\n },\n\n /**\n * Reads an operation's input schema against an Entity. A key that names a\n * field maps to it; any other key is mapped explicitly, to a Field, to\n * `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred\n * from a naming convention such as `authorId`.\n */\n input: <\n E extends AnyEntity,\n Fields extends Schema.Struct.Fields,\n // `{}` when every key maps itself, so the argument can be omitted.\n const Mapping = {},\n >(\n entity: E,\n schema: Schema.Struct<Fields>,\n ...mapping: keyof InputMapping<E, Fields, Mapping> extends never\n ? [mapping?: Mapping & InputMapping<E, Fields, Mapping>]\n : [mapping: Mapping & InputMapping<E, Fields, Mapping>]\n ): EntityInput<E, Fields, InputMembers<E, Fields, Mapping>> => {\n const written: Readonly<Record<string, InputMember | string | undefined>> = mapping[0] ?? {}\n for (const key of Object.keys(written))\n if (!(key in schema.fields))\n throw new Error(`Entity \"${entity.name}\": \"${key}\" is mapped but is not a key of the input`)\n // A member named by its key: a Field as it is, a relation as its ids.\n const named = (key: string, name: string): InputMember => {\n const member = (entity.members as Readonly<Record<string, EntityMember | undefined>>)[name]\n switch (member?._tag) {\n case 'Field':\n return member\n case 'Relation':\n return Object.freeze({ _tag: 'RelationInput', relation: member })\n case 'Derived':\n case undefined:\n return fail(\n entity,\n `input key \"${key}\" is mapped to \"${name}\", which names no field or relation`,\n )\n }\n }\n const given: Readonly<Record<string, InputMember | undefined>> = mapValues(\n written,\n (member, key) => (typeof member === 'string' ? named(key, member) : member),\n )\n const fields: Readonly<Record<string, InputMember | undefined>> = entity.fields\n const members = mapValues(schema.fields, (_, key) => {\n const member =\n given[key] ??\n fields[key] ??\n fail(entity, `input key \"${key}\" names no field; map it to a member or Entity.unmapped`)\n const owned =\n member._tag === 'Field'\n ? member\n : member._tag === 'RelationInput' || member._tag === 'NestedInput'\n ? member.relation\n : member._tag === 'Unmapped'\n ? undefined\n : fail(\n entity,\n `input key \"${key}\" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`,\n )\n if (owned !== undefined && owned.owner.token !== entity.identity.token)\n fail(entity, `input key \"${key}\" is mapped to a member of \"${owned.owner.name}\"`)\n if (\n member._tag === 'NestedInput' &&\n !isSameEntity(member.input.entity, member.relation.target())\n )\n fail(\n entity,\n `input key \"${key}\" nests an input of \"${member.input.entity.name}\", but \"${member.relation.key}\" is of \"${member.relation.target().name}\"`,\n )\n return member\n })\n return Object.freeze({ entity, schema, members: Object.freeze(members) }) as never\n },\n\n /** For an input key that is about the operation rather than the Entity. */\n unmapped,\n\n /**\n * The schemas of some of an Entity's fields, by key, to spread into an input's\n * struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.\n * The input then keeps the field's own rules, and its keys map themselves.\n */\n fields: <E extends AnyEntity, const Keys extends ReadonlyArray<keyof E['fields'] & string>>(\n entity: E,\n ...keys: Keys\n ): { readonly [K in Keys[number]]: E['fields'][K]['schema'] } =>\n Object.fromEntries(\n keys.map(key => [\n key,\n (\n (\n entity.fields as Readonly<\n Record<string, EntityField<string, string, Schema.Constraint> | undefined>\n >\n )[key] ?? fail(entity, `\"${key}\" is not a field`)\n ).schema,\n ]),\n ) as never,\n\n /**\n * The Selection of every member an input writes, with each relation as refs:\n * what an edit screen loads before it shows the input's current values.\n */\n selectFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n ): Selection<\n E['name'],\n WrittenSpec<Members>,\n SelectionSchema<E, WrittenSpec<Members>>,\n IdOf<E>\n > => {\n const members: Readonly<Record<string, InputMember>> = input.members as never\n const spec = Object.fromEntries(\n Object.values(members).flatMap((member): ReadonlyArray<readonly [string, unknown]> =>\n member._tag === 'Field'\n ? [[member.key, true]]\n : member._tag === 'RelationInput'\n ? [[member.relation.key, true]]\n : member._tag === 'NestedInput'\n ? // What the nested input writes of the target, so its keys can be shown too.\n [[member.relation.key, Entity.selectFor(member.input)]]\n : [],\n ),\n )\n return Entity.select(input.entity, spec as never) as never\n },\n\n /**\n * The input values that reproduce `value`, a value read through `selectFor`\n * (or any Selection with those members): a field as it is, a relation as the\n * id or ids of its refs. A key whose member `value` lacks is left out, as is\n * an unmapped key, which the Entity knows nothing about.\n */\n valuesFor: <E extends AnyEntity, Fields extends Schema.Struct.Fields, Members>(\n input: EntityInput<E, Fields, Members>,\n value: Readonly<Record<string, unknown>>,\n ): Partial<Schema.Struct.Type<Fields>> => {\n const members: Readonly<Record<string, InputMember>> = input.members as never\n // The id of a ref or of a nested Selection's value; `undefined` when it has none.\n const idOf = (held: unknown): unknown =>\n held === null\n ? null\n : typeof held === 'object' && 'id' in held\n ? held.id\n : typeof held === 'string'\n ? held\n : undefined\n const entries = Object.entries(members).flatMap(([key, member]) => {\n if (member._tag === 'Unmapped') return []\n const written = member._tag === 'Field' ? member.key : member.relation.key\n if (!(written in value)) return []\n const read = value[written]\n switch (member._tag) {\n case 'Field':\n return [[key, read] as const]\n case '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 case 'RelationInput': {\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 }\n })\n return Object.fromEntries(entries) as Partial<Schema.Struct.Type<Fields>>\n },\n\n is: isEntity,\n\n /** True when both descriptors are versions of one Entity. */\n same: isSameEntity,\n}\n\nfunction one<Target extends AnyEntity>(target: Target): RelationSpec<Target, 'one', false>\nfunction one<Target extends AnyEntity, const Optional extends boolean>(\n target: Target,\n options: { readonly optional: Optional },\n): RelationSpec<Target, 'one', Optional>\nfunction one(\n target: AnyEntity,\n options?: { readonly optional: boolean },\n): RelationSpec<AnyEntity, 'one', boolean> {\n return { target, cardinality: 'one', optional: options?.optional ?? false }\n}\n\n/** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */\nexport const Relation = {\n one,\n\n /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */\n input: <R extends EntityRelation<any, any, any, any, any>>(relation: R): RelationInput<R> =>\n Object.freeze({ _tag: 'RelationInput', relation }),\n\n /**\n * For `Entity.input`: the input key holds the relation's target itself, written\n * through `input`, an `Entity.input` of the target. A `many` holds a list.\n */\n nested: <R extends EntityRelation<any, any, any, any, any>, I extends EntityInput<any, any, any>>(\n relation: R,\n input: I,\n ): NestedInput<R, I> => Object.freeze({ _tag: 'NestedInput', relation, input }),\n\n many: <Target extends AnyEntity>(target: Target): RelationSpec<Target, 'many', false> => ({\n target,\n cardinality: 'many',\n optional: false,\n }),\n}\n\nexport const Derived = {\n make: <S extends Schema.Constraint>(schema: S): DerivedSpec<S> => ({ schema }),\n}\n\nexport * from './expr.js'\nexport * from './words.js'\nexport * from './shape.js'\n// The reference semantics of the IR above. The conformance suite that proves\n// an interpreter agrees with it is `foldkit-entity/conformance`, kept out of\n// this entry because it is fixture data every form and admin screen would\n// otherwise carry.\nexport * from './evaluate.js'\n"],"mappings":";;;AAEA,MAAM,aAAa,QACjB,UAAU,OAAO,GAAG,KAAK,UAAU,YAAY,GAAG;AAEpD,MAAM,UAAU,QACd,UAAU,SAAS,GAAG,KACtB,UAAU,kBAAkB,GAAG,KAC9B,UAAU,UAAU,GAAG,KAAK,OAAO,IAAI,YAAY,YACnD,UAAU,QAAQ,GAAG,KAAK,IAAI,MAAM,SAAS,KAAK,IAAI,MAAM,MAAM,MAAM;;AAG3E,MAAa,cAAc;;CAEzB;;;;;CAMA,UAAU,QACR,UAAU,QAAQ,GAAG,IAAI,IAAI,MAAM,QAAO,WAAU,CAAC,UAAU,MAAM,CAAC,IAAI,CAAC,GAAG;;CAGhF;AACF;;;;;;;;;;;;;;;;AC+GA,MAAM,SAAS,UACb,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,QAAQ,MAAM,OAAO,KAAA;;;;;;;AAQhF,MAAM,WAAc,WAA8B;CAAE,MAAM;CAAW;AAAM;AAE3E,MAAM,aAAa,WAA+E;CAChG,MAAM;CACN,OAAO,MAAM;CACb,KAAK,MAAM;CACX,QAAQ,MAAM;AAChB;AAEA,MAAM,gCAAgB,IAAI,IAAI;CAAC;CAAM;CAAQ;AAAU,CAAC;;AAGxD,MAAa,eAAe,UAC1B,cAAc,IAAI,MAAM,KAAK,CAAW;;;;;AAM1C,MAAM,aAAgB,UAAsC;CAC1D,MAAM,MAAM,MAAM,KAAK;CACvB,IAAI,QAAQ,SACV,OAAO,UAAU,KAAuD;CAE1E,IAAI,QAAQ,aAAa,QAAQ,WAAW,cAAc,IAAI,GAAa,GACzE,OAAO;CAET,OAAO,QAAQ,KAAK;AACtB;;AAGA,MAAM,UAAa,OAAuB,SAA0B;CAClE,MAAM,UAA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U;IAC/E;IACA,KAAK,iBAAiB;KACpB,MAAM,MAAM,MAAM,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI;KAG5D,QADc,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,SAAS,KAAA,CAAS,IAAI,QAAQ,KAAA,KACvD,CAAC,CAAC,KAAK,GAAG,CAAU,IAAI,CAAC;IAC1C;GACF;EACF,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
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "foldkit-entity",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Domain structure for Foldkit Plus: an Entity's fields, relations, and derived members as typed values, and Selections of them.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"foldkit",
|
|
@@ -27,10 +27,12 @@
|
|
|
27
27
|
"sideEffects": false,
|
|
28
28
|
"exports": {
|
|
29
29
|
".": {
|
|
30
|
+
"foldkit-plus:source": "./src/index.ts",
|
|
30
31
|
"types": "./dist/index.d.mts",
|
|
31
32
|
"import": "./dist/index.mjs"
|
|
32
33
|
},
|
|
33
34
|
"./conformance": {
|
|
35
|
+
"foldkit-plus:source": "./src/conformance/index.ts",
|
|
34
36
|
"types": "./dist/conformance/index.d.mts",
|
|
35
37
|
"import": "./dist/conformance/index.mjs"
|
|
36
38
|
}
|
|
@@ -44,7 +46,7 @@
|
|
|
44
46
|
"foldkit-metadata": "0.1.0"
|
|
45
47
|
},
|
|
46
48
|
"peerDependencies": {
|
|
47
|
-
"effect": "
|
|
49
|
+
"effect": ">=4.0.0-rc.116 <4.0.0-rc.118"
|
|
48
50
|
},
|
|
49
51
|
"devDependencies": {
|
|
50
52
|
"effect": "4.0.0-rc.116",
|