@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.
- package/README.md +1297 -2
- package/dist/access.d.ts +209 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +241 -0
- package/dist/access.js.map +1 -0
- package/dist/build.d.ts +555 -0
- package/dist/build.d.ts.map +1 -0
- package/dist/build.js +655 -0
- package/dist/build.js.map +1 -0
- package/dist/collection.d.ts +480 -0
- package/dist/collection.d.ts.map +1 -0
- package/dist/collection.js +351 -0
- package/dist/collection.js.map +1 -0
- package/dist/crud.d.ts +46 -0
- package/dist/crud.d.ts.map +1 -0
- package/dist/crud.js +527 -0
- package/dist/crud.js.map +1 -0
- package/dist/describe.d.ts +89 -0
- package/dist/describe.d.ts.map +1 -0
- package/dist/describe.js +119 -0
- package/dist/describe.js.map +1 -0
- package/dist/errors.d.ts +183 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +150 -0
- package/dist/errors.js.map +1 -0
- package/dist/family.d.ts +80 -0
- package/dist/family.d.ts.map +1 -0
- package/dist/family.js +227 -0
- package/dist/family.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/marker.d.ts +15 -0
- package/dist/marker.d.ts.map +1 -0
- package/dist/marker.js +28 -0
- package/dist/marker.js.map +1 -0
- package/dist/mask.d.ts +69 -0
- package/dist/mask.d.ts.map +1 -0
- package/dist/mask.js +277 -0
- package/dist/mask.js.map +1 -0
- package/dist/populate.d.ts +39 -0
- package/dist/populate.d.ts.map +1 -0
- package/dist/populate.js +72 -0
- package/dist/populate.js.map +1 -0
- package/dist/relations.d.ts +144 -0
- package/dist/relations.d.ts.map +1 -0
- package/dist/relations.js +144 -0
- package/dist/relations.js.map +1 -0
- package/dist/repo.d.ts +99 -0
- package/dist/repo.d.ts.map +1 -0
- package/dist/repo.js +92 -0
- package/dist/repo.js.map +1 -0
- package/dist/sort.d.ts +86 -0
- package/dist/sort.d.ts.map +1 -0
- package/dist/sort.js +187 -0
- package/dist/sort.js.map +1 -0
- package/dist/store/conformance.d.ts +15 -0
- package/dist/store/conformance.d.ts.map +1 -0
- package/dist/store/conformance.js +811 -0
- package/dist/store/conformance.js.map +1 -0
- package/dist/store/index.d.ts +9 -0
- package/dist/store/index.d.ts.map +1 -0
- package/dist/store/index.js +8 -0
- package/dist/store/index.js.map +1 -0
- package/dist/store.d.ts +119 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +176 -0
- package/dist/store.js.map +1 -0
- package/dist/tenancy.d.ts +66 -0
- package/dist/tenancy.d.ts.map +1 -0
- package/dist/tenancy.js +69 -0
- package/dist/tenancy.js.map +1 -0
- package/dist/tracing.d.ts +12 -0
- package/dist/tracing.d.ts.map +1 -0
- package/dist/tracing.js +27 -0
- package/dist/tracing.js.map +1 -0
- package/dist/where.d.ts +95 -0
- package/dist/where.d.ts.map +1 -0
- package/dist/where.js +308 -0
- package/dist/where.js.map +1 -0
- package/package.json +80 -2
- package/skills/lattice/SKILL.md +106 -0
- package/skills/lattice/references/access.md +90 -0
- package/skills/lattice/references/cli.md +87 -0
- package/skills/lattice/references/collection.md +94 -0
- package/skills/lattice/references/event-handler.md +88 -0
- package/skills/lattice/references/masking.md +72 -0
- package/skills/lattice/references/method.md +88 -0
- package/skills/lattice/references/override.md +160 -0
- package/skills/lattice/references/relations.md +91 -0
- package/skills/lattice/references/tenancy.md +82 -0
- package/skills/lattice/references/testing.md +75 -0
- package/src/access.ts +449 -0
- package/src/build.ts +1888 -0
- package/src/collection.ts +1025 -0
- package/src/crud.ts +797 -0
- package/src/describe.ts +232 -0
- package/src/errors.ts +174 -0
- package/src/family.ts +334 -0
- package/src/index.ts +44 -0
- package/src/marker.ts +54 -0
- package/src/mask.ts +336 -0
- package/src/populate.ts +103 -0
- package/src/relations.ts +370 -0
- package/src/repo.ts +218 -0
- package/src/sort.ts +271 -0
- package/src/store/conformance.ts +1179 -0
- package/src/store/index.ts +22 -0
- package/src/store.ts +315 -0
- package/src/tenancy.ts +124 -0
- package/src/tracing.ts +29 -0
- package/src/where.ts +463 -0
|
@@ -0,0 +1,1025 @@
|
|
|
1
|
+
import { Event, type EventCatalog } from 'hexok';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { type Label, labelOf } from './describe.js';
|
|
4
|
+
import { maskShapes } from './mask.js';
|
|
5
|
+
import {
|
|
6
|
+
type AnyMany,
|
|
7
|
+
type JoinShape,
|
|
8
|
+
joinSchemas,
|
|
9
|
+
type LinkShape,
|
|
10
|
+
type Many,
|
|
11
|
+
type ManyOnDelete,
|
|
12
|
+
type RefCheck,
|
|
13
|
+
type RefField,
|
|
14
|
+
refsOf,
|
|
15
|
+
} from './relations.js';
|
|
16
|
+
import { defaultLimit, maxLimit, sortSchema } from './sort.js';
|
|
17
|
+
import type { Index } from './store.js';
|
|
18
|
+
import { tenantShapes } from './tenancy.js';
|
|
19
|
+
import { type AnyWhere, innerOf, whereSchema, wrapperOf } from './where.js';
|
|
20
|
+
|
|
21
|
+
/** The operations Lattice generates for every collection. */
|
|
22
|
+
export type Action = 'find' | 'count' | 'get' | 'create' | 'update' | 'delete';
|
|
23
|
+
|
|
24
|
+
const systemShape = {
|
|
25
|
+
id: z.string(),
|
|
26
|
+
// ISO 8601 strings, not Date: ts-pf sends JSON, so a Date would reach an
|
|
27
|
+
// HTTP client as a string while its type still said Date.
|
|
28
|
+
createdAt: z.iso.datetime(),
|
|
29
|
+
updatedAt: z.iso.datetime(),
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// Only `z.object()`: unknown keys are stripped. A loose object would let any
|
|
33
|
+
// key into the store, and its index signature would reach every client type.
|
|
34
|
+
type Schema<Shape extends z.core.$ZodShape> = z.ZodObject<Shape, z.core.$strip>;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A patch field: optional, and also nullable when null clears the field,
|
|
38
|
+
* as `clears` decides at runtime.
|
|
39
|
+
*/
|
|
40
|
+
type PatchField<S extends z.core.$ZodType> = S extends {
|
|
41
|
+
_zod: { optout: 'optional' };
|
|
42
|
+
}
|
|
43
|
+
? null extends z.output<S>
|
|
44
|
+
? z.ZodOptional<S>
|
|
45
|
+
: z.ZodOptional<z.ZodNullable<S>>
|
|
46
|
+
: z.ZodOptional<S>;
|
|
47
|
+
|
|
48
|
+
// The shape `schema.partial().extend({ id })` would have, as Zod types it,
|
|
49
|
+
// with null on each field it clears.
|
|
50
|
+
type PatchShape<Shape extends z.core.$ZodShape> = z.core.util.Extend<
|
|
51
|
+
{ -readonly [K in keyof Shape]: PatchField<Shape[K]> },
|
|
52
|
+
{ id: z.ZodString }
|
|
53
|
+
>;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* A schema with its `default` and `prefault` wrappers removed, wherever they
|
|
57
|
+
* sit in its wrapper chain. Every other wrapper is kept around the stripped
|
|
58
|
+
* inner schema.
|
|
59
|
+
*/
|
|
60
|
+
function withoutDefault(schema: z.core.$ZodType): z.core.$ZodType {
|
|
61
|
+
const wrapper = wrapperOf(schema);
|
|
62
|
+
if (wrapper === undefined) return schema;
|
|
63
|
+
const inner = withoutDefault(wrapper.inner);
|
|
64
|
+
return schema instanceof z.core.$ZodDefault ||
|
|
65
|
+
schema instanceof z.core.$ZodPrefault
|
|
66
|
+
? inner
|
|
67
|
+
: wrapper.around(inner);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Whether null in a patch clears `field` (0035): an optional field with no
|
|
72
|
+
* default, whose schema refuses null. A nullable field stores null instead,
|
|
73
|
+
* and a required or defaulted one refuses it.
|
|
74
|
+
*/
|
|
75
|
+
function clears(field: z.core.$ZodType): boolean {
|
|
76
|
+
return field._zod.optout === 'optional' && !z.safeParse(field, null).success;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The update input: `id` and every field optional, with no defaults, and
|
|
81
|
+
* null on each field it clears. Zod 4's `.partial()` keeps `default` and
|
|
82
|
+
* `prefault`, even inside `.optional()`, so a patch that omits a defaulted
|
|
83
|
+
* field would reset it. Each field is rebuilt without them. The overload
|
|
84
|
+
* states the type; the implementation rebuilds the shape in a loop, which a
|
|
85
|
+
* mapped type cannot express.
|
|
86
|
+
*/
|
|
87
|
+
function patchSchema<Shape extends z.core.$ZodShape>(
|
|
88
|
+
schema: Schema<Shape>,
|
|
89
|
+
): z.ZodObject<PatchShape<Shape>, z.core.$strip>;
|
|
90
|
+
function patchSchema(schema: z.ZodObject): z.ZodObject {
|
|
91
|
+
return z.object({
|
|
92
|
+
...Object.fromEntries(
|
|
93
|
+
Object.entries(schema.shape).map(([name, field]) => {
|
|
94
|
+
const inner = withoutDefault(field);
|
|
95
|
+
return [name, z.optional(clears(field) ? z.nullable(inner) : inner)];
|
|
96
|
+
}),
|
|
97
|
+
),
|
|
98
|
+
id: z.string(),
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The fields a patch's null clears: update removes their keys. */
|
|
103
|
+
function clearedFields(schema: z.ZodObject): ReadonlySet<string> {
|
|
104
|
+
return new Set(
|
|
105
|
+
Object.entries(schema.shape)
|
|
106
|
+
.filter(([, field]) => clears(field))
|
|
107
|
+
.map(([name]) => name),
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The fields Lattice adds to a collection's schema: system and tenant. */
|
|
112
|
+
type Stamped<Tenant extends string> = typeof systemShape &
|
|
113
|
+
Record<Tenant, z.ZodString>;
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* The stored document's schema, as zod's `extend` types it. It is named, not
|
|
117
|
+
* inferred from `outputOf`: declaration emit spells an inferred type out,
|
|
118
|
+
* dropping zod's `Extend` alias, and the spelled-out form of a join
|
|
119
|
+
* collection's output no longer fits `AnyCollection` in the published .d.ts.
|
|
120
|
+
*/
|
|
121
|
+
type Output<
|
|
122
|
+
Shape extends z.core.$ZodShape,
|
|
123
|
+
Tenant extends string,
|
|
124
|
+
> = z.ZodObject<
|
|
125
|
+
z.core.util.Extend<Shape, z.core.util.Writeable<Stamped<Tenant>>>,
|
|
126
|
+
z.core.$strip
|
|
127
|
+
>;
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The stored document's schema: the schema's fields plus the system and
|
|
131
|
+
* tenant fields. Built from the shape, so an output never carries the
|
|
132
|
+
* schema's object-level refinements: they check input, and Zod 4 refuses to
|
|
133
|
+
* overwrite a key of a refined object, which a populated read and a masked
|
|
134
|
+
* field both do.
|
|
135
|
+
*/
|
|
136
|
+
function outputOf<Shape extends z.core.$ZodShape, Tenant extends string>(
|
|
137
|
+
shape: Shape,
|
|
138
|
+
tenant: Tenant | undefined,
|
|
139
|
+
): Output<Shape, Tenant> {
|
|
140
|
+
// Typed, so `extend` infers `Stamped<Tenant>` itself: an anonymous spread
|
|
141
|
+
// type would make an `Extend` the compiler cannot relate to `Output`.
|
|
142
|
+
const stamped: Stamped<Tenant> = {
|
|
143
|
+
...systemShape,
|
|
144
|
+
...tenantShapes(tenant).field,
|
|
145
|
+
};
|
|
146
|
+
return z.object(shape).extend(stamped);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* The document a client receives: `Output`, with each maskable field
|
|
151
|
+
* optional, since a caller's rules may withhold it. One mapped type over the
|
|
152
|
+
* output's own shape, so the stored output's type is computed once. The same
|
|
153
|
+
* type as `Output` when nothing is maskable.
|
|
154
|
+
*/
|
|
155
|
+
export type ClientOutput<
|
|
156
|
+
Shape extends z.core.$ZodShape,
|
|
157
|
+
Tenant extends string,
|
|
158
|
+
M extends string,
|
|
159
|
+
> = [M] extends [never]
|
|
160
|
+
? Output<Shape, Tenant>
|
|
161
|
+
: // Inline, not MaskShape: an app's declarations then name only what
|
|
162
|
+
// core exports (TS2883).
|
|
163
|
+
z.ZodObject<
|
|
164
|
+
{
|
|
165
|
+
[K in keyof Output<Shape, Tenant>['shape']]: K extends M
|
|
166
|
+
? z.ZodOptional<Output<Shape, Tenant>['shape'][K]>
|
|
167
|
+
: Output<Shape, Tenant>['shape'][K];
|
|
168
|
+
},
|
|
169
|
+
z.core.$strip
|
|
170
|
+
>;
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* A collection's two output schemas. Each maskable field is a marked clone,
|
|
174
|
+
* required in `output` and optional in `clientOutput`, so a router can find
|
|
175
|
+
* it in any output built from either. The overload states their types; the
|
|
176
|
+
* implementation builds them for any shape.
|
|
177
|
+
*/
|
|
178
|
+
function outputsOf<
|
|
179
|
+
Shape extends z.core.$ZodShape,
|
|
180
|
+
Tenant extends string,
|
|
181
|
+
M extends string,
|
|
182
|
+
>(
|
|
183
|
+
slug: string,
|
|
184
|
+
schema: Schema<Shape>,
|
|
185
|
+
tenant: Tenant | undefined,
|
|
186
|
+
maskable: readonly M[],
|
|
187
|
+
): {
|
|
188
|
+
readonly output: Output<Shape, Tenant>;
|
|
189
|
+
readonly clientOutput: ClientOutput<Shape, Tenant, M>;
|
|
190
|
+
};
|
|
191
|
+
function outputsOf(
|
|
192
|
+
slug: string,
|
|
193
|
+
schema: z.ZodObject,
|
|
194
|
+
tenant: string | undefined,
|
|
195
|
+
maskable: readonly string[],
|
|
196
|
+
): { readonly output: z.ZodObject; readonly clientOutput: z.ZodObject } {
|
|
197
|
+
if (maskable.length === 0) {
|
|
198
|
+
const output = outputOf(schema.shape, tenant);
|
|
199
|
+
return { output, clientOutput: output };
|
|
200
|
+
}
|
|
201
|
+
const { stored, client } = maskShapes(slug, schema.shape, maskable);
|
|
202
|
+
return {
|
|
203
|
+
output: outputOf({ ...schema.shape, ...stored }, tenant),
|
|
204
|
+
clientOutput: outputOf({ ...schema.shape, ...client }, tenant),
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The input and output schema of each generated operation, from the
|
|
210
|
+
* collection's schema and its output. The output has the tenant field;
|
|
211
|
+
* create and update input never do, so a client cannot set or change it.
|
|
212
|
+
*/
|
|
213
|
+
export function operations<
|
|
214
|
+
Shape extends z.core.$ZodShape,
|
|
215
|
+
Tenant extends string = never,
|
|
216
|
+
>(schema: Schema<Shape>, output: Output<Shape, Tenant>) {
|
|
217
|
+
const id = z.object({ id: z.string() });
|
|
218
|
+
return {
|
|
219
|
+
find: {
|
|
220
|
+
input: z.object({
|
|
221
|
+
where: whereSchema(output).optional(),
|
|
222
|
+
sort: sortSchema(output),
|
|
223
|
+
limit: z.number().int().min(1).max(maxLimit).default(defaultLimit),
|
|
224
|
+
after: z.string().optional(),
|
|
225
|
+
}),
|
|
226
|
+
output: z.object({ docs: z.array(output), next: z.string().nullable() }),
|
|
227
|
+
},
|
|
228
|
+
count: {
|
|
229
|
+
input: z.object({ where: whereSchema(output).optional() }),
|
|
230
|
+
output: z.object({ count: z.number().int().nonnegative() }),
|
|
231
|
+
},
|
|
232
|
+
get: { input: id, output },
|
|
233
|
+
create: { input: schema, output },
|
|
234
|
+
update: {
|
|
235
|
+
input: patchSchema(schema),
|
|
236
|
+
output,
|
|
237
|
+
cleared: clearedFields(schema),
|
|
238
|
+
},
|
|
239
|
+
delete: { input: id, output },
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export type Operations<
|
|
244
|
+
Shape extends z.core.$ZodShape,
|
|
245
|
+
Tenant extends string = never,
|
|
246
|
+
> = ReturnType<typeof operations<Shape, Tenant>>;
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* The event classes of a collection, one per write. A payload's `doc` is the
|
|
250
|
+
* stored document, before afterRead: an event records what was written, and
|
|
251
|
+
* afterRead only shapes what a read returns. A tenanted collection's events
|
|
252
|
+
* also carry `tenantId`, so a handler can scope itself to that tenant.
|
|
253
|
+
*/
|
|
254
|
+
function events<
|
|
255
|
+
const Slug extends string,
|
|
256
|
+
Shape extends z.core.$ZodShape,
|
|
257
|
+
Tenant extends string,
|
|
258
|
+
>(
|
|
259
|
+
slug: Slug,
|
|
260
|
+
output: Operations<Shape, Tenant>['get']['output'],
|
|
261
|
+
tenant: Tenant | undefined,
|
|
262
|
+
) {
|
|
263
|
+
const base = { actorId: z.string(), ...tenantShapes(tenant).event };
|
|
264
|
+
return {
|
|
265
|
+
created: Event(`${slug}.created`, z.object({ doc: output, ...base })),
|
|
266
|
+
updated: Event(
|
|
267
|
+
`${slug}.updated`,
|
|
268
|
+
z.object({ doc: output, previous: output, ...base }),
|
|
269
|
+
),
|
|
270
|
+
deleted: Event(`${slug}.deleted`, z.object({ doc: output, ...base })),
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export type Events<
|
|
275
|
+
Slug extends string,
|
|
276
|
+
Shape extends z.core.$ZodShape,
|
|
277
|
+
Tenant extends string = never,
|
|
278
|
+
> = ReturnType<typeof events<Slug, Shape, Tenant>>;
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* An index on a collection, by the names of its stored document's fields:
|
|
282
|
+
* the schema's, the system fields and the tenant field. Key order is the
|
|
283
|
+
* index's key order.
|
|
284
|
+
*/
|
|
285
|
+
export type CollectionIndex<Doc> = {
|
|
286
|
+
readonly fields: { readonly [K in keyof Doc & string]?: 1 | -1 };
|
|
287
|
+
readonly unique?: boolean;
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
/** A collection's data without system fields: what create takes. */
|
|
291
|
+
export type Data<Shape extends z.core.$ZodShape> = z.output<Schema<Shape>>;
|
|
292
|
+
|
|
293
|
+
/** A stored document: the data plus `id`, `createdAt`, `updatedAt` and the tenant field. */
|
|
294
|
+
export type Document<
|
|
295
|
+
Shape extends z.core.$ZodShape,
|
|
296
|
+
Tenant extends string = never,
|
|
297
|
+
> = z.output<Operations<Shape, Tenant>['get']['output']>;
|
|
298
|
+
|
|
299
|
+
export type ChangeArgs<
|
|
300
|
+
Shape extends z.core.$ZodShape,
|
|
301
|
+
Tenant extends string = never,
|
|
302
|
+
> =
|
|
303
|
+
| { readonly data: Data<Shape>; readonly operation: 'create' }
|
|
304
|
+
| {
|
|
305
|
+
readonly data: Data<Shape>;
|
|
306
|
+
readonly operation: 'update';
|
|
307
|
+
/** The stored document before this change. */
|
|
308
|
+
readonly previous: Document<Shape, Tenant>;
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Collection hooks. They transform data and nothing else (0019).
|
|
313
|
+
* `beforeChange` gets the whole document after the change, without system
|
|
314
|
+
* fields, on create and update alike. `afterRead` gets every document a
|
|
315
|
+
* generated operation returns.
|
|
316
|
+
*/
|
|
317
|
+
export type Hooks<
|
|
318
|
+
Shape extends z.core.$ZodShape,
|
|
319
|
+
Tenant extends string = never,
|
|
320
|
+
> = {
|
|
321
|
+
// Method signatures, not function properties: a method's parameters are
|
|
322
|
+
// bivariant, so every collection stays assignable to AnyCollection.
|
|
323
|
+
beforeChange?(
|
|
324
|
+
args: ChangeArgs<Shape, Tenant>,
|
|
325
|
+
): Data<Shape> | Promise<Data<Shape>>;
|
|
326
|
+
afterRead?(args: {
|
|
327
|
+
readonly doc: Document<Shape, Tenant>;
|
|
328
|
+
}): Document<Shape, Tenant> | Promise<Document<Shape, Tenant>>;
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
/** A collection declaration. It names no use case classes. */
|
|
332
|
+
export interface Collection<
|
|
333
|
+
Slug extends string,
|
|
334
|
+
Shape extends z.core.$ZodShape,
|
|
335
|
+
Tenant extends string = never,
|
|
336
|
+
Relations extends AnyRelations = Record<never, never>,
|
|
337
|
+
Maskable extends string = never,
|
|
338
|
+
> {
|
|
339
|
+
readonly slug: Slug;
|
|
340
|
+
/**
|
|
341
|
+
* How the collection reads in a sentence, such as in a generated summary:
|
|
342
|
+
* the declared label, or one from the slug.
|
|
343
|
+
*/
|
|
344
|
+
readonly label: Label;
|
|
345
|
+
readonly schema: Schema<Shape>;
|
|
346
|
+
/**
|
|
347
|
+
* The field that holds a document's tenant id, or undefined for a global
|
|
348
|
+
* collection. Lattice stamps it on create and filters every call by it.
|
|
349
|
+
*/
|
|
350
|
+
readonly tenant: [Tenant] extends [never] ? undefined : Tenant;
|
|
351
|
+
/** The document a read returns: the schema plus `id`, `createdAt`, `updatedAt` and the tenant field. */
|
|
352
|
+
readonly output: Operations<Shape, Tenant>['get']['output'];
|
|
353
|
+
/** The fields a caller's `fields` rules may withhold from what it reads. */
|
|
354
|
+
readonly maskable: readonly Maskable[];
|
|
355
|
+
/**
|
|
356
|
+
* The document a client receives: `output`, with each maskable field
|
|
357
|
+
* optional. A method that returns this collection's documents declares it
|
|
358
|
+
* as its output.
|
|
359
|
+
*/
|
|
360
|
+
readonly clientOutput: ClientOutput<Shape, Tenant, Maskable>;
|
|
361
|
+
/**
|
|
362
|
+
* The indexes `build().ensure()` creates: the declared ones, then one per
|
|
363
|
+
* ref field, led by the tenant field.
|
|
364
|
+
*/
|
|
365
|
+
readonly indexes: readonly Index[];
|
|
366
|
+
/** The ref fields, with their targets and onDelete. */
|
|
367
|
+
readonly refs: readonly RefField[];
|
|
368
|
+
/** Each `many()` relation, with its derived join collection. */
|
|
369
|
+
readonly relations: Relations;
|
|
370
|
+
/**
|
|
371
|
+
* The hexok `Event` classes its generated writes publish, with tokens
|
|
372
|
+
* `<slug>.created`, `.updated` and `.deleted`. The app lists them in its
|
|
373
|
+
* own catalog.
|
|
374
|
+
*/
|
|
375
|
+
readonly events: Events<Slug, Shape, Tenant>;
|
|
376
|
+
readonly beforeChange?: Hooks<Shape, Tenant>['beforeChange'];
|
|
377
|
+
readonly afterRead?: Hooks<Shape, Tenant>['afterRead'];
|
|
378
|
+
/** The same collection with these hooks. A later call replaces a hook it names. */
|
|
379
|
+
hooks(
|
|
380
|
+
hooks: Hooks<Shape, Tenant>,
|
|
381
|
+
): Collection<Slug, Shape, Tenant, Relations, Maskable>;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* A relation as the framework reads it, whatever its collections. Its
|
|
386
|
+
* schemas are Zod core's `$ZodType`, not classic `ZodType`: every
|
|
387
|
+
* collection with a relation is checked against this type once, and
|
|
388
|
+
* against classic `ZodType` that check compares every classic method.
|
|
389
|
+
*/
|
|
390
|
+
export type AnyRelation = {
|
|
391
|
+
readonly target: string;
|
|
392
|
+
readonly onDelete: ManyOnDelete;
|
|
393
|
+
readonly through: AnyCollection;
|
|
394
|
+
readonly parentField: string;
|
|
395
|
+
readonly targetField: string;
|
|
396
|
+
readonly list: {
|
|
397
|
+
readonly input: z.core.$ZodType<
|
|
398
|
+
{
|
|
399
|
+
readonly id: string;
|
|
400
|
+
readonly where?: AnyWhere | undefined;
|
|
401
|
+
readonly sort: readonly string[];
|
|
402
|
+
readonly limit: number;
|
|
403
|
+
readonly after?: string | undefined;
|
|
404
|
+
readonly populate?: readonly string[] | undefined;
|
|
405
|
+
},
|
|
406
|
+
// The input type too: the contract's expansion reads `populate` there.
|
|
407
|
+
{ readonly populate?: readonly string[] | undefined }
|
|
408
|
+
>;
|
|
409
|
+
readonly output: z.core.$ZodType;
|
|
410
|
+
};
|
|
411
|
+
readonly set: {
|
|
412
|
+
readonly input: z.core.$ZodType<{
|
|
413
|
+
readonly id: string;
|
|
414
|
+
readonly links: readonly Readonly<Record<string, unknown>>[];
|
|
415
|
+
}>;
|
|
416
|
+
readonly output: z.core.$ZodType;
|
|
417
|
+
};
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
export type AnyRelations = Readonly<Record<string, AnyRelation>>;
|
|
421
|
+
|
|
422
|
+
/** The most links one `set` takes. A bigger relation is a method's work. */
|
|
423
|
+
export const maxLinks = 1000;
|
|
424
|
+
|
|
425
|
+
type JoinOps<
|
|
426
|
+
P extends string,
|
|
427
|
+
Tenant extends string,
|
|
428
|
+
T extends string,
|
|
429
|
+
D extends ManyOnDelete,
|
|
430
|
+
F extends z.core.$ZodShape,
|
|
431
|
+
> = Operations<JoinShape<P, T, D, F>, Tenant>;
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* One `many()` relation of collection `P`: the derived join collection, its
|
|
435
|
+
* two ref fields, and the schemas of `<slug>.<relation>.list` and `.set`.
|
|
436
|
+
*/
|
|
437
|
+
export type Relation<
|
|
438
|
+
P extends string,
|
|
439
|
+
Tenant extends string,
|
|
440
|
+
M extends AnyMany,
|
|
441
|
+
> =
|
|
442
|
+
M extends Many<
|
|
443
|
+
infer T extends string,
|
|
444
|
+
infer Th extends string,
|
|
445
|
+
infer F extends z.core.$ZodShape,
|
|
446
|
+
infer D extends ManyOnDelete
|
|
447
|
+
>
|
|
448
|
+
? {
|
|
449
|
+
readonly target: T;
|
|
450
|
+
readonly onDelete: D;
|
|
451
|
+
readonly through: Collection<Th, JoinShape<P, T, D, F>, Tenant>;
|
|
452
|
+
readonly parentField: `${P}Id`;
|
|
453
|
+
readonly targetField: `${T}Id`;
|
|
454
|
+
readonly list: {
|
|
455
|
+
readonly input: z.ZodObject<
|
|
456
|
+
z.core.util.Extend<
|
|
457
|
+
JoinOps<P, Tenant, T, D, F>['find']['input']['shape'],
|
|
458
|
+
{
|
|
459
|
+
id: z.ZodString;
|
|
460
|
+
populate: z.ZodOptional<
|
|
461
|
+
z.ZodArray<z.ZodEnum<{ [K in `${P}Id` | `${T}Id`]: K }>>
|
|
462
|
+
>;
|
|
463
|
+
}
|
|
464
|
+
>,
|
|
465
|
+
z.core.$strip
|
|
466
|
+
>;
|
|
467
|
+
readonly output: JoinOps<P, Tenant, T, D, F>['find']['output'];
|
|
468
|
+
};
|
|
469
|
+
readonly set: {
|
|
470
|
+
readonly input: z.ZodObject<
|
|
471
|
+
{
|
|
472
|
+
id: z.ZodString;
|
|
473
|
+
links: z.ZodArray<z.ZodObject<LinkShape<T, D, F>, z.core.$strip>>;
|
|
474
|
+
},
|
|
475
|
+
z.core.$strip
|
|
476
|
+
>;
|
|
477
|
+
readonly output: z.ZodObject<
|
|
478
|
+
{ docs: z.ZodArray<JoinOps<P, Tenant, T, D, F>['get']['output']> },
|
|
479
|
+
z.core.$strip
|
|
480
|
+
>;
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
: never;
|
|
484
|
+
|
|
485
|
+
export type RelationsOf<
|
|
486
|
+
P extends string,
|
|
487
|
+
Tenant extends string,
|
|
488
|
+
R extends Readonly<Record<string, AnyMany>>,
|
|
489
|
+
> = { readonly [K in keyof R]: Relation<P, Tenant, R[K]> };
|
|
490
|
+
|
|
491
|
+
/** An event class as hexok's `EventCatalog` takes it, whatever its payload. */
|
|
492
|
+
type AnyEventClass = Parameters<typeof EventCatalog>[1][string];
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Any collection, as the framework reads it. Its event classes are erased
|
|
496
|
+
* the way a catalog erases them: an `Event` class's payload type is both a
|
|
497
|
+
* constructor parameter and a property, so one collection's classes fit no
|
|
498
|
+
* wider payload type. `hooks()` is left out because it returns them.
|
|
499
|
+
*/
|
|
500
|
+
export type AnyCollection = Omit<
|
|
501
|
+
Collection<string, z.core.$ZodShape>,
|
|
502
|
+
'events' | 'hooks' | 'tenant' | 'relations' | 'maskable' | 'clientOutput'
|
|
503
|
+
> & {
|
|
504
|
+
readonly tenant: string | undefined;
|
|
505
|
+
readonly relations: AnyRelations;
|
|
506
|
+
readonly maskable: readonly string[];
|
|
507
|
+
readonly clientOutput: Collection<string, z.core.$ZodShape>['output'];
|
|
508
|
+
readonly events: Readonly<
|
|
509
|
+
Record<keyof Events<string, z.core.$ZodShape>, AnyEventClass>
|
|
510
|
+
>;
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* Names a schema field or the tenant field cannot take: the system fields,
|
|
515
|
+
* which would be replaced, and the `Where` keys, which would read as a filter.
|
|
516
|
+
*/
|
|
517
|
+
export const reservedFields = [
|
|
518
|
+
'id',
|
|
519
|
+
'createdAt',
|
|
520
|
+
'updatedAt',
|
|
521
|
+
'and',
|
|
522
|
+
'or',
|
|
523
|
+
] as const;
|
|
524
|
+
type ReservedField = (typeof reservedFields)[number];
|
|
525
|
+
|
|
526
|
+
// Names a store would misread: MongoDB reads a dot as a path, a leading `$`
|
|
527
|
+
// as an operator, and `_id` is where a store keeps `id`.
|
|
528
|
+
type StoreName = `${string}.${string}` | `$${string}` | '_id';
|
|
529
|
+
|
|
530
|
+
function isStoreName(name: string): boolean {
|
|
531
|
+
return name.includes('.') || name.startsWith('$') || name === '_id';
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
const storeNameError = (name: string) =>
|
|
535
|
+
`"${name}" is not a valid field name: it contains ".", starts with "$" or is "_id"`;
|
|
536
|
+
|
|
537
|
+
type DateField<Shape extends z.core.$ZodShape> = {
|
|
538
|
+
[K in keyof Shape]: [Exclude<z.output<Shape[K]>, null | undefined>] extends [
|
|
539
|
+
never,
|
|
540
|
+
]
|
|
541
|
+
? never
|
|
542
|
+
: [Exclude<z.output<Shape[K]>, null | undefined>] extends [Date]
|
|
543
|
+
? K
|
|
544
|
+
: never;
|
|
545
|
+
}[keyof Shape];
|
|
546
|
+
|
|
547
|
+
// A rejected tenant adds a key the options lack, so the error names it. The
|
|
548
|
+
// tenant field is Lattice's, like the system fields.
|
|
549
|
+
type TenantCheck<Shape extends z.core.$ZodShape, Tenant extends string> = [
|
|
550
|
+
Tenant & (keyof Shape | ReservedField | StoreName),
|
|
551
|
+
] extends [never]
|
|
552
|
+
? unknown
|
|
553
|
+
: {
|
|
554
|
+
readonly '~error': `tenant "${Tenant & string}" is stamped by Lattice; it cannot be a schema field, a reserved name or an invalid field name`;
|
|
555
|
+
};
|
|
556
|
+
|
|
557
|
+
// A rejected schema adds a key the options lack, so the error names the
|
|
558
|
+
// field. Only top-level Dates are checked here; collection() finds the rest.
|
|
559
|
+
type FieldCheck<Shape extends z.core.$ZodShape> = [
|
|
560
|
+
keyof Shape & ReservedField,
|
|
561
|
+
] extends [never]
|
|
562
|
+
? [keyof Shape & StoreName] extends [never]
|
|
563
|
+
? [DateField<Shape>] extends [never]
|
|
564
|
+
? unknown
|
|
565
|
+
: {
|
|
566
|
+
readonly '~error': `"${DateField<Shape> & string}" is a Date; store an ISO string (z.iso.datetime())`;
|
|
567
|
+
}
|
|
568
|
+
: {
|
|
569
|
+
readonly '~error': `"${keyof Shape & StoreName & string}" is not a valid field name: it contains ".", starts with "$" or is "_id"`;
|
|
570
|
+
}
|
|
571
|
+
: {
|
|
572
|
+
readonly '~error': `"${keyof Shape & ReservedField}" is a reserved field name`;
|
|
573
|
+
};
|
|
574
|
+
|
|
575
|
+
/** The schemas inside `schema`, each with the path suffix that reaches it. */
|
|
576
|
+
function children(schema: z.core.$ZodType): [z.core.$ZodType, string][] {
|
|
577
|
+
const inner = innerOf(schema);
|
|
578
|
+
if (inner !== undefined) return [[inner, '']];
|
|
579
|
+
if (schema instanceof z.core.$ZodUnion) {
|
|
580
|
+
return schema._zod.def.options.map((option) => [option, '']);
|
|
581
|
+
}
|
|
582
|
+
if (schema instanceof z.core.$ZodArray) {
|
|
583
|
+
return [[schema._zod.def.element, '[]']];
|
|
584
|
+
}
|
|
585
|
+
if (schema instanceof z.core.$ZodObject) {
|
|
586
|
+
return Object.entries(schema._zod.def.shape).map(([key, field]) => [
|
|
587
|
+
field,
|
|
588
|
+
`.${key}`,
|
|
589
|
+
]);
|
|
590
|
+
}
|
|
591
|
+
return [];
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/**
|
|
595
|
+
* Rejects field forms the contract cannot carry honestly. A Date reaches an
|
|
596
|
+
* HTTP client as a string. A transform hides a field's kind, so a `Where` on
|
|
597
|
+
* it cannot be checked; normalizing belongs in a beforeChange hook (0012).
|
|
598
|
+
*/
|
|
599
|
+
function checkField(path: string, schema: z.core.$ZodType): void {
|
|
600
|
+
const { type } = schema._zod.def;
|
|
601
|
+
if (type === 'date') {
|
|
602
|
+
throw new Error(
|
|
603
|
+
`Lattice: "${path}" is a Date; store an ISO string (z.iso.datetime())`,
|
|
604
|
+
);
|
|
605
|
+
}
|
|
606
|
+
if (type === 'pipe' || type === 'transform') {
|
|
607
|
+
throw new Error(
|
|
608
|
+
`Lattice: "${path}" has a transform; use a beforeChange hook`,
|
|
609
|
+
);
|
|
610
|
+
}
|
|
611
|
+
for (const [child, suffix] of children(schema)) {
|
|
612
|
+
checkField(`${path}${suffix}`, child);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/** `<relation>.<field>` for each link field a join collection cannot have. */
|
|
617
|
+
type BadLinkField<Slug extends string, Tenant extends string, R> = {
|
|
618
|
+
[K in keyof R]: R[K] extends Many<
|
|
619
|
+
infer T extends string,
|
|
620
|
+
string,
|
|
621
|
+
infer F,
|
|
622
|
+
ManyOnDelete
|
|
623
|
+
>
|
|
624
|
+
? `${K & string}.${keyof F & (`${Slug}Id` | `${T}Id` | ReservedField | Tenant | StoreName) & string}`
|
|
625
|
+
: never;
|
|
626
|
+
}[keyof R];
|
|
627
|
+
|
|
628
|
+
// A rejected relation adds a key the options lack, so the error names it.
|
|
629
|
+
type RelationCheck<
|
|
630
|
+
Slug extends string,
|
|
631
|
+
Shape extends z.core.$ZodShape,
|
|
632
|
+
Tenant extends string,
|
|
633
|
+
R,
|
|
634
|
+
> = [BadLinkField<Slug, Tenant, R>] extends [never]
|
|
635
|
+
? RelationNameCheck<Slug, Shape, R>
|
|
636
|
+
: {
|
|
637
|
+
readonly '~error': `link field "${BadLinkField<Slug, Tenant, R>}" is a ref field, a reserved name, the tenant or an invalid field name`;
|
|
638
|
+
};
|
|
639
|
+
|
|
640
|
+
type RelationNameCheck<
|
|
641
|
+
Slug extends string,
|
|
642
|
+
Shape extends z.core.$ZodShape,
|
|
643
|
+
R,
|
|
644
|
+
> = [keyof R & (keyof Shape | Action | 'read')] extends [never]
|
|
645
|
+
? {
|
|
646
|
+
[K in keyof R]: R[K] extends { readonly target: Slug }
|
|
647
|
+
? `${K & string} relates ${Slug} to itself, which many() does not support`
|
|
648
|
+
: never;
|
|
649
|
+
}[keyof R] extends infer E
|
|
650
|
+
? [E] extends [never]
|
|
651
|
+
? unknown
|
|
652
|
+
: { readonly '~error': E }
|
|
653
|
+
: never
|
|
654
|
+
: {
|
|
655
|
+
readonly '~error': `relation "${keyof R & (keyof Shape | Action | 'read') & string}" has the name of a field, an action or an access key`;
|
|
656
|
+
};
|
|
657
|
+
|
|
658
|
+
export function collection<
|
|
659
|
+
const Slug extends string,
|
|
660
|
+
Shape extends z.core.$ZodShape,
|
|
661
|
+
const Tenant extends string = never,
|
|
662
|
+
const R extends Readonly<Record<string, AnyMany>> = Record<never, never>,
|
|
663
|
+
const M extends keyof Shape & string = never,
|
|
664
|
+
>(
|
|
665
|
+
slug: Slug,
|
|
666
|
+
options: {
|
|
667
|
+
readonly schema: Schema<Shape>;
|
|
668
|
+
/**
|
|
669
|
+
* The field that holds each document's tenant id, such as
|
|
670
|
+
* `'organizationId'`. Lattice adds it to the output, stamps it on
|
|
671
|
+
* create, and filters every call by the caller's tenant.
|
|
672
|
+
*/
|
|
673
|
+
readonly tenant?: Tenant;
|
|
674
|
+
/**
|
|
675
|
+
* Indexes the store creates at startup, through `build().ensure()`. A
|
|
676
|
+
* tenanted collection's indexes usually lead with the tenant field.
|
|
677
|
+
*/
|
|
678
|
+
readonly indexes?: readonly CollectionIndex<
|
|
679
|
+
z.output<Output<Shape, Tenant>>
|
|
680
|
+
>[];
|
|
681
|
+
/**
|
|
682
|
+
* `many()` relations, by name. Each derives a join collection and gets
|
|
683
|
+
* `<slug>.<name>.list` and `.set`.
|
|
684
|
+
*/
|
|
685
|
+
readonly relations?: R;
|
|
686
|
+
/**
|
|
687
|
+
* Schema fields a caller's rules may withhold, such as `['amount']`.
|
|
688
|
+
* `.collection(C, { fields })` gives each its read rule. Not a ref, and
|
|
689
|
+
* not in a unique index, which would reveal a value through CONFLICT.
|
|
690
|
+
*/
|
|
691
|
+
readonly maskable?: readonly M[];
|
|
692
|
+
/**
|
|
693
|
+
* How the collection reads mid-sentence, such as `{ singular: 'person',
|
|
694
|
+
* plural: 'people' }`. Generated summaries and the admin use it. Without
|
|
695
|
+
* it, the label comes from the slug: `deal_stages` reads "deal stage"
|
|
696
|
+
* and "deal stages".
|
|
697
|
+
*/
|
|
698
|
+
readonly label?: Label;
|
|
699
|
+
} & FieldCheck<Shape> &
|
|
700
|
+
RefCheck<Shape> &
|
|
701
|
+
TenantCheck<Shape, Tenant> &
|
|
702
|
+
RelationCheck<Slug, Shape, Tenant, R>,
|
|
703
|
+
): Collection<Slug, Shape, Tenant, RelationsOf<Slug, Tenant, R>, M> {
|
|
704
|
+
for (const [name, field] of Object.entries(options.schema.shape)) {
|
|
705
|
+
if (reservedFields.some((reserved) => reserved === name)) {
|
|
706
|
+
throw new Error(`Lattice: "${name}" is a reserved field name`);
|
|
707
|
+
}
|
|
708
|
+
if (isStoreName(name)) throw new Error(`Lattice: ${storeNameError(name)}`);
|
|
709
|
+
checkField(`${slug}.${name}`, field);
|
|
710
|
+
}
|
|
711
|
+
const names = Object.keys(options.schema.shape);
|
|
712
|
+
const { tenant } = options;
|
|
713
|
+
if (
|
|
714
|
+
tenant !== undefined &&
|
|
715
|
+
([...names, ...reservedFields].some((name) => name === tenant) ||
|
|
716
|
+
isStoreName(tenant))
|
|
717
|
+
) {
|
|
718
|
+
throw new Error(
|
|
719
|
+
`Lattice: tenant "${tenant}" is stamped by Lattice; it cannot be a schema field, a reserved name or an invalid field name`,
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
const relations: Readonly<Record<string, AnyMany>> = options.relations ?? {};
|
|
723
|
+
for (const [name, relation] of Object.entries(relations)) {
|
|
724
|
+
if ([...names, ...actions, 'read'].some((other) => other === name)) {
|
|
725
|
+
throw new Error(
|
|
726
|
+
`Lattice: relation "${name}" has the name of a field, an action or an access key`,
|
|
727
|
+
);
|
|
728
|
+
}
|
|
729
|
+
if (relation.target === slug) {
|
|
730
|
+
throw new Error(
|
|
731
|
+
`Lattice: ${name} relates ${slug} to itself, which many() does not support`,
|
|
732
|
+
);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
// A stored index names each field with its direction; an optional key
|
|
736
|
+
// left undefined names nothing.
|
|
737
|
+
const declaredIndexes: readonly Index[] = (options.indexes ?? []).map(
|
|
738
|
+
({ fields, unique }) => ({
|
|
739
|
+
fields: Object.fromEntries(
|
|
740
|
+
Object.entries(fields).flatMap(
|
|
741
|
+
([field, direction]): [string, 1 | -1][] =>
|
|
742
|
+
direction === 1 || direction === -1 ? [[field, direction]] : [],
|
|
743
|
+
),
|
|
744
|
+
),
|
|
745
|
+
...(unique === undefined ? {} : { unique }),
|
|
746
|
+
}),
|
|
747
|
+
);
|
|
748
|
+
const maskable: readonly M[] = options.maskable ?? [];
|
|
749
|
+
for (const [index, field] of maskable.entries()) {
|
|
750
|
+
if (!names.includes(field) || maskable.indexOf(field) !== index) {
|
|
751
|
+
throw new Error(
|
|
752
|
+
`Lattice: maskable "${field}" is not a field of ${slug}, or is named twice`,
|
|
753
|
+
);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
return define<Slug, Shape, Tenant, RelationsOf<Slug, Tenant, R>, M>(
|
|
757
|
+
slug,
|
|
758
|
+
options.schema,
|
|
759
|
+
tenant,
|
|
760
|
+
declaredIndexes,
|
|
761
|
+
relationsOf(slug, tenant, options.relations),
|
|
762
|
+
options.label ?? labelOf(slug),
|
|
763
|
+
maskable,
|
|
764
|
+
);
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/** The generated operations, for the relation-name check. */
|
|
768
|
+
const actions = ['find', 'count', 'get', 'create', 'update', 'delete'];
|
|
769
|
+
|
|
770
|
+
/**
|
|
771
|
+
* A collection from a checked schema: its output, refs, indexes and events.
|
|
772
|
+
* `collection()` checks a user's options and calls it; a join collection is
|
|
773
|
+
* defined here directly.
|
|
774
|
+
*/
|
|
775
|
+
function define<
|
|
776
|
+
Slug extends string,
|
|
777
|
+
Shape extends z.core.$ZodShape,
|
|
778
|
+
Tenant extends string,
|
|
779
|
+
Relations extends AnyRelations,
|
|
780
|
+
M extends string = never,
|
|
781
|
+
>(
|
|
782
|
+
slug: Slug,
|
|
783
|
+
schema: Schema<Shape>,
|
|
784
|
+
tenant: Tenant | undefined,
|
|
785
|
+
declaredIndexes: readonly Index[],
|
|
786
|
+
relations: Relations,
|
|
787
|
+
label: Label,
|
|
788
|
+
maskable: readonly M[] = [],
|
|
789
|
+
): Collection<Slug, Shape, Tenant, Relations, M> {
|
|
790
|
+
const { output, clientOutput } = outputsOf<Shape, Tenant, M>(
|
|
791
|
+
slug,
|
|
792
|
+
schema,
|
|
793
|
+
tenant,
|
|
794
|
+
maskable,
|
|
795
|
+
);
|
|
796
|
+
const fields = Object.keys(output.shape);
|
|
797
|
+
for (const index of declaredIndexes) {
|
|
798
|
+
const keys = Object.keys(index.fields);
|
|
799
|
+
if (keys.length === 0) {
|
|
800
|
+
throw new Error(`Lattice: an index on "${slug}" names no fields`);
|
|
801
|
+
}
|
|
802
|
+
const unknown = keys.find((key) => !fields.includes(key));
|
|
803
|
+
if (unknown !== undefined) {
|
|
804
|
+
throw new Error(
|
|
805
|
+
`Lattice: an index on "${slug}" names "${unknown}", which is not a field`,
|
|
806
|
+
);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
const refs = refsOf(slug, schema.shape);
|
|
810
|
+
for (const field of maskable) {
|
|
811
|
+
// A populated ref would show the target document a mask hides, and a
|
|
812
|
+
// unique index answers CONFLICT for a value another row holds.
|
|
813
|
+
if (refs.some((ref) => ref.field === field)) {
|
|
814
|
+
throw new Error(
|
|
815
|
+
`Lattice: ${slug}.${field} is a ref; it cannot be maskable`,
|
|
816
|
+
);
|
|
817
|
+
}
|
|
818
|
+
if (
|
|
819
|
+
declaredIndexes.some(
|
|
820
|
+
(index) => index.unique === true && field in index.fields,
|
|
821
|
+
)
|
|
822
|
+
) {
|
|
823
|
+
throw new Error(
|
|
824
|
+
`Lattice: ${slug}.${field} is maskable, so it cannot be in a unique index: a CONFLICT would reveal its value`,
|
|
825
|
+
);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
// restrict, cascade and nullify look children up by their ref field,
|
|
829
|
+
// within the tenant: each ref gets an index, unless a declared one starts
|
|
830
|
+
// with the same keys, which serves the lookup as well.
|
|
831
|
+
const refIndexes = refs
|
|
832
|
+
.map(
|
|
833
|
+
({ field }): Index => ({
|
|
834
|
+
fields:
|
|
835
|
+
tenant === undefined ? { [field]: 1 } : { [tenant]: 1, [field]: 1 },
|
|
836
|
+
}),
|
|
837
|
+
)
|
|
838
|
+
.filter(
|
|
839
|
+
(index) => !declaredIndexes.some((other) => startsWith(other, index)),
|
|
840
|
+
);
|
|
841
|
+
return declared<Slug, Shape, Tenant, Relations, M>(
|
|
842
|
+
slug,
|
|
843
|
+
label,
|
|
844
|
+
schema,
|
|
845
|
+
tenantShapes(tenant).tenant,
|
|
846
|
+
[...declaredIndexes, ...refIndexes],
|
|
847
|
+
refs,
|
|
848
|
+
relations,
|
|
849
|
+
{ output, clientOutput, maskable },
|
|
850
|
+
events(slug, output, tenant),
|
|
851
|
+
{},
|
|
852
|
+
);
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* The relations of collection `parent`, each with its derived join
|
|
857
|
+
* collection. The overload states each relation's types, including the
|
|
858
|
+
* join's computed field names; the implementation builds them in a loop,
|
|
859
|
+
* which a mapped type cannot express.
|
|
860
|
+
*/
|
|
861
|
+
function relationsOf<
|
|
862
|
+
P extends string,
|
|
863
|
+
Tenant extends string,
|
|
864
|
+
R extends Readonly<Record<string, AnyMany>>,
|
|
865
|
+
>(
|
|
866
|
+
parent: P,
|
|
867
|
+
tenant: Tenant | undefined,
|
|
868
|
+
relations: R | undefined,
|
|
869
|
+
): RelationsOf<P, Tenant, R>;
|
|
870
|
+
function relationsOf(
|
|
871
|
+
parent: string,
|
|
872
|
+
tenant: string | undefined,
|
|
873
|
+
relations: Readonly<Record<string, AnyMany>> | undefined,
|
|
874
|
+
): AnyRelations {
|
|
875
|
+
return Object.fromEntries(
|
|
876
|
+
Object.entries(relations ?? {}).map(([name, relation]) => [
|
|
877
|
+
name,
|
|
878
|
+
relationOf(parent, tenant, relation),
|
|
879
|
+
]),
|
|
880
|
+
);
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
function relationOf(
|
|
884
|
+
parent: string,
|
|
885
|
+
tenant: string | undefined,
|
|
886
|
+
relation: AnyMany,
|
|
887
|
+
): AnyRelation {
|
|
888
|
+
const { join, link, parentField, targetField } = joinSchemas(
|
|
889
|
+
parent,
|
|
890
|
+
relation,
|
|
891
|
+
);
|
|
892
|
+
const fieldNames = Object.keys(relation.fields?.shape ?? {});
|
|
893
|
+
const clash = fieldNames.find(
|
|
894
|
+
(name) =>
|
|
895
|
+
name === parentField ||
|
|
896
|
+
name === targetField ||
|
|
897
|
+
reservedFields.some((reserved) => reserved === name) ||
|
|
898
|
+
name === tenant ||
|
|
899
|
+
isStoreName(name),
|
|
900
|
+
);
|
|
901
|
+
if (clash !== undefined) {
|
|
902
|
+
throw new Error(
|
|
903
|
+
`Lattice: "${relation.through}" link field "${clash}" is a ref field, a reserved name, the tenant or an invalid field name`,
|
|
904
|
+
);
|
|
905
|
+
}
|
|
906
|
+
const keys = (...fields: string[]): Index['fields'] =>
|
|
907
|
+
Object.fromEntries(
|
|
908
|
+
[...(tenant === undefined ? [] : [tenant]), ...fields].map((field) => [
|
|
909
|
+
field,
|
|
910
|
+
1,
|
|
911
|
+
]),
|
|
912
|
+
);
|
|
913
|
+
// One link per pair, and a lookup from each side: list and a parent's
|
|
914
|
+
// cascade read the pair index's prefix, a target's onDelete the other.
|
|
915
|
+
const through = define(
|
|
916
|
+
relation.through,
|
|
917
|
+
join,
|
|
918
|
+
tenant,
|
|
919
|
+
[
|
|
920
|
+
{ fields: keys(parentField, targetField), unique: true },
|
|
921
|
+
{ fields: keys(targetField) },
|
|
922
|
+
],
|
|
923
|
+
{},
|
|
924
|
+
labelOf(relation.through),
|
|
925
|
+
);
|
|
926
|
+
const ops = operations(through.schema, through.output);
|
|
927
|
+
return {
|
|
928
|
+
target: relation.target,
|
|
929
|
+
onDelete: relation.onDelete ?? 'restrict',
|
|
930
|
+
through,
|
|
931
|
+
parentField,
|
|
932
|
+
targetField,
|
|
933
|
+
list: {
|
|
934
|
+
// A link's ref fields populate as on any read.
|
|
935
|
+
input: ops.find.input.extend({
|
|
936
|
+
id: z.string(),
|
|
937
|
+
populate: z.array(z.enum([parentField, targetField])).optional(),
|
|
938
|
+
}),
|
|
939
|
+
output: ops.find.output,
|
|
940
|
+
},
|
|
941
|
+
set: {
|
|
942
|
+
input: z.object({
|
|
943
|
+
id: z.string(),
|
|
944
|
+
links: z
|
|
945
|
+
.array(link)
|
|
946
|
+
.max(maxLinks)
|
|
947
|
+
.superRefine((links, ctx) => {
|
|
948
|
+
const seen = new Set<unknown>();
|
|
949
|
+
links.forEach((value, index) => {
|
|
950
|
+
const target = value[targetField];
|
|
951
|
+
if (seen.has(target)) {
|
|
952
|
+
ctx.addIssue({
|
|
953
|
+
code: 'custom',
|
|
954
|
+
path: [index, targetField],
|
|
955
|
+
message: `${targetField} repeats an earlier link`,
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
seen.add(target);
|
|
959
|
+
});
|
|
960
|
+
}),
|
|
961
|
+
}),
|
|
962
|
+
output: z.object({ docs: z.array(through.output) }),
|
|
963
|
+
},
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// A collection with other hooks keeps the same event classes: a catalog
|
|
968
|
+
// matches an event to its class with instanceof.
|
|
969
|
+
function declared<
|
|
970
|
+
Slug extends string,
|
|
971
|
+
Shape extends z.core.$ZodShape,
|
|
972
|
+
Tenant extends string,
|
|
973
|
+
Relations extends AnyRelations,
|
|
974
|
+
M extends string,
|
|
975
|
+
>(
|
|
976
|
+
slug: Slug,
|
|
977
|
+
label: Label,
|
|
978
|
+
schema: Schema<Shape>,
|
|
979
|
+
tenant: Collection<Slug, Shape, Tenant>['tenant'],
|
|
980
|
+
indexes: readonly Index[],
|
|
981
|
+
refs: readonly RefField[],
|
|
982
|
+
relations: Relations,
|
|
983
|
+
outputs: {
|
|
984
|
+
readonly output: Operations<Shape, Tenant>['get']['output'];
|
|
985
|
+
readonly clientOutput: ClientOutput<Shape, Tenant, M>;
|
|
986
|
+
readonly maskable: readonly M[];
|
|
987
|
+
},
|
|
988
|
+
events: Events<Slug, Shape, Tenant>,
|
|
989
|
+
hooks: Hooks<Shape, Tenant>,
|
|
990
|
+
): Collection<Slug, Shape, Tenant, Relations, M> {
|
|
991
|
+
return {
|
|
992
|
+
slug,
|
|
993
|
+
label,
|
|
994
|
+
schema,
|
|
995
|
+
tenant,
|
|
996
|
+
indexes,
|
|
997
|
+
refs,
|
|
998
|
+
relations,
|
|
999
|
+
...outputs,
|
|
1000
|
+
events,
|
|
1001
|
+
...hooks,
|
|
1002
|
+
hooks: (next) =>
|
|
1003
|
+
declared<Slug, Shape, Tenant, Relations, M>(
|
|
1004
|
+
slug,
|
|
1005
|
+
label,
|
|
1006
|
+
schema,
|
|
1007
|
+
tenant,
|
|
1008
|
+
indexes,
|
|
1009
|
+
refs,
|
|
1010
|
+
relations,
|
|
1011
|
+
outputs,
|
|
1012
|
+
events,
|
|
1013
|
+
{ ...hooks, ...next },
|
|
1014
|
+
),
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/** Whether index `a` starts with the keys of `b`, in the same order and directions. */
|
|
1019
|
+
function startsWith(a: Index, b: Index): boolean {
|
|
1020
|
+
const left = Object.entries(a.fields);
|
|
1021
|
+
return Object.entries(b.fields).every(([field, direction], i) => {
|
|
1022
|
+
const other = left[i];
|
|
1023
|
+
return other !== undefined && other[0] === field && other[1] === direction;
|
|
1024
|
+
});
|
|
1025
|
+
}
|