@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
package/src/relations.ts
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { AnyCollection } from './collection.js';
|
|
3
|
+
import { labelOf } from './describe.js';
|
|
4
|
+
import { innerOf } from './where.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* What happens to the documents that refer to one being deleted:
|
|
8
|
+
* `restrict` refuses the delete, `cascade` deletes them too, and `nullify`
|
|
9
|
+
* clears the reference (0028).
|
|
10
|
+
*/
|
|
11
|
+
export type OnDelete = 'restrict' | 'cascade' | 'nullify';
|
|
12
|
+
|
|
13
|
+
/** A reference as Lattice reads it: the target collection's slug and its onDelete. */
|
|
14
|
+
type RefInfo<Slug extends string = string, D extends OnDelete = OnDelete> = {
|
|
15
|
+
readonly slug: Slug;
|
|
16
|
+
readonly onDelete: D;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A string field that holds the id of a document in collection `Slug`.
|
|
21
|
+
* `'~ref'` is a type-only brand; at runtime the reference is a no-op check,
|
|
22
|
+
* so a clone such as `.min(1)` keeps it.
|
|
23
|
+
*/
|
|
24
|
+
export type Ref<Slug extends string, D extends OnDelete> = z.ZodString & {
|
|
25
|
+
readonly '~ref'?: RefInfo<Slug, D>;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** The check that carries a reference. It accepts every value. */
|
|
29
|
+
type RefMarker = z.core.$ZodCheck<string> & { readonly '~lattice': RefInfo };
|
|
30
|
+
|
|
31
|
+
function isMarker(check: unknown): check is RefMarker {
|
|
32
|
+
return typeof check === 'object' && check !== null && '~lattice' in check;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* What a ref says to an empty id, in words from its slug's label: "Choose
|
|
37
|
+
* the company". "The", not "a" or "an": the article depends on how the
|
|
38
|
+
* label sounds. A slug whose singular labelOf cannot find, such as
|
|
39
|
+
* `people`, says "Choose one".
|
|
40
|
+
*/
|
|
41
|
+
function emptyRef(slug: string): string {
|
|
42
|
+
const { singular, plural } = labelOf(slug);
|
|
43
|
+
return singular === plural ? 'Choose one' : `Choose the ${singular}`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Marks a string field as the id of a document in collection `slug`. The
|
|
48
|
+
* slug, not the collection, so collections can refer to each other.
|
|
49
|
+
* `z.array(ref(slug))` is a list of ids. The marker is what Lattice reads;
|
|
50
|
+
* `x-lattice-ref` is what the field's JSON Schema says, so a client such as
|
|
51
|
+
* the admin knows where an id points. Both come from `slug`, here. No
|
|
52
|
+
* document has an empty id, so a ref refuses ''.
|
|
53
|
+
*/
|
|
54
|
+
export function ref<
|
|
55
|
+
const Slug extends string,
|
|
56
|
+
const D extends OnDelete = 'restrict',
|
|
57
|
+
>(slug: Slug, options?: { readonly onDelete?: D }): Ref<Slug, D> {
|
|
58
|
+
const info: RefInfo = { slug, onDelete: options?.onDelete ?? 'restrict' };
|
|
59
|
+
const marker: RefMarker = Object.assign(
|
|
60
|
+
z.check<string>(() => {}),
|
|
61
|
+
{ '~lattice': info },
|
|
62
|
+
);
|
|
63
|
+
return z
|
|
64
|
+
.string()
|
|
65
|
+
.min(1, emptyRef(slug))
|
|
66
|
+
.check(marker)
|
|
67
|
+
.meta({ 'x-lattice-ref': slug });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ---------------------------------------------------------------- many
|
|
71
|
+
|
|
72
|
+
/** What deleting a target does to its links: refuse, or delete them. */
|
|
73
|
+
export type ManyOnDelete = 'restrict' | 'cascade';
|
|
74
|
+
|
|
75
|
+
/** A many-to-many relation, through a join collection Lattice derives. */
|
|
76
|
+
export type Many<
|
|
77
|
+
Target extends string,
|
|
78
|
+
Through extends string,
|
|
79
|
+
Fields extends z.core.$ZodShape,
|
|
80
|
+
D extends ManyOnDelete,
|
|
81
|
+
> = {
|
|
82
|
+
readonly kind: 'many';
|
|
83
|
+
readonly target: Target;
|
|
84
|
+
/** The join collection's slug. */
|
|
85
|
+
readonly through: Through;
|
|
86
|
+
/** Fields each link carries, such as `sortOrder`. */
|
|
87
|
+
readonly fields: z.ZodObject<Fields, z.core.$strip> | undefined;
|
|
88
|
+
/** What deleting a target does to its links. Undefined is restrict. */
|
|
89
|
+
readonly onDelete: D | undefined;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
export type AnyMany = Many<string, string, z.core.$ZodShape, ManyOnDelete>;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Relates each document to many of `target`, through a join collection
|
|
96
|
+
* `through` with `<parent>Id`, `<target>Id` and `fields`. Lattice derives
|
|
97
|
+
* that collection; its slug is `through`.
|
|
98
|
+
*/
|
|
99
|
+
export function many<
|
|
100
|
+
const Target extends string,
|
|
101
|
+
const Through extends string,
|
|
102
|
+
Fields extends z.core.$ZodShape = Record<never, never>,
|
|
103
|
+
const D extends ManyOnDelete = 'restrict',
|
|
104
|
+
>(
|
|
105
|
+
target: Target,
|
|
106
|
+
options: {
|
|
107
|
+
readonly through: Through;
|
|
108
|
+
readonly fields?: z.ZodObject<Fields, z.core.$strip>;
|
|
109
|
+
readonly onDelete?: D;
|
|
110
|
+
},
|
|
111
|
+
// NoInfer: inside `collection({ relations })`, the relations constraint
|
|
112
|
+
// would otherwise infer an omitted `fields` as any shape and an omitted
|
|
113
|
+
// `onDelete` as both options, instead of their defaults.
|
|
114
|
+
): Many<Target, Through, NoInfer<Fields>, NoInfer<D>> {
|
|
115
|
+
return {
|
|
116
|
+
kind: 'many',
|
|
117
|
+
target,
|
|
118
|
+
through: options.through,
|
|
119
|
+
fields: options.fields,
|
|
120
|
+
onDelete: options.onDelete,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The join collection's shape: the two refs, then the link fields. */
|
|
125
|
+
export type JoinShape<
|
|
126
|
+
P extends string,
|
|
127
|
+
T extends string,
|
|
128
|
+
D extends ManyOnDelete,
|
|
129
|
+
F extends z.core.$ZodShape,
|
|
130
|
+
> = {
|
|
131
|
+
[K in `${P}Id` | `${T}Id` | keyof F]: K extends `${P}Id`
|
|
132
|
+
? Ref<P, 'cascade'>
|
|
133
|
+
: K extends `${T}Id`
|
|
134
|
+
? Ref<T, D>
|
|
135
|
+
: F[K];
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/** What `set` takes per link: the target's id and the link fields. */
|
|
139
|
+
export type LinkShape<
|
|
140
|
+
T extends string,
|
|
141
|
+
D extends ManyOnDelete,
|
|
142
|
+
F extends z.core.$ZodShape,
|
|
143
|
+
> = {
|
|
144
|
+
[K in `${T}Id` | keyof F]: K extends `${T}Id` ? Ref<T, D> : F[K];
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* The join collection's schema, and the link schema `set` takes. Untyped:
|
|
149
|
+
* `relationsOf` in collection.ts states their types.
|
|
150
|
+
*/
|
|
151
|
+
export function joinSchemas(
|
|
152
|
+
parent: string,
|
|
153
|
+
relation: AnyMany,
|
|
154
|
+
): {
|
|
155
|
+
readonly join: z.ZodObject<z.core.$ZodShape, z.core.$strip>;
|
|
156
|
+
readonly link: z.ZodObject<z.core.$ZodShape, z.core.$strip>;
|
|
157
|
+
readonly parentField: string;
|
|
158
|
+
readonly targetField: string;
|
|
159
|
+
} {
|
|
160
|
+
const parentField = `${parent}Id`;
|
|
161
|
+
const targetField = `${relation.target}Id`;
|
|
162
|
+
const fields = relation.fields?.shape ?? {};
|
|
163
|
+
const target = {
|
|
164
|
+
[targetField]: ref(relation.target, {
|
|
165
|
+
onDelete: relation.onDelete ?? 'restrict',
|
|
166
|
+
}),
|
|
167
|
+
};
|
|
168
|
+
return {
|
|
169
|
+
join: z.object({
|
|
170
|
+
[parentField]: ref(parent, { onDelete: 'cascade' }),
|
|
171
|
+
...target,
|
|
172
|
+
...fields,
|
|
173
|
+
}),
|
|
174
|
+
link: z.object({ ...target, ...fields }),
|
|
175
|
+
parentField,
|
|
176
|
+
targetField,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ---------------------------------------------------------------- types
|
|
181
|
+
|
|
182
|
+
/** The reference a field schema holds, through optional, nullable, default and array. */
|
|
183
|
+
type RefIn<F> = F extends { readonly '~ref'?: infer R extends RefInfo }
|
|
184
|
+
? R
|
|
185
|
+
: F extends
|
|
186
|
+
| z.ZodOptional<infer I>
|
|
187
|
+
| z.ZodNullable<infer I>
|
|
188
|
+
| z.ZodDefault<infer I>
|
|
189
|
+
| z.ZodArray<infer I>
|
|
190
|
+
? RefIn<I>
|
|
191
|
+
: never;
|
|
192
|
+
|
|
193
|
+
/** Each ref field of `Shape`, and the slug it refers to. */
|
|
194
|
+
export type RefSlugs<Shape extends z.core.$ZodShape> = {
|
|
195
|
+
[K in keyof Shape as [RefIn<Shape[K]>] extends [never] ? never : K]: RefIn<
|
|
196
|
+
Shape[K]
|
|
197
|
+
>['slug'];
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
/** The fields of `Shape` whose ref cascades. */
|
|
201
|
+
export type CascadeFields<Shape extends z.core.$ZodShape> = {
|
|
202
|
+
[K in keyof Shape]: [RefIn<Shape[K]>] extends [never]
|
|
203
|
+
? never
|
|
204
|
+
: RefIn<Shape[K]>['onDelete'] extends 'cascade'
|
|
205
|
+
? K
|
|
206
|
+
: never;
|
|
207
|
+
}[keyof Shape];
|
|
208
|
+
|
|
209
|
+
/** A field whose own schema is a ref with `nullify`: nothing wraps it optional or nullable. */
|
|
210
|
+
type RequiredNullify<Shape extends z.core.$ZodShape> = {
|
|
211
|
+
[K in keyof Shape]: Shape[K] extends {
|
|
212
|
+
readonly '~ref'?: RefInfo<string, 'nullify'>;
|
|
213
|
+
}
|
|
214
|
+
? K
|
|
215
|
+
: never;
|
|
216
|
+
}[keyof Shape];
|
|
217
|
+
|
|
218
|
+
/** A list of ids, possibly wrapped, with `cascade`. */
|
|
219
|
+
type ArrayCascade<F> =
|
|
220
|
+
F extends z.ZodArray<infer I>
|
|
221
|
+
? [RefIn<I>] extends [never]
|
|
222
|
+
? false
|
|
223
|
+
: RefIn<I>['onDelete'] extends 'cascade'
|
|
224
|
+
? true
|
|
225
|
+
: false
|
|
226
|
+
: F extends
|
|
227
|
+
| z.ZodOptional<infer I>
|
|
228
|
+
| z.ZodNullable<infer I>
|
|
229
|
+
| z.ZodDefault<infer I>
|
|
230
|
+
? ArrayCascade<I>
|
|
231
|
+
: false;
|
|
232
|
+
|
|
233
|
+
type CascadeArrays<Shape extends z.core.$ZodShape> = {
|
|
234
|
+
[K in keyof Shape]: ArrayCascade<Shape[K]> extends true ? K : never;
|
|
235
|
+
}[keyof Shape];
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* The definition-time rules of refs. A rejected schema adds a key the
|
|
239
|
+
* options lack, so the error names the field.
|
|
240
|
+
*/
|
|
241
|
+
export type RefCheck<Shape extends z.core.$ZodShape> = [
|
|
242
|
+
RequiredNullify<Shape>,
|
|
243
|
+
] extends [never]
|
|
244
|
+
? [CascadeArrays<Shape>] extends [never]
|
|
245
|
+
? unknown
|
|
246
|
+
: {
|
|
247
|
+
readonly '~error': `"${CascadeArrays<Shape> & string}" is a list of ids; it cannot cascade (use restrict or nullify)`;
|
|
248
|
+
}
|
|
249
|
+
: {
|
|
250
|
+
readonly '~error': `"${RequiredNullify<Shape> & string}" is required; nullify needs it .optional() or .nullable()`;
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
// ---------------------------------------------------------------- runtime
|
|
254
|
+
|
|
255
|
+
/** One ref field of a collection, as the generated delete reads it. */
|
|
256
|
+
export type RefField = {
|
|
257
|
+
readonly field: string;
|
|
258
|
+
readonly slug: string;
|
|
259
|
+
readonly onDelete: OnDelete;
|
|
260
|
+
/** A list of ids: nullify pulls the id, and a lookup uses `has`. */
|
|
261
|
+
readonly array: boolean;
|
|
262
|
+
/** What nullify writes: undefined to unset, or null. */
|
|
263
|
+
readonly cleared: null | undefined;
|
|
264
|
+
};
|
|
265
|
+
|
|
266
|
+
/** The ref a field schema holds, unwrapping as `RefIn` does. */
|
|
267
|
+
function refIn(
|
|
268
|
+
schema: z.core.$ZodType,
|
|
269
|
+
):
|
|
270
|
+
| { info: RefInfo; array: boolean; optional: boolean; nullable: boolean }
|
|
271
|
+
| undefined {
|
|
272
|
+
let current = schema;
|
|
273
|
+
let optional = false;
|
|
274
|
+
let nullable = false;
|
|
275
|
+
let array = false;
|
|
276
|
+
for (;;) {
|
|
277
|
+
if (current instanceof z.core.$ZodOptional) optional = true;
|
|
278
|
+
if (current instanceof z.core.$ZodNullable) nullable = true;
|
|
279
|
+
const inner = innerOf(current);
|
|
280
|
+
if (inner !== undefined) {
|
|
281
|
+
current = inner;
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
if (current instanceof z.core.$ZodArray && !array) {
|
|
285
|
+
array = true;
|
|
286
|
+
current = current._zod.def.element;
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
break;
|
|
290
|
+
}
|
|
291
|
+
const marker = (current._zod.def.checks ?? []).find(isMarker);
|
|
292
|
+
return marker === undefined
|
|
293
|
+
? undefined
|
|
294
|
+
: { info: marker['~lattice'], array, optional, nullable };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* The ref fields of a schema. Throws on the rules `RefCheck` states, for
|
|
299
|
+
* the forms the types do not catch.
|
|
300
|
+
*/
|
|
301
|
+
export function refsOf(slug: string, shape: z.core.$ZodShape): RefField[] {
|
|
302
|
+
const refs: RefField[] = [];
|
|
303
|
+
for (const [field, schema] of Object.entries(shape)) {
|
|
304
|
+
const found = refIn(schema);
|
|
305
|
+
if (found === undefined) continue;
|
|
306
|
+
const { info, array, optional, nullable } = found;
|
|
307
|
+
if (array && info.onDelete === 'cascade') {
|
|
308
|
+
throw new Error(
|
|
309
|
+
`Lattice: "${slug}.${field}" is a list of ids; it cannot cascade (use restrict or nullify)`,
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
if (!array && info.onDelete === 'nullify' && !optional && !nullable) {
|
|
313
|
+
throw new Error(
|
|
314
|
+
`Lattice: "${slug}.${field}" is required; nullify needs it .optional() or .nullable()`,
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
refs.push({
|
|
318
|
+
field,
|
|
319
|
+
slug: info.slug,
|
|
320
|
+
onDelete: info.onDelete,
|
|
321
|
+
array,
|
|
322
|
+
cleared: optional ? undefined : null,
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
return refs;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** A relation as REFERENCED names it: its parent collection and its name. */
|
|
329
|
+
export type RelationName = {
|
|
330
|
+
readonly collection: string;
|
|
331
|
+
readonly name: string;
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* A collection that refers to another one, through one of its ref fields.
|
|
336
|
+
* A join collection's refs carry the relation that derived it, since the
|
|
337
|
+
* join is not in the catalog.
|
|
338
|
+
*/
|
|
339
|
+
export type Referrer = {
|
|
340
|
+
readonly collection: AnyCollection;
|
|
341
|
+
readonly ref: RefField;
|
|
342
|
+
readonly relation: RelationName | undefined;
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
/** The referrers of each collection, by its slug. */
|
|
346
|
+
export type Referrers = ReadonlyMap<string, readonly Referrer[]>;
|
|
347
|
+
|
|
348
|
+
/** Who refers to each collection among `collections`. */
|
|
349
|
+
export function referrersOf(collections: readonly AnyCollection[]): Referrers {
|
|
350
|
+
const relations = new Map(
|
|
351
|
+
collections.flatMap((parent) =>
|
|
352
|
+
Object.entries(parent.relations).map(
|
|
353
|
+
([name, relation]): [string, RelationName] => [
|
|
354
|
+
relation.through.slug,
|
|
355
|
+
{ collection: parent.slug, name },
|
|
356
|
+
],
|
|
357
|
+
),
|
|
358
|
+
),
|
|
359
|
+
);
|
|
360
|
+
const referrers = new Map<string, Referrer[]>();
|
|
361
|
+
for (const collection of collections) {
|
|
362
|
+
const relation = relations.get(collection.slug);
|
|
363
|
+
for (const ref of collection.refs) {
|
|
364
|
+
const list = referrers.get(ref.slug) ?? [];
|
|
365
|
+
list.push({ collection, ref, relation });
|
|
366
|
+
referrers.set(ref.slug, list);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return referrers;
|
|
370
|
+
}
|
package/src/repo.ts
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import type { z } from 'zod';
|
|
2
|
+
import { unscoped, whereOf } from './access.js';
|
|
3
|
+
import type { AnyCollection } from './collection.js';
|
|
4
|
+
import { LatticeError, parse } from './errors.js';
|
|
5
|
+
import { defaultLimit, defaultSort, keyOf, type Sort } from './sort.js';
|
|
6
|
+
import type { CollectionStore, FindQuery, Patch, StoredDoc } from './store.js';
|
|
7
|
+
import { type Scope, type TenantField, withoutTenant } from './tenancy.js';
|
|
8
|
+
import { type AnyWhere, both, nullish, type Where } from './where.js';
|
|
9
|
+
|
|
10
|
+
/** A collection's stored document: its schema plus `id`, `createdAt` and `updatedAt`. */
|
|
11
|
+
export type Doc<C extends { readonly output: z.ZodType }> = z.output<
|
|
12
|
+
C['output']
|
|
13
|
+
>;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A collection's document as a client receives it: `Doc`, with each
|
|
17
|
+
* maskable field optional, since the caller's rules may withhold it.
|
|
18
|
+
*/
|
|
19
|
+
export type ClientDoc<C extends { readonly clientOutput: z.ZodType }> =
|
|
20
|
+
z.output<C['clientOutput']>;
|
|
21
|
+
|
|
22
|
+
/** A query of `Repo.find`. Each key is optional; the defaults are find's. */
|
|
23
|
+
export type RepoQuery<D> = {
|
|
24
|
+
readonly where?: Where<D>;
|
|
25
|
+
readonly sort?: Sort<D>;
|
|
26
|
+
readonly limit?: number;
|
|
27
|
+
/** The `next` cursor of the previous page. */
|
|
28
|
+
readonly after?: string;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* What a `Repo` call runs under: the call's scope for this collection, from
|
|
33
|
+
* `ctx.access.scope()`, or `unscoped` for trusted code that acts for no
|
|
34
|
+
* caller. Required, so a forgotten filter cannot read every row (0023).
|
|
35
|
+
*/
|
|
36
|
+
export type RepoScope<C extends AnyCollection> =
|
|
37
|
+
| Scope<C['slug']>
|
|
38
|
+
| typeof unscoped;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* What `insert` runs under. A tenanted collection's new row needs its
|
|
42
|
+
* tenant, so `unscoped` cannot insert into it: use the call's scope, or
|
|
43
|
+
* `tenancy.scope(C, tenantId)`.
|
|
44
|
+
*/
|
|
45
|
+
export type InsertScope<C extends AnyCollection> = [TenantField<C>] extends [
|
|
46
|
+
never,
|
|
47
|
+
]
|
|
48
|
+
? RepoScope<C>
|
|
49
|
+
: Scope<C['slug']>;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* A typed view of the `CollectionStore` for one collection, for hand-written
|
|
53
|
+
* use cases and event handlers. It is trusted: no hooks, no events and no
|
|
54
|
+
* access. `insert` parses its data with the schema, as create does; `update`
|
|
55
|
+
* writes its typed patch as given. Each call runs under
|
|
56
|
+
* the scope it is given: a row outside it acts as missing. A tenant bypass
|
|
57
|
+
* scope reads only: a write through it on a tenanted collection is
|
|
58
|
+
* FORBIDDEN.
|
|
59
|
+
*/
|
|
60
|
+
export interface Repo<C extends AnyCollection> {
|
|
61
|
+
get(id: string, scope: RepoScope<C>): Promise<Doc<C> | null>;
|
|
62
|
+
/** The docs that exist and are in scope, in the order of `ids`. */
|
|
63
|
+
getMany(ids: readonly string[], scope: RepoScope<C>): Promise<Doc<C>[]>;
|
|
64
|
+
find(
|
|
65
|
+
query: RepoQuery<Doc<C>>,
|
|
66
|
+
scope: RepoScope<C>,
|
|
67
|
+
): Promise<{
|
|
68
|
+
docs: Doc<C>[];
|
|
69
|
+
next: string | null;
|
|
70
|
+
}>;
|
|
71
|
+
/** How many documents in scope match `where`. */
|
|
72
|
+
count(where: Where<Doc<C>>, scope: RepoScope<C>): Promise<number>;
|
|
73
|
+
/**
|
|
74
|
+
* Parses `data` with the collection's schema, as create does: defaults
|
|
75
|
+
* apply, unknown keys are dropped, and a failed check is VALIDATION. Then
|
|
76
|
+
* stores it with a new `id`, `createdAt`, `updatedAt` and the scope's
|
|
77
|
+
* tenant.
|
|
78
|
+
*/
|
|
79
|
+
insert(data: z.input<C['schema']>, scope: InsertScope<C>): Promise<Doc<C>>;
|
|
80
|
+
/**
|
|
81
|
+
* Writes the fields in `patch` and bumps `updatedAt`; null when no doc in
|
|
82
|
+
* scope has `id`. It never writes the tenant field.
|
|
83
|
+
*/
|
|
84
|
+
update(
|
|
85
|
+
id: string,
|
|
86
|
+
patch: Partial<z.output<C['schema']>>,
|
|
87
|
+
scope: RepoScope<C>,
|
|
88
|
+
): Promise<Doc<C> | null>;
|
|
89
|
+
/** The removed doc, or null when no doc in scope has `id`. */
|
|
90
|
+
remove(id: string, scope: RepoScope<C>): Promise<Doc<C> | null>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The filter of a write. A bypass scope has no tenant, so it cannot write a
|
|
95
|
+
* tenanted collection.
|
|
96
|
+
*/
|
|
97
|
+
function writable(
|
|
98
|
+
collection: AnyCollection,
|
|
99
|
+
scope: Scope | typeof unscoped,
|
|
100
|
+
): AnyWhere | undefined {
|
|
101
|
+
const where = whereOf(collection.slug, scope);
|
|
102
|
+
if (
|
|
103
|
+
collection.tenant !== undefined &&
|
|
104
|
+
scope !== unscoped &&
|
|
105
|
+
scope.tenantId === undefined
|
|
106
|
+
) {
|
|
107
|
+
throw LatticeError.FORBIDDEN();
|
|
108
|
+
}
|
|
109
|
+
return where;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** A new document: `data` with an `id`, `createdAt` and `updatedAt`. */
|
|
113
|
+
export function stamped<D extends object>(data: D) {
|
|
114
|
+
const now = new Date().toISOString();
|
|
115
|
+
return { ...data, id: crypto.randomUUID(), createdAt: now, updatedAt: now };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** A patch that also bumps `updatedAt`. */
|
|
119
|
+
export function touched<P extends Patch>(patch: P) {
|
|
120
|
+
return { ...patch, updatedAt: new Date().toISOString() };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** A store query with find's default sort and limit. */
|
|
124
|
+
export function findQuery(
|
|
125
|
+
collection: AnyCollection,
|
|
126
|
+
query: {
|
|
127
|
+
readonly where?: AnyWhere | undefined;
|
|
128
|
+
readonly sort?: readonly string[] | undefined;
|
|
129
|
+
readonly limit?: number | undefined;
|
|
130
|
+
readonly after?: string | undefined;
|
|
131
|
+
},
|
|
132
|
+
): FindQuery {
|
|
133
|
+
const { where, limit, after } = query;
|
|
134
|
+
const sort = query.sort ?? defaultSort;
|
|
135
|
+
const { shape } = collection.output;
|
|
136
|
+
return {
|
|
137
|
+
collection: collection.slug,
|
|
138
|
+
sort,
|
|
139
|
+
// The sort fields the schema lets a document lack.
|
|
140
|
+
optional: sort
|
|
141
|
+
.map((key) => keyOf(key).field)
|
|
142
|
+
.filter((field) => {
|
|
143
|
+
const schema = shape[field];
|
|
144
|
+
return schema !== undefined && nullish(schema);
|
|
145
|
+
}),
|
|
146
|
+
limit: limit ?? defaultLimit,
|
|
147
|
+
...(where === undefined ? {} : { where }),
|
|
148
|
+
...(after === undefined ? {} : { after }),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The repo of `collection`. The store holds untyped documents (`StoredDoc`); a
|
|
154
|
+
* repo trusts that each one has its collection's type, as the writes that
|
|
155
|
+
* put it there did. The overload states that type; the implementation is
|
|
156
|
+
* typed for any collection, so no value is cast.
|
|
157
|
+
*/
|
|
158
|
+
export function repo<C extends AnyCollection>(
|
|
159
|
+
store: CollectionStore,
|
|
160
|
+
collection: C,
|
|
161
|
+
): Repo<C>;
|
|
162
|
+
export function repo(
|
|
163
|
+
store: CollectionStore,
|
|
164
|
+
collection: AnyCollection,
|
|
165
|
+
): Omit<Repo<AnyCollection>, 'insert'> & {
|
|
166
|
+
// Any collection: a global one's insert takes `unscoped` too.
|
|
167
|
+
insert(
|
|
168
|
+
data: z.input<AnyCollection['schema']>,
|
|
169
|
+
scope: RepoScope<AnyCollection>,
|
|
170
|
+
): Promise<Doc<AnyCollection>>;
|
|
171
|
+
} {
|
|
172
|
+
const { slug } = collection;
|
|
173
|
+
// Each method is async, so a scope for another collection rejects, as a
|
|
174
|
+
// store failure would, rather than throwing before a promise exists.
|
|
175
|
+
return {
|
|
176
|
+
async get(id, scope) {
|
|
177
|
+
return store.get(slug, id, whereOf(slug, scope));
|
|
178
|
+
},
|
|
179
|
+
async getMany(ids, scope) {
|
|
180
|
+
return store.getMany(slug, ids, whereOf(slug, scope));
|
|
181
|
+
},
|
|
182
|
+
async find(query, scope) {
|
|
183
|
+
const where = both(query.where, whereOf(slug, scope));
|
|
184
|
+
return store.find(findQuery(collection, { ...query, where }));
|
|
185
|
+
},
|
|
186
|
+
async count(where, scope) {
|
|
187
|
+
return store.count(slug, both(where, whereOf(slug, scope)));
|
|
188
|
+
},
|
|
189
|
+
async insert(data, scope) {
|
|
190
|
+
// A new row has no filter to meet, but a scope for another collection
|
|
191
|
+
// is still refused.
|
|
192
|
+
writable(collection, scope);
|
|
193
|
+
const { tenant } = collection;
|
|
194
|
+
if (tenant !== undefined && scope === unscoped) {
|
|
195
|
+
throw new Error(
|
|
196
|
+
`Lattice: "${slug}" is tenanted, so insert needs a scope with a tenant, such as tenancy.scope()`,
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
// The tenant comes from the scope, after the parse: the schema has none.
|
|
200
|
+
const parsed = parse(collection.schema, data);
|
|
201
|
+
const doc: StoredDoc = stamped(
|
|
202
|
+
tenant === undefined || scope === unscoped
|
|
203
|
+
? parsed
|
|
204
|
+
: { ...parsed, [tenant]: scope.tenantId },
|
|
205
|
+
);
|
|
206
|
+
await store.insert(slug, doc);
|
|
207
|
+
return doc;
|
|
208
|
+
},
|
|
209
|
+
async update(id, patch, scope) {
|
|
210
|
+
const where = writable(collection, scope);
|
|
211
|
+
const changes = touched(withoutTenant(collection, patch));
|
|
212
|
+
return store.update(slug, id, changes, where);
|
|
213
|
+
},
|
|
214
|
+
async remove(id, scope) {
|
|
215
|
+
return store.remove(slug, id, writable(collection, scope));
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
}
|