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