foldkit-entity 0.14.0 → 0.15.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.
Files changed (93) hide show
  1. package/README.md +139 -5
  2. package/dist/collation.d.ts +33 -2
  3. package/dist/collation.d.ts.map +1 -0
  4. package/dist/conformance/index.d.ts +4 -4
  5. package/dist/conformance/index.d.ts.map +1 -1
  6. package/dist/conformance/index.js +5 -7
  7. package/dist/conformance/index.js.map +1 -1
  8. package/dist/conformance/operator.d.ts +1 -2
  9. package/dist/conformance/operator.d.ts.map +1 -1
  10. package/dist/conformance/operator.js +2 -6
  11. package/dist/conformance/operator.js.map +1 -1
  12. package/dist/conformance/relational.d.ts +17 -17
  13. package/dist/conformance/relational.d.ts.map +1 -1
  14. package/dist/conformance/relational.js +1 -3
  15. package/dist/conformance/relational.js.map +1 -1
  16. package/dist/conformance/variants.d.ts +47 -0
  17. package/dist/conformance/variants.d.ts.map +1 -0
  18. package/dist/conformance/variants.js +126 -0
  19. package/dist/conformance/variants.js.map +1 -0
  20. package/dist/context.d.ts +60 -2
  21. package/dist/context.d.ts.map +1 -0
  22. package/dist/descriptor.d.ts +33 -0
  23. package/dist/descriptor.d.ts.map +1 -0
  24. package/dist/descriptor.js +137 -0
  25. package/dist/descriptor.js.map +1 -0
  26. package/dist/entity.d.ts +231 -0
  27. package/dist/entity.d.ts.map +1 -0
  28. package/dist/entity.js +435 -0
  29. package/dist/entity.js.map +1 -0
  30. package/dist/evaluate.d.ts +204 -2
  31. package/dist/evaluate.d.ts.map +1 -0
  32. package/dist/evaluate.js +51 -7
  33. package/dist/evaluate.js.map +1 -1
  34. package/dist/expr.d.ts +915 -2
  35. package/dist/expr.d.ts.map +1 -0
  36. package/dist/expr.js +50 -10
  37. package/dist/expr.js.map +1 -1
  38. package/dist/held.d.ts +112 -2
  39. package/dist/held.d.ts.map +1 -0
  40. package/dist/held.js +13 -2
  41. package/dist/held.js.map +1 -1
  42. package/dist/ids.d.ts +8 -0
  43. package/dist/ids.d.ts.map +1 -0
  44. package/dist/ids.js +8 -0
  45. package/dist/ids.js.map +1 -0
  46. package/dist/index.d.ts +380 -6
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +108 -12
  49. package/dist/index.js.map +1 -0
  50. package/dist/invariant.d.ts +123 -2
  51. package/dist/invariant.d.ts.map +1 -0
  52. package/dist/invariant.js +236 -1
  53. package/dist/invariant.js.map +1 -0
  54. package/dist/law.d.ts +264 -2
  55. package/dist/law.d.ts.map +1 -0
  56. package/dist/law.js +1 -1
  57. package/dist/operators.d.ts +170 -2
  58. package/dist/operators.d.ts.map +1 -0
  59. package/dist/operators.js +3 -3
  60. package/dist/readFilter.d.ts +8 -2
  61. package/dist/readFilter.d.ts.map +1 -0
  62. package/dist/sets.d.ts +18 -2
  63. package/dist/sets.d.ts.map +1 -0
  64. package/dist/sets.js +1 -1
  65. package/dist/shape.d.ts +23 -2
  66. package/dist/shape.d.ts.map +1 -0
  67. package/dist/tested.d.ts +8 -2
  68. package/dist/tested.d.ts.map +1 -0
  69. package/dist/text.d.ts +27 -2
  70. package/dist/text.d.ts.map +1 -0
  71. package/dist/text.js +1 -1
  72. package/dist/variants.d.ts +72 -0
  73. package/dist/variants.d.ts.map +1 -0
  74. package/dist/variants.js +76 -0
  75. package/dist/variants.js.map +1 -0
  76. package/dist/words.d.ts +17 -2
  77. package/dist/words.d.ts.map +1 -0
  78. package/dist/write.d.ts +312 -2
  79. package/dist/write.d.ts.map +1 -0
  80. package/dist/write.js +3 -3
  81. package/package.json +3 -3
  82. package/dist/collation-BB4YTIbY.d.ts +0 -34
  83. package/dist/collation-BB4YTIbY.d.ts.map +0 -1
  84. package/dist/index-48JeXG0A.d.ts +0 -2585
  85. package/dist/index-48JeXG0A.d.ts.map +0 -1
  86. package/dist/readFilter-CWMnFRVw.d.ts +0 -9
  87. package/dist/readFilter-CWMnFRVw.d.ts.map +0 -1
  88. package/dist/shape-LAowRf9f.d.ts +0 -23
  89. package/dist/shape-LAowRf9f.d.ts.map +0 -1
  90. package/dist/src-DKhUqLoC.js +0 -731
  91. package/dist/src-DKhUqLoC.js.map +0 -1
  92. package/dist/words-a4e9o-TK.d.ts +0 -18
  93. package/dist/words-a4e9o-TK.d.ts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":["ExprContext","EntityTypeId","EntitySet","AnyVariantUnion","NowExpr","ViewerExpr","ViewerPathExpr","SelectionTypeId","SelectionPageTypeId"],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;iBA2BiB,eAAe;WACrB,MAAM;;WAEN;;;iBAIM,YAAY,qBAAqB,oBAAoB,UAAU,OAAO;WAC5E;WACA,OAAO,eAAe;WACtB,KAAK;WACL,QAAQ;WACR,UAAU;;YAGT;;;;;;YAOA;;iBAGK,aACf,eAAe,WACf,UAAU,aACV;WAES,QAAQ;WACR,aAAa;WACb,UAAU;WACV,UAAU,OAAO,OAAO;;;;;;;iBAQlB,eACf,qBACA,oBACA,eAAe,WACf,UAAU,aACV;WAES;WACA,OAAO,eAAe;WACtB,KAAK;;WAEL,cAAc;WACd,aAAa;WACb,UAAU;;;;;WAKV,UAAU,OAAO,OAAO;WACxB,UAAU;;KAGhB,cAAc,+BAA+B;;;;;;;;;;YAWtC,aAAa,KAAK;;;;;;EAM5B;aAAqB,SAAS,OAAO,OAAO;aAAmB,SAAS,OAAO,OAAO;;EACtF;aAAkB,UAAU;;EAC5B;aAAmB,UAAU;aAAsB,QAAQ;;;qBAEhD,YAAU,KAAA,WAAA;;WAHO,UAAA;;;WACC,UAAA;WAA8B,QAAA;;;WAF7B,SAAA,OAAO,OAAO;WAA4B,SAAA,OAAO,OAAO;;;iBAOvE;;WAEN,QAAQ;WACR,KAAK;;WAEL,MAAM;;WAEN,SAASA;;;;;;YAOR,WAAW,YAAY,eAAe,OAAO;;;;;iBAMxC;WACN;;WAEA,SAAS;;WAET,WAAW;aACT;aACA;;;;;;;;;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AAY,4BAA0B,UAE/D,GAAC;aACS,QAAQ;QAC3B,mBACM;aACI;aAAyB,UAAU;aAAY,QAAQ"}
