@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
@@ -0,0 +1,232 @@
1
+ import { type DocsMeta, docs } from '@ts-pf/docs';
2
+ import { type McpEffect, mcp } from '@ts-pf/mcp/meta';
3
+
4
+ /**
5
+ * Every text and fact Lattice writes into a contract, in one place: each
6
+ * procedure's summary and `lattice` meta, a collection's label, and why a
7
+ * query on a maskable field may be refused. They reach the catalog, so
8
+ * OpenAPI, codegen's JSDoc, MCP tools and the admin read them with no code
9
+ * in the app.
10
+ */
11
+
12
+ /** A generated collection operation, or a relation's. */
13
+ type GeneratedOp =
14
+ | 'find'
15
+ | 'count'
16
+ | 'get'
17
+ | 'create'
18
+ | 'update'
19
+ | 'delete'
20
+ | 'list'
21
+ | 'set';
22
+
23
+ /**
24
+ * How an operation affects data, as `@ts-pf/mcp` reads it for tool
25
+ * annotations: reads are read-only, and an operation that removes data
26
+ * (delete, or a relation's `set`, which drops links it is not given) is
27
+ * destructive.
28
+ */
29
+ export type EffectOf<Op extends GeneratedOp> = Op extends
30
+ | 'find'
31
+ | 'count'
32
+ | 'get'
33
+ | 'list'
34
+ ? 'read'
35
+ : Op extends 'delete' | 'set'
36
+ ? 'destructive'
37
+ : 'write';
38
+
39
+ const effects: { readonly [Op in GeneratedOp]: EffectOf<Op> } = {
40
+ find: 'read',
41
+ count: 'read',
42
+ get: 'read',
43
+ list: 'read',
44
+ create: 'write',
45
+ update: 'write',
46
+ delete: 'destructive',
47
+ set: 'destructive',
48
+ };
49
+
50
+ /** How a collection reads in a sentence: `{ singular: 'company', plural: 'companies' }`. */
51
+ export type Label = { readonly singular: string; readonly plural: string };
52
+
53
+ /**
54
+ * What every Lattice procedure says about itself in its meta, under the
55
+ * `lattice` key: its collection and that collection's label, and which
56
+ * operation it is. A relation's `list` and `set` name the relation, and a
57
+ * method names itself. An override carries the meta of the operation it
58
+ * replaces, because clients see the same procedure.
59
+ */
60
+ export type LatticeMeta =
61
+ | {
62
+ readonly collection: string;
63
+ readonly label: Label;
64
+ readonly operation:
65
+ | 'find'
66
+ | 'count'
67
+ | 'get'
68
+ | 'create'
69
+ | 'update'
70
+ | 'delete';
71
+ }
72
+ | {
73
+ readonly collection: string;
74
+ readonly label: Label;
75
+ readonly operation: 'list' | 'set';
76
+ readonly relation: string;
77
+ /** The slug of the collection the relation's links point to. */
78
+ readonly target: string;
79
+ }
80
+ | {
81
+ readonly collection: string;
82
+ readonly label: Label;
83
+ readonly operation: 'method';
84
+ readonly method: string;
85
+ };
86
+
87
+ /** A procedure's meta: its summary, its MCP effect, and Lattice's facts. */
88
+ export type ProcedureMeta<Fx extends McpEffect> = {
89
+ readonly docs: DocsMeta;
90
+ readonly mcp: { readonly effect: Fx };
91
+ readonly lattice: LatticeMeta;
92
+ };
93
+
94
+ /** The words of an identifier: `post_categories` and `postCategories` are "post categories". */
95
+ function words(name: string): string {
96
+ return name
97
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
98
+ .split(/[\s_-]+/)
99
+ .filter((word) => word.length > 0)
100
+ .join(' ')
101
+ .toLowerCase();
102
+ }
103
+
104
+ /**
105
+ * The singular of an English plural, for the common endings only. A slug
106
+ * it gets wrong, such as `news` or `people`, declares its label.
107
+ */
108
+ function singularOf(plural: string): string {
109
+ if (/[^aeiou]ies$/.test(plural)) return `${plural.slice(0, -3)}y`;
110
+ if (/(sses|shes|ches|xes|zzes)$/.test(plural)) return plural.slice(0, -2);
111
+ if (/(ss|us|is)$/.test(plural) || !plural.endsWith('s')) return plural;
112
+ return plural.slice(0, -1);
113
+ }
114
+
115
+ /** A collection's label from its slug: `deal_stages` is "deal stage" and "deal stages". */
116
+ export function labelOf(slug: string): Label {
117
+ const plural = words(slug);
118
+ const last = plural.lastIndexOf(' ');
119
+ return {
120
+ singular: `${plural.slice(0, last + 1)}${singularOf(plural.slice(last + 1))}`,
121
+ plural,
122
+ };
123
+ }
124
+
125
+ /** What a summary names: the collection, the operation, and what it populates. */
126
+ export type Described =
127
+ | {
128
+ readonly slug: string;
129
+ readonly label: Label;
130
+ readonly op: Exclude<GeneratedOp, 'list' | 'set'>;
131
+ readonly populate: readonly string[];
132
+ }
133
+ | {
134
+ readonly slug: string;
135
+ readonly label: Label;
136
+ readonly op: 'list' | 'set';
137
+ readonly relation: string;
138
+ readonly target: string;
139
+ readonly populate: readonly string[];
140
+ };
141
+
142
+ const query =
143
+ 'Filter with where, order with sort, and page with limit and after (the previous page’s next).';
144
+
145
+ /**
146
+ * One short sentence per operation, naming the inputs that matter. "One",
147
+ * not "a" or "an": the article depends on how the label sounds.
148
+ */
149
+ function summaryOf(described: Described): string {
150
+ const { singular, plural } = described.label;
151
+ const populate =
152
+ described.populate.length === 0
153
+ ? ''
154
+ : ` populate expands ${described.populate.join(', ')} into documents.`;
155
+ switch (described.op) {
156
+ case 'find':
157
+ return `Find ${plural}. ${query}${populate}`;
158
+ case 'count':
159
+ return `Count ${plural}. Filter with where.`;
160
+ case 'get':
161
+ return `Get one ${singular} by id.${populate}`;
162
+ case 'create':
163
+ return `Create one ${singular}.`;
164
+ case 'update':
165
+ return `Update one ${singular} by id. Send only the fields to change, and null to clear an optional one.`;
166
+ case 'delete':
167
+ return `Delete one ${singular} by id.`;
168
+ case 'list':
169
+ return `List the ${words(described.relation)} of one ${singular}, by its id. ${query}${populate}`;
170
+ case 'set':
171
+ return `Replace the ${words(described.relation)} of one ${singular}, by its id. Links not given are removed.`;
172
+ }
173
+ }
174
+
175
+ /** The `lattice` meta of a generated or relation procedure. */
176
+ function latticeOf(described: Described): LatticeMeta {
177
+ const { slug, label } = described;
178
+ switch (described.op) {
179
+ case 'list':
180
+ case 'set':
181
+ return {
182
+ collection: slug,
183
+ label,
184
+ operation: described.op,
185
+ relation: described.relation,
186
+ target: described.target,
187
+ };
188
+ default:
189
+ return { collection: slug, label, operation: described.op };
190
+ }
191
+ }
192
+
193
+ /** The meta of a generated procedure. */
194
+ export function generatedMeta<Op extends GeneratedOp>(
195
+ described: Described & { readonly op: Op },
196
+ ): ProcedureMeta<EffectOf<Op>> {
197
+ return {
198
+ ...docs({ summary: summaryOf(described) }),
199
+ ...mcp({ effect: effects[described.op] }),
200
+ lattice: latticeOf(described),
201
+ };
202
+ }
203
+
204
+ /** The meta of a method's procedure, from its `summary` and `effect` statics. */
205
+ export function methodMeta<Fx extends McpEffect>(method: {
206
+ readonly slug: string;
207
+ readonly label: Label;
208
+ readonly name: string;
209
+ readonly summary: string;
210
+ readonly effect: Fx;
211
+ }): ProcedureMeta<Fx> {
212
+ return {
213
+ ...docs({ summary: method.summary }),
214
+ ...mcp({ effect: method.effect }),
215
+ lattice: {
216
+ collection: method.slug,
217
+ label: method.label,
218
+ operation: 'method',
219
+ method: method.name,
220
+ },
221
+ };
222
+ }
223
+
224
+ /** A `where` entry's description for a maskable field. */
225
+ export function refusedWhere(field: string): string {
226
+ return `Refused (VALIDATION) when the caller may not read ${field}.`;
227
+ }
228
+
229
+ /** A `sort` description for a collection with maskable fields. */
230
+ export function refusedSort(fields: readonly string[]): string {
231
+ return `Field names, "-" first for descending. Sorting on ${fields.join(', ')} is refused (VALIDATION) when the caller may not read it.`;
232
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,174 @@
1
+ import { type ErrorMap, toValidationIssues } from '@ts-pf/contract';
2
+ import { PFError } from '@ts-pf/protocol';
3
+ import { CodedError, catalogBrand, Errors, type StandardSchemaV1 } from 'hexok';
4
+ import { z } from 'zod';
5
+
6
+ const issue = z.object({
7
+ path: z.array(z.union([z.string(), z.number()])),
8
+ message: z.string(),
9
+ });
10
+
11
+ const target = z.object({ collection: z.string(), id: z.string() });
12
+
13
+ const definitions = {
14
+ VALIDATION: {
15
+ message: 'Validation failed',
16
+ data: z.object({ issues: z.array(issue) }),
17
+ },
18
+ UNAUTHORIZED: { message: 'The actor is missing or invalid' },
19
+ FORBIDDEN: { message: 'The actor may not do this' },
20
+ NOT_FOUND: { message: 'No document with this id', data: target },
21
+ CONFLICT: { message: 'A document with this id already exists', data: target },
22
+ REFERENCED: {
23
+ message: 'Other documents refer to this one',
24
+ data: target.extend({
25
+ // A join collection is not in the catalog: `relation` names the
26
+ // parent collection's relation that derived it.
27
+ by: z.object({
28
+ collection: z.string(),
29
+ field: z.string(),
30
+ relation: z
31
+ .object({ collection: z.string(), name: z.string() })
32
+ .optional(),
33
+ }),
34
+ }),
35
+ },
36
+ };
37
+
38
+ /** Lattice's refusals. Each reaches a ts-pf client under the same code. */
39
+ export class LatticeError extends Errors('lattice', definitions) {}
40
+
41
+ export type LatticeCode = keyof typeof definitions;
42
+
43
+ /** Every LatticeError code. An app may not declare one of these. */
44
+ export const latticeCodes: readonly string[] = Object.keys(definitions);
45
+
46
+ /**
47
+ * The errors every procedure declares, with their statuses. VALIDATION is
48
+ * not declared: it is a ts-pf protocol code, which a contract must not
49
+ * redeclare, and clients already type its `data.issues`.
50
+ */
51
+ export const declaredErrors = {
52
+ UNAUTHORIZED: { ...definitions.UNAUTHORIZED, status: 401 },
53
+ FORBIDDEN: { ...definitions.FORBIDDEN, status: 403 },
54
+ NOT_FOUND: { ...definitions.NOT_FOUND, status: 404 },
55
+ CONFLICT: { ...definitions.CONFLICT, status: 409 },
56
+ REFERENCED: { ...definitions.REFERENCED, status: 409 },
57
+ } satisfies ErrorMap;
58
+
59
+ export type Issue = z.output<typeof issue>;
60
+
61
+ /**
62
+ * A VALIDATION error for Zod issues: each issue as Zod reports it, with
63
+ * every unknown key on its own path. A field that fails two checks has two
64
+ * issues, in the order its schema declares them.
65
+ */
66
+ export function invalid(issues: readonly z.core.$ZodIssue[]) {
67
+ return LatticeError.VALIDATION({
68
+ issues: issues.flatMap((issue): Issue[] => {
69
+ const path = issue.path.map((key) =>
70
+ typeof key === 'symbol' ? String(key) : key,
71
+ );
72
+ // Zod reports every unknown key of one object as one issue. Split them
73
+ // so each path names the field or operator that is not allowed.
74
+ if (issue.code === 'unrecognized_keys') {
75
+ return issue.keys.map((key) => ({
76
+ path: [...path, key],
77
+ message: `"${key}" is not a field or not allowed on this field`,
78
+ }));
79
+ }
80
+ return [{ path, message: issue.message }];
81
+ }),
82
+ });
83
+ }
84
+
85
+ /** `value` parsed by `schema`, or a VALIDATION error naming each path. */
86
+ export function parse<S extends z.core.$ZodType>(
87
+ schema: S,
88
+ value: unknown,
89
+ ): z.output<S> {
90
+ const result = z.safeParse(schema, value);
91
+ if (!result.success) throw invalid(result.error.issues);
92
+ return result.data;
93
+ }
94
+
95
+ /** hexok's schema-check failure, such as `Entity.parse` or `validationError`. */
96
+ function isCodedValidation(error: unknown): error is CodedError<'VALIDATION'> {
97
+ return error instanceof CodedError && error.code === 'VALIDATION';
98
+ }
99
+
100
+ /**
101
+ * An expected refusal, and the fields that describe it: a member of any
102
+ * hexok `Errors` catalog, LatticeError included, or a hexok `CodedError`
103
+ * VALIDATION. The caller can act on it, so it is not a failure. Whether a
104
+ * client sees it is `toClientError`'s decision.
105
+ */
106
+ export function refusal(
107
+ error: unknown,
108
+ ): { catalog?: unknown; code: unknown } | undefined {
109
+ if (isCodedValidation(error)) return { code: error.code };
110
+ if (!(error instanceof Error) || !(catalogBrand in error)) return undefined;
111
+ return {
112
+ catalog: error[catalogBrand],
113
+ code: 'code' in error ? error.code : undefined,
114
+ };
115
+ }
116
+
117
+ /**
118
+ * The error a client receives. A LatticeError keeps its code, message, data
119
+ * and status. A hexok VALIDATION becomes the protocol VALIDATION. Anything
120
+ * else goes through the app's `map`; what that returns unchanged, ts-pf
121
+ * sends as INTERNAL.
122
+ */
123
+ export function toClientError(
124
+ error: unknown,
125
+ map: (error: unknown) => unknown,
126
+ ): unknown {
127
+ if (LatticeError.is(error)) {
128
+ if (error.code === 'VALIDATION') {
129
+ return new PFError({
130
+ code: error.code,
131
+ message: error.message,
132
+ data: error.data,
133
+ cause: error,
134
+ });
135
+ }
136
+ return new PFError({
137
+ code: error.code,
138
+ message: error.message,
139
+ status: declaredErrors[error.code].status,
140
+ ...('data' in error ? { data: error.data } : {}),
141
+ cause: error,
142
+ });
143
+ }
144
+ if (isCodedValidation(error)) {
145
+ return new PFError({
146
+ code: 'VALIDATION',
147
+ message: error.message,
148
+ data: { issues: toValidationIssues(issuesOf(error.data)) },
149
+ cause: error,
150
+ });
151
+ }
152
+ return map(error);
153
+ }
154
+
155
+ /** The Standard Schema issues in a hexok VALIDATION's `data`. */
156
+ function issuesOf(data: unknown): StandardSchemaV1.Issue[] {
157
+ if (typeof data !== 'object' || data === null || !('issues' in data)) {
158
+ return [];
159
+ }
160
+ const { issues } = data;
161
+ return Array.isArray(issues) ? issues.filter(isIssue) : [];
162
+ }
163
+
164
+ function isIssue(value: unknown): value is StandardSchemaV1.Issue {
165
+ return (
166
+ typeof value === 'object' &&
167
+ value !== null &&
168
+ 'message' in value &&
169
+ typeof value.message === 'string' &&
170
+ (!('path' in value) ||
171
+ value.path === undefined ||
172
+ Array.isArray(value.path))
173
+ );
174
+ }