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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uncollated.js","names":[],"sources":["../src/uncollated.ts"],"sourcesContent":["import { Match, Option, Schema, SchemaAST } from 'effect'\nimport type { OrderTerm } from './expr.js'\n\n/**\n * Whether values encoded by `ast` order the same everywhere: numbers and\n * booleans, never text. A null among them does too: where it goes is said on\n * every order term.\n */\nconst ordersIntrinsically = (ast: SchemaAST.AST): boolean =>\n SchemaAST.isNumber(ast) ||\n SchemaAST.isBoolean(ast) ||\n (SchemaAST.isLiteral(ast) && typeof ast.literal !== 'string') ||\n (SchemaAST.isUnion(ast) &&\n ast.types.every(member => SchemaAST.isNull(member) || ordersIntrinsically(member)))\n\n/**\n * Why an order term cannot be answered the same by every reader for want of a\n * collation: a field of text that declares none. SQLite compares bytes,\n * Postgres follows its database's locale and JavaScript compares UTF-16 units,\n * so `Query.placement` and `evaluate` both refuse it, for this reason.\n */\nexport const uncollatedText = (orderTerm: OrderTerm): Option.Option<string> =>\n Match.value(orderTerm.expr).pipe(\n Match.tag('Field', field =>\n Option.isNone(orderTerm.collation) && !ordersIntrinsically(Schema.toEncoded(field.schema).ast)\n ? Option.some(\n `it orders by ${field.owner.name}.${field.key}, text with no declared collation`,\n )\n : Option.none<string>(),\n ),\n Match.orElse(() => Option.none<string>()),\n )\n"],"mappings":";;;;;;;AAQA,MAAM,uBAAuB,QAC3B,UAAU,SAAS,GAAG,KACtB,UAAU,UAAU,GAAG,KACtB,UAAU,UAAU,GAAG,KAAK,OAAO,IAAI,YAAY,YACnD,UAAU,QAAQ,GAAG,KACpB,IAAI,MAAM,OAAM,WAAU,UAAU,OAAO,MAAM,KAAK,oBAAoB,MAAM,CAAC;;;;;;;AAQrF,MAAa,kBAAkB,cAC7B,MAAM,MAAM,UAAU,IAAI,CAAC,CAAC,KAC1B,MAAM,IAAI,UAAS,UACjB,OAAO,OAAO,UAAU,SAAS,KAAK,CAAC,oBAAoB,OAAO,UAAU,MAAM,MAAM,CAAC,CAAC,GAAG,IACzF,OAAO,KACL,gBAAgB,MAAM,MAAM,KAAK,GAAG,MAAM,IAAI,kCAChD,IACA,OAAO,KAAa,CAC1B,GACA,MAAM,aAAa,OAAO,KAAa,CAAC,CAC1C"}
package/dist/write.d.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import { Data, Effect, Option, Schema } from "effect";
2
2
  import { AnyEntity, EntityField, EntityInput, EntityRef, EntityRelation } from "./index.js";
3
3
  import { ContextValue } from "./sets.js";
4
- import { BeforeRow } from "./invariant.js";
5
- import { Collation as Collation$1 } from "./collation.js";
4
+ import { AnyRefinement, RefinementOf } from "./refine.js";
5
+ import { BeforeRow, Invariant } from "./invariant.js";
6
6
  import { AnyExpr, AnyQuery as AnyQuery$1, InputExpr, Predicate, Reads } from "./expr.js";
7
+ import { Collation as Collation$1 } from "./collation.js";
7
8
  import { Held } from "./held.js";
8
- import { MemoryOperators as MemoryOperators$1 } from "./operators.js";
9
9
  import { ExprContext as ExprContext$1 } from "./context.js";
10
+ import { MemoryOperators as MemoryOperators$1 } from "./operators.js";
11
+ import { Footprint } from "./footprint.js";
10
12
  type AnyField = EntityField<string, string, Schema.Constraint>;
11
13
  type OneRelation$1 = EntityRelation<string, string, AnyEntity, 'one', boolean>;
