@latticecms/core 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +1174 -2
  2. package/dist/access.d.ts +210 -0
  3. package/dist/access.d.ts.map +1 -0
  4. package/dist/access.js +225 -0
  5. package/dist/access.js.map +1 -0
  6. package/dist/build.d.ts +507 -0
  7. package/dist/build.d.ts.map +1 -0
  8. package/dist/build.js +598 -0
  9. package/dist/build.js.map +1 -0
  10. package/dist/collection.d.ts +480 -0
  11. package/dist/collection.d.ts.map +1 -0
  12. package/dist/collection.js +344 -0
  13. package/dist/collection.js.map +1 -0
  14. package/dist/crud.d.ts +30 -0
  15. package/dist/crud.d.ts.map +1 -0
  16. package/dist/crud.js +539 -0
  17. package/dist/crud.js.map +1 -0
  18. package/dist/describe.d.ts +89 -0
  19. package/dist/describe.d.ts.map +1 -0
  20. package/dist/describe.js +119 -0
  21. package/dist/describe.js.map +1 -0
  22. package/dist/errors.d.ts +179 -0
  23. package/dist/errors.d.ts.map +1 -0
  24. package/dist/errors.js +146 -0
  25. package/dist/errors.js.map +1 -0
  26. package/dist/family.d.ts +80 -0
  27. package/dist/family.d.ts.map +1 -0
  28. package/dist/family.js +231 -0
  29. package/dist/family.js.map +1 -0
  30. package/dist/index.d.ts +14 -0
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.js +10 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/marker.d.ts +15 -0
  35. package/dist/marker.d.ts.map +1 -0
  36. package/dist/marker.js +28 -0
  37. package/dist/marker.js.map +1 -0
  38. package/dist/mask.d.ts +69 -0
  39. package/dist/mask.d.ts.map +1 -0
  40. package/dist/mask.js +255 -0
  41. package/dist/mask.js.map +1 -0
  42. package/dist/populate.d.ts +32 -0
  43. package/dist/populate.d.ts.map +1 -0
  44. package/dist/populate.js +73 -0
  45. package/dist/populate.js.map +1 -0
  46. package/dist/relations.d.ts +143 -0
  47. package/dist/relations.d.ts.map +1 -0
  48. package/dist/relations.js +128 -0
  49. package/dist/relations.js.map +1 -0
  50. package/dist/repo.d.ts +99 -0
  51. package/dist/repo.d.ts.map +1 -0
  52. package/dist/repo.js +83 -0
  53. package/dist/repo.js.map +1 -0
  54. package/dist/sort.d.ts +61 -0
  55. package/dist/sort.d.ts.map +1 -0
  56. package/dist/sort.js +145 -0
  57. package/dist/sort.js.map +1 -0
  58. package/dist/store/conformance.d.ts +15 -0
  59. package/dist/store/conformance.d.ts.map +1 -0
  60. package/dist/store/conformance.js +683 -0
  61. package/dist/store/conformance.js.map +1 -0
  62. package/dist/store/index.d.ts +9 -0
  63. package/dist/store/index.d.ts.map +1 -0
  64. package/dist/store/index.js +8 -0
  65. package/dist/store/index.js.map +1 -0
  66. package/dist/store.d.ts +113 -0
  67. package/dist/store.d.ts.map +1 -0
  68. package/dist/store.js +176 -0
  69. package/dist/store.js.map +1 -0
  70. package/dist/tenancy.d.ts +66 -0
  71. package/dist/tenancy.d.ts.map +1 -0
  72. package/dist/tenancy.js +69 -0
  73. package/dist/tenancy.js.map +1 -0
  74. package/dist/tracing.d.ts +12 -0
  75. package/dist/tracing.d.ts.map +1 -0
  76. package/dist/tracing.js +27 -0
  77. package/dist/tracing.js.map +1 -0
  78. package/dist/where.d.ts +95 -0
  79. package/dist/where.d.ts.map +1 -0
  80. package/dist/where.js +308 -0
  81. package/dist/where.js.map +1 -0
  82. package/package.json +79 -2
  83. package/skills/lattice/SKILL.md +106 -0
  84. package/skills/lattice/references/access.md +76 -0
  85. package/skills/lattice/references/cli.md +87 -0
  86. package/skills/lattice/references/collection.md +91 -0
  87. package/skills/lattice/references/event-handler.md +88 -0
  88. package/skills/lattice/references/masking.md +72 -0
  89. package/skills/lattice/references/method.md +85 -0
  90. package/skills/lattice/references/override.md +77 -0
  91. package/skills/lattice/references/relations.md +90 -0
  92. package/skills/lattice/references/tenancy.md +82 -0
  93. package/skills/lattice/references/testing.md +75 -0
  94. package/src/access.ts +429 -0
  95. package/src/build.ts +1722 -0
  96. package/src/collection.ts +1018 -0
  97. package/src/crud.ts +795 -0
  98. package/src/describe.ts +232 -0
  99. package/src/errors.ts +170 -0
  100. package/src/family.ts +334 -0
  101. package/src/index.ts +42 -0
  102. package/src/marker.ts +54 -0
  103. package/src/mask.ts +307 -0
  104. package/src/populate.ts +96 -0
  105. package/src/relations.ts +353 -0
  106. package/src/repo.ts +209 -0
  107. package/src/sort.ts +214 -0
  108. package/src/store/conformance.ts +1007 -0
  109. package/src/store/index.ts +16 -0
  110. package/src/store.ts +309 -0
  111. package/src/tenancy.ts +124 -0
  112. package/src/tracing.ts +29 -0
  113. package/src/where.ts +463 -0
