foldkit-entity 0.16.0 → 0.18.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 (82) hide show
  1. package/README.md +582 -240
  2. package/dist/conformance/index.d.ts.map +1 -1
  3. package/dist/conformance/index.js +30 -4
  4. package/dist/conformance/index.js.map +1 -1
  5. package/dist/conformance/operator.d.ts.map +1 -1
  6. package/dist/conformance/operator.js +13 -4
  7. package/dist/conformance/operator.js.map +1 -1
  8. package/dist/descriptor.d.ts +5 -1
  9. package/dist/descriptor.d.ts.map +1 -1
  10. package/dist/descriptor.js +6 -2
  11. package/dist/descriptor.js.map +1 -1
  12. package/dist/entity.d.ts +16 -3
  13. package/dist/entity.d.ts.map +1 -1
  14. package/dist/entity.js +44 -14
  15. package/dist/entity.js.map +1 -1
  16. package/dist/enumerate.d.ts +44 -0
  17. package/dist/enumerate.d.ts.map +1 -0
  18. package/dist/enumerate.js +128 -0
  19. package/dist/enumerate.js.map +1 -0
  20. package/dist/evaluate.d.ts +12 -6
  21. package/dist/evaluate.d.ts.map +1 -1
  22. package/dist/evaluate.js +48 -23
  23. package/dist/evaluate.js.map +1 -1
  24. package/dist/expr.d.ts +78 -22
  25. package/dist/expr.d.ts.map +1 -1
  26. package/dist/expr.js +86 -57
  27. package/dist/expr.js.map +1 -1
  28. package/dist/footprint.d.ts +120 -0
  29. package/dist/footprint.d.ts.map +1 -0
  30. package/dist/footprint.js +41 -0
  31. package/dist/footprint.js.map +1 -0
  32. package/dist/held.js +11 -3
  33. package/dist/held.js.map +1 -1
  34. package/dist/index.d.ts +24 -7
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +10 -6
  37. package/dist/index.js.map +1 -1
  38. package/dist/invariant.d.ts +41 -11
  39. package/dist/invariant.d.ts.map +1 -1
  40. package/dist/invariant.js +102 -51
  41. package/dist/invariant.js.map +1 -1
  42. package/dist/law.d.ts.map +1 -1
  43. package/dist/law.js +3 -9
  44. package/dist/law.js.map +1 -1
  45. package/dist/lawCore.d.ts +42 -0
  46. package/dist/lawCore.d.ts.map +1 -0
  47. package/dist/lawCore.js +12 -0
  48. package/dist/lawCore.js.map +1 -0
  49. package/dist/lawIds.d.ts +15 -0
  50. package/dist/lawIds.d.ts.map +1 -0
  51. package/dist/lawIds.js +13 -0
  52. package/dist/lawIds.js.map +1 -0
  53. package/dist/laws.d.ts +308 -0
  54. package/dist/laws.d.ts.map +1 -0
  55. package/dist/laws.js +566 -0
  56. package/dist/laws.js.map +1 -0
  57. package/dist/memoryTable.d.ts +11 -0
  58. package/dist/memoryTable.d.ts.map +1 -0
  59. package/dist/memoryTable.js +69 -0
  60. package/dist/memoryTable.js.map +1 -0
  61. package/dist/operators.d.ts +1 -1
  62. package/dist/operators.d.ts.map +1 -1
  63. package/dist/operators.js +2 -66
  64. package/dist/operators.js.map +1 -1
  65. package/dist/refine.d.ts +64 -0
  66. package/dist/refine.d.ts.map +1 -0
  67. package/dist/refine.js +104 -0
  68. package/dist/refine.js.map +1 -0
  69. package/dist/rows.d.ts +15 -0
  70. package/dist/rows.d.ts.map +1 -0
  71. package/dist/rows.js +23 -0
  72. package/dist/rows.js.map +1 -0
  73. package/dist/sets.js.map +1 -1
  74. package/dist/uncollated.d.ts +10 -0
  75. package/dist/uncollated.d.ts.map +1 -0
  76. package/dist/uncollated.js +18 -0
  77. package/dist/uncollated.js.map +1 -0
  78. package/dist/write.d.ts +65 -7
  79. package/dist/write.d.ts.map +1 -1
  80. package/dist/write.js +128 -30
  81. package/dist/write.js.map +1 -1
  82. package/package.json +3 -3
@@ -1,8 +1,8 @@
1
1
  import { Schema, SchemaAST } from "effect";
2
2
  import { AnyEntity, EntityInput } from "./index.js";
3
+ import { Row } from "./evaluate.js";
3
4
  import { FieldExpr, NextExpr, Predicate, Reads } from "./expr.js";
4
5
  import { MemoryOperators as MemoryOperators$1 } from "./operators.js";
5
- import { Row } from "./evaluate.js";
6
6
  /** One invariant of an Entity, as its interpreters read it. */
