cvx-kit 0.1.14 → 0.1.16

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 (51) hide show
  1. package/README.md +64 -45
  2. package/dist/querying/cursors.d.mts +5 -0
  3. package/dist/querying/cursors.mjs +1 -1
  4. package/dist/querying/cursors.mjs.map +1 -1
  5. package/dist/querying.d.mts +20 -6
  6. package/dist/querying.mjs +1 -1
  7. package/dist/querying.mjs.map +1 -1
  8. package/dist/relations.mjs +1 -1
  9. package/dist/relations.mjs.map +1 -1
  10. package/dist/zod-table.d.mts +59 -2
  11. package/dist/zod-table.mjs +1 -1
  12. package/dist/zod-table.mjs.map +1 -1
  13. package/package.json +10 -3
  14. package/AGENTS.md +0 -47
  15. package/CHANGELOG.md +0 -324
  16. package/ROADMAP.md +0 -126
  17. package/docs/agent-tools.md +0 -41
  18. package/docs/approvals.md +0 -201
  19. package/docs/architecture.md +0 -124
  20. package/docs/auth.md +0 -443
  21. package/docs/command-context.md +0 -150
  22. package/docs/commands-legacy.md +0 -513
  23. package/docs/commands.md +0 -173
  24. package/docs/conventions.md +0 -345
  25. package/docs/crud.md +0 -66
  26. package/docs/domain-contracts.md +0 -148
  27. package/docs/domain-operations.md +0 -615
  28. package/docs/effect.md +0 -403
  29. package/docs/llms.md +0 -324
  30. package/docs/maintainability.md +0 -124
  31. package/docs/migration.md +0 -351
  32. package/docs/oxlint.md +0 -254
  33. package/docs/querying.md +0 -293
  34. package/docs/tenancy.md +0 -176
  35. package/docs/triggers.md +0 -77
  36. package/docs/upgrading.md +0 -287
  37. package/docs/webhooks.md +0 -58
  38. package/docs/zod-table.md +0 -278
  39. package/scripts/convex-config-bridge.mjs +0 -44
  40. package/scripts/convex-smoke-env.mjs +0 -33
  41. package/scripts/extract-changelog.mjs +0 -29
  42. package/scripts/owned-process.mjs +0 -140
  43. package/scripts/owned-process.test.mjs +0 -107
  44. package/scripts/smoke-packed-components.mjs +0 -341
  45. package/scripts/smoke-packed-effect.mjs +0 -439
  46. package/scripts/smoke-packed-querying.mjs +0 -296
  47. package/scripts/test-packed-auth.mjs +0 -72
  48. package/scripts/test-packed-effect.mjs +0 -482
  49. package/scripts/test-packed-ids.mjs +0 -150
  50. package/scripts/test-packed-oxlint.mjs +0 -167
  51. package/scripts/test-packed-querying.mjs +0 -185
