@latticecms/core 0.0.0 → 0.2.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 (113) hide show
  1. package/README.md +1297 -2
  2. package/dist/access.d.ts +209 -0
  3. package/dist/access.d.ts.map +1 -0
  4. package/dist/access.js +241 -0
  5. package/dist/access.js.map +1 -0
  6. package/dist/build.d.ts +555 -0
  7. package/dist/build.d.ts.map +1 -0
  8. package/dist/build.js +655 -0
  9. package/dist/build.js.map +1 -0
  10. package/dist/collection.d.ts +480 -0
  11. package/dist/collection.d.ts.map +1 -0
  12. package/dist/collection.js +351 -0
  13. package/dist/collection.js.map +1 -0
  14. package/dist/crud.d.ts +46 -0
  15. package/dist/crud.d.ts.map +1 -0
  16. package/dist/crud.js +527 -0
  17. package/dist/crud.js.map +1 -0
  18. package/dist/describe.d.ts +89 -0
  19. package/dist/describe.d.ts.map +1 -0
  20. package/dist/describe.js +119 -0
  21. package/dist/describe.js.map +1 -0
  22. package/dist/errors.d.ts +183 -0
  23. package/dist/errors.d.ts.map +1 -0
  24. package/dist/errors.js +150 -0
  25. package/dist/errors.js.map +1 -0
  26. package/dist/family.d.ts +80 -0
  27. package/dist/family.d.ts.map +1 -0
  28. package/dist/family.js +227 -0
  29. package/dist/family.js.map +1 -0
  30. package/dist/index.d.ts +14 -0
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.js +10 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/marker.d.ts +15 -0
  35. package/dist/marker.d.ts.map +1 -0
  36. package/dist/marker.js +28 -0
  37. package/dist/marker.js.map +1 -0
  38. package/dist/mask.d.ts +69 -0
  39. package/dist/mask.d.ts.map +1 -0
  40. package/dist/mask.js +277 -0
  41. package/dist/mask.js.map +1 -0
  42. package/dist/populate.d.ts +39 -0
  43. package/dist/populate.d.ts.map +1 -0
  44. package/dist/populate.js +72 -0
  45. package/dist/populate.js.map +1 -0
  46. package/dist/relations.d.ts +144 -0
  47. package/dist/relations.d.ts.map +1 -0
  48. package/dist/relations.js +144 -0
  49. package/dist/relations.js.map +1 -0
  50. package/dist/repo.d.ts +99 -0
  51. package/dist/repo.d.ts.map +1 -0
  52. package/dist/repo.js +92 -0
  53. package/dist/repo.js.map +1 -0
  54. package/dist/sort.d.ts +86 -0
  55. package/dist/sort.d.ts.map +1 -0
  56. package/dist/sort.js +187 -0
  57. package/dist/sort.js.map +1 -0
  58. package/dist/store/conformance.d.ts +15 -0
  59. package/dist/store/conformance.d.ts.map +1 -0
  60. package/dist/store/conformance.js +811 -0
  61. package/dist/store/conformance.js.map +1 -0
  62. package/dist/store/index.d.ts +9 -0
  63. package/dist/store/index.d.ts.map +1 -0
  64. package/dist/store/index.js +8 -0
  65. package/dist/store/index.js.map +1 -0
  66. package/dist/store.d.ts +119 -0
  67. package/dist/store.d.ts.map +1 -0
  68. package/dist/store.js +176 -0
  69. package/dist/store.js.map +1 -0
  70. package/dist/tenancy.d.ts +66 -0
  71. package/dist/tenancy.d.ts.map +1 -0
  72. package/dist/tenancy.js +69 -0
  73. package/dist/tenancy.js.map +1 -0
  74. package/dist/tracing.d.ts +12 -0
  75. package/dist/tracing.d.ts.map +1 -0
  76. package/dist/tracing.js +27 -0
  77. package/dist/tracing.js.map +1 -0
  78. package/dist/where.d.ts +95 -0
  79. package/dist/where.d.ts.map +1 -0
  80. package/dist/where.js +308 -0
  81. package/dist/where.js.map +1 -0
  82. package/package.json +80 -2
  83. package/skills/lattice/SKILL.md +106 -0
  84. package/skills/lattice/references/access.md +90 -0
  85. package/skills/lattice/references/cli.md +87 -0
  86. package/skills/lattice/references/collection.md +94 -0
  87. package/skills/lattice/references/event-handler.md +88 -0
  88. package/skills/lattice/references/masking.md +72 -0
  89. package/skills/lattice/references/method.md +88 -0
  90. package/skills/lattice/references/override.md +160 -0
  91. package/skills/lattice/references/relations.md +91 -0
  92. package/skills/lattice/references/tenancy.md +82 -0
  93. package/skills/lattice/references/testing.md +75 -0
  94. package/src/access.ts +449 -0
  95. package/src/build.ts +1888 -0
  96. package/src/collection.ts +1025 -0
  97. package/src/crud.ts +797 -0
  98. package/src/describe.ts +232 -0
  99. package/src/errors.ts +174 -0
  100. package/src/family.ts +334 -0
  101. package/src/index.ts +44 -0
  102. package/src/marker.ts +54 -0
  103. package/src/mask.ts +336 -0
  104. package/src/populate.ts +103 -0
  105. package/src/relations.ts +370 -0
  106. package/src/repo.ts +218 -0
  107. package/src/sort.ts +271 -0
  108. package/src/store/conformance.ts +1179 -0
  109. package/src/store/index.ts +22 -0
  110. package/src/store.ts +315 -0
  111. package/src/tenancy.ts +124 -0
  112. package/src/tracing.ts +29 -0
  113. package/src/where.ts +463 -0