7
7
  export interface Invariant {
8
8
  /** Stable, unique within its Entity: what a refusal names, and forms and logs key on. */
@@ -57,8 +57,9 @@ export type Judgement = {
57
57
  /** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */
58
58
  export declare const readsBefore: (held: Invariant) => boolean;
59
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
60
+ * An invariant as declared: the step that attaches it to its Entity and
61
+ * returns the descriptor it was given, carrying its id and, once attached,
62
+ * that Entity's name, so a refusal is matched
62
63
  * against the declaration rather than a string spelled again
63
64
  * (`Refusal.isInvalidBy(refusal, reservedWithinQuantity)`). An id is unique
64
65
  * only within an Entity, so the name is part of what a refusal names; reading
@@ -82,7 +83,9 @@ interface Options<E extends AnyEntity> {
82
83
  * Declares what every stored row, or every change of one, must hold:
83
84
  * `Entity.invariant('reservedWithinQuantity', ({ after }) =>
84
85
  * 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
+ * write leaves, or with `before` too over the change an update makes. It is
87
+ * the Entity's: every descriptor of it judges it, and the step returns the one
88
+ * it was given. Applied to that Entity again, it adds nothing.
86
89
  * Refused where it is declared: an id declared twice, a predicate over another
87
90
  * Entity, one reading an input or nothing of `after` (that is a `when`), a path
88
91
  * naming no field.
@@ -100,15 +103,42 @@ export declare const judgeAgainst: (invariants: ReadonlyArray<Invariant>, change
100
103
  * are not judged.
101
104
  */
102
105
  export declare const judge: (entity: AnyEntity, change: Change, operators?: MemoryOperators$1) => Judgement;
106
+ /** What `judgeInput` is given beside the input's value. */
107
+ export interface JudgeInputOptions {
108
+ /** The table the judge runs operators with: `Operators.kernel` by default. */
109
+ readonly operators?: MemoryOperators$1 | undefined;
110
+ /**
111
+ * The row the input edits, encoded as the store holds it (`rowFrom`): the
112
+ * input's keys are laid over it, and it is the row before, so transition
113
+ * invariants are judged too. None for a create.
114
+ */
115
+ readonly over?: Readonly<Record<string, unknown>> | undefined;
116
+ }
117
+ /**
118
+ * The row an input's value describes, judged under its Entity's invariants:
119
+ * each key mapped to a field, encoded as the store holds it, and each mapped
120
+ * to a `one` relation as the id it points at. Without `over`, an invariant
121
+ * over a field the input does not set (an `Option` holding nothing, a key left
122
+ * out) is undecided, so a partial input is never called valid on its account,
123
+ * and no transition is judged. With `over`, the row it edits, such a field is
124
+ * the row's, and the change from the row to the row with the input laid over
125
+ * it is judged, transitions included.
126
+ */
127
+ export declare const judgeInput: (input: EntityInput<AnyEntity, any, any>, value: Readonly<Record<string, unknown>>, options?: JudgeInputOptions) => Judgement;
128
+ /**
129
+ * A decoded value of `entity`, such as a Selection's, as the row the judge
130
+ * reads: each field it holds encoded as the store holds it, and each `one`
131
+ * relation as the id it points at. A member it does not hold is left out, so
132
+ * an invariant reading it is undecided.
133
+ */
134
+ export declare const rowFrom: (entity: AnyEntity, value: Readonly<Record<string, unknown>>) => Readonly<Record<string, unknown>>;
103
135
  /**
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.
136
+ * The members outside `input` that its Entity's invariants read, of each
137
+ * invariant that also reads a member the input sets: what a form over the
138
+ * input loads beside its own keys (`Entity.selectFor(input, { also })`), so it
139
+ * can judge those invariants over the row it edits.
110
140
  */
111
- export declare const judgeInput: (input: EntityInput<AnyEntity, any, any>, value: Readonly<Record<string, unknown>>, operators?: MemoryOperators$1) => Judgement;
141
+ export declare const judgedBy: (input: EntityInput<AnyEntity, any, any>) => Readonly<Record<string, true>>;
112
142
  /**
113
143
  * The Entity's state invariants as an Effect Schema check over its row type:
114
144
  * each failure at its path, with its message. The value is encoded first,
@@ -1 +1 @@
1
- {"version":3,"file":"invariant.d.ts","names":["MemoryOperators"],"sources":["../src/invariant.ts"],"mappings":";;;;;;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,0BAAwB,UAC/B,sBACR;;;;;;;qBA0CU,UAAO,QACV,WAAS,OACV,SAAS,6BACf,SAAS;;;;;;;qBA0BC,WAAQ,OACZ,YAAY,yBAClB,SAAS;;;;;;;;qBA2BC,QAAS,UAAU,WAAS,QAC/B,GAAC;WACW,YAAYA;MAC/B,UAAU,OAAO,OAAO,OAAO,KAAK"}
package/dist/invariant.js CHANGED
@@ -1,17 +1,18 @@
1
- import { Option, Schema } from "effect";
2
- import { Metadata } from "foldkit-metadata";
1
+ import { Match, Option, Schema } from "effect";
3
2
  import { put } from "./record.js";
4
3
  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";
4
+ import { extend, invariantsOfIdentity, variantBases } from "./descriptor.js";
5
+ import { linkId, oneRelations } from "./rows.js";
8
6
  import { OperatorMissingError, truthOver } from "./evaluate.js";
7
+ import { Expr, Query, dependenciesOf } from "./expr.js";
8
+ import { kernelOperators } from "./memoryTable.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 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.
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,20 +27,15 @@ 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
- const fail = (entity, message) => {
32
+ const fail$1 = (entity, message) => {
36
33
  throw new Error(`[foldkit-entity] Entity.invariant on ${entity.name}: ${message}`);
37
34
  };
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 relations = entity.relations;
42
- const links = Object.values(relations).flatMap((member) => member._tag === "Relation" && member.cardinality === "one" ? [member] : []);
38
+ const links = oneRelations(entity);
43
39
  const nexts = [...Object.entries(fields).map(([key, field]) => [key, Expr.next(field)]), ...links.map((link) => [link.key, Expr.next(link)])];
44
40
  const after = Object.fromEntries(nexts);
45
41
  const predicate = build({
@@ -48,12 +44,12 @@ const declareOn = (entity, id, build, options) => {
48
44
  });
49
45
  const body = Query.from(entity).pipe(Query.where(predicate));
50
46
  const dependencies = Query.dependencies(body);
51
- if (dependencies.inputs.length > 0) fail(entity, `"${id}" reads the input ${dependencies.inputs.join(", ")}; it judges stored rows`);
47
+ if (dependencies.inputs.length > 0) fail$1(entity, `"${id}" reads the input ${dependencies.inputs.join(", ")}; it judges stored rows`);
52
48
  const beforeReads = dependencies.predicate.map((field) => field.key);
53
49
  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\``);
50
+ if (afterReads.length === 0) fail$1(entity, `"${id}" reads no field of \`after\`; what a write may start from is its \`when\``);
55
51
  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`);
52
+ for (const key of path) if (!Object.hasOwn(fields, key) && !links.some((link) => link.key === key)) fail$1(entity, `"${id}"'s path names "${key}", neither a field nor a one relation`);
57
53
  return Object.freeze({
58
54
  id,
59
55
  entity: entity.name,
@@ -68,7 +64,9 @@ const declareOn = (entity, id, build, options) => {
68
64
  * Declares what every stored row, or every change of one, must hold:
69
65
  * `Entity.invariant('reservedWithinQuantity', ({ after }) =>
70
66
  * Expr.lte(after.reserved, after.quantity), { message })` over the row a
71
- * 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.
72
70
  * Refused where it is declared: an id declared twice, a predicate over another
73
71
  * Entity, one reading an input or nothing of `after` (that is a `when`), a path
74
72
  * naming no field.
@@ -76,12 +74,18 @@ const declareOn = (entity, id, build, options) => {
76
74
  const invariant = (id, build, options) => {
77
75
  let attached;
78
76
  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)]) });
77
+ if (id.length === 0) fail$1(entity, "an invariant needs an id");
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
+ }
82
+ if (invariantsOf(entity).some((held) => held.id === id)) fail$1(entity, `"${id}" is declared twice`);
83
+ extend(entity, { invariants: [declareOn(entity, id, build, options)] });
84
+ attached = {
85
+ identity: entity.identity,
86
+ name: entity.name
87
+ };
88
+ return entity;
85
89
  };