package/dist/index.js CHANGED
@@ -1,14 +1,110 @@
1
- import { Collation } from "./collation.js";
1
+ import { Data, Option, Schema } from "effect";
2
+ import { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from "./ids.js";
2
3
  import { contextValue, viewerIdOf } from "./context.js";
3
- import { SchemaShape } from "./shape.js";
4
- import { Law, LawDescription } from "./law.js";
5
- import { Expr, Order, Query, dependenciesOf, isPredicate, maxPathLength, maxQueryNodes, missingName, noOperators } from "./expr.js";
6
- import { Held, idOfRef } from "./held.js";
7
- import { Text } from "./text.js";
8
- import { Evidence, OperatorDescription, Operators } from "./operators.js";
9
- import { ContextMissingError, Judge, OperatorMissingError, QueryEvaluateError, RowsMissingError, applyOperator, assertSupported, compareRows, decided, evaluate, evaluateEach, supported, truthOver, valueOfOperand } from "./evaluate.js";
10
- import { a as Relation, i as EntityTypeId, n as Derived, o as SelectionPageTypeId, r as Entity, s as SelectionTypeId, t as Derivation } from "./src-DKhUqLoC.js";
11
- import { ReadFilter } from "./readFilter.js";
12
- import { Words } from "./words.js";
4
+ import * as Entity from "./entity.js";
13
5
  import { Computation, Write } from "./write.js";
14
- export { Collation, Computation, ContextMissingError, Derivation, Derived, Entity, EntityTypeId, Evidence, Expr, Held, Judge, Law, LawDescription, OperatorDescription, OperatorMissingError, Operators, Order, Query, QueryEvaluateError, ReadFilter, Relation, RowsMissingError, SchemaShape, SelectionPageTypeId, SelectionTypeId, Text, Words, Write, applyOperator, assertSupported, compareRows, contextValue, decided, dependenciesOf, evaluate, evaluateEach, idOfRef, isPredicate, maxPathLength, maxQueryNodes, missingName, noOperators, supported, truthOver, valueOfOperand, viewerIdOf };
6
+ export * from "./shape.js";
7
+ export * from "./collation.js";
8
+ export * from "./expr.js";
9
+ export * from "./held.js";
10
+ export * from "./operators.js";
11
+ export * from "./law.js";
12
+ export * from "./text.js";
13
+ export * from "./readFilter.js";
14
+ export * from "./words.js";
15
+ export * from "./evaluate.js";
16
+ // src/index.ts
17
+ /**
18
+ * `foldkit-entity` — domain structure as typed values.
19
+ *
20
+ * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations
21
+ * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable
22
+ * values an interpreter supplies). It describes; it fetches, stores, and
23
+ * renders nothing. Remote, Drizzle, and form packages interpret it and attach
24
+ * what they need as `foldkit-metadata`.
25
+ */
26
+ const Derivation = Data.taggedEnum();
27
+ function one(target, options) {
28
+ const onDelete = options?.onDelete;
29
+ if (onDelete !== void 0 && onDelete !== "cascade") throw new Error(`[foldkit-entity] Relation.one(${target.name}): onDelete is 'cascade'; ${String(onDelete)} is not one`);
30
+ return {
31
+ target,
32
+ cardinality: "one",
33
+ optional: options?.optional ?? false,
34
+ onDelete: Option.fromUndefinedOr(onDelete)
35
+ };
36
+ }
37
+ /** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */
38
+ const Relation = {
39
+ one,
40
+ /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */
41
+ input: (relation) => Object.freeze({
42
+ _tag: "RelationInput",
43
+ relation
44
+ }),
45
+ /**
46
+ * For `Entity.input`: the input key holds the relation's target itself, written
47
+ * through `input`, an `Entity.input` of the target. A `many` holds a list.
48
+ */
49
+ nested: (relation, input) => Object.freeze({
50
+ _tag: "NestedInput",
51
+ relation,
52
+ input
53
+ }),
54
+ many: (target) => ({
55
+ target,
56
+ cardinality: "many",
57
+ optional: false,
58
+ onDelete: Option.none()
59
+ })
60
+ };
61
+ /** A count: never negative, never a fraction. */
62
+ const CountSchema = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0));
63
+ /** The id of the row an exists found, as every Remote id is held: text, or none. */
64
+ const WitnessSchema = Schema.OptionFromNullOr(Schema.String);
65
+ const Derived = {
66
+ /**
67
+ * A member only an interpreter can compute, of type `schema`: it supplies the
68
+ * value. `predict` says how a client foresees it for a row it writes (Guard's
69
+ * `may`); without it the row reads as missing the member until the answer.
70
+ * `forbids` says which write to the row its value refuses (Guard's `may`
71
+ * again), so a client holding it refuses that write where it is made.
72
+ */
73
+ make: (schema, options = {}) => ({
74
+ schema,
75
+ derives: Derivation.Supplied({
76
+ predict: Option.fromUndefinedOr(options.predict),
77
+ forbids: Option.fromUndefinedOr(options.forbids)
78
+ })
79
+ }),
80
+ /**
81
+ * How many rows point at this one through `relation`, a `one` relation of
82
+ * the counted Entity: `likeCount: Derived.count(Like.relations.post)` on
83
+ * Post. Added after `Entity.relate`, which makes the relation. A server
84
+ * compiles it from the relation's storage, and a client predicts it from
85
+ * the rows a pending write inserts, deletes or points elsewhere.
86
+ */
87
+ count: (relation) => ({
88
+ schema: CountSchema,
89
+ derives: Derivation.Count({ relation })
90
+ }),
91
+ /**
92
+ * Whether a row points at this one through `relation` and at whoever reads
93
+ * it through `viewer`, another `one` relation of the same pointing Entity:
94
+ * `liked: Derived.exists(Like.relations.post, { viewer: Like.relations.user })`
95
+ * on Post. Its value is that row's id as the store holds it, or none, so the
96
+ * reader can take it back (`Write.delete` by that id). It depends on who
97
+ * reads it: a server answers it for the principal it reads as, and a client
98
+ * predicts it for the viewer it is told of.
99
+ */
100
+ exists: (relation, options) => ({
101
+ schema: WitnessSchema,
102
+ derives: Derivation.Exists({
103
+ relation,
104
+ viewer: options.viewer
105
+ })
106
+ })
107
+ };
108
+ export { Computation, Derivation, Derived, Entity, EntityTypeId, Relation, SelectionPageTypeId, SelectionTypeId, Write, contextValue, viewerIdOf };
109
+
110
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-entity` — domain structure as typed values.\n *\n * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations\n * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable\n * values an interpreter supplies). It describes; it fetches, stores, and\n * renders nothing. Remote, Drizzle, and form packages interpret it and attach\n * what they need as `foldkit-metadata`.\n */\nimport { Data, Option, type Pipeable, Schema } from 'effect'\nimport type { Metadata } from 'foldkit-metadata'\nimport type { ExprContext, NowExpr, ViewerExpr, ViewerPathExpr } from './context.js'\nimport type { HeldRow, HeldRows } from './held.js'\nimport { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from './ids.js'\nimport type { EntitySet } from './sets.js'\n// The members of `Entity`, a namespace rather than an object so a page keeps only\n// those it calls (#378). Exported under the interface's name; `export * as`\n// would make each `Entity` type here a reference the declaration emitter refuses.\nimport * as EntityMembers from './entity.js'\nimport type { AnyVariantUnion } from './variants.js'\n\nexport { EntityTypeId, SelectionPageTypeId, SelectionTypeId } from './ids.js'\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/**\n * What happens to a row when the row its `one` relation points at is deleted\n * (`Relation.one(Post, { onDelete: 'cascade' })`): `cascade`, it is deleted\n * with it, by the server in the write that deletes, and foreseen by a client.\n */\nexport type OnDelete = 'cascade'\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 readonly onDelete: Option.Option<OnDelete>\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 /**\n * What happens to this row when the row a `one` relation points at is\n * deleted; none for a `many`, and for a `one` declared with nothing.\n */\n readonly onDelete: Option.Option<OnDelete>\n readonly metadata: Metadata\n}\n\ntype OneRelation = EntityRelation<string, string, AnyEntity, 'one', boolean>\n\n/**\n * What a derived member is. `Supplied` (`Derived.make`): an interpreter\n * supplies it, and nothing else can say what it is. `Count`\n * (`Derived.count`): how many rows point at this one through `relation`, a\n * `one` relation of the counted Entity. `Exists` (`Derived.exists`): the id of\n * a row pointing here through `relation` whose `viewer` relation points at\n * whoever reads it, or none. A client predicts both from the rows it writes,\n * and a server compiles both from the relations' storage.\n */\nexport type Derivation = Data.TaggedEnum<{\n /**\n * `predict`: how a client foresees it for a row it writes; none, it waits\n * for the server. `forbids`: which write to the row its value refuses, so a\n * client holding it refuses that write where it is made.\n */\n Supplied: { readonly predict: Option.Option<Predict>; readonly forbids: Option.Option<Forbids> }\n Count: { readonly relation: OneRelation }\n Exists: { readonly relation: OneRelation; readonly viewer: OneRelation }\n}>\nexport const Derivation = Data.taggedEnum<Derivation>()\n\n/** What a supplied member's prediction is given: the row a write leaves, as its holder has it. */\nexport interface Predicting {\n /** The Entity written, as the write declared it. */\n readonly entity: AnyEntity\n readonly row: HeldRow\n /** The holder's other rows, where a rule's path reads. */\n readonly rows: HeldRows\n /** The operation's context: who asks, and the write's time. */\n readonly context: ExprContext\n}\n\n/**\n * A supplied member foreseen: its value **encoded**, as the store holds it, or\n * none where the holder cannot know it, so nothing is shown before the answer.\n */\nexport type Predict = (predicting: Predicting) => Option.Option<unknown>\n\n/**\n * What a write does to a row it finds, as a supplied member's `forbids` is\n * asked: an update's members and the relations it points, or a delete.\n */\nexport interface WriteSurface {\n readonly kind: 'Update' | 'Delete'\n /** The members it sets, moves or computes, relations not among them. */\n readonly members: ReadonlyArray<string>\n /** Each relation it points: at a row (`Link`), or at none (`Unlink`). */\n readonly relations: ReadonlyArray<{\n readonly relation: string\n readonly interaction: 'Link' | 'Unlink'\n }>\n}\n\n/**\n * Whether a supplied member's value, **encoded** as the store holds it,\n * refuses `surface`, with the reader's words for why when there are any; none\n * where it does not say so for certain. Only a definite refusal: a client\n * refuses the write unseen, and its server would refuse it too.\n */\nexport type Forbids = (\n value: unknown,\n surface: WriteSurface,\n) => Option.Option<{ readonly reason: Option.Option<string> }>\n\n/** What `Derived.make`, `Derived.count` or `Derived.exists` returns, before an Entity owns it. */\nexport interface DerivedSpec<S extends Schema.Constraint, D extends Derivation = Derivation> {\n readonly schema: S\n readonly derives: D\n}\n\n/** A value consumers may read that is not part of `entity.schema`, and what it derives. */\nexport interface EntityDerived<\n Name extends string,\n Key extends string,\n S extends Schema.Constraint,\n D extends Derivation = Derivation,\n> {\n readonly _tag: 'Derived'\n readonly owner: EntityIdentity<Name>\n readonly key: Key\n readonly schema: S\n readonly derives: D\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<\n Name,\n K,\n Derived[K]['schema'],\n Derived[K]['derives']\n >\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 /** The members whose value is the write's context, never its input (`Entity.sets`), by key. */\n readonly sets: Readonly<Record<string, EntitySet>>\n readonly metadata: Metadata\n}\n\nexport type AnyEntity = Entity<string, any, any, any>\n\n/**\n * An Entity whose rows are one of several shapes (`Entity.defineVariants`).\n * `variants` is Effect's tagged union of them, read with its own `match`;\n * `fields` and `schema` are the stored row, which every case shares.\n */\nexport interface VariantEntity<\n Name extends string,\n Fields extends Schema.Struct.Fields,\n Relations extends RelationSpecs = {},\n Derived extends DerivedSpecs = {},\n Union extends AnyVariantUnion = AnyVariantUnion,\n> extends Entity<Name, Fields, Relations, Derived> {\n readonly variants: Union\n}\n\nexport type AnyVariantEntity = VariantEntity<string, any, any, any, any>\n\n/** The keys of an Entity's `one` relations. */\ntype OneRelationKeys<E extends AnyEntity> = {\n [K in keyof E['relations'] & string]: E['relations'][K]['cardinality'] extends 'one' ? K : never\n}[keyof E['relations'] & string]\n\n/**\n * What a field holding `T` may be set to: the time where it holds a number,\n * the viewer's id where text, and what a path from the viewer reads where it\n * holds that.\n */\ntype ContextValueFor<T> =\n | (number extends T ? NowExpr<number> : never)\n | (T extends string ? ViewerExpr<T> : never)\n | ViewerPathExpr<T | null>\n\n/** The name of the Entity the `one` relation `K` points at. */\ntype TargetName<E extends AnyEntity, K extends keyof E['relations']> = ReturnType<\n E['relations'][K]['target']\n>['name']\n\n/**\n * What `Entity.sets` takes, by member: a field the value of the write's\n * context it can hold, a `one` relation `Expr.viewer` of its target.\n */\nexport type EntitySets<E extends AnyEntity> = {\n readonly [K in Exclude<keyof E['fields'] & string, 'id'>]?: ContextValueFor<\n Schema.Schema.Type<E['fields'][K]['schema']>\n >\n} & {\n readonly [K in OneRelationKeys<E>]?: ViewerExpr<unknown, TargetName<E, K>>\n}\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 VariantEntity<infer Name, infer Fields, infer R, infer D, infer U>\n ? VariantEntity<Name, Fields, R & RelatedSpecs<Es, Rs, K>, D, U>\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/**\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\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\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/**\n * Which part of a `many` relation to read: the first or last so many, from a\n * cursor or from the end. A cursor is whatever the interpreter handed out with an\n * earlier page; nothing here looks inside it.\n */\nexport interface PageWindow {\n readonly first?: number | undefined\n readonly last?: number | undefined\n readonly after?: string | undefined\n readonly before?: string | undefined\n}\n\n/** 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\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/**\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\nexport type { InputMembers, WrittenAs, WrittenKey, WrittenSpec } from './entity.js'\nexport { EntityMembers as Entity }\n\n/** How a `one` relation is declared: whether it may point nowhere, and what a delete of its target does. */\nexport interface OneOptions<Optional extends boolean> {\n readonly optional?: Optional\n /** `cascade`: a row pointing here is deleted with the row it points at. */\n readonly onDelete?: OnDelete\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: OneOptions<Optional> & { readonly optional: Optional },\n): RelationSpec<Target, 'one', Optional>\nfunction one<Target extends AnyEntity>(\n target: Target,\n options: OneOptions<false>,\n): RelationSpec<Target, 'one', false>\nfunction one(\n target: AnyEntity,\n options?: OneOptions<boolean>,\n): RelationSpec<AnyEntity, 'one', boolean> {\n const onDelete = options?.onDelete\n if (onDelete !== undefined && onDelete !== 'cascade')\n throw new Error(\n `[foldkit-entity] Relation.one(${target.name}): onDelete is 'cascade'; ${String(onDelete)} is not one`,\n )\n return {\n target,\n cardinality: 'one',\n optional: options?.optional ?? false,\n onDelete: Option.fromUndefinedOr(onDelete),\n }\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 onDelete: Option.none(),\n }),\n}\n\n/** A count: never negative, never a fraction. */\nconst CountSchema = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n\n/** The id of the row an exists found, as every Remote id is held: text, or none. */\nconst WitnessSchema = Schema.OptionFromNullOr(Schema.String)\n\ntype OwnerName<R> = R extends EntityRelation<infer Name, any, any, any, any> ? Name : never\n\nexport const Derived = {\n /**\n * A member only an interpreter can compute, of type `schema`: it supplies the\n * value. `predict` says how a client foresees it for a row it writes (Guard's\n * `may`); without it the row reads as missing the member until the answer.\n * `forbids` says which write to the row its value refuses (Guard's `may`\n * again), so a client holding it refuses that write where it is made.\n */\n make: <S extends Schema.Constraint>(\n schema: S,\n options: {\n readonly predict?: Predict | undefined\n readonly forbids?: Forbids | undefined\n } = {},\n ): DerivedSpec<S, Extract<Derivation, { readonly _tag: 'Supplied' }>> => ({\n schema,\n derives: Derivation.Supplied({\n predict: Option.fromUndefinedOr(options.predict),\n forbids: Option.fromUndefinedOr(options.forbids),\n }),\n }),\n\n /**\n * How many rows point at this one through `relation`, a `one` relation of\n * the counted Entity: `likeCount: Derived.count(Like.relations.post)` on\n * Post. Added after `Entity.relate`, which makes the relation. A server\n * compiles it from the relation's storage, and a client predicts it from\n * the rows a pending write inserts, deletes or points elsewhere.\n */\n count: <R extends EntityRelation<string, string, AnyEntity, 'one', boolean>>(\n relation: R,\n ): DerivedSpec<typeof CountSchema, { readonly _tag: 'Count'; readonly relation: R }> => ({\n schema: CountSchema,\n derives: Derivation.Count({ relation }) as { readonly _tag: 'Count'; readonly relation: R },\n }),\n\n /**\n * Whether a row points at this one through `relation` and at whoever reads\n * it through `viewer`, another `one` relation of the same pointing Entity:\n * `liked: Derived.exists(Like.relations.post, { viewer: Like.relations.user })`\n * on Post. Its value is that row's id as the store holds it, or none, so the\n * reader can take it back (`Write.delete` by that id). It depends on who\n * reads it: a server answers it for the principal it reads as, and a client\n * predicts it for the viewer it is told of.\n */\n exists: <\n R extends OneRelation,\n V extends EntityRelation<OwnerName<R>, string, AnyEntity, 'one', boolean>,\n >(\n relation: R,\n options: { readonly viewer: V },\n ): DerivedSpec<\n typeof WitnessSchema,\n { readonly _tag: 'Exists'; readonly relation: R; readonly viewer: V }\n > => ({\n schema: WitnessSchema,\n derives: Derivation.Exists({ relation, viewer: options.viewer }) as {\n readonly _tag: 'Exists'\n readonly relation: R\n readonly viewer: V\n },\n }),\n}\n\nexport * from './expr.js'\nexport {\n contextValue,\n viewerIdOf,\n type ExprContext,\n type NowExpr,\n type ViewerExpr,\n type ViewerPathExpr,\n} from './context.js'\nexport * from './collation.js'\nexport * from './operators.js'\nexport * from './law.js'\nexport * from './text.js'\nexport * from './readFilter.js'\nexport * from './words.js'\nexport * from './shape.js'\nexport type {\n AnyVariantUnion,\n CheckCases,\n EntityVariants,\n StoredFields,\n VariantCases,\n VariantUnion,\n} from './variants.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'\nexport * from './held.js'\nexport type {\n AfterRow,\n BeforeRow,\n Change,\n DeclaredInvariant,\n Invariant,\n Judgement,\n} from './invariant.js'\nexport type { ContextValue, EntitySet, SetOn } from './sets.js'\nexport {\n Write,\n type AnyWrite,\n type BoundWrite,\n type ConditionedWrite,\n Computation,\n type WriteAssignment,\n type WriteComputations,\n type WriteCondition,\n type WriteIncrement,\n type WriteKind,\n type WriteLink,\n type WriteSet,\n type ContextSet,\n type ContextRead,\n type ContextValues,\n} from './write.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA+GA,MAAa,aAAa,KAAK,WAAuB;AA0UtD,SAAS,IACP,QACA,SACyC;CACzC,MAAM,WAAW,SAAS;CAC1B,IAAI,aAAa,KAAA,KAAa,aAAa,WACzC,MAAM,IAAI,MACR,iCAAiC,OAAO,KAAK,4BAA4B,OAAO,QAAQ,EAAE,YAC5F;CACF,OAAO;EACL;EACA,aAAa;EACb,UAAU,SAAS,YAAY;EAC/B,UAAU,OAAO,gBAAgB,QAAQ;CAC3C;AACF;;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;EACV,UAAU,OAAO,KAAK;CACxB;AACF;;AAGA,MAAM,cAAc,OAAO,OAAO,MAAM,OAAO,MAAM,GAAG,OAAO,uBAAuB,CAAC,CAAC;;AAGxF,MAAM,gBAAgB,OAAO,iBAAiB,OAAO,MAAM;AAI3D,MAAa,UAAU;;;;;;;;CAQrB,OACE,QACA,UAGI,CAAC,OACmE;EACxE;EACA,SAAS,WAAW,SAAS;GAC3B,SAAS,OAAO,gBAAgB,QAAQ,OAAO;GAC/C,SAAS,OAAO,gBAAgB,QAAQ,OAAO;EACjD,CAAC;CACH;;;;;;;;CASA,QACE,cACuF;EACvF,QAAQ;EACR,SAAS,WAAW,MAAM,EAAE,SAAS,CAAC;CACxC;;;;;;;;;;CAWA,SAIE,UACA,aAII;EACJ,QAAQ;EACR,SAAS,WAAW,OAAO;GAAE;GAAU,QAAQ,QAAQ;EAAO,CAAC;CAKjE;AACF"}
@@ -1,2 +1,123 @@
1
- import { Ct as judgeInput, St as judgeAgainst, _t as Judgement, bt as invariantsOf, ft as AfterRow, gt as Invariant, ht as DeclaredInvariant, mt as Change, pt as BeforeRow, vt as check, wt as readsBefore, xt as judge, yt as invariant } from "./index-48JeXG0A.js";
2
- export { AfterRow, BeforeRow, Change, DeclaredInvariant, Invariant, Judgement, check, invariant, invariantsOf, judge, judgeAgainst, judgeInput, readsBefore };
1
+ import { Schema, SchemaAST } from "effect";
2
+ import { AnyEntity, EntityInput } from "./index.js";
3
+ import { FieldExpr, NextExpr, Predicate, Reads } from "./expr.js";
4
+ import { MemoryOperators as MemoryOperators$1 } from "./operators.js";
5
+ import { Row } from "./evaluate.js";
6
+ /** One invariant of an Entity, as its interpreters read it. */
7
+ export interface Invariant {
8
+ /** Stable, unique within its Entity: what a refusal names, and forms and logs key on. */
9
+ readonly id: string;
10
+ /** The Entity it is declared on: ids are unique only within one, so a refusal names both. */
11
+ readonly entity: string;
12
+ readonly predicate: Predicate;
13
+ /** What someone the rules let write is told when a write would break it. */
14
+ readonly message: string;
15
+ /** The members a form shows the failure beside. */
16
+ readonly path: ReadonlyArray<string>;
17
+ /** The members it reads of the row before a write (fields, `one` relations); none for a state invariant. */
18
+ readonly before: ReadonlyArray<string>;
19
+ /** The members it reads of the row after. */
20
+ readonly after: ReadonlyArray<string>;
21
+ }
22
+ /** The keys of an Entity's `one` relations: what a row holds as the id each points at. */
23
+ type LinkKeys<E extends AnyEntity> = { [K in keyof E['relations'] & string]: E['relations'][K]['cardinality'] extends 'one' ? K : never; }[keyof E['relations'] & string];
24
+ /** The id a `one` relation points at, as a row holds it: null for an optional one pointing nowhere. */
25
+ type LinkOf<E extends AnyEntity, K extends keyof E['relations']> = E['relations'][K]['optional'] extends true ? string | null : string;
26
+ /**
27
+ * Each field as the row before a write holds it, and each `one` relation as
28
+ * the id it points at: what an invariant reads as `before`. Encoded, as the
29
+ * store holds it and the judge reads it, so a literal is written so too (a
30
+ * date as its ISO text).
31
+ */
32
+ export type BeforeRow<E extends AnyEntity> = { readonly [K in keyof E['fields'] & string]: FieldExpr<Schema.Codec.Encoded<E['fields'][K]['schema']>> & Reads<E['name']>; } & { readonly [K in LinkKeys<E>]: FieldExpr<LinkOf<E, K>> & Reads<E['name']>; };
33
+ /** Each field, and each `one` relation's id, as the row after a write holds it: `after`. */
34
+ export type AfterRow<E extends AnyEntity> = { readonly [K in keyof E['fields'] & string]: NextExpr<Schema.Codec.Encoded<E['fields'][K]['schema']>> & Reads<E['name']>; } & { readonly [K in LinkKeys<E>]: NextExpr<LinkOf<E, K>> & Reads<E['name']>; };
35
+ /** A row, or a change from one row to another, as an invariant is judged over it. */
36
+ export interface Change {
37
+ readonly after: Row;
38
+ /** The row before an update; none for a create, which judges no transition invariant. */
39
+ readonly before?: Row;
40
+ }
41
+ /** What a row, or a change, comes to under an Entity's invariants. */
42
+ export type Judgement = {
43
+ readonly _tag: 'Valid';
44
+ } | {
45
+ readonly _tag: 'Invalid';
46
+ readonly failures: ReadonlyArray<Invariant>;
47
+ } |
48
+ /**
49
+ * Validity is not known: some invariant reads a field the row does not have
50
+ * (`fields`), or calls an operator the table does not run (`operators`, by name).
51
+ */
52
+ {
53
+ readonly _tag: 'Undecided';
54
+ readonly fields: ReadonlyArray<string>;
55
+ readonly operators: ReadonlyArray<string>;
56
+ };
57
+ /** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */
58
+ export declare const readsBefore: (held: Invariant) => boolean;
59
+ /**
60
+ * An invariant as declared: the step that attaches it to its Entity, carrying
61
+ * its id and, once attached, that Entity's name, so a refusal is matched
62
+ * against the declaration rather than a string spelled again
63
+ * (`Refusal.isInvalidBy(refusal, reservedWithinQuantity)`). An id is unique
64
+ * only within an Entity, so the name is part of what a refusal names; reading
65
+ * it before the declaration is attached throws.
66
+ */
67
+ export interface DeclaredInvariant<E extends AnyEntity> {
68
+ (entity: E): E;
69
+ readonly id: string;
70
+ readonly entity: string;
71
+ }
72
+ /** How an invariant is declared: what `build` returns over the rows, and what a failure says. */
73
+ type Build<E extends AnyEntity> = (rows: {
74
+ readonly before: BeforeRow<E>;
75
+ readonly after: AfterRow<E>;
76
+ }) => Predicate & Reads<E['name']>;
77
+ interface Options<E extends AnyEntity> {
78
+ readonly message: string;
79
+ readonly path?: ReadonlyArray<(keyof E['fields'] & string) | LinkKeys<E>>;
80
+ }
81
+ /**
82
+ * Declares what every stored row, or every change of one, must hold:
83
+ * `Entity.invariant('reservedWithinQuantity', ({ after }) =>
84
+ * Expr.lte(after.reserved, after.quantity), { message })` over the row a
85
+ * write leaves, or with `before` too over the change an update makes.
86
+ * Refused where it is declared: an id declared twice, a predicate over another
87
+ * Entity, one reading an input or nothing of `after` (that is a `when`), a path
88
+ * naming no field.
89
+ */
90
+ export declare const invariant: <E extends AnyEntity>(id: string, build: Build<E>, options: Options<E>) => DeclaredInvariant<E>;
91
+ /** The Entity's invariants, in the order they were declared. */
92
+ export declare const invariantsOf: (entity: AnyEntity) => ReadonlyArray<Invariant>;
93
+ /** `Entity.judge` against invariants already read, such as those a database binding keeps. */
94
+ export declare const judgeAgainst: (invariants: ReadonlyArray<Invariant>, change: Change, operators?: MemoryOperators$1) => Judgement;
95
+ /**
96
+ * A row, or a change, under every invariant (each row as the store holds it,
97
+ * encoded): valid only when each is true. SQL's unknown, from a null, fails
98
+ * one, as a `WHERE` drops the row; a field a row does not have leaves it
99
+ * undecided, never valid. Without `before` (a create), transition invariants
100
+ * are not judged.
101
+ */
102
+ export declare const judge: (entity: AnyEntity, change: Change, operators?: MemoryOperators$1) => Judgement;
103
+ /**
104
+ * The row an input's value describes, judged under its Entity's state
105
+ * invariants: each key mapped to a field, encoded as the store holds it, and
106
+ * each mapped to a `one` relation as the id it points at. An
107
+ * invariant over a field the input does not set (an `Option` holding nothing, a
108
+ * key left out) is undecided, so a partial input is never called valid on its
109
+ * account. It has no row before, so it judges no transition.
110
+ */
111
+ export declare const judgeInput: (input: EntityInput<AnyEntity, any, any>, value: Readonly<Record<string, unknown>>, operators?: MemoryOperators$1) => Judgement;
112
+ /**
113
+ * The Entity's state invariants as an Effect Schema check over its row type:
114
+ * each failure at its path, with its message. The value is encoded first,
115
+ * field by field, so it is judged as the store would hold it. Refused where it
116
+ * is made when an invariant calls an operator `operators` does not run: such a
117
+ * check would pass every value.
118
+ */
119
+ export declare const check: <E extends AnyEntity>(entity: E, options?: {
120
+ readonly operators?: MemoryOperators$1 | undefined;
121
+ }) => SchemaAST.Filter<Schema.Schema.Type<E['schema']>>;
122
+ export {};
123
+ //# sourceMappingURL=invariant.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invariant.d.ts","names":["MemoryOperators"],"sources":["../src/invariant.ts"],"mappings":";;;;;;iBAgDiB;;WAEN;;WAEA;WACA,WAAW;;WAEX;;WAEA,MAAM;;WAEN,QAAQ;;WAER,OAAO;;;KAIb,SAAS,UAAU,gBACrB,WAAW,0BAA0B,eAAe,kCAAkC,mBACjF;;KAGH,OACH,UAAU,WACV,gBAAgB,kBACd,eAAe;;;;;;;YAQP,UAAU,UAAU,yBACpB,WAAW,uBAAuB,UAC1C,OAAO,MAAM,QAAQ,YAAY,iBAEjC,MAAM,4BACM,KAAK,SAAS,KAAK,UAAU,OAAO,GAAG,MAAM,MAAM;;YAGvD,SAAS,UAAU,yBACnB,WAAW,uBAAuB,SAC1C,OAAO,MAAM,QAAQ,YAAY,iBAEjC,MAAM,4BACM,KAAK,SAAS,KAAK,SAAS,OAAO,GAAG,MAAM,MAAM;;iBAGjD;WACN,OAAO;;WAEP,SAAS;;;YAUR;WACG;;WACA;WAA0B,UAAU,cAAc;;;;;;;WAMlD;WACA,QAAQ;WACR,WAAW;;;qBAIb,cAAW,MAAU;;;;;;;;;iBAUjB,kBAAkB,UAAU;GAC1C,QAAQ,IAAI;WACJ;WACA;;;KAQN,MAAM,UAAU,cAAc;WACxB,QAAQ,UAAU;WAClB,OAAO,SAAS;MACrB,YAAY,MAAM;UAEd,QAAQ,UAAU;WACjB;WACA,OAAO,qBAAqB,wBAAwB,SAAS;;;;;;;;;;;qBAgE3D,YAAa,UAAU,WAAS,YACjC,OACH,MAAM,IAAE,SACN,QAAQ,OAChB,kBAAkB;;qBAkFR,eAAY,QAAY,cAAY,cAAc;;qBAOlD,eAAY,YACX,cAAc,YAAU,QAC5B,QAAM,YACHA,sBACV;;;;;;;;qBAyCU,QAAK,QACR,WAAS,QACT,QAAM,YACHA,sBACV;;;;;;;;;qBAUU,aAAU,OACd,YAAY,sBAAoB,OAChC,SAAS,0BAAwB,YAC7BA,sBACV;;;;;;;;qBAsCU,QAAS,UAAU,WAAS,QAC/B,GAAC;WACW,YAAYA;MAC/B,UAAU,OAAO,OAAO,OAAO,KAAK"}
package/dist/invariant.js CHANGED
@@ -1 +1,236 @@
1
- export { c as check, l as invariant, u as invariantsOf, d as judge, f as judgeAgainst, p as judgeInput, m as readsBefore } from "./src-DKhUqLoC.js";
1
+ import { Option, Schema } from "effect";
2
+ import { Metadata } from "foldkit-metadata";
3
+ import { put } from "./record.js";
4
+ import { storesNull, variantsOf } from "./variants.js";
5
+ import { remake, variantBases } from "./descriptor.js";
6
+ import { Expr, Query, dependenciesOf } from "./expr.js";
7
+ import { Operators } from "./operators.js";
8
+ import { OperatorMissingError, truthOver } from "./evaluate.js";
9
+ // src/invariant.ts
10
+ /**
11
+ * Invariants: what every stored row of an Entity must hold, and what every
12
+ * change of one must, declared once on the Entity through its metadata and read
13
+ * from there by each interpreter: the reference judge here, a Schema check, a
14
+ * form, a server's writer.
15
+ *
16
+ * One is built over the row before a write (`before`, each field as `Expr.field`) and
17
+ * the row after it (`after`, each field as `Expr.next`); each `one` relation is
18
+ * there too, as the id it points at, so a judged row holds it as that id. What
19
+ * it reads decides when it is judged:
20
+ *
21
+ * ```text
22
+ * reads `after` only -> a state invariant: every create and update, a CHECK constraint
23
+ * reads `before` too -> a transition invariant: every update, which has a row before
24
+ * ```
25
+ *
26
+ * It reads no input and no principal. Who may write is a guard's; whether a
27
+ * write applies now is its `when`'s.
28
+ */
29
+ const Invariants = Metadata.key("foldkit-entity/invariants", {
30
+ merge: (values) => [...new Set(values)],
31
+ summarize: (invariant) => invariant.id
32
+ });
33
+ /** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */
34
+ const readsBefore = (held) => held.before.length > 0;
35
+ const fail = (entity, message) => {
36
+ throw new Error(`[foldkit-entity] Entity.invariant on ${entity.name}: ${message}`);
37
+ };
38
+ /** The invariant `build` declares over `entity`'s rows, refused where it could judge nothing. */
39
+ const declareOn = (entity, id, build, options) => {
40
+ const fields = entity.fields;
41
+ const relations = entity.relations;
42
+ const links = Object.values(relations).flatMap((member) => member._tag === "Relation" && member.cardinality === "one" ? [member] : []);
43
+ const nexts = [...Object.entries(fields).map(([key, field]) => [key, Expr.next(field)]), ...links.map((link) => [link.key, Expr.next(link)])];
44
+ const after = Object.fromEntries(nexts);
45
+ const predicate = build({
46
+ before: Object.fromEntries(nexts.map(([key, next]) => [key, next.field])),
47
+ after
48
+ });
49
+ const body = Query.from(entity).pipe(Query.where(predicate));
50
+ const dependencies = Query.dependencies(body);
51
+ if (dependencies.inputs.length > 0) fail(entity, `"${id}" reads the input ${dependencies.inputs.join(", ")}; it judges stored rows`);
52
+ const beforeReads = dependencies.predicate.map((field) => field.key);
53
+ const afterReads = dependencies.next.map((field) => field.key);
54
+ if (afterReads.length === 0) fail(entity, `"${id}" reads no field of \`after\`; what a write may start from is its \`when\``);
55
+ const path = options.path ?? [.../* @__PURE__ */ new Set([...afterReads, ...beforeReads])];
56
+ for (const key of path) if (!Object.hasOwn(fields, key) && !links.some((link) => link.key === key)) fail(entity, `"${id}"'s path names "${key}", neither a field nor a one relation`);
57
+ return Object.freeze({
58
+ id,
59
+ entity: entity.name,
60
+ predicate,
61
+ message: options.message,
62
+ path: Object.freeze([...path]),
63
+ before: Object.freeze(beforeReads),
64
+ after: Object.freeze(afterReads)
65
+ });
66
+ };
67
+ /**
68
+ * Declares what every stored row, or every change of one, must hold:
69
+ * `Entity.invariant('reservedWithinQuantity', ({ after }) =>
70
+ * Expr.lte(after.reserved, after.quantity), { message })` over the row a
71
+ * write leaves, or with `before` too over the change an update makes.
72
+ * Refused where it is declared: an id declared twice, a predicate over another
73
+ * Entity, one reading an input or nothing of `after` (that is a `when`), a path
74
+ * naming no field.
75
+ */
76
+ const invariant = (id, build, options) => {
77
+ let attached;
78
+ const declared = (entity) => {
79
+ if (id.length === 0) fail(entity, "an invariant needs an id");
80
+ if (attached !== void 0 && attached !== entity.name) fail(entity, `"${id}" is declared on ${attached} already: declare it again for this Entity`);
81
+ if (invariantsOf(entity).some((held) => held.id === id)) fail(entity, `"${id}" is declared twice`);
82
+ const held = declareOn(entity, id, build, options);
83
+ attached = entity.name;
84
+ return remake(entity, { metadata: Metadata.combine([entity.metadata, Invariants.of(held)]) });
85
+ };
86
+ return Object.defineProperties(declared, {
87
+ id: {
88
+ value: id,
89
+ enumerable: true
90
+ },
91
+ entity: {
92
+ enumerable: true,
93
+ get: () => {
94
+ if (attached === void 0) throw new Error(`[foldkit-entity] Entity.invariant "${id}" names no Entity until it is attached to one`);
95
+ return attached;
96
+ }
97
+ }
98
+ });
99
+ };
100
+ const ofCases = /* @__PURE__ */ new WeakMap();
101
+ /**
102
+ * Each case's invariant of a variant Entity (`variant_Available`): a field
103
+ * of its own is held, and one of another case is null. Built when first
104
+ * read, so declaring variants reaches no expression code.
105
+ */
106
+ const caseInvariants = (identity) => {
107
+ const base = variantBases.get(identity);
108
+ if (base === void 0) return [];
109
+ const known = ofCases.get(identity);
110
+ if (known !== void 0) return known;
111
+ const variants = Option.getOrThrow(variantsOf(identity));
112
+ const { name } = base;
113
+ const separate = Object.keys(base.fields).filter((key) => key !== "_tag" && variants.tags.some((tag) => !Object.hasOwn(variants.cases[tag], key)));
114
+ const built = variants.tags.flatMap((tag) => {
115
+ const own = variants.cases[tag];
116
+ const reads = separate.filter((key) => !Object.hasOwn(own, key) || !storesNull(own[key]));
117
+ if (reads.length === 0) return [];
118
+ const held = reads.filter((key) => Object.hasOwn(own, key));
119
+ const foreign = reads.filter((key) => !Object.hasOwn(own, key));
120
+ return [declareOn(base, `variant_${tag}`, ({ after }) => {
121
+ const row = after;
122
+ const checks = [...held.map((key) => Expr.isNotNull(row[key])), ...foreign.map((key) => Expr.isNull(row[key]))];
123
+ return Expr.or(Expr.not(Expr.eq(row._tag, tag)), Expr.and(checks[0], ...checks.slice(1)));
124
+ }, {
125
+ message: `A ${name} that is ${tag} ${[...held.length > 0 ? [`holds ${held.join(", ")}`] : [], ...foreign.length > 0 ? [`holds none of ${foreign.join(", ")}`] : []].join(" and ")}`,
126
+ path: reads
127
+ })];
128
+ });
129
+ ofCases.set(identity, built);
130
+ return built;
131
+ };
132
+ /** The Entity's invariants, in the order they were declared. */
133
+ const invariantsOf = (entity) => {
134
+ const cases = caseInvariants(entity.identity);
135
+ const declared = Invariants.get(entity.metadata);
136
+ return cases.length === 0 ? declared : [...cases, ...declared];
137
+ };
138
+ /** `Entity.judge` against invariants already read, such as those a database binding keeps. */
139
+ const judgeAgainst = (invariants, change, operators = Operators.kernel) => {
140
+ const missing = /* @__PURE__ */ new Set();
141
+ const unrun = /* @__PURE__ */ new Set();
142
+ const failures = [];
143
+ const { after, before } = change;
144
+ for (const held of invariants) {
145
+ if (readsBefore(held) && before === void 0) continue;
146
+ const absent = [...held.after.filter((key) => !Object.hasOwn(after, key)), ...held.before.filter((key) => !Object.hasOwn(before ?? {}, key))];
147
+ if (absent.length > 0) absent.forEach((key) => missing.add(key));
148
+ else try {
149
+ if (truthOver(held.predicate, before ?? {}, {}, after, operators) !== true) failures.push(held);
150
+ } catch (error) {
151
+ if (!(error instanceof OperatorMissingError)) throw error;
152
+ unrun.add(error.named);
153
+ }
154
+ }
155
+ if (failures.length > 0) return {
156
+ _tag: "Invalid",
157
+ failures
158
+ };
159
+ if (missing.size > 0 || unrun.size > 0) return {
160
+ _tag: "Undecided",
161
+ fields: [...missing],
162
+ operators: [...unrun]
163
+ };
164
+ return { _tag: "Valid" };
165
+ };
166
+ /**
167
+ * A row, or a change, under every invariant (each row as the store holds it,
168
+ * encoded): valid only when each is true. SQL's unknown, from a null, fails
169
+ * one, as a `WHERE` drops the row; a field a row does not have leaves it
170
+ * undecided, never valid. Without `before` (a create), transition invariants
171
+ * are not judged.
172
+ */
173
+ const judge = (entity, change, operators = Operators.kernel) => judgeAgainst(invariantsOf(entity), change, operators);
174
+ /**
175
+ * The row an input's value describes, judged under its Entity's state
176
+ * invariants: each key mapped to a field, encoded as the store holds it, and
177
+ * each mapped to a `one` relation as the id it points at. An
178
+ * invariant over a field the input does not set (an `Option` holding nothing, a
179
+ * key left out) is undecided, so a partial input is never called valid on its
180
+ * account. It has no row before, so it judges no transition.
181
+ */
182
+ const judgeInput = (input, value, operators = Operators.kernel) => {
183
+ const invariants = invariantsOf(input.entity);
184
+ if (invariants.length === 0) return { _tag: "Valid" };
185
+ const members = input.members;
186
+ const row = {};
187
+ for (const [key, member] of Object.entries(members)) {
188
+ if (!Object.hasOwn(value, key)) continue;
189
+ if (member._tag === "RelationInput" && member.relation.cardinality === "one") {
190
+ const given = value[key];
191
+ const id = Option.isOption(given) ? Option.getOrNull(given) : given;
192
+ if (id === null || typeof id === "string") put(row, member.relation.key, id);
193
+ continue;
194
+ }
195
+ if (member._tag !== "Field") continue;
196
+ const encode = Schema.encodeUnknownOption(member.schema);
197
+ const given = value[key];
198
+ const held = Option.isOption(given) ? given : Option.fromUndefinedOr(given);
199
+ const stored = Option.orElse(encode(given), () => Option.flatMap(held, encode));
200
+ Option.map(Option.flatMap(held, () => stored), (encoded) => put(row, member.key, encoded));
201
+ }
202
+ return judgeAgainst(invariants, { after: row }, operators);
203
+ };
204
+ /**
205
+ * The Entity's state invariants as an Effect Schema check over its row type:
206
+ * each failure at its path, with its message. The value is encoded first,
207
+ * field by field, so it is judged as the store would hold it. Refused where it
208
+ * is made when an invariant calls an operator `operators` does not run: such a
209
+ * check would pass every value.
210
+ */
211
+ const check = (entity, options = {}) => {
212
+ const predicates = invariantsOf(entity).map((held) => held.predicate);
213
+ const missing = Expr.unsupported(predicates, {
214
+ operations: dependenciesOf(...predicates).operations,
215
+ operators: options.operators ?? Operators.kernel
216
+ });
217
+ if (missing.length > 0) throw new Error(`[foldkit-entity] Entity.check of ${entity.name}: its invariants call ${missing.join(", ")}, which the operator table does not run; pass one that does as \`operators\``);
218
+ return Schema.makeFilter((value) => {
219
+ const fields = entity.fields;
220
+ const decoded = value;
221
+ const row = {};
222
+ for (const [key, field] of Object.entries(fields)) {
223
+ if (!Object.hasOwn(decoded, key)) continue;
224
+ put(row, key, Schema.encodeUnknownSync(field.schema)(decoded[key]));
225
+ }
226
+ const judged = judge(entity, { after: row }, options.operators);
227
+ if (judged._tag !== "Invalid") return void 0;
228
+ return judged.failures.flatMap((failure) => failure.path.length === 0 ? [failure.message] : failure.path.map((key) => ({
229
+ path: [key],
230
+ issue: failure.message
231
+ })));
232
+ });
233
+ };
234
+ export { check, invariant, invariantsOf, judge, judgeAgainst, judgeInput, readsBefore };
235
+
236
+ //# sourceMappingURL=invariant.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invariant.js","names":[],"sources":["../src/invariant.ts"],"sourcesContent":["/**\n * Invariants: what every stored row of an Entity must hold, and what every\n * change of one must, declared once on the Entity through its metadata and read\n * from there by each interpreter: the reference judge here, a Schema check, a\n * form, a server's writer.\n *\n * One is built over the row before a write (`before`, each field as `Expr.field`) and\n * the row after it (`after`, each field as `Expr.next`); each `one` relation is\n * there too, as the id it points at, so a judged row holds it as that id. What\n * it reads decides when it is judged:\n *\n * ```text\n * reads `after` only -> a state invariant: every create and update, a CHECK constraint\n * reads `before` too -> a transition invariant: every update, which has a row before\n * ```\n *\n * It reads no input and no principal. Who may write is a guard's; whether a\n * write applies now is its `when`'s.\n */\nimport { Metadata } from 'foldkit-metadata'\nimport { Option, Schema, type SchemaAST } from 'effect'\nimport { OperatorMissingError, truthOver, type Row } from './evaluate.js'\nimport { Operators, type MemoryOperators } from './operators.js'\nimport { put } from './record.js'\nimport {\n Expr,\n Query,\n dependenciesOf,\n type FieldExpr,\n type NextExpr,\n type OneRelation,\n type Predicate,\n type Reads,\n} from './expr.js'\nimport { remake, variantBases } from './descriptor.js'\nimport type {\n AnyEntity,\n EntityField,\n EntityIdentity,\n EntityInput,\n EntityMember,\n InputMember,\n} from './index.js'\nimport { storesNull, variantsOf } from './variants.js'\n\ntype AnyField = EntityField<string, string, Schema.Constraint>\n\n/** One invariant of an Entity, as its interpreters read it. */\nexport interface Invariant {\n /** Stable, unique within its Entity: what a refusal names, and forms and logs key on. */\n readonly id: string\n /** The Entity it is declared on: ids are unique only within one, so a refusal names both. */\n readonly entity: string\n readonly predicate: Predicate\n /** What someone the rules let write is told when a write would break it. */\n readonly message: string\n /** The members a form shows the failure beside. */\n readonly path: ReadonlyArray<string>\n /** The members it reads of the row before a write (fields, `one` relations); none for a state invariant. */\n readonly before: ReadonlyArray<string>\n /** The members it reads of the row after. */\n readonly after: ReadonlyArray<string>\n}\n\n/** The keys of an Entity's `one` relations: what a row holds as the id each points at. */\ntype LinkKeys<E extends AnyEntity> = {\n [K in keyof E['relations'] & string]: E['relations'][K]['cardinality'] extends 'one' ? K : never\n}[keyof E['relations'] & string]\n\n/** The id a `one` relation points at, as a row holds it: null for an optional one pointing nowhere. */\ntype LinkOf<\n E extends AnyEntity,\n K extends keyof E['relations'],\n> = E['relations'][K]['optional'] extends true ? string | null : string\n\n/**\n * Each field as the row before a write holds it, and each `one` relation as\n * the id it points at: what an invariant reads as `before`. Encoded, as the\n * store holds it and the judge reads it, so a literal is written so too (a\n * date as its ISO text).\n */\nexport type BeforeRow<E extends AnyEntity> = {\n readonly [K in keyof E['fields'] & string]: FieldExpr<\n Schema.Codec.Encoded<E['fields'][K]['schema']>\n > &\n Reads<E['name']>\n} & { readonly [K in LinkKeys<E>]: FieldExpr<LinkOf<E, K>> & Reads<E['name']> }\n\n/** Each field, and each `one` relation's id, as the row after a write holds it: `after`. */\nexport type AfterRow<E extends AnyEntity> = {\n readonly [K in keyof E['fields'] & string]: NextExpr<\n Schema.Codec.Encoded<E['fields'][K]['schema']>\n > &\n Reads<E['name']>\n} & { readonly [K in LinkKeys<E>]: NextExpr<LinkOf<E, K>> & Reads<E['name']> }\n\n/** A row, or a change from one row to another, as an invariant is judged over it. */\nexport interface Change {\n readonly after: Row\n /** The row before an update; none for a create, which judges no transition invariant. */\n readonly before?: Row\n}\n\nconst Invariants = Metadata.key<Invariant>('foldkit-entity/invariants', {\n // The same invariant reached twice (two annotated copies combined) is one.\n merge: values => [...new Set(values)],\n summarize: invariant => invariant.id,\n})\n\n/** What a row, or a change, comes to under an Entity's invariants. */\nexport type Judgement =\n | { readonly _tag: 'Valid' }\n | { readonly _tag: 'Invalid'; readonly failures: ReadonlyArray<Invariant> }\n /**\n * Validity is not known: some invariant reads a field the row does not have\n * (`fields`), or calls an operator the table does not run (`operators`, by name).\n */\n | {\n readonly _tag: 'Undecided'\n readonly fields: ReadonlyArray<string>\n readonly operators: ReadonlyArray<string>\n }\n\n/** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */\nexport const readsBefore = (held: Invariant): boolean => held.before.length > 0\n\n/**\n * An invariant as declared: the step that attaches it to its Entity, carrying\n * its id and, once attached, that Entity's name, so a refusal is matched\n * against the declaration rather than a string spelled again\n * (`Refusal.isInvalidBy(refusal, reservedWithinQuantity)`). An id is unique\n * only within an Entity, so the name is part of what a refusal names; reading\n * it before the declaration is attached throws.\n */\nexport interface DeclaredInvariant<E extends AnyEntity> {\n (entity: E): E\n readonly id: string\n readonly entity: string\n}\n\nconst fail = (entity: AnyEntity, message: string): never => {\n throw new Error(`[foldkit-entity] Entity.invariant on ${entity.name}: ${message}`)\n}\n\n/** How an invariant is declared: what `build` returns over the rows, and what a failure says. */\ntype Build<E extends AnyEntity> = (rows: {\n readonly before: BeforeRow<E>\n readonly after: AfterRow<E>\n}) => Predicate & Reads<E['name']>\n\ninterface Options<E extends AnyEntity> {\n readonly message: string\n readonly path?: ReadonlyArray<(keyof E['fields'] & string) | LinkKeys<E>>\n}\n\n/** The invariant `build` declares over `entity`'s rows, refused where it could judge nothing. */\nconst declareOn = <E extends AnyEntity>(\n entity: E,\n id: string,\n build: Build<E>,\n options: Options<E>,\n): Invariant => {\n const fields = entity.fields as Readonly<Record<string, E['fields'][string]>>\n const relations = entity.relations as Readonly<Record<string, EntityMember>>\n // A `one` relation reads as the id it points at; a `many` holds no one value.\n const links = Object.values(relations).flatMap(member =>\n member._tag === 'Relation' && member.cardinality === 'one' ? [member as OneRelation] : [],\n )\n const nexts = [\n ...Object.entries(fields).map(([key, field]) => [key, Expr.next(field)] as const),\n ...links.map(link => [link.key, Expr.next(link)] as const),\n ]\n const after = Object.fromEntries(nexts) as unknown as AfterRow<E>\n // Before a write, each is what its `after` reads after it: the same operand, unmoved.\n const before = Object.fromEntries(\n nexts.map(([key, next]) => [key, next.field]),\n ) as unknown as BeforeRow<E>\n const predicate = build({ before, after }) as Predicate\n // `where` refuses a predicate over another Entity, which the type allows when it is unmarked.\n const body = Query.from(entity).pipe(Query.where(predicate))\n const dependencies = Query.dependencies(body)\n if (dependencies.inputs.length > 0) {\n fail(entity, `\"${id}\" reads the input ${dependencies.inputs.join(', ')}; it judges stored rows`)\n }\n const beforeReads = dependencies.predicate.map(field => field.key)\n const afterReads = dependencies.next.map(field => field.key)\n // Reading the row before alone, it says which rows a write may start from: a write's `when`.\n // Judged as an invariant, a create would skip it and a repair would be refused by it.\n if (afterReads.length === 0) {\n fail(entity, `\"${id}\" reads no field of \\`after\\`; what a write may start from is its \\`when\\``)\n }\n const path = options.path ?? [...new Set([...afterReads, ...beforeReads])]\n for (const key of path) {\n if (!Object.hasOwn(fields, key) && !links.some(link => link.key === key))\n fail(entity, `\"${id}\"'s path names \"${key}\", neither a field nor a one relation`)\n }\n return Object.freeze({\n id,\n entity: entity.name,\n predicate,\n message: options.message,\n path: Object.freeze([...path]),\n before: Object.freeze(beforeReads),\n after: Object.freeze(afterReads),\n })\n}\n\n/**\n * Declares what every stored row, or every change of one, must hold:\n * `Entity.invariant('reservedWithinQuantity', ({ after }) =>\n * Expr.lte(after.reserved, after.quantity), { message })` over the row a\n * write leaves, or with `before` too over the change an update makes.\n * Refused where it is declared: an id declared twice, a predicate over another\n * Entity, one reading an input or nothing of `after` (that is a `when`), a path\n * naming no field.\n */\nexport const invariant = <E extends AnyEntity>(\n id: string,\n build: Build<E>,\n options: Options<E>,\n): DeclaredInvariant<E> => {\n let attached: string | undefined\n const declared = (entity: E): E => {\n if (id.length === 0) fail(entity, 'an invariant needs an id')\n if (attached !== undefined && attached !== entity.name)\n fail(entity, `\"${id}\" is declared on ${attached} already: declare it again for this Entity`)\n if (invariantsOf(entity).some(held => held.id === id)) fail(entity, `\"${id}\" is declared twice`)\n const held = declareOn(entity, id, build, options)\n attached = entity.name\n return remake(entity, {\n metadata: Metadata.combine([entity.metadata, Invariants.of(held)]),\n }) as E\n }\n return Object.defineProperties(declared, {\n id: { value: id, enumerable: true },\n entity: {\n enumerable: true,\n get: () => {\n if (attached === undefined) {\n throw new Error(\n `[foldkit-entity] Entity.invariant \"${id}\" names no Entity until it is attached to one`,\n )\n }\n return attached\n },\n },\n }) as DeclaredInvariant<E>\n}\n\nconst ofCases = new WeakMap<EntityIdentity<string>, ReadonlyArray<Invariant>>()\n\n/**\n * Each case's invariant of a variant Entity (`variant_Available`): a field\n * of its own is held, and one of another case is null. Built when first\n * read, so declaring variants reaches no expression code.\n */\nconst caseInvariants = (identity: EntityIdentity<string>): ReadonlyArray<Invariant> => {\n const base = variantBases.get(identity)\n if (base === undefined) return []\n const known = ofCases.get(identity)\n if (known !== undefined) return known\n const variants = Option.getOrThrow(variantsOf(identity))\n const { name } = base\n const separate = Object.keys(base.fields).filter(\n key => key !== '_tag' && variants.tags.some(tag => !Object.hasOwn(variants.cases[tag]!, key)),\n )\n const built = variants.tags.flatMap(tag => {\n const own = variants.cases[tag]!\n const reads = separate.filter(key => !Object.hasOwn(own, key) || !storesNull(own[key]!))\n if (reads.length === 0) return []\n const held = reads.filter(key => Object.hasOwn(own, key))\n const foreign = reads.filter(key => !Object.hasOwn(own, key))\n return [\n declareOn<AnyEntity>(\n base,\n `variant_${tag}`,\n ({ after }) => {\n const row = after as Readonly<Record<string, NextExpr<unknown>>>\n const checks = [\n ...held.map(key => Expr.isNotNull(row[key]!)),\n ...foreign.map(key => Expr.isNull(row[key]!)),\n ]\n return Expr.or(\n Expr.not(Expr.eq(row._tag!, tag)),\n Expr.and(checks[0]!, ...checks.slice(1)),\n )\n },\n {\n message: `A ${name} that is ${tag} ${[\n ...(held.length > 0 ? [`holds ${held.join(', ')}`] : []),\n ...(foreign.length > 0 ? [`holds none of ${foreign.join(', ')}`] : []),\n ].join(' and ')}`,\n path: reads,\n },\n ),\n ]\n })\n ofCases.set(identity, built)\n return built\n}\n\n/** The Entity's invariants, in the order they were declared. */\nexport const invariantsOf = (entity: AnyEntity): ReadonlyArray<Invariant> => {\n const cases = caseInvariants(entity.identity)\n const declared = Invariants.get(entity.metadata)\n return cases.length === 0 ? declared : [...cases, ...declared]\n}\n\n/** `Entity.judge` against invariants already read, such as those a database binding keeps. */\nexport const judgeAgainst = (\n invariants: ReadonlyArray<Invariant>,\n change: Change,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => {\n const missing = new Set<string>()\n const unrun = new Set<string>()\n const failures: Array<Invariant> = []\n const { after, before } = change\n for (const held of invariants) {\n // A create has no row before, so a transition invariant has nothing to judge.\n if (readsBefore(held) && before === undefined) continue\n const absent = [\n ...held.after.filter(key => !Object.hasOwn(after, key)),\n ...held.before.filter(key => !Object.hasOwn(before ?? {}, key)),\n ]\n if (absent.length > 0) absent.forEach(key => missing.add(key))\n else {\n try {\n if (truthOver(held.predicate, before ?? {}, {}, after, operators) !== true) {\n failures.push(held)\n }\n } catch (error) {\n // An operator this table does not run is a judgement it cannot make, as a\n // field the row lacks is: a form passes it, and a server's checks refuse to\n // start without the operator (expr-operations-DESIGN §5.6).\n if (!(error instanceof OperatorMissingError)) throw error\n unrun.add(error.named)\n }\n }\n }\n if (failures.length > 0) return { _tag: 'Invalid', failures }\n if (missing.size > 0 || unrun.size > 0) {\n return { _tag: 'Undecided', fields: [...missing], operators: [...unrun] }\n }\n return { _tag: 'Valid' }\n}\n\n/**\n * A row, or a change, under every invariant (each row as the store holds it,\n * encoded): valid only when each is true. SQL's unknown, from a null, fails\n * one, as a `WHERE` drops the row; a field a row does not have leaves it\n * undecided, never valid. Without `before` (a create), transition invariants\n * are not judged.\n */\nexport const judge = (\n entity: AnyEntity,\n change: Change,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => judgeAgainst(invariantsOf(entity), change, operators)\n\n/**\n * The row an input's value describes, judged under its Entity's state\n * invariants: each key mapped to a field, encoded as the store holds it, and\n * each mapped to a `one` relation as the id it points at. An\n * invariant over a field the input does not set (an `Option` holding nothing, a\n * key left out) is undecided, so a partial input is never called valid on its\n * account. It has no row before, so it judges no transition.\n */\nexport const judgeInput = (\n input: EntityInput<AnyEntity, any, any>,\n value: Readonly<Record<string, unknown>>,\n operators: MemoryOperators = Operators.kernel,\n): Judgement => {\n const invariants = invariantsOf(input.entity)\n if (invariants.length === 0) return { _tag: 'Valid' }\n const members = input.members as Readonly<Record<string, InputMember>>\n const row: Record<string, unknown> = {}\n for (const [key, member] of Object.entries(members)) {\n if (!Object.hasOwn(value, key)) continue\n // A `one` relation's key holds the id it points at: the row holds that id, or null.\n if (member._tag === 'RelationInput' && member.relation.cardinality === 'one') {\n const given = value[key]\n const id = Option.isOption(given) ? Option.getOrNull(given) : given\n if (id === null || typeof id === 'string') put(row, member.relation.key, id)\n continue\n }\n if (member._tag !== 'Field') continue\n const encode = Schema.encodeUnknownOption(\n member.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n const given = value[key]\n const held = Option.isOption(given) ? given : Option.fromUndefinedOr(given)\n // The value as the field holds it: itself for a field typed `Option`, else what it holds.\n // One the field cannot hold is no row the store would keep, so it decides nothing here.\n const stored = Option.orElse(encode(given), () => Option.flatMap(held, encode))\n Option.map(\n Option.flatMap(held, () => stored),\n encoded => put(row, member.key, encoded),\n )\n }\n return judgeAgainst(invariants, { after: row }, operators)\n}\n\n/**\n * The Entity's state invariants as an Effect Schema check over its row type:\n * each failure at its path, with its message. The value is encoded first,\n * field by field, so it is judged as the store would hold it. Refused where it\n * is made when an invariant calls an operator `operators` does not run: such a\n * check would pass every value.\n */\nexport const check = <E extends AnyEntity>(\n entity: E,\n options: { readonly operators?: MemoryOperators | undefined } = {},\n): SchemaAST.Filter<Schema.Schema.Type<E['schema']>> => {\n const predicates = invariantsOf(entity).map(held => held.predicate)\n // The judge runs every operation an invariant reads; an operator alone can be missing.\n const missing = Expr.unsupported(predicates, {\n operations: dependenciesOf(...predicates).operations,\n operators: options.operators ?? Operators.kernel,\n })\n if (missing.length > 0) {\n throw new Error(\n `[foldkit-entity] Entity.check of ${entity.name}: its invariants call ${missing.join(', ')}, which the operator table does not run; pass one that does as \\`operators\\``,\n )\n }\n return Schema.makeFilter(value => {\n const fields = entity.fields as Readonly<Record<string, AnyField>>\n const decoded = value as Readonly<Record<string, unknown>>\n const row: Record<string, unknown> = {}\n for (const [key, field] of Object.entries(fields)) {\n if (!Object.hasOwn(decoded, key)) continue\n put(\n row,\n key,\n Schema.encodeUnknownSync(field.schema as unknown as Schema.Codec<unknown, unknown>)(\n decoded[key],\n ),\n )\n }\n const judged = judge(entity, { after: row }, options.operators)\n if (judged._tag !== 'Invalid') return undefined\n return judged.failures.flatMap((failure): ReadonlyArray<Schema.FilterIssue> =>\n failure.path.length === 0\n ? [failure.message]\n : failure.path.map(key => ({ path: [key], issue: failure.message })),\n )\n })\n}\n"],"mapp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