foldkit-entity 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +147 -5
  2. package/dist/collation.d.ts +33 -2
  3. package/dist/collation.d.ts.map +1 -0
  4. package/dist/conformance/index.d.ts +4 -4
  5. package/dist/conformance/index.d.ts.map +1 -1
  6. package/dist/conformance/index.js +5 -7
  7. package/dist/conformance/index.js.map +1 -1
  8. package/dist/conformance/operator.d.ts +1 -2
  9. package/dist/conformance/operator.d.ts.map +1 -1
  10. package/dist/conformance/operator.js +2 -6
  11. package/dist/conformance/operator.js.map +1 -1
  12. package/dist/conformance/relational.d.ts +17 -17
  13. package/dist/conformance/relational.d.ts.map +1 -1
  14. package/dist/conformance/relational.js +1 -3
  15. package/dist/conformance/relational.js.map +1 -1
  16. package/dist/conformance/variants.d.ts +47 -0
  17. package/dist/conformance/variants.d.ts.map +1 -0
  18. package/dist/conformance/variants.js +126 -0
  19. package/dist/conformance/variants.js.map +1 -0
  20. package/dist/context.d.ts +60 -2
  21. package/dist/context.d.ts.map +1 -0
  22. package/dist/descriptor.d.ts +33 -0
  23. package/dist/descriptor.d.ts.map +1 -0
  24. package/dist/descriptor.js +137 -0
  25. package/dist/descriptor.js.map +1 -0
  26. package/dist/entity.d.ts +231 -0
  27. package/dist/entity.d.ts.map +1 -0
  28. package/dist/entity.js +436 -0
  29. package/dist/entity.js.map +1 -0
  30. package/dist/evaluate.d.ts +204 -2
  31. package/dist/evaluate.d.ts.map +1 -0
  32. package/dist/evaluate.js +51 -7
  33. package/dist/evaluate.js.map +1 -1
  34. package/dist/expr.d.ts +915 -2
  35. package/dist/expr.d.ts.map +1 -0
  36. package/dist/expr.js +50 -10
  37. package/dist/expr.js.map +1 -1
  38. package/dist/held.d.ts +112 -2
  39. package/dist/held.d.ts.map +1 -0
  40. package/dist/held.js +13 -2
  41. package/dist/held.js.map +1 -1
  42. package/dist/ids.d.ts +8 -0
  43. package/dist/ids.d.ts.map +1 -0
  44. package/dist/ids.js +8 -0
  45. package/dist/ids.js.map +1 -0
  46. package/dist/index.d.ts +400 -6
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +113 -12
  49. package/dist/index.js.map +1 -0
  50. package/dist/invariant.d.ts +123 -2
  51. package/dist/invariant.d.ts.map +1 -0
  52. package/dist/invariant.js +236 -1
  53. package/dist/invariant.js.map +1 -0
  54. package/dist/law.d.ts +264 -2
  55. package/dist/law.d.ts.map +1 -0
  56. package/dist/law.js +1 -1
  57. package/dist/operators.d.ts +170 -2
  58. package/dist/operators.d.ts.map +1 -0
  59. package/dist/operators.js +3 -3
  60. package/dist/readFilter.d.ts +8 -2
  61. package/dist/readFilter.d.ts.map +1 -0
  62. package/dist/sets.d.ts +18 -2
  63. package/dist/sets.d.ts.map +1 -0
  64. package/dist/sets.js +1 -1
  65. package/dist/shape.d.ts +23 -2
  66. package/dist/shape.d.ts.map +1 -0
  67. package/dist/tested.d.ts +8 -2
  68. package/dist/tested.d.ts.map +1 -0
  69. package/dist/text.d.ts +27 -2
  70. package/dist/text.d.ts.map +1 -0
  71. package/dist/text.js +1 -1
  72. package/dist/variants.d.ts +72 -0
  73. package/dist/variants.d.ts.map +1 -0
  74. package/dist/variants.js +76 -0
  75. package/dist/variants.js.map +1 -0
  76. package/dist/words.d.ts +17 -2
  77. package/dist/words.d.ts.map +1 -0
  78. package/dist/write.d.ts +312 -2
  79. package/dist/write.d.ts.map +1 -0
  80. package/dist/write.js +3 -3
  81. package/package.json +3 -3
  82. package/dist/collation-BB4YTIbY.d.ts +0 -34
  83. package/dist/collation-BB4YTIbY.d.ts.map +0 -1
  84. package/dist/index-48JeXG0A.d.ts +0 -2585
  85. package/dist/index-48JeXG0A.d.ts.map +0 -1
  86. package/dist/readFilter-CWMnFRVw.d.ts +0 -9
  87. package/dist/readFilter-CWMnFRVw.d.ts.map +0 -1
  88. package/dist/shape-LAowRf9f.d.ts +0 -23
  89. package/dist/shape-LAowRf9f.d.ts.map +0 -1
  90. package/dist/src-DKhUqLoC.js +0 -731
  91. package/dist/src-DKhUqLoC.js.map +0 -1
  92. package/dist/words-a4e9o-TK.d.ts +0 -18
  93. package/dist/words-a4e9o-TK.d.ts.map +0 -1