package/dist/family.js ADDED
@@ -0,0 +1,231 @@
1
+ import { SpanKind } from '@opentelemetry/api';
2
+ import { UseCase } from 'hexok';
3
+ import { z } from 'zod';
4
+ import { CallAccess } from './access.js';
5
+ import { invalid, LatticeError, refusal } from './errors.js';
6
+ import { withheldPaths, withheldWrites } from './mask.js';
7
+ import { tenancy } from './tenancy.js';
8
+ import { failed, tracer } from './tracing.js';
9
+ /**
10
+ * The fields that say who made a call, for its log lines: the actor's id,
11
+ * and its tenant id or `tenancy: 'bypass'`.
12
+ */
13
+ export function callerFields(family, actor) {
14
+ const actorId = family.actorId(actor);
15
+ const tenant = family.tenantOf?.(actor);
16
+ if (tenant === undefined)
17
+ return { actorId };
18
+ if (tenant === tenancy.bypass)
19
+ return { actorId, tenancy: 'bypass' };
20
+ return { actorId, tenantId: tenant };
21
+ }
22
+ /**
23
+ * The errors a family has logged, its guards' rejections and what `onCatch`
24
+ * saw, with how. The procedure middleware skips both outcomes; the edge's
25
+ * `onError` skips only failures, so a refusal the client sees as INTERNAL
26
+ * still reaches it. A WeakMap keeps the error object as it is and holds it
27
+ * no longer than the caller.
28
+ */
29
+ const logged = new WeakMap();
30
+ /** How a family logged `error`, or undefined when no family did. */
31
+ export function loggedByFamily(error) {
32
+ return typeof error === 'object' && error !== null
33
+ ? logged.get(error)
34
+ : undefined;
35
+ }
36
+ /** The action of `token`: a generated operation's or a method's name. */
37
+ function actionOf(spec, token) {
38
+ const { slug } = spec.collection;
39
+ return token.startsWith(`${slug}.`) ? token.slice(slug.length + 1) : token;
40
+ }
41
+ /**
42
+ * The logger of one call: `ctx.logger` with the call's collection, action
43
+ * and, once the actor has parsed, its id and tenant. Every family log line
44
+ * goes through it, so the fields cannot drift.
45
+ */
46
+ function callLogger(logger, spec, token, caller) {
47
+ return logger.child({
48
+ collection: spec.collection.slug,
49
+ action: actionOf(spec, token),
50
+ ...caller,
51
+ });
52
+ }
53
+ /**
54
+ * Logs a thrown value once and records it: info for a refusal, error for
55
+ * anything else. Returns it, so a guard can throw it.
56
+ */
57
+ function logThrown(log, token, error, durationMs) {
58
+ const timing = durationMs === undefined ? {} : { durationMs };
59
+ const refused = refusal(error);
60
+ if (refused !== undefined) {
61
+ log.info(token, { outcome: 'refused', ...refused, ...timing });
62
+ }
63
+ else if (error instanceof Error) {
64
+ log.error(error, { outcome: 'failed', ...timing });
65
+ }
66
+ else {
67
+ log.error(token, { outcome: 'failed', thrown: error, ...timing });
68
+ }
69
+ if (typeof error === 'object' && error !== null) {
70
+ logged.set(error, refused === undefined ? 'failed' : 'refused');
71
+ }
72
+ return error;
73
+ }
74
+ /**
75
+ * Builds the app's one use case family on hexok `UseCase.context`. Before
76
+ * any member's `execute` runs, the actor must parse against `actor`, the
77
+ * input against the member's `input` static, and `ctx.access` must allow
78
+ * the member's action. Each call writes one line
79
+ * through a child of `ctx.logger`: info when it returns or a guard or
80
+ * `execute` refuses it, error when it throws anything else.
81
+ */
82
+ export function family(options) {
83
+ const caller = (actor) => callerFields({ actorId: options.actorId, tenantOf: options.tenantOf }, actor);
84
+ const factory = UseCase.context()
85
+ // Guards run outside hexok's hooks, so each logs its own rejection.
86
+ .guard(({ ctx, spec, token }) => {
87
+ // The call's context parsed the actor once (familyContext), so this
88
+ // guard reads that parse rather than repeating it. The issues describe
89
+ // the caller's credentials, so they stay out of the error and the log.
90
+ if (!CallAccess.parsed(ctx.access, ctx.actor)) {
91
+ const log = callLogger(ctx.logger, spec, token, undefined);
92
+ throw logThrown(log, token, LatticeError.UNAUTHORIZED());
93
+ }
94
+ })
95
+ .guard(({ ctx, spec, token, input }) => {
96
+ // hexok hands execute the caller's input, not the parsed value. So a
97
+ // method's input schema uses no defaults or transforms; a generated use
98
+ // case parses its own input inside execute to strip unknown keys and
99
+ // apply defaults.
100
+ if (spec.input === undefined)
101
+ return;
102
+ const result = z.safeParse(spec.input, input);
103
+ if (!result.success) {
104
+ const log = callLogger(ctx.logger, spec, token, caller(ctx.actor));
105
+ throw logThrown(log, token, invalid(result.error.issues));
106
+ }
107
+ })
108
+ // Access, after the actor and the input are known good. Generated
109
+ // operations, overrides and methods all pass here, so none can skip the
110
+ // FORBIDDEN check. The answer stays on ctx.access for execute's scope.
111
+ .guard(async ({ ctx, spec, token, input }) => {
112
+ const action = actionOf(spec, token);
113
+ // Create's function receives the parsed input, as execute will see it.
114
+ const data = action !== 'create'
115
+ ? undefined
116
+ : spec.input === undefined
117
+ ? input
118
+ : z.parse(spec.input, input);
119
+ try {
120
+ await ctx.access.scope(spec.collection, action, data);
121
+ }
122
+ catch (error) {
123
+ const log = callLogger(ctx.logger, spec, token, caller(ctx.actor));
124
+ throw logThrown(log, token, error);
125
+ }
126
+ })
127
+ // A where or a sort on a field the caller's rules withhold would reveal
128
+ // it through which rows match or their order, and an update would change
129
+ // a value the caller cannot see (0035), so each is refused, on every
130
+ // path. Output masking happens where a client receives the result.
131
+ .guard(async ({ ctx, spec, token, input }) => {
132
+ const action = actionOf(spec, token);
133
+ if (action !== 'find' && action !== 'count' && action !== 'update') {
134
+ return;
135
+ }
136
+ const withheld = await CallAccess.withheld(ctx.access, spec.collection);
137
+ if (withheld.size === 0)
138
+ return;
139
+ const issues = action === 'update'
140
+ ? withheldWrites(input, withheld)
141
+ : withheldPaths(input, withheld);
142
+ if (issues.length > 0) {
143
+ const log = callLogger(ctx.logger, spec, token, caller(ctx.actor));
144
+ throw logThrown(log, token, LatticeError.VALIDATION({ issues }));
145
+ }
146
+ })
147
+ .hooks({
148
+ preExecute: ({ ctx, spec, token }) => {
149
+ const fields = caller(ctx.actor);
150
+ return {
151
+ log: callLogger(ctx.logger, spec, token, fields),
152
+ started: performance.now(),
153
+ span: useCaseSpan(spec, token, fields),
154
+ };
155
+ },
156
+ // The span ends in postExecute and onCatch, beside the log line,
157
+ // rather than in its own onFinally: each hook is one more await on
158
+ // every call, traced or not.
159
+ postExecute: ({ token }, { log, started, span }) => {
160
+ log.info(token, { outcome: 'ok', durationMs: since(started) });
161
+ if (span.isRecording())
162
+ span.setAttribute('lattice.outcome', 'ok');
163
+ span.end();
164
+ },
165
+ onCatch: ({ ctx, spec, token, error }, state) => {
166
+ // State is undefined only when preExecute itself threw.
167
+ if (state === undefined) {
168
+ logThrown(callLogger(ctx.logger, spec, token, undefined), token, error);
169
+ }
170
+ else {
171
+ logThrown(state.log, token, error, since(state.started));
172
+ const refused = refusal(error);
173
+ if (refused === undefined) {
174
+ failed(state.span, error);
175
+ }
176
+ else if (state.span.isRecording()) {
177
+ // A refusal is not a failure: the status stays UNSET.
178
+ state.span.setAttributes({
179
+ 'lattice.outcome': 'refused',
180
+ 'lattice.code': String(refused.code),
181
+ });
182
+ }
183
+ state.span.end();
184
+ }
185
+ },
186
+ });
187
+ // The generated use cases and the procedure middleware read these, so the
188
+ // app states them once.
189
+ return Object.assign(factory, {
190
+ actor: options.actor,
191
+ actorId: options.actorId,
192
+ tenantOf: options.tenantOf,
193
+ });
194
+ }
195
+ /**
196
+ * The use case's span: a child of the active span, the procedure's or a
197
+ * direct caller's. hexok has no around hook, so this span cannot be made
198
+ * active for execute: the store calls execute makes are its siblings, not
199
+ * its children. Its attributes are set only when a span records, so
200
+ * without an SDK they cost nothing.
201
+ */
202
+ function useCaseSpan(spec, token, caller) {
203
+ const span = tracer.startSpan(token, { kind: SpanKind.INTERNAL });
204
+ if (span.isRecording())
205
+ span.setAttributes(spanFields(spec, token, caller));
206
+ return span;
207
+ }
208
+ /**
209
+ * A use case span's attributes: what ran and for whom, never its input or
210
+ * a document. The caller's fields are its log line's.
211
+ */
212
+ function spanFields(spec, token, caller) {
213
+ return {
214
+ 'lattice.use_case': token,
215
+ 'lattice.collection': spec.collection.slug,
216
+ 'lattice.action': actionOf(spec, token),
217
+ ...(caller.actorId === undefined
218
+ ? {}
219
+ : { 'lattice.actor_id': caller.actorId }),
220
+ ...(caller.tenantId === undefined
221
+ ? {}
222
+ : { 'lattice.tenant_id': caller.tenantId }),
223
+ ...(caller.tenancy === undefined
224
+ ? {}
225
+ : { 'lattice.tenancy': caller.tenancy }),
226
+ };
227
+ }
228
+ function since(started) {
229
+ return Math.round(performance.now() - started);
230
+ }
231
+ //# sourceMappingURL=family.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"family.js","sourceRoot":"","sources":["../src/family.ts"],"names":[],"mappings":"AACA,OAAO,EAA8B,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAE1E,OAAO,EAAyB,OAAO,EAAE,MAAM,OAAO,CAAC;AACvD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC1D,OAAO,EAAe,OAAO,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAmD9C;;;GAGG;AACH,MAAM,UAAU,YAAY,CAC1B,MAAmD,EACnD,KAAY;IAEZ,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACtC,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC,KA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CAAC,WAAW,EAAE;QAAE,IAAI,CAAC,aAAa,CAAC,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;IAC5E,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;GAGG;AACH,SAAS,UAAU,CACjB,IAAgB,EAChB,KAAa,EACb,MAAwC;IAExC,OAAO;QACL,kBAAkB,EAAE,KAAK;QACzB,oBAAoB,EAAE,IAAI,CAAC,UAAU,CAAC,IAAI;QAC1C,gBAAgB,EAAE,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC;QACvC,GAAG,CAAC,MAAM,CAAC,OAAO,KAAK,SAAS;YAC9B,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,EAAE,kBAAkB,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;QAC3C,GAAG,CAAC,MAAM,CAAC,QAAQ,KAAK,SAAS;YAC/B,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,EAAE,mBAAmB,EAAE,MAAM,CAAC,QAAQ,EAAE,CAAC;QAC7C,GAAG,CAAC,MAAM,CAAC,OAAO,KAAK,SAAS;YAC9B,CAAC,CAAC,EAAE;YACJ,CAAC,CAAC,EAAE,iBAAiB,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;KAC3C,CAAC;AACJ,CAAC;AAED,SAAS,KAAK,CAAC,OAAe;IAC5B,OAAO,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,OAAO,CAAC,CAAC;AACjD,CAAC"}
@@ -0,0 +1,14 @@
1
+ export { Access, type AccessRequest, type CallAccess, unscoped, } from './access.js';
2
+ export { type Contract, type Framework, framework, type ReadUseCase, reservedNames, } from './build.js';
3
+ export { type Collection, collection, type RelationsOf, reservedFields, } from './collection.js';
4
+ export { type LatticeMeta, labelOf } from './describe.js';
5
+ export { LatticeError } from './errors.js';
6
+ export { type CallContext, type Family, type FamilyContext, family, } from './family.js';
7
+ export type { Withheld } from './populate.js';
8
+ export { type JoinShape, type Many, type ManyOnDelete, many, type OnDelete, type Ref, ref, } from './relations.js';
9
+ export type { ClientDoc, Doc, Repo } from './repo.js';
10
+ export type { Sort } from './sort.js';
11
+ export { CollectionStore, MemoryStore } from './store.js';
12
+ export { type Scope, tenancy } from './tenancy.js';
13
+ export type { Where } from './where.js';
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,MAAM,EACN,KAAK,aAAa,EAClB,KAAK,UAAU,EACf,QAAQ,GACT,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,KAAK,QAAQ,EACb,KAAK,SAAS,EACd,SAAS,EACT,KAAK,WAAW,EAChB,aAAa,GACd,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,KAAK,UAAU,EACf,UAAU,EACV,KAAK,WAAW,EAChB,cAAc,GACf,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,KAAK,WAAW,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,MAAM,EACX,KAAK,aAAa,EAClB,MAAM,GACP,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,EACL,KAAK,SAAS,EACd,KAAK,IAAI,EACT,KAAK,YAAY,EACjB,IAAI,EACJ,KAAK,QAAQ,EACb,KAAK,GAAG,EACR,GAAG,GACJ,MAAM,gBAAgB,CAAC;AACxB,YAAY,EAAE,SAAS,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACtD,YAAY,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAE,KAAK,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACnD,YAAY,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ export { Access, unscoped, } from './access.js';
2
+ export { framework, reservedNames, } from './build.js';
3
+ export { collection, reservedFields, } from './collection.js';
4
+ export { labelOf } from './describe.js';
5
+ export { LatticeError } from './errors.js';
6
+ export { family, } from './family.js';
7
+ export { many, ref, } from './relations.js';
8
+ export { CollectionStore, MemoryStore } from './store.js';
9
+ export { tenancy } from './tenancy.js';
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,MAAM,EAGN,QAAQ,GACT,MAAM,aAAa,CAAC;AACrB,OAAO,EAGL,SAAS,EAET,aAAa,GACd,MAAM,YAAY,CAAC;AACpB,OAAO,EAEL,UAAU,EAEV,cAAc,GACf,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAoB,OAAO,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAIL,MAAM,GACP,MAAM,aAAa,CAAC;AAErB,OAAO,EAIL,IAAI,EAGJ,GAAG,GACJ,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAc,OAAO,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,15 @@
1
+ import { z } from 'zod';
2
+ /** A maskable field as the marker records it: its collection and name. */
3
+ export type Masked = {
4
+ readonly collection: string;
5
+ readonly field: string;
6
+ };
7
+ /** The field a schema node is marked as, or undefined. */
8
+ export declare function markOf(schema: z.core.$ZodType): Masked | undefined;
9
+ /**
10
+ * `schema` with the mask marker added: a clone, never the app's schema. The
11
+ * clone keeps the app's meta, such as a `title`, and adds
12
+ * `x-lattice-maskable`, so the field's JSON Schema says it may be withheld.
13
+ */
14
+ export declare function marked<T extends z.core.$ZodType>(schema: T, masked: Masked): T;
15
+ //# sourceMappingURL=marker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"marker.d.ts","sourceRoot":"","sources":["../src/marker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,0EAA0E;AAC1E,MAAM,MAAM,MAAM,GAAG;IAAE,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAiB7E,0DAA0D;AAC1D,wBAAgB,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,GAAG,MAAM,GAAG,SAAS,CAElE;AAED;;;;GAIG;AACH,wBAAgB,MAAM,CAAC,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,QAAQ,EAC9C,MAAM,EAAE,CAAC,EACT,MAAM,EAAE,MAAM,GACb,CAAC,CAoBH"}
package/dist/marker.js ADDED
@@ -0,0 +1,28 @@
1
+ import { z } from 'zod';
2
+ function isMaskMarker(check) {
3
+ return (typeof check === 'object' && check !== null && '~lattice-mask' in check);
4
+ }
5
+ /** The field a schema node is marked as, or undefined. */
6
+ export function markOf(schema) {
7
+ return (schema._zod.def.checks ?? []).find(isMaskMarker)?.['~lattice-mask'];
8
+ }
9
+ /**
10
+ * `schema` with the mask marker added: a clone, never the app's schema. The
11
+ * clone keeps the app's meta, such as a `title`, and adds
12
+ * `x-lattice-maskable`, so the field's JSON Schema says it may be withheld.
13
+ */
14
+ export function marked(schema, masked) {
15
+ const marker = Object.assign(z.check(() => { }), {
16
+ '~lattice-mask': masked,
17
+ });
18
+ const { def } = schema._zod;
19
+ // `parent` makes the clone inherit the schema's meta, as Zod's own
20
+ // methods do.
21
+ const clone = z.core.util.clone(schema, { ...def, checks: [...(def.checks ?? []), marker] }, { parent: true });
22
+ z.globalRegistry.add(clone, {
23
+ ...z.globalRegistry.get(clone),
24
+ 'x-lattice-maskable': true,
25
+ });
26
+ return clone;
27
+ }
28
+ //# sourceMappingURL=marker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"marker.js","sourceRoot":"","sources":["../src/marker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAcxB,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,eAAe,IAAI,KAAK,CACxE,CAAC;AACJ,CAAC;AAED,0DAA0D;AAC1D,MAAM,UAAU,MAAM,CAAC,MAAuB;IAC5C,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,EAAE,CAAC,eAAe,CAAC,CAAC;AAC9E,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,MAAM,CACpB,MAAS,EACT,MAAc;IAEd,MAAM,MAAM,GAAe,MAAM,CAAC,MAAM,CACtC,CAAC,CAAC,KAAK,CAAU,GAAG,EAAE,GAAE,CAAC,CAAC,EAC1B;QACE,eAAe,EAAE,MAAM;KACxB,CACF,CAAC;IACF,MAAM,EAAE,GAAG,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC;IAC5B,mEAAmE;IACnE,cAAc;IACd,MAAM,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAC7B,MAAM,EACN,EAAE,GAAG,GAAG,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,IAAI,EAAE,CAAC,EAAE,MAAM,CAAC,EAAE,EACnD,EAAE,MAAM,EAAE,IAAI,EAAE,CACjB,CAAC;IACF,CAAC,CAAC,cAAc,CAAC,GAAG,CAAC,KAAK,EAAE;QAC1B,GAAG,CAAC,CAAC,cAAc,CAAC,GAAG,CAAC,KAAK,CAAC;QAC9B,oBAAoB,EAAE,IAAI;KAC3B,CAAC,CAAC;IACH,OAAO,KAAK,CAAC;AACf,CAAC"}
package/dist/mask.d.ts ADDED
@@ -0,0 +1,69 @@
1
+ import { z } from 'zod';
2
+ import { type Masked } from './marker.js';
3
+ /** `Shape` with each maskable field optional, as a client may receive it. */
4
+ export type MaskShape<Shape extends z.core.$ZodShape, M extends string> = {
5
+ [K in keyof Shape]: K extends M ? z.ZodOptional<Shape[K]> : Shape[K];
6
+ };
7
+ /**
8
+ * The shapes a collection's outputs are built from: `stored`, with each
9
+ * maskable field marked, and `client`, with each marked and optional.
10
+ */
11
+ export declare function maskShapes<Shape extends z.core.$ZodShape, M extends string>(slug: string, shape: Shape, maskable: readonly M[]): {
12
+ readonly stored: Shape;
13
+ readonly client: MaskShape<Shape, M>;
14
+ };
15
+ /**
16
+ * Where in an output a withheld field is removed. Built once per procedure
17
+ * from its output schema; only the parts that hold a masked field.
18
+ */
19
+ export type MaskPlan = {
20
+ readonly kind: 'object';
21
+ readonly keys: ReadonlyMap<string, {
22
+ readonly masked?: Masked;
23
+ readonly child?: MaskPlan;
24
+ }>;
25
+ } | {
26
+ readonly kind: 'array';
27
+ readonly item: MaskPlan;
28
+ } | {
29
+ readonly kind: 'record';
30
+ readonly value: MaskPlan;
31
+ } | {
32
+ readonly kind: 'tuple';
33
+ readonly items: readonly (MaskPlan | undefined)[];
34
+ readonly rest: MaskPlan | undefined;
35
+ } | {
36
+ readonly kind: 'each';
37
+ readonly plans: readonly MaskPlan[];
38
+ };
39
+ /**
40
+ * The mask plan of an output schema, or undefined when nothing in it is
41
+ * masked. `where` names the procedure, for errors. It sees through objects,
42
+ * arrays, records, tuples, unions, intersections and the optional, nullable,
43
+ * default, readonly and catch wrappers. A schema it cannot see through
44
+ * throws, so no masked field can hide inside one. A masked field must be
45
+ * optional where it sits: a client may not receive it.
46
+ */
47
+ export declare function maskPlan(schema: z.core.$ZodType, where: string): MaskPlan | undefined;
48
+ /** The collections a plan masks fields of. */
49
+ export declare function maskedCollections(plan: MaskPlan): Set<string>;
50
+ /**
51
+ * `value` with each field `withheld` says to remove taken out, where `plan`
52
+ * puts one. It copies what it changes, so a document the use case still
53
+ * holds is not changed.
54
+ */
55
+ export declare function applyMask(plan: MaskPlan, value: unknown, withheld: (masked: Masked) => boolean): unknown;
56
+ /**
57
+ * The keys of an update's patch that name a withheld field, for VALIDATION
58
+ * issues (0035): a caller cannot change, or clear, what it cannot read.
59
+ */
60
+ export declare function withheldWrites(input: unknown, withheld: ReadonlySet<string>): {
61
+ path: (string | number)[];
62
+ message: string;
63
+ }[];
64
+ /** The where and sort paths that name a withheld field, for VALIDATION issues. */
65
+ export declare function withheldPaths(input: unknown, withheld: ReadonlySet<string>): {
66
+ path: (string | number)[];
67
+ message: string;
68
+ }[];
69
+ //# sourceMappingURL=mask.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mask.d.ts","sourceRoot":"","sources":["../src/mask.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,KAAK,MAAM,EAAkB,MAAM,aAAa,CAAC;AAG1D,6EAA6E;AAC7E,MAAM,MAAM,SAAS,CAAC,KAAK,SAAS,CAAC,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC,SAAS,MAAM,IAAI;KACvE,CAAC,IAAI,MAAM,KAAK,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC;CACrE,CAAC;AAEF;;;GAGG;AACH,wBAAgB,UAAU,CAAC,KAAK,SAAS,CAAC,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC,SAAS,MAAM,EACzE,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,KAAK,EACZ,QAAQ,EAAE,SAAS,CAAC,EAAE,GACrB;IAAE,QAAQ,C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Q,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,GACpC,OAAO,CA6CT;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,KAAK,EAAE,OAAO,EACd,QAAQ,EAAE,WAAW,CAAC,MAAM,CAAC,GAC5B;IAAE,IAAI,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,EAAE,CAQlD;AAED,kFAAkF;AAClF,wBAAgB,aAAa,CAC3B,KAAK,EAAE,OAAO,EACd,QAAQ,EAAE,WAAW,CAAC,MAAM,CAAC,GAC5B;IAAE,IAAI,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,EAAE,CA4BlD"}
package/dist/mask.js ADDED
@@ -0,0 +1,255 @@
1
+ import { z } from 'zod';
2
+ import { marked, markOf } from './marker.js';
3
+ import { innerOf } from './where.js';
4
+ export function maskShapes(slug, shape, maskable) {
5
+ const stored = { ...shape };
6
+ const client = { ...shape };
7
+ for (const field of maskable) {
8
+ const schema = shape[field];
9
+ if (schema === undefined)
10
+ continue;
11
+ const mark = marked(schema, { collection: slug, field });
12
+ stored[field] = mark;
13
+ // The description reaches JSON Schema, so OpenAPI and MCP say why.
14
+ client[field] = z
15
+ .optional(mark)
16
+ .describe('Withheld when the caller may not read it.');
17
+ }
18
+ return { stored, client };
19
+ }
20
+ /** The name of a schema kind Lattice cannot see through, or undefined. */
21
+ function opaque(schema) {
22
+ if (schema instanceof z.core.$ZodLazy)
23
+ return 'z.lazy()';
24
+ if (schema instanceof z.core.$ZodPipe)
25
+ return 'a pipe or transform';
26
+ if (schema instanceof z.core.$ZodTransform)
27
+ return 'a transform';
28
+ if (schema instanceof z.core.$ZodCustom)
29
+ return 'z.custom()';
30
+ if (schema instanceof z.core.$ZodAny)
31
+ return 'z.any()';
32
+ if (schema instanceof z.core.$ZodUnknown)
33
+ return 'z.unknown()';
34
+ if (schema instanceof z.core.$ZodPromise)
35
+ return 'z.promise()';
36
+ return undefined;
37
+ }
38
+ /**
39
+ * The mask plan of an output schema, or undefined when nothing in it is
40
+ * masked. `where` names the procedure, for errors. It sees through objects,
41
+ * arrays, records, tuples, unions, intersections and the optional, nullable,
42
+ * default, readonly and catch wrappers. A schema it cannot see through
43
+ * throws, so no masked field can hide inside one. A masked field must be
44
+ * optional where it sits: a client may not receive it.
45
+ */
46
+ export function maskPlan(schema, where) {
47
+ const fail = (message) => {
48
+ throw new Error(`Lattice: the output of "${where}" ${message}`);
49
+ };
50
+ const visit = (node) => {
51
+ const mark = markOf(node);
52
+ if (mark !== undefined) {
53
+ fail(`holds ${mark.collection}.${mark.field} where it is required; declare it optional: use the collection's clientOutput`);
54
+ }
55
+ const kind = opaque(node);
56
+ if (kind !== undefined) {
57
+ fail(`has ${kind}, which Lattice cannot see through to mask a field; declare a plain schema`);
58
+ }
59
+ const inner = innerOf(node);
60
+ if (inner !== undefined)
61
+ return visit(inner);
62
+ if (node instanceof z.core.$ZodObject) {
63
+ const keys = new Map();
64
+ for (const [key, field] of Object.entries(node._zod.def.shape)) {
65
+ const found = maskedField(field);
66
+ if (found !== undefined) {
67
+ if (!found.optional) {
68
+ fail(`holds ${found.masked.collection}.${found.masked.field} where it is required, as "${key}"; declare it optional: use the collection's clientOutput`);
69
+ }
70
+ keys.set(key, { masked: found.masked });
71
+ continue;
72
+ }
73
+ const child = visit(field);
74
+ if (child !== undefined)
75
+ keys.set(key, { child });
76
+ }
77
+ return keys.size === 0 ? undefined : { kind: 'object', keys };
78
+ }
79
+ if (node instanceof z.core.$ZodArray) {
80
+ const item = visit(node._zod.def.element);
81
+ return item === undefined ? undefined : { kind: 'array', item };
82
+ }
83
+ if (node instanceof z.core.$ZodRecord) {
84
+ const value = visit(node._zod.def.valueType);
85
+ return value === undefined ? undefined : { kind: 'record', value };
86
+ }
87
+ if (node instanceof z.core.$ZodTuple) {
88
+ const items = node._zod.def.items.map(visit);
89
+ const { rest: restSchema } = node._zod.def;
90
+ const rest = restSchema === null ? undefined : visit(restSchema);
91
+ return items.every((item) => item === undefined) && rest === undefined
92
+ ? undefined
93
+ : { kind: 'tuple', items, rest };
94
+ }
95
+ const branches = node instanceof z.core.$ZodUnion
96
+ ? node._zod.def.options
97
+ : node instanceof z.core.$ZodIntersection
98
+ ? [node._zod.def.left, node._zod.def.right]
99
+ : [];
100
+ const plans = branches.flatMap((branch) => visit(branch) ?? []);
101
+ return plans.length === 0 ? undefined : { kind: 'each', plans };
102
+ };
103
+ return visit(schema);
104
+ }
105
+ /**
106
+ * The masked field an object property holds, seen through its wrappers, and
107
+ * whether the property may be absent. Undefined for an unmasked property.
108
+ */
109
+ function maskedField(field) {
110
+ let current = field;
111
+ let optional = false;
112
+ while (current !== undefined) {
113
+ if (current instanceof z.core.$ZodOptional)
114
+ optional = true;
115
+ const mark = markOf(current);
116
+ if (mark !== undefined)
117
+ return { masked: mark, optional };
118
+ current = innerOf(current);
119
+ }
120
+ return undefined;
121
+ }
122
+ /** The collections a plan masks fields of. */
123
+ export function maskedCollections(plan) {
124
+ const slugs = new Set();
125
+ const visit = (node) => {
126
+ switch (node.kind) {
127
+ case 'object':
128
+ for (const { masked, child } of node.keys.values()) {
129
+ if (masked !== undefined)
130
+ slugs.add(masked.collection);
131
+ if (child !== undefined)
132
+ visit(child);
133
+ }
134
+ return;
135
+ case 'array':
136
+ visit(node.item);
137
+ return;
138
+ case 'record':
139
+ visit(node.value);
140
+ return;
141
+ case 'tuple':
142
+ for (const item of node.items)
143
+ if (item !== undefined)
144
+ visit(item);
145
+ if (node.rest !== undefined)
146
+ visit(node.rest);
147
+ return;
148
+ case 'each':
149
+ for (const plan of node.plans)
150
+ visit(plan);
151
+ }
152
+ };
153
+ visit(plan);
154
+ return slugs;
155
+ }
156
+ function isRecord(value) {
157
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
158
+ }
159
+ /**
160
+ * `value` with each field `withheld` says to remove taken out, where `plan`
161
+ * puts one. It copies what it changes, so a document the use case still
162
+ * holds is not changed.
163
+ */
164
+ export function applyMask(plan, value, withheld) {
165
+ switch (plan.kind) {
166
+ case 'object': {
167
+ if (!isRecord(value))
168
+ return value;
169
+ let out;
170
+ for (const [key, { masked, child }] of plan.keys) {
171
+ if (!Object.hasOwn(value, key))
172
+ continue;
173
+ out ??= { ...value };
174
+ if (masked !== undefined && withheld(masked)) {
175
+ delete out[key];
176
+ }
177
+ else if (child !== undefined) {
178
+ out[key] = applyMask(child, value[key], withheld);
179
+ }
180
+ }
181
+ return out ?? value;
182
+ }
183
+ case 'array':
184
+ return Array.isArray(value)
185
+ ? value.map((item) => applyMask(plan.item, item, withheld))
186
+ : value;
187
+ case 'record':
188
+ return isRecord(value)
189
+ ? Object.fromEntries(Object.entries(value).map(([key, item]) => [
190
+ key,
191
+ applyMask(plan.value, item, withheld),
192
+ ]))
193
+ : value;
194
+ case 'tuple':
195
+ return Array.isArray(value)
196
+ ? value.map((item, index) => {
197
+ const itemPlan = index < plan.items.length ? plan.items[index] : plan.rest;
198
+ return itemPlan === undefined
199
+ ? item
200
+ : applyMask(itemPlan, item, withheld);
201
+ })
202
+ : value;
203
+ case 'each':
204
+ return plan.plans.reduce((current, branch) => applyMask(branch, current, withheld), value);
205
+ }
206
+ }
207
+ /**
208
+ * The keys of an update's patch that name a withheld field, for VALIDATION
209
+ * issues (0035): a caller cannot change, or clear, what it cannot read.
210
+ */
211
+ export function withheldWrites(input, withheld) {
212
+ if (!isRecord(input))
213
+ return [];
214
+ return Object.entries(input)
215
+ .filter(([key, value]) => value !== undefined && withheld.has(key))
216
+ .map(([key]) => ({
217
+ path: [key],
218
+ message: `"${key}" is not readable, so it cannot be changed`,
219
+ }));
220
+ }
221
+ /** The where and sort paths that name a withheld field, for VALIDATION issues. */
222
+ export function withheldPaths(input, withheld) {
223
+ const issues = [];
224
+ const message = (field) => `"${field}" is not readable`;
225
+ const where = (node, path) => {
226
+ if (!isRecord(node))
227
+ return;
228
+ for (const [key, value] of Object.entries(node)) {
229
+ if ((key === 'and' || key === 'or') && Array.isArray(value)) {
230
+ value.forEach((clause, index) => {
231
+ where(clause, [...path, key, index]);
232
+ });
233
+ }
234
+ else if (withheld.has(key)) {
235
+ issues.push({ path: [...path, key], message: message(key) });
236
+ }
237
+ }
238
+ };
239
+ if (!isRecord(input))
240
+ return issues;
241
+ where(input.where, ['where']);
242
+ const { sort } = input;
243
+ if (Array.isArray(sort)) {
244
+ sort.forEach((key, index) => {
245
+ if (typeof key !== 'string')
246
+ return;
247
+ const field = key.startsWith('-') ? key.slice(1) : key;
248
+ if (withheld.has(field)) {
249
+ issues.push({ path: ['sort', index], message: message(field) });
250
+ }
251
+ });
252
+ }
253
+ return issues;
254
+ }
255
+ //# sourceMappingURL=mask.js.map