12
14
  /** One input key the write sets, and the field it sets. */
@@ -106,6 +108,24 @@ export interface Write<E extends AnyEntity, Fields extends Schema.Struct.Fields,
106
108
  * a row it holds of, and refuses the rest as unmet.
107
109
  */
108
110
  readonly when: Option.Option<AnyQuery$1>;
111
+ /**
112
+ * The state the row must be in for the write to land (`from: Draft`): its
113
+ * predicate is in `when` too, so a row in another state is refused as unmet.
114
+ */
115
+ readonly from: Option.Option<AnyRefinement>;
116
+ /**
117
+ * The state every row the write can start from is in once it lands
118
+ * (`becomes: Published`): proved where the write is declared, by
119
+ * enumerating them, or, where enumeration cannot decide, kept by `ensures`.
120
+ */
121
+ readonly becomes: Option.Option<AnyRefinement>;
122
+ /**
123
+ * The postcondition a `becomes` enumeration could not decide is held to
124
+ * where the write commits: an invariant of this write alone, with the id
125
+ * `becomes:<State>`, judged by each writer beside the Entity's invariants
126
+ * and refused as `Invalid`. None for a write with no such claim.
127
+ */
128
+ readonly ensures: Option.Option<Invariant>;
109
129
  /** The keys it sets, in the input's order. */
110
130
  readonly sets: ReadonlyArray<WriteSet>;
111
131
  /**
@@ -149,23 +169,36 @@ export type WriteComputations<E extends AnyEntity, Fields extends Schema.Struct.
149
169
  type UpdateOptions<E extends AnyEntity, Fields extends Schema.Struct.Fields> = RowOptions<Fields> & {
150
170
  readonly increment?: WriteIncrements<E, Fields>;
151
171
  readonly compute?: WriteComputations<E, Fields>;
172
+ readonly becomes?: RefinementOf<E> | undefined;
152
173
  };
153
- /** `update`: conditioned when given `when`, which the overloads tell apart. */
174
+ /** `update`: conditioned when given `when` or `from`, which the overloads tell apart. */
154
175
  interface UpdateWrite {
155
176
  <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: UpdateOptions<E, Fields> & {
156
177
  readonly when: WriteCondition<E, Fields>;
178
+ readonly from?: RefinementOf<E> | undefined;
157
179
  }): ConditionedWrite<E, Fields, 'Update'>;
158
180
  <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: UpdateOptions<E, Fields> & {
159
181
  readonly when?: undefined;
182
+ readonly from: RefinementOf<E>;
183
+ }): ConditionedWrite<E, Fields, 'Update'>;
184
+ <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: UpdateOptions<E, Fields> & {
185
+ readonly when?: undefined;
186
+ readonly from?: undefined;
160
187
  }): Write<E, Fields, 'Update'>;
161
188
  }
162
- /** `delete`: conditioned when given `when`, as an update is. */
189
+ /** `delete`: conditioned when given `when` or `from`, as an update is. */
163
190
  interface DeleteWrite {
164
191
  <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: RowOptions<Fields> & {
165
192
  readonly when: WriteCondition<E, Fields>;
193
+ readonly from?: RefinementOf<E> | undefined;
194
+ }): ConditionedWrite<E, Fields, 'Delete'>;
195
+ <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: RowOptions<Fields> & {
196
+ readonly when?: undefined;
197
+ readonly from: RefinementOf<E>;
166
198
  }): ConditionedWrite<E, Fields, 'Delete'>;
167
199
  <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: RowOptions<Fields> & {
168
200
  readonly when?: undefined;
201
+ readonly from?: undefined;
169
202
  }): Write<E, Fields, 'Delete'>;
170
203
  }
171
204
  /**
@@ -204,6 +237,8 @@ export interface ContextValues {
204
237
  * server reads every row its asker may see, and reads a hidden one as null.
205
238
  */
206
239
  export type ContextRead<E, R> = (row: EntityRef, key: string) => Effect.Effect<Held<unknown>, E, R>;
240
+ /** Every member a write may change, by key: `Write.writes`, and the revision it expects, which it moves on. */
241
+ export declare const writtenKeys: (write: AnyWrite) => ReadonlyArray<string>;
207
242
  export declare const Write: {
208
243
  /**
209
244
  * Sets, on the row whose id is the input's `id` key, every field the input
@@ -221,7 +256,15 @@ export declare const Write: {
221
256
  *
222
257
  * `when` is what the row must hold for the update to land, checked where it
223
258
  * commits (`({ input }) => Expr.eq(Post.fields.status, 'draft')`); a row it
224
- * does not hold of is refused as unmet.
259
+ * does not hold of is refused as unmet. `from: Draft` (an `Entity.refine`
260
+ * state) joins that state's predicate to it.
261
+ *
262
+ * `becomes: Published` says every row it can start from is in that state
263
+ * once it lands. It is proved where the write is declared, by enumerating
264
+ * those rows over finite fields: one it leaves outside throws, naming it.
265
+ * One enumeration cannot decide (`becomes: InStock` over an increment) is
266
+ * the write's postcondition, `ensures`: each writer judges it where the
267
+ * write commits and refuses a row it leaves outside as `Invalid`.
225
268
  *
226
269
  * `compute` sets a field to what an expression comes to over the row before
227
270
  * the write and the input, run where it commits
@@ -238,10 +281,12 @@ export declare const Write: {
238
281
  *
239
282
  * What its Entity sets from the write's context (`Entity.sets`: who asks,
240
283
  * when) it writes too, never from the input: a server fills them, a client
241
- * predicts them. An update writes those set `on: 'write'`.
284
+ * predicts them. An update writes those set `on: 'write'`. `becomes`, as an
285
+ * update's, is proved over what the insert sets, or else ensured.
242
286
  */
243
287
  insert: <E extends AnyEntity, Fields extends Schema.Struct.Fields>(input: EntityInput<E, Fields, any>, options: {
244
288
  readonly id: keyof Fields & string;
289
+ readonly becomes?: RefinementOf<E> | undefined;
245
290
  }) => Write<E, Fields, 'Insert'>;
246
291
  /**
247
292
  * Deletes the row whose id is the input's `id` key, only while it is still at
@@ -259,6 +304,13 @@ export declare const Write: {
259
304
  readonly field: string;
260
305
  readonly revision: unknown;
261
306
  }>;
307
+ /**
308
+ * The postcondition a write's `becomes` holds it to where it commits, as
309
+ * the invariant a refusal names (`Refusal.isInvalidBy(refusal,
310
+ * Write.ensured(Sell.write))`). Throws for a write with none: one with no
311
+ * `becomes`, or one whose `becomes` was proved where it was declared.
312
+ */
313
+ ensured: (write: AnyWrite) => Invariant;
262
314
  /** The members any invocation may write: what a query reading none of them cannot be changed by. */
263
315
  writes: (write: AnyWrite) => ReadonlyArray<AnyField | OneRelation$1>;
264
316
  /**
@@ -273,6 +325,12 @@ export declare const Write: {
273
325
  contextValues: <E, R>(write: AnyWrite, by: ExprContext$1, read: ContextRead<E, R>) => Effect.Effect<ContextValues, E, R>;
274
326
  /** The Entities a write's paths from the viewer read, by name: what a server must have a source of. */
275
327
  contextReads: (write: AnyWrite) => ReadonlyArray<string>;
328
+ /**
329
+ * What a write reads and writes of its row, by field key (`Write.reads`,
330
+ * and `Write.writes` with the revision it expects, which it moves on): what
331
+ * `Laws.check` judges it by.
332
+ */
333
+ footprint: (write: AnyWrite) => Footprint;
276
334
  /**
277
335
  * The fields a write reads from the row it writes: those its `when` reads,
278
336
  * each it increments, each its assignments read, and the revision it
@@ -1 +1 @@
1
- {"version":3,"file":"write.d.ts","names":["OneRelation","Collation","AnyQuery","ExprContext","MemoryOperators"],"sources":["../src/write.ts"],"mappings":";;;;;;;;;KA+CK,WAAW,4BAA4B,OAAO;KAC9CA,gBAAc,+BAA+B;;iBAGjC;WACN;WACA,OAAO;;;;;;;iBAQD,uBAAuB;WAC7B;;;;;;;iBAQM;WACN,OAAO;WACP,MAAM;;;;;;WAMN;;;;;;;;;YAUC,cAAc,KAAK;EAC7B;aAAkB;;EAClB;aAAkB;;EAClB;aAC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,GAAG;;EAgCb,eAAA,OAAA,aAAW;;;;;;;EAgBlB,QAAA,OAAA,aAAW,cAAc;;;;;;;EAoBjC,OAAA,eAAe,OAAO,OAAO,QAAM,OACjC,MAAM,WAAW,SAAO,OACxB,OAAO,OAAO,KAAK,SAAO,OAC1B,0BACN;;;;;EAmDiB,aAAA,OAAA,KAAK,8CAA4C;;;;;;;;;;EAsB9D,QAAA,KAAA,SAAS,0BAAwB,OAC/B,KAAK,sDAAoD;aAC5C,WAAWC;;aAEtB,KAAK,SAAS;aACd,SAAS"}
1
+ {"version":3,"file":"write.d.ts","names":["OneRelation","Collation","AnyQuery","ExprContext","MemoryOperators"],"sources":["../src/write.ts"],"mappings":";;;;;;;;;;;KAmDK,WAAW,4BAA4B,OAAO;KAC9CA,gBAAc,+BAA+B;;iBAGjC;WACN;WACA,OAAO;;;;;;;iBAQD,uBAAuB;WAC7B;;;;;;;iBAQM;WACN,OAAO;WACP,MAAM;;;;;;WAMN;;;;;;;;;YAUC,cAAc,KAAK;EAC7B;aAAkB;;EAClB;aAAkB;;EAClB;aACW;aACA,MAAM,cAAc;aACpB,WAAWC;;;qBAGX,aAAW,KAAA,WAAA;;WALD;WACJ,MAAA,cAAc;WACT,WAAAA;;;WALC;;;WACE;;;iBAUV;WACN;WACA,UAAUD;;;iBAIJ;WACN,QAAQ,WAAWA;WACnB,OAAO;;;YAIN;;;;;;iBAOK,MACf,UAAU,WACV,eAAe,OAAO,OAAO,QAC7B,aAAa,YAAY;WAEhB,MAAM;WACN,OAAO,YAAY,GAAG;;WAEtB,IAAI;aAAsB,WAAW;;;;;;WAKrC,SAAS;aAAsB,WAAW;;;;;;;WAM1C,MAAM,OAAO,OAAOE;;;;;WAKpB,MAAM,OAAO,OAAO;;;;;;WAMpB,SAAS,OAAO,OAAO;;;;;;;WAOvB,SAAS,OAAO,OAAO;;WAEvB,MAAM,cAAc;;;;;WAKpB,YAAY,cAAc;;WAE1B,aAAa,cAAc;;WAE3B,OAAO,cAAc;;;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;;;;;;;EAYf,QAAA,OAAA,aAAW,cAAc;;;;;;;EAoBjC,OAAA,eAAe,OAAO,OAAO,QAAM,OACjC,MAAM,WAAW,SAAO,OACxB,OAAO,OAAO,KAAK,SAAO,OAC1B,0BACN;;;;;EAmDiB,aAAA,OAAA,KAAK,8CAA4C;;;;;;;;;;EAsB9D,QAAA,KAAA,SAAS,0BAAwB,OAC/B,KAAK,sDAAoD;aAC5C,WAAWC;;aAEtB,KAAK,SAAS;aACd,SAAS"}
package/dist/write.js CHANGED
@@ -1,10 +1,13 @@
1
1
  import { Data, Effect, Match, Option, Schema, SchemaAST } from "effect";
2
2
  import { own, put } from "./record.js";
3
3
  import { SchemaShape } from "./shape.js";
4
+ import { inState, localTo } from "./refine.js";
5
+ import { applyOperator } from "./evaluate.js";
4
6
  import { Expr, Query, dependenciesOf, isPredicate } from "./expr.js";
5
7
  import { Held, idOfRef } from "./held.js";
6
8
  import { contextValue, viewerIdOf } from "./context.js";
7
- import { applyOperator } from "./evaluate.js";
9
+ import { Footprint } from "./footprint.js";
10
+ import { Steps, steps } from "./enumerate.js";
8
11
  // src/write.ts
9
12
  /**
10
13
  * A write as a value: what an operation changes, declared over the input it
@@ -22,10 +25,10 @@ import { applyOperator } from "./evaluate.js";
22
25
  * Entity having a field does not mean anyone may set it.
23
26
  */
24
27
  const Computation = Data.taggedEnum();
25
- const update = (input, options) => settingSomething(Object.freeze({
28
+ const update = (input, options) => becoming(settingSomething(Object.freeze({
26
29
  ...declared("Update", input, options),
27
30
  context: contextOf(input.entity, "write")
28
- }));
31
+ })));
29
32
  const remove = (input, options) => {
30
33
  const write = declared("Delete", input, options);
31
34
  const named = [...write.sets, ...write.links][0];
@@ -35,6 +38,8 @@ const remove = (input, options) => {
35
38
  const fail = (input, message) => {
36
39
  throw new Error(`[foldkit-entity] Write of ${input.entity.name}: ${message}`);
37
40
  };
41
+ /** The context terms (`Expr.viewer`, `Expr.now`) an expression's reads include. */
42
+ const contextTerms = (reads) => reads.operations.filter((operation) => operation === "viewer" || operation === "now");
38
43
  const membersOf = (input) => input.members;
39
44
  /** A field's value as the store holds it. A field's schema needs no service, so none is asked. */
40
45
  const encoded = (field, value) => Schema.encodeUnknownSync(field.schema)(value);
@@ -50,8 +55,13 @@ const given = (value) => {
50
55
  const fieldAt = (input, key, role) => {
51
56
  const member = own(membersOf(input), key);
52
57
  if (member === void 0) return fail(input, `${role} "${key}" is not a key of the input`);
53
- if (member._tag !== "Field") return fail(input, `${role} "${key}" is not mapped to a field`);
54
- return member;
58
+ const unmapped = () => fail(input, `${role} "${key}" is not mapped to a field`);
59
+ return Match.valueTags(member, {
60
+ Field: (field) => field,
61
+ Unmapped: unmapped,
62
+ RelationInput: unmapped,
63
+ NestedInput: unmapped
64
+ });
55
65
  };
56
66
  /**
57
67
  * What every kind shares: the key naming the row, the expected revision, and
@@ -92,9 +102,12 @@ const declared = (kind, input, options) => {
92
102
  }
93
103
  const placeholders = Object.create(null);
94
104
  for (const [key, schema] of Object.entries(input.schema.fields)) placeholders[key] = Expr.input(key, schema);
95
- const when = Option.map(Option.fromUndefinedOr(options.when), (condition) => {
96
- return Query.from(input.entity).pipe(Query.where(condition({ input: placeholders })));
97
- });
105
+ const from = Option.map(Option.fromUndefinedOr(options.from), (state) => localTo(input.entity, state, "from"));
106
+ const becomes = Option.map(Option.fromUndefinedOr(options.becomes), (state) => localTo(input.entity, state, "becomes"));
107
+ const conditions = [...Option.toArray(Option.map(from, (state) => state.predicate)), ...Option.toArray(Option.map(Option.fromUndefinedOr(options.when), (condition) => condition({ input: placeholders })))];
108
+ const asking = contextTerms(dependenciesOf(...conditions));
109
+ if (asking.length > 0) fail(input, `its \`when\` reads ${asking.map((term) => `Expr.${term}`).join(" and ")}; a precondition reads the row and the input only, and a guard rule says who is asking`);
110
+ const when = conditions.length === 0 ? Option.none() : Option.some(Query.from(input.entity).pipe(Query.where(...conditions)));
98
111
  const increments = Object.entries(options.increment ?? {}).flatMap(([fieldKey, key]) => key === void 0 ? [] : [incrementOf(input, fieldKey, key, {
99
112
  expect,
100
113
  sets
@@ -125,6 +138,9 @@ const declared = (kind, input, options) => {
125
138
  }),
126
139
  expect,
127
140
  when,
141
+ from,
142
+ becomes,
143
+ ensures: Option.none(),
128
144
  sets: Object.freeze(sets),
129
145
  increments: Object.freeze(increments),
130
146
  assignments: Object.freeze(assignments),
@@ -174,7 +190,10 @@ const walked = (path, by, read) => Option.match(viewerIdOf(path.viewer.entity, b
174
190
  };
175
191
  }
176
192
  const end = yield* read(at, path.field.key);
177
- return end._tag === "Unheld" ? end : Held.of(end.value ?? null);
193
+ return Held.match(end, {
194
+ onHeld: (value) => Held.of(value ?? null),
195
+ onUnheld: () => end
196
+ });
178
197
  })
179
198
  });
180
199
  /** Whether a field stores a null. */
@@ -233,7 +252,7 @@ const assignmentOf = (input, fieldKey, compute, declared) => {
233
252
  if (isPredicate(expr) || holdsPredicate(expr)) return fail(input, `computes "${fieldKey}" with a predicate, which an assignment carries only as a value`);
234
253
  const reads = dependenciesOf(expr);
235
254
  if (reads.next.length > 0) return fail(input, `computes "${fieldKey}" from the row after the write, which an assignment never reads`);
236
- const context = reads.operations.filter((operation) => operation === "viewer" || operation === "now");
255
+ const context = contextTerms(reads);
237
256
  if (context.length > 0) return fail(input, `computes "${fieldKey}" from the write's context (${context.map((term) => `Expr.${term}`).join(", ")}), which an assignment does not read; a value the context gives is declared with Entity.sets`);
238
257
  if (reads.reaches.length > 0) return fail(input, `computes "${fieldKey}" through a relation, from another row, which an assignment does not read`);
239
258
  const stranger = reads.fields.find((read) => read.owner.name !== input.entity.name);
@@ -254,7 +273,10 @@ const assignmentOf = (input, fieldKey, compute, declared) => {
254
273
  const computationOf = (write, expr, input) => {
255
274
  switch (expr._tag) {
256
275
  case "Field":
257
- case "Next": return Computation.Field({ key: expr._tag === "Field" ? expr.key : expr.field.key });
276
+ case "Next": return Computation.Field({ key: Match.valueTags(expr, {
277
+ Field: ({ key }) => key,
278
+ Next: ({ field }) => field.key
279
+ }) });
258
280
  case "Literal": return Computation.Value({ value: expr.value });
259
281
  case "Input": return Computation.Value({ value: Schema.encodeUnknownSync(write.input.schema.fields[expr.key])(input[expr.key]) });
260
282
  case "Call": return Computation.Call({
@@ -310,8 +332,46 @@ const incrementOf = (input, fieldKey, key, declared) => {
310
332
  integer
311
333
  });
312
334
  };
335
+ /**
336
+ * A write declared to leave every row in a state, proved by enumerating the
337
+ * rows it can start from: refused where it is declared when one is left
338
+ * outside it. Where enumeration cannot decide, the claim is the write's
339
+ * postcondition (`ensures`), which each writer holds where it commits.
340
+ */
341
+ const becoming = (write) => Option.match(write.becomes, {
342
+ onNone: () => write,
343
+ onSome: (target) => {
344
+ const entity = write.input.entity.name;
345
+ const enforced = () => Object.freeze({
346
+ ...write,
347
+ ensures: Option.some(Object.freeze({
348
+ id: `becomes:${target.name}`,
349
+ entity,
350
+ predicate: target.after,
351
+ message: `The ${entity} would not be ${target.name} once written`,
352
+ path: target.reads,
353
+ before: Object.freeze([]),
354
+ after: target.reads
355
+ }))
356
+ });
357
+ return Steps.$match(steps(write, target.reads), {
358
+ Undecided: enforced,
359
+ Steps: ({ steps: each }) => {
360
+ const judged = each.map((step) => ({
361
+ step,
362
+ holds: inState(target, step.after)
363
+ }));
364
+ const broken = judged.find(({ holds }) => Option.contains(holds, false));
365
+ if (broken !== void 0) fail(write.input, `becomes ${entity}.${target.name}, but from ${JSON.stringify(broken.step.before)} given ${JSON.stringify(broken.step.input)} it leaves ${JSON.stringify(broken.step.after)}`);
366
+ return judged.some(({ holds }) => Option.isNone(holds)) ? enforced() : write;
367
+ }
368
+ });
369
+ }
370
+ });
313
371
  /** An update or an insert that would write nothing is refused where it is declared. */
314
372
  const settingSomething = (write) => write.sets.length === 0 && write.links.length === 0 && write.increments.length === 0 && write.assignments.length === 0 && write.context.length === 0 ? fail(write.input, "it sets no field") : write;
373
+ /** Every member a write may change, by key: `Write.writes`, and the revision it expects, which it moves on. */
374
+ const writtenKeys = (write) => [...Write.writes(write).map((member) => member.key), ...write.expect === void 0 ? [] : [write.expect.field.key]];
315
375
  const Write = {
316
376
  /**
317
377
  * Sets, on the row whose id is the input's `id` key, every field the input
@@ -329,7 +389,15 @@ const Write = {
329
389
  *
330
390
  * `when` is what the row must hold for the update to land, checked where it
331
391
  * commits (`({ input }) => Expr.eq(Post.fields.status, 'draft')`); a row it
332
- * does not hold of is refused as unmet.
392
+ * does not hold of is refused as unmet. `from: Draft` (an `Entity.refine`
393
+ * state) joins that state's predicate to it.
394
+ *
395
+ * `becomes: Published` says every row it can start from is in that state
396
+ * once it lands. It is proved where the write is declared, by enumerating
397
+ * those rows over finite fields: one it leaves outside throws, naming it.
398
+ * One enumeration cannot decide (`becomes: InStock` over an increment) is
399
+ * the write's postcondition, `ensures`: each writer judges it where the
400
+ * write commits and refuses a row it leaves outside as `Invalid`.
333
401
  *
334
402
  * `compute` sets a field to what an expression comes to over the row before
335
403
  * the write and the input, run where it commits
@@ -346,12 +414,13 @@ const Write = {
346
414
  *
347
415
  * What its Entity sets from the write's context (`Entity.sets`: who asks,
348
416
  * when) it writes too, never from the input: a server fills them, a client
349
- * predicts them. An update writes those set `on: 'write'`.
417
+ * predicts them. An update writes those set `on: 'write'`. `becomes`, as an
418
+ * update's, is proved over what the insert sets, or else ensured.
350
419
  */
351
- insert: (input, options) => settingSomething(Object.freeze({
420
+ insert: (input, options) => becoming(settingSomething(Object.freeze({
352
421
  ...declared("Insert", input, options),
353
422
  context: contextOf(input.entity, "create")
354
- })),
423
+ }))),
355
424
  /**
356
425
  * Deletes the row whose id is the input's `id` key, only while it is still at
357
426
  * the revision `expect` names, when it names one. It sets nothing, so a key
@@ -368,6 +437,15 @@ const Write = {
368
437
  field: field.key,
369
438
  revision: encoded(field, value[key])
370
439
  })),
440
+ /**
441
+ * The postcondition a write's `becomes` holds it to where it commits, as
442
+ * the invariant a refusal names (`Refusal.isInvalidBy(refusal,
443
+ * Write.ensured(Sell.write))`). Throws for a write with none: one with no
444
+ * `becomes`, or one whose `becomes` was proved where it was declared.
445
+ */
446
+ ensured: (write) => Option.getOrElse(write.ensures, () => {
447
+ throw new Error(`[foldkit-entity] Write.ensured: this write of ${write.input.entity.name} ensures nothing; only a becomes enumeration cannot decide is held where it commits`);
448
+ }),
371
449
  /** The members any invocation may write: what a query reading none of them cannot be changed by. */
372
450
  writes: (write) => [
373
451
  ...write.sets.map((set) => set.field),
@@ -390,21 +468,28 @@ const Write = {
390
468
  const links = {};
391
469
  const unfilled = [];
392
470
  for (const { member, value } of write.context) {
393
- const comes = value._tag === "ViewerPath" ? Held.match(yield* walked(value, by, read), {
394
- onHeld: (held) => Option.some(held),
471
+ const comes = yield* Match.value(value).pipe(Match.tag("ViewerPath", (path) => Effect.map(walked(path, by, read), (held) => Held.match(held, {
472
+ onHeld: (some) => Option.some(some),
395
473
  onUnheld: () => Option.none()
396
- }) : contextValue(value, by);
474
+ }))), Match.orElse((other) => Effect.succeed(contextValue(other, by))));
397
475
  if (Option.isNone(comes)) unfilled.push(member.key);
398
- else if (member._tag === "Relation") {
399
- const id = comes.value;
400
- if (id !== null) put(links, member.key, Option.some({
401
- entity: member.target().name,
402
- id: String(id)
403
- }));
404
- else if (member.optional) put(links, member.key, Option.none());
405
- else unfilled.push(member.key);
406
- } else if (comes.value !== null || holdsNull(member)) put(values, member.key, comes.value);
407
- else unfilled.push(member.key);
476
+ else {
477
+ const given = comes.value;
478
+ Match.valueTags(member, {
479
+ Relation: (relation) => {
480
+ if (given !== null) put(links, relation.key, Option.some({
481
+ entity: relation.target().name,
482
+ id: String(given)
483
+ }));
484
+ else if (relation.optional) put(links, relation.key, Option.none());
485
+ else unfilled.push(relation.key);
486
+ },
487
+ Field: (field) => {
488
+ if (given !== null || holdsNull(field)) put(values, field.key, given);
489
+ else unfilled.push(field.key);
490
+ }
491
+ });
492
+ }
408
493
  }
409
494
  return {
410
495
  values,
@@ -413,7 +498,20 @@ const Write = {
413
498
  };
414
499
  }),
415
500
  /** The Entities a write's paths from the viewer read, by name: what a server must have a source of. */
416
- contextReads: (write) => [...new Set(write.context.flatMap(({ value }) => value._tag === "ViewerPath" ? [value.viewer.entity.name, ...value.via.map((relation) => relation.target().name)] : []))],
501
+ contextReads: (write) => [...new Set(write.context.flatMap(({ value }) => {
502
+ if (value._tag !== "ViewerPath") return [];
503
+ const { viewer, via } = value;
504
+ return [viewer.entity.name, ...via.map((relation) => relation.target().name)];
505
+ }))],
506
+ /**
507
+ * What a write reads and writes of its row, by field key (`Write.reads`,
508
+ * and `Write.writes` with the revision it expects, which it moves on): what
509
+ * `Laws.check` judges it by.
510
+ */
511
+ footprint: (write) => Footprint.Derived({
512
+ reads: Write.reads(write).map((field) => field.key),
513
+ writes: writtenKeys(write)
514
+ }),
417
515
  /**
418
516
  * The fields a write reads from the row it writes: those its `when` reads,
419
517
  * each it increments, each its assignments read, and the revision it
@@ -515,6 +613,6 @@ const Write = {
515
613
  };
516
614
  }
517
615
  };
518
- export { Computation, Write };
616
+ export { Computation, Write, writtenKeys };
519
617
 
520
618
  //# sourceMappingURL=write.js.map