86
90
  return Object.defineProperties(declared, {
87
91
  id: {
@@ -92,7 +96,7 @@ const invariant = (id, build, options) => {
92
96
  enumerable: true,
93
97
  get: () => {
94
98
  if (attached === void 0) throw new Error(`[foldkit-entity] Entity.invariant "${id}" names no Entity until it is attached to one`);
95
- return attached;
99
+ return attached.name;
96
100
  }
97
101
  }
98
102
  });
@@ -132,11 +136,11 @@ const caseInvariants = (identity) => {
132
136
  /** The Entity's invariants, in the order they were declared. */
133
137
  const invariantsOf = (entity) => {
134
138
  const cases = caseInvariants(entity.identity);
135
- const declared = Invariants.get(entity.metadata);
139
+ const declared = invariantsOfIdentity(entity.identity);
136
140
  return cases.length === 0 ? declared : [...cases, ...declared];
137
141
  };
138
142
  /** `Entity.judge` against invariants already read, such as those a database binding keeps. */
139
- const judgeAgainst = (invariants, change, operators = Operators.kernel) => {
143
+ const judgeAgainst = (invariants, change, operators = kernelOperators) => {
140
144
  const missing = /* @__PURE__ */ new Set();
141
145
  const unrun = /* @__PURE__ */ new Set();
142
146
  const failures = [];
@@ -170,16 +174,18 @@ const judgeAgainst = (invariants, change, operators = Operators.kernel) => {
170
174
  * undecided, never valid. Without `before` (a create), transition invariants
171
175
  * are not judged.
172
176
  */
173
- const judge = (entity, change, operators = Operators.kernel) => judgeAgainst(invariantsOf(entity), change, operators);
177
+ const judge = (entity, change, operators = kernelOperators) => judgeAgainst(invariantsOf(entity), change, operators);
174
178
  /**
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.
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.
181
187
  */
182
- const judgeInput = (input, value, operators = Operators.kernel) => {
188
+ const judgeInput = (input, value, options = {}) => {
183
189
  const invariants = invariantsOf(input.entity);
184
190
  if (invariants.length === 0) return { _tag: "Valid" };
185
191
  const members = input.members;
@@ -199,7 +205,55 @@ const judgeInput = (input, value, operators = Operators.kernel) => {
199
205
  const stored = Option.orElse(encode(given), () => Option.flatMap(held, encode));
200
206
  Option.map(Option.flatMap(held, () => stored), (encoded) => put(row, member.key, encoded));
201
207
  }
202
- return judgeAgainst(invariants, { after: row }, operators);
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;
203
257
  };
204
258
  /**
205
259
  * The Entity's state invariants as an Effect Schema check over its row type:
@@ -212,25 +266,22 @@ const check = (entity, options = {}) => {
212
266
  const predicates = invariantsOf(entity).map((held) => held.predicate);
213
267
  const missing = Expr.unsupported(predicates, {
214
268
  operations: dependenciesOf(...predicates).operations,
215
- operators: options.operators ?? Operators.kernel
269
+ operators: options.operators ?? kernelOperators
216
270
  });
217
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\``);
218
272
  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
- }
273
+ const row = rowFrom(entity, value);
226
274
  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
- })));
275
+ return Match.valueTags(judged, {
276
+ Invalid: ({ failures }) => failures.flatMap((failure) => failure.path.length === 0 ? [failure.message] : failure.path.map((key) => ({
277
+ path: [key],
278
+ issue: failure.message
279
+ }))),
280
+ Valid: () => void 0,
281
+ Undecided: () => void 0
282
+ });
232
283
  });
233
284
  };
234
- export { check, invariant, invariantsOf, judge, judgeAgainst, judgeInput, readsBefore };
285
+ export { check, invariant, invariantsOf, judge, judgeAgainst, judgeInput, judgedBy, readsBefore, rowFrom };
235
286
 
236
287
  //# sourceMappingURL=invariant.js.map
@@ -1 +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.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 ?? 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuGA,MAAM,aAAa,SAAS,IAAe,6BAA6B;CAEtE,QAAO,WAAU,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;CACpC,YAAW,cAAa,UAAU;AACpC,CAAC;;AAiBD,MAAa,eAAe,SAA6B,KAAK,OAAO,SAAS;AAgB9E,MAAM,QAAQ,QAAmB,YAA2B;CAC1D,MAAM,IAAI,MAAM,wCAAwC,OAAO,KAAK,IAAI,SAAS;AACnF;;AAcA,MAAM,aACJ,QACA,IACA,OACA,YACc;CACd,MAAM,SAAS,OAAO;CACtB,MAAM,YAAY,OAAO;CAEzB,MAAM,QAAQ,OAAO,OAAO,SAAS,CAAC,CAAC,SAAQ,WAC7C,OAAO,SAAS,cAAc,OAAO,gBAAgB,QAAQ,CAAC,MAAqB,IAAI,CAAC,CAC1F;CACA,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,KAA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,KAAK,KAAI,SAAQ;GAAE,MAAM,CAAC,GAAG;GAAG,OAAO,QAAQ;EAAQ,EAAE,CACvE;CACF,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,MA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A,OAAO,OAAO,OAAO;eACtB;eACD,MAAA;;;eAfe,QAAA,OAAO,OAAO,OAAO;;;eAErB,QAAA,OAAO,OAAO,OAAO;;;eAsBrB,QAAA,OAAO,OAAO,OAAO;eAAqB,MAAA;;;eApB3C,QAAA,OAAO,OAAO,OAAO;;;eAGjC,QAAA,OAAO,OAAO,OAAO;eACtB;eACD,MAAA;;;eAUE,QAAA,OAAO,OAAO,OAAO;eACtB,OAAA;eACG;;;eAMF,QAAA,OAAO,OAAO,OAAO;eAClB;eACD;;;eAGkB,QAAA,OAAO,OAAO,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6D5D,iBAAc,KAAQ,mBAAiB;;EAMvC,WAAQ,KAAQ,QAAM"}
package/dist/law.js CHANGED
@@ -1,13 +1,7 @@
1
- import { Data, Option, Schema } from "effect";
1
+ import { Option, Schema } from "effect";
2
+ import { Laws, lawKind } from "./lawCore.js";
2
3
  import { jsonSchemaOf } from "./jsonSchema.js";
3
4
  // src/law.ts
4
- /**
5
- * Laws an operator declares (expr-operations-DESIGN §10): equations every
6
- * implementation of it keeps over a domain. A law describes; nothing rewrites a
7
- * body by one. `Conformance.laws` tests an implementation against them, and
8
- * what it finds is evidence recorded in that implementation's table.
9
- */
10
- const Laws = Data.taggedEnum();
11
5
  const unnarrowed = { domain: Option.none() };
12
6
  /**
13
7
  * A law as JSON says it: what `Operators.describe` lists and evidence names.
@@ -97,7 +91,7 @@ const Law = {
97
91
  })
98
92
  });
99
93
  return {
100
- kind: law._tag.charAt(0).toLowerCase() + law._tag.slice(1),
94
+ kind: lawKind(law),
101
95
  witnesses,
102
96
  domain: Option.match(law.domain, {
103
97
  onNone: () => null,
package/dist/law.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"law.js","names":[],"sources":["../src/law.ts"],"sourcesContent":["/**\n * Laws an operator declares (expr-operations-DESIGN §10): equations every\n * implementation of it keeps over a domain. A law describes; nothing rewrites a\n * body by one. `Conformance.laws` tests an implementation against them, and\n * what it finds is evidence recorded in that implementation's table.\n */\nimport { Data, Option, Schema } from 'effect'\nimport type { Operator } from './expr.js'\nimport { jsonSchemaOf } from './jsonSchema.js'\n\n/** An operator a law names as a witness: the inverse, or the operator distributed over. */\ntype AnyOperator = Operator<ReadonlyArray<Schema.Top>, Schema.Top>\n\n/** Which argument a witness stands in. */\nexport type Side = 'left' | 'right' | 'both'\n\n/**\n * A law, over its domain: by default every non-null value of the operator's\n * input schemas; narrowed by `Law.within`.\n */\nexport type Law = Data.TaggedEnum<{\n /** `op(op(a, b), c) = op(a, op(b, c))` */\n Associative: { readonly domain: Option.Option<Schema.Top> }\n /** `op(a, b) = op(b, a)` */\n Commutative: { readonly domain: Option.Option<Schema.Top> }\n /** `op(a, a) = a` */\n Idempotent: { readonly domain: Option.Option<Schema.Top> }\n /** `op(e, a) = a` (left), `op(a, e) = a` (right), or both. */\n Identity: {\n readonly domain: Option.Option<Schema.Top>\n readonly value: unknown\n readonly side: Side\n }\n /** `op(z, a) = z` (left), `op(a, z) = z` (right), or both. */\n Absorbing: {\n readonly domain: Option.Option<Schema.Top>\n readonly value: unknown\n readonly side: Side\n }\n /** `op(a, other(a)) = identity` */\n Inverse: {\n readonly domain: Option.Option<Schema.Top>\n readonly other: AnyOperator\n readonly identity: unknown\n }\n /** `op(a, over(b, c)) = over(op(a, b), op(a, c))` */\n Distributes: { readonly domain: Option.Option<Schema.Top>; readonly over: AnyOperator }\n /** `a ≤ b` at `position` implies `op(…a…) ≤ op(…b…)`, or `≥` when decreasing. */\n Monotonic: {\n readonly domain: Option.Option<Schema.Top>\n readonly direction: 'increasing' | 'decreasing'\n readonly position: number\n }\n /** Folding the result equals folding the arguments first: its text keeps their collation (§7). */\n PreservesCollation: { readonly domain: Option.Option<Schema.Top> }\n}>\n\nconst Laws = Data.taggedEnum<Law>()\nconst unnarrowed = { domain: Option.none<Schema.Top>() }\n\n/**\n * A law as JSON says it: what `Operators.describe` lists and evidence names.\n * Its witnesses are values as stored and operators by name; its domain is a\n * JSON Schema, or `null` for the operator's whole input.\n */\nexport const LawDescription = Schema.Struct({\n kind: Schema.String,\n witnesses: Schema.Record(Schema.String, Schema.Unknown),\n domain: Schema.Unknown,\n})\nexport type LawDescription = typeof LawDescription.Type\n\n/** An operator by its id, and its version when that is not the first. */\nconst nameOf = (operator: AnyOperator): string =>\n operator.descriptor.version === 1\n ? operator.descriptor.id\n : `${operator.descriptor.id}@${operator.descriptor.version}`\n\nexport const Law = {\n associative: Laws.Associative(unnarrowed),\n commutative: Laws.Commutative(unnarrowed),\n idempotent: Laws.Idempotent(unnarrowed),\n preservesCollation: Laws.PreservesCollation(unnarrowed),\n /** `value` leaves the other argument as it is, from `side` (both by default). */\n identity: (value: unknown, side: Side = 'both'): Law =>\n Laws.Identity({ ...unnarrowed, value, side }),\n /** `value` is the answer whatever the other argument, from `side` (both by default). */\n absorbing: (value: unknown, side: Side = 'both'): Law =>\n Laws.Absorbing({ ...unnarrowed, value, side }),\n /** `other` undoes the operator: `op(a, other(a))` is `identity`. */\n inverse: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n other: Operator<In, Out>,\n identity: unknown,\n ): Law => Laws.Inverse({ ...unnarrowed, other, identity }),\n /** The operator distributes over `over`, from the left. */\n distributes: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n over: Operator<In, Out>,\n ): Law => Laws.Distributes({ ...unnarrowed, over }),\n /** Moving the argument at `position` up moves the result up (or down, decreasing). */\n monotonic: (direction: 'increasing' | 'decreasing', position: number): Law =>\n Laws.Monotonic({ ...unnarrowed, direction, position }),\n /**\n * The law over the values `domain` accepts only: a law that holds of the\n * integers and not of every number, say, narrowed so it is tested where it\n * is claimed.\n */\n within: (law: Law, domain: Schema.Top): Law =>\n Object.freeze({ ...law, domain: Option.some(domain) }),\n\n $match: Laws.$match,\n\n /**\n * The operators a law, as JSON, calls besides its own (`inverse`'s and\n * `distributes`' witnesses), by name: evidence of it is of their\n * implementations too, and goes when one of them is replaced.\n */\n witnessesNamed: (law: LawDescription): ReadonlyArray<string> =>\n [law.witnesses['other'], law.witnesses['over']].filter(\n (name): name is string => typeof name === 'string',\n ),\n\n /** The law as JSON: its kind, its witnesses (operators by name) and its domain's JSON Schema. */\n describe: (law: Law): LawDescription => {\n const witnesses: Record<string, unknown> = Laws.$match(law, {\n Associative: () => ({}),\n Commutative: () => ({}),\n Idempotent: () => ({}),\n PreservesCollation: () => ({}),\n Identity: ({ value, side }) => ({ value, side }),\n Absorbing: ({ value, side }) => ({ value, side }),\n Inverse: ({ other, identity }) => ({ other: nameOf(other), identity }),\n Distributes: ({ over }) => ({ over: nameOf(over) }),\n Monotonic: ({ direction, position }) => ({ direction, position }),\n })\n return {\n kind: law._tag.charAt(0).toLowerCase() + law._tag.slice(1),\n witnesses,\n domain: Option.match(law.domain, {\n onNone: () => null,\n onSome: jsonSchemaOf,\n }),\n }\n },\n}\n"],"mappings":";;;;;;;;;AAyDA,MAAM,OAAO,KAAK,WAAgB;AAClC,MAAM,aAAa,EAAE,QAAQ,OAAO,KAAiB,EAAE;;;;;;AAOvD,MAAa,iBAAiB,OAAO,OAAO;CAC1C,MAAM,OAAO;CACb,WAAW,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;CACtD,QAAQ,OAAO;AACjB,CAAC;;AAID,MAAM,UAAU,aACd,SAAS,WAAW,YAAY,IAC5B,SAAS,WAAW,KACpB,GAAG,SAAS,WAAW,GAAG,GAAG,SAAS,WAAW;AAEvD,MAAa,MAAM;CACjB,aAAa,KAAK,YAAY,UAAU;CACxC,aAAa,KAAK,YAAY,UAAU;CACxC,YAAY,KAAK,WAAW,UAAU;CACtC,oBAAoB,KAAK,mBAAmB,UAAU;;CAEtD,WAAW,OAAgB,OAAa,WACtC,KAAK,SAAS;EAAE,GAAG;EAAY;EAAO;CAAK,CAAC;;CAE9C,YAAY,OAAgB,OAAa,WACvC,KAAK,UAAU;EAAE,GAAG;EAAY;EAAO;CAAK,CAAC;;CAE/C,UACE,OACA,aACQ,KAAK,QAAQ;EAAE,GAAG;EAAY;EAAO;CAAS,CAAC;;CAEzD,cACE,SACQ,KAAK,YAAY;EAAE,GAAG;EAAY;CAAK,CAAC;;CAElD,YAAY,WAAwC,aAClD,KAAK,UAAU;EAAE,GAAG;EAAY;EAAW;CAAS,CAAC;;;;;;CAMvD,SAAS,KAAU,WACjB,OAAO,OAAO;EAAE,GAAG;EAAK,QAAQ,OAAO,KAAK,MAAM;CAAE,CAAC;CAEvD,QAAQ,KAAK;;;;;;CAOb,iBAAiB,QACf,CAAC,IAAI,UAAU,UAAU,IAAI,UAAU,OAAO,CAAC,CAAC,QAC7C,SAAyB,OAAO,SAAS,QAC5C;;CAGF,WAAW,QAA6B;EACtC,MAAM,YAAqC,KAAK,OAAO,KAAK;GAC1D,oBAAoB,CAAC;GACrB,oBAAoB,CAAC;GACrB,mBAAmB,CAAC;GACpB,2BAA2B,CAAC;GAC5B,WAAW,EAAE,OAAO,YAAY;IAAE;IAAO;GAAK;GAC9C,YAAY,EAAE,OAAO,YAAY;IAAE;IAAO;GAAK;GAC/C,UAAU,EAAE,OAAO,gBAAgB;IAAE,OAAO,OAAO,KAAK;IAAG;GAAS;GACpE,cAAc,EAAE,YAAY,EAAE,MAAM,OAAO,IAAI,EAAE;GACjD,YAAY,EAAE,WAAW,gBAAgB;IAAE;IAAW;GAAS;EACjE,CAAC;EACD,OAAO;GACL,MAAM,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,IAAI,KAAK,MAAM,CAAC;GACzD;GACA,QAAQ,OAAO,MAAM,IAAI,QAAQ;IAC/B,cAAc;IACd,QAAQ;GACV,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"law.js","names":[],"sources":["../src/law.ts"],"sourcesContent":["/**\n * Laws an operator declares (expr-operations-DESIGN §10): equations every\n * implementation of it keeps over a domain. A law describes; nothing rewrites a\n * body by one. `Conformance.laws` tests an implementation against them, and\n * what it finds is evidence recorded in that implementation's table.\n */\nimport type { Data } from 'effect'\nimport { Option, Schema } from 'effect'\nimport type { Operator } from './expr.js'\nimport { jsonSchemaOf } from './jsonSchema.js'\nimport { Laws, lawKind } from './lawCore.js'\n\n/** An operator a law names as a witness: the inverse, or the operator distributed over. */\ntype AnyOperator = Operator<ReadonlyArray<Schema.Top>, Schema.Top>\n\n/** Which argument a witness stands in. */\nexport type Side = 'left' | 'right' | 'both'\n\n/**\n * A law, over its domain: by default every non-null value of the operator's\n * input schemas; narrowed by `Law.within`.\n */\nexport type Law = Data.TaggedEnum<{\n /** `op(op(a, b), c) = op(a, op(b, c))` */\n Associative: { readonly domain: Option.Option<Schema.Top> }\n /** `op(a, b) = op(b, a)` */\n Commutative: { readonly domain: Option.Option<Schema.Top> }\n /** `op(a, a) = a` */\n Idempotent: { readonly domain: Option.Option<Schema.Top> }\n /** `op(e, a) = a` (left), `op(a, e) = a` (right), or both. */\n Identity: {\n readonly domain: Option.Option<Schema.Top>\n readonly value: unknown\n readonly side: Side\n }\n /** `op(z, a) = z` (left), `op(a, z) = z` (right), or both. */\n Absorbing: {\n readonly domain: Option.Option<Schema.Top>\n readonly value: unknown\n readonly side: Side\n }\n /** `op(a, other(a)) = identity` */\n Inverse: {\n readonly domain: Option.Option<Schema.Top>\n readonly other: AnyOperator\n readonly identity: unknown\n }\n /** `op(a, over(b, c)) = over(op(a, b), op(a, c))` */\n Distributes: { readonly domain: Option.Option<Schema.Top>; readonly over: AnyOperator }\n /** `a ≤ b` at `position` implies `op(…a…) ≤ op(…b…)`, or `≥` when decreasing. */\n Monotonic: {\n readonly domain: Option.Option<Schema.Top>\n readonly direction: 'increasing' | 'decreasing'\n readonly position: number\n }\n /** Folding the result equals folding the arguments first: its text keeps their collation (§7). */\n PreservesCollation: { readonly domain: Option.Option<Schema.Top> }\n}>\n\nconst unnarrowed = { domain: Option.none<Schema.Top>() }\n\n/**\n * A law as JSON says it: what `Operators.describe` lists and evidence names.\n * Its witnesses are values as stored and operators by name; its domain is a\n * JSON Schema, or `null` for the operator's whole input.\n */\nexport const LawDescription = Schema.Struct({\n kind: Schema.String,\n witnesses: Schema.Record(Schema.String, Schema.Unknown),\n domain: Schema.Unknown,\n})\nexport type LawDescription = typeof LawDescription.Type\n\n/** An operator by its id, and its version when that is not the first. */\nconst nameOf = (operator: AnyOperator): string =>\n operator.descriptor.version === 1\n ? operator.descriptor.id\n : `${operator.descriptor.id}@${operator.descriptor.version}`\n\nexport const Law = {\n associative: Laws.Associative(unnarrowed),\n commutative: Laws.Commutative(unnarrowed),\n idempotent: Laws.Idempotent(unnarrowed),\n preservesCollation: Laws.PreservesCollation(unnarrowed),\n /** `value` leaves the other argument as it is, from `side` (both by default). */\n identity: (value: unknown, side: Side = 'both'): Law =>\n Laws.Identity({ ...unnarrowed, value, side }),\n /** `value` is the answer whatever the other argument, from `side` (both by default). */\n absorbing: (value: unknown, side: Side = 'both'): Law =>\n Laws.Absorbing({ ...unnarrowed, value, side }),\n /** `other` undoes the operator: `op(a, other(a))` is `identity`. */\n inverse: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n other: Operator<In, Out>,\n identity: unknown,\n ): Law => Laws.Inverse({ ...unnarrowed, other, identity }),\n /** The operator distributes over `over`, from the left. */\n distributes: <In extends ReadonlyArray<Schema.Top>, Out extends Schema.Top>(\n over: Operator<In, Out>,\n ): Law => Laws.Distributes({ ...unnarrowed, over }),\n /** Moving the argument at `position` up moves the result up (or down, decreasing). */\n monotonic: (direction: 'increasing' | 'decreasing', position: number): Law =>\n Laws.Monotonic({ ...unnarrowed, direction, position }),\n /**\n * The law over the values `domain` accepts only: a law that holds of the\n * integers and not of every number, say, narrowed so it is tested where it\n * is claimed.\n */\n within: (law: Law, domain: Schema.Top): Law =>\n Object.freeze({ ...law, domain: Option.some(domain) }),\n\n $match: Laws.$match,\n\n /**\n * The operators a law, as JSON, calls besides its own (`inverse`'s and\n * `distributes`' witnesses), by name: evidence of it is of their\n * implementations too, and goes when one of them is replaced.\n */\n witnessesNamed: (law: LawDescription): ReadonlyArray<string> =>\n [law.witnesses['other'], law.witnesses['over']].filter(\n (name): name is string => typeof name === 'string',\n ),\n\n /** The law as JSON: its kind, its witnesses (operators by name) and its domain's JSON Schema. */\n describe: (law: Law): LawDescription => {\n const witnesses: Record<string, unknown> = Laws.$match(law, {\n Associative: () => ({}),\n Commutative: () => ({}),\n Idempotent: () => ({}),\n PreservesCollation: () => ({}),\n Identity: ({ value, side }) => ({ value, side }),\n Absorbing: ({ value, side }) => ({ value, side }),\n Inverse: ({ other, identity }) => ({ other: nameOf(other), identity }),\n Distributes: ({ over }) => ({ over: nameOf(over) }),\n Monotonic: ({ direction, position }) => ({ direction, position }),\n })\n return {\n kind: lawKind(law),\n witnesses,\n domain: Option.match(law.domain, {\n onNone: () => null,\n onSome: jsonSchemaOf,\n }),\n }\n },\n}\n"],"mappings":";;;;AA2DA,MAAM,aAAa,EAAE,QAAQ,OAAO,KAAiB,EAAE;;;;;;AAOvD,MAAa,iBAAiB,OAAO,OAAO;CAC1C,MAAM,OAAO;CACb,WAAW,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;CACtD,QAAQ,OAAO;AACjB,CAAC;;AAID,MAAM,UAAU,aACd,SAAS,WAAW,YAAY,IAC5B,SAAS,WAAW,KACpB,GAAG,SAAS,WAAW,GAAG,GAAG,SAAS,WAAW;AAEvD,MAAa,MAAM;CACjB,aAAa,KAAK,YAAY,UAAU;CACxC,aAAa,KAAK,YAAY,UAAU;CACxC,YAAY,KAAK,WAAW,UAAU;CACtC,oBAAoB,KAAK,mBAAmB,UAAU;;CAEtD,WAAW,OAAgB,OAAa,WACtC,KAAK,SAAS;EAAE,GAAG;EAAY;EAAO;CAAK,CAAC;;CAE9C,YAAY,OAAgB,OAAa,WACvC,KAAK,UAAU;EAAE,GAAG;EAAY;EAAO;CAAK,CAAC;;CAE/C,UACE,OACA,aACQ,KAAK,QAAQ;EAAE,GAAG;EAAY;EAAO;CAAS,CAAC;;CAEzD,cACE,SACQ,KAAK,YAAY;EAAE,GAAG;EAAY;CAAK,CAAC;;CAElD,YAAY,WAAwC,aAClD,KAAK,UAAU;EAAE,GAAG;EAAY;EAAW;CAAS,CAAC;;;;;;CAMvD,SAAS,KAAU,WACjB,OAAO,OAAO;EAAE,GAAG;EAAK,QAAQ,OAAO,KAAK,MAAM;CAAE,CAAC;CAEvD,QAAQ,KAAK;;;;;;CAOb,iBAAiB,QACf,CAAC,IAAI,UAAU,UAAU,IAAI,UAAU,OAAO,CAAC,CAAC,QAC7C,SAAyB,OAAO,SAAS,QAC5C;;CAGF,WAAW,QAA6B;EACtC,MAAM,YAAqC,KAAK,OAAO,KAAK;GAC1D,oBAAoB,CAAC;GACrB,oBAAoB,CAAC;GACrB,mBAAmB,CAAC;GACpB,2BAA2B,CAAC;GAC5B,WAAW,EAAE,OAAO,YAAY;IAAE;IAAO;GAAK;GAC9C,YAAY,EAAE,OAAO,YAAY;IAAE;IAAO;GAAK;GAC/C,UAAU,EAAE,OAAO,gBAAgB;IAAE,OAAO,OAAO,KAAK;IAAG;GAAS;GACpE,cAAc,EAAE,YAAY,EAAE,MAAM,OAAO,IAAI,EAAE;GACjD,YAAY,EAAE,WAAW,gBAAgB;IAAE;IAAW;GAAS;EACjE,CAAC;EACD,OAAO;GACL,MAAM,QAAQ,GAAG;GACjB;GACA,QAAQ,OAAO,MAAM,IAAI,QAAQ;IAC/B,cAAc;IACd,QAAQ;GACV,CAAC;EACH;CACF;AACF"}
@@ -0,0 +1,42 @@
1
+ import { Data } from "effect";
2
+ import { Law } from "./law.js";
3
+ export declare const Laws: Data.TaggedEnum.Constructor<{
4
+ readonly _tag: "Absorbing";
5
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
6
+ readonly value: unknown;
7
+ readonly side: import("./law.js").Side;
8
+ } | {
9
+ readonly _tag: "Associative";
10
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
11
+ } | {
12
+ readonly _tag: "Commutative";
13
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
14
+ } | {
15
+ readonly _tag: "Distributes";
16
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
17
+ readonly over: import("./expr.js").Operator<readonly import("effect/Schema").Top[], import("effect/Schema").Top>;
18
+ } | {
19
+ readonly _tag: "Idempotent";
20
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
21
+ } | {
22
+ readonly _tag: "Identity";
23
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
24
+ readonly value: unknown;
25
+ readonly side: import("./law.js").Side;
26
+ } | {
27
+ readonly _tag: "Inverse";
28
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
29
+ readonly other: import("./expr.js").Operator<readonly import("effect/Schema").Top[], import("effect/Schema").Top>;
30
+ readonly identity: unknown;
31
+ } | {
32
+ readonly _tag: "Monotonic";
33
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
34
+ readonly direction: 'increasing' | 'decreasing';
35
+ readonly position: number;
36
+ } | {
37
+ readonly _tag: "PreservesCollation";
38
+ readonly domain: import("effect/Option").Option<import("effect/Schema").Top>;
39
+ }>;
40
+ /** The law's kind as a name: `Associative` is `associative`. */
41
+ export declare const lawKind: (law: Law) => string;
42
+ //# sourceMappingURL=lawCore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lawCore.d.ts","names":[],"sources":["../src/lawCore.ts"],"mappings":";;qBAOa,MAAI,KAAA,WAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAGJ,UAAO,KAAS"}
@@ -0,0 +1,12 @@
1
+ import { Data } from "effect";
2
+ // src/lawCore.ts
3
+ /**
4
+ * What evaluating a body needs of a law: its variants and its kind. Apart from
5
+ * `Law.describe` so a client that never describes one keeps no JSON Schema.
6
+ */
7
+ const Laws = Data.taggedEnum();
8
+ /** The law's kind as a name: `Associative` is `associative`. */
9
+ const lawKind = (law) => law._tag.charAt(0).toLowerCase() + law._tag.slice(1);
10
+ export { Laws, lawKind };
11
+
12
+ //# sourceMappingURL=lawCore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lawCore.js","names":[],"sources":["../src/lawCore.ts"],"sourcesContent":["/**\n * What evaluating a body needs of a law: its variants and its kind. Apart from\n * `Law.describe` so a client that never describes one keeps no JSON Schema.\n */\nimport { Data } from 'effect'\nimport type { Law } from './law.js'\n\nexport const Laws = Data.taggedEnum<Law>()\n\n/** The law's kind as a name: `Associative` is `associative`. */\nexport const lawKind = (law: Law): string => law._tag.charAt(0).toLowerCase() + law._tag.slice(1)\n"],"mappings":";;;;;;AAOA,MAAa,OAAO,KAAK,WAAgB;;AAGzC,MAAa,WAAW,QAAqB,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,IAAI,KAAK,MAAM,CAAC"}