foldkit-entity 0.17.0 → 0.19.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 +475 -227
- package/dist/conformance/index.d.ts.map +1 -1
- package/dist/conformance/index.js +10 -4
- package/dist/conformance/index.js.map +1 -1
- package/dist/descriptor.d.ts +5 -1
- package/dist/descriptor.d.ts.map +1 -1
- package/dist/descriptor.js +6 -2
- package/dist/descriptor.js.map +1 -1
- package/dist/entity.d.ts +3 -2
- package/dist/entity.d.ts.map +1 -1
- package/dist/entity.js +5 -3
- package/dist/entity.js.map +1 -1
- package/dist/enumerate.d.ts +44 -0
- package/dist/enumerate.d.ts.map +1 -0
- package/dist/enumerate.js +128 -0
- package/dist/enumerate.js.map +1 -0
- package/dist/evaluate.d.ts +11 -5
- package/dist/evaluate.d.ts.map +1 -1
- package/dist/evaluate.js +27 -6
- package/dist/evaluate.js.map +1 -1
- package/dist/expr.d.ts +8 -2
- package/dist/expr.d.ts.map +1 -1
- package/dist/expr.js +19 -10
- package/dist/expr.js.map +1 -1
- package/dist/footprint.d.ts +120 -0
- package/dist/footprint.d.ts.map +1 -0
- package/dist/footprint.js +41 -0
- package/dist/footprint.js.map +1 -0
- package/dist/index.d.ts +8 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -3
- package/dist/index.js.map +1 -1
- package/dist/invariant.d.ts +41 -11
- package/dist/invariant.d.ts.map +1 -1
- package/dist/invariant.js +83 -38
- package/dist/invariant.js.map +1 -1
- package/dist/lawIds.d.ts +15 -0
- package/dist/lawIds.d.ts.map +1 -0
- package/dist/lawIds.js +13 -0
- package/dist/lawIds.js.map +1 -0
- package/dist/laws.d.ts +308 -0
- package/dist/laws.d.ts.map +1 -0
- package/dist/laws.js +566 -0
- package/dist/laws.js.map +1 -0
- package/dist/operators.d.ts +1 -1
- package/dist/refine.d.ts +64 -0
- package/dist/refine.d.ts.map +1 -0
- package/dist/refine.js +104 -0
- package/dist/refine.js.map +1 -0
- package/dist/rows.d.ts +15 -0
- package/dist/rows.d.ts.map +1 -0
- package/dist/rows.js +23 -0
- package/dist/rows.js.map +1 -0
- package/dist/uncollated.d.ts +10 -0
- package/dist/uncollated.d.ts.map +1 -0
- package/dist/uncollated.js +18 -0
- package/dist/uncollated.js.map +1 -0
- package/dist/write.d.ts +64 -6
- package/dist/write.d.ts.map +1 -1
- package/dist/write.js +88 -12
- package/dist/write.js.map +1 -1
- package/package.json +3 -3
package/dist/invariant.js
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
import { Match, Option, Schema } from "effect";
|
|
2
|
-
import { Metadata } from "foldkit-metadata";
|
|
3
2
|
import { put } from "./record.js";
|
|
4
3
|
import { storesNull, variantsOf } from "./variants.js";
|
|
5
|
-
import {
|
|
4
|
+
import { extend, invariantsOfIdentity, variantBases } from "./descriptor.js";
|
|
5
|
+
import { linkId, oneRelations } from "./rows.js";
|
|
6
|
+
import { OperatorMissingError, truthOver } from "./evaluate.js";
|
|
6
7
|
import { Expr, Query, dependenciesOf } from "./expr.js";
|
|
7
8
|
import { kernelOperators } from "./memoryTable.js";
|
|
8
|
-
import { OperatorMissingError, truthOver } from "./evaluate.js";
|
|
9
9
|
// src/invariant.ts
|
|
10
10
|
/**
|
|
11
11
|
* Invariants: what every stored row of an Entity must hold, and what every
|
|
12
|
-
* change of one must, declared once on the Entity
|
|
13
|
-
*
|
|
14
|
-
*
|
|
12
|
+
* change of one must, declared once on the Entity and read by each
|
|
13
|
+
* interpreter: the reference judge here, a Schema check, a form, a server's
|
|
14
|
+
* writer. They are the Entity's, as its relations are, so every descriptor of
|
|
15
|
+
* it judges them, the one they were declared over included.
|
|
15
16
|
*
|
|
16
17
|
* One is built over the row before a write (`before`, each field as `Expr.field`) and
|
|
17
18
|
* the row after it (`after`, each field as `Expr.next`); each `one` relation is
|
|
@@ -26,10 +27,6 @@ import { OperatorMissingError, truthOver } from "./evaluate.js";
|
|
|
26
27
|
* It reads no input and no principal. Who may write is a guard's; whether a
|
|
27
28
|
* write applies now is its `when`'s.
|
|
28
29
|
*/
|
|
29
|
-
const Invariants = Metadata.key("foldkit-entity/invariants", {
|
|
30
|
-
merge: (values) => [...new Set(values)],
|
|
31
|
-
summarize: (invariant) => invariant.id
|
|
32
|
-
});
|
|
33
30
|
/** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */
|
|
34
31
|
const readsBefore = (held) => held.before.length > 0;
|
|
35
32
|
const fail$1 = (entity, message) => {
|
|
@@ -38,11 +35,7 @@ const fail$1 = (entity, message) => {
|
|
|
38
35
|
/** The invariant `build` declares over `entity`'s rows, refused where it could judge nothing. */
|
|
39
36
|
const declareOn = (entity, id, build, options) => {
|
|
40
37
|
const fields = entity.fields;
|
|
41
|
-
const
|
|
42
|
-
const links = Object.values(relations).flatMap((member) => {
|
|
43
|
-
if (member._tag !== "Relation" || member.cardinality !== "one") return [];
|
|
44
|
-
return [member];
|
|
45
|
-
});
|
|
38
|
+
const links = oneRelations(entity);
|
|
46
39
|
const nexts = [...Object.entries(fields).map(([key, field]) => [key, Expr.next(field)]), ...links.map((link) => [link.key, Expr.next(link)])];
|
|
47
40
|
const after = Object.fromEntries(nexts);
|
|
48
41
|
const predicate = build({
|
|
@@ -71,7 +64,9 @@ const declareOn = (entity, id, build, options) => {
|
|
|
71
64
|
* Declares what every stored row, or every change of one, must hold:
|
|
72
65
|
* `Entity.invariant('reservedWithinQuantity', ({ after }) =>
|
|
73
66
|
* Expr.lte(after.reserved, after.quantity), { message })` over the row a
|
|
74
|
-
* write leaves, or with `before` too over the change an update makes.
|
|
67
|
+
* write leaves, or with `before` too over the change an update makes. It is
|
|
68
|
+
* the Entity's: every descriptor of it judges it, and the step returns the one
|
|
69
|
+
* it was given. Applied to that Entity again, it adds nothing.
|
|
75
70
|
* Refused where it is declared: an id declared twice, a predicate over another
|
|
76
71
|
* Entity, one reading an input or nothing of `after` (that is a `when`), a path
|
|
77
72
|
* naming no field.
|
|
@@ -80,11 +75,17 @@ const invariant = (id, build, options) => {
|
|
|
80
75
|
let attached;
|
|
81
76
|
const declared = (entity) => {
|
|
82
77
|
if (id.length === 0) fail$1(entity, "an invariant needs an id");
|
|
83
|
-
if (attached !== void 0
|
|
78
|
+
if (attached !== void 0) {
|
|
79
|
+
if (attached.identity !== entity.identity) fail$1(entity, `"${id}" is declared on ${attached.name} already: declare it again for this Entity`);
|
|
80
|
+
return entity;
|
|
81
|
+
}
|
|
84
82
|
if (invariantsOf(entity).some((held) => held.id === id)) fail$1(entity, `"${id}" is declared twice`);
|
|
85
|
-
|
|
86
|
-
attached =
|
|
87
|
-
|
|
83
|
+
extend(entity, { invariants: [declareOn(entity, id, build, options)] });
|
|
84
|
+
attached = {
|
|
85
|
+
identity: entity.identity,
|
|
86
|
+
name: entity.name
|
|
87
|
+
};
|
|
88
|
+
return entity;
|
|
88
89
|
};
|
|
89
90
|
return Object.defineProperties(declared, {
|
|
90
91
|
id: {
|
|
@@ -95,7 +96,7 @@ const invariant = (id, build, options) => {
|
|
|
95
96
|
enumerable: true,
|
|
96
97
|
get: () => {
|
|
97
98
|
if (attached === void 0) throw new Error(`[foldkit-entity] Entity.invariant "${id}" names no Entity until it is attached to one`);
|
|
98
|
-
return attached;
|
|
99
|
+
return attached.name;
|
|
99
100
|
}
|
|
100
101
|
}
|
|
101
102
|
});
|
|
@@ -135,7 +136,7 @@ const caseInvariants = (identity) => {
|
|
|
135
136
|
/** The Entity's invariants, in the order they were declared. */
|
|
136
137
|
const invariantsOf = (entity) => {
|
|
137
138
|
const cases = caseInvariants(entity.identity);
|
|
138
|
-
const declared =
|
|
139
|
+
const declared = invariantsOfIdentity(entity.identity);
|
|
139
140
|
return cases.length === 0 ? declared : [...cases, ...declared];
|
|
140
141
|
};
|
|
141
142
|
/** `Entity.judge` against invariants already read, such as those a database binding keeps. */
|
|
@@ -175,14 +176,16 @@ const judgeAgainst = (invariants, change, operators = kernelOperators) => {
|
|
|
175
176
|
*/
|
|
176
177
|
const judge = (entity, change, operators = kernelOperators) => judgeAgainst(invariantsOf(entity), change, operators);
|
|
177
178
|
/**
|
|
178
|
-
* The row an input's value describes, judged under its Entity's
|
|
179
|
-
*
|
|
180
|
-
*
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
*
|
|
179
|
+
* The row an input's value describes, judged under its Entity's invariants:
|
|
180
|
+
* each key mapped to a field, encoded as the store holds it, and each mapped
|
|
181
|
+
* to a `one` relation as the id it points at. Without `over`, an invariant
|
|
182
|
+
* over a field the input does not set (an `Option` holding nothing, a key left
|
|
183
|
+
* out) is undecided, so a partial input is never called valid on its account,
|
|
184
|
+
* and no transition is judged. With `over`, the row it edits, such a field is
|
|
185
|
+
* the row's, and the change from the row to the row with the input laid over
|
|
186
|
+
* it is judged, transitions included.
|
|
184
187
|
*/
|
|
185
|
-
const judgeInput = (input, value,
|
|
188
|
+
const judgeInput = (input, value, options = {}) => {
|
|
186
189
|
const invariants = invariantsOf(input.entity);
|
|
187
190
|
if (invariants.length === 0) return { _tag: "Valid" };
|
|
188
191
|
const members = input.members;
|
|
@@ -202,7 +205,55 @@ const judgeInput = (input, value, operators = kernelOperators) => {
|
|
|
202
205
|
const stored = Option.orElse(encode(given), () => Option.flatMap(held, encode));
|
|
203
206
|
Option.map(Option.flatMap(held, () => stored), (encoded) => put(row, member.key, encoded));
|
|
204
207
|
}
|
|
205
|
-
|
|
208
|
+
const operators = options.operators ?? kernelOperators;
|
|
209
|
+
if (options.over === void 0) return judgeAgainst(invariants, { after: row }, operators);
|
|
210
|
+
const after = {};
|
|
211
|
+
for (const [key, held] of Object.entries(options.over)) put(after, key, held);
|
|
212
|
+
for (const [key, held] of Object.entries(row)) put(after, key, held);
|
|
213
|
+
return judgeAgainst(invariants, {
|
|
214
|
+
after,
|
|
215
|
+
before: options.over
|
|
216
|
+
}, operators);
|
|
217
|
+
};
|
|
218
|
+
/**
|
|
219
|
+
* A decoded value of `entity`, such as a Selection's, as the row the judge
|
|
220
|
+
* reads: each field it holds encoded as the store holds it, and each `one`
|
|
221
|
+
* relation as the id it points at. A member it does not hold is left out, so
|
|
222
|
+
* an invariant reading it is undecided.
|
|
223
|
+
*/
|
|
224
|
+
const rowFrom = (entity, value) => {
|
|
225
|
+
const fields = entity.fields;
|
|
226
|
+
const row = {};
|
|
227
|
+
for (const [key, field] of Object.entries(fields)) {
|
|
228
|
+
if (!Object.hasOwn(value, key)) continue;
|
|
229
|
+
put(row, key, Schema.encodeUnknownSync(field.schema)(value[key]));
|
|
230
|
+
}
|
|
231
|
+
for (const link of oneRelations(entity)) {
|
|
232
|
+
if (!Object.hasOwn(value, link.key)) continue;
|
|
233
|
+
Option.map(linkId(value[link.key]), (id) => put(row, link.key, id));
|
|
234
|
+
}
|
|
235
|
+
return row;
|
|
236
|
+
};
|
|
237
|
+
/**
|
|
238
|
+
* The members outside `input` that its Entity's invariants read, of each
|
|
239
|
+
* invariant that also reads a member the input sets: what a form over the
|
|
240
|
+
* input loads beside its own keys (`Entity.selectFor(input, { also })`), so it
|
|
241
|
+
* can judge those invariants over the row it edits.
|
|
242
|
+
*/
|
|
243
|
+
const judgedBy = (input) => {
|
|
244
|
+
const sets = new Set(Object.values(input.members).flatMap((member) => Match.valueTags(member, {
|
|
245
|
+
Field: ({ key }) => [key],
|
|
246
|
+
RelationInput: ({ relation }) => [relation.key],
|
|
247
|
+
NestedInput: ({ relation }) => [relation.key],
|
|
248
|
+
Unmapped: () => []
|
|
249
|
+
})));
|
|
250
|
+
const read = {};
|
|
251
|
+
for (const held of invariantsOf(input.entity)) {
|
|
252
|
+
const reads = [...held.after, ...held.before];
|
|
253
|
+
if (!reads.some((key) => sets.has(key))) continue;
|
|
254
|
+
for (const key of reads) if (!sets.has(key)) put(read, key, true);
|
|
255
|
+
}
|
|
256
|
+
return read;
|
|
206
257
|
};
|
|
207
258
|
/**
|
|
208
259
|
* The Entity's state invariants as an Effect Schema check over its row type:
|
|
@@ -219,13 +270,7 @@ const check = (entity, options = {}) => {
|
|
|
219
270
|
});
|
|
220
271
|
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\``);
|
|
221
272
|
return Schema.makeFilter((value) => {
|
|
222
|
-
const
|
|
223
|
-
const decoded = value;
|
|
224
|
-
const row = {};
|
|
225
|
-
for (const [key, field] of Object.entries(fields)) {
|
|
226
|
-
if (!Object.hasOwn(decoded, key)) continue;
|
|
227
|
-
put(row, key, Schema.encodeUnknownSync(field.schema)(decoded[key]));
|
|
228
|
-
}
|
|
273
|
+
const row = rowFrom(entity, value);
|
|
229
274
|
const judged = judge(entity, { after: row }, options.operators);
|
|
230
275
|
return Match.valueTags(judged, {
|
|
231
276
|
Invalid: ({ failures }) => failures.flatMap((failure) => failure.path.length === 0 ? [failure.message] : failure.path.map((key) => ({
|
|
@@ -237,6 +282,6 @@ const check = (entity, options = {}) => {
|
|
|
237
282
|
});
|
|
238
283
|
});
|
|
239
284
|
};
|
|
240
|
-
export { check, invariant, invariantsOf, judge, judgeAgainst, judgeInput, readsBefore };
|
|
285
|
+
export { check, invariant, invariantsOf, judge, judgeAgainst, judgeInput, judgedBy, readsBefore, rowFrom };
|
|
241
286
|
|
|
242
287
|
//# sourceMappingURL=invariant.js.map
|
package/dist/invariant.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invariant.js","names":["fail"],"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 { Match, Option, Schema, type SchemaAST } from 'effect'\nimport { OperatorMissingError, truthOver, type Row } from './evaluate.js'\nimport { kernelOperators } from './memoryTable.js'\nimport 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 if (member._tag !== 'Relation' || member.cardinality !== 'one') return []\n return [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 = kernelOperators,\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 = kernelOperators,\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 = kernelOperators,\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.getOrUndefined(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 ?? kernelOperators,\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 return Match.valueTags(judged, {\n Invalid: ({ failures }) =>\n failures.flatMap((failure): ReadonlyArray<Schema.FilterIssue> =>\n failure.path.length === 0\n ? [failure.message]\n : failure.path.map(key => ({ path: [key], issue: failure.message })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ACjC,YAAW,IAAI,KAAK,OAAO,KAAK,OAAO,CACzC;CACF;CACA,OAAO,aAAa,YAAY,EAAE,OAAO,IAAI,GAAG,SAAS;AAC3D;;;;;;;;AASA,MAAa,SACX,QACA,UAAgE,CAAC,MACX;CACtD,MAAM,aAAa,aAAa,MAAM,CAAC,CAAC,KAAI,SAAQ,KAAK,SAAS;CAElE,MAAM,UAAU,KAAK,YAAY,YAAY;EAC3C,YAAY,eAAe,GAAG,UAAU,CAAC,CAAC;EAC1C,WAAW,QAAQ,aAAa;CAClC,CAAC;CACD,IAAI,QAAQ,SAAS,GACnB,MAAM,IAAI,MACR,oCAAoC,OAAO,KAAK,wBAAwB,QAAQ,KAAK,IAAI,EAAE,6EAC7F;CAEF,OAAO,OAAO,YAAW,UAAS;EAChC,MAAM,SAAS,OAAO;EACtB,MAAM,UAAU;EAChB,MAAM,MAA+B,CAAC;EACtC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAAG;GACjD,IAAI,CAAC,OAAO,OAAO,SAAS,GAAG,GAAG;GAClC,IACE,KACA,KACA,OAAO,kBAAkB,MAAM,MAAmD,CAAC,CACjF,QAAQ,IACV,CACF;EACF;EACA,MAAM,SAAS,MAAM,QAAQ,EAAE,OAAO,IAAI,GAAG,QAAQ,SAAS;EAC9D,OAAO,MAAM,UAAU,QAAQ;GAC7B,UAAU,EAAE,eACV,SAAS,SAAS,YAChB,QAAQ,KAAK,WAAW,IACpB,CAAC,QAAQ,OAAO,IAChB,QAAQ,KAAK,KAAI,SAAQ;IAAE,MAAM,CAAC,GAAG;IAAG,OAAO,QAAQ;GAAQ,EAAE,CACvE;GACF,aAAa,KAAA;GACb,iBAAiB,KAAA;EACnB,CAAC;CACH,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"invariant.js","names":["fail"],"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 and read by each\n * interpreter: the reference judge here, a Schema check, a form, a server's\n * writer. They are the Entity's, as its relations are, so every descriptor of\n * it judges them, the one they were declared over included.\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 { Match, Option, Schema, type SchemaAST } from 'effect'\nimport { OperatorMissingError, truthOver, type Row } from './evaluate.js'\nimport { kernelOperators } from './memoryTable.js'\nimport type { MemoryOperators } from './operators.js'\nimport { put } from './record.js'\nimport { linkId, oneRelations } from './rows.js'\nimport {\n Expr,\n Query,\n dependenciesOf,\n type FieldExpr,\n type NextExpr,\n type Predicate,\n type Reads,\n} from './expr.js'\nimport { extend, invariantsOfIdentity, variantBases } from './descriptor.js'\nimport type { AnyEntity, EntityField, EntityIdentity, EntityInput, InputMember } 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\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 and\n * returns the descriptor it was given, carrying its id and, once attached,\n * 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 // A `one` relation reads as the id it points at.\n const links = oneRelations(entity)\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. It is\n * the Entity's: every descriptor of it judges it, and the step returns the one\n * it was given. Applied to that Entity again, it adds nothing.\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: { readonly identity: EntityIdentity<string>; readonly name: string } | undefined\n const declared = (entity: E): E => {\n if (id.length === 0) fail(entity, 'an invariant needs an id')\n if (attached !== undefined) {\n if (attached.identity !== entity.identity)\n fail(\n entity,\n `\"${id}\" is declared on ${attached.name} already: declare it again for this Entity`,\n )\n // Applied again to its Entity, as a module evaluated twice or two pipes over one base do.\n return entity\n }\n if (invariantsOf(entity).some(held => held.id === id)) fail(entity, `\"${id}\" is declared twice`)\n extend(entity, { invariants: [declareOn(entity, id, build, options)] })\n attached = { identity: entity.identity, name: entity.name }\n return entity\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.name\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 = invariantsOfIdentity(entity.identity)\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 = kernelOperators,\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 = kernelOperators,\n): Judgement => judgeAgainst(invariantsOf(entity), change, operators)\n\n/** What `judgeInput` is given beside the input's value. */\nexport interface JudgeInputOptions {\n /** The table the judge runs operators with: `Operators.kernel` by default. */\n readonly operators?: MemoryOperators | undefined\n /**\n * The row the input edits, encoded as the store holds it (`rowFrom`): the\n * input's keys are laid over it, and it is the row before, so transition\n * invariants are judged too. None for a create.\n */\n readonly over?: Readonly<Record<string, unknown>> | undefined\n}\n\n/**\n * The row an input's value describes, judged under its Entity's invariants:\n * each key mapped to a field, encoded as the store holds it, and each mapped\n * to a `one` relation as the id it points at. Without `over`, an invariant\n * over a field the input does not set (an `Option` holding nothing, a key left\n * out) is undecided, so a partial input is never called valid on its account,\n * and no transition is judged. With `over`, the row it edits, such a field is\n * the row's, and the change from the row to the row with the input laid over\n * it is judged, transitions included.\n */\nexport const judgeInput = (\n input: EntityInput<AnyEntity, any, any>,\n value: Readonly<Record<string, unknown>>,\n options: JudgeInputOptions = {},\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.getOrUndefined(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 const operators = options.operators ?? kernelOperators\n if (options.over === undefined) return judgeAgainst(invariants, { after: row }, operators)\n const after: Record<string, unknown> = {}\n for (const [key, held] of Object.entries(options.over)) put(after, key, held)\n for (const [key, held] of Object.entries(row)) put(after, key, held)\n return judgeAgainst(invariants, { after, before: options.over }, operators)\n}\n\n/**\n * A decoded value of `entity`, such as a Selection's, as the row the judge\n * reads: each field it holds encoded as the store holds it, and each `one`\n * relation as the id it points at. A member it does not hold is left out, so\n * an invariant reading it is undecided.\n */\nexport const rowFrom = (\n entity: AnyEntity,\n value: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, unknown>> => {\n const fields = entity.fields as Readonly<Record<string, AnyField>>\n const row: Record<string, unknown> = {}\n for (const [key, field] of Object.entries(fields)) {\n if (!Object.hasOwn(value, key)) continue\n put(\n row,\n key,\n Schema.encodeUnknownSync(field.schema as unknown as Schema.Codec<unknown, unknown>)(\n value[key],\n ),\n )\n }\n for (const link of oneRelations(entity)) {\n if (!Object.hasOwn(value, link.key)) continue\n Option.map(linkId(value[link.key]), id => put(row, link.key, id))\n }\n return row\n}\n\n/**\n * The members outside `input` that its Entity's invariants read, of each\n * invariant that also reads a member the input sets: what a form over the\n * input loads beside its own keys (`Entity.selectFor(input, { also })`), so it\n * can judge those invariants over the row it edits.\n */\nexport const judgedBy = (\n input: EntityInput<AnyEntity, any, any>,\n): Readonly<Record<string, true>> => {\n const sets = new Set(\n Object.values(input.members as Readonly<Record<string, InputMember>>).flatMap(member =>\n Match.valueTags(member, {\n Field: ({ key }) => [key],\n RelationInput: ({ relation }) => [relation.key],\n NestedInput: ({ relation }) => [relation.key],\n Unmapped: () => [],\n }),\n ),\n )\n const read: Record<string, true> = {}\n for (const held of invariantsOf(input.entity)) {\n const reads = [...held.after, ...held.before]\n if (!reads.some(key => sets.has(key))) continue\n for (const key of reads) if (!sets.has(key)) put(read, key, true)\n }\n return read\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 ?? kernelOperators,\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 row = rowFrom(entity, value as Readonly<Record<string, unknown>>)\n const judged = judge(entity, { after: row }, options.operators)\n return Match.valueTags(judged, {\n Invalid: ({ failures }) =>\n 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 Valid: () => undefined,\n Undecided: () => undefined,\n })\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgHA,MAAa,eAAe,SAA6B,KAAK,OAAO,SAAS;AAiB9E,MAAMA,UAAQ,QAAmB,YAA2B;CAC1D,MAAM,IAAI,MAAM,wCAAwC,OAAO,KAAK,IAAI,SAAS;AACnF;;AAcA,MAAM,aACJ,QACA,IACA,OACA,YACc;CACd,MAAM,SAAS,OAAO;CAEtB,MAAM,QAAQ,aAAa,MAAM;CACjC,MAAM,QAAQ,CACZ,GAAG,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,KAAK,KAAK,KAAK,CAAC,CAAU,GAChF,GAAG,MAAM,KAAI,SAAQ,CAAC,KAAK,KAAK,KAAK,KAAK,IAAI,CAAC,CAAU,CAC3D;CACA,MAAM,QAAQ,OAAO,YAAY,KAAK;CAKtC,MAAM,YAAY,MAAM;EAAE,QAHX,OAAO,YACpB,MAAM,KAAK,CAAC,KAAK,UAAU,CAAC,KAAK,KAAK,KAAK,CAAC,CAEf;EAAG;CAAM,CAAC;CAEzC,MAAM,OAAO,MAAM,KAAK,MAAM,CAAC,CAAC,KAAK,MAAM,MAAM,SAAS,CAAC;CAC3D,MAAM,eAAe,MAAM,aAAa,IAAI;CAC5C,IAAI,aAAa,OAAO,SAAS,GAC/B,OAAK,QAAQ,IAAI,GAAG,oBAAoB,aAAa,OAAO,KAAK,IAAI,EAAE,wBAAwB;CAEjG,MAAM,cAAc,aAAa,UAAU,KAAI,UAAS,MAAM,GAAG;CACjE,MAAM,aAAa,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,aAAa,MAAM,MAAM,GAAG;EAC7C,MAAM,QAAQ,CAAC,GAAG,KAAK,OAAO,GAAG,KAAK,MAAM;EAC5C,IAAI,CAAC,MAAM,MAAK,QAAO,KAAK,IAAI,GAAG,CAAC,GAAG;EACvC,KAAK,MAAM,OAAO,OAAO,IAAI,CAAC,KAAK,IAAI,GAAG,GAAG,IAAI,MAAM,KAAK,IAAI;CAClE;CACA,OAAO;AACT;;;;;;;;AASA,MAAa,SACX,QACA,UAAgE,CAAC,MACX;CACtD,MAAM,aAAa,aAAa,MAAM,CAAC,CAAC,KAAI,SAAQ,KAAK,SAAS;CAElE,MAAM,UAAU,KAAK,YAAY,YAAY;EAC3C,YAAY,eAAe,GAAG,UAAU,CAAC,CAAC;EAC1C,WAAW,QAAQ,aAAa;CAClC,CAAC;CACD,IAAI,QAAQ,SAAS,GACnB,MAAM,IAAI,MACR,oCAAoC,OAAO,KAAK,wBAAwB,QAAQ,KAAK,IAAI,EAAE,6EAC7F;CAEF,OAAO,OAAO,YAAW,UAAS;EAChC,MAAM,MAAM,QAAQ,QAAQ,KAA0C;EACtE,MAAM,SAAS,MAAM,QAAQ,EAAE,OAAO,IAAI,GAAG,QAAQ,SAAS;EAC9D,OAAO,MAAM,UAAU,QAAQ;GAC7B,UAAU,EAAE,eACV,SAAS,SAAS,YAChB,QAAQ,KAAK,WAAW,IACpB,CAAC,QAAQ,OAAO,IAChB,QAAQ,KAAK,KAAI,SAAQ;IAAE,MAAM,CAAC,GAAG;IAAG,OAAO,QAAQ;GAAQ,EAAE,CACvE;GACF,aAAa,KAAA;GACb,iBAAiB,KAAA;EACnB,CAAC;CACH,CAAC;AACH"}
|
package/dist/lawIds.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ids a transition and a law have in evidence and in Surface's graph. A
|
|
3
|
+
* module of their own, so code naming a law or a transition does not carry
|
|
4
|
+
* `Laws.check`.
|
|
5
|
+
*/
|
|
6
|
+
/** A declared write's id: `write:Sell`. The function `Laws.transition` is. */
|
|
7
|
+
export declare const transitionId: (entry: {
|
|
8
|
+
readonly name: string;
|
|
9
|
+
}) => string;
|
|
10
|
+
/** An invariant's id: `Product.reservedWithinStock`. The function `Laws.law` is. */
|
|
11
|
+
export declare const lawId: (invariant: {
|
|
12
|
+
readonly id: string;
|
|
13
|
+
readonly entity: string;
|
|
14
|
+
}) => string;
|
|
15
|
+
//# sourceMappingURL=lawIds.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lawIds.d.ts","names":[],"sources":["../src/lawIds.ts"],"mappings":";;;;;;qBAOa,eAAY;WAAsB;;;qBAGlC,QAAK;WAA0B;WAAqB"}
|
package/dist/lawIds.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// src/lawIds.ts
|
|
2
|
+
/**
|
|
3
|
+
* The ids a transition and a law have in evidence and in Surface's graph. A
|
|
4
|
+
* module of their own, so code naming a law or a transition does not carry
|
|
5
|
+
* `Laws.check`.
|
|
6
|
+
*/
|
|
7
|
+
/** A declared write's id: `write:Sell`. The function `Laws.transition` is. */
|
|
8
|
+
const transitionId = (entry) => `write:${entry.name}`;
|
|
9
|
+
/** An invariant's id: `Product.reservedWithinStock`. The function `Laws.law` is. */
|
|
10
|
+
const lawId = (invariant) => `${invariant.entity}.${invariant.id}`;
|
|
11
|
+
export { lawId, transitionId };
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=lawIds.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lawIds.js","names":[],"sources":["../src/lawIds.ts"],"sourcesContent":["/**\n * The ids a transition and a law have in evidence and in Surface's graph. A\n * module of their own, so code naming a law or a transition does not carry\n * `Laws.check`.\n */\n\n/** A declared write's id: `write:Sell`. The function `Laws.transition` is. */\nexport const transitionId = (entry: { readonly name: string }): string => `write:${entry.name}`\n\n/** An invariant's id: `Product.reservedWithinStock`. The function `Laws.law` is. */\nexport const lawId = (invariant: { readonly id: string; readonly entity: string }): string =>\n `${invariant.entity}.${invariant.id}`\n"],"mappings":";;;;;;;AAOA,MAAa,gBAAgB,UAA6C,SAAS,MAAM;;AAGzF,MAAa,SAAS,cACpB,GAAG,UAAU,OAAO,GAAG,UAAU"}
|