package/docs/effect.md DELETED
@@ -1,403 +0,0 @@
1
- # Effect domain commands and queries
2
-
3
- `cvx-kit/effect` adds cohesive command/query declarations and a shared API
4
- runner. Handlers can return ordinary values, Promises, or Effects. Each
5
- registry returns a lazy Effect from `exec(operation, input, host)`; the API
6
- adapter provides request services and runs it once.
7
-
8
- This is the recommended command API. The older `Foundation.Command` facade
9
- and `exec({ operation, handler })` executor API are deprecated and retained for
10
- compatibility. Declare handlers inside `command({...})` for new command code.
11
-
12
- Install Effect explicitly:
13
-
14
- ```sh
15
- bun add effect@4.0.1
16
- ```
17
-
18
- The optional peer range is `>=4.0.1 <5`. Existing imports and Promise-based
19
- Foundation consumers work without Effect installed. Use the public facade;
20
- the internal module paths are not supported imports.
21
-
22
- ## A complete domain-to-API example
23
-
24
- These four TypeScript sections form one module and are compiled together
25
- against the packed public package. The example uses Convex's generic builders
26
- with a concrete schema so it is standalone. In an app, put the schema in
27
- `convex/schema.ts`, import your generated `query`, `mutation`, `QueryCtx`, and
28
- `MutationCtx` from `./_generated/server`, and split the remaining code into
29
- services, domain registries, shared API setup, and endpoint modules.
30
-
31
- The API obtains the actor from authenticated Convex identity. Caller arguments
32
- contain only a document key and title. Both services constrain document reads
33
- and writes by that actor; the application should also enforce its own roles
34
- and tenant policies. The small permission checker below only requires a
35
- nonempty trusted actor.
36
-
37
- ### Contracts and injectable capabilities
38
-
39
- The reader has no write methods. The mutation provider will add the writer;
40
- a native query cannot satisfy a command's writer requirement. Expected errors
41
- are values in the Effect error channel, rather than thrown exceptions.
42
-
43
- ```ts
44
- import { Context, Effect } from 'effect'
45
- import {
46
- defineSchema,
47
- defineTable,
48
- queryGeneric,
49
- mutationGeneric,
50
- type DataModelFromSchemaDefinition,
51
- type QueryBuilder,
52
- type MutationBuilder,
53
- type GenericQueryCtx,
54
- type GenericMutationCtx,
55
- } from 'convex/server'
56
- import { ConvexError, v } from 'convex/values'
57
- import { z } from 'zod'
58
- import { createEffectFoundation, effectApiBuilder } from 'cvx-kit/effect'
59
- import type { AuditEntryInput } from 'cvx-kit/components/foundation'
60
-
61
- export const schema = defineSchema({
62
- documents: defineTable({ key: v.string(), owner: v.string(), title: v.string() }).index(
63
- 'by_owner_key',
64
- ['owner', 'key'],
65
- ),
66
- audits: defineTable({ actor: v.string(), operation: v.string(), documentKey: v.string() }),
67
- })
68
- type DataModel = DataModelFromSchemaDefinition<typeof schema>
69
- type QueryCtx = GenericQueryCtx<DataModel>
70
- type MutationCtx = GenericMutationCtx<DataModel>
71
- const nativeQuery: QueryBuilder<DataModel, 'public'> = queryGeneric
72
- const nativeMutation: MutationBuilder<DataModel, 'public'> = mutationGeneric
73
-
74
- type Host = { actor: string }
75
- class DocumentMissing {
76
- readonly _tag = 'DocumentMissing'
77
- }
78
- class RenameRejected {
79
- readonly _tag = 'RenameRejected'
80
- }
81
- class AccessDenied {
82
- readonly _tag = 'AccessDenied'
83
- }
84
- class DocumentReader extends Context.Service<
85
- DocumentReader,
86
- { title: (key: string, actor: string) => Effect.Effect<string, DocumentMissing> }
87
- >()('DocumentReader') {}
88
- class DocumentWriter extends Context.Service<
89
- DocumentWriter,
90
- {
91
- rename: (key: string, title: string, actor: string) => Effect.Effect<void, DocumentMissing>
92
- audit: (actor: string, entry: AuditEntryInput) => Effect.Effect<void>
93
- }
94
- >()('DocumentWriter') {}
95
- ```
96
-
97
- ### Cohesive domain declarations
98
-
99
- `label` is an ordinary async handler, and `preview` uses a generator. `title` uses `Effect.fn` with explicit input
100
- and host annotations. `rename` returns an `Effect.gen` program, yields the
101
- query directly, then uses the injected writer. Its pipe converts the query's
102
- missing-document error into a domain-specific rename rejection before adding
103
- a span. The audit entry sits beside the command, and the shared audit policy
104
- uses the same invocation's writer.
105
-
106
- ```ts
107
- const foundation = createEffectFoundation({
108
- observability: {
109
- enabled: false,
110
- classifyError: () => ({ outcome: 'failed' as const, errorCode: 'DOCUMENT_OPERATION_FAILED' }),
111
- },
112
- checkPermission: (host: Host) =>
113
- host.actor.length > 0 ? Effect.void : Effect.fail(new AccessDenied()),
114
- writeAudit: (host: Host, entry: AuditEntryInput) =>
115
- Effect.gen(function* () {
116
- const writer = yield* DocumentWriter
117
- yield* writer.audit(host.actor, entry)
118
- }),
119
- })
120
- const keyInput = z.object({ key: z.string().min(1) })
121
- const renameInput = keyInput.extend({ title: z.string().trim().min(1) })
122
- const titleResult = z.string().transform((title) => ({ title }))
123
-
124
- export const documents = foundation.Query({
125
- context: (host: Host) => host,
126
- operations: ({ query }) => ({
127
- label: query({
128
- input: keyInput,
129
- result: z.string(),
130
- handler: async (input) => `Document ${input.key}`,
131
- }),
132
- preview: query({
133
- input: keyInput,
134
- result: titleResult,
135
- permission: 'documents:read',
136
- handler: (input, host) =>
137
- Effect.gen(function* () {
138
- const reader = yield* DocumentReader
139
- return yield* reader.title(input.key, host.actor)
140
- }),
141
- }),
142
- title: query({
143
- input: keyInput,
144
- result: titleResult,
145
- permission: 'documents:read',
146
- handler: Effect.fn('documents.title')(function* (
147
- input: z.output<typeof keyInput>,
148
- host: Host,
149
- ) {
150
- const reader = yield* DocumentReader
151
- return yield* reader.title(input.key, host.actor)
152
- }),
153
- }),
154
- }),
155
- })
156
- export const documentCommands = foundation.Command({
157
- context: (host: Host) => host,
158
- operations: ({ command }) => ({
159
- rename: command({
160
- input: renameInput,
161
- result: titleResult,
162
- classification: 'business',
163
- permission: 'documents:write',
164
- handler: (input, host) =>
165
- Effect.gen(function* () {
166
- // A nested query stays in the same Effect; no inner runner.
167
- yield* documents.exec('title', { key: input.key }, host)
168
- const writer = yield* DocumentWriter
169
- yield* writer.rename(input.key, input.title, host.actor)
170
- return input.title
171
- }).pipe(
172
- Effect.catchTag('DocumentMissing', () => Effect.fail(new RenameRejected())),
173
- Effect.withSpan('documents.rename'),
174
- ),
175
- guard: (host) => (host.actor.length > 0 ? Effect.void : Effect.fail(new AccessDenied())),
176
- middleware: ({ next }) => next().pipe(Effect.withSpan('documents.command')),
177
- audit: ({ command: input, result }, host) => ({
178
- actorId: host.actor,
179
- operation: 'documents.rename',
180
- aggregate: { type: 'document', id: input.key },
181
- metadata: { title: result.title },
182
- }),
183
- }),
184
- }),
185
- })
186
- ```
187
-
188
- ### Request services and shared API setup
189
-
190
- Construct the services once in each shared builder provider. Endpoint handlers
191
- do not call `Context.make`, `Effect.runPromise`, or an extra execution helper.
192
- The database Promise wrappers below intentionally preserve unexpected database
193
- failures as defects. For external integrations with expected failures, use
194
- `Effect.tryPromise` and return your own typed error.
195
-
196
- `mapError` projects an expected failure to a small `ConvexError` payload. It
197
- receives `unknown`, so narrow it before projection. Defects, interruption,
198
- and combined causes do not become expected failures through this hook; the
199
- adapter preserves those failure causes. The registered function still fails,
200
- which is required for mutation rollback.
201
-
202
- ```ts
203
- function readerFor(ctx: QueryCtx): Context.Context<DocumentReader> {
204
- return Context.make(DocumentReader, {
205
- title: (key, actor) =>
206
- Effect.gen(function* () {
207
- const document = yield* Effect.promise(() =>
208
- ctx.db
209
- .query('documents')
210
- .withIndex('by_owner_key', (q) => q.eq('owner', actor).eq('key', key))
211
- .unique(),
212
- )
213
- if (!document) return yield* Effect.fail(new DocumentMissing())
214
- return document.title
215
- }),
216
- })
217
- }
218
- function writerFor(ctx: MutationCtx): Context.Context<DocumentWriter> {
219
- return Context.make(DocumentWriter, {
220
- rename: (key, title, actor) =>
221
- Effect.gen(function* () {
222
- const document = yield* Effect.promise(() =>
223
- ctx.db
224
- .query('documents')
225
- .withIndex('by_owner_key', (q) => q.eq('owner', actor).eq('key', key))
226
- .unique(),
227
- )
228
- if (!document) return yield* Effect.fail(new DocumentMissing())
229
- yield* Effect.promise(() => ctx.db.patch(document._id, { title }))
230
- }),
231
- audit: (actor, entry) =>
232
- Effect.promise(() =>
233
- ctx.db.insert('audits', {
234
- actor,
235
- operation: entry.operation,
236
- documentKey: entry.aggregate.id,
237
- }),
238
- ).pipe(Effect.asVoid),
239
- })
240
- }
241
- function authenticatedHost(ctx: QueryCtx) {
242
- return Effect.gen(function* () {
243
- const identity = yield* Effect.promise(() => ctx.auth.getUserIdentity())
244
- if (!identity) return yield* Effect.fail(new AccessDenied())
245
- return { actor: identity.tokenIdentifier }
246
- })
247
- }
248
- function projectExpectedError(error: unknown) {
249
- if (error instanceof DocumentMissing || error instanceof RenameRejected)
250
- return new ConvexError({ code: 'DOCUMENT_NOT_FOUND' })
251
- if (error instanceof AccessDenied) return new ConvexError({ code: 'ACCESS_DENIED' })
252
- return new Error('Document operation failed', { cause: error })
253
- }
254
- const queryApi = effectApiBuilder(nativeQuery, {
255
- services: readerFor,
256
- mapError: projectExpectedError,
257
- })
258
- const mutationApi = effectApiBuilder(nativeMutation, {
259
- services: (ctx) => Context.merge(readerFor(ctx), writerFor(ctx)),
260
- mapError: projectExpectedError,
261
- })
262
- ```
263
-
264
- ### Consume the domain operations in the API
265
-
266
- The Convex callback remains `(ctx, input)`; the domain callback and executor
267
- use input before context/host. Both endpoints are normal native registrations
268
- with argument and return validators. Each handler authenticates the request
269
- and returns the domain Effect. The adapter supplies the services required by
270
- the complete nested program.
271
-
272
- ```ts
273
- export const documentTitle = queryApi({
274
- args: { key: v.string() },
275
- returns: v.object({ title: v.string() }),
276
- handler: (ctx, input) =>
277
- Effect.gen(function* () {
278
- const host = yield* authenticatedHost(ctx)
279
- return yield* documents.exec('title', input, host)
280
- }),
281
- })
282
- export const renameDocument = mutationApi({
283
- args: { key: v.string(), title: v.string() },
284
- returns: v.object({ title: v.string() }),
285
- handler: (ctx, input) =>
286
- Effect.gen(function* () {
287
- const host = yield* authenticatedHost(ctx)
288
- return yield* documentCommands.exec('rename', input, host)
289
- }),
290
- })
291
- ```
292
-
293
- ## Types and schema boundaries
294
-
295
- The command accepts `z.input<typeof renameInput>`. Its handler sees
296
- `z.output<typeof renameInput>`, so the title has already been trimmed. The
297
- handler returns a string, which is the input of `titleResult`; the registry's
298
- final result is `{ title: string }`, the output of that transform. Middleware
299
- `next()` returns the handler result before the final result parser, so wrap
300
- or transform that value according to the result schema's input contract.
301
-
302
- TypeScript preserves the selected operation's success, expected error, and
303
- service requirements. The title query requires `DocumentReader`; rename
304
- requires `DocumentReader | DocumentWriter` and can fail with `AccessDenied`
305
- or `RenameRejected`. The API builder checks that its provider supplies those
306
- services. A reader-only provider cannot register rename, and an incompatible
307
- handler result cannot pass its declared native return validator.
308
-
309
- This is server-side Effect composition. Generated Convex references retain
310
- native argument/result types and visibility; they do not carry Effect's typed
311
- error or service channels over the transport. Clients receive ordinary Convex
312
- results or errors.
313
-
314
- For inferred declarations, put `handler` and `guard` before `middleware`, as
315
- above. Middleware-first declarations need explicit callback and error/service
316
- annotations where inference cannot recover the later handler's channels.
317
- `Effect.fn` accepts typed function arguments; `Effect.gen` accepts a generator
318
- whose yielded Effects determine its channels. Use `(input, context) =>
319
- Effect.gen(function* () { ... })` when those values come from the declaration.
320
- A constructed `Effect.gen` program cannot itself receive handler arguments.
321
-
322
- ## Hooks, replay, and execution scope
323
-
324
- A command runs input parsing, observation setup and context resolution, then
325
- permission checking, preparation, middleware, shared and operation guards,
326
- handler, final result parsing, audit construction, aggregate checking, audit
327
- writing, and completion. Observation records the outcome. Query permission
328
- checking runs before its context resolver, followed by middleware, guards,
329
- handler, and result parsing. Command audit/completion hooks do not exist on
330
- queries.
331
-
332
- Optional command `prepare(context, input)` returns `{ kind: 'execute',
333
- complete }` or `{ kind: 'replay', result }`. The completion callback receives
334
- the parsed final result. Permission checking still precedes replay. A replay
335
- result is parsed with `replayResult` when supplied, otherwise with `result`,
336
- and skips middleware, guards, handler, audit writing, and completion.
337
- Middleware receives `operation`, parsed `input` (also `command`), `context`,
338
- and `next`; it may provide an enriched context to `next({ context })`.
339
- Each execution allows `next` once. Audit construction sees the original domain
340
- context, and the audit writer sees the original trusted host.
341
-
342
- The provider may return a `Context`, a Promise of a Context, or an Effect that
343
- builds a Context. It runs separately for every native invocation. The shared
344
- runner opens an Effect scope, evaluates the provider and handler, and awaits
345
- scope finalizers before returning or throwing. Use `Effect.acquireRelease`
346
- inside a provider for resources that actually need cleanup. Nested domain
347
- operations share that runner and scope; do not run them independently inside
348
- handlers. Cleanup failure remains an endpoint failure, including when it
349
- combines with a handler failure.
350
-
351
- ## Convex boundaries and observed support
352
-
353
- A domain query is a reusable read operation; its name does not choose the
354
- native function kind. A native Convex query must perform deterministic database
355
- reads. Native mutations can write, and a failed command, result validator,
356
- audit writer, completion hook, or awaited cleanup rolls back that mutation's
357
- writes. Actions are the place for HTTP and other external integrations.
358
- An action's separate `ctx.runMutation` calls are separate transactions: a
359
- later failure does not undo an earlier successful mutation.
360
-
361
- The packed public facade was compiled and executed under npm and Bun with
362
- Effect 4.0.1 and `convex-helpers` 0.1.123. Legacy packed consumers also ran with
363
- Effect absent. Local Convex 1.45.0 checks exercised ordinary, generator, and
364
- named-function query composition; request cleanup; expected and combined
365
- failures; mutation validation and lifecycle rollback; and an action using
366
- loopback HTTP with separate mutation transactions. `Effect.withSpan` was
367
- accepted in those programs; this does not establish exported telemetry,
368
- background fibers, arbitrary concurrency, or every Effect runtime capability
369
- in Convex.
370
-
371
- The standalone packed compiler includes `ESNext.Disposable` in its library
372
- set for Effect 4 declarations. If your project's TypeScript environment does
373
- not already provide those globals, include that library as well.
374
-
375
- ## Adopt one domain at a time
376
-
377
- Keep existing Promise registries and API endpoints while adding the optional
378
- facade for a new domain. Move each operation's handler beside its schemas and
379
- hooks, switch domain callbacks to input-first arguments, and return the new
380
- registry's lazy Effect to a shared API adapter. A normal async handler works
381
- in the cohesive declaration without a generator; wrap expected Promise failures
382
- only when you want a typed error channel.
383
-
384
- The [command guide](./commands.md) documents the current lifecycle and migration
385
- steps; the [deprecated API reference](./commands-legacy.md) retains old examples.
386
- The [authentication guide](./auth.md)
387
- shows the shared `createEffectAuthFunctions(config, policies)` factory and how
388
- to wrap individual trusted builders with `effectZodApiBuilder`, so auth,
389
- tenancy, validators, row-level policies, and triggers run through their
390
- existing builder before Effect request services are provisioned.
391
-
392
- For an app-wide foundation, configure `query`, `mutation`, and `action` policies
393
- once with `createEffectAuthFunctions` and explicit separate system policies.
394
- Query handles bind readers, mutation handles bind the secured triggered writer,
395
- and action handles use `runMutation` rather than a mutation database.
396
-
397
- Optional request context can also be added through the existing Effect API adapter's
398
- `context` callback. Bind selected registries with `commands.withContext(value)`
399
- and consume `ctx.commands.exec(name, input)` through the application's existing
400
- function helper names. Keep dependencies local to each feature; explicit execution
401
- and input-only command handlers remain supported. See [optional context injection](./command-context.md).
402
-
403
- See [Optional domain contracts](./domain-contracts.md) for shared declarations, named implementations, and registry audit defaults in both Effect and Promise registries.