foldkit-entity 0.9.0 → 0.11.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.
@@ -1,21 +1,5 @@
1
1
  import { Array as Array$1, Match, Option, Pipeable, Schema, SchemaAST } from "effect";
2
2
  import { Metadata } from "foldkit-metadata";
3
- //#region src/shape.ts
4
- const isNullish = (ast) => SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast);
5
- const isText = (ast) => SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal === "string" || SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText);
6
- /** What a schema's AST holds, read through Effect's own guards. */
7
- const SchemaShape = {
8
- /** True for the `null` and `undefined` members that make a schema optional. */
9
- isNullish,
10
- /**
11
- * The members of a schema with `null` and `undefined` set aside, so optional
12
- * text is still text; a schema that is not a union is its one member.
13
- */
14
- present: (ast) => SchemaAST.isUnion(ast) ? ast.types.filter((member) => !isNullish(member)) : [ast],
15
- /** True when every value the schema admits is a string. */
16
- isText
17
- };
18
- //#endregion
19
3
  //#region src/collation.ts
20
4
  /**
21
5
  * How text compares when a query orders by it, declared rather than left to
@@ -109,7 +93,7 @@ const isPredicate = (value) => predicateTags.has(tagOf(value));
109
93
  const toOperand = (value) => {
110
94
  const tag = tagOf(value);
111
95
  if (tag === "Field") return fieldExpr(value);
112
- if (tag === "Literal" || tag === "Input" || predicateTags.has(tag)) return value;
96
+ if (tag === "Literal" || tag === "Input" || tag === "Next" || predicateTags.has(tag)) return value;
113
97
  return literal(value);
114
98
  };
115
99
  /** As `toOperand`, where only a scalar makes sense: `is null` of a predicate is not a question. */
@@ -144,6 +128,7 @@ const literalKind = (value) => {
144
128
  /** How a side orders, read from its encoded form. */
145
129
  const sideKind = (side) => Match.value(side).pipe(Match.tagsExhaustive({
146
130
  Field: (field) => orderKindOf(Schema.toEncoded(field.schema).ast),
131
+ Next: ({ field }) => orderKindOf(Schema.toEncoded(field.schema).ast),
147
132
  Input: (input) => orderKindOf(Schema.toEncoded(input.schema).ast),
148
133
  Literal: ({ value }) => literalKind(value)
149
134
  }));
@@ -159,7 +144,7 @@ const collationFor = (step, left, right, given) => {
159
144
  const kinds = new Set([sideKind(left), sideKind(right)].filter((kind) => kind !== "null"));
160
145
  if (kinds.has("none") || kinds.size > 1) throw new Error(`[foldkit-entity] Expr.${step}: only numbers with numbers, or text with text, order alike in every interpreter, as stored`);
161
146
  if (!kinds.has("text")) return Option.none();
162
- const fields = [left, right].flatMap((side) => Match.value(side).pipe(Match.tag("Field", (field) => [field]), Match.orElse(() => [])));
147
+ const fields = [left, right].flatMap((side) => Match.value(side).pipe(Match.tag("Field", (field) => [field]), Match.tag("Next", (next) => [next.field]), Match.orElse(() => [])));
163
148
  const [first] = fields;
164
149
  if (first === void 0) throw new Error(`[foldkit-entity] Expr.${step}: text compared with no field, whose collation would say how it orders`);
165
150
  const named = fields.map((field) => `${field.owner.name}.${field.key}`).join(" and ");
@@ -223,10 +208,19 @@ const Expr = {
223
208
  key,
224
209
  schema
225
210
  }),
211
+ /**
212
+ * A field as the row a write would leave holds it: what `Entity.invariant`'s
213
+ * builder hands out as `after`.
214
+ */
215
+ next: (field) => node({
216
+ _tag: "Next",
217
+ field: fieldExpr(field)
218
+ }),
226
219
  /** One field of one Entity, as a scalar. */
227
220
  field: (field) => fieldExpr(field),
228
221
  /**
229
- * Two scalars are the same value. A field or a plain value on either side is
222
+ * Two scalars are the same value: a field (or an expression) on the left,
223
+ * and the value on the right, typed from it. Fields and plain values are
230
224
  * coerced, so the common form reads as it means:
231
225
  *
232
226
  * ```ts
@@ -362,7 +356,52 @@ const Expr = {
362
356
  */
363
357
  whenGiven: (input, build) => Expr.or(Expr.isNull(input), build(input)),
364
358
  /** An expression as readable text; see `showExpr` for what it is and is not. */
365
- show: (node) => showExpr(node)
359
+ show: (node) => showExpr(node),
360
+ /**
361
+ * The predicate with each field after a write (`Next`) that `values` names,
362
+ * by key, read as that value: how an invariant is judged where the
363
+ * write's new values are known. A field it does not name stays `Next`, for
364
+ * the interpreter to read as the row after holds it.
365
+ */
366
+ substituteNext: (predicate, values) => substituted(predicate, (operand) => Match.value(operand).pipe(Match.tag("Next", ({ field }) => Object.hasOwn(values, field.key) ? literal(values[field.key]) : operand), Match.orElse(() => operand)))
367
+ };
368
+ const substitutedSide = (side, rewrite) => isPredicate(side) ? substituted(side, rewrite) : rewrite(side);
369
+ const substituted = (predicate, rewrite) => {
370
+ switch (predicate._tag) {
371
+ case "Eq": return node({
372
+ ...predicate,
373
+ left: substitutedSide(predicate.left, rewrite),
374
+ right: substitutedSide(predicate.right, rewrite)
375
+ });
376
+ case "Null": return node({
377
+ ...predicate,
378
+ operand: rewrite(predicate.operand)
379
+ });
380
+ case "Contains": return node({
381
+ ...predicate,
382
+ value: rewrite(predicate.value),
383
+ search: substitutedSide(predicate.search, rewrite)
384
+ });
385
+ case "In": return node({
386
+ ...predicate,
387
+ value: rewrite(predicate.value),
388
+ among: rewrite(predicate.among)
389
+ });
390
+ case "And":
391
+ case "Or": return node({
392
+ ...predicate,
393
+ operands: Array$1.map(predicate.operands, (operand) => substituted(operand, rewrite))
394
+ });
395
+ case "Not": return node({
396
+ ...predicate,
397
+ operand: substituted(predicate.operand, rewrite)
398
+ });
399
+ case "Compare": return node({
400
+ ...predicate,
401
+ left: rewrite(predicate.left),
402
+ right: rewrite(predicate.right)
403
+ });
404
+ }
366
405
  };
