@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/mask.ts ADDED
@@ -0,0 +1,336 @@
1
+ import { z } from 'zod';
2
+ import { CallAccess } from './access.js';
3
+ import { LatticeError } from './errors.js';
4
+ import { type Masked, marked, markOf } from './marker.js';
5
+ import { innerOf } from './where.js';
6
+
7
+ /** `Shape` with each maskable field optional, as a client may receive it. */
8
+ export type MaskShape<Shape extends z.core.$ZodShape, M extends string> = {
9
+ [K in keyof Shape]: K extends M ? z.ZodOptional<Shape[K]> : Shape[K];
10
+ };
11
+
12
+ /**
13
+ * The shapes a collection's outputs are built from: `stored`, with each
14
+ * maskable field marked, and `client`, with each marked and optional.
15
+ */
16
+ export function maskShapes<Shape extends z.core.$ZodShape, M extends string>(
17
+ slug: string,
18
+ shape: Shape,
19
+ maskable: readonly M[],
20
+ ): { readonly stored: Shape; readonly client: MaskShape<Shape, M> };
21
+ export function maskShapes(
22
+ slug: string,
23
+ shape: z.core.$ZodShape,
24
+ maskable: readonly string[],
25
+ ): { readonly stored: z.core.$ZodShape; readonly client: z.core.$ZodShape } {
26
+ const stored: Record<string, z.core.$ZodType> = { ...shape };
27
+ const client: Record<string, z.core.$ZodType> = { ...shape };
28
+ for (const field of maskable) {
29
+ const schema = shape[field];
30
+ if (schema === undefined) continue;
31
+ const mark = marked(schema, { collection: slug, field });
32
+ stored[field] = mark;
33
+ // The description reaches JSON Schema, so OpenAPI and MCP say why.
34
+ client[field] = z
35
+ .optional(mark)
36
+ .describe('Withheld when the caller may not read it.');
37
+ }
38
+ return { stored, client };
39
+ }
40
+
41
+ /**
42
+ * Where in an output a withheld field is removed. Built once per procedure
43
+ * from its output schema; only the parts that hold a masked field.
44
+ */
45
+ export type MaskPlan =
46
+ | {
47
+ readonly kind: 'object';
48
+ readonly keys: ReadonlyMap<
49
+ string,
50
+ { readonly masked?: Masked; readonly child?: MaskPlan }
51
+ >;
52
+ }
53
+ | { readonly kind: 'array'; readonly item: MaskPlan }
54
+ | { readonly kind: 'record'; readonly value: MaskPlan }
55
+ | {
56
+ readonly kind: 'tuple';
57
+ readonly items: readonly (MaskPlan | undefined)[];
58
+ readonly rest: MaskPlan | undefined;
59
+ }
60
+ // A union or an intersection: the value may match any branch, so every
61
+ // branch's masks apply. A key is only ever removed, so this can over-mask
62
+ // a same-named key of another branch, never under-mask.
63
+ | { readonly kind: 'each'; readonly plans: readonly MaskPlan[] };
64
+
65
+ /** The name of a schema kind Lattice cannot see through, or undefined. */
66
+ function opaque(schema: z.core.$ZodType): string | undefined {
67
+ if (schema instanceof z.core.$ZodLazy) return 'z.lazy()';
68
+ if (schema instanceof z.core.$ZodPipe) return 'a pipe or transform';
69
+ if (schema instanceof z.core.$ZodTransform) return 'a transform';
70
+ if (schema instanceof z.core.$ZodCustom) return 'z.custom()';
71
+ if (schema instanceof z.core.$ZodAny) return 'z.any()';
72
+ if (schema instanceof z.core.$ZodUnknown) return 'z.unknown()';
73
+ if (schema instanceof z.core.$ZodPromise) return 'z.promise()';
74
+ return undefined;
75
+ }
76
+
77
+ /**
78
+ * The mask plan of an output schema, or undefined when nothing in it is
79
+ * masked. `where` names the procedure, for errors. It sees through objects,
80
+ * arrays, records, tuples, unions, intersections and the optional, nullable,
81
+ * default, readonly and catch wrappers. A schema it cannot see through
82
+ * throws, so no masked field can hide inside one. A masked field must be
83
+ * optional where it sits: a client may not receive it.
84
+ */
85
+ export function maskPlan(
86
+ schema: z.core.$ZodType,
87
+ where: string,
88
+ ): MaskPlan | undefined {
89
+ const fail = (message: string): never => {
90
+ throw new Error(`Lattice: the output of "${where}" ${message}`);
91
+ };
92
+ const visit = (node: z.core.$ZodType): MaskPlan | undefined => {
93
+ const mark = markOf(node);
94
+ if (mark !== undefined) {
95
+ fail(
96
+ `holds ${mark.collection}.${mark.field} where it is required; declare it optional: use the collection's clientOutput`,
97
+ );
98
+ }
99
+ const kind = opaque(node);
100
+ if (kind !== undefined) {
101
+ fail(
102
+ `has ${kind}, which Lattice cannot see through to mask a field; declare a plain schema`,
103
+ );
104
+ }
105
+ const inner = innerOf(node);
106
+ if (inner !== undefined) return visit(inner);
107
+ if (node instanceof z.core.$ZodObject) {
108
+ const keys = new Map<string, { masked?: Masked; child?: MaskPlan }>();
109
+ for (const [key, field] of Object.entries(node._zod.def.shape)) {
110
+ const found = maskedField(field);
111
+ if (found !== undefined) {
112
+ if (!found.optional) {
113
+ fail(
114
+ `holds ${found.masked.collection}.${found.masked.field} where it is required, as "${key}"; declare it optional: use the collection's clientOutput`,
115
+ );
116
+ }
117
+ keys.set(key, { masked: found.masked });
118
+ continue;
119
+ }
120
+ const child = visit(field);
121
+ if (child !== undefined) keys.set(key, { child });
122
+ }
123
+ return keys.size === 0 ? undefined : { kind: 'object', keys };
124
+ }
125
+ if (node instanceof z.core.$ZodArray) {
126
+ const item = visit(node._zod.def.element);
127
+ return item === undefined ? undefined : { kind: 'array', item };
128
+ }
129
+ if (node instanceof z.core.$ZodRecord) {
130
+ const value = visit(node._zod.def.valueType);
131
+ return value === undefined ? undefined : { kind: 'record', value };
132
+ }
133
+ if (node instanceof z.core.$ZodTuple) {
134
+ const items = node._zod.def.items.map(visit);
135
+ const { rest: restSchema } = node._zod.def;
136
+ const rest = restSchema === null ? undefined : visit(restSchema);
137
+ return items.every((item) => item === undefined) && rest === undefined
138
+ ? undefined
139
+ : { kind: 'tuple', items, rest };
140
+ }
141
+ const branches =
142
+ node instanceof z.core.$ZodUnion
143
+ ? node._zod.def.options
144
+ : node instanceof z.core.$ZodIntersection
145
+ ? [node._zod.def.left, node._zod.def.right]
146
+ : [];
147
+ const plans = branches.flatMap((branch) => visit(branch) ?? []);
148
+ return plans.length === 0 ? undefined : { kind: 'each', plans };
149
+ };
150
+ return visit(schema);
151
+ }
152
+
153
+ /**
154
+ * The masked field an object property holds, seen through its wrappers, and
155
+ * whether the property may be absent. Undefined for an unmasked property.
156
+ */
157
+ function maskedField(
158
+ field: z.core.$ZodType,
159
+ ): { masked: Masked; optional: boolean } | undefined {
160
+ let current: z.core.$ZodType | undefined = field;
161
+ let optional = false;
162
+ while (current !== undefined) {
163
+ if (current instanceof z.core.$ZodOptional) optional = true;
164
+ const mark = markOf(current);
165
+ if (mark !== undefined) return { masked: mark, optional };
166
+ current = innerOf(current);
167
+ }
168
+ return undefined;
169
+ }
170
+
171
+ /** The collections a plan masks fields of. */
172
+ export function maskedCollections(plan: MaskPlan): Set<string> {
173
+ const slugs = new Set<string>();
174
+ const visit = (node: MaskPlan): void => {
175
+ switch (node.kind) {
176
+ case 'object':
177
+ for (const { masked, child } of node.keys.values()) {
178
+ if (masked !== undefined) slugs.add(masked.collection);
179
+ if (child !== undefined) visit(child);
180
+ }
181
+ return;
182
+ case 'array':
183
+ visit(node.item);
184
+ return;
185
+ case 'record':
186
+ visit(node.value);
187
+ return;
188
+ case 'tuple':
189
+ for (const item of node.items) if (item !== undefined) visit(item);
190
+ if (node.rest !== undefined) visit(node.rest);
191
+ return;
192
+ case 'each':
193
+ for (const plan of node.plans) visit(plan);
194
+ }
195
+ };
196
+ visit(plan);
197
+ return slugs;
198
+ }
199
+
200
+ function isRecord(value: unknown): value is Record<string, unknown> {
201
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
202
+ }
203
+
204
+ /**
205
+ * `value` with each field `withheld` says to remove taken out, where `plan`
206
+ * puts one. It copies what it changes, so a document the use case still
207
+ * holds is not changed.
208
+ */
209
+ export function applyMask(
210
+ plan: MaskPlan,
211
+ value: unknown,
212
+ withheld: (masked: Masked) => boolean,
213
+ ): unknown {
214
+ switch (plan.kind) {
215
+ case 'object': {
216
+ if (!isRecord(value)) return value;
217
+ let out: Record<string, unknown> | undefined;
218
+ for (const [key, { masked, child }] of plan.keys) {
219
+ if (!Object.hasOwn(value, key)) continue;
220
+ out ??= { ...value };
221
+ if (masked !== undefined && withheld(masked)) {
222
+ delete out[key];
223
+ } else if (child !== undefined) {
224
+ out[key] = applyMask(child, value[key], withheld);
225
+ }
226
+ }
227
+ return out ?? value;
228
+ }
229
+ case 'array':
230
+ return Array.isArray(value)
231
+ ? value.map((item) => applyMask(plan.item, item, withheld))
232
+ : value;
233
+ case 'record':
234
+ return isRecord(value)
235
+ ? Object.fromEntries(
236
+ Object.entries(value).map(([key, item]) => [
237
+ key,
238
+ applyMask(plan.value, item, withheld),
239
+ ]),
240
+ )
241
+ : value;
242
+ case 'tuple':
243
+ return Array.isArray(value)
244
+ ? value.map((item, index) => {
245
+ const itemPlan =
246
+ index < plan.items.length ? plan.items[index] : plan.rest;
247
+ return itemPlan === undefined
248
+ ? item
249
+ : applyMask(itemPlan, item, withheld);
250
+ })
251
+ : value;
252
+ case 'each':
253
+ return plan.plans.reduce(
254
+ (current, branch) => applyMask(branch, current, withheld),
255
+ value,
256
+ );
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Refuses, as VALIDATION, a `where` or `sort` on find or count, or an
262
+ * update patch, that names a field withheld from the caller (0031, 0035).
263
+ * A query would reveal it through which rows match or their order, and an
264
+ * update would change a value the caller cannot see. The family guard runs
265
+ * it on every use case, and the generated bodies run it again (0036), so a
266
+ * body called from an override skips nothing.
267
+ */
268
+ export async function refuseWithheld(
269
+ access: CallAccess,
270
+ collection: {
271
+ readonly slug: string;
272
+ readonly maskable: readonly string[];
273
+ },
274
+ action: string,
275
+ input: unknown,
276
+ ): Promise<void> {
277
+ if (action !== 'find' && action !== 'count' && action !== 'update') return;
278
+ const withheld = await CallAccess.withheld(access, collection);
279
+ if (withheld.size === 0) return;
280
+ const issues =
281
+ action === 'update'
282
+ ? withheldWrites(input, withheld)
283
+ : withheldPaths(input, withheld);
284
+ if (issues.length > 0) throw LatticeError.VALIDATION({ issues });
285
+ }
286
+
287
+ /**
288
+ * The keys of an update's patch that name a withheld field, for VALIDATION
289
+ * issues (0035): a caller cannot change, or clear, what it cannot read.
290
+ */
291
+ function withheldWrites(
292
+ input: unknown,
293
+ withheld: ReadonlySet<string>,
294
+ ): { path: (string | number)[]; message: string }[] {
295
+ if (!isRecord(input)) return [];
296
+ return Object.entries(input)
297
+ .filter(([key, value]) => value !== undefined && withheld.has(key))
298
+ .map(([key]) => ({
299
+ path: [key],
300
+ message: `"${key}" is not readable, so it cannot be changed`,
301
+ }));
302
+ }
303
+
304
+ /** The where and sort paths that name a withheld field, for VALIDATION issues. */
305
+ function withheldPaths(
306
+ input: unknown,
307
+ withheld: ReadonlySet<string>,
308
+ ): { path: (string | number)[]; message: string }[] {
309
+ const issues: { path: (string | number)[]; message: string }[] = [];
310
+ const message = (field: string) => `"${field}" is not readable`;
311
+ const where = (node: unknown, path: (string | number)[]): void => {
312
+ if (!isRecord(node)) return;
313
+ for (const [key, value] of Object.entries(node)) {
314
+ if ((key === 'and' || key === 'or') && Array.isArray(value)) {
315
+ value.forEach((clause, index) => {
316
+ where(clause, [...path, key, index]);
317
+ });
318
+ } else if (withheld.has(key)) {
319
+ issues.push({ path: [...path, key], message: message(key) });
320
+ }
321
+ }
322
+ };
323
+ if (!isRecord(input)) return issues;
324
+ where(input.where, ['where']);
325
+ const { sort } = input;
326
+ if (Array.isArray(sort)) {
327
+ sort.forEach((key, index) => {
328
+ if (typeof key !== 'string') return;
329
+ const field = key.startsWith('-') ? key.slice(1) : key;
330
+ if (withheld.has(field)) {
331
+ issues.push({ path: ['sort', index], message: message(field) });
332
+ }
333
+ });
334
+ }
335
+ return issues;
336
+ }
@@ -0,0 +1,103 @@
1
+ import { z } from 'zod';
2
+ import type { AnyCollection, AnyRelation } from './collection.js';
3
+
4
+ /**
5
+ * A populated document the caller may not read, or one that no longer
6
+ * exists: its id only (0022). A UI can still show the row.
7
+ */
8
+ const withheld = z.object({ id: z.string() });
9
+
10
+ export type Withheld = z.output<typeof withheld>;
11
+
12
+ /**
13
+ * A read's `populate` input: a list of `keys`, or no field when there are
14
+ * none. An object, so a read's input extends its `shape`, and typed, so the
15
+ * read's body takes its list from one parse.
16
+ */
17
+ export type PopulateInput = z.ZodObject &
18
+ z.ZodType<{ populate?: string[] | undefined }>;
19
+
20
+ export function populateInput(keys: readonly string[]): PopulateInput {
21
+ const [first, ...rest] = keys;
22
+ return first === undefined
23
+ ? z.object({})
24
+ : z.object({ populate: z.array(z.enum([first, ...rest])).optional() });
25
+ }
26
+
27
+ /**
28
+ * What `populate` may name on a read of `collection`: its ref fields, and
29
+ * on `get` its `many()` relations. `find` populates refs only, so a page
30
+ * cannot fetch up to 1000 links for each of its documents.
31
+ */
32
+ export function populateKeys(
33
+ collection: AnyCollection,
34
+ read: 'get' | 'find',
35
+ ): string[] {
36
+ return [
37
+ ...collection.refs.map((ref) => ref.field),
38
+ ...(read === 'get' ? Object.keys(collection.relations) : []),
39
+ ];
40
+ }
41
+
42
+ /** The fields a link of `relation` carries, beside its two refs. */
43
+ export function linkFields(relation: AnyRelation): string[] {
44
+ return Object.keys(relation.through.schema.shape).filter(
45
+ (field) => field !== relation.parentField && field !== relation.targetField,
46
+ );
47
+ }
48
+
49
+ /**
50
+ * The schemas of a populated read of `collection`, by the client output
51
+ * schema of each collection: `fields` holds each ref field's expanded schema (its
52
+ * target document or `Withheld`, element-wise for a list of ids), and `wide`
53
+ * is the document as a read sends it, with each ref field plain or expanded.
54
+ */
55
+ export function expansionOf(
56
+ collection: AnyCollection,
57
+ outputs: ReadonlyMap<string, z.ZodType>,
58
+ read: 'get' | 'find',
59
+ ): {
60
+ readonly fields: Readonly<Record<string, z.ZodType>>;
61
+ readonly wide: z.ZodObject;
62
+ } {
63
+ const fields: Record<string, z.ZodType> = {};
64
+ const wide: Record<string, z.ZodType> = {};
65
+ const targetOf = (slug: string) => {
66
+ const target = outputs.get(slug);
67
+ if (target === undefined) {
68
+ throw new Error(
69
+ `Lattice: "${slug}" is not a collection of this framework, so ${collection.slug} cannot populate it`,
70
+ );
71
+ }
72
+ return z.union([target, withheld]);
73
+ };
74
+ for (const { field, slug, array } of collection.refs) {
75
+ const one = targetOf(slug);
76
+ const plain = collection.clientOutput.shape[field];
77
+ if (plain === undefined) {
78
+ throw new Error(`Lattice: ${collection.slug} has no field "${field}"`);
79
+ }
80
+ const expanded = array ? z.array(one) : one;
81
+ fields[field] = expanded;
82
+ wide[field] = z.union([plain, expanded]);
83
+ }
84
+ if (read === 'get') {
85
+ // A relation is in the output only when populated: its links, each
86
+ // with its fields and its target document.
87
+ for (const [name, relation] of Object.entries(collection.relations)) {
88
+ const { shape } = relation.through.clientOutput;
89
+ const link = z.object({
90
+ ...Object.fromEntries(
91
+ linkFields(relation).flatMap((field) => {
92
+ const schema = shape[field];
93
+ return schema === undefined ? [] : [[field, schema]];
94
+ }),
95
+ ),
96
+ doc: targetOf(relation.target),
97
+ });
98
+ fields[name] = z.array(link);
99
+ wide[name] = z.array(link).optional();
100
+ }
101
+ }
102
+ return { fields, wide: collection.clientOutput.extend(wide) };
103
+ }