package/src/crud.ts ADDED
@@ -0,0 +1,797 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import type { z } from 'zod';
3
+ import { CallAccess } from './access.js';
4
+ import type {
5
+ Action,
6
+ AnyCollection,
7
+ AnyRelation,
8
+ ChangeArgs,
9
+ Data,
10
+ Document,
11
+ Events,
12
+ Operations,
13
+ } from './collection.js';
14
+ import { maxLinks } from './collection.js';
15
+ import { LatticeError, parse } from './errors.js';
16
+ import type { Family, FamilyContext } from './family.js';
17
+ import { refuseWithheld } from './mask.js';
18
+ import { linkFields, type PopulateInput } from './populate.js';
19
+ import type { Referrers, RefField } from './relations.js';
20
+ import { findQuery, stamped, touched } from './repo.js';
21
+ import type { CollectionStore, StoredDoc } from './store.js';
22
+ import { tenantClause, withoutTenant } from './tenancy.js';
23
+ import { type AnyWhere, both } from './where.js';
24
+
25
+ type AnyShape = z.core.$ZodShape;
26
+
27
+ // The payload of each event. AnyCollection's event classes take any payload,
28
+ // so each one is checked against its schema type with `satisfies`.
29
+ type Payload<Name extends keyof Events<string, AnyShape>> = InstanceType<
30
+ Events<string, AnyShape>[Name]
31
+ >['payload'];
32
+
33
+ /** A use case as build() calls it. */
34
+ export type Executable<Ctx> = {
35
+ execute(ctx: Ctx, input: unknown): Promise<unknown>;
36
+ };
37
+
38
+ /**
39
+ * The app's event publisher, such as app-template's `DomainEventPublisher`.
40
+ * `publish` is a method signature, so its parameter is bivariant: a publisher
41
+ * typed by any catalog fits here. `.collection()` checks that it takes that
42
+ * collection's events.
43
+ */
44
+ export type EventPublisher = { publish(event: object): Promise<void> };
45
+
46
+ /** What one generated call works with. */
47
+ type Call = {
48
+ readonly store: CollectionStore;
49
+ readonly events: EventPublisher;
50
+ readonly collection: AnyCollection;
51
+ readonly ops: Operations<AnyShape>;
52
+ /** The access and tenant filter of this call, for every store call. */
53
+ readonly scope: AnyWhere | undefined;
54
+ /** What a read's `populate` may name: the schema of that one field. */
55
+ readonly populate: PopulateInput;
56
+ readonly actorId: string;
57
+ /** The call's tenant on this collection: what create stamps and events carry. */
58
+ readonly tenantId: string | undefined;
59
+ /** Who refers to each collection, for onDelete. */
60
+ readonly referrers: Referrers;
61
+ /** The call's access, for the collections a read populates. */
62
+ readonly access: CallAccess;
63
+ /** Every collection, by slug: what a populated ref reads. */
64
+ readonly collections: ReadonlyMap<string, AnyCollection>;
65
+ };
66
+
67
+ /**
68
+ * The filter that limits what a call may see and change (0005): the call's
69
+ * access scope. Asked here, so a body called from another operation's
70
+ * override is still checked (0036); after the family's guard, it reads the
71
+ * kept answer. Create has no row to filter: its body asks with its data.
72
+ */
73
+ async function scopeOf(
74
+ ctx: FamilyContext<unknown>,
75
+ collection: AnyCollection,
76
+ action: Action,
77
+ ): Promise<AnyWhere | undefined> {
78
+ if (action === 'create') return undefined;
79
+ return (await ctx.access.scope(collection, action)).where;
80
+ }
81
+
82
+ /** `tenantId` for an event payload, on a tenanted collection only. */
83
+ function tenantPayload(call: Call): { tenantId?: string } {
84
+ return call.tenantId === undefined ? {} : { tenantId: call.tenantId };
85
+ }
86
+
87
+ function notFound(call: Call, id: string) {
88
+ return LatticeError.NOT_FOUND({ collection: call.collection.slug, id });
89
+ }
90
+
91
+ /** A stored doc as the collection's document type: it has its timestamps. */
92
+ function documentOf(
93
+ call: Pick<Call, 'collection'>,
94
+ doc: StoredDoc,
95
+ ): Document<AnyShape> {
96
+ const { createdAt, updatedAt } = doc;
97
+ if (typeof createdAt !== 'string' || typeof updatedAt !== 'string') {
98
+ throw new Error(
99
+ `Lattice: "${call.collection.slug}.${doc.id}" has no createdAt or updatedAt`,
100
+ );
101
+ }
102
+ return { ...doc, createdAt, updatedAt };
103
+ }
104
+
105
+ /** A document's own tenant, for a tenanted collection. */
106
+ function tenantOfDoc(
107
+ collection: AnyCollection,
108
+ doc: StoredDoc,
109
+ ): string | undefined {
110
+ const value =
111
+ collection.tenant === undefined ? undefined : doc[collection.tenant];
112
+ return typeof value === 'string' ? value : undefined;
113
+ }
114
+
115
+ /** A document of a collection, in a delete's plan. */
116
+ type Node = { readonly collection: AnyCollection; readonly doc: StoredDoc };
117
+
118
+ /** What a delete will do, decided before it writes anything. */
119
+ type Plan = {
120
+ /** Cascaded documents, in the order found: parents before children. */
121
+ readonly deletes: Node[];
122
+ /** Documents whose ref to a deleted one is cleared. */
123
+ readonly nullifies: (Node & {
124
+ readonly ref: RefField;
125
+ readonly id: string;
126
+ })[];
127
+ };
128
+
129
+ function keyOf(node: Node): string {
130
+ return JSON.stringify([node.collection.slug, node.doc.id]);
131
+ }
132
+
133
+ /** Every document of `collection` matching `where`, page by page. */
134
+ async function* every(
135
+ store: CollectionStore,
136
+ collection: AnyCollection,
137
+ where: AnyWhere,
138
+ ): AsyncGenerator<StoredDoc> {
139
+ let after: string | undefined;
140
+ do {
141
+ const page = await store.find(
142
+ findQuery(collection, { where, sort: ['id'], limit: 100, after }),
143
+ );
144
+ yield* page.docs;
145
+ after = page.next ?? undefined;
146
+ } while (after !== undefined);
147
+ }
148
+
149
+ /**
150
+ * The onDelete plan of deleting `root`, through every ref to it, and to
151
+ * each cascaded document in turn. Restrict throws REFERENCED here, before
152
+ * anything is written. These are system steps: they skip access functions,
153
+ * but each carries the tenant of the document it starts from, so a row of
154
+ * another tenant that stores this id is neither counted nor touched. A
155
+ * global document's children are found across tenants.
156
+ */
157
+ async function planDelete(
158
+ store: CollectionStore,
159
+ referrers: Referrers,
160
+ root: Node,
161
+ ): Promise<Plan> {
162
+ const plan: Plan = { deletes: [], nullifies: [] };
163
+ const visited = new Set([keyOf(root)]);
164
+ const queue: Node[] = [root];
165
+ for (let node = queue.shift(); node !== undefined; node = queue.shift()) {
166
+ const { id } = node.doc;
167
+ const tenantId = tenantOfDoc(node.collection, node.doc);
168
+ for (const { collection, ref, relation } of referrers.get(
169
+ node.collection.slug,
170
+ ) ?? []) {
171
+ const where =
172
+ both(
173
+ { [ref.field]: ref.array ? { has: id } : { eq: id } },
174
+ tenantClause(collection, tenantId),
175
+ ) ?? {};
176
+ if (ref.onDelete === 'restrict') {
177
+ if ((await store.count(collection.slug, where)) > 0) {
178
+ throw LatticeError.REFERENCED({
179
+ collection: node.collection.slug,
180
+ id,
181
+ by: {
182
+ collection: collection.slug,
183
+ field: ref.field,
184
+ ...(relation === undefined ? {} : { relation }),
185
+ },
186
+ });
187
+ }
188
+ continue;
189
+ }
190
+ for await (const doc of every(store, collection, where)) {
191
+ const child = { collection, doc };
192
+ if (ref.onDelete === 'nullify') {
193
+ plan.nullifies.push({ ...child, ref, id });
194
+ } else if (!visited.has(keyOf(child))) {
195
+ // A cycle meets a document already planned: stop there.
196
+ visited.add(keyOf(child));
197
+ plan.deletes.push(child);
198
+ queue.push(child);
199
+ }
200
+ }
201
+ }
202
+ }
203
+ return plan;
204
+ }
205
+
206
+ /**
207
+ * Applies a plan in `store`, returning the events it owes. Clears refs
208
+ * first, then deletes the cascaded documents, the deepest first, so a
209
+ * store without transactions ends with the parent, deleted last by the
210
+ * caller.
211
+ */
212
+ async function applyPlan(
213
+ store: CollectionStore,
214
+ call: Pick<Call, 'actorId'>,
215
+ plan: Plan,
216
+ ): Promise<object[]> {
217
+ const events: object[] = [];
218
+ const deleted = new Set(plan.deletes.map(keyOf));
219
+ for (const { collection, doc, ref, id } of plan.nullifies) {
220
+ if (deleted.has(keyOf({ collection, doc }))) continue;
221
+ // Read again: an earlier step may have changed this document.
222
+ const current = await store.get(collection.slug, doc.id);
223
+ if (current === null) continue;
224
+ const value = current[ref.field];
225
+ const cleared = ref.array
226
+ ? Array.isArray(value)
227
+ ? value.filter((element) => element !== id)
228
+ : value
229
+ : ref.cleared;
230
+ const updated = await store.update(
231
+ collection.slug,
232
+ doc.id,
233
+ touched({ [ref.field]: cleared }),
234
+ );
235
+ if (updated === null) continue;
236
+ const tenantId = tenantOfDoc(collection, updated);
237
+ events.push(
238
+ new collection.events.updated({
239
+ doc: documentOf({ collection }, updated),
240
+ previous: documentOf({ collection }, current),
241
+ actorId: call.actorId,
242
+ ...(tenantId === undefined ? {} : { tenantId }),
243
+ } satisfies Payload<'updated'>),
244
+ );
245
+ }
246
+ for (const { collection, doc } of [...plan.deletes].reverse()) {
247
+ const removed = await store.remove(collection.slug, doc.id);
248
+ if (removed === null) continue;
249
+ const tenantId = tenantOfDoc(collection, removed);
250
+ events.push(
251
+ new collection.events.deleted({
252
+ doc: documentOf({ collection }, removed),
253
+ actorId: call.actorId,
254
+ ...(tenantId === undefined ? {} : { tenantId }),
255
+ } satisfies Payload<'deleted'>),
256
+ );
257
+ }
258
+ return events;
259
+ }
260
+
261
+ async function read(
262
+ call: Pick<Call, 'collection'>,
263
+ doc: StoredDoc,
264
+ ): Promise<Document<AnyShape>> {
265
+ const document = documentOf(call, doc);
266
+ const { afterRead } = call.collection;
267
+ return afterRead === undefined ? document : afterRead({ doc: document });
268
+ }
269
+
270
+ /** What populating a read works with. */
271
+ type Populating = Pick<Call, 'store' | 'access' | 'collections'>;
272
+
273
+ /** The ids a ref field holds: one, a list, or none. */
274
+ function idsIn(value: unknown): string[] {
275
+ return (Array.isArray(value) ? value : [value]).filter(
276
+ (id): id is string => typeof id === 'string',
277
+ );
278
+ }
279
+
280
+ /**
281
+ * The documents of `slug` among `ids` that the caller may read, by id: one
282
+ * getMany under the caller's read scope there, which carries the tenant,
283
+ * then each through its afterRead. A `false` read access withholds them
284
+ * all rather than failing the read that populates them.
285
+ */
286
+ async function readable(
287
+ call: Populating,
288
+ slug: string,
289
+ ids: readonly string[],
290
+ ): Promise<ReadonlyMap<string, Document<AnyShape>>> {
291
+ const collection = call.collections.get(slug);
292
+ if (collection === undefined) {
293
+ throw new Error(`Lattice: no collection "${slug}" to populate`);
294
+ }
295
+ const scope = await call.access.scope(collection, 'read').catch((error) => {
296
+ if (LatticeError.is(error) && error.code === 'FORBIDDEN') return null;
297
+ throw error;
298
+ });
299
+ if (scope === null) return new Map();
300
+ const stored = await call.store.getMany(slug, ids, scope.where);
301
+ return new Map(
302
+ await Promise.all(
303
+ stored.map(
304
+ async (doc): Promise<[string, Document<AnyShape>]> => [
305
+ doc.id,
306
+ await read({ collection }, doc),
307
+ ],
308
+ ),
309
+ ),
310
+ );
311
+ }
312
+
313
+ /**
314
+ * `docs` of `collection` with the ref fields in `keys` populated (0022).
315
+ * Ids are collected per target collection across all of `docs`, and each
316
+ * target is read once. A target the caller may not read, or one that no
317
+ * longer exists, is `{ id }`. A list of ids populates element-wise.
318
+ */
319
+ async function populated(
320
+ call: Populating,
321
+ collection: AnyCollection,
322
+ keys: readonly string[],
323
+ docs: readonly Document<AnyShape>[],
324
+ ): Promise<Document<AnyShape>[]> {
325
+ const refs = collection.refs.filter((ref) => keys.includes(ref.field));
326
+ if (refs.length === 0) return [...docs];
327
+ const wanted = new Map<string, Set<string>>();
328
+ for (const doc of docs) {
329
+ for (const ref of refs) {
330
+ const ids = wanted.get(ref.slug) ?? new Set();
331
+ for (const id of idsIn(doc[ref.field])) ids.add(id);
332
+ wanted.set(ref.slug, ids);
333
+ }
334
+ }
335
+ const found = new Map(
336
+ await Promise.all(
337
+ [...wanted].map(
338
+ async ([slug, ids]): Promise<
339
+ [string, ReadonlyMap<string, Document<AnyShape>>]
340
+ > => [slug, await readable(call, slug, [...ids])],
341
+ ),
342
+ ),
343
+ );
344
+ return docs.map((doc) => {
345
+ const next = { ...doc };
346
+ for (const ref of refs) {
347
+ const targets = found.get(ref.slug);
348
+ const swap = (id: unknown) =>
349
+ typeof id === 'string' ? (targets?.get(id) ?? { id }) : id;
350
+ const value = doc[ref.field];
351
+ next[ref.field] = Array.isArray(value) ? value.map(swap) : swap(value);
352
+ }
353
+ return next;
354
+ });
355
+ }
356
+
357
+ async function change(
358
+ call: Call,
359
+ args: ChangeArgs<AnyShape>,
360
+ ): Promise<Data<AnyShape>> {
361
+ const { beforeChange } = call.collection;
362
+ return beforeChange === undefined ? args.data : beforeChange(args);
363
+ }
364
+
365
+ /**
366
+ * Each operation's body. Each parses its own input: the family guard has
367
+ * rejected bad input, but hexok hands execute the raw value, so parsing here
368
+ * strips unknown keys and applies the create schema's defaults.
369
+ */
370
+ /*
371
+ * Each write publishes its event after the store write succeeds, so a failed
372
+ * write publishes nothing. A publish that fails reaches the caller although
373
+ * the write stays: the delivery gap architecture.md accepts until the outbox.
374
+ */
375
+ /**
376
+ * `document` with the `many()` relations in `keys` populated, as `get`
377
+ * does: each relation's links in one find on its join collection, inside
378
+ * the parent's tenant, then their targets in one getMany. `set` keeps a
379
+ * parent to at most 1000 links, so one find holds them all. The links run
380
+ * under the parent's read, as `list` does, which the get has passed.
381
+ */
382
+ async function withLinks(
383
+ call: Populating,
384
+ collection: AnyCollection,
385
+ keys: readonly string[],
386
+ parent: StoredDoc,
387
+ document: Document<AnyShape>,
388
+ ): Promise<Document<AnyShape>> {
389
+ const next = { ...document };
390
+ for (const [name, relation] of Object.entries(collection.relations)) {
391
+ if (!keys.includes(name)) continue;
392
+ const join = relation.through;
393
+ const where = both(
394
+ { [relation.parentField]: { eq: parent.id } },
395
+ tenantClause(join, tenantOfDoc(collection, parent)),
396
+ );
397
+ const { docs } = await call.store.find(
398
+ findQuery(join, { where, limit: maxLinks }),
399
+ );
400
+ const targets = await readable(
401
+ call,
402
+ relation.target,
403
+ docs.flatMap((link) => idsIn(link[relation.targetField])),
404
+ );
405
+ const fields = linkFields(relation);
406
+ next[name] = docs.map((link) => {
407
+ const id = link[relation.targetField];
408
+ return {
409
+ ...Object.fromEntries(
410
+ fields
411
+ .filter((field) => link[field] !== undefined)
412
+ .map((field) => [field, link[field]]),
413
+ ),
414
+ doc: typeof id === 'string' ? (targets.get(id) ?? { id }) : id,
415
+ };
416
+ });
417
+ }
418
+ return next;
419
+ }
420
+
421
+ const operations: Record<
422
+ Action,
423
+ (call: Call, raw: unknown) => Promise<unknown>
424
+ > = {
425
+ async find(call, raw) {
426
+ const { where, sort, limit, after } = parse(call.ops.find.input, raw);
427
+ await refuseWithheld(call.access, call.collection, 'find', raw);
428
+ const { populate = [] } = parse(call.populate, raw);
429
+ const page = await call.store.find(
430
+ findQuery(call.collection, {
431
+ where: both(where, call.scope),
432
+ sort,
433
+ limit,
434
+ after,
435
+ }),
436
+ );
437
+ const docs = await Promise.all(page.docs.map((doc) => read(call, doc)));
438
+ return {
439
+ docs: await populated(call, call.collection, populate, docs),
440
+ next: page.next,
441
+ };
442
+ },
443
+
444
+ async count(call, raw) {
445
+ const { where } = parse(call.ops.count.input, raw);
446
+ await refuseWithheld(call.access, call.collection, 'count', raw);
447
+ return {
448
+ count: await call.store.count(
449
+ call.collection.slug,
450
+ both(where, call.scope),
451
+ ),
452
+ };
453
+ },
454
+
455
+ async get(call, raw) {
456
+ const { id } = parse(call.ops.get.input, raw);
457
+ const { populate = [] } = parse(call.populate, raw);
458
+ const doc = await call.store.get(call.collection.slug, id, call.scope);
459
+ if (doc === null) throw notFound(call, id);
460
+ const [document] = await populated(call, call.collection, populate, [
461
+ await read(call, doc),
462
+ ]);
463
+ return document === undefined
464
+ ? document
465
+ : withLinks(call, call.collection, populate, doc, document);
466
+ },
467
+
468
+ async create(call, raw) {
469
+ const input = parse(call.ops.create.input, raw);
470
+ // Create has no scope to filter by, so its access is asked here, with
471
+ // the data it will write.
472
+ await call.access.scope(call.collection, 'create', input);
473
+ const data = await change(call, { data: input, operation: 'create' });
474
+ // Stamped after beforeChange, so a hook cannot pick the tenant.
475
+ const { tenant } = call.collection;
476
+ const doc = stamped(
477
+ tenant === undefined
478
+ ? data
479
+ : { ...withoutTenant(call.collection, data), [tenant]: call.tenantId },
480
+ );
481
+ await call.store.insert(call.collection.slug, doc);
482
+ await call.events.publish(
483
+ new call.collection.events.created({
484
+ doc,
485
+ actorId: call.actorId,
486
+ ...tenantPayload(call),
487
+ } satisfies Payload<'created'>),
488
+ );
489
+ return read(call, doc);
490
+ },
491
+
492
+ async update(call, raw) {
493
+ // The id schema types `id`; across all collections the patch schema is an
494
+ // index signature, which would type it unknown.
495
+ const { id } = parse(call.ops.get.input, raw);
496
+ const { id: _, ...patch } = parse(call.ops.update.input, raw);
497
+ await refuseWithheld(call.access, call.collection, 'update', patch);
498
+ const stored = await call.store.get(call.collection.slug, id, call.scope);
499
+ if (stored === null) throw notFound(call, id);
500
+ const previous = documentOf(call, stored);
501
+ // The tenant field is Lattice's, like the system fields: the schema does
502
+ // not have it, so leaving it in would read as a stored key to remove.
503
+ const { id: _id, createdAt, updatedAt, ...stamps } = previous;
504
+ const data = withoutTenant(call.collection, stamps);
505
+ // The merged document must pass the whole schema, as a create would, so
506
+ // an object-level refinement holds on update too. Parsing also drops
507
+ // stored keys the schema no longer has.
508
+ // A null on a field it clears removes the key (0035); a nullable field
509
+ // keeps its null as a value.
510
+ const { cleared } = call.ops.update;
511
+ const merged = parse(
512
+ call.ops.create.input,
513
+ Object.fromEntries(
514
+ Object.entries({ ...data, ...patch }).filter(
515
+ ([key, value]) => value !== null || !cleared.has(key),
516
+ ),
517
+ ),
518
+ );
519
+ // beforeChange sees the whole document after the change, as on create.
520
+ // A hook that returns the tenant field changes nothing: update never
521
+ // writes it.
522
+ const next = withoutTenant(
523
+ call.collection,
524
+ await change(call, { data: merged, operation: 'update', previous }),
525
+ );
526
+ // Only the fields that differ from the stored ones are written. A stored
527
+ // key that is gone from `next` (dropped by the schema or by the hook) is
528
+ // written as undefined, which the store removes.
529
+ const changes = Object.fromEntries(
530
+ Object.keys({ ...data, ...next })
531
+ .filter((key) => !isDeepStrictEqual(data[key], next[key]))
532
+ .map((key) => [key, next[key]]),
533
+ );
534
+ const updated = await call.store.update(
535
+ call.collection.slug,
536
+ id,
537
+ touched(changes),
538
+ call.scope,
539
+ );
540
+ if (updated === null) throw notFound(call, id);
541
+ await call.events.publish(
542
+ new call.collection.events.updated({
543
+ doc: documentOf(call, updated),
544
+ previous,
545
+ actorId: call.actorId,
546
+ ...tenantPayload(call),
547
+ } satisfies Payload<'updated'>),
548
+ );
549
+ return read(call, updated);
550
+ },
551
+
552
+ async delete(call, raw) {
553
+ const { id } = parse(call.ops.delete.input, raw);
554
+ const { slug } = call.collection;
555
+ // With refs to this collection, onDelete runs in one store transaction,
556
+ // and its events publish only after the commit (0028).
557
+ const { removed, owed } =
558
+ (call.referrers.get(slug) ?? []).length === 0
559
+ ? { removed: await call.store.remove(slug, id, call.scope), owed: [] }
560
+ : await call.store.transaction(async (store) => {
561
+ const doc = await store.get(slug, id, call.scope);
562
+ if (doc === null) throw notFound(call, id);
563
+ const plan = await planDelete(store, call.referrers, {
564
+ collection: call.collection,
565
+ doc,
566
+ });
567
+ const owed = await applyPlan(store, call, plan);
568
+ return { removed: await store.remove(slug, id, call.scope), owed };
569
+ });
570
+ if (removed === null) throw notFound(call, id);
571
+ for (const event of owed) await call.events.publish(event);
572
+ await call.events.publish(
573
+ new call.collection.events.deleted({
574
+ doc: documentOf(call, removed),
575
+ actorId: call.actorId,
576
+ ...tenantPayload(call),
577
+ } satisfies Payload<'deleted'>),
578
+ );
579
+ return read(call, removed);
580
+ },
581
+ };
582
+
583
+ /**
584
+ * What one generated operation does, from parsing its input to its events:
585
+ * the body its use case runs, and what an override's `generated` calls
586
+ * (0036). It runs no guards, logging or spans; the calling use case has.
587
+ */
588
+ export type Body<Ctx> = (ctx: Ctx, input: unknown) => Promise<unknown>;
589
+
590
+ /** The body of one generated operation. */
591
+ export function operationBody<Actor>(
592
+ family: Family<Actor>,
593
+ store: CollectionStore,
594
+ events: EventPublisher,
595
+ collection: AnyCollection,
596
+ ops: Operations<AnyShape>,
597
+ action: Action,
598
+ populate: PopulateInput,
599
+ referrers: Referrers,
600
+ collections: ReadonlyMap<string, AnyCollection>,
601
+ ): Body<FamilyContext<Actor>> {
602
+ const run = operations[action];
603
+ return async (ctx, raw) =>
604
+ run(
605
+ {
606
+ store,
607
+ events,
608
+ collection,
609
+ ops,
610
+ scope: await scopeOf(ctx, collection, action),
611
+ populate,
612
+ actorId: family.actorId(ctx.actor),
613
+ tenantId: CallAccess.stampOf(ctx.access, collection),
614
+ referrers,
615
+ access: ctx.access,
616
+ collections,
617
+ },
618
+ raw,
619
+ );
620
+ }
621
+
622
+ /**
623
+ * A generated use case, an operation's or a relation operation's, in the
624
+ * app's family: its guards, logging and span around `body`.
625
+ */
626
+ export function generatedUseCase<Actor>(
627
+ family: Family<Actor>,
628
+ token: string,
629
+ spec: {
630
+ readonly collection: AnyCollection;
631
+ readonly input: z.core.$ZodType;
632
+ readonly output: z.core.$ZodType;
633
+ },
634
+ body: Body<FamilyContext<Actor>>,
635
+ ): Executable<FamilyContext<Actor>> {
636
+ class Generated extends family(token, spec) {
637
+ async execute(ctx: FamilyContext<Actor>, raw: unknown): Promise<unknown> {
638
+ return body(ctx, raw);
639
+ }
640
+ }
641
+ return new Generated();
642
+ }
643
+
644
+ /**
645
+ * The body of a relation operation of `collection`: `<slug>.<name>.list` or
646
+ * `.set`. `list` runs the parent's read and `set` its update (0028): each
647
+ * first gets the parent under that scope, so a parent outside it is
648
+ * NOT_FOUND.
649
+ */
650
+ export function relationBody<Actor>(
651
+ family: Family<Actor>,
652
+ store: CollectionStore,
653
+ events: EventPublisher,
654
+ collection: AnyCollection,
655
+ name: string,
656
+ relation: AnyRelation,
657
+ op: 'list' | 'set',
658
+ collections: ReadonlyMap<string, AnyCollection>,
659
+ ): Body<FamilyContext<Actor>> {
660
+ const join = relation.through;
661
+ const { parentField, targetField } = relation;
662
+ // The fields of a link, as `set` compares them.
663
+ const linkFields = Object.keys(join.schema.shape).filter(
664
+ (field) => field !== parentField,
665
+ );
666
+
667
+ /** The parent under the scope of `action`, or NOT_FOUND. */
668
+ async function parentOf(ctx: FamilyContext<Actor>, id: string) {
669
+ const scope = await ctx.access.scope(collection, `${name}.${op}`);
670
+ const parent = await store.get(collection.slug, id, scope.where);
671
+ if (parent === null) {
672
+ throw LatticeError.NOT_FOUND({ collection: collection.slug, id });
673
+ }
674
+ return parent;
675
+ }
676
+
677
+ /** The links of `id`, inside the parent's tenant. */
678
+ function linksOf(id: string, tenantId: string | undefined): AnyWhere {
679
+ return (
680
+ both({ [parentField]: { eq: id } }, tenantClause(join, tenantId)) ?? {}
681
+ );
682
+ }
683
+
684
+ async function list(ctx: FamilyContext<Actor>, raw: unknown) {
685
+ const { id, where, sort, limit, after, populate } = parse(
686
+ relation.list.input,
687
+ raw,
688
+ );
689
+ const parent = await parentOf(ctx, id);
690
+ const page = await store.find(
691
+ findQuery(join, {
692
+ where: both(where, linksOf(id, tenantOfDoc(collection, parent))),
693
+ sort,
694
+ limit,
695
+ after,
696
+ }),
697
+ );
698
+ return {
699
+ docs: await populated(
700
+ { store, access: ctx.access, collections },
701
+ join,
702
+ populate ?? [],
703
+ page.docs.map((doc) => documentOf({ collection: join }, doc)),
704
+ ),
705
+ next: page.next,
706
+ };
707
+ }
708
+
709
+ async function set(ctx: FamilyContext<Actor>, raw: unknown) {
710
+ const { id, links } = parse(relation.set.input, raw);
711
+ const parent = await parentOf(ctx, id);
712
+ const tenantId = tenantOfDoc(collection, parent);
713
+ const actorId = family.actorId(ctx.actor);
714
+ const tenant = tenantId === undefined ? {} : { tenantId };
715
+ // The set replaces the links by diffing: an unchanged link keeps its id
716
+ // and createdAt, and each change owes its own event, after the commit.
717
+ const { docs, owed } = await store.transaction(async (tx) => {
718
+ const existing: StoredDoc[] = [];
719
+ for await (const doc of every(tx, join, linksOf(id, tenantId))) {
720
+ existing.push(doc);
721
+ }
722
+ const byTarget = new Map(existing.map((doc) => [doc[targetField], doc]));
723
+ const wanted = new Set(links.map((link) => link[targetField]));
724
+ const owed: object[] = [];
725
+ for (const doc of existing) {
726
+ if (wanted.has(doc[targetField])) continue;
727
+ const removed = await tx.remove(join.slug, doc.id);
728
+ if (removed === null) continue;
729
+ owed.push(
730
+ new join.events.deleted({
731
+ doc: documentOf({ collection: join }, removed),
732
+ actorId,
733
+ ...tenant,
734
+ } satisfies Payload<'deleted'>),
735
+ );
736
+ }
737
+ const docs: StoredDoc[] = [];
738
+ for (const link of links) {
739
+ const previous = byTarget.get(link[targetField]);
740
+ if (previous === undefined) {
741
+ const doc = stamped({
742
+ ...link,
743
+ [parentField]: id,
744
+ ...(join.tenant === undefined || tenantId === undefined
745
+ ? {}
746
+ : { [join.tenant]: tenantId }),
747
+ });
748
+ await tx.insert(join.slug, doc);
749
+ owed.push(
750
+ new join.events.created({
751
+ doc: documentOf({ collection: join }, doc),
752
+ actorId,
753
+ ...tenant,
754
+ } satisfies Payload<'created'>),
755
+ );
756
+ docs.push(doc);
757
+ continue;
758
+ }
759
+ // A field the new link leaves out is written as undefined, which
760
+ // the store removes.
761
+ const changes = Object.fromEntries(
762
+ linkFields
763
+ .filter((field) => !isDeepStrictEqual(previous[field], link[field]))
764
+ .map((field) => [field, link[field]]),
765
+ );
766
+ if (Object.keys(changes).length === 0) {
767
+ docs.push(previous);
768
+ continue;
769
+ }
770
+ const updated = await tx.update(
771
+ join.slug,
772
+ previous.id,
773
+ touched(changes),
774
+ );
775
+ if (updated === null) throw notFoundIn(join, previous.id);
776
+ owed.push(
777
+ new join.events.updated({
778
+ doc: documentOf({ collection: join }, updated),
779
+ previous: documentOf({ collection: join }, previous),
780
+ actorId,
781
+ ...tenant,
782
+ } satisfies Payload<'updated'>),
783
+ );
784
+ docs.push(updated);
785
+ }
786
+ return { docs, owed };
787
+ });
788
+ for (const event of owed) await events.publish(event);
789
+ return { docs: docs.map((doc) => documentOf({ collection: join }, doc)) };
790
+ }
791
+
792
+ return op === 'list' ? list : set;
793
+ }
794
+
795
+ function notFoundIn(collection: AnyCollection, id: string) {
796
+ return LatticeError.NOT_FOUND({ collection: collection.slug, id });
797
+ }