367
406
  /** A term, its nulls placed by `options` or by the direction's default. */
368
407
  const term = (direction, expr, options = {}) => node({
@@ -467,6 +506,22 @@ const walk = (expr, found) => {
467
506
  case "Input":
468
507
  found.inputs.add(expr.key);
469
508
  return;
509
+ case "Next": {
510
+ found.operations.add("next");
511
+ const { field } = expr;
512
+ const byKey = found.next.get(field.owner.token) ?? /* @__PURE__ */ new Map();
513
+ found.next.set(field.owner.token, byKey);
514
+ if (!byKey.has(field.key)) {
515
+ const read = {
516
+ entity: field.owner.name,
517
+ key: field.key,
518
+ owner: field.owner
519
+ };
520
+ byKey.set(field.key, read);
521
+ found.nextOrder.push(read);
522
+ }
523
+ return;
524
+ }
470
525
  case "Eq":
471
526
  found.operations.add("eq");
472
527
  walk(expr.left, found);
@@ -523,11 +578,14 @@ const dependenciesOf = (...nodes) => {
523
578
  fields: /* @__PURE__ */ new Map(),
524
579
  order: [],
525
580
  inputs: /* @__PURE__ */ new Set(),
581
+ next: /* @__PURE__ */ new Map(),
582
+ nextOrder: [],
526
583
  operations: /* @__PURE__ */ new Set()
527
584
  };
528
585
  for (const term of nodes) walk(term, found);
529
586
  return {
530
587
  fields: found.order,
588
+ next: found.nextOrder,
531
589
  inputs: [...found.inputs],
532
590
  operations: [...found.operations]
533
591
  };
@@ -540,6 +598,9 @@ const fieldsIn = function* (expr, seen) {
540
598
  case "Field":
541
599
  yield expr;
542
600
  return;
601
+ case "Next":
602
+ yield expr.field;
603
+ return;
543
604
  case "Literal":
544
605
  case "Input": return;
545
606
  case "Eq":
@@ -598,7 +659,8 @@ const childrenOf = (expr) => {
598
659
  switch (expr._tag) {
599
660
  case "Literal":
600
661
  case "Field":
601
- case "Input": return [];
662
+ case "Input":
663
+ case "Next": return [];
602
664
  case "Eq": return [expr.left, expr.right];
603
665
  case "Null": return [expr.operand];
604
666
  case "Contains": return [expr.value, expr.search];
@@ -762,6 +824,7 @@ const showExpr = (node) => {
762
824
  case "Literal": return JSON.stringify(node.value) ?? String(node.value);
763
825
  case "Field": return `${node.owner.name}.${node.key}`;
764
826
  case "Input": return `$${node.key}`;
827
+ case "Next": return `next ${node.field.owner.name}.${node.field.key}`;
765
828
  case "Eq": return `${showOperand(node.left)} = ${showOperand(node.right)}`;
766
829
  case "Null": return `${showOperand(node.operand)} is ${node.present ? "not null" : "null"}`;
767
830
  case "Contains": return `contains(${showOperand(node.value)}, ${showOperand(node.search)})`;
@@ -785,45 +848,6 @@ const showConnected = (node) => Match.value(node).pipe(Match.tags({
785
848
  }), Match.orElse(() => showExpr(node)));
786
849
  const showOperand = (node) => isPredicate(node) ? `(${showExpr(node)})` : showExpr(node);
787
850
  //#endregion
788
- //#region src/readFilter.ts
789
- /**
790
- * The members a server filters an Entity's rows by under a rule the client
791
- * does not run, such as an authorization rule. A client that places rows in
792
- * a list judges membership by the list's body; a change to one of these
793
- * members can move a row into or out of what the server lists, which only
794
- * the server can say. Declared by whoever owns the rule (`foldkit-guard`
795
- * attaches it), read by whoever places (`foldkit-remote`).
796
- */
797
- const key = Metadata.key("foldkit-entity/read-filter", {
798
- merge: (lists) => [[...new Set(lists.flat())]],
799
- summarize: (members) => members.join(", ")
800
- });
801
- const ReadFilter = {
802
- /** Entity metadata: the rows the server lists depend on these members. */
803
- of: (members) => key.of(members),
804
- /** The members an Entity's metadata names, every attachment's together. */
805
- members: (metadata) => key.get(metadata)[0] ?? []
806
- };
807
- //#endregion
808
- //#region src/words.ts
809
- const text = (value) => typeof value === "string" ? Option.some(value) : Option.none();
810
- const Words = {
811
- /**
812
- * A schema's words, as a label and its help text. Under Effect 4 a checked
813
- * schema resolves to its last check's annotations, which say what the check
814
- * expects and carry no `title`, so a title given before the check is read from
815
- * the schema's own annotations. Read words through this, never through
816
- * `Schema.resolveAnnotations` directly.
817
- */
818
- of: (schema) => {
819
- const resolved = Schema.resolveAnnotations(schema) ?? {};
820
- const own = schema.ast.annotations ?? {};
821
- return {
822
- title: Option.orElse(text(resolved.title), () => text(own["title"])),
823
- description: Option.orElse(text(resolved.description), () => text(own["description"]))
824
- };
825
- } };
826
- //#endregion
827
851
  //#region src/evaluate.ts
828
852
  /**
829
853
  * The reference interpreter: a query body run over rows already in memory.
@@ -855,11 +879,12 @@ var QueryEvaluateError = class extends Error {
855
879
  this.name = "QueryEvaluateError";
856
880
  }
857
881
  };
858
- const valueOf = (node, row, input) => {
882
+ const valueOf = (node, scope) => {
859
883
  switch (node._tag) {
860
- case "Field": return row[node.key];
884
+ case "Field": return scope.row[node.key];
885
+ case "Next": return scope.next[node.field.key];
861
886
  case "Literal": return node.value;
862
- case "Input": return input[node.key];
887
+ case "Input": return scope.input[node.key];
863
888
  }
864
889
  };
865
890
  const isNull = (value) => value === null || value === void 0;
@@ -876,57 +901,57 @@ const NUL = String.fromCharCode(0);
876
901
  */
877
902
  const holdsNul = (value) => typeof value === "string" && value.includes(NUL);
878
903
  /** A predicate used as a value is its own truth; anything else is its value. */
879
- const sideOf = (node, row, input) => isPredicate(node) ? truthValue(holds(node, row, input)) : valueOf(node, row, input);
904
+ const sideOf = (node, scope) => isPredicate(node) ? truthValue(holds(node, scope)) : valueOf(node, scope);
880
905
  /**
881
906
  * A predicate compared as a value. SQL's unknown is null there too, so an
882
907
  * unknown compared to anything stays unknown rather than becoming false.
883
908
  */
884
909
  const truthValue = (truth) => truth === "unknown" ? null : truth;
885
- const holds = (node, row, input) => {
910
+ const holds = (node, scope) => {
886
911
  switch (node._tag) {
887
912
  case "Eq": {
888
- const left = sideOf(node.left, row, input);
889
- const right = sideOf(node.right, row, input);
913
+ const left = sideOf(node.left, scope);
914
+ const right = sideOf(node.right, scope);
890
915
  if (isNull(left) || isNull(right)) return "unknown";
891
916
  if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError("an equality was given text holding a NUL character, which SQL text cannot hold portably");
892
917
  return left === right;
893
918
  }
894
- case "Null": return isNull(valueOf(node.operand, row, input)) !== node.present;
919
+ case "Null": return isNull(valueOf(node.operand, scope)) !== node.present;
895
920
  case "Contains": {
896
- const value = valueOf(node.value, row, input);
897
- const search = sideOf(node.search, row, input);
921
+ const value = valueOf(node.value, scope);
922
+ const search = sideOf(node.search, scope);
898
923
  if (isNull(value) || isNull(search)) return "unknown";
899
924
  if (typeof value !== "string" || typeof search !== "string") throw new QueryEvaluateError("a containment test was given something that is not text");
900
925
  if (holdsNul(value) || holdsNul(search)) throw new QueryEvaluateError("a containment test was given text holding a NUL character, which SQL text cannot hold portably");
901
926
  return foldAscii(value).includes(foldAscii(search));
902
927
  }
903
928
  case "In": {
904
- const among = valueOf(node.among, row, input);
929
+ const among = valueOf(node.among, scope);
905
930
  if (!Array.isArray(among)) throw new QueryEvaluateError("a membership test was given a list that is not a list");
906
931
  if (among.length === 0) return false;
907
- const value = valueOf(node.value, row, input);
932
+ const value = valueOf(node.value, scope);
908
933
  if (holdsNul(value) || among.some(holdsNul)) throw new QueryEvaluateError("a membership test was given text holding a NUL character, which SQL text cannot hold portably");
909
934
  if (isNull(value)) return "unknown";
910
935
  if (among.some((each) => each === value)) return true;
911
936
  return among.some(isNull) ? "unknown" : false;
912
937
  }
913
938
  case "And": {
914
- const truths = node.operands.map((operand) => holds(operand, row, input));
939
+ const truths = node.operands.map((operand) => holds(operand, scope));
915
940
  if (truths.includes(false)) return false;
916
941
  return truths.includes("unknown") ? "unknown" : true;
917
942
  }
918
943
  case "Or": {
919
- const truths = node.operands.map((operand) => holds(operand, row, input));
944
+ const truths = node.operands.map((operand) => holds(operand, scope));
920
945
  if (truths.includes(true)) return true;
921
946
  return truths.includes("unknown") ? "unknown" : false;
922
947
  }
923
948
  case "Not": {
924
- const truth = holds(node.operand, row, input);
949
+ const truth = holds(node.operand, scope);
925
950
  return truth === "unknown" ? "unknown" : !truth;
926
951
  }
927
952
  case "Compare": {
928
- const left = valueOf(node.left, row, input);
929
- const right = valueOf(node.right, row, input);
953
+ const left = valueOf(node.left, scope);
954
+ const right = valueOf(node.right, scope);
930
955
  if (isNull(left) || isNull(right)) return "unknown";
931
956
  if (holdsNul(left) || holdsNul(right)) throw new QueryEvaluateError("a comparison was given text holding a NUL character, which SQL text cannot hold portably");
932
957
  const kind = typeof left;
@@ -947,13 +972,28 @@ const readsAField = /* @__PURE__ */ new WeakMap();
947
972
  const decided = (node, input) => {
948
973
  let reads = readsAField.get(node);
949
974
  if (reads === void 0) {
950
- reads = dependenciesOf(node).fields.length > 0;
975
+ const read = dependenciesOf(node);
976
+ reads = read.fields.length + read.next.length > 0;
951
977
  readsAField.set(node, reads);
952
978
  }
953
- return reads ? Option.none() : Option.some(holds(node, {}, input));
979
+ return reads ? Option.none() : Option.some(holds(node, {
980
+ row: {},
981
+ input,
982
+ next: {}
983
+ }));
954
984
  };
985
+ /** A predicate's truth over one row (and, for an invariant, the row after a write): SQL's three values. */
986
+ const truthOver = (node, row, input = {}, next = {}) => holds(node, {
987
+ row,
988
+ input,
989
+ next
990
+ });
955
991
  /** Every predicate must hold: the list is the conjunction, as it is in a `Query`. */
956
- const matches = (body, row, input) => body.where.every((node) => holds(node, row, input) === true);
992
+ const matches = (body, row, input) => body.where.every((node) => holds(node, {
993
+ row,
994
+ input,
995
+ next: {}
996
+ }) === true);
957
997
  /** The kinds of value this interpreter orders by; every key of one term must share one. */
958
998
  const comparable = /* @__PURE__ */ new Set([
959
999
  "string",
@@ -1076,6 +1116,190 @@ const evaluate = (body, input, rows) => {
1076
1116
  return ordered(rows.filter((row) => matches(body, row, input)), Query.orderFor(body, input), body.entity.name);
1077
1117
  };
1078
1118
  //#endregion
1119
+ //#region src/invariant.ts
1120
+ /**
1121
+ * Invariants: what every stored row of an Entity must hold, and what every
1122
+ * change of one must, declared once on the Entity through its metadata and read
1123
+ * from there by each interpreter: the reference judge here, a Schema check, a
1124
+ * form, a server's writer.
1125
+ *
1126
+ * One is built over the row before a write (`before`, each field as `Expr.field`) and
1127
+ * the row after it (`after`, each field as `Expr.next`). What it reads decides
1128
+ * when it is judged:
1129
+ *
1130
+ * ```text
1131
+ * reads `after` only -> a state invariant: every create and update, a CHECK constraint
1132
+ * reads `before` too -> a transition invariant: every update, which has a row before
1133
+ * ```
1134
+ *
1135
+ * It reads no input and no principal. Who may write is a guard's; whether a
1136
+ * write applies now is its `when`'s.
1137
+ */
1138
+ const Invariants = Metadata.key("foldkit-entity/invariants", {
1139
+ merge: (values) => [...new Set(values)],
1140
+ summarize: (invariant) => invariant.id
1141
+ });
1142
+ /** Whether an invariant reads the row before, and so is judged only where there is one. */
1143
+ const readsBefore = (held) => held.before.length > 0;
1144
+ const fail$2 = (entity, message) => {
1145
+ throw new Error(`[foldkit-entity] Entity.invariant on ${entity.name}: ${message}`);
1146
+ };
1147
+ const invariant = (id, build, options) => Object.assign((entity) => {
1148
+ if (id.length === 0) fail$2(entity, "an invariant needs an id");
1149
+ if (invariantsOf(entity).some((held) => held.id === id)) fail$2(entity, `"${id}" is declared twice`);
1150
+ const fields = entity.fields;
1151
+ const after = Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, Expr.next(field)]));
1152
+ const predicate = build({
1153
+ before: Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, Expr.field(field)])),
1154
+ after
1155
+ });
1156
+ const body = Query.from(entity).pipe(Query.where(predicate));
1157
+ const dependencies = Query.dependencies(body);
1158
+ if (dependencies.inputs.length > 0) fail$2(entity, `"${id}" reads the input ${dependencies.inputs.join(", ")}; it judges stored rows`);
1159
+ const beforeReads = dependencies.predicate.map((field) => field.key);
1160
+ const afterReads = dependencies.next.map((field) => field.key);
1161
+ if (afterReads.length === 0) fail$2(entity, `"${id}" reads no field of \`after\`; what a write may start from is its \`when\``);
1162
+ const path = options.path ?? [.../* @__PURE__ */ new Set([...afterReads, ...beforeReads])];
1163
+ for (const key of path) if (!Object.hasOwn(fields, key)) fail$2(entity, `"${id}"'s path names "${key}", not a field`);
1164
+ return entity.pipe(Entity.annotate(Invariants.of(Object.freeze({
1165
+ id,
1166
+ predicate,
1167
+ message: options.message,
1168
+ path: Object.freeze([...path]),
1169
+ before: Object.freeze(beforeReads),
1170
+ after: Object.freeze(afterReads)
1171
+ }))));
1172
+ }, { id });
1173
+ const invariantsOf = (entity) => Invariants.get(entity.metadata);
1174
+ /** `judge` with the invariants given, as a binding that keeps them holds them. */
1175
+ const judgeAgainst = (invariants, change) => {
1176
+ const missing = /* @__PURE__ */ new Set();
1177
+ const failures = [];
1178
+ const { after, before } = change;
1179
+ for (const held of invariants) {
1180
+ if (readsBefore(held) && before === void 0) continue;
1181
+ const absent = [...held.after.filter((key) => !Object.hasOwn(after, key)), ...held.before.filter((key) => !Object.hasOwn(before ?? {}, key))];
1182
+ if (absent.length > 0) absent.forEach((key) => missing.add(key));
1183
+ else if (truthOver(held.predicate, before ?? {}, {}, after) !== true) failures.push(held);
1184
+ }
1185
+ if (failures.length > 0) return {
1186
+ _tag: "Invalid",
1187
+ failures
1188
+ };
1189
+ if (missing.size > 0) return {
1190
+ _tag: "Undecided",
1191
+ fields: [...missing]
1192
+ };
1193
+ return { _tag: "Valid" };
1194
+ };
1195
+ /**
1196
+ * A row, or a change, under every invariant (each row as the store holds it,
1197
+ * encoded): valid only when each is true. SQL's unknown, from a null, fails
1198
+ * one, as a `WHERE` drops the row; a field a row does not have leaves it
1199
+ * undecided, never valid. Without `before` (a create), transition invariants
1200
+ * are not judged.
1201
+ */
1202
+ const judge = (entity, change) => judgeAgainst(invariantsOf(entity), change);
1203
+ /**
1204
+ * The row an input's value describes, judged under its Entity's state
1205
+ * invariants: each key mapped to a field, encoded as the store holds it. An
1206
+ * invariant over a field the input does not set (an `Option` holding nothing, a
1207
+ * key left out) is undecided, so a partial input is never called valid on its
1208
+ * account. It has no row before, so it judges no transition.
1209
+ */
1210
+ const judgeInput = (input, value) => {
1211
+ const invariants = invariantsOf(input.entity);
1212
+ if (invariants.length === 0) return { _tag: "Valid" };
1213
+ const members = input.members;
1214
+ const row = {};
1215
+ for (const [key, member] of Object.entries(members)) {
1216
+ if (member._tag !== "Field" || !Object.hasOwn(value, key)) continue;
1217
+ const encode = Schema.encodeUnknownOption(member.schema);
1218
+ const given = value[key];
1219
+ const held = Option.isOption(given) ? given : Option.fromUndefinedOr(given);
1220
+ const stored = Option.orElse(encode(given), () => Option.flatMap(held, encode));
1221
+ Option.map(Option.flatMap(held, () => stored), (encoded) => {
1222
+ row[member.key] = encoded;
1223
+ });
1224
+ }
1225
+ return judgeAgainst(invariants, { after: row });
1226
+ };
1227
+ /**
1228
+ * The Entity's state invariants as an Effect Schema check over its row type:
1229
+ * each failure at its path, with its message. The value is encoded first,
1230
+ * field by field, so it is judged as the store would hold it.
1231
+ */
1232
+ const check = (entity) => Schema.makeFilter((value) => {
1233
+ const fields = entity.fields;
1234
+ const decoded = value;
1235
+ const row = {};
1236
+ for (const [key, field] of Object.entries(fields)) {
1237
+ if (!Object.hasOwn(decoded, key)) continue;
1238
+ row[key] = Schema.encodeUnknownSync(field.schema)(decoded[key]);
1239
+ }
1240
+ const judged = judge(entity, { after: row });
1241
+ if (judged._tag !== "Invalid") return void 0;
1242
+ return judged.failures.flatMap((failure) => failure.path.length === 0 ? [failure.message] : failure.path.map((key) => ({
1243
+ path: [key],
1244
+ issue: failure.message
1245
+ })));
1246
+ });
1247
+ //#endregion
1248
+ //#region src/shape.ts
1249
+ const isNullish = (ast) => SchemaAST.isNull(ast) || SchemaAST.isUndefined(ast);
1250
+ const isText = (ast) => SchemaAST.isString(ast) || SchemaAST.isTemplateLiteral(ast) || SchemaAST.isLiteral(ast) && typeof ast.literal === "string" || SchemaAST.isUnion(ast) && ast.types.length > 0 && ast.types.every(isText);
1251
+ /** What a schema's AST holds, read through Effect's own guards. */
1252
+ const SchemaShape = {
1253
+ /** True for the `null` and `undefined` members that make a schema optional. */
1254
+ isNullish,
1255
+ /**
1256
+ * The members of a schema with `null` and `undefined` set aside, so optional
1257
+ * text is still text; a schema that is not a union is its one member.
1258
+ */
1259
+ present: (ast) => SchemaAST.isUnion(ast) ? ast.types.filter((member) => !isNullish(member)) : [ast],
1260
+ /** True when every value the schema admits is a string. */
1261
+ isText
1262
+ };
1263
+ //#endregion
1264
+ //#region src/readFilter.ts
1265
+ /**
1266
+ * The members a server filters an Entity's rows by under a rule the client
1267
+ * does not run, such as an authorization rule. A client that places rows in
1268
+ * a list judges membership by the list's body; a change to one of these
1269
+ * members can move a row into or out of what the server lists, which only
1270
+ * the server can say. Declared by whoever owns the rule (`foldkit-guard`
1271
+ * attaches it), read by whoever places (`foldkit-remote`).
1272
+ */
1273
+ const key = Metadata.key("foldkit-entity/read-filter", {
1274
+ merge: (lists) => [[...new Set(lists.flat())]],
1275
+ summarize: (members) => members.join(", ")
1276
+ });
1277
+ const ReadFilter = {
1278
+ /** Entity metadata: the rows the server lists depend on these members. */
1279
+ of: (members) => key.of(members),
1280
+ /** The members an Entity's metadata names, every attachment's together. */
1281
+ members: (metadata) => key.get(metadata)[0] ?? []
1282
+ };
1283
+ //#endregion
1284
+ //#region src/words.ts
1285
+ const text = (value) => typeof value === "string" ? Option.some(value) : Option.none();
1286
+ const Words = {
1287
+ /**
1288
+ * A schema's words, as a label and its help text. Under Effect 4 a checked
1289
+ * schema resolves to its last check's annotations, which say what the check
1290
+ * expects and carry no `title`, so a title given before the check is read from
1291
+ * the schema's own annotations. Read words through this, never through
1292
+ * `Schema.resolveAnnotations` directly.
1293
+ */
1294
+ of: (schema) => {
1295
+ const resolved = Schema.resolveAnnotations(schema) ?? {};
1296
+ const own = schema.ast.annotations ?? {};
1297
+ return {
1298
+ title: Option.orElse(text(resolved.title), () => text(own["title"])),
1299
+ description: Option.orElse(text(resolved.description), () => text(own["description"]))
1300
+ };
1301
+ } };
1302
+ //#endregion
1079
1303
  //#region src/write.ts
1080
1304
  /**
1081
1305
  * A write as a value: what an operation changes, declared over the input it
@@ -1092,6 +1316,13 @@ const evaluate = (body, input, rows) => {
1092
1316
  * It is authority someone declared, never something derived from an Entity: an
1093
1317
  * Entity having a field does not mean anyone may set it.
1094
1318
  */
1319
+ const update = (input, options) => settingSomething(declared("Update", input, options));
1320
+ const remove = (input, options) => {
1321
+ const write = declared("Delete", input, options);
1322
+ const named = [...write.sets, ...write.links][0];
1323
+ if (named !== void 0) fail$1(input, `a delete sets nothing, but "${named.key}" is mapped`);
1324
+ return write;
1325
+ };
1095
1326
  const fail$1 = (input, message) => {
1096
1327
  throw new Error(`[foldkit-entity] Write of ${input.entity.name}: ${message}`);
1097
1328
  };
@@ -1150,6 +1381,15 @@ const declared = (kind, input, options) => {
1150
1381
  case "NestedInput": fail$1(input, `"${key}" writes a nested row; a write writes its own row only`);
1151
1382
  }
1152
1383
  }
1384
+ const when = Option.map(Option.fromUndefinedOr(options.when), (condition) => {
1385
+ const placeholders = Object.create(null);
1386
+ for (const [key, schema] of Object.entries(input.schema.fields)) placeholders[key] = Expr.input(key, schema);
1387
+ return Query.from(input.entity).pipe(Query.where(condition({ input: placeholders })));
1388
+ });
1389
+ const increments = Object.entries(options.increment ?? {}).flatMap(([fieldKey, key]) => key === void 0 ? [] : [incrementOf(input, fieldKey, key, {
1390
+ expect,
1391
+ sets
1392
+ })]);
1153
1393
  return Object.freeze({
1154
1394
  _tag: kind,
1155
1395
  input,
@@ -1158,12 +1398,38 @@ const declared = (kind, input, options) => {
1158
1398
  field: id
1159
1399
  }),
1160
1400
  expect,
1401
+ when,
1161
1402
  sets: Object.freeze(sets),
1403
+ increments: Object.freeze(increments),
1162
1404
  links: Object.freeze(links)
1163
1405
  });
1164
1406
  };
1407
+ /** Whether a value's stored form is a plain number. */
1408
+ const storedAsNumber = (schema) => SchemaAST.isNumber(Schema.toEncoded(schema).ast);
1409
+ /**
1410
+ * One increment, checked: a field of the Entity stored as a number, written
1411
+ * by nothing else, moved by an unmapped input key whose value is a number.
1412
+ */
1413
+ const incrementOf = (input, fieldKey, key, declared) => {
1414
+ const fields = input.entity.fields;
1415
+ const field = Object.hasOwn(fields, fieldKey) ? fields[fieldKey] : void 0;
1416
+ if (field === void 0) return fail$1(input, `increments "${fieldKey}", which is not a field`);
1417
+ if (fieldKey === "id") return fail$1(input, "increments the id");
1418
+ if (declared.expect?.field.key === fieldKey) return fail$1(input, `increments "${fieldKey}", the revision it expects`);
1419
+ if (declared.sets.some((set) => set.field.key === fieldKey)) return fail$1(input, `increments "${fieldKey}", which a key also sets`);
1420
+ if (!storedAsNumber(field.schema)) return fail$1(input, `increments "${fieldKey}", which is not stored as a number`);
1421
+ const member = membersOf(input)[key];
1422
+ if (member === void 0) return fail$1(input, `"${key}" is not a key of the input`);
1423
+ if (member._tag !== "Unmapped") return fail$1(input, `"${key}" is an amount, so it must be unmapped, not written as a member`);
1424
+ const amount = input.schema.fields[key];
1425
+ if (!storedAsNumber(amount)) return fail$1(input, `"${key}" is an amount, but not a number`);
1426
+ return Object.freeze({
1427
+ key,
1428
+ field
1429
+ });
1430
+ };
1165
1431
  /** An update or an insert that would write nothing is refused where it is declared. */
1166
- const settingSomething = (write) => write.sets.length === 0 && write.links.length === 0 ? fail$1(write.input, "it sets no field") : write;
1432
+ const settingSomething = (write) => write.sets.length === 0 && write.links.length === 0 && write.increments.length === 0 ? fail$1(write.input, "it sets no field") : write;
1167
1433
  const Write = {
1168
1434
  /**
1169
1435
  * Sets, on the row whose id is the input's `id` key, every field the input
@@ -1178,10 +1444,12 @@ const Write = {
1178
1444
  * id it holds. Refused where it is written: an `id` that is not the Entity's
1179
1445
  * `id` field, a `many` relation or a nested key (not written by an update
1180
1446
  * yet), or nothing to set.
1447
+ *
1448
+ * `when` is what the row must hold for the update to land, checked where it
1449
+ * commits (`({ input }) => Expr.eq(Post.fields.status, 'draft')`); a row it
1450
+ * does not hold of is refused as unmet.
1181
1451
  */
1182
- update: (input, options) => {
1183
- return settingSomething(declared("Update", input, options));
1184
- },
1452
+ update,
1185
1453
  /**
1186
1454
  * Inserts the row whose id is the input's `id` key, an id the client chose,
1187
1455
  * with every field and `one` relation the input maps a key to. An insert
@@ -1195,14 +1463,9 @@ const Write = {
1195
1463
  * Deletes the row whose id is the input's `id` key, only while it is still at
1196
1464
  * the revision `expect` names, when it names one. It sets nothing, so a key
1197
1465
  * mapped to a member is refused where it is written. A row already gone (a
1198
- * retry) is gone.
1466
+ * retry) is gone. `when`, as an update's, is what the row must hold.
1199
1467
  */
1200
- delete: (input, options) => {
1201
- const write = declared("Delete", input, options);
1202
- const named = [...write.sets, ...write.links][0];
1203
- if (named !== void 0) fail$1(input, `a delete sets nothing, but "${named.key}" is mapped`);
1204
- return write;
1205
- },
1468
+ delete: remove,
1206
1469
  /**
1207
1470
  * The revision this input says the row was read at, encoded, with its field:
1208
1471
  * what an interpreter writes only a row still at. None for a write that
@@ -1213,7 +1476,24 @@ const Write = {
1213
1476
  revision: encoded(field, value[key])
1214
1477
  })),
1215
1478
  /** The members any invocation may write: what a query reading none of them cannot be changed by. */
1216
- writes: (write) => [...write.sets.map((set) => set.field), ...write.links.map((link) => link.relation)],
1479
+ writes: (write) => [
1480
+ ...write.sets.map((set) => set.field),
1481
+ ...write.increments.map((increment) => increment.field),
1482
+ ...write.links.map((link) => link.relation)
1483
+ ],
1484
+ /**
1485
+ * The fields a write reads from the row it writes: those its `when` reads,
1486
+ * each it increments, and the revision it expects. What an interpreter
1487
+ * must read, and what a startup check judges it could disclose.
1488
+ */
1489
+ reads: (write) => {
1490
+ const fields = /* @__PURE__ */ new Map();
1491
+ const add = (field) => fields.set(field.key, field);
1492
+ Option.map(write.when, (body) => Query.dependencies(body).predicate.forEach((field) => add(field)));
1493
+ write.increments.forEach((increment) => add(increment.field));
1494
+ if (write.expect !== void 0) add(write.expect.field);
1495
+ return [...fields.values()];
1496
+ },
1217
1497
  /**
1218
1498
  * The row this input writes and its new values, encoded as the store holds
1219
1499
  * them: the patch a client shows before the server answers. `keys`, when
@@ -1240,11 +1520,20 @@ const Write = {
1240
1520
  id: String(encoded(target.fields.id, id))
1241
1521
  }));
1242
1522
  }
1523
+ const increments = {};
1524
+ for (const { key, field } of write.increments) {
1525
+ if (!asked(key)) continue;
1526
+ const schema = write.input.schema.fields[key];
1527
+ Option.map(given(input[key]), (held) => {
1528
+ increments[field.key] = Schema.encodeUnknownSync(schema)(held);
1529
+ });
1530
+ }
1243
1531
  return {
1244
1532
  entity: write.input.entity.name,
1245
1533
  id: String(encoded(write.id.field, input[write.id.key])),
1246
1534
  values,
1247
- links
1535
+ links,
1536
+ increments
1248
1537
  };
1249
1538
  }
1250
1539
  };
@@ -1453,6 +1742,36 @@ const Entity = {
1453
1742
  ...entity,
1454
1743
  metadata: Metadata.combine([entity.metadata, metadata])
1455
1744
  }),
1745
+ /**
1746
+ * Declares what every stored row, or every change of one, must hold:
1747
+ * `Entity.invariant('reservedWithinQuantity', ({ after }) =>
1748
+ * Expr.lte(after.reserved, after.quantity), { message })` over the row a
1749
+ * write leaves, or with `before` too over the change an update makes.
1750
+ * Refused where it is declared: an id declared twice, a predicate over another
1751
+ * Entity, one reading an input or nothing of `after` (that is a `when`), a path
1752
+ * naming no field.
1753
+ */
1754
+ invariant,
1755
+ /** The Entity's invariants, in the order they were declared. */
1756
+ invariants: invariantsOf,
1757
+ /**
1758
+ * A row (`{ after }`, a create's) or a change (`{ before, after }`, an
1759
+ * update's) under the Entity's invariants: `Valid`, `Invalid` with the ones
1760
+ * that fail (a null fails, as SQL's unknown), or `Undecided` with the fields
1761
+ * one reads that a row lacks.
1762
+ */
1763
+ judge,
1764
+ /** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */
1765
+ readsBefore,
1766
+ /** `Entity.judge` against invariants already read, such as those a database binding keeps. */
1767
+ judgeAgainst,
1768
+ /**
1769
+ * The row an `Entity.input`'s value describes, judged: what a form can say
1770
+ * before the server does. Undecided for an invariant over a field it leaves unset.
1771
+ */
1772
+ judgeInput,
1773
+ /** The state invariants as a Schema check over the row type, each failure at its path. */
1774
+ check,
1456
1775
  /** Attaches an interpreter's metadata to members, by key. */
1457
1776
  annotateMembers: (metadata) => (entity) => {
1458
1777
  const given = metadata;
@@ -1588,6 +1907,6 @@ const Relation = {
1588
1907
  };
1589
1908
  const Derived = { make: (schema) => ({ schema }) };
1590
1909
  //#endregion
1591
- export { SchemaShape as C, Collation as S, Order as _, SelectionPageTypeId as a, isPredicate as b, QueryEvaluateError as c, decided as d, evaluate as f, Expr as g, ReadFilter as h, Relation as i, assertSupported as l, Words as m, Entity as n, SelectionTypeId as o, supported as p, EntityTypeId as r, Write as s, Derived as t, compareRows as u, Query as v, maxQueryNodes as x, dependenciesOf as y };
1910
+ export { maxQueryNodes as C, isPredicate as S, truthOver as _, SelectionPageTypeId as a, Query as b, Words as c, QueryEvaluateError as d, assertSupported as f, supported as g, evaluate as h, Relation as i, ReadFilter as l, decided as m, Entity as n, SelectionTypeId as o, compareRows as p, EntityTypeId as r, Write as s, Derived as t, SchemaShape as u, Expr as v, Collation as w, dependenciesOf as x, Order as y };
1592
1911
 
1593
- //# sourceMappingURL=src-5avJ3IkP.mjs.map
1912
+ //# sourceMappingURL=src-DwKdHZDu.mjs.map