cvx-kit

Reusable Convex application kit: foundation kernels, a generic approvals
component, zod table boundaries, auth-aware function constructors with
per-app role vocabularies, an application trigger registry, and an audited
command protocol.
bun add cvx-kit
# or: npm install cvx-kit
Supported versions: Convex ^1.46.0, Zod ^4.5.4, Bun 1.3+, and Node.js
24+ with npm 11+. The library runtime is ESM-only.
Toolchain
bun install — dependencies
bun run test — vite-plus test suite (vp test run, convex-test on edge-runtime)
bun run typecheck — tsc --noEmit
bun run build — vp pack (tsdown on Rolldown); all build options live in
the pack key of vite.config.ts: per-module ESM + .d.mts to dist/,
target ES2025, minified, deps external, publint-verified
bun run build:codegen — re-run convex codegen for both components, then build
Documentation
Full docs live on GitHub
and are bundled with the repository's agent skill.
The npm package includes this README; full docs and skills are installed separately.
If you use a coding agent, install the cvx-kit skill from your application directory:
npx skills add ImRLopezAG/cvx-kit --skill cvx-kit
The skills CLI lets you choose your agent. Installation
is project-scoped by default; add --global only for a user-wide install. Public
GitHub installation needs no login. Preview available skills with
npx skills add ImRLopezAG/cvx-kit --list.
The skill reads the guides needed for each task instead of loading all docs.
Check your installed package version against the skill's source revision before
using newer APIs. For a release containing the skill, use its GitHub tag URL
(https://github.com/ImRLopezAG/cvx-kit/tree/<tag>/skills/cvx-kit) as the install source.
Maintainers edit skills/cvx-kit/references/ directly. CI verifies that relative
links remain inside the installed skill with bun run skills:check.
Guides:
-
native-id-relations.md — native-ID union links, authorized inverse pages, and migration
-
architecture.md — the layered application shape the kit encodes
-
conventions.md — the doctrine: folder structure, file anatomy, naming grammar, import rules
-
zod-table.md — one zod shape per entity, masked into every boundary
-
auth.md — auth-aware function constructors from injected policy
-
commands.md — Effect command declarations, lifecycle, and migration
-
effect.md — opt-in Effect v4 registries, injected services, and shared API builders
-
domain-operations.md — server domain/API examples, contracts, errors, receipts, workflow steps, and selected tools
-
triggers.md — trigger registry, timestamps/append-only/no-delete
-
approvals.md — declarative approval workflows
-
tenancy.md — row-level security (roles) with opt-in multi-tenant isolation
-
crud.md — the CRUD command factory
-
webhooks.md — the sanctioned webhook boundary
-
agent-tools.md — agent tools that are audited commands
-
upgrading.md — 0.0.x → 0.1.0, old way → new way
-
maintainability.md — keeping a Convex app maintainable long-term
-
migration.md — restructuring an existing raw Convex project into this architecture
-
llms.md — optional condensed reference for coding agents
Per-request import cost
Convex evaluates a function's whole static import graph on every request, and queries and mutations cannot use dynamic import(). Whatever a module builds at import is paid on every call. The kit builders do not convert validators at registration. Convex reads them when it exports function metadata at push, and the handler builds its parse state on first call. To keep a module from building schemas for functions it is not serving, declare them lazily:
export const listPayments = authQuery({
get args() {
return financeContract.queries.listPayments.input
},
get returns() {
return financeContract.queries.listPayments.result
},
handler: (ctx, args) => ctx.queries.finance.exec('listPayments', args),
})
With args: contract.queries.x.input, the property read builds the schema at import. A getter defers it. Declare contract operations as getters too (see the domain contracts guide), so that reading or executing one operation builds and binds only that operation. Keep the trigger registry out of query modules with createAuthReaders (see cvx-kit/auth below). Validation is identical in every form.
Two more things keep the deferral intact. First, a paginationOpts(...) or pageDto(...) call at module scope outside a contract still builds at import, so put it behind a getter or inside the operation that uses it. Second, pass Convex's generated builders (query, mutation, ...) to the kit constructors. A wrapper that spreads or copies the definition reads its getters at registration.
Modules
cvx-kit/zod-table
One zod shape per entity, masked into every boundary it crosses:
import { zodTable } from 'cvx-kit/zod-table'
export const documents = zodTable(
'documents',
(id) => ({
title: z.string(),
ownerId: id('users'),
secretNote: z.string(),
}),
{
commandFields: ['title'], // what a command may say
publicFields: ['title', 'ownerId'], // the DTO allowlist
},
)
// documents.table → defineTable(...) for schema.ts
// documents.toPublicDto(row) → projects AND re-parses (runtime redaction)
For fields shared across tables, create a reusable declaration function:
import { createTable } from 'cvx-kit/zod-table'
const customTable = createTable({ ref: z.string(), nextActivity: z.string() })
const tasks = customTable('tasks', () => ({ title: z.string() }))
const projects = customTable('projects', () => ({ name: z.string() }))
It accepts the same arguments and returns the same boundary as zodTable.
Table-specific fields cannot repeat shared field names. See the
zod-table guide
for field masks and examples.
Every table gets createdAt, updatedAt, and archivedAt baked in —
opinionated, server-owned, always excluded from inserts and commands
(expose them via publicFields when a DTO needs them). Register the
timestamps trigger once and they maintain themselves; archivedAt stays
under application control.
zodVariantTable covers discriminated-union tables; jsonSafeZid keeps
LLM-tool JSON schemas primitive while preserving the Id<...> type.
cvx-kit/relations and cvx-kit/querying
See the querying guide,
DTO parameters, and
consumer rule reference.
Declare relationships once in convex/relations.ts, then configure the engine
once in convex/querying.ts. Both factories are also available from the package
root. The relations subpath exposes declarations and public types; executor
metadata and managed reader capabilities are internal.
// convex/relations.ts
import { defineRelations } from 'cvx-kit/relations'
import './domain/tasks/table' // Establish native indexes before compiling the registry.
import { tasks, labels, edges } from './domain/tasks/schema'
export const relations = defineRelations({ tasks, labels, edges }, (r) => ({
tasks: {
referenceTask: r.one.tasks({ from: r.tasks.reference, to: r.tasks._id }),
labels: r.many.labels({
from: r.tasks._id.through(r.edges.task),
to: r.labels._id.through(r.edges.label),
}),
},
}))
The tables can be zodTable, tenantTable, or three-argument zodVariantTable boundaries, with
indexes supporting each declared lookup. Names can distinguish multiple edges
to the same table; references can point to the same table. A one edge returns a
public DTO or null. A many edge returns a bounded native page. Junction output
preserves duplicate edge occurrences, even when target reads are memoized.
Missing and unreadable targets have the same public result.
defineRelations checks table names, native table ownership and the structure
of relation declarations. Variant tables also run their native table preflight
then, to expose common-field references. It captures each table's stored field semantics,
public DTO validation, variants and active indexes on that table's first use:
its schema helpers, an engine read, or a selected relation that reaches it. Each
edge's field types and indexes are checked when the edge is first read. Invalid
tables and edges throw on first use instead of at registration. Complete schema
and index configuration before calling defineRelations. Later changes to
source declarations do not affect a table after its first use. Create a new
registry to adopt changes. Caller-owned declarations remain mutable.
Call verifyRelations(relations) from a test to run every deferred check, so CI
fails on an invalid registry:
import { verifyRelations } from 'cvx-kit/relations'
import { relations } from '../convex/relations'
test('relation registry is valid', () => verifyRelations(relations))
Relation DTOs support .refine(). They reject opaque .superRefine() and
.check() callbacks; express those validations with .refine() instead.
Captured callbacks still observe application state through their closures.
Variant tables keep their discriminated public unions. Use the relation callback's
second argument, branch('payments', 'creditor_payment').creditorId, for a
branch-specific reference; its tag is checked before lookup. See the
variant querying guide for the
complete authenticated flow and branch filter syntax.
// convex/querying.ts
import { createQueryEngine } from 'cvx-kit/querying'
import schema from './schema'
import { relations } from './relations'
export const querying = createQueryEngine({ schema, relations })
One engine serves every registered table. Cursor keys load internally on first
pagination from server environment variables CVX_QUERY_CURSOR_KEYS_JSON
(key IDs mapped to 128-character hex secrets) and CVX_QUERY_CURSOR_CURRENT_KEY_ID.
Keep key material out of arguments, client code, and logs. Optional overrides
belong in a separate second argument; see querying. The default codec
uses authenticated AES-SIV encryption without a plaintext fallback; identical
payloads under the same binding reveal equality. Tokens bind filters, selected
output, index, order, relation ancestry, principal/tenant/security scope, and
registry/policy/engine versions. Page-size changes alone remain valid. Retain
old keys during rotation when existing cursors should continue working.
Relation registration captures and validates schemas eagerly; eligible private
DTO schemas reconstruct on first projection. Public helper schemas stay fresh.
See registry capture and compatibility
for eager fallback and the unsupported side-effecting internal Proxy boundary.
Use the registry's validators in domain contracts and an authenticated Query
registry handler:
const options = relations.tables.tasks.paginationOpts({
department: true,
status: true,
labels: { name: true },
})
const result = relations.tables.tasks.pageDto({ labels: true })
// In the Query operation's handler, ctx comes from createAuthFunctions.authQuery.
const page = await querying(ctx)
.tasks.where({ tenant: ctx.tenant })
.with({ labels: true })
.paginate(args)
// A separate authenticated child endpoint validates parent with tasks.schema.shape._id.
const nextLabels = await querying(ctx)
.tasks.relation(parent, 'labels')
.paginate({ numItems: 25, cursor: page.page[0].labels.continueCursor })
Select filterable stored fields explicitly, including server-owned fields when
needed. Public DTO fields do not determine filter eligibility. Scalar predicates
support equality, ranges, and, or, and not; many predicates use some or
none. Eligibility and composed read authorization run before parents fill a
page. Parent, junction, target, and continuation reads all recheck authorization.
include and paginated(dto) retain their existing behavior independently.
For large generated static APIs, opt into compact argument validators with
paginationOpts(selection, { validator: 'compact' }) on a table or relation.
Use the resulting schema with cvx-kit's authenticated builders. Common filters
remain precisely typed; deeper generated filter branches become opaque where
native ID checks allow it. Full depth, node, membership, and value validation
still runs before customization or handler work. Use PaginationFiltersInput
from cvx-kit/relations to check deeper filter literals. See the
compact filter guide
for registration requirements and ID-heavy size limits.
Chain .when(value, 'index_name') to choose the first present condition: false,
0, and '' are present; null and undefined are absent. The gate does not
bind an index field; validated filters and server .where(...) constraints do.
An incompatible explicit choice fails. Automatic selection uses the longest
usable equality prefix, then stable index-name order, with creation-time fallback.
order: 'desc' reverses the chosen native index order. Native continuation,
split/end cursors, and page status are preserved, with external tokens protected.