dartvex_codegen 0.3.0
dartvex_codegen: ^0.3.0 copied to clipboard
CLI code generator for Convex backends. Generates type-safe Dart bindings from the validators in your Convex function spec.
dartvex_codegen #
CLI code generator for Convex backends. Generates type-safe Dart bindings from your Convex function spec (the args and returns validators of your public functions) — companion tool to dartvex.
The Dartvex ecosystem #
| Package | Description |
|---|---|
dartvex |
Core client — WebSocket sync, subscriptions, auth |
dartvex_flutter |
Flutter widgets — Provider, Query, Mutation |
dartvex_codegen |
CLI code generator — type-safe Dart bindings from function validators |
dartvex_local |
Offline support — SQLite cache, mutation queue |
dartvex_auth_better |
Better Auth adapter |
Source and full docs: github.com/AndreFrelicot/dartvex
Installation #
dev_dependencies:
dartvex_codegen: ^0.3.0
Requires Dart ^3.7.0.
The generated bindings call dartvex APIs such as
ConvexFunctionCaller.paginatedQuery and QueryLoading (0.2.0), and
generated mutations forward an optional optimistic update to
ConvexFunctionCaller.mutate (0.3.0), so use the dartvex release that
matches this generator. The application consuming the generated code needs:
dependencies:
dartvex: ^0.3.0
Usage #
Generate from an existing Convex TypeScript project:
dart run dartvex_codegen generate \
--project /path/to/convex-backend \
--output /path/to/dart_app/lib/convex_api
--project runs convex function-spec in that directory, which lists the
functions deployed to the project's configured (dev) deployment, not the
local TypeScript sources. Push your changes first (keep npx convex dev
running) so the bindings match your code.
Generate from a previously exported spec file:
dart run dartvex_codegen generate \
--spec-file /path/to/function_spec.json \
--output /path/to/dart_app/lib/convex_api
Useful flags:
--client-import package:dartvex/dartvex.dart--dry-run(generated files go to stdout; warnings go to stderr)--verbose(show the Convex CLI output)--watch
Run dart run dartvex_codegen --help to list the commands (generate,
scrub) and dart run dartvex_codegen generate --help for every option.
Watch mode #
--watch regenerates whenever its input changes:
- With
--spec-file, it reacts to rewrites of that file, including atomic replaces (git pull, editor safe-writes,mv). An empty file (a shell redirect that has not been written yet) is skipped silently. - With
--project, it watches the project directory recursively (including on Linux, where each directory is watched individually;node_modules,.git,.dart_tool, and the output directory are skipped). Because the spec comes from the deployment, it re-reads it 2, 5, and 10 seconds after each change so aconvex devpush that finishes after the first regeneration is still picked up; unchanged specs are not rewritten. If a push takes longer, save again or rerungenerate.
Failed regenerations are reported on stderr and watching continues. If the watch itself fails (for example, the watched directory is removed), the command exits with a non-zero code.
Scrubbing an exported spec #
Before committing an exported spec file, scrub the real deployment URL it bakes in:
npx convex function-spec | dart run dartvex_codegen scrub > function_spec.json
scrub reads from stdin (or --spec-file) and writes the spec with the
top-level url replaced by https://your-deployment.convex.cloud
(customizable via --placeholder-url). The transform is idempotent and
preserves key order, so committed diffs stay minimal. Like --project,
scrub and generate --spec-file skip banner lines that package runners
such as yarn v1 print around the JSON.
Generated API #
The generator produces:
api.dartas the main entrypointruntime.dartwith shared helper types likeOptional<T>schema.dartwith typed table IDsmodules/...with typed wrappers around Convex queries, mutations, and actions
Example:
import 'package:dartvex/dartvex.dart';
import 'package:my_app/convex_api/api.dart';
final client = ConvexClient('https://your-deployment.convex.cloud');
final api = ConvexApi(client);
final messages = await api.messages.list();
await api.messages.send(author: 'Andre', text: 'Hello');
final subscription = api.messages.listSubscribe();
One-shot calls return the decoded Dart type (Future<List<ListResultItem>>,
Future<MessagesId>, ...). ...Subscribe() methods return a
TypedConvexSubscription<T> (stream, cancel()), whose stream emits the
sealed TypedQueryResult<T>:
final subscription = api.messages.listSubscribe();
subscription.stream.listen((result) {
switch (result) {
case TypedQuerySuccess(:final value, :final hasPendingWrites):
print('${value.length} messages (pending writes: $hasPendingWrites)');
case TypedQueryLoading():
break; // transient, for example an optimistic clear
case TypedQueryError(:final message):
print(message);
}
});
A server value the bindings cannot decode (for example an enum value added
after generation) arrives as a TypedQueryError rather than a stream error.
Paginated queries return a TypedConvexPaginatedQuery<T> (stream,
current, items, loadMore(), cancel()). Its
TypedConvexPaginatedResult<T> snapshots carry items, status, isDone,
error and hasPendingWrites (optimistic writes affect a loaded page), and
undecodable items are reported as ConvexPaginationStatus.error. Optional arguments use
Optional<T> from runtime.dart, so an omitted argument and an explicit
null stay distinct.
Generated mutation methods take an optional optimisticUpdate, forwarded to
the client's mutate:
await api.messages.send(
author: 'Andre',
text: 'Hello',
optimisticUpdate: (store) {
// Update cached query results through the OptimisticLocalStore.
},
);
Type mapping notes #
v.number()maps todouble;v.int64()maps toBigInt;v.commitTs()maps toObject, holding aBigIntcommit timestamp orConvexCommitTsPlaceholder.instance(what a mutation gets when it reads back a field it wrote withdb.vars.commitTs, as Convex types itbigint | CommitTsPlaceholder);v.id("table")maps to the generated<Table>Idclass;v.function()handles map toString;v.any()maps todynamic.- Unions of literals become enums. Other unions become a sealed class with
one
<Union><n>Valuecase per member, as long as Dart can tell the members apart at runtime. Members with the same runtime shape (for examplev.string()andv.id("users"), or objects without a distinct literal discriminator field) make generation fail with an "Ambiguous union" error. - Records with string, id, or literal-union keys become
Map<String, V>. - Field names are converted to camelCase. If a system field collides with a
user field (
_idnext toid), the system field is renamed (systemId,systemCreationTime). Likewise, a system table whose ID class would collide with a user table's (_storageandstorage) gets aSystemprefix (SystemStorageId). - Names that are Dart keywords or built-in identifiers (
get,set,sync, ...) orObjectmembers (toString,hashCode, ...) get aValuesuffix for members and aTypesuffix for type names (kv:setgeneratessetValue()withSetTypeArgs). These names are kept for compatibility with existing bindings. - Generated type names come from the function name, not its module path, so
two modules that both export
listeach declare aListResult. Use import prefixes if one Dart file needs both.
Using other clients #
The generated API classes wrap a core ConvexFunctionCaller, which
ConvexClient and ConvexClientWithAuth implement.
- In Flutter,
ConvexProvider.of(context).functionCaller(dartvex_flutter) returns one for the provider's client: the wrappedConvexClientforConvexClientRuntime, and a stub-backed caller forFakeConvexClientin widget tests (itspaginatedQueryis unsupported). dartvex_local'sConvexLocalClientis not aConvexFunctionCaller(itsmutatereturns aLocalMutationResult); typed calls made through the underlyingConvexClientbypass its cache and offline queue.- For anything else, implement
ConvexFunctionCallerand pass it toConvexApi.--client-importlets the generated files import that interface (plusQueryResult,ConvexSubscription,ConvexPaginatedQuery, andOptimisticUpdate) from a library of your own that re-exports them.
How It Works #
| Stage | Description |
|---|---|
GenerateCommand |
Main CLI command for code generation |
SpecParser |
Parses Convex function_spec.json |
TypeMapper |
Maps Convex types to Dart types |
DartGenerator |
Generates Dart source from function specs |
FileEmitter |
Writes generated files to disk |
The CLI (dart run dartvex_codegen, or runConvexCodegen /
GenerateCommand) is the supported interface. The library also exports the
pipeline stages above and their helper types for programmatic use, but
while the package is pre-1.0 they may change in minor releases.
Workflow #
- Keep your Convex backend in TypeScript, with
args/returnsvalidators. - Push it (
npx convex dev/npx convex deploy). - Run
dartvex_codegen generate. - Import the generated
api.dartin your Dart or Flutter app and call typed wrappers instead of raw function names and raw maps. Regenerate after every backend change and after upgradingdartvex_codegen.
Full Documentation #
See the Dartvex monorepo for full documentation and examples.