@latticecms/core 0.0.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1297 -2
- package/dist/access.d.ts +209 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +241 -0
- package/dist/access.js.map +1 -0
- package/dist/build.d.ts +555 -0
- package/dist/build.d.ts.map +1 -0
- package/dist/build.js +655 -0
- package/dist/build.js.map +1 -0
- package/dist/collection.d.ts +480 -0
- package/dist/collection.d.ts.map +1 -0
- package/dist/collection.js +351 -0
- package/dist/collection.js.map +1 -0
- package/dist/crud.d.ts +46 -0
- package/dist/crud.d.ts.map +1 -0
- package/dist/crud.js +527 -0
- package/dist/crud.js.map +1 -0
- package/dist/describe.d.ts +89 -0
- package/dist/describe.d.ts.map +1 -0
- package/dist/describe.js +119 -0
- package/dist/describe.js.map +1 -0
- package/dist/errors.d.ts +183 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +150 -0
- package/dist/errors.js.map +1 -0
- package/dist/family.d.ts +80 -0
- package/dist/family.d.ts.map +1 -0
- package/dist/family.js +227 -0
- package/dist/family.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/marker.d.ts +15 -0
- package/dist/marker.d.ts.map +1 -0
- package/dist/marker.js +28 -0
- package/dist/marker.js.map +1 -0
- package/dist/mask.d.ts +69 -0
- package/dist/mask.d.ts.map +1 -0
- package/dist/mask.js +277 -0
- package/dist/mask.js.map +1 -0
- package/dist/populate.d.ts +39 -0
- package/dist/populate.d.ts.map +1 -0
- package/dist/populate.js +72 -0
- package/dist/populate.js.map +1 -0
- package/dist/relations.d.ts +144 -0
- package/dist/relations.d.ts.map +1 -0
- package/dist/relations.js +144 -0
- package/dist/relations.js.map +1 -0
- package/dist/repo.d.ts +99 -0
- package/dist/repo.d.ts.map +1 -0
- package/dist/repo.js +92 -0
- package/dist/repo.js.map +1 -0
- package/dist/sort.d.ts +86 -0
- package/dist/sort.d.ts.map +1 -0
- package/dist/sort.js +187 -0
- package/dist/sort.js.map +1 -0
- package/dist/store/conformance.d.ts +15 -0
- package/dist/store/conformance.d.ts.map +1 -0
- package/dist/store/conformance.js +811 -0
- package/dist/store/conformance.js.map +1 -0
- package/dist/store/index.d.ts +9 -0
- package/dist/store/index.d.ts.map +1 -0
- package/dist/store/index.js +8 -0
- package/dist/store/index.js.map +1 -0
- package/dist/store.d.ts +119 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +176 -0
- package/dist/store.js.map +1 -0
- package/dist/tenancy.d.ts +66 -0
- package/dist/tenancy.d.ts.map +1 -0
- package/dist/tenancy.js +69 -0
- package/dist/tenancy.js.map +1 -0
- package/dist/tracing.d.ts +12 -0
- package/dist/tracing.d.ts.map +1 -0
- package/dist/tracing.js +27 -0
- package/dist/tracing.js.map +1 -0
- package/dist/where.d.ts +95 -0
- package/dist/where.d.ts.map +1 -0
- package/dist/where.js +308 -0
- package/dist/where.js.map +1 -0
- package/package.json +80 -2
- package/skills/lattice/SKILL.md +106 -0
- package/skills/lattice/references/access.md +90 -0
- package/skills/lattice/references/cli.md +87 -0
- package/skills/lattice/references/collection.md +94 -0
- package/skills/lattice/references/event-handler.md +88 -0
- package/skills/lattice/references/masking.md +72 -0
- package/skills/lattice/references/method.md +88 -0
- package/skills/lattice/references/override.md +160 -0
- package/skills/lattice/references/relations.md +91 -0
- package/skills/lattice/references/tenancy.md +82 -0
- package/skills/lattice/references/testing.md +75 -0
- package/src/access.ts +449 -0
- package/src/build.ts +1888 -0
- package/src/collection.ts +1025 -0
- package/src/crud.ts +797 -0
- package/src/describe.ts +232 -0
- package/src/errors.ts +174 -0
- package/src/family.ts +334 -0
- package/src/index.ts +44 -0
- package/src/marker.ts +54 -0
- package/src/mask.ts +336 -0
- package/src/populate.ts +103 -0
- package/src/relations.ts +370 -0
- package/src/repo.ts +218 -0
- package/src/sort.ts +271 -0
- package/src/store/conformance.ts +1179 -0
- package/src/store/index.ts +22 -0
- package/src/store.ts +315 -0
- package/src/tenancy.ts +124 -0
- package/src/tracing.ts +29 -0
- package/src/where.ts +463 -0
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Access
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
A collection's access functions attach at composition, beside its methods and overrides:
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
// examples/crm/src/servers/rpc/contract.ts
|
|
9
|
+
/** Any signed-in caller may do this. The edge has already checked the actor. */
|
|
10
|
+
const anyone = () => true;
|
|
11
|
+
|
|
12
|
+
// An archived deal is hidden from every read and can no longer change.
|
|
13
|
+
const live = () => ({ archived: { eq: false } });
|
|
14
|
+
|
|
15
|
+
// A closed deal can no longer change either. Like an archived one, it
|
|
16
|
+
// answers update with NOT_FOUND. It closes through deals.close, which
|
|
17
|
+
// refuses a second close as AlreadyClosed.
|
|
18
|
+
const editable = () => ({
|
|
19
|
+
archived: { eq: false },
|
|
20
|
+
closedAt: { exists: false },
|
|
21
|
+
});
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
// examples/crm/src/servers/rpc/contract.ts
|
|
26
|
+
.collection(Deals, {
|
|
27
|
+
access: {
|
|
28
|
+
read: live,
|
|
29
|
+
create: anyone,
|
|
30
|
+
update: editable,
|
|
31
|
+
delete: live,
|
|
32
|
+
close: live,
|
|
33
|
+
},
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## How it works
|
|
37
|
+
|
|
38
|
+
- `access` has one function per action: `read` (find, count and get), `create`, `update`, `delete`, and one per method.
|
|
39
|
+
- Each function receives `{ actor }`, typed by the family's actor schema. `create` also receives `data`, its parsed input.
|
|
40
|
+
- `read`, `update`, `delete` and a method return `boolean` or a `Where` on the collection's documents, or a promise of one. `create` returns `boolean`.
|
|
41
|
+
- `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.
|
|
42
|
+
- It fails closed. A missing function denies, and `access: {}` denies everything. An override uses the function of the action it replaces.
|
|
43
|
+
- An access `Where` is ANDed with the caller's `where` and the tenant clause. A caller can only narrow it.
|
|
44
|
+
|
|
45
|
+
A filter on the actor narrows a global collection to the caller's organization, and lets support read every row:
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
// examples/crm/src/servers/rpc/contract.ts
|
|
49
|
+
.collection(Memberships, {
|
|
50
|
+
// A member reads the memberships of the organization it acts in: its
|
|
51
|
+
// team, for a team list or an owner picker. Support reads every one.
|
|
52
|
+
// An organization switcher uses /auth organizations instead, since /rpc
|
|
53
|
+
// needs an organization first. No create, update or delete: only
|
|
54
|
+
// trusted code writes them.
|
|
55
|
+
access: {
|
|
56
|
+
read: ({ actor }) =>
|
|
57
|
+
'support' in actor
|
|
58
|
+
? true
|
|
59
|
+
: { organizationId: { eq: actor.organizationId } },
|
|
60
|
+
},
|
|
61
|
+
})
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
A soft delete is a `read` filter, as `live` is above, with an override of `delete`. Read [override.md](override.md).
|
|
65
|
+
|
|
66
|
+
## In a hand-written use case
|
|
67
|
+
|
|
68
|
+
The family checks access before every `execute`: generated operations, overrides and methods. A hand-written use case gets the same filter with `ctx.access.scope(C, action)` and passes the `Scope` to every repo call:
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
// examples/crm/src/app/use-cases/deals/close-deal.ts
|
|
72
|
+
const scope = await ctx.access.scope(Deals, 'close');
|
|
73
|
+
const deal = await this.deps.deals.get(input.id, scope);
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
A deal outside the scope is `null` there, as it is `NOT_FOUND` to a client.
|
|
77
|
+
|
|
78
|
+
## Do not
|
|
79
|
+
|
|
80
|
+
- Do not load a document and then check the actor against it. Return a `Where` instead.
|
|
81
|
+
- Do not pass `unscoped` from a use case that acts for a caller. It skips access and tenancy.
|
|
82
|
+
- Do not put authentication in an access function. The edge proves the caller. Access sees the actor it built.
|
|
83
|
+
- Do not filter by a maskable field. A `Where` on `amount` reveals a bound on hidden values.
|
|
84
|
+
|
|
85
|
+
## Errors you will see
|
|
86
|
+
|
|
87
|
+
- A `Where` that names a field the collection lacks does not compile: TypeScript says the object is not assignable to `boolean | Where<...>`.
|
|
88
|
+
- A key that is not an action or a method fails `.collection()` with `'~error'`: `"publish" is not an action of deals`.
|
|
89
|
+
- A method with no access function fails with `deals.close has no access function; it is always FORBIDDEN`.
|
|
90
|
+
- At runtime, a refusal is `FORBIDDEN`, logged once, and a row outside the filter is `NOT_FOUND`.
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# CLI
|
|
2
|
+
|
|
3
|
+
`@latticecms/cli` gives the app the `lattice` command. It edits the app's own files where their shape gives one place for each edit, or writes nothing, exits 1, and prints the lines to add by hand.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install --save-dev @latticecms/cli
|
|
7
|
+
npx lattice --help
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Its paths come from the `"lattice"` key in the app's `package.json`, and default to the crm's layout. `tenant` has no default. The crm sets `"lattice": { "tenant": "organizationId" }`.
|
|
11
|
+
|
|
12
|
+
## lattice collection
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npx lattice collection deal_notes
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
- It writes the collection (a required `name`, its title field), a test, its `.collection()` registration in the composition, and its three events in the catalog. The test checks the registration and the schema, and builds nothing, so later refs, methods and overrides never break it.
|
|
19
|
+
- It needs the app's own `typescript`, 5.8 to 6. TypeScript 7 has no JavaScript API, and the CLI says to install `typescript@^6`.
|
|
20
|
+
- The registration's access is open to any signed-in caller, inside tenancy. Tighten it next. Read [access.md](access.md).
|
|
21
|
+
- `--tenant <field>` or `--global` overrides the config. `--label person,people` declares an irregular label. `--dry-run` prints a diff.
|
|
22
|
+
- It refuses a slug in use, a reserved name, a join collection's name, a name the files already declare, or a composition without exactly one exported `framework()` chain.
|
|
23
|
+
|
|
24
|
+
## lattice migration
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npx lattice migration add-notes-index
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
- It writes the next numbered migration, whose id comes from the list's ids, and appends it to the list in `src/infra/migrations/index.ts`.
|
|
31
|
+
- Its `up()` throws until it is written. Write it, then build. A migration that ran is recorded, and never runs again.
|
|
32
|
+
- `up({ db, session, signal, logger })` gets the raw database. Documents there have their stored shape, old fields included. That is why a migration does not use a repo.
|
|
33
|
+
- `--transaction` runs `up` and its record in one transaction, on a replica set.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
// examples/crm/src/infra/migrations/0001-backfill-deal-archived.ts
|
|
37
|
+
export default {
|
|
38
|
+
id: 1,
|
|
39
|
+
name: 'backfill-deal-archived',
|
|
40
|
+
async up({ db, logger }) {
|
|
41
|
+
const { modifiedCount } = await db
|
|
42
|
+
.collection('deals')
|
|
43
|
+
.updateMany(
|
|
44
|
+
{ archived: { $exists: false } },
|
|
45
|
+
{ $set: { archived: false } },
|
|
46
|
+
);
|
|
47
|
+
logger.info('deals backfilled', { modifiedCount });
|
|
48
|
+
},
|
|
49
|
+
} satisfies Migration;
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`up` must be safe to run again after it failed partway: the next run retries it. The filter above skips the deals already done.
|
|
53
|
+
|
|
54
|
+
## lattice migrate
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
npm run build && npx lattice migrate
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
It imports the built module `"lattice.migrate"` names, starts its store, runs store-mongo's `migrate()`, and stops the store. The crm's module:
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
// examples/crm/src/servers/scripts/migrate.ts
|
|
64
|
+
export const store = mongoStore(process.env);
|
|
65
|
+
export { migrations };
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
The crm also migrates at startup. Ordering, history and the lock are `migrate()`'s.
|
|
69
|
+
|
|
70
|
+
## When to edit by hand
|
|
71
|
+
|
|
72
|
+
- When the command refuses a shape and prints the lines, add them where it says.
|
|
73
|
+
- When a file is not in the crm's layout and the config cannot name it.
|
|
74
|
+
- Access, fields, methods, overrides and relations: the CLI scaffolds a collection, nothing more.
|
|
75
|
+
|
|
76
|
+
## Do not
|
|
77
|
+
|
|
78
|
+
- Do not number a migration by hand past a gap. `migrate()` refuses a gap or a duplicate id.
|
|
79
|
+
- Do not rename or remove a migration that ran. `migrate()` refuses the list.
|
|
80
|
+
- Do not leave a scaffolded collection's access open when the story needs less.
|
|
81
|
+
|
|
82
|
+
## Errors you will see
|
|
83
|
+
|
|
84
|
+
- Exit 1 with `lattice: <why>` and nothing written: a refusal. When the shape was the reason, the lines to add follow on stdout.
|
|
85
|
+
- Exit 2: a usage error or a bad `"lattice"` config, naming the key.
|
|
86
|
+
- `Migration 2 add-notes-index is not written yet: write up() before running it.`, from a stub that was built and run.
|
|
87
|
+
- `Migration ids must run 1, 2, 3 … in list order, with no gap`, from `migrate()`.
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# Collection
|
|
2
|
+
|
|
3
|
+
A collection is a slug and a `z.object()` schema. `collection(slug, options)` returns a declaration: no store, no actor, no use case. The framework compiles it.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
// examples/crm/src/domain/collections/companies.ts
|
|
7
|
+
import { collection } from '@latticecms/core';
|
|
8
|
+
import { z } from 'zod';
|
|
9
|
+
|
|
10
|
+
export const Companies = collection('companies', {
|
|
11
|
+
schema: z.object({
|
|
12
|
+
// The message is what a form shows at the field.
|
|
13
|
+
name: z.string().min(1, 'Enter a name'),
|
|
14
|
+
domain: z.string().optional(),
|
|
15
|
+
industry: z.string().optional(),
|
|
16
|
+
phone: z.string().optional(),
|
|
17
|
+
}),
|
|
18
|
+
// Each organization sees and changes only its own rows.
|
|
19
|
+
tenant: 'organizationId',
|
|
20
|
+
});
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Lattice adds `id`, `createdAt` and `updatedAt` to every document, and the tenant field to a tenanted one. Put one collection in one file under `domain/collections/`.
|
|
24
|
+
|
|
25
|
+
## How to write one
|
|
26
|
+
|
|
27
|
+
- The slug is lower snake case and plural: `deal_contacts`. It names the store collection, the contract slice and the events (`deals.created`).
|
|
28
|
+
- `tenant: 'organizationId'` makes the collection tenanted. Leave it out for a collection every tenant shares. Read [tenancy.md](tenancy.md).
|
|
29
|
+
- `label: { singular, plural }` says how the collection reads mid-sentence, in summaries and the admin. Without it, the label comes from the slug: `deal_stages` reads "deal stage". Declare it when the singular would be wrong, as for `people`.
|
|
30
|
+
- `indexes` lists the indexes `build().ensure()` creates. Name fields as stored, system and tenant fields included. A tenanted index leads with the tenant field. Lattice adds one per ref; declare the rest.
|
|
31
|
+
- The admin titles a document by its first required, unmasked string field named `name`, `title`, `label` or `email`, in lists and pickers.
|
|
32
|
+
- `.hooks({ beforeChange, afterRead })` transforms data and nothing else.
|
|
33
|
+
- Make a field `.optional()` when a user may clear it. Generated update takes `null` to clear it, and the admin sends `null` when the field is emptied. A required or defaulted field cannot be cleared.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
// examples/crm/src/domain/collections/deals.ts
|
|
37
|
+
// The pipeline view: one organization's deals in a stage, newest first.
|
|
38
|
+
indexes: [{ fields: { organizationId: 1, stage: 1, createdAt: -1 } }],
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
// examples/crm/src/domain/collections/memberships.ts
|
|
43
|
+
// The edge's lookup, and one membership per pair.
|
|
44
|
+
indexes: [{ fields: { userId: 1, organizationId: 1 }, unique: true }],
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
A hook normalizes what the store keeps:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
// examples/crm/src/domain/collections/contacts.ts
|
|
51
|
+
}).hooks({
|
|
52
|
+
// One spelling per address, so a where on email finds it.
|
|
53
|
+
beforeChange: ({ data }) => ({ ...data, email: data.email.toLowerCase() }),
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Registering it
|
|
58
|
+
|
|
59
|
+
A new collection is three edits besides its file: an import and `.collection(C, { access })` in the composition, and its three events in the app's catalog. `lattice collection <slug>` makes all three, with a test. Read [cli.md](cli.md).
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
// examples/crm/src/domain/events/domain-events.ts
|
|
63
|
+
companiesCreated: Companies.events.created,
|
|
64
|
+
companiesUpdated: Companies.events.updated,
|
|
65
|
+
companiesDeleted: Companies.events.deleted,
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
A collection missing from the catalog fails to compile at `build()`: the publisher does not take its events.
|
|
69
|
+
|
|
70
|
+
## Do not
|
|
71
|
+
|
|
72
|
+
- Do not store a `z.date()` or use a transform. Store ISO strings (`z.iso.datetime()`), and normalize in `beforeChange`.
|
|
73
|
+
- Do not name a field `id`, `createdAt`, `updatedAt`, `and` or `or`, or the tenant field. Core lists them in `reservedFields`.
|
|
74
|
+
- Do not name a field with a `.`, a leading `$`, or `_id`. MongoDB would read it as a path, an operator or the id.
|
|
75
|
+
- Do not name a slug `use`, `router`, `middleware`, `useAfter` or `$context`. Core lists them in `reservedNames`.
|
|
76
|
+
- Do not put rules in a hook. A rule that refuses a write belongs in an override.
|
|
77
|
+
|
|
78
|
+
## Errors you will see
|
|
79
|
+
|
|
80
|
+
A wrong option is a compile error on `collection()`. TypeScript reports a missing `'~error'` property, and its type is the reason:
|
|
81
|
+
|
|
82
|
+
```text
|
|
83
|
+
Property ''~error'' is missing in type '{ schema: ...; tenant: "organizationId"; }' but required in type '{ readonly '~error': "tenant \"organizationId\" is stamped by Lattice; it cannot be a schema field, a reserved name or an invalid field name"; }'.
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
The same checks throw at runtime, with `Lattice:` and the same words:
|
|
87
|
+
|
|
88
|
+
- `"createdAt" is a reserved field name`
|
|
89
|
+
- `"closedAt" is a Date; store an ISO string (z.iso.datetime())`
|
|
90
|
+
- `"<path>" has a transform; use a beforeChange hook`
|
|
91
|
+
- `an index on "deals" names "stag", which is not a field`
|
|
92
|
+
- `"router" is a ts-pf implementer key`, and `"deals" is already a collection`, at `.collection()`
|
|
93
|
+
|
|
94
|
+
A catalog that lacks the collection fails `build()` to compile: `'~error'` reads `the events publisher does not take "notes.created"`.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Event handler
|
|
2
|
+
|
|
3
|
+
Generated writes publish the collection's events: `Deals.events.created`, `.updated` and `.deleted`, with tokens `deals.created` and so on. Payloads are `{ doc, actorId }`, plus `previous` on update and `tenantId` on a tenanted collection. Overrides and methods publish their own events. Work that follows an event is a hexok `EventHandler`.
|
|
4
|
+
|
|
5
|
+
Read hexok's skill (`references/event-handler.md`) for the primitive. This file covers what Lattice adds.
|
|
6
|
+
|
|
7
|
+
## The catalog
|
|
8
|
+
|
|
9
|
+
The app lists every collection's events in its one catalog, next to its own:
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
// examples/crm/src/domain/events/domain-events.ts
|
|
13
|
+
dealContactsCreated: Deals.relations.contacts.through.events.created,
|
|
14
|
+
dealContactsUpdated: Deals.relations.contacts.through.events.updated,
|
|
15
|
+
dealContactsDeleted: Deals.relations.contacts.through.events.deleted,
|
|
16
|
+
dealClosed: DealClosedEvent,
|
|
17
|
+
}) {}
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
`build({ events })` takes the app's publisher. It must take every collection's events, or `build()` does not compile.
|
|
21
|
+
|
|
22
|
+
## A handler is system code
|
|
23
|
+
|
|
24
|
+
A handler acts for no caller. It reads inside the event's own tenant with `tenancy.scope`, never with an actor's access. The crm's handlers follow `DealClosedEvent`, which `deals.close` publishes with its tenant:
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
// examples/crm/src/app/event-handlers/deal-closed-webhook.ts
|
|
28
|
+
export class SendDealClosedWebhook extends EventHandler(
|
|
29
|
+
'deals.send-closed-webhook',
|
|
30
|
+
DealClosedEvent,
|
|
31
|
+
) {
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
// examples/crm/src/app/event-handlers/deal-closed-webhook.ts
|
|
36
|
+
async handle(event: DealClosedEvent): Promise<void> {
|
|
37
|
+
const { dealId, outcome, tenantId } = event.payload;
|
|
38
|
+
const deal = await this.deps.deals.get(
|
|
39
|
+
dealId,
|
|
40
|
+
tenancy.scope(Deals, tenantId),
|
|
41
|
+
);
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The crm has no handler on a collection event. One is written the same way: `EventHandler(token, Deals.events.updated)`, with `event.payload.tenantId` for its scope and `event.payload.doc` for the stored document.
|
|
45
|
+
|
|
46
|
+
## What leaves the product
|
|
47
|
+
|
|
48
|
+
A collection event stays inside the product. Another product or a customer gets a mapping of its own, made in a handler:
|
|
49
|
+
|
|
50
|
+
- an integration event, through `@hexok/integration-events`, with a versioned contract;
|
|
51
|
+
- a webhook, through `@hexok/webhooks`, with its own catalog.
|
|
52
|
+
|
|
53
|
+
The mapping copies field by field, so a new internal field reaches no one outside:
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
// examples/crm/src/app/event-handlers/deal-closed-webhook.ts
|
|
57
|
+
export function dealClosedWebhook(
|
|
58
|
+
deal: Doc<typeof Deals>,
|
|
59
|
+
outcome: 'won' | 'lost',
|
|
60
|
+
closedAt: string,
|
|
61
|
+
): DealClosedWebhook['payload'] {
|
|
62
|
+
return {
|
|
63
|
+
dealId: deal.id,
|
|
64
|
+
companyId: deal.companyId,
|
|
65
|
+
title: deal.title,
|
|
66
|
+
outcome,
|
|
67
|
+
closedAt,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Events carry whole documents, masked fields included. The mapping decides what leaves. The crm's webhook leaves out `amount`; its integration event carries it, inside the company.
|
|
73
|
+
|
|
74
|
+
Each handler subscribes in the worker in its own consumer group. Delivery is at least once: use a stable id, such as `deal.closed:<id>`, so a consumer dedupes. The crm's worker is `src/servers/worker/`; core's README section "A worker: webhooks and integration events" walks it.
|
|
75
|
+
|
|
76
|
+
## Do not
|
|
77
|
+
|
|
78
|
+
- Do not send a collection event to another product or a customer. Map it.
|
|
79
|
+
- Do not read with `unscoped` in a handler. Use `tenancy.scope(C, event.payload.tenantId)`.
|
|
80
|
+
- Do not block a write in a handler. A rule that refuses a write belongs in an override.
|
|
81
|
+
- Do not subscribe by pattern. A handler names its event class.
|
|
82
|
+
- Do not expect read events. Reads publish nothing.
|
|
83
|
+
|
|
84
|
+
## Errors you will see
|
|
85
|
+
|
|
86
|
+
- `build()` does not compile when the publisher refuses an event: `'~error'` reads `the events publisher does not take "deals.created"`.
|
|
87
|
+
- `tenancy.scope` takes only a tenanted collection. A global one is a type error, and throws `"organizations" has no tenant field`.
|
|
88
|
+
- A publish failure after a generated write reaches the caller, and the write stays. There is no outbox yet.
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# Masking
|
|
2
|
+
|
|
3
|
+
Masking withholds a field from a caller whose rule says no. The collection names the fields that may be withheld. Composition says who may read each one.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
// examples/crm/src/domain/collections/deals.ts
|
|
7
|
+
// Only managers and support see amounts: the contract's fields rule.
|
|
8
|
+
maskable: ['amount'],
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
// examples/crm/src/servers/rpc/contract.ts
|
|
13
|
+
// A member sees every deal of the organization, without its amount.
|
|
14
|
+
fields: {
|
|
15
|
+
amount: {
|
|
16
|
+
read: ({ actor }) => 'support' in actor || actor.role === 'manager',
|
|
17
|
+
},
|
|
18
|
+
},
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## How it works
|
|
22
|
+
|
|
23
|
+
- `fields` is required exactly when the collection has maskable fields, with one rule per field. A rule receives `{ actor }`, is asked once per call, and returns `boolean` or a promise of one.
|
|
24
|
+
- A withheld field is absent from what a client receives: generated reads and writes, a relation's `list`, populated documents, overrides and methods. Masking happens in the router, on every client path: HTTP, `createLocalClient` and MCP.
|
|
25
|
+
- A client's type has the field optional for every caller: `deal.amount` is `number | undefined`. `ClientDoc<C>` names that document. `Doc<C>` stays whole.
|
|
26
|
+
- A `where` or `sort` on a field the caller may not read is `VALIDATION`, at any depth. No filter, count, order or cursor reveals it.
|
|
27
|
+
- An `update` that names a field the caller may not read, with a value or `null`, is `VALIDATION` at its path, overrides included. The caller cannot see what it would destroy. `create` still takes the field: a member creates a deal with its amount.
|
|
28
|
+
- Server code sees whole documents: repos, direct `useCases` calls and events' `doc`. A webhook or integration event maps the document field by field and decides what leaves.
|
|
29
|
+
|
|
30
|
+
A method that returns the collection's documents declares `output: Deals.clientOutput`, or a schema built from it:
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
// examples/crm/src/app/use-cases/deals/close-deal.ts
|
|
34
|
+
// As a client receives a deal: the amount is withheld from a member.
|
|
35
|
+
output: Deals.clientOutput,
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The crm checks it over HTTP:
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
// examples/crm/src/servers/http/masking.test.ts
|
|
42
|
+
for (const input of [
|
|
43
|
+
{ where: { amount: { gt: 1000 } } },
|
|
44
|
+
{ sort: ['-amount'] },
|
|
45
|
+
]) {
|
|
46
|
+
expect(await rpc('ann', 'deals/find', input)).toMatchObject({
|
|
47
|
+
ok: false,
|
|
48
|
+
error: { code: 'VALIDATION' },
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Do not
|
|
54
|
+
|
|
55
|
+
These reveal a masked field, and masking does not catch them:
|
|
56
|
+
|
|
57
|
+
- Do not refine an object across a maskable field. Its failure depends on the hidden value.
|
|
58
|
+
- Do not filter access by a maskable field. The rows that exist reveal a bound.
|
|
59
|
+
- Do not derive another field from a masked one, in `afterRead` or a method's output.
|
|
60
|
+
- Do not return `Deals.output` from a method. Its maskable field is required, and build refuses it.
|
|
61
|
+
- Do not mask by deleting the field in a use case. Name it `maskable` and give it a rule.
|
|
62
|
+
|
|
63
|
+
A rule sees the actor, not the row.
|
|
64
|
+
|
|
65
|
+
## Errors you will see
|
|
66
|
+
|
|
67
|
+
- A collection with a maskable field and no `fields` rule fails `.collection()`, and throws `deals needs exactly one fields rule for each maskable field (amount); it has none`.
|
|
68
|
+
- `maskable "amout" is not a field of deals, or is named twice`.
|
|
69
|
+
- `deals.companyId is a ref; it cannot be maskable`, and `deals.amount is maskable, so it cannot be in a unique index: a CONFLICT would reveal its value`.
|
|
70
|
+
- A method output that holds a maskable field as required, or that Lattice cannot see through (`z.lazy()`, a transform, `z.custom()`, `z.unknown()`), throws at `build()`: `the output of "deals.close" ...`.
|
|
71
|
+
- At runtime, a query on an unreadable field is `VALIDATION`, with the message `"amount" is not readable` at its path.
|
|
72
|
+
- An update of an unreadable field is `VALIDATION`, with `"amount" is not readable, so it cannot be changed` at its path. A form for that caller leaves the field out.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Method
|
|
2
|
+
|
|
3
|
+
A method is a procedure of the collection's own: an action the generated operations do not have, such as closing a deal. It is a hand-written use case in the app's family, with its own input and output, and a `summary` and `effect` that describe it to MCP, OpenAPI and the admin.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
// examples/crm/src/app/use-cases/deals/close-deal.ts
|
|
7
|
+
/** Wins or loses a deal, once, and publishes DealClosed. */
|
|
8
|
+
export class CloseDeal extends AppUseCase('deals.close', {
|
|
9
|
+
collection: Deals,
|
|
10
|
+
input: z.object({ id: z.string(), outcome: z.enum(['won', 'lost']) }),
|
|
11
|
+
// As a client receives a deal: the amount is withheld from a member.
|
|
12
|
+
output: Deals.clientOutput,
|
|
13
|
+
// What MCP tells a model, and the admin shows for the action.
|
|
14
|
+
summary:
|
|
15
|
+
'Close a deal as won or lost, by its id. A deal closes once; closing it again is AlreadyClosed.',
|
|
16
|
+
effect: 'write',
|
|
17
|
+
}) {
|
|
18
|
+
constructor(
|
|
19
|
+
private readonly deps: {
|
|
20
|
+
deals: Repo<typeof Deals>;
|
|
21
|
+
events: DomainEventPublisher;
|
|
22
|
+
},
|
|
23
|
+
) {
|
|
24
|
+
super();
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## How to write one
|
|
29
|
+
|
|
30
|
+
- The token is `<slug>.<name>`. The name is not a generated operation, `read`, a relation, a ts-pf implementer key, or dotted.
|
|
31
|
+
- `input` and `output` are Zod schemas. A method that returns the collection's documents uses `C.clientOutput`, so masking applies. Read [masking.md](masking.md).
|
|
32
|
+
- `summary` is one sentence on what it does. `effect` is `read`, `write` or `destructive`. MCP turns them into the tool's description and hints, and the admin shows the method as an action: a document action when its input has `id`.
|
|
33
|
+
- Access has a function named after the method. The use case asks for its scope with that name:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
// examples/crm/src/app/use-cases/deals/close-deal.ts
|
|
37
|
+
const scope = await ctx.access.scope(Deals, 'close');
|
|
38
|
+
const deal = await this.deps.deals.get(input.id, scope);
|
|
39
|
+
if (deal === null) throw notFound(input.id);
|
|
40
|
+
if (deal.closedAt !== undefined) {
|
|
41
|
+
throw DomainError.AlreadyClosed({ id: input.id });
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
- A domain refusal, such as `AlreadyClosed`, is a member of the app's `Errors` catalog. The app declares it in `framework({ errors: { declared, map } })`, so a client narrows on its code and data.
|
|
46
|
+
- A method publishes its own events: a hexok `Event` the app adds to its catalog, with the tenant in its payload.
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
// examples/crm/src/app/use-cases/deals/close-deal.ts
|
|
50
|
+
await this.deps.events.publish(
|
|
51
|
+
new DealClosedEvent({
|
|
52
|
+
dealId: closed.id,
|
|
53
|
+
outcome: input.outcome,
|
|
54
|
+
actorId: AppUseCase.actorId(ctx.actor),
|
|
55
|
+
// The deal's own tenant: a support actor cannot write, so it never
|
|
56
|
+
// reaches this line.
|
|
57
|
+
tenantId: closed.organizationId,
|
|
58
|
+
}),
|
|
59
|
+
);
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Register it with its access, and build it from the repos:
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
// examples/crm/src/servers/app.ts
|
|
66
|
+
methods: ({ repos }) => ({
|
|
67
|
+
deals: { close: new CloseDeal({ deals: repos.deals, events }) },
|
|
68
|
+
activities: {
|
|
69
|
+
log: new LogActivity({ activities: repos.activities, events }),
|
|
70
|
+
},
|
|
71
|
+
}),
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
A client calls it like a generated procedure, with no annotations: `local.deals.close({ id, outcome: 'won' })`.
|
|
75
|
+
|
|
76
|
+
## Do not
|
|
77
|
+
|
|
78
|
+
- Do not add a method for what an override does. A different delete is an override of `delete`.
|
|
79
|
+
- Do not return `Deals.output`. Return `Deals.clientOutput`.
|
|
80
|
+
- Do not check the actor's role inside `execute`. Put it in the method's access function.
|
|
81
|
+
- Do not write a free-standing ts-pf procedure beside the framework. A method is the collection's procedure.
|
|
82
|
+
|
|
83
|
+
## Errors you will see
|
|
84
|
+
|
|
85
|
+
- A method without `summary` and `effect` fails `.collection()` with `'~error'`: `method "close" needs a summary and an effect: what it does, and whether it reads, writes or is destructive`. A blank `summary` throws at runtime.
|
|
86
|
+
- `"find" is a generated operation, an access key, a relation, a ts-pf implementer key, or has a dot`, for a bad name.
|
|
87
|
+
- `deals.close has no access function; it is always FORBIDDEN`, when access lacks the method.
|
|
88
|
+
- `Lattice: the output of "deals.close" ...` at `build()`, for an output that requires a maskable field.
|