@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.
- package/README.md +1174 -2
- package/dist/access.d.ts +210 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +225 -0
- package/dist/access.js.map +1 -0
- package/dist/build.d.ts +507 -0
- package/dist/build.d.ts.map +1 -0
- package/dist/build.js +598 -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 +344 -0
- package/dist/collection.js.map +1 -0
- package/dist/crud.d.ts +30 -0
- package/dist/crud.d.ts.map +1 -0
- package/dist/crud.js +539 -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 +179 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +146 -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 +231 -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 +255 -0
- package/dist/mask.js.map +1 -0
- package/dist/populate.d.ts +32 -0
- package/dist/populate.d.ts.map +1 -0
- package/dist/populate.js +73 -0
- package/dist/populate.js.map +1 -0
- package/dist/relations.d.ts +143 -0
- package/dist/relations.d.ts.map +1 -0
- package/dist/relations.js +128 -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 +83 -0
- package/dist/repo.js.map +1 -0
- package/dist/sort.d.ts +61 -0
- package/dist/sort.d.ts.map +1 -0
- package/dist/sort.js +145 -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 +683 -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 +113 -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 +79 -2
- package/skills/lattice/SKILL.md +106 -0
- package/skills/lattice/references/access.md +76 -0
- package/skills/lattice/references/cli.md +87 -0
- package/skills/lattice/references/collection.md +91 -0
- package/skills/lattice/references/event-handler.md +88 -0
- package/skills/lattice/references/masking.md +72 -0
- package/skills/lattice/references/method.md +85 -0
- package/skills/lattice/references/override.md +77 -0
- package/skills/lattice/references/relations.md +90 -0
- package/skills/lattice/references/tenancy.md +82 -0
- package/skills/lattice/references/testing.md +75 -0
- package/src/access.ts +429 -0
- package/src/build.ts +1722 -0
- package/src/collection.ts +1018 -0
- package/src/crud.ts +795 -0
- package/src/describe.ts +232 -0
- package/src/errors.ts +170 -0
- package/src/family.ts +334 -0
- package/src/index.ts +42 -0
- package/src/marker.ts +54 -0
- package/src/mask.ts +307 -0
- package/src/populate.ts +96 -0
- package/src/relations.ts +353 -0
- package/src/repo.ts +209 -0
- package/src/sort.ts +214 -0
- package/src/store/conformance.ts +1007 -0
- package/src/store/index.ts +16 -0
- package/src/store.ts +309 -0
- package/src/tenancy.ts +124 -0
- package/src/tracing.ts +29 -0
- package/src/where.ts +463 -0
package/README.md
CHANGED
|
@@ -1,5 +1,1177 @@
|
|
|
1
1
|
# @latticecms/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Collections that compile into hexok use cases, hexok event classes and a ts-pf contract. A collection is a Zod schema with a slug. `framework()` turns a set of them into a typed RPC contract, and `build()` wires that contract to a store and an event publisher. Every generated piece is a real hexok `UseCase`, `Event`, `Errors` and `Port`, and a real ts-pf `router`, so a hand-written one can take its place with the same types.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Status: before 1.0, not yet published. Breaking changes are free until 1.0. The design and the reasons behind it are in [docs/architecture.md](../../docs/architecture.md).
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @latticecms/core hexok @ts-pf/contract @ts-pf/protocol @ts-pf/server @ts-pf/docs @ts-pf/mcp zod @hexok/logger @opentelemetry/api
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Everything after `@latticecms/core` is a peer dependency: `hexok` 2, the `@ts-pf/*` packages 1, `zod` 4, `@hexok/logger` 0.2 and `@opentelemetry/api` 1. The app installs them, so it and Lattice share one copy of each:
|
|
14
|
+
|
|
15
|
+
- a `UseCase`, `Port` or `Errors` class the app imports is the same class Lattice built, so `instanceof` and hexok's checks hold;
|
|
16
|
+
- the contract's types are ts-pf's own, so every ts-pf client, `@ts-pf/openapi` and `@ts-pf/mcp` read them;
|
|
17
|
+
- a schema the app writes is the Zod Lattice parses with;
|
|
18
|
+
- the OpenTelemetry SDK the app registers is the one Lattice's spans reach.
|
|
19
|
+
|
|
20
|
+
`@ts-pf/docs` and `@ts-pf/mcp` carry the per-procedure descriptions; Lattice imports only `docs()` and the dependency-free `@ts-pf/mcp/meta`. Serve the result with `@ts-pf/server-http`, and call it with `@ts-pf/client`. A store adapter, such as [`@latticecms/store-mongo`](../store-mongo), is its own package.
|
|
21
|
+
|
|
22
|
+
## Quick start
|
|
23
|
+
|
|
24
|
+
One collection, one family, an in-memory store and an in-process client. It runs as is, with Node 24 (`node quickstart.ts`).
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
// examples/crm/src/quickstart/quickstart.ts
|
|
28
|
+
import { NoopLogger } from '@hexok/logger';
|
|
29
|
+
import { collection, family, framework, MemoryStore } from '@latticecms/core';
|
|
30
|
+
import { createLocalClient } from '@ts-pf/server';
|
|
31
|
+
import { z } from 'zod';
|
|
32
|
+
|
|
33
|
+
const Notes = collection('notes', {
|
|
34
|
+
schema: z.object({
|
|
35
|
+
title: z.string().min(1),
|
|
36
|
+
done: z.boolean().default(false),
|
|
37
|
+
}),
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const AppUseCase = family({
|
|
41
|
+
actor: z.object({ userId: z.string() }),
|
|
42
|
+
actorId: (actor) => actor.userId,
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const { app } = framework({ family: AppUseCase })
|
|
46
|
+
.collection(Notes, {
|
|
47
|
+
access: {
|
|
48
|
+
read: () => true,
|
|
49
|
+
create: () => true,
|
|
50
|
+
update: () => true,
|
|
51
|
+
delete: () => true,
|
|
52
|
+
},
|
|
53
|
+
})
|
|
54
|
+
.build({
|
|
55
|
+
store: new MemoryStore(),
|
|
56
|
+
// Where collection events go: nowhere, here.
|
|
57
|
+
events: { async publish(_event: { readonly payload: unknown }) {} },
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
const client = createLocalClient(app, {
|
|
61
|
+
context: { actor: { userId: 'ann' }, logger: new NoopLogger() },
|
|
62
|
+
});
|
|
63
|
+
const note = await client.notes.create({ title: 'Write the docs' });
|
|
64
|
+
await client.notes.update({ id: note.id, done: true });
|
|
65
|
+
const { docs } = await client.notes.find({ where: { done: { eq: true } } });
|
|
66
|
+
console.log(docs.map((doc) => doc.title));
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
It prints `[ 'Write the docs' ]`. The client is typed from the contract: `client.notes.find` takes a typed `where`, and returns typed documents with `id`, `createdAt` and `updatedAt`. Over HTTP, the same app is served by `@ts-pf/server-http`'s `FetchHandler`; see [The auth edge](#the-auth-edge).
|
|
70
|
+
|
|
71
|
+
## The agent skill
|
|
72
|
+
|
|
73
|
+
Core ships an agent skill in `skills/lattice`: a `SKILL.md` with the steps from a collection to an override, and one reference per concept (collections, access, tenancy, relations, masking, overrides, methods, event handlers, testing and the CLI), each quoting the crm. In an app that installs core, link it into the agents' skill directories with:
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
npx skills experimental_sync -y -r
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
It links `.agents/skills/lattice` to `node_modules/@latticecms/core/skills/lattice`, beside hexok's `hexok` skill and the `ts-pf-*` skills. `-r` also reads the dependencies of each workspace package, where a monorepo's app keeps them.
|
|
80
|
+
|
|
81
|
+
## Concepts
|
|
82
|
+
|
|
83
|
+
The examples come from [`examples/crm`](../../examples/crm): a CRM with tenanted companies, contacts and deals on MongoDB, served to signed-in members of an organization.
|
|
84
|
+
|
|
85
|
+
### Collections
|
|
86
|
+
|
|
87
|
+
A collection is a slug and a `z.object()` schema. Hooks transform data and nothing else.
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
// examples/crm/src/domain/collections/contacts.ts
|
|
91
|
+
import { collection, ref } from '@latticecms/core';
|
|
92
|
+
import { z } from 'zod';
|
|
93
|
+
|
|
94
|
+
export const Contacts = collection('contacts', {
|
|
95
|
+
schema: z.object({
|
|
96
|
+
name: z.string().min(1),
|
|
97
|
+
email: z.email(),
|
|
98
|
+
// A company with contacts cannot be deleted: restrict, the default.
|
|
99
|
+
companyId: ref('companies'),
|
|
100
|
+
}),
|
|
101
|
+
tenant: 'organizationId',
|
|
102
|
+
}).hooks({
|
|
103
|
+
// One spelling per address, so a where on email finds it.
|
|
104
|
+
beforeChange: ({ data }) => ({ ...data, email: data.email.toLowerCase() }),
|
|
105
|
+
});
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Lattice adds `id`, `createdAt` and `updatedAt` to every document, and the tenant field to a tenanted one. `collection()`'s options are in the [reference](#collection-options).
|
|
109
|
+
|
|
110
|
+
#### Hooks
|
|
111
|
+
|
|
112
|
+
`.hooks({ beforeChange?, afterRead? })` returns the same collection with those hooks. A later call replaces a hook it names.
|
|
113
|
+
|
|
114
|
+
- `beforeChange({ data, operation, previous? })` runs after validation, before the write, on create and update. `data` is the whole document after the change, without system fields. It returns the data to store.
|
|
115
|
+
- `afterRead({ doc })` runs on every document a generated operation returns. It does not change what is stored or what events carry.
|
|
116
|
+
|
|
117
|
+
### The family
|
|
118
|
+
|
|
119
|
+
The app has one use case family. Generated and hand-written use cases extend it, and share its guards, logging and spans. `tenantOf` gives each call its organization, or a read-only bypass for support staff.
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
// examples/crm/src/app/use-cases/context.ts
|
|
123
|
+
import { family, tenancy } from '@latticecms/core';
|
|
124
|
+
import type { UseCase } from 'hexok';
|
|
125
|
+
import { z } from 'zod';
|
|
126
|
+
import { role } from '../../domain/collections/memberships.js';
|
|
127
|
+
|
|
128
|
+
/** A member acting in one organization, with its role there; the edge checked both. */
|
|
129
|
+
const memberSchema = z.strictObject({
|
|
130
|
+
userId: z.string().min(1),
|
|
131
|
+
organizationId: z.string().min(1),
|
|
132
|
+
role,
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Support staff: they read every organization's rows and change none. The
|
|
137
|
+
* edge sets this from server config, never from the request, and a support
|
|
138
|
+
* actor has no organization.
|
|
139
|
+
*/
|
|
140
|
+
const supportSchema = z.strictObject({
|
|
141
|
+
userId: z.string().min(1),
|
|
142
|
+
support: z.literal(true),
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Who is calling. The edge builds it from the session and the
|
|
147
|
+
* organization header. Strict, so an actor with both an organization and
|
|
148
|
+
* the support flag is invalid rather than read as either.
|
|
149
|
+
*/
|
|
150
|
+
export const actorSchema = z.union([memberSchema, supportSchema]);
|
|
151
|
+
|
|
152
|
+
export type Actor = z.output<typeof actorSchema>;
|
|
153
|
+
|
|
154
|
+
/** The app's one use case family. Generated and hand-written use cases share it. */
|
|
155
|
+
export const AppUseCase = family({
|
|
156
|
+
actor: actorSchema,
|
|
157
|
+
actorId: (actor) => actor.userId,
|
|
158
|
+
tenantOf: (actor) =>
|
|
159
|
+
'support' in actor ? tenancy.bypass : actor.organizationId,
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
export type AppCtx = UseCase.Ctx<typeof AppUseCase>;
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
`family({ actor, actorId, tenantOf? })` builds a hexok `UseCase.context` family.
|
|
166
|
+
|
|
167
|
+
A caller passes `{ actor, logger }` (`CallContext<Actor>`): the actor, and a `@hexok/logger` `Logger` for the call. Lattice adds `access`, the call's access, so a use case receives `{ actor, logger, access }` (`FamilyContext<Actor>`).
|
|
168
|
+
|
|
169
|
+
- Before `execute`, the actor must parse against `actor`, the input against the use case's `input` static, and access must allow the use case's action. A bad actor is `UNAUTHORIZED`, bad input is `VALIDATION`, and a refusal is `FORBIDDEN`.
|
|
170
|
+
- The actor is parsed once per call, and everything after sees the parsed value: access functions, `tenantOf`, `actorId`, log lines, `execute`'s `ctx.actor` and events. Keys the schema strips never reach them, and a transform's output does. Make an actor union of `z.strictObject`s when a key changes meaning, such as a `support` flag, so an actor that mixes the shapes is refused rather than read as one of them.
|
|
171
|
+
- `actorId` names the id that log lines and collection events carry. The family exposes `actor`, `actorId` and `tenantOf`, so hand-written code calls `AppUseCase.actorId(ctx.actor)`.
|
|
172
|
+
- `tenantOf` names the actor's tenant id, or `tenancy.bypass`. A framework with a tenanted collection requires it; see [Tenancy](#tenancy).
|
|
173
|
+
- Every call writes one line through a child of `ctx.logger` with `collection`, `action`, `actorId`, `tenantId` (or `tenancy: 'bypass'`), `outcome` and `durationMs`.
|
|
174
|
+
- A hand-written use case extends the family with a `collection` static, and `input` and `output` schemas for a method. Its token is `<slug>.<name>`.
|
|
175
|
+
- A method also says what it does, in `summary`, and how it affects data, in `effect`: `read`, `write` or `destructive`. They become its procedure's `docs` and `mcp` meta, so MCP tools, OpenAPI and the admin describe it from one place. An override declares neither: it keeps the meta of the operation it replaces.
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
// examples/crm/src/app/use-cases/deals/close-deal.ts
|
|
179
|
+
export class CloseDeal extends AppUseCase('deals.close', {
|
|
180
|
+
collection: Deals,
|
|
181
|
+
input: z.object({ id: z.string(), outcome: z.enum(['won', 'lost']) }),
|
|
182
|
+
// As a client receives a deal: the amount is withheld from a member.
|
|
183
|
+
output: Deals.clientOutput,
|
|
184
|
+
// What MCP tells a model, and the admin shows for the action.
|
|
185
|
+
summary:
|
|
186
|
+
'Close a deal as won or lost, by its id. A deal closes once; closing it again is AlreadyClosed.',
|
|
187
|
+
effect: 'write',
|
|
188
|
+
}) {
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
`FamilyContext<Actor>` is the context type a use case receives, and `CallContext<Actor>` the one a caller passes. `Family<Actor, Tenanted>` is the family's type; `Tenanted` is true when it has `tenantOf`.
|
|
192
|
+
|
|
193
|
+
### The framework
|
|
194
|
+
|
|
195
|
+
`framework({ family, errors? })` starts a definition, and `.collection()` adds each collection with its access rules, and its methods and overrides. The definition holds no ports, so a client or a codegen script imports `contract` without the server.
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
// examples/crm/src/servers/rpc/contract.ts
|
|
199
|
+
import { framework } from '@latticecms/core';
|
|
200
|
+
import { AppUseCase } from '../../app/use-cases/context.js';
|
|
201
|
+
import { ArchiveDeal } from '../../app/use-cases/deals/archive-deal.js';
|
|
202
|
+
import { CloseDeal } from '../../app/use-cases/deals/close-deal.js';
|
|
203
|
+
import { Companies } from '../../domain/collections/companies.js';
|
|
204
|
+
import { Contacts } from '../../domain/collections/contacts.js';
|
|
205
|
+
import { Deals } from '../../domain/collections/deals.js';
|
|
206
|
+
import { Memberships } from '../../domain/collections/memberships.js';
|
|
207
|
+
import { Organizations } from '../../domain/collections/organizations.js';
|
|
208
|
+
import { clientErrors, toRpcError } from './errors.js';
|
|
209
|
+
|
|
210
|
+
/** Any signed-in caller may do this. The edge has already checked the actor. */
|
|
211
|
+
const anyone = () => true;
|
|
212
|
+
|
|
213
|
+
// An archived deal is hidden from every read and can no longer change.
|
|
214
|
+
const live = () => ({ archived: { eq: false } });
|
|
215
|
+
|
|
216
|
+
/** The CRM's API: five collections, one override and one method. No ports. */
|
|
217
|
+
export const crm = framework({
|
|
218
|
+
family: AppUseCase,
|
|
219
|
+
errors: { declared: clientErrors, map: toRpcError },
|
|
220
|
+
})
|
|
221
|
+
.collection(Companies, {
|
|
222
|
+
access: { read: anyone, create: anyone, update: anyone, delete: anyone },
|
|
223
|
+
})
|
|
224
|
+
.collection(Contacts, {
|
|
225
|
+
access: { read: anyone, create: anyone, update: anyone, delete: anyone },
|
|
226
|
+
})
|
|
227
|
+
.collection(Deals, {
|
|
228
|
+
access: {
|
|
229
|
+
read: live,
|
|
230
|
+
create: anyone,
|
|
231
|
+
update: live,
|
|
232
|
+
delete: live,
|
|
233
|
+
close: live,
|
|
234
|
+
},
|
|
235
|
+
// A member sees every deal of the organization, without its amount.
|
|
236
|
+
fields: {
|
|
237
|
+
amount: {
|
|
238
|
+
read: ({ actor }) => 'support' in actor || actor.role === 'manager',
|
|
239
|
+
},
|
|
240
|
+
},
|
|
241
|
+
methods: { close: CloseDeal },
|
|
242
|
+
overrides: { delete: ArchiveDeal },
|
|
243
|
+
})
|
|
244
|
+
.collection(Memberships, {
|
|
245
|
+
// A caller lists its own memberships, in every organization. An
|
|
246
|
+
// organization switcher uses /auth organizations instead, since /rpc
|
|
247
|
+
// needs an organization first. No create, update or delete: only
|
|
248
|
+
// trusted code writes them.
|
|
249
|
+
access: { read: ({ actor }) => ({ userId: { eq: actor.userId } }) },
|
|
250
|
+
})
|
|
251
|
+
.collection(Organizations, {
|
|
252
|
+
// A member reads the organization it acts in, and support every one.
|
|
253
|
+
// No create, update or delete: only trusted code writes them.
|
|
254
|
+
access: {
|
|
255
|
+
read: ({ actor }) =>
|
|
256
|
+
'support' in actor ? true : { id: { eq: actor.organizationId } },
|
|
257
|
+
},
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
/** What clients and codegen import. */
|
|
261
|
+
export const contract = crm.contract;
|
|
262
|
+
|
|
263
|
+
export { AppUseCase, Companies, Contacts, Deals, Memberships, Organizations };
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
`framework({ family, errors? })` starts a definition. `errors` is the app's `{ declared, map }`; an app with no domain errors leaves it out.
|
|
267
|
+
|
|
268
|
+
`.collection(C, { access, fields?, methods?, overrides? })` adds a collection. Its slug becomes a contract slice with `find`, `count`, `get`, `create`, `update` and `delete`. `access` is required; see [Access](#access).
|
|
269
|
+
|
|
270
|
+
- `fields: { amount: { read } }` gives each maskable field its read rule, and is required exactly when `C` has one; see [Field masking](#field-masking).
|
|
271
|
+
- `methods: { name: Class }` adds a procedure. `overrides: { action: Class }` replaces a generated one.
|
|
272
|
+
- Each class must name `C` and its token, and its `execute` must take and return the procedure's types. A mismatch, a reserved name, or a slug added twice is a compile error and a runtime throw.
|
|
273
|
+
- A slug, relation or method may not be one of `reservedNames`: `$context`, `use`, `useAfter`, `middleware` and `router`, the ts-pf implementer's own keys.
|
|
274
|
+
- A method without `summary` and `effect`, and an override with either, is a compile error and a runtime throw. The error names the method or override. A blank `summary` throws.
|
|
275
|
+
|
|
276
|
+
`.contract` is the ts-pf contract, built once on first read. `Contract<E, D>` is its type.
|
|
277
|
+
|
|
278
|
+
### `build()`
|
|
279
|
+
|
|
280
|
+
`build()` wires the definition to a store and a publisher. The method and override instances get the typed repos.
|
|
281
|
+
|
|
282
|
+
```ts
|
|
283
|
+
// examples/crm/src/servers/app.ts
|
|
284
|
+
import type { CollectionStore } from '@latticecms/core';
|
|
285
|
+
import type { DomainEventPublisher } from '../app/ports/events/domain-event-publisher.js';
|
|
286
|
+
import { ArchiveDeal } from '../app/use-cases/deals/archive-deal.js';
|
|
287
|
+
import { CloseDeal } from '../app/use-cases/deals/close-deal.js';
|
|
288
|
+
import { crm } from './rpc/contract.js';
|
|
289
|
+
|
|
290
|
+
export type AppPorts = {
|
|
291
|
+
readonly store: CollectionStore;
|
|
292
|
+
readonly events: DomainEventPublisher;
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
/** The implemented router, use cases and repos over these ports. */
|
|
296
|
+
export function createApp({ store, events }: AppPorts) {
|
|
297
|
+
return crm.build({
|
|
298
|
+
store,
|
|
299
|
+
events,
|
|
300
|
+
methods: ({ repos }) => ({
|
|
301
|
+
deals: { close: new CloseDeal({ deals: repos.deals, events }) },
|
|
302
|
+
}),
|
|
303
|
+
overrides: ({ repos }) => ({
|
|
304
|
+
deals: { delete: new ArchiveDeal({ deals: repos.deals }) },
|
|
305
|
+
}),
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export type CrmApp = ReturnType<typeof createApp>;
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
`build({ store, events, access?, methods?, overrides? })` wires the definition and returns:
|
|
313
|
+
|
|
314
|
+
| Output | What it is |
|
|
315
|
+
| --- | --- |
|
|
316
|
+
| `app` | The implemented ts-pf router, for `FetchHandler` and `createLocalClient` |
|
|
317
|
+
| `useCases` | The hexok instance that serves each procedure: generated, override or method, each typed precisely |
|
|
318
|
+
| `repos` | A `Repo<C>` per collection: the objects the factories received |
|
|
319
|
+
| `onError` | `onError(logger)` for `FetchHandler` |
|
|
320
|
+
| `context` | `context({ actor, logger })`: the context for a direct `useCases.*.execute` call |
|
|
321
|
+
| `ensure` | `ensure()`: creates each collection's declared indexes, in definition order, and never drops one |
|
|
322
|
+
|
|
323
|
+
- `methods` and `overrides` are factories, `({ repos }) => instances`, keyed by slug and then name. Each is required exactly when a collection declared one.
|
|
324
|
+
- `access` replaces the functions given at `.collection()` with another `Access` adapter.
|
|
325
|
+
- `app` adds a fresh `access` to each call's context. A direct caller gets one from `context()`. Access answers are kept on the context, so make one per call or per job.
|
|
326
|
+
- `events` must take every collection's events. One that cannot is a compile error that names each refused token.
|
|
327
|
+
- Await `ensure()` after the store has started and before serving, as the CRM's [`server.ts`](#build) does.
|
|
328
|
+
- `Framework<Actor, D, E, Tenanted>` is the definition's type.
|
|
329
|
+
|
|
330
|
+
The server starts the store, runs the migrations, creates the indexes, then serves:
|
|
331
|
+
|
|
332
|
+
```ts
|
|
333
|
+
// examples/crm/src/servers/http/server.ts
|
|
334
|
+
const crm = createApp({ store, events: deps.events });
|
|
335
|
+
await store.start();
|
|
336
|
+
await migrate(store, migrations, { logger });
|
|
337
|
+
await crm.ensure();
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
A client needs no annotations. Input, output and declared errors come from the contract, so the client narrows on the app's `AlreadyClosed` and its `data`:
|
|
341
|
+
|
|
342
|
+
```ts
|
|
343
|
+
// examples/crm/src/servers/app.test.ts
|
|
344
|
+
const deal = await local.deals.create({
|
|
345
|
+
title: 'Big one',
|
|
346
|
+
companyId: 'c1',
|
|
347
|
+
amount: 1000,
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
const won = await local.deals.close({ id: deal.id, outcome: 'won' });
|
|
351
|
+
expect(won).toMatchObject({ stage: 'won', closedAt: expect.any(String) });
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
```ts
|
|
355
|
+
// examples/crm/src/servers/app.test.ts
|
|
356
|
+
const again = await asResult(
|
|
357
|
+
local.deals.close({ id: deal.id, outcome: 'lost' }),
|
|
358
|
+
);
|
|
359
|
+
if (again.ok) throw new Error('expected AlreadyClosed');
|
|
360
|
+
if (again.error.code !== 'AlreadyClosed')
|
|
361
|
+
throw new Error(again.error.code);
|
|
362
|
+
expectTypeOf(again.error.data).toEqualTypeOf<{ id: string }>();
|
|
363
|
+
expect(again.error.data).toEqual({ id: deal.id });
|
|
364
|
+
expect(again.error.status).toBe(409);
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
### Access
|
|
368
|
+
|
|
369
|
+
Access decides what a call may see and change. It is a filter in the query: Lattice never loads a row and then decides whether the caller may see it.
|
|
370
|
+
|
|
371
|
+
`.collection(C, { access })` takes one function per action: `read` (find, count and get), `create`, `update`, `delete`, and one per method.
|
|
372
|
+
|
|
373
|
+
- Each function receives `{ actor }`, typed by the family's actor schema. `create` also receives `data`, its parsed input.
|
|
374
|
+
- `read`, `update`, `delete` and a method return `boolean` or a `Where` on `C`'s documents, or a promise of one. `create` returns `boolean`.
|
|
375
|
+
- `true` allows every row. `false` refuses the call with `FORBIDDEN`. A `Where` limits the call to the rows that match: a row outside it is `NOT_FOUND` on get, update and delete, and `find` never returns it.
|
|
376
|
+
- A missing function denies. `access: {}` denies everything. An override uses the function of the action it replaces.
|
|
377
|
+
- A `Where` on a field `C` lacks, a key that is not an action or a method, and a method with no function are compile errors.
|
|
378
|
+
- An access `Where` is ANDed with the caller's `where`, so a caller can only narrow it.
|
|
379
|
+
|
|
380
|
+
A family guard checks access before every `execute`: generated operations, overrides and methods. The refusal is logged once. Each function runs once per call.
|
|
381
|
+
|
|
382
|
+
A hand-written use case gets its filter with `ctx.access.scope(C, action)`, and passes the `Scope` to its repo calls. It may ask for another collection's scope too, such as `ctx.access.scope(Posts, 'find')`.
|
|
383
|
+
|
|
384
|
+
```ts
|
|
385
|
+
// examples/crm/src/app/use-cases/deals/close-deal.ts
|
|
386
|
+
const scope = await ctx.access.scope(Deals, 'close');
|
|
387
|
+
const deal = await this.deps.deals.get(input.id, scope);
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
Hide rows with a `read` filter, such as soft-deleted ones. The CRM's `live` filter above hides an archived deal from `find` and `get`, and keeps it from changing.
|
|
391
|
+
|
|
392
|
+
`Access` is the hexok port behind this. `build({ access })` takes another adapter of it. Its `check({ actor, collection, action, data? })` returns `boolean` or a `Where`; `action` is `find`, `count`, `get`, `create`, `update`, `delete` or a method's name, and `data` is passed for `create` only. Its `readable({ actor, collection, fields })` returns which of a collection's maskable fields the actor may read; a field it leaves out is withheld, so an adapter that forgets one withholds it.
|
|
393
|
+
|
|
394
|
+
### Tenancy
|
|
395
|
+
|
|
396
|
+
A collection with `tenant: 'organizationId'` keeps each tenant's rows apart. Lattice adds the field to the output, stamps it on create, and filters every call by the caller's tenant. A collection without `tenant` is global: no call is filtered by tenant.
|
|
397
|
+
|
|
398
|
+
```ts
|
|
399
|
+
const AppUseCase = family({
|
|
400
|
+
actor: z.object({ userId: z.string(), organizationId: z.string(), support: z.boolean().optional() }),
|
|
401
|
+
actorId: (actor) => actor.userId,
|
|
402
|
+
tenantOf: (actor) => (actor.support === true ? tenancy.bypass : actor.organizationId),
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
const Notes = collection('notes', {
|
|
406
|
+
schema: z.object({ title: z.string() }),
|
|
407
|
+
tenant: 'organizationId',
|
|
408
|
+
});
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
- `family({ tenantOf })` gives each call's tenant. A tenanted collection in a framework whose family has no `tenantOf` is a compile error and a throw.
|
|
412
|
+
- The tenant field is in `Doc` and `Where`, never in create or update input. Create stamps it after `beforeChange`, update never writes it, and a client cannot set or change it.
|
|
413
|
+
- In the output's JSON Schema, and so in OpenAPI and MCP, the tenant field carries `x-lattice-tenant: true`, so a client such as the admin shows it read-only.
|
|
414
|
+
- Every scope is the tenant clause ANDed with the access `Where`. Another tenant's row is `NOT_FOUND` on get, update and delete, and `find` never returns it, page after page.
|
|
415
|
+
- A schema field with the tenant's name, or a reserved name, is a compile error and a throw.
|
|
416
|
+
|
|
417
|
+
`tenancy.bypass` is what `tenantOf` returns for a platform actor, such as support staff. The actor schema validates the flag, and the edge sets it per request.
|
|
418
|
+
|
|
419
|
+
- A bypassed call reads across tenants. It can filter `find` by the tenant field.
|
|
420
|
+
- It is read-only on tenanted collections: generated create, update and delete are `FORBIDDEN`, and so is a repo write through its scope.
|
|
421
|
+
- Its log line carries `tenancy: 'bypass'`, and each bypassed scope writes one `tenancy.bypass` line with the actor, collection and action.
|
|
422
|
+
|
|
423
|
+
Server code says which tenant it works in. An event handler uses `tenancy.scope(C, tenantId)`: the tenant clause and no access. An insert through it is stamped with that tenant. `tenancy.scope` takes only a tenanted collection.
|
|
424
|
+
|
|
425
|
+
```ts
|
|
426
|
+
await repos.notes.update(id, patch, tenancy.scope(Notes, event.payload.tenantId));
|
|
427
|
+
```
|
|
428
|
+
|
|
429
|
+
`unscoped` still reads and writes every tenant, but it cannot insert into a tenanted collection, since the row would belong to no tenant. That is a compile error and a throw.
|
|
430
|
+
|
|
431
|
+
### Relations and population
|
|
432
|
+
|
|
433
|
+
#### Refs and `onDelete`
|
|
434
|
+
|
|
435
|
+
`ref(slug, { onDelete? })` marks a string field as the id of a document in another collection. It names the collection by its slug, so two collections can refer to each other. `z.array(ref(slug))` is a list of ids.
|
|
436
|
+
|
|
437
|
+
```ts
|
|
438
|
+
const Projects = collection('projects', {
|
|
439
|
+
schema: z.object({
|
|
440
|
+
name: z.string(),
|
|
441
|
+
companyId: ref('companies', { onDelete: 'cascade' }),
|
|
442
|
+
reviewerId: ref('users', { onDelete: 'nullify' }).optional(),
|
|
443
|
+
}),
|
|
444
|
+
tenant: 'organizationId',
|
|
445
|
+
});
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
- A ref is a string: Zod's methods work on it, and `ref('users').min(1).optional()` is still a ref.
|
|
449
|
+
- A slug that is not a collection of the framework is a compile error and a throw at `build()`, and on `.contract`. Collections may be added in any order.
|
|
450
|
+
- A write does not check that the referenced document exists. Deleting it is where refs are kept whole.
|
|
451
|
+
- Each ref gets an index in `ensure()`, led by the tenant field, unless the collection declares one with the same keys.
|
|
452
|
+
- A ref's JSON Schema says where it points, as `x-lattice-ref: 'companies'`: in inputs, outputs, the id branch of a populated field, each item of a list of ids, and a join collection's ids. OpenAPI and MCP carry it, and the admin links and picks documents by it.
|
|
453
|
+
|
|
454
|
+
`onDelete` says what the generated delete of the referenced document does to the documents that refer to it:
|
|
455
|
+
|
|
456
|
+
| `onDelete` | When a referenced document is deleted |
|
|
457
|
+
| --- | --- |
|
|
458
|
+
| `restrict` (default) | The delete is refused with `REFERENCED` (409), `{ collection, id, by: { collection, field, relation? } }`, while any document refers to it |
|
|
459
|
+
| `cascade` | The referring documents are deleted too, and their own refs are followed in turn. A cycle stops at a document already deleted. A list of ids cannot cascade |
|
|
460
|
+
| `nullify` | The ref is cleared: an optional field is removed, a nullable one set to null, and the id pulled from a list. A required ref cannot nullify |
|
|
461
|
+
|
|
462
|
+
- These are system steps: they skip access functions, because the caller was allowed to delete the parent. They stay inside the parent's tenant, so another tenant's row that stores this id is neither counted nor touched. A global parent's children are found across tenants.
|
|
463
|
+
- Everything runs in one `store.transaction()`, with the parent deleted last. Restrict is checked before anything is written. Each cascaded document emits its `deleted` event and each nullified one its `updated` event, after the commit, never inside it. A failure rolls the whole delete back, and nothing is published.
|
|
464
|
+
- A collection that overrides `delete` cannot have a cascading ref: the cascade would hard-delete rows its override keeps, such as soft-deleted deals. It is a compile error and a throw at `.collection()`; use `restrict` or `nullify`.
|
|
465
|
+
- `onDelete` runs in the generated delete only. An override of `delete`, such as a soft delete, keeps the row, so its children stay valid; an override that removes rows handles their refs itself. `Repo.remove` is trusted and does not run it.
|
|
466
|
+
|
|
467
|
+
#### `many()` relations
|
|
468
|
+
|
|
469
|
+
`many(target, { through, fields?, onDelete? })` relates each document to many of another collection, through a join collection Lattice derives:
|
|
470
|
+
|
|
471
|
+
```ts
|
|
472
|
+
const Posts = collection('posts', {
|
|
473
|
+
schema: z.object({ title: z.string() }),
|
|
474
|
+
tenant: 'organizationId',
|
|
475
|
+
relations: {
|
|
476
|
+
categories: many('categories', {
|
|
477
|
+
through: 'post_categories',
|
|
478
|
+
fields: z.object({ sortOrder: z.number().int().default(0) }),
|
|
479
|
+
}),
|
|
480
|
+
},
|
|
481
|
+
});
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
- The join collection is `Posts.relations.categories.through`, with slug `through`. Its documents are `{ postsId, categoriesId, ...fields }` plus the system fields and the parent's tenant field. `postsId` cascades from the post; `categoriesId` takes `onDelete` (`restrict` by default, or `cascade`). A category the join restricts is `REFERENCED` with `by: { collection: 'post_categories', field: 'categoriesId', relation: { collection: 'posts', name: 'categories' } }`: the join collection is not in the catalog, so `relation` names the relation a client can show. It has its own events, which the app lists in its catalog like any collection's, and it is in `repos` (`repos.post_categories`), but it has no slice: links change only through `set`.
|
|
485
|
+
- It gets a unique index on the pair, and one on `categoriesId`, both led by the tenant field.
|
|
486
|
+
- `posts.categories.list({ id, where?, sort?, limit?, after? })` pages the post's links, with find's `where`, `sort` and cursor over the link documents. It runs the post's `read` access: a post outside it is `NOT_FOUND`.
|
|
487
|
+
- `posts.categories.set({ id, links })` replaces the post's links: each link is `{ categoriesId, ...fields }`, at most 1000, and a target repeated is `VALIDATION`. It runs the post's `update` access. It diffs, in one `store.transaction()`: links no longer listed are deleted, new ones inserted, and changed fields updated; an unchanged link keeps its id and `createdAt`. Each change emits its own join event, after the commit. It returns the links in the order given. A tenant bypass cannot set.
|
|
488
|
+
- Both are use cases in the family (`useCases.posts.categories.set`), and can be overridden: `overrides: { categories: { set: ReorderCategories } }`.
|
|
489
|
+
- A relation name may not be a schema field, an operation, `read`, a method or a ts-pf implementer key, and `through` may not be another collection's slug. A collection cannot relate to itself with `many()`. A link field may not be named like the two ref fields, a reserved name or the tenant field. Method names may not contain a dot. Each is a compile error and a throw.
|
|
490
|
+
|
|
491
|
+
#### Population
|
|
492
|
+
|
|
493
|
+
A read takes `populate`, a list of what to replace with documents. The output type follows the list on every ts-pf client, and on `useCases`, through ts-pf's expandable outputs:
|
|
494
|
+
|
|
495
|
+
```ts
|
|
496
|
+
// examples/crm/src/servers/app.test.ts
|
|
497
|
+
const got = await local.contacts.get({
|
|
498
|
+
id: ada.id,
|
|
499
|
+
populate: ['companyId'],
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
expectTypeOf(got.companyId).toEqualTypeOf<
|
|
503
|
+
Doc<typeof Companies> | Withheld
|
|
504
|
+
>();
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
With the `Posts` above, and an `authorId` ref to `users`:
|
|
508
|
+
|
|
509
|
+
```ts
|
|
510
|
+
const post = await client.posts.get({ id, populate: ['authorId', 'categories'] });
|
|
511
|
+
post.authorId; // Doc<typeof Users> | Withheld
|
|
512
|
+
post.categories; // { sortOrder: number; doc: Doc<typeof Categories> | Withheld }[]
|
|
513
|
+
const plain = await client.posts.get({ id });
|
|
514
|
+
plain.authorId; // string
|
|
515
|
+
const page = await client.posts.find({ populate: ['authorId'] });
|
|
516
|
+
const links = await client.posts.categories.list({ id, populate: ['categoriesId'] });
|
|
517
|
+
```
|
|
518
|
+
|
|
519
|
+
- `get` populates ref fields and `many()` relations. `find` populates ref fields only, so one page cannot fetch up to 1000 links per document; a relation on `find` is a compile error and `VALIDATION`. A relation's `list` populates its links' refs, which is how a page of links gets its documents.
|
|
520
|
+
- A ref populates as the target document. A list of ids populates element-wise. A nullable or optional ref keeps its `null` or `undefined`. A relation populates as its links, each `{ ...fields, doc }`, and is in the output only when populated.
|
|
521
|
+
- A populated document the caller may not read, or one that no longer exists, is `Withheld`: `{ id }` only. Narrow with a field: `'email' in post.authorId`.
|
|
522
|
+
- Each target collection is read once per call, with `getMany`, for all the documents and fields that refer to it. It runs under the caller's `read` access there, which carries the tenant, and through its `afterRead`. A relation's links are read in one `find` on the join collection, inside the parent's tenant, under the parent's `read`.
|
|
523
|
+
- A `read: false` on a target does not fail the read: every document of that target is `{ id }`.
|
|
524
|
+
- One level deep: a populated document's own refs stay ids.
|
|
525
|
+
- A `populate` list held in a `K[]` variable gives the wide type, where each ref is the id or the document, because it could hold any subset.
|
|
526
|
+
- An overridden `get`, `find` or `list` is plain: it takes no `populate`, because the override serves it and population runs in the generated read.
|
|
527
|
+
|
|
528
|
+
### Field masking
|
|
529
|
+
|
|
530
|
+
A collection names the fields a caller's rules may withhold, with `maskable`. Composition gives each a read rule, in `.collection(C, { fields })`; see [Masking by role](#masking-by-role). The rule receives `{ actor }` and is asked once per call per collection.
|
|
531
|
+
|
|
532
|
+
```ts
|
|
533
|
+
// examples/crm/src/domain/collections/deals.ts
|
|
534
|
+
export const Deals = collection('deals', {
|
|
535
|
+
schema: z.object({
|
|
536
|
+
title: z.string().min(1),
|
|
537
|
+
// An archived deal still refers to its company, so it restricts too.
|
|
538
|
+
companyId: ref('companies'),
|
|
539
|
+
amount: z.number().nonnegative(),
|
|
540
|
+
stage: z.enum(dealStages).default('lead'),
|
|
541
|
+
// deals.delete archives: the row stays, with archived set.
|
|
542
|
+
archived: z.boolean().default(false),
|
|
543
|
+
closedAt: z.iso.datetime().optional(),
|
|
544
|
+
}),
|
|
545
|
+
tenant: 'organizationId',
|
|
546
|
+
// The people on a deal, and what each is to it. A contact on a deal
|
|
547
|
+
// cannot be deleted: restrict, the default.
|
|
548
|
+
relations: {
|
|
549
|
+
contacts: many('contacts', {
|
|
550
|
+
through: 'deal_contacts',
|
|
551
|
+
fields: z.object({ role: contactRole }),
|
|
552
|
+
}),
|
|
553
|
+
},
|
|
554
|
+
// Only managers and support see amounts: the contract's fields rule.
|
|
555
|
+
maskable: ['amount'],
|
|
556
|
+
// The pipeline view: one organization's deals in a stage, newest first.
|
|
557
|
+
indexes: [{ fields: { organizationId: 1, stage: 1, createdAt: -1 } }],
|
|
558
|
+
});
|
|
559
|
+
```
|
|
560
|
+
|
|
561
|
+
- A withheld field is left out of what a client receives: `get`, `find`, `create`, `update` and `delete`, a relation's `list`, and documents populated into another collection's read, under the caller's rule for that collection. It is masked where every procedure returns to a client (HTTP, `createLocalClient`, MCP), so overrides and methods are masked too.
|
|
562
|
+
- A client's type has the field optional: `deal.amount` is `number | undefined`, for every caller, since types cannot follow the actor. `ClientDoc<C>` names that document; `Doc<C>` stays the stored one.
|
|
563
|
+
- A `where` or a `sort` on a field the caller may not read, at any depth, on `find` or `count`, is `VALIDATION` naming its path. So no filter, count, order or cursor reveals it. A caller who may read it filters and sorts as usual.
|
|
564
|
+
- An `update` whose patch names a field the caller may not read, with a value or `null`, is `VALIDATION` at its path: `"amount" is not readable, so it cannot be changed`. A caller cannot see what the write would destroy. The family's guard checks it, so an override of `update` is refused too. `create` still takes the field, so a caller who may not read a required maskable field can create the document.
|
|
565
|
+
- A method that returns a collection's documents declares `output: Deals.clientOutput`, or a schema built from it (`.extend()`, `.pick()`, `shape.amount`). An output that holds a maskable field where it is required, such as `Deals.output`, throws at `build()`, and so does an output Lattice cannot see through (`z.lazy()`, a transform, `z.custom()`, `z.unknown()`, `z.any()`) in an app with a maskable field.
|
|
566
|
+
- Server code sees whole documents: repos, direct `useCases.*.execute` calls and events' `doc`. A page rendered for a user calls through `createLocalClient`. Masking for a webhook happens where the webhook maps the event.
|
|
567
|
+
- In JSON Schema, and so in OpenAPI and MCP, the field is optional, with `x-lattice-maskable: true` and the description "Withheld when the caller may not read it." Its `where` entry says "Refused (VALIDATION) when the caller may not read amount.", and a `sort` that could name it says the same. Meta the app gave the field, such as a `title`, stays.
|
|
568
|
+
|
|
569
|
+
Masking covers the named field only. These can still reveal it:
|
|
570
|
+
|
|
571
|
+
- An object-level `.refine()` that reads a maskable field can fail a non-reader's update depending on the hidden value. Don't refine across a maskable field.
|
|
572
|
+
- An access `Where` that filters rows by a maskable field, such as `read: () => ({ amount: { lt: 1000 } })`, reveals a bound through which rows exist.
|
|
573
|
+
- An `afterRead` hook that derives another field from a masked one, or a method that computes a field of its own from it, is not masked.
|
|
574
|
+
|
|
575
|
+
### Events
|
|
576
|
+
|
|
577
|
+
`collection()` derives three hexok `Event` classes: `Contacts.events.created`, `.updated` and `.deleted`, with tokens `contacts.created` and so on. Payloads are `{ doc, actorId }`, and `{ doc, previous, actorId }` on update, typed from the schema. `doc` is the stored document. A tenanted collection's payloads also carry `tenantId`.
|
|
578
|
+
|
|
579
|
+
The app lists them in its own catalog, next to its hand-written events:
|
|
580
|
+
|
|
581
|
+
```ts
|
|
582
|
+
// examples/crm/src/domain/events/domain-events.ts
|
|
583
|
+
export class DomainEvents extends EventCatalog('domain-events', {
|
|
584
|
+
companiesCreated: Companies.events.created,
|
|
585
|
+
companiesUpdated: Companies.events.updated,
|
|
586
|
+
companiesDeleted: Companies.events.deleted,
|
|
587
|
+
contactsCreated: Contacts.events.created,
|
|
588
|
+
contactsUpdated: Contacts.events.updated,
|
|
589
|
+
contactsDeleted: Contacts.events.deleted,
|
|
590
|
+
dealsCreated: Deals.events.created,
|
|
591
|
+
dealsUpdated: Deals.events.updated,
|
|
592
|
+
dealsDeleted: Deals.events.deleted,
|
|
593
|
+
membershipsCreated: Memberships.events.created,
|
|
594
|
+
membershipsUpdated: Memberships.events.updated,
|
|
595
|
+
membershipsDeleted: Memberships.events.deleted,
|
|
596
|
+
organizationsCreated: Organizations.events.created,
|
|
597
|
+
organizationsUpdated: Organizations.events.updated,
|
|
598
|
+
organizationsDeleted: Organizations.events.deleted,
|
|
599
|
+
dealContactsCreated: Deals.relations.contacts.through.events.created,
|
|
600
|
+
dealContactsUpdated: Deals.relations.contacts.through.events.updated,
|
|
601
|
+
dealContactsDeleted: Deals.relations.contacts.through.events.deleted,
|
|
602
|
+
dealClosed: DealClosedEvent,
|
|
603
|
+
}) {}
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
- Generated writes publish through `build({ events })` after the store write succeeds. A publish failure reaches the caller, and the write stays. Reads publish nothing. Overrides and methods publish their own events.
|
|
607
|
+
- Collection events stay inside the product. Another product or a customer gets a mapping of its own: an integration event or a webhook. See [A worker](#a-worker-webhooks-and-integration-events).
|
|
608
|
+
|
|
609
|
+
### Tracing
|
|
610
|
+
|
|
611
|
+
Lattice traces through `@opentelemetry/api`. With no OpenTelemetry SDK registered, the API is a no-op, and that is the switch: there is no option. An app that registers an SDK, with a context manager such as `@opentelemetry/context-async-hooks`, gets these spans. Their tracer is `@latticecms/core`, at the package's version.
|
|
612
|
+
|
|
613
|
+
| Span | Kind | Where | Attributes |
|
|
614
|
+
| --- | --- | --- | --- |
|
|
615
|
+
| `deals/find`, one per procedure | server | Lattice's router middleware, on every caller: HTTP, `createLocalClient`, MCP | `rpc.system` (`ts-pf`), `rpc.service` (`deals`), `rpc.method` (`find`; a relation's is `categories/list`), `lattice.outcome`, `lattice.code` |
|
|
616
|
+
| `deals.find`, one per use case | internal | the family's hooks, on every path, `useCases` too | `lattice.use_case`, `lattice.collection`, `lattice.action`, `lattice.actor_id`, `lattice.tenant_id` or `lattice.tenancy: 'bypass'`, `lattice.outcome`, `lattice.code` |
|
|
617
|
+
|
|
618
|
+
- The procedure span is active while the procedure runs. The use case span is its child, or the caller's span's on a direct `useCases.*.execute`.
|
|
619
|
+
- A store's spans, such as MongoStore's, are children of the active span: the procedure's, or the caller's. hexok has no hook around `execute`, so the use case span cannot be made active: a store call is its sibling, not its child.
|
|
620
|
+
- `lattice.outcome` is `ok`, `refused` or `failed`. A refusal (`FORBIDDEN`, `NOT_FOUND`, `VALIDATION`, any declared code) sets `lattice.code` and leaves the status unset: it is the caller's, not a failure. An unexpected throw sets status ERROR, `error.type`, and an exception event.
|
|
621
|
+
- A guard's refusal, and ts-pf's own input check, happen before the use case's hooks: they show on the procedure span only.
|
|
622
|
+
- A span carries no input, no document and no masked value: only names, ids, codes and outcomes.
|
|
623
|
+
|
|
624
|
+
To export these spans, register an SDK at startup; see [Tracing with an SDK](#tracing-with-an-sdk).
|
|
625
|
+
|
|
626
|
+
### MCP and OpenAPI
|
|
627
|
+
|
|
628
|
+
Each generated procedure carries `docs({ summary })` and `mcp({ effect })` in its `.meta()`, so `@ts-pf/openapi`, `@ts-pf/codegen` and `@ts-pf/mcp` describe it with no code in the app. The summary names the collection by its label; see the [reference](#collection-options).
|
|
629
|
+
|
|
630
|
+
| Procedure | `effect` | Summary, for `deals` |
|
|
631
|
+
| --- | --- | --- |
|
|
632
|
+
| `find` | `read` | Find deals. Filter with where, order with sort, and page with limit and after (the previous page’s next). populate expands companyId into documents. |
|
|
633
|
+
| `count` | `read` | Count deals. Filter with where. |
|
|
634
|
+
| `get` | `read` | Get one deal by id. populate expands companyId into documents. |
|
|
635
|
+
| `create` | `write` | Create one deal. |
|
|
636
|
+
| `update` | `write` | Update one deal by id. Send only the fields to change, and null to clear an optional one. |
|
|
637
|
+
| `delete` | `destructive` | Delete one deal by id. |
|
|
638
|
+
| a relation's `list` | `read` | List the categories of one post, by its id. … |
|
|
639
|
+
| a relation's `set` | `destructive` | Replace the categories of one post, by its id. Links not given are removed. |
|
|
640
|
+
|
|
641
|
+
- The `populate` sentence appears only when the read can populate.
|
|
642
|
+
- `@ts-pf/mcp` turns `read` into `readOnlyHint: true`, and `destructive` into `destructiveHint: true`. The effect is a literal in the contract's type too, so `all(tk.deals, { effect: 'read' })` selects in types what it selects at runtime.
|
|
643
|
+
- A method's meta comes from its `summary` and `effect` statics; see [The family](#the-family). An override keeps its procedure's meta.
|
|
644
|
+
- Every procedure also carries a `lattice` key: its collection, the collection's label, and its operation. A relation's `list` and `set` name the relation and its `target` collection, and a method names itself: `{ collection: 'deals', label: { singular: 'deal', plural: 'deals' }, operation: 'method', method: 'close' }`. `LatticeMeta` is its type. A client such as the admin reads it from `catalog()`, instead of guessing from a procedure's path.
|
|
645
|
+
|
|
646
|
+
A maskable field says in its JSON Schema that it may be withheld, and that a query on it may be refused; see [Field masking](#field-masking). A populated read has ts-pf's `x-ts-pf-expand` in OpenAPI. The crm serves both; see [Serving MCP and OpenAPI](#serving-mcp-and-openapi).
|
|
647
|
+
|
|
648
|
+
## Recipes
|
|
649
|
+
|
|
650
|
+
Each recipe quotes [`examples/crm`](../../examples/crm), and names the file, or links to the root README's Getting started. A test in the crm checks that every quote here matches its file, and the walkthrough runs Getting started as written.
|
|
651
|
+
|
|
652
|
+
### The smallest edge
|
|
653
|
+
|
|
654
|
+
The root README's [Getting started](../../README.md#4-the-server) has the smallest edge that keeps these rules: a fixed token from `@hexok/auth`'s `StaticTokenAuthenticator`, a membership check on every call, and the actor built only after both. A test runs it as written. The crm's edge below is the same shape with sessions, support actors and MCP.
|
|
655
|
+
|
|
656
|
+
### The auth edge
|
|
657
|
+
|
|
658
|
+
Lattice never imports auth. The edge decides who the actor is, and passes it in the call context. In the crm, a `@hexok/auth` session proves the user, and a membership lookup checks the organization the request names, on every request:
|
|
659
|
+
|
|
660
|
+
```ts
|
|
661
|
+
// examples/crm/src/servers/http/handler.ts
|
|
662
|
+
async function signedIn(
|
|
663
|
+
deps: HttpDeps,
|
|
664
|
+
request: Request,
|
|
665
|
+
logger: Logger,
|
|
666
|
+
edge: Edge,
|
|
667
|
+
): Promise<{ readonly userId: string; readonly token: string } | undefined> {
|
|
668
|
+
const refused = (reason: string) => {
|
|
669
|
+
logger.info(edge, { outcome: 'refused', code: 'UNAUTHORIZED', reason });
|
|
670
|
+
return undefined;
|
|
671
|
+
};
|
|
672
|
+
const token = bearerToken(request.headers.get('authorization'));
|
|
673
|
+
// The reason hexok's sessions give for no token.
|
|
674
|
+
if (token === undefined) return refused('missing');
|
|
675
|
+
const found = await deps.sessions.authenticate(token);
|
|
676
|
+
if (!found.ok) return refused(found.code);
|
|
677
|
+
return { userId: found.value.userId, token };
|
|
678
|
+
}
|
|
679
|
+
```
|
|
680
|
+
|
|
681
|
+
```ts
|
|
682
|
+
// examples/crm/src/servers/http/handler.ts
|
|
683
|
+
function actorContext(deps: HttpDeps) {
|
|
684
|
+
const memberships = deps.crm.repos.memberships;
|
|
685
|
+
return async (
|
|
686
|
+
userId: string,
|
|
687
|
+
request: Request,
|
|
688
|
+
logger: Logger,
|
|
689
|
+
edge: Edge,
|
|
690
|
+
): Promise<CallContext<Actor>> => {
|
|
691
|
+
if (deps.support.has(userId)) {
|
|
692
|
+
return { actor: { userId, support: true }, logger };
|
|
693
|
+
}
|
|
694
|
+
const organizationId = request.headers.get(organizationHeader);
|
|
695
|
+
// Trusted edge code: it decides who the actor is, so no actor's access
|
|
696
|
+
// applies yet. A missing organization and one that does not exist look
|
|
697
|
+
// the same as one the user is not a member of.
|
|
698
|
+
const [member] =
|
|
699
|
+
organizationId === null
|
|
700
|
+
? []
|
|
701
|
+
: (
|
|
702
|
+
await memberships.find(
|
|
703
|
+
{
|
|
704
|
+
where: {
|
|
705
|
+
userId: { eq: userId },
|
|
706
|
+
organizationId: { eq: organizationId },
|
|
707
|
+
},
|
|
708
|
+
limit: 1,
|
|
709
|
+
},
|
|
710
|
+
unscoped,
|
|
711
|
+
)
|
|
712
|
+
).docs;
|
|
713
|
+
if (organizationId === null || member === undefined) {
|
|
714
|
+
logger.info(edge, {
|
|
715
|
+
outcome: 'refused',
|
|
716
|
+
code: 'FORBIDDEN',
|
|
717
|
+
reason: organizationId === null ? 'no-organization' : 'not-a-member',
|
|
718
|
+
});
|
|
719
|
+
throw refusal('FORBIDDEN');
|
|
720
|
+
}
|
|
721
|
+
return { actor: { userId, organizationId, role: member.role }, logger };
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
```
|
|
725
|
+
|
|
726
|
+
`FetchHandler` serves the app at `/rpc` with that context, and `onError` from `build()` logs what the family did not:
|
|
727
|
+
|
|
728
|
+
```ts
|
|
729
|
+
// examples/crm/src/servers/http/handler.ts
|
|
730
|
+
const onError = deps.crm.onError(deps.logger);
|
|
731
|
+
const api = new FetchHandler(deps.crm.app, { onError });
|
|
732
|
+
const auth = new FetchHandler(createAuthRouter(deps), { onError });
|
|
733
|
+
const contextOf = actorContext(deps);
|
|
734
|
+
const apiContext = async (request: Request) => {
|
|
735
|
+
const logger = deps.logger.child({ requestId: requestIdOf(request) });
|
|
736
|
+
const user = await signedIn(deps, request, logger, 'rpc');
|
|
737
|
+
if (user === undefined) throw refusal('UNAUTHORIZED');
|
|
738
|
+
return contextOf(user.userId, request, logger, 'rpc');
|
|
739
|
+
};
|
|
740
|
+
```
|
|
741
|
+
|
|
742
|
+
| Case | Answer |
|
|
743
|
+
| --- | --- |
|
|
744
|
+
| No token, a bad or expired one, or an ended session | `401 UNAUTHORIZED`, one body for all |
|
|
745
|
+
| No organization header, not a member, or no such organization | `403 FORBIDDEN`, one body for all |
|
|
746
|
+
| A support user | Reads every organization, changes nothing |
|
|
747
|
+
|
|
748
|
+
The reason is logged, never sent. A switched or revoked membership takes effect on the next request, because the check runs on each one.
|
|
749
|
+
|
|
750
|
+
### Login on its own router
|
|
751
|
+
|
|
752
|
+
Sign-in is not a Lattice procedure: every Lattice procedure has an actor, and a caller signing in has none yet. The crm serves it at `/auth`, beside `/rpc`, as a plain ts-pf router, with sign-out and the caller's organizations:
|
|
753
|
+
|
|
754
|
+
```ts
|
|
755
|
+
// examples/crm/src/servers/auth/contract.ts
|
|
756
|
+
export const authContract = router({
|
|
757
|
+
login: procedure
|
|
758
|
+
.input(loginInput)
|
|
759
|
+
.output(z.object({ token: z.string().min(1) }))
|
|
760
|
+
.errors({
|
|
761
|
+
UNAUTHORIZED: { status: 401, message: 'The credentials are not valid' },
|
|
762
|
+
}),
|
|
763
|
+
logout: procedure.input(z.object({})).output(z.null()),
|
|
764
|
+
/**
|
|
765
|
+
* The organizations the signed-in user is a member of, by name, for an
|
|
766
|
+
* organization switcher. It needs a session and no organization header:
|
|
767
|
+
* the caller has not picked one yet. Support acts in none, so it gets none.
|
|
768
|
+
*/
|
|
769
|
+
organizations: procedure
|
|
770
|
+
.input(z.object({}))
|
|
771
|
+
.output(z.array(z.object({ id: z.string(), name: z.string() })))
|
|
772
|
+
.errors({
|
|
773
|
+
UNAUTHORIZED: { status: 401, message: 'The actor is missing or invalid' },
|
|
774
|
+
}),
|
|
775
|
+
});
|
|
776
|
+
```
|
|
777
|
+
|
|
778
|
+
```ts
|
|
779
|
+
// examples/crm/src/servers/auth/router.ts
|
|
780
|
+
login: impl.login.handler(async ({ context, input }) => {
|
|
781
|
+
try {
|
|
782
|
+
const { userId } = await deps.login.execute(
|
|
783
|
+
{ logger: context.logger },
|
|
784
|
+
input,
|
|
785
|
+
);
|
|
786
|
+
return { token: await deps.sessions.open({ userId }) };
|
|
787
|
+
} catch (error) {
|
|
788
|
+
if (!LoginError.is(error)) throw error;
|
|
789
|
+
throw new PFError({
|
|
790
|
+
code: 'UNAUTHORIZED',
|
|
791
|
+
status: 401,
|
|
792
|
+
message: error.message,
|
|
793
|
+
cause: error,
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
}),
|
|
797
|
+
```
|
|
798
|
+
|
|
799
|
+
- The `Login` use case checks the password and the lockout; the router opens the session. The use case never sees a token.
|
|
800
|
+
- `organizations` lists the signed-in user's organizations, `{ id, name }`, sorted by name, for an organization switcher. It needs a session and no organization header, since the caller has not picked one yet. It runs the edge's own session check, and reads memberships and organizations through their repos as trusted edge code, as the membership check does. Support gets none.
|
|
801
|
+
- Password hashes and failed attempts live in store collections Lattice never registers, `credentials` and `login_attempts`, so no procedure, MCP tool or OpenAPI document can reach them.
|
|
802
|
+
- The crm's [README](../../examples/crm/README.md#passwords-and-their-limits) gives the hashing and lockout rules.
|
|
803
|
+
|
|
804
|
+
### Masking by role
|
|
805
|
+
|
|
806
|
+
The edge puts the member's role on the actor ([The auth edge](#the-auth-edge)), and the collection's `fields` rule reads it:
|
|
807
|
+
|
|
808
|
+
```ts
|
|
809
|
+
// examples/crm/src/servers/rpc/contract.ts
|
|
810
|
+
// A member sees every deal of the organization, without its amount.
|
|
811
|
+
fields: {
|
|
812
|
+
amount: {
|
|
813
|
+
read: ({ actor }) => 'support' in actor || actor.role === 'manager',
|
|
814
|
+
},
|
|
815
|
+
},
|
|
816
|
+
```
|
|
817
|
+
|
|
818
|
+
A member's `deals.find` has no `amount`, and a `where` or `sort` on it is `VALIDATION`. A manager and support read it, and a manager filters by it. A member may still set it on create or update; the response leaves it out. The crm tests this over HTTP in [`masking.test.ts`](../../examples/crm/src/servers/http/masking.test.ts).
|
|
819
|
+
|
|
820
|
+
### A worker: webhooks and integration events
|
|
821
|
+
|
|
822
|
+
Collection events stay inside the product. In the crm, the HTTP process publishes each domain event to a `@hexok/queue` queue, and a worker process maps the ones that leave: a customer webhook through `@hexok/webhooks`, and an integration event for the company's other products through `@hexok/integration-events`.
|
|
823
|
+
|
|
824
|
+
```ts
|
|
825
|
+
// examples/crm/src/servers/worker/worker.ts
|
|
826
|
+
const integration = new IntegrationPublisher(CrmDeals, {
|
|
827
|
+
queue: deps.integrationQueue,
|
|
828
|
+
});
|
|
829
|
+
|
|
830
|
+
const handlers = [
|
|
831
|
+
new SendDealClosedWebhook({ deals: repos.deals, webhooks, logger }),
|
|
832
|
+
new PublishDealClosed({ deals: repos.deals, integration, logger }),
|
|
833
|
+
];
|
|
834
|
+
```
|
|
835
|
+
|
|
836
|
+
A handler is system code. It reads inside the event's own tenant, with `tenancy.scope`, never with an actor's access, and maps the document field by field, so a new field on the collection reaches no one outside until it is added to the mapping:
|
|
837
|
+
|
|
838
|
+
```ts
|
|
839
|
+
// examples/crm/src/app/event-handlers/deal-closed-integration.ts
|
|
840
|
+
async handle(event: DealClosedEvent): Promise<void> {
|
|
841
|
+
const { dealId, outcome, tenantId } = event.payload;
|
|
842
|
+
const deal = await this.deps.deals.get(
|
|
843
|
+
dealId,
|
|
844
|
+
tenancy.scope(Deals, tenantId),
|
|
845
|
+
);
|
|
846
|
+
if (deal === null || deal.closedAt === undefined) {
|
|
847
|
+
this.deps.logger.warn('deal.closed integration skipped', {
|
|
848
|
+
dealId,
|
|
849
|
+
tenantId,
|
|
850
|
+
reason: deal === null ? 'not-found' : 'not-closed',
|
|
851
|
+
});
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
854
|
+
await this.deps.integration.publish(
|
|
855
|
+
new DealClosedV1(dealClosedV1(deal, tenantId, outcome, deal.closedAt)),
|
|
856
|
+
// A deal closes once: a redelivery publishes the same id, and a
|
|
857
|
+
// consumer dedupes on it.
|
|
858
|
+
{ id: `deal.closed:${deal.id}`, subject: deal.id },
|
|
859
|
+
);
|
|
860
|
+
}
|
|
861
|
+
```
|
|
862
|
+
|
|
863
|
+
- Each handler subscribes in its own consumer group, inside a consumer span, through [`subscribe.ts`](../../examples/crm/src/servers/worker/subscribe.ts).
|
|
864
|
+
- The webhook leaves out `amount`, a field only managers read. The integration contract, [`src/integration/deals.ts`](../../examples/crm/src/integration/deals.ts), carries it: it is internal to the company.
|
|
865
|
+
- Masking applies where a document leaves for a client. Events and repos carry whole documents, so each mapping decides what leaves.
|
|
866
|
+
|
|
867
|
+
### Tracing with an SDK
|
|
868
|
+
|
|
869
|
+
Lattice's spans and the store's need an SDK and a context manager registered once, before the app serves. The crm's tests register one with an in-memory exporter; an app does the same at startup with its exporter, such as `@opentelemetry/sdk-node` and OTLP:
|
|
870
|
+
|
|
871
|
+
```ts
|
|
872
|
+
// examples/crm/src/servers/http/tracing.test.ts
|
|
873
|
+
const exporter = new InMemorySpanExporter();
|
|
874
|
+
beforeAll(() => {
|
|
875
|
+
context.setGlobalContextManager(
|
|
876
|
+
new AsyncLocalStorageContextManager().enable(),
|
|
877
|
+
);
|
|
878
|
+
trace.setGlobalTracerProvider(
|
|
879
|
+
new BasicTracerProvider({
|
|
880
|
+
spanProcessors: [new SimpleSpanProcessor(exporter)],
|
|
881
|
+
}),
|
|
882
|
+
);
|
|
883
|
+
});
|
|
884
|
+
```
|
|
885
|
+
|
|
886
|
+
A `deals/find` over HTTP is then a procedure span with the use case span and the store call under it. The crm's production processes register no SDK, so they record nothing.
|
|
887
|
+
|
|
888
|
+
### Serving MCP and OpenAPI
|
|
889
|
+
|
|
890
|
+
The crm turns the contract into MCP tools with `@ts-pf/mcp`. Every tool describes itself, generated or a method. The procedures no caller may use are the app's to leave out:
|
|
891
|
+
|
|
892
|
+
```ts
|
|
893
|
+
// examples/crm/src/servers/mcp/toolset.ts
|
|
894
|
+
const tk = createToolkit(contract).$context<CallContext<Actor>>();
|
|
895
|
+
|
|
896
|
+
// No access rule allows these, so every call is FORBIDDEN: as tools they
|
|
897
|
+
// would only cost a model context and wrong turns. They stay on /rpc.
|
|
898
|
+
const alwaysDenied = [
|
|
899
|
+
tk.memberships.create,
|
|
900
|
+
tk.memberships.update,
|
|
901
|
+
tk.memberships.delete,
|
|
902
|
+
tk.organizations.create,
|
|
903
|
+
tk.organizations.update,
|
|
904
|
+
tk.organizations.delete,
|
|
905
|
+
];
|
|
906
|
+
|
|
907
|
+
/**
|
|
908
|
+
* The API's procedures as MCP tools, each named by its path. Every one
|
|
909
|
+
* carries its summary and effect from the contract: Lattice writes them for
|
|
910
|
+
* generated operations, and a method declares them on its use case.
|
|
911
|
+
*/
|
|
912
|
+
export const crmTools = tk.$toolset({
|
|
913
|
+
tools: [all(tk, { exclude: alwaysDenied })],
|
|
914
|
+
});
|
|
915
|
+
|
|
916
|
+
// A new procedure fails this line until the toolset exposes it or this
|
|
917
|
+
// line excludes it.
|
|
918
|
+
tk.$coverage({ toolsets: [crmTools], exclude: alwaysDenied });
|
|
919
|
+
```
|
|
920
|
+
|
|
921
|
+
The tools run in process through the implemented router, so access, tenancy, masking, errors and spans are the same as on `/rpc`. The edge checks the session before the MCP SDK reads the request, and the tool context reuses the auth edge's `actorContext`:
|
|
922
|
+
|
|
923
|
+
```ts
|
|
924
|
+
// examples/crm/src/servers/http/handler.ts
|
|
925
|
+
const tools = bindTools(crmTools, {
|
|
926
|
+
app: deps.crm.app,
|
|
927
|
+
onError,
|
|
928
|
+
async context(info) {
|
|
929
|
+
const userId = info.authInfo?.extra?.userId;
|
|
930
|
+
const requestId = info.authInfo?.extra?.requestId;
|
|
931
|
+
const request = info.requestInfo;
|
|
932
|
+
// The edge sets all three before the SDK runs: this is a bug guard.
|
|
933
|
+
if (
|
|
934
|
+
typeof userId !== 'string' ||
|
|
935
|
+
typeof requestId !== 'string' ||
|
|
936
|
+
request === undefined
|
|
937
|
+
) {
|
|
938
|
+
throw refusal('UNAUTHORIZED');
|
|
939
|
+
}
|
|
940
|
+
return contextOf(
|
|
941
|
+
userId,
|
|
942
|
+
request,
|
|
943
|
+
deps.logger.child({ requestId }),
|
|
944
|
+
'mcp',
|
|
945
|
+
);
|
|
946
|
+
},
|
|
947
|
+
});
|
|
948
|
+
```
|
|
949
|
+
|
|
950
|
+
The OpenAPI document is a projection of the contract's catalog, with ts-pf's `codegen` profile for generators in other languages:
|
|
951
|
+
|
|
952
|
+
```ts
|
|
953
|
+
// examples/crm/src/servers/rpc/openapi.ts
|
|
954
|
+
export function openapiDocument() {
|
|
955
|
+
return openapi(catalogDocument(), {
|
|
956
|
+
info: { title: 'Lattice CRM', version: '0.0.0' },
|
|
957
|
+
profile: 'codegen',
|
|
958
|
+
});
|
|
959
|
+
}
|
|
960
|
+
```
|
|
961
|
+
|
|
962
|
+
The crm serves it at `GET /openapi.json`, and the catalog itself at `GET /catalog.json`, to signed-in users only, since both say which fields are masked. The catalog carries each procedure's `lattice` meta and the `x-lattice-*` keys; the admin builds its views from it. A TypeScript client in another repo uses `@ts-pf/codegen` on the same catalog instead; the crm's [`codegen.test.ts`](../../examples/crm/src/servers/rpc/codegen.test.ts) is that client, with no casts.
|
|
963
|
+
|
|
964
|
+
### Mounting the admin
|
|
965
|
+
|
|
966
|
+
[`@latticecms/admin`](../admin) renders the app from the catalog it serves. The crm's page signs in through `/auth`, lists the user's organizations for a switcher from `/auth organizations`, which needs no organization header, and calls the API with the picked one:
|
|
967
|
+
|
|
968
|
+
```tsx
|
|
969
|
+
// examples/crm/src/web/app.tsx
|
|
970
|
+
const auth = useMemo(
|
|
971
|
+
() => authClient(sessionFetch(token, undefined, onSignedOut)),
|
|
972
|
+
[token, onSignedOut],
|
|
973
|
+
);
|
|
974
|
+
// A 401 signs out through the session's fetch. Anything else, such as a
|
|
975
|
+
// dropped connection, can be tried again.
|
|
976
|
+
const load = useCallback(() => {
|
|
977
|
+
setFailed(false);
|
|
978
|
+
auth.organizations({}).then(setOrganizations, () => setFailed(true));
|
|
979
|
+
}, [auth]);
|
|
980
|
+
useEffect(load, [load]);
|
|
981
|
+
const current =
|
|
982
|
+
organizations?.find(({ id }) => id === picked) ?? organizations?.[0];
|
|
983
|
+
const fetch = useMemo(
|
|
984
|
+
() => sessionFetch(token, current?.id, onSignedOut),
|
|
985
|
+
[token, current, onSignedOut],
|
|
986
|
+
);
|
|
987
|
+
```
|
|
988
|
+
|
|
989
|
+
`<Admin>` is keyed by the organization, so a switch starts with an empty cache and never shows another organization's rows:
|
|
990
|
+
|
|
991
|
+
```tsx
|
|
992
|
+
// examples/crm/src/web/app.tsx
|
|
993
|
+
<Admin
|
|
994
|
+
// A new organization is a new admin, with an empty cache.
|
|
995
|
+
key={current?.id ?? 'support'}
|
|
996
|
+
fetch={fetch}
|
|
997
|
+
catalogUrl="/catalog.json"
|
|
998
|
+
basePath="/admin"
|
|
999
|
+
```
|
|
1000
|
+
|
|
1001
|
+
The edge checks the organization header on every call, as in [The auth edge](#the-auth-edge). The admin's README has its props, the catalog route and what it renders. The smallest page, a token form, is in the root README's [Getting started](../../README.md#5-the-admin-page).
|
|
1002
|
+
|
|
1003
|
+
## Reference
|
|
1004
|
+
|
|
1005
|
+
### `collection()` options
|
|
1006
|
+
|
|
1007
|
+
`collection(slug, { schema, tenant?, indexes?, relations?, maskable?, label? })`
|
|
1008
|
+
|
|
1009
|
+
Returns a `Collection` with `slug`, `label`, `schema`, `tenant`, `indexes`, `output`, `clientOutput`, `maskable`, `events` and `hooks()`. `output` is the stored document's schema: the collection's schema plus `id`, `createdAt`, `updatedAt` and the tenant field. `clientOutput` is the document a client receives: `output`, with each maskable field optional.
|
|
1010
|
+
|
|
1011
|
+
- `schema` is a `z.object()`. Unknown keys are stripped.
|
|
1012
|
+
- `id`, `createdAt`, `updatedAt`, `and` and `or` are reserved field names, listed in `reservedFields`. The tenant field may not be one either.
|
|
1013
|
+
- No `z.date()` and no transforms, anywhere in the schema. Store ISO strings (`z.iso.datetime()`). Normalize in a `beforeChange` hook. `collection()` throws at definition time, and a top-level Date or reserved name fails to compile.
|
|
1014
|
+
- `createdAt` and `updatedAt` are ISO 8601 strings.
|
|
1015
|
+
- `tenant: 'organizationId'` makes the collection tenanted; see [Tenancy](#tenancy). Without it, the collection is global.
|
|
1016
|
+
- A field name may not contain `.`, start with `$`, or be `_id`: MongoDB would read it as a path, an operator or the id.
|
|
1017
|
+
- `maskable: ['amount']` names schema fields a caller's rules may withhold; see [Field masking](#field-masking). A maskable field may not be a ref or in a unique index.
|
|
1018
|
+
- `label: { singular: 'person', plural: 'people' }` says how the collection reads mid-sentence, in generated summaries and the admin. Without it, the label comes from the slug: `deal_stages` reads "deal stage" and "deal stages". Declare it when the slug's singular would be wrong, as for `people` or `news`. `labelOf(slug)` returns the label a slug gets.
|
|
1019
|
+
- A field's label in a client such as the admin is its name in words, or its JSON Schema `title`: `amount: z.number().meta({ title: 'Deal value' })`. Zod's `.meta()` reaches the catalog, OpenAPI and MCP.
|
|
1020
|
+
- `indexes` lists the indexes the store creates at startup, through `build().ensure()`: `[{ fields: { stage: 1, createdAt: -1 } }, { fields: { email: 1 }, unique: true }]`. Fields are named from the stored document, so the system fields and the tenant field count; any other name is a compile error and a throw. Key order is the index's order. `id` needs no index. A tenanted collection's indexes usually lead with the tenant field, because every call filters by it; Lattice does not add it for you.
|
|
1021
|
+
|
|
1022
|
+
### Catalog facts
|
|
1023
|
+
|
|
1024
|
+
`catalog(contract)` from `@ts-pf/docs` carries what a client such as the admin needs, so it reads them instead of guessing from paths and names:
|
|
1025
|
+
|
|
1026
|
+
| Fact | Where | What it says |
|
|
1027
|
+
| --- | --- | --- |
|
|
1028
|
+
| `lattice` meta | Each procedure's meta | Its collection, the collection's label, and its operation; a relation's name and `target`; a method's name. `LatticeMeta` is its type |
|
|
1029
|
+
| `docs` and `mcp` meta | Each procedure's meta | Its summary and its effect: `read`, `write` or `destructive`. A method's come from its `summary` and `effect` statics |
|
|
1030
|
+
| `x-lattice-ref` | A ref's JSON Schema | The slug of the collection it points to |
|
|
1031
|
+
| `x-lattice-maskable` | A maskable field's JSON Schema | That a caller's rule may withhold it |
|
|
1032
|
+
| `x-lattice-tenant` | The tenant field's JSON Schema | That Lattice stamps it, so a client shows it read-only |
|
|
1033
|
+
| `title` | A field's JSON Schema, from `.meta({ title })` | Its label; without one, a client uses its name in words |
|
|
1034
|
+
|
|
1035
|
+
### `Where` and `Sort`
|
|
1036
|
+
|
|
1037
|
+
`find` takes `{ where?, sort?, limit?, after? }` and returns `{ docs, next }`. `Where<Doc>` and `Sort<Doc>` are typed from the document, system fields included.
|
|
1038
|
+
|
|
1039
|
+
| Field kind | Operators |
|
|
1040
|
+
| --- | --- |
|
|
1041
|
+
| string | `eq`, `ne`, `in`, `nin`, `gt`, `gte`, `lt`, `lte`, `contains`, `exists` |
|
|
1042
|
+
| number | `eq`, `ne`, `in`, `nin`, `gt`, `gte`, `lt`, `lte`, `exists` |
|
|
1043
|
+
| boolean, enum | `eq`, `ne`, `in`, `nin`, `exists` |
|
|
1044
|
+
| array of strings, numbers or enum values | `has`, `exists` |
|
|
1045
|
+
| array of anything else, object, anything else | `exists` |
|
|
1046
|
+
|
|
1047
|
+
- Several fields or operators must all match. `and` and `or` nest. Null and missing follow MongoDB's semantics.
|
|
1048
|
+
- `contains` is a case-insensitive substring, never a regex.
|
|
1049
|
+
- `has` matches an array with an element equal to its value. A missing or null array has none.
|
|
1050
|
+
- `sort` is an array such as `['-createdAt', 'title']`. Only required, non-null string, number and enum fields sort. The default is `['-createdAt']`, and `id` is always the last tiebreak. Its JSON Schema lists every key it accepts, so a client sees the valid keys.
|
|
1051
|
+
- `limit` is 1 to 100, default 20. `next` is an opaque cursor for `after`, or null on the last page.
|
|
1052
|
+
- A field or operator the schema does not allow is a type error and `VALIDATION`.
|
|
1053
|
+
|
|
1054
|
+
`count` takes `{ where? }` and returns `{ count }`: how many documents `find` would return across every page. It runs `read` access and the tenant clause, as `find` does, validates `where` the same way, and writes one log line. A list that needs a total calls `find` and `count` side by side; `find` never counts.
|
|
1055
|
+
|
|
1056
|
+
`update` takes `{ id }` and the fields to change. A field left out keeps its value, and a patch never applies a default.
|
|
1057
|
+
|
|
1058
|
+
- `null` clears an optional field with no default: the key is removed, and the `updated` event's `doc` lacks it. Its JSON Schema, and so its client type, takes `null`: `closedAt?: string | null`.
|
|
1059
|
+
- A nullable field stores `null`. A required or defaulted field refuses `null` with `VALIDATION` at its path.
|
|
1060
|
+
- The document after the change is validated with the whole schema, so an object-level `.refine()` holds on update too.
|
|
1061
|
+
|
|
1062
|
+
### Errors
|
|
1063
|
+
|
|
1064
|
+
Every procedure declares `UNAUTHORIZED` (401), `FORBIDDEN` (403), `NOT_FOUND` (404 with `{ collection, id }`), `CONFLICT` (409 with `{ collection, id }`) and `REFERENCED` (409 with `{ collection, id, by }`), plus the app's declared errors. `VALIDATION` is ts-pf's protocol code, with `{ path, message }[]` issues.
|
|
1065
|
+
|
|
1066
|
+
- `LatticeError` is the hexok `Errors` catalog behind those codes. Overrides and methods throw it, so they answer as the generated operations do: `LatticeError.NOT_FOUND({ collection: 'deals', id })`.
|
|
1067
|
+
- The app's errors are a hexok `Errors` catalog, its client map and its mapper, as in hexok's app-template: `framework({ errors: { declared, map } })`. An app code that collides with Lattice's is a compile error.
|
|
1068
|
+
- An error that is neither Lattice's nor mapped by the app reaches an HTTP client as `INTERNAL`. An in-process caller gets the original error.
|
|
1069
|
+
|
|
1070
|
+
### `Repo` and `Doc`
|
|
1071
|
+
|
|
1072
|
+
`Repo<C>` is a typed view of the store for one collection: `get`, `getMany`, `find`, `count`, `insert`, `update` and `remove`. Use it in hand-written use cases and event handlers. It is trusted: it runs no hooks, no events and no access check.
|
|
1073
|
+
|
|
1074
|
+
- `insert` takes the schema's input type and parses it, as create does: defaults apply, unknown keys are dropped, and a failed check throws `LatticeError` `VALIDATION` with create's issues. Then it stamps `id`, `createdAt` and `updatedAt`.
|
|
1075
|
+
- `update` takes a typed patch of the schema's output and writes it as given, with no parse. It bumps `updatedAt`. A key set to `undefined` removes the field.
|
|
1076
|
+
|
|
1077
|
+
Every call takes a scope as its last argument: the call's `Scope` from `ctx.access.scope()`, a tenant's from `tenancy.scope()`, or `unscoped`. A row outside the scope acts as missing. `unscoped` reads and writes every row; trusted code that acts for no caller passes it, such as a script. A `Scope` for another collection throws.
|
|
1078
|
+
|
|
1079
|
+
On a tenanted collection, `insert` stamps the scope's tenant and does not take `unscoped`. `update` never writes the tenant field. `scope.tenantId` is the tenant, for a method's own events.
|
|
1080
|
+
|
|
1081
|
+
`Doc<C>` is the collection's stored document type.
|
|
1082
|
+
|
|
1083
|
+
```ts
|
|
1084
|
+
// examples/crm/src/app/use-cases/deals/archive-deal.ts
|
|
1085
|
+
export class ArchiveDeal extends AppUseCase('deals.delete', {
|
|
1086
|
+
collection: Deals,
|
|
1087
|
+
}) {
|
|
1088
|
+
constructor(private readonly deps: { deals: Repo<typeof Deals> }) {
|
|
1089
|
+
super();
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
async execute(
|
|
1093
|
+
ctx: AppCtx,
|
|
1094
|
+
input: { id: string },
|
|
1095
|
+
): Promise<Doc<typeof Deals>> {
|
|
1096
|
+
const deal = await this.deps.deals.update(
|
|
1097
|
+
input.id,
|
|
1098
|
+
{ archived: true },
|
|
1099
|
+
await ctx.access.scope(Deals, 'delete'),
|
|
1100
|
+
);
|
|
1101
|
+
// The same refusal the generated delete gives for a missing id.
|
|
1102
|
+
if (deal === null) {
|
|
1103
|
+
throw LatticeError.NOT_FOUND({ collection: Deals.slug, id: input.id });
|
|
1104
|
+
}
|
|
1105
|
+
return deal;
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
```
|
|
1109
|
+
|
|
1110
|
+
### `CollectionStore` and `MemoryStore`
|
|
1111
|
+
|
|
1112
|
+
`CollectionStore` is the hexok port every collection uses: `ensure`, `find`, `count`, `get`, `getMany`, `insert`, `update`, `remove` and `transaction`. A `where` on a single-row call limits the rows it can touch; a row outside it acts as missing. `MemoryStore` is the in-memory adapter, for tests and examples. It stores copies and enforces unique indexes.
|
|
1113
|
+
|
|
1114
|
+
- `ensure(collection, indexes)` creates the indexes a collection lacks and never drops one. An `Index` is `{ fields: { status: 1, createdAt: -1 }, unique? }`. A unique index treats a missing field as null, as MongoDB does, and a write that breaks one is `CONFLICT`.
|
|
1115
|
+
- `count(collection, where?)` counts the documents that match.
|
|
1116
|
+
- `transaction(work)` runs `work` with a store whose calls join one unit: a commit, or on a throw, nothing. Each store makes it as atomic as it can, and a store without transactions runs `work` on itself, in order. A nested `transaction` joins the outer one. `MemoryStore` snapshots its collections and restores them on a throw; it does not isolate calls made outside `work` while it runs.
|
|
1117
|
+
|
|
1118
|
+
### Writing a store adapter
|
|
1119
|
+
|
|
1120
|
+
`@latticecms/core/store` has what an adapter needs: the `CollectionStore` port, its types (`StoredDoc`, `Patch`, `FindQuery`, `Page`, `Index`), the parsed filter (`AnyWhere`, with `FieldOps` for each field's operators), and the cursor helpers (`orderOf`, `Order`, `after`, `encodeCursor`). A store receives values Lattice has parsed. Filters follow MongoDB's null and missing rules, and the keyset of `after` is itself an `AnyWhere`, so a store applies it like any filter.
|
|
1121
|
+
|
|
1122
|
+
`@latticecms/core/store/conformance` has `storeCases`: the cases every store passes, asserted with `node:assert`, so any test runner runs them. Give each case a fresh store:
|
|
1123
|
+
|
|
1124
|
+
```ts
|
|
1125
|
+
import { storeCases } from '@latticecms/core/store/conformance';
|
|
1126
|
+
|
|
1127
|
+
describe('MongoStore conformance', () => {
|
|
1128
|
+
let store: MongoStore;
|
|
1129
|
+
beforeEach(async () => {
|
|
1130
|
+
store = await freshStore();
|
|
1131
|
+
});
|
|
1132
|
+
afterEach(() => store.stop());
|
|
1133
|
+
|
|
1134
|
+
it.each(storeCases)('$name', ({ run }) => run(store));
|
|
1135
|
+
});
|
|
1136
|
+
```
|
|
1137
|
+
|
|
1138
|
+
A case that needs a capability some stores lack says so in `needs`. A store without transactions runs the rest:
|
|
1139
|
+
|
|
1140
|
+
```ts
|
|
1141
|
+
it.each(storeCases.filter((c) => !c.needs?.includes('transactions')))('$name', ({ run }) => run(store));
|
|
1142
|
+
```
|
|
1143
|
+
|
|
1144
|
+
### Other types
|
|
1145
|
+
|
|
1146
|
+
- `Withheld` is `{ id: string }`: a populated document the caller may not read.
|
|
1147
|
+
- `LatticeMeta` is the `lattice` key of each procedure's meta; see [MCP and OpenAPI](#mcp-and-openapi).
|
|
1148
|
+
- `ClientDoc<C>` is a collection's document as a client receives it, each maskable field optional.
|
|
1149
|
+
- `ReadUseCase<Proc, Ctx>` is the type of a populating read in `useCases`: its `execute` is generic in the `populate` list.
|
|
1150
|
+
- `Ref<Slug, OnDelete>`, `Many<Target, Through, Fields, OnDelete>`, `RelationsOf` and `JoinShape` are the types of refs, relations and join collections. `OnDelete` and `ManyOnDelete` are their `onDelete` values. An app names them only when it exports its collections from a package with declarations.
|
|
1151
|
+
- `CallAccess` is the type of `ctx.access`. `AccessRequest<Actor>` is what `Access.check` receives.
|
|
1152
|
+
- `Scope` is what `ctx.access.scope()` and `tenancy.scope()` return.
|
|
1153
|
+
|
|
1154
|
+
## Guarantees
|
|
1155
|
+
|
|
1156
|
+
The tests prove each of these.
|
|
1157
|
+
|
|
1158
|
+
- A client of the contract needs no type annotations at the call site.
|
|
1159
|
+
- An override keeps the contract's types, and a method adds a typed procedure.
|
|
1160
|
+
- Each call writes one log line. Each refusal is logged once, whether the call came over RPC, in process, or through `useCases`.
|
|
1161
|
+
- No use case runs when access says `false`, and no row outside an access `Where` is read, changed or returned.
|
|
1162
|
+
- Each access function runs once per call.
|
|
1163
|
+
- No call reaches another tenant's rows, and every bypassed call is logged.
|
|
1164
|
+
- Events publish only after a successful write.
|
|
1165
|
+
- A populated document passes its collection's `read` access and tenant, or comes back as `{ id }`.
|
|
1166
|
+
- A field a caller may not read never reaches it through a procedure's output, a filter, a count, a sort or a cursor, and the caller's update cannot change or clear it.
|
|
1167
|
+
- An update patch never resets a field to its default.
|
|
1168
|
+
- On update, the merged document is validated with the whole schema.
|
|
1169
|
+
|
|
1170
|
+
## Not yet
|
|
1171
|
+
|
|
1172
|
+
These are not built. [docs/architecture.md](../../docs/architecture.md#known-limits) lists the known limits of what is.
|
|
1173
|
+
|
|
1174
|
+
- An `@hexok/authz` adapter for `Access`. It waits for hexok to release `@hexok/authz`.
|
|
1175
|
+
- `entity`: a collection backed by a hexok `Entity` instead of a schema.
|
|
1176
|
+
- A store per collection. One `build({ store })` serves every collection.
|
|
1177
|
+
- File uploads: a file field, its blob storage and downloads.
|