@@ -1,731 +0,0 @@
1
- import { SchemaShape } from "./shape.js";
2
- import { own, put } from "./record.js";
3
- import { Expr, Query, dependenciesOf } from "./expr.js";
4
- import { Operators } from "./operators.js";
5
- import { OperatorMissingError, truthOver } from "./evaluate.js";
6
- import { checkedSet } from "./sets.js";
7
- import { Data, Option, Pipeable, Schema } from "effect";
8
- import { Metadata } from "foldkit-metadata";
9
- // src/invariant.ts
10
- /**
11
- * Invariants: what every stored row of an Entity must hold, and what every
12
- * change of one must, declared once on the Entity through its metadata and read
13
- * from there by each interpreter: the reference judge here, a Schema check, a
14
- * form, a server's writer.
15
- *
16
- * One is built over the row before a write (`before`, each field as `Expr.field`) and
17
- * the row after it (`after`, each field as `Expr.next`). What it reads decides
18
- * when it is judged:
19
- *
20
- * ```text
21
- * reads `after` only -> a state invariant: every create and update, a CHECK constraint
22
- * reads `before` too -> a transition invariant: every update, which has a row before
23
- * ```
24
- *
25
- * It reads no input and no principal. Who may write is a guard's; whether a
26
- * write applies now is its `when`'s.
27
- */
28
- const Invariants = Metadata.key("foldkit-entity/invariants", {
29
- merge: (values) => [...new Set(values)],
30
- summarize: (invariant) => invariant.id
31
- });
32
- /** Whether an invariant reads the row before, and so is judged only where there is one. */
33
- const readsBefore = (held) => held.before.length > 0;
34
- const fail$1 = (entity, message) => {
35
- throw new Error(`[foldkit-entity] Entity.invariant on ${entity.name}: ${message}`);
36
- };
37
- const invariant = (id, build, options) => {
38
- let attached;
39
- const declared = (entity) => {
40
- if (id.length === 0) fail$1(entity, "an invariant needs an id");
41
- if (attached !== void 0 && attached !== entity.name) fail$1(entity, `"${id}" is declared on ${attached} already: declare it again for this Entity`);
42
- if (invariantsOf(entity).some((held) => held.id === id)) fail$1(entity, `"${id}" is declared twice`);
43
- const fields = entity.fields;
44
- const after = Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, Expr.next(field)]));
45
- const predicate = build({
46
- before: Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, Expr.field(field)])),
47
- after
48
- });
49
- const body = Query.from(entity).pipe(Query.where(predicate));
50
- const dependencies = Query.dependencies(body);
51
- if (dependencies.inputs.length > 0) fail$1(entity, `"${id}" reads the input ${dependencies.inputs.join(", ")}; it judges stored rows`);
52
- const beforeReads = dependencies.predicate.map((field) => field.key);
53
- const afterReads = dependencies.next.map((field) => field.key);
54
- if (afterReads.length === 0) fail$1(entity, `"${id}" reads no field of \`after\`; what a write may start from is its \`when\``);
55
- const path = options.path ?? [.../* @__PURE__ */ new Set([...afterReads, ...beforeReads])];
56
- for (const key of path) if (!Object.hasOwn(fields, key)) fail$1(entity, `"${id}"'s path names "${key}", not a field`);
57
- attached = entity.name;
58
- return entity.pipe(Entity.annotate(Invariants.of(Object.freeze({
59
- id,
60
- entity: entity.name,
61
- predicate,
62
- message: options.message,
63
- path: Object.freeze([...path]),
64
- before: Object.freeze(beforeReads),
65
- after: Object.freeze(afterReads)
66
- }))));
67
- };
68
- return Object.defineProperties(declared, {
69
- id: {
70
- value: id,
71
- enumerable: true
72
- },
73
- entity: {
74
- enumerable: true,
75
- get: () => {
76
- if (attached === void 0) throw new Error(`[foldkit-entity] Entity.invariant "${id}" names no Entity until it is attached to one`);
77
- return attached;
78
- }
79
- }
80
- });
81
- };
82
- const invariantsOf = (entity) => Invariants.get(entity.metadata);
83
- /** `judge` with the invariants given, as a binding that keeps them holds them. */
84
- const judgeAgainst = (invariants, change, operators = Operators.kernel) => {
85
- const missing = /* @__PURE__ */ new Set();
86
- const unrun = /* @__PURE__ */ new Set();
87
- const failures = [];
88
- const { after, before } = change;
89
- for (const held of invariants) {
90
- if (readsBefore(held) && before === void 0) continue;
91
- const absent = [...held.after.filter((key) => !Object.hasOwn(after, key)), ...held.before.filter((key) => !Object.hasOwn(before ?? {}, key))];
92
- if (absent.length > 0) absent.forEach((key) => missing.add(key));
93
- else try {
94
- if (truthOver(held.predicate, before ?? {}, {}, after, operators) !== true) failures.push(held);
95
- } catch (error) {
96
- if (!(error instanceof OperatorMissingError)) throw error;
97
- unrun.add(error.named);
98
- }
99
- }
100
- if (failures.length > 0) return {
101
- _tag: "Invalid",
102
- failures
103
- };
104
- if (missing.size > 0 || unrun.size > 0) return {
105
- _tag: "Undecided",
106
- fields: [...missing],
107
- operators: [...unrun]
108
- };
109
- return { _tag: "Valid" };
110
- };
111
- /**
112
- * A row, or a change, under every invariant (each row as the store holds it,
113
- * encoded): valid only when each is true. SQL's unknown, from a null, fails
114
- * one, as a `WHERE` drops the row; a field a row does not have leaves it
115
- * undecided, never valid. Without `before` (a create), transition invariants
116
- * are not judged.
117
- */
118
- const judge = (entity, change, operators = Operators.kernel) => judgeAgainst(invariantsOf(entity), change, operators);
119
- /**
120
- * The row an input's value describes, judged under its Entity's state
121
- * invariants: each key mapped to a field, encoded as the store holds it. An
122
- * invariant over a field the input does not set (an `Option` holding nothing, a
123
- * key left out) is undecided, so a partial input is never called valid on its
124
- * account. It has no row before, so it judges no transition.
125
- */
126
- const judgeInput = (input, value, operators = Operators.kernel) => {
127
- const invariants = invariantsOf(input.entity);
128
- if (invariants.length === 0) return { _tag: "Valid" };
129
- const members = input.members;
130
- const row = {};
131
- for (const [key, member] of Object.entries(members)) {
132
- if (member._tag !== "Field" || !Object.hasOwn(value, key)) continue;
133
- const encode = Schema.encodeUnknownOption(member.schema);
134
- const given = value[key];
135
- const held = Option.isOption(given) ? given : Option.fromUndefinedOr(given);
136
- const stored = Option.orElse(encode(given), () => Option.flatMap(held, encode));
137
- Option.map(Option.flatMap(held, () => stored), (encoded) => put(row, member.key, encoded));
138
- }
139
- return judgeAgainst(invariants, { after: row }, operators);
140
- };
141
- /**
142
- * The Entity's state invariants as an Effect Schema check over its row type:
143
- * each failure at its path, with its message. The value is encoded first,
144
- * field by field, so it is judged as the store would hold it. Refused where it
145
- * is made when an invariant calls an operator `operators` does not run: such a
146
- * check would pass every value.
147
- */
148
- const check = (entity, options = {}) => {
149
- const predicates = invariantsOf(entity).map((held) => held.predicate);
150
- const missing = Expr.unsupported(predicates, {
151
- operations: dependenciesOf(...predicates).operations,
152
- operators: options.operators ?? Operators.kernel
153
- });
154
- 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\``);
155
- return Schema.makeFilter((value) => {
156
- const fields = entity.fields;
157
- const decoded = value;
158
- const row = {};
159
- for (const [key, field] of Object.entries(fields)) {
160
- if (!Object.hasOwn(decoded, key)) continue;
161
- put(row, key, Schema.encodeUnknownSync(field.schema)(decoded[key]));
162
- }
163
- const judged = judge(entity, { after: row }, options.operators);
164
- if (judged._tag !== "Invalid") return void 0;
165
- return judged.failures.flatMap((failure) => failure.path.length === 0 ? [failure.message] : failure.path.map((key) => ({
166
- path: [key],
167
- issue: failure.message
168
- })));
169
- });
170
- };
171
- // src/index.ts
172
- /**
173
- * `foldkit-entity` — domain structure as typed values.
174
- *
175
- * An Entity names its intrinsic Fields (one `Schema.Struct`), its Relations
176
- * (navigation edges to other Entities, declared with `Entity.relate`), and its Derived members (readable
177
- * values an interpreter supplies). It describes; it fetches, stores, and
178
- * renders nothing. Remote, Drizzle, and form packages interpret it and attach
179
- * what they need as `foldkit-metadata`.
180
- */
181
- const EntityTypeId = Symbol.for("foldkit-entity/Entity");
182
- const Derivation = Data.taggedEnum();
183
- const SelectionTypeId = Symbol.for("foldkit-entity/Selection");
184
- const SelectionPageTypeId = Symbol.for("foldkit-entity/SelectionPage");
185
- /** The `id` field's schema when it is text, so a ref's id keeps its brand and its checks; else text. */
186
- const idSchemaOf = (entity) => {
187
- const id = entity.fields.id;
188
- if (id === void 0 || id._tag !== "Field") return Schema.String;
189
- const type = Schema.toType(id.schema);
190
- return SchemaShape.isText(type.ast) ? type : Schema.String;
191
- };
192
- const isSelectionPage = (value) => typeof value === "object" && value !== null && SelectionPageTypeId in value;
193
- const isSelection = (value) => typeof value === "object" && value !== null && SelectionTypeId in value;
194
- const unmapped = Object.freeze({ _tag: "Unmapped" });
195
- const shapes = /* @__PURE__ */ new WeakMap();
196
- const shapeOf = (identity) => {
197
- const known = shapes.get(identity);
198
- if (known !== void 0) return known;
199
- const shape = {
200
- relations: {},
201
- derived: {},
202
- sets: {},
203
- revision: 0
204
- };
205
- shapes.set(identity, shape);
206
- return shape;
207
- };
208
- const partsOf = /* @__PURE__ */ new WeakMap();
209
- const EntityProto = {
210
- [EntityTypeId]: EntityTypeId,
211
- pipe() {
212
- return Pipeable.pipeArguments(this, arguments);
213
- }
214
- };
215
- const make = (parts) => {
216
- const shape = shapeOf(parts.identity);
217
- const fields = Object.freeze(parts.fields);
218
- const copies = /* @__PURE__ */ new WeakMap();
219
- const annotate = (members) => Object.freeze(mapValues(members, (member, key) => {
220
- const extra = own(parts.annotated, key);
221
- if (extra === void 0) return member;
222
- const copied = copies.get(member);
223
- if (copied !== void 0) return copied;
224
- const copy = Object.freeze({
225
- ...member,
226
- metadata: Metadata.combine([member.metadata, extra])
227
- });
228
- copies.set(member, copy);
229
- return copy;
230
- }));
231
- let seen = -1;
232
- let view;
233
- const current = () => {
234
- if (seen !== shape.revision) {
235
- const relations = annotate(shape.relations);
236
- const derived = annotate(shape.derived);
237
- view = {
238
- relations,
239
- derived,
240
- sets: Object.freeze({ ...shape.sets }),
241
- members: Object.freeze({
242
- ...fields,
243
- ...relations,
244
- ...derived
245
- })
246
- };
247
- seen = shape.revision;
248
- }
249
- return view;
250
- };
251
- const entity = Object.create(EntityProto);
252
- Object.defineProperties(entity, {
253
- identity: {
254
- value: parts.identity,
255
- enumerable: true
256
- },
257
- name: {
258
- value: parts.identity.name,
259
- enumerable: true
260
- },
261
- schema: {
262
- value: parts.schema,
263
- enumerable: true
264
- },
265
- fields: {
266
- value: fields,
267
- enumerable: true
268
- },
269
- relations: {
270
- get: () => current().relations,
271
- enumerable: true
272
- },
273
- derived: {
274
- get: () => current().derived,
275
- enumerable: true
276
- },
277
- members: {
278
- get: () => current().members,
279
- enumerable: true
280
- },
281
- sets: {
282
- get: () => current().sets,
283
- enumerable: true
284
- },
285
- metadata: {
286
- value: parts.metadata,
287
- enumerable: true
288
- }
289
- });
290
- partsOf.set(entity, parts);
291
- return Object.freeze(entity);
292
- };
293
- /** A new descriptor of the same Entity, with some of its own parts changed. */
294
- const remake = (entity, changed) => make({
295
- ...partsOf.get(entity),
296
- ...changed
297
- });
298
- /** Adds to the Entity's shared members, which every descriptor of it then reads. */
299
- const extend = (entity, added) => {
300
- const shape = shapeOf(entity.identity);
301
- for (const [key, member] of Object.entries(added.relations ?? {})) put(shape.relations, key, member);
302
- for (const [key, member] of Object.entries(added.derived ?? {})) put(shape.derived, key, member);
303
- for (const [key, set] of Object.entries(added.sets ?? {})) put(shape.sets, key, set);
304
- shape.revision += 1;
305
- };
306
- const isSameEntity = (left, right) => left.identity.token === right.identity.token;
307
- const fail = (entity, message) => {
308
- throw new Error(`Entity "${entity.name}": ${message}`);
309
- };
310
- const isEntity = (value) => typeof value === "object" && value !== null && EntityTypeId in value;
311
- const kindName = {
312
- Field: "field",
313
- Relation: "relation",
314
- Derived: "derived member"
315
- };
316
- const kindOf = (entity, key) => {
317
- const member = entity.members[key];
318
- return member && kindName[member._tag];
319
- };
320
- const assertFree = (entity, keys, adding) => {
321
- for (const key of keys) {
322
- const kind = kindOf(entity, key);
323
- if (kind !== void 0) throw new Error(`Entity "${entity.name}": cannot add ${adding} "${key}", it is already a ${kind}`);
324
- }
325
- };
326
- const mapValues = (record, f) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, f(value, key)]));
327
- const Entity = {
328
- /** Declares an Entity from its intrinsic fields. Each call is a new identity. */
329
- define: (name, schema) => {
330
- const identity = Object.freeze({
331
- name,
332
- token: Symbol(name)
333
- });
334
- return make({
335
- identity,
336
- schema,
337
- fields: mapValues(schema.fields, (fieldSchema, key) => Object.freeze({
338
- _tag: "Field",
339
- owner: identity,
340
- key,
341
- schema: fieldSchema,
342
- metadata: Metadata.empty
343
- })),
344
- annotated: {},
345
- metadata: Metadata.empty
346
- });
347
- },
348
- /**
349
- * Declares the relations between a set of Entities in one step, and returns
350
- * them related. One step, because Entities that point at each other cannot
351
- * each be declared in terms of the other.
352
- */
353
- relate: (entities, relations) => {
354
- const keyByToken = /* @__PURE__ */ new Map();
355
- for (const [key, entity] of Object.entries(entities)) {
356
- if (!isEntity(entity)) throw new Error(`Entity.relate: "${key}" is not an Entity`);
357
- const earlier = keyByToken.get(entity.identity.token);
358
- if (earlier !== void 0) throw new Error(`Entity.relate: "${earlier}" and "${key}" are the same Entity`);
359
- keyByToken.set(entity.identity.token, key);
360
- }
361
- const given = relations;
362
- for (const owner of Object.keys(given)) if (!Object.hasOwn(entities, owner)) throw new Error(`Entity.relate: relations given for "${owner}", which is not being related`);
363
- const related = {};
364
- const additions = [];
365
- for (const [ownerKey, entity] of Object.entries(entities)) {
366
- const specs = own(given, ownerKey) ?? {};
367
- assertFree(entity, Object.keys(specs), "relation");
368
- const added = mapValues(specs, (spec, key) => {
369
- const targetKey = isEntity(spec.target) ? keyByToken.get(spec.target.identity.token) : void 0;
370
- if (targetKey === void 0) throw new Error(`Entity "${entity.name}": relation "${key}" targets an Entity that is not being related`);
371
- return Object.freeze({
372
- _tag: "Relation",
373
- owner: entity.identity,
374
- key,
375
- target: () => related[targetKey],
376
- cardinality: spec.cardinality,
377
- optional: spec.optional,
378
- metadata: Metadata.empty
379
- });
380
- });
381
- additions.push([entity, added]);
382
- put(related, ownerKey, entity);
383
- }
384
- for (const [entity, added] of additions) extend(entity, { relations: added });
385
- return Object.freeze(related);
386
- },
387
- /**
388
- * Selects members of an Entity and assembles the schema of the result. A
389
- * relation selected with `true` yields an `EntityRef`; with a Selection of its
390
- * target, that Selection's value. `many` yields an array, an optional `one`
391
- * is nullable.
392
- */
393
- select: (entity, spec) => {
394
- const members = entity.members;
395
- const fields = mapValues(spec, (selected, key) => {
396
- const member = own(members, key);
397
- if (member === void 0) throw new Error(`Entity "${entity.name}": cannot select "${key}", it is not a member`);
398
- if (member._tag !== "Relation") {
399
- if (selected !== true) throw new Error(`Entity "${entity.name}": "${key}" is a ${kindName[member._tag]}, select it with true`);
400
- return member.schema;
401
- }
402
- const target = member.target();
403
- if (isSelectionPage(selected)) {
404
- if (member.cardinality !== "many") throw new Error(`Entity "${entity.name}": "${key}" is one ${target.name}, so it has no pages`);
405
- if (!isSameEntity(selected.selection.entity, target)) throw new Error(`Entity "${entity.name}": "${key}" pages a Selection of ${target.name}`);
406
- return Schema.Struct({
407
- items: Schema.Array(selected.selection.schema),
408
- hasNext: Schema.Boolean,
409
- hasPrevious: Schema.Boolean
410
- });
411
- }
412
- let item;
413
- if (selected === true) item = Schema.Struct({
414
- entity: Schema.Literal(target.name),
415
- id: idSchemaOf(target)
416
- });
417
- else if (isSelection(selected) && isSameEntity(selected.entity, target)) item = selected.schema;
418
- else throw new Error(`Entity "${entity.name}": "${key}" takes true or a Selection of ${target.name}`);
419
- return member.cardinality === "many" ? Schema.Array(item) : member.optional ? Schema.NullOr(item) : item;
420
- });
421
- return Object.freeze({
422
- [SelectionTypeId]: SelectionTypeId,
423
- entity,
424
- members: spec,
425
- schema: Schema.Struct(fields)
426
- });
427
- },
428
- /**
429
- * A `many` relation read a page at a time, in place of its Selection:
430
- * `comments: Entity.page(CommentSummary, { first: 10 })`. The value is a page
431
- * of the Selection's values: `items`, `hasNext`, `hasPrevious`. Reading on from a cursor is another window.
432
- */
433
- page: (selection, window) => {
434
- const sides = [window.first, window.last].filter((size) => size !== void 0);
435
- if (sides.length !== 1 || !sides.every((size) => Number.isInteger(size) && size >= 0)) throw new Error(`Entity.page: a window of ${selection.entity.name} takes first or last, a non-negative integer`);
436
- if (window.first !== void 0 && window.before !== void 0 || window.last !== void 0 && window.after !== void 0) throw new Error(`Entity.page: a window of ${selection.entity.name} reads first after a cursor, or last before one`);
437
- return Object.freeze({
438
- [SelectionPageTypeId]: SelectionPageTypeId,
439
- selection,
440
- window
441
- });
442
- },
443
- /**
444
- * Adds readable members that are not part of `entity.schema`. A
445
- * `Derived.count` or `Derived.exists` must read rows pointing at this
446
- * Entity: one over a relation to another is refused here, as is an exists
447
- * whose viewer is not another `one` relation of the same pointing Entity.
448
- */
449
- derived: (specs) => (entity) => {
450
- const members = entity.members;
451
- const fresh = Object.fromEntries(Object.entries(specs).filter(([key, spec]) => {
452
- const taken = own(members, key);
453
- return !(taken?._tag === "Derived" && taken.schema === spec.schema && taken.derives === spec.derives);
454
- }));
455
- assertFree(entity, Object.keys(fresh), "derived member");
456
- const added = mapValues(fresh, (spec, key) => {
457
- const pointingHere = (relation, verb) => {
458
- if (relation.cardinality !== "one") fail(entity, `"${key}" ${verb} "${relation.key}", a many relation; name a one relation that points here`);
459
- if (!isSameEntity(relation.target(), entity)) fail(entity, `"${key}" ${verb} "${relation.owner.name}.${relation.key}", which points at ${relation.target().name}`);
460
- };
461
- Derivation.$match(spec.derives, {
462
- Supplied: () => void 0,
463
- Count: ({ relation }) => pointingHere(relation, "counts"),
464
- Exists: ({ relation, viewer }) => {
465
- pointingHere(relation, "reads");
466
- if (viewer.owner.token !== relation.owner.token || viewer.key === relation.key) fail(entity, `"${key}"'s viewer "${viewer.owner.name}.${viewer.key}" must be another one relation of ${relation.owner.name}`);
467
- }
468
- });
469
- return Object.freeze({
470
- _tag: "Derived",
471
- owner: entity.identity,
472
- key,
473
- schema: spec.schema,
474
- derives: spec.derives,
475
- metadata: Metadata.empty
476
- });
477
- });
478
- extend(entity, { derived: added });
479
- return entity;
480
- },
481
- /**
482
- * Says which members take their value from the write's context, never its
483
- * input: `Expr.viewer(User)`, whoever asks (a `one` relation to a User, or a
484
- * field holding their id), and `Expr.now`, when (a field stored as a
485
- * number). `on` says which writes set them: `'create'`, every insert, or
486
- * `'write'`, every insert and every update.
487
- *
488
- * ```ts
489
- * const Post = Blog.Post.pipe(
490
- * Entity.sets({ author: Expr.viewer(User), createdAt: Expr.now }, { on: 'create' }),
491
- * Entity.sets({ editedAt: Expr.now }, { on: 'write' }),
492
- * )
493
- * ```
494
- *
495
- * Every write of the Entity follows from it: a server writes the values and
496
- * a client predicts them, and a write whose input sets one is refused where
497
- * it is declared. Refused here: the id, a member set already, a `many`
498
- * relation, a relation set to anything but the viewer of its target, and a
499
- * field that cannot hold its value. Added after `Entity.relate` to set a
500
- * relation.
501
- */
502
- sets: (values, options) => (entity) => {
503
- const given = values;
504
- const added = {};
505
- for (const [key, value] of Object.entries(given)) {
506
- if (value === void 0) continue;
507
- put(added, key, checkedSet(entity, key, value, options.on));
508
- }
509
- extend(entity, { sets: added });
510
- return entity;
511
- },
512
- /** Attaches an interpreter's metadata to the Entity itself. */
513
- annotate: (metadata) => (entity) => remake(entity, { metadata: Metadata.combine([entity.metadata, metadata]) }),
514
- /**
515
- * Declares what every stored row, or every change of one, must hold:
516
- * `Entity.invariant('reservedWithinQuantity', ({ after }) =>
517
- * Expr.lte(after.reserved, after.quantity), { message })` over the row a
518
- * write leaves, or with `before` too over the change an update makes.
519
- * Refused where it is declared: an id declared twice, a predicate over another
520
- * Entity, one reading an input or nothing of `after` (that is a `when`), a path
521
- * naming no field.
522
- */
523
- invariant,
524
- /** The Entity's invariants, in the order they were declared. */
525
- invariants: invariantsOf,
526
- /**
527
- * A row (`{ after }`, a create's) or a change (`{ before, after }`, an
528
- * update's) under the Entity's invariants: `Valid`, `Invalid` with the ones
529
- * that fail (a null fails, as SQL's unknown), or `Undecided` with the fields
530
- * one reads that a row lacks.
531
- */
532
- judge,
533
- /** Whether an invariant reads the row before a write: judged on updates only, and no CHECK. */
534
- readsBefore,
535
- /** `Entity.judge` against invariants already read, such as those a database binding keeps. */
536
- judgeAgainst,
537
- /**
538
- * The row an `Entity.input`'s value describes, judged: what a form can say
539
- * before the server does. Undecided for an invariant over a field it leaves unset.
540
- */
541
- judgeInput,
542
- /** The state invariants as a Schema check over the row type, each failure at its path. */
543
- check,
544
- /** Attaches an interpreter's metadata to members, by key. */
545
- annotateMembers: (metadata) => (entity) => {
546
- const given = metadata;
547
- for (const key of Object.keys(given)) if (kindOf(entity, key) === void 0) throw new Error(`Entity "${entity.name}": cannot annotate "${key}", it is not a member`);
548
- const parts = partsOf.get(entity);
549
- const fields = mapValues(entity.fields, (member, key) => {
550
- const extra = own(given, key);
551
- return extra === void 0 ? member : Object.freeze({
552
- ...member,
553
- metadata: Metadata.combine([member.metadata, extra])
554
- });
555
- });
556
- const annotated = { ...parts.annotated };
557
- for (const [key, extra] of Object.entries(given)) {
558
- if (extra === void 0 || Object.hasOwn(entity.fields, key)) continue;
559
- const earlier = own(parts.annotated, key);
560
- put(annotated, key, earlier === void 0 ? extra : Metadata.combine([earlier, extra]));
561
- }
562
- return remake(entity, {
563
- fields,
564
- annotated
565
- });
566
- },
567
- /**
568
- * Reads an operation's input schema against an Entity. A key that names a
569
- * field maps to it; any other key is mapped explicitly, to a Field, to
570
- * `Relation.input(relation)`, or to `Entity.unmapped`. Nothing is inferred
571
- * from a naming convention such as `authorId`.
572
- */
573
- input: (entity, schema, ...mapping) => {
574
- const written = mapping[0] ?? {};
575
- for (const key of Object.keys(written)) if (!Object.hasOwn(schema.fields, key)) throw new Error(`Entity "${entity.name}": "${key}" is mapped but is not a key of the input`);
576
- const named = (key, name) => {
577
- const member = entity.members[name];
578
- switch (member?._tag) {
579
- case "Field": return member;
580
- case "Relation": return Object.freeze({
581
- _tag: "RelationInput",
582
- relation: member
583
- });
584
- case "Derived":
585
- case void 0: return fail(entity, `input key "${key}" is mapped to "${name}", which names no field or relation`);
586
- }
587
- };
588
- const given = mapValues(written, (member, key) => typeof member === "string" ? named(key, member) : member);
589
- const fields = entity.fields;
590
- const members = mapValues(schema.fields, (_, key) => {
591
- const member = own(given, key) ?? own(fields, key) ?? fail(entity, `input key "${key}" names no field; map it to a member or Entity.unmapped`);
592
- const owned = member._tag === "Field" ? member : member._tag === "RelationInput" || member._tag === "NestedInput" ? member.relation : member._tag === "Unmapped" ? void 0 : fail(entity, `input key "${key}" maps to a Field, Relation.input(relation), Relation.nested(relation, input), or Entity.unmapped`);
593
- if (owned !== void 0 && owned.owner.token !== entity.identity.token) fail(entity, `input key "${key}" is mapped to a member of "${owned.owner.name}"`);
594
- if (member._tag === "NestedInput" && !isSameEntity(member.input.entity, member.relation.target())) fail(entity, `input key "${key}" nests an input of "${member.input.entity.name}", but "${member.relation.key}" is of "${member.relation.target().name}"`);
595
- return member;
596
- });
597
- return Object.freeze({
598
- entity,
599
- schema,
600
- members: Object.freeze(members)
601
- });
602
- },
603
- /** For an input key that is about the operation rather than the Entity. */
604
- unmapped,
605
- /**
606
- * The schemas of some of an Entity's fields, by key, to spread into an input's
607
- * struct: `Schema.Struct({ ...Entity.fields(Post, 'id', 'title'), editorId: ... })`.
608
- * The input then keeps the field's own rules, and its keys map themselves.
609
- */
610
- fields: (entity, ...keys) => Object.fromEntries(keys.map((key) => [key, (own(entity.fields, key) ?? fail(entity, `"${key}" is not a field`)).schema])),
611
- /**
612
- * The Selection of every member an input writes, with each relation as refs:
613
- * what an edit screen loads before it shows the input's current values.
614
- */
615
- selectFor: (input) => {
616
- const members = input.members;
617
- const spec = Object.fromEntries(Object.values(members).flatMap((member) => member._tag === "Field" ? [[member.key, true]] : member._tag === "RelationInput" ? [[member.relation.key, true]] : member._tag === "NestedInput" ? [[member.relation.key, Entity.selectFor(member.input)]] : []));
618
- return Entity.select(input.entity, spec);
619
- },
620
- /**
621
- * The input values that reproduce `value`, a value read through `selectFor`
622
- * (or any Selection with those members): a field as it is, a relation as the
623
- * id or ids of its refs. A key whose member `value` lacks is left out, as is
624
- * an unmapped key, which the Entity knows nothing about.
625
- */
626
- valuesFor: (input, value) => {
627
- const members = input.members;
628
- const idOf = (held) => held === null ? null : typeof held === "object" && "id" in held ? held.id : typeof held === "string" ? held : void 0;
629
- const entries = Object.entries(members).flatMap(([key, member]) => {
630
- if (member._tag === "Unmapped") return [];
631
- const written = member._tag === "Field" ? member.key : member.relation.key;
632
- if (!(written in value)) return [];
633
- const read = value[written];
634
- switch (member._tag) {
635
- case "Field": return [[key, read]];
636
- case "NestedInput": {
637
- const nested = (held) => typeof held === "object" && held !== null ? Entity.valuesFor(member.input, held) : null;
638
- return [[key, Array.isArray(read) ? read.map(nested) : nested(read)]];
639
- }
640
- case "RelationInput": {
641
- const ids = Array.isArray(read) ? read.map(idOf) : idOf(read);
642
- return (Array.isArray(ids) ? !ids.includes(void 0) : ids !== void 0) ? [[key, ids]] : [];
643
- }
644
- }
645
- });
646
- return Object.fromEntries(entries);
647
- },
648
- is: isEntity,
649
- /** True when both descriptors are versions of one Entity. */
650
- same: isSameEntity
651
- };
652
- function one(target, options) {
653
- return {
654
- target,
655
- cardinality: "one",
656
- optional: options?.optional ?? false
657
- };
658
- }
659
- /** What the owner sees: one or many of `target`. Used inside `Entity.relate`. */
660
- const Relation = {
661
- one,
662
- /** For `Entity.input`: the input key holds this relation's target id, or ids for a `many`. */
663
- input: (relation) => Object.freeze({
664
- _tag: "RelationInput",
665
- relation
666
- }),
667
- /**
668
- * For `Entity.input`: the input key holds the relation's target itself, written
669
- * through `input`, an `Entity.input` of the target. A `many` holds a list.
670
- */
671
- nested: (relation, input) => Object.freeze({
672
- _tag: "NestedInput",
673
- relation,
674
- input
675
- }),
676
- many: (target) => ({
677
- target,
678
- cardinality: "many",
679
- optional: false
680
- })
681
- };
682
- /** A count: never negative, never a fraction. */
683
- const CountSchema = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0));
684
- /** The id of the row an exists found, as every Remote id is held: text, or none. */
685
- const WitnessSchema = Schema.OptionFromNullOr(Schema.String);
686
- const Derived = {
687
- /**
688
- * A member only an interpreter can compute, of type `schema`: it supplies the
689
- * value. `predict` says how a client foresees it for a row it writes (Guard's
690
- * `may`); without it the row reads as missing the member until the answer.
691
- * `forbids` says which write to the row its value refuses (Guard's `may`
692
- * again), so a client holding it refuses that write where it is made.
693
- */
694
- make: (schema, options = {}) => ({
695
- schema,
696
- derives: Derivation.Supplied({
697
- predict: Option.fromUndefinedOr(options.predict),
698
- forbids: Option.fromUndefinedOr(options.forbids)
699
- })
700
- }),
701
- /**
702
- * How many rows point at this one through `relation`, a `one` relation of
703
- * the counted Entity: `likeCount: Derived.count(Like.relations.post)` on
704
- * Post. Added after `Entity.relate`, which makes the relation. A server
705
- * compiles it from the relation's storage, and a client predicts it from
706
- * the rows a pending write inserts, deletes or points elsewhere.
707
- */
708
- count: (relation) => ({
709
- schema: CountSchema,
710
- derives: Derivation.Count({ relation })
711
- }),
712
- /**
713
- * Whether a row points at this one through `relation` and at whoever reads
714
- * it through `viewer`, another `one` relation of the same pointing Entity:
715
- * `liked: Derived.exists(Like.relations.post, { viewer: Like.relations.user })`
716
- * on Post. Its value is that row's id as the store holds it, or none, so the
717
- * reader can take it back (`Write.delete` by that id). It depends on who
718
- * reads it: a server answers it for the principal it reads as, and a client
719
- * predicts it for the viewer it is told of.
720
- */
721
- exists: (relation, options) => ({
722
- schema: WitnessSchema,
723
- derives: Derivation.Exists({
724
- relation,
725
- viewer: options.viewer
726
- })
727
- })
728
- };
729
- export { Relation as a, check as c, judge as d, judgeAgainst as f, EntityTypeId as i, invariant as l, readsBefore as m, Derived as n, SelectionPageTypeId as o, judgeInput as p, Entity as r, SelectionTypeId as s, Derivation as t, invariantsOf as u };
730
-
731
- //# sourceMappingURL=src-DKhUqLoC.js.map