@vllnt/convex-helpers 0.2.0 → 0.2.1-canary.2ee4768

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 (64) hide show
  1. package/CHANGELOG.md +64 -5
  2. package/NOTICE +3 -3
  3. package/README.md +382 -260
  4. package/dist/better-auth.d.ts +10 -0
  5. package/dist/better-auth.d.ts.map +1 -1
  6. package/dist/better-auth.js +9 -0
  7. package/dist/better-auth.js.map +1 -1
  8. package/dist/builders.d.ts +5 -4
  9. package/dist/builders.d.ts.map +1 -1
  10. package/dist/builders.js +5 -4
  11. package/dist/builders.js.map +1 -1
  12. package/dist/identity.d.ts +25 -0
  13. package/dist/identity.d.ts.map +1 -1
  14. package/dist/identity.js +23 -0
  15. package/dist/identity.js.map +1 -1
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +2 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/mcp/pagination/types.d.ts +2 -0
  21. package/dist/mcp/pagination/types.d.ts.map +1 -1
  22. package/dist/mcp/resources/helpers.d.ts +8 -0
  23. package/dist/mcp/resources/helpers.d.ts.map +1 -1
  24. package/dist/mcp/resources/helpers.js +8 -0
  25. package/dist/mcp/resources/helpers.js.map +1 -1
  26. package/dist/mcp/resources/types.d.ts +1 -0
  27. package/dist/mcp/resources/types.d.ts.map +1 -1
  28. package/dist/mcp/server.d.ts +10 -0
  29. package/dist/mcp/server.d.ts.map +1 -1
  30. package/dist/mcp/server.js +10 -0
  31. package/dist/mcp/server.js.map +1 -1
  32. package/dist/mcp/tools/helpers.d.ts +21 -0
  33. package/dist/mcp/tools/helpers.d.ts.map +1 -1
  34. package/dist/mcp/tools/helpers.js +21 -0
  35. package/dist/mcp/tools/helpers.js.map +1 -1
  36. package/dist/mcp/tools/types.d.ts +13 -3
  37. package/dist/mcp/tools/types.d.ts.map +1 -1
  38. package/dist/mcp/types.d.ts +8 -0
  39. package/dist/mcp/types.d.ts.map +1 -1
  40. package/dist/mcp/validators.d.ts +18 -0
  41. package/dist/mcp/validators.d.ts.map +1 -1
  42. package/dist/mcp/validators.js +18 -0
  43. package/dist/mcp/validators.js.map +1 -1
  44. package/dist/validators.d.ts +6 -7
  45. package/dist/validators.d.ts.map +1 -1
  46. package/dist/validators.js +11 -7
  47. package/dist/validators.js.map +1 -1
  48. package/docs/API.md +155 -81
  49. package/llms.txt +75 -39
  50. package/package.json +20 -18
  51. package/src/better-auth.ts +10 -0
  52. package/src/builders.ts +5 -4
  53. package/src/identity.ts +25 -0
  54. package/src/index.ts +2 -0
  55. package/src/mcp/pagination/types.ts +2 -0
  56. package/src/mcp/resources/helpers.ts +8 -0
  57. package/src/mcp/resources/types.ts +1 -0
  58. package/src/mcp/server.ts +10 -0
  59. package/src/mcp/tools/helpers.ts +21 -0
  60. package/src/mcp/tools/types.ts +13 -3
  61. package/src/mcp/types.ts +8 -0
  62. package/src/mcp/validators.ts +18 -0
  63. package/src/validators.ts +10 -7
  64. package/docs/READINESS.md +0 -175
package/docs/API.md CHANGED
@@ -2,10 +2,11 @@
2
2
 
3
3
  **Compatibility:** `convex@^1.45.0`; ESM-only.
4
4
 
5
- **Availability:** this reference follows current main. `./better-auth`,
6
- `./identity`, `./builders` and `./validators` first ship in `0.2.0`; `0.1.0` has
7
- only the root utilities and `./mcp`. See the
8
- [installation guide](../README.md#installation). Planned modules are not
5
+ **Availability:** on GitHub this reference describes `main`; the copy shipped at
6
+ `node_modules/@vllnt/convex-helpers/docs/API.md` describes the installed
7
+ version. `./better-auth`, `./identity`, `./builders` and `./validators` first
8
+ ship in `0.2.0`; `0.1.0` has only the root utilities and `./mcp`. See the
9
+ [install section](../README.md#install). Planned modules are not
9
10
  exports.
10
11
 
11
12
  This library provides pure functions and host-`ctx` glue utilities. It is a
@@ -21,8 +22,15 @@ order.
21
22
 
22
23
  ```ts
23
24
  import { asyncMap } from "@vllnt/convex-helpers";
25
+ import { v } from "convex/values";
24
26
 
25
- const docs = await asyncMap(ids, (id) => ctx.db.get(id));
27
+ import { query } from "./_generated/server";
28
+
29
+ export const getProjects = query({
30
+ args: { ids: v.array(v.id("projects")) },
31
+ handler: async (ctx, { ids }) =>
32
+ asyncMap(ids, (id) => ctx.db.get("projects", id)),
33
+ });
26
34
  ```
27
35
 
28
36
  | Param | Type | Description |
@@ -40,8 +48,15 @@ Filters null and undefined values from an array.
40
48
 
41
49
  ```ts
42
50
  import { asyncMap, pruneNull } from "@vllnt/convex-helpers";
51
+ import { v } from "convex/values";
52
+
53
+ import { query } from "./_generated/server";
43
54
 
44
- const docs = pruneNull(await asyncMap(ids, (id) => ctx.db.get(id)));
55
+ export const getExistingProjects = query({
56
+ args: { ids: v.array(v.id("projects")) },
57
+ handler: async (ctx, { ids }) =>
58
+ pruneNull(await asyncMap(ids, (id) => ctx.db.get("projects", id))),
59
+ });
45
60
  ```
46
61
 
47
62
  | Param | Type | Description |
@@ -59,8 +74,15 @@ it is.
59
74
 
60
75
  ```ts
61
76
  import { nullThrows } from "@vllnt/convex-helpers";
77
+ import { v } from "convex/values";
78
+
79
+ import { query } from "./_generated/server";
62
80
 
63
- const doc = nullThrows(await ctx.db.get(id), `Document ${id} not found`);
81
+ export const getProject = query({
82
+ args: { id: v.id("projects") },
83
+ handler: async (ctx, { id }) =>
84
+ nullThrows(await ctx.db.get("projects", id), `Project ${id} not found`),
85
+ });
64
86
  ```
65
87
 
66
88
  | Param | Type | Description |
@@ -79,15 +101,22 @@ const doc = nullThrows(await ctx.db.get(id), `Document ${id} not found`);
79
101
  Error thrown when a required document is null or undefined.
80
102
 
81
103
  ```ts
82
- import { NullDocumentError } from "@vllnt/convex-helpers";
83
-
84
- try {
85
- const doc = nullThrows(await ctx.db.get(id));
86
- } catch (e) {
87
- if (e instanceof NullDocumentError) {
88
- // handle missing document
89
- }
90
- }
104
+ import { NullDocumentError, nullThrows } from "@vllnt/convex-helpers";
105
+ import { v } from "convex/values";
106
+
107
+ import { query } from "./_generated/server";
108
+
109
+ export const projectName = query({
110
+ args: { id: v.id("projects") },
111
+ handler: async (ctx, { id }) => {
112
+ try {
113
+ return nullThrows(await ctx.db.get("projects", id)).name;
114
+ } catch (error) {
115
+ if (error instanceof NullDocumentError) return null;
116
+ throw error;
117
+ }
118
+ },
119
+ });
91
120
  ```
92
121
 
93
122
  ## MCP tools (`./mcp`)
@@ -105,19 +134,26 @@ framework's route.
105
134
 
106
135
  ```ts
107
136
  import { createMCPServer, query } from "@vllnt/convex-helpers/mcp";
137
+ import { v } from "convex/values";
138
+
139
+ import { api } from "@/convex/_generated/api";
108
140
 
109
- export const mcp = createMCPServer({
141
+ const mcp = createMCPServer({
110
142
  auth: { validate: async (key) => key === process.env.MCP_API_KEY },
111
143
  tools: {
112
- list: query(api.tasks.list, {
144
+ list_projects: query(api.projects.list, {
113
145
  args: v.object({}),
114
- description: "List tasks",
146
+ description: "List all projects",
115
147
  }),
116
148
  },
117
149
  });
150
+
118
151
  export const { GET, POST } = mcp.handler();
119
152
  ```
120
153
 
154
+ This is a Next.js route file such as `app/api/mcp/route.ts`; the `@/convex/...`
155
+ import assumes a `@/*` path alias to the project root.
156
+
121
157
  Security boundaries (host-owned): resources do not run `onToolCall`/`before`
122
158
  hooks (only tools do), so any valid bearer key reads every registered resource;
123
159
  `_`-prefixed resource URI parameters are rejected. `CallContext.apiKey` is a
@@ -130,33 +166,33 @@ per-instance secret. An `onResourceRead` hook is not provided.
130
166
 
131
167
  `ServerConfig`:
132
168
 
133
- | Field | Type | Description |
134
- | ----------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
135
- | `auth` | `AuthConfig` | **Required.** `validate(apiKey) => boolean` gates every request (default-deny — `createMCPServer` throws without it). Optional `convexToken(apiKey)` resolves a Convex auth token per call. |
136
- | `tools` | `Record<string, ToolDef>` | Named tools built with `query`/`mutation`/`action`. |
137
- | `resources` | `Record<string, ResourceDef>` | Named resources built with `resource`. |
138
- | `convexUrl` | `string` | Convex deployment URL. Defaults to `CONVEX_URL` / `NEXT_PUBLIC_CONVEX_URL`. |
139
- | `client` | `ConvexClient` | Inject a client (e.g. `convex-test`'s `t`) instead of a URL. Mutually exclusive with `auth.convexToken`. |
140
- | `hooks` | `LifecycleHooks` | `onToolCall(ctx)` fires `before`/`success`/`error`; `before` may `abort` or inject server-side args via `extendArgs`. |
141
- | `name`, `version` | `string` | Server identity advertised over MCP. |
142
- | `pagination` | `PaginationConfig` | Opt-in `tools/list` pagination — see below. |
169
+ | Field | Type | Description |
170
+ | ----------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
171
+ | `auth` | `AuthConfig` | **Required.** `validate(apiKey) => boolean` gates every request (default-deny — `createMCPServer` throws without it). Optional `convexToken(apiKey)` resolves a Convex auth token once per HTTP request, used only by the default client. |
172
+ | `tools` | `Record<string, ToolDef>` | Named tools built with `query`/`mutation`/`action`. |
173
+ | `resources` | `Record<string, ResourceDef>` | Named resources built with `resource`. |
174
+ | `convexUrl` | `string` | Convex deployment URL. Defaults to `CONVEX_URL` / `NEXT_PUBLIC_CONVEX_URL`. |
175
+ | `client` | `ConvexClient` | Inject a client (e.g. `convex-test`'s `t`) instead of a URL. Mutually exclusive with `auth.convexToken`. |
176
+ | `hooks` | `LifecycleHooks` | `onToolCall(ctx)` fires `before`/`success`/`error`; `before` may `abort` or inject server-side args via `extendArgs`. When a tool sets `onError`, only `onError` runs in the error phase. |
177
+ | `name`, `version` | `string` | Server identity advertised over MCP. |
178
+ | `pagination` | `PaginationConfig` | Opt-in `tools/list` pagination — see below. |
143
179
 
144
180
  ### query / mutation / action
145
181
 
146
182
  `query(ref, options)` / `mutation(ref, options)` / `action(ref, options)` wrap a
147
183
  Convex function reference as a typed `ToolDef`.
148
184
 
149
- | Option | Type | Description |
150
- | ------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
151
- | `args` | `ConvexValidator` | A `v.object({...})` validator; converted to the tool's JSON-Schema input. |
152
- | `description` | `string` | Human/LLM-facing tool description. |
153
- | `tags` | `Record<string, string>` | Arbitrary metadata. |
154
- | `timeout` | `number` | Per-call timeout (ms, finite, 0 to 2147483647; 0 disables), supported only for queries. Mutation/action timeouts are rejected because their execution cannot be cancelled safely. |
155
- | `onError` | `(ctx) => HookReturn` | Per-tool error hook. |
185
+ | Option | Type | Description |
186
+ | ------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
187
+ | `args` | `ConvexValidator` | A `v.object({...})` validator; converted to the tool's JSON-Schema input. |
188
+ | `description` | `string` | Human/LLM-facing tool description. |
189
+ | `tags` | `Record<string, string>` | Arbitrary metadata. |
190
+ | `timeout` | `number` | Per-call timeout (ms, finite, 0 to 2147483647; 0 disables), supported only for queries. Mutation/action timeouts are rejected because their execution cannot be cancelled safely. |
191
+ | `onError` | `(ctx) => OnCallResult \| undefined \| Promise<OnCallResult \| undefined> \| Promise<void>` | Per-tool error hook; when set, it runs in the error phase instead of `onToolCall`. |
156
192
 
157
193
  ### resource(ref, options)
158
194
 
159
- Wraps a Convex function reference as an MCP resource
195
+ Wraps a Convex query reference as an MCP resource
160
196
  (`{ args?, description? }`). URI parameters are parsed through `args` before
161
197
  dispatch. Parameter names starting with `_` are rejected before dispatch
162
198
  (reserved for server-injected context). Resources run no lifecycle hooks, so
@@ -164,7 +200,7 @@ authorize inside the backing function. JSON `int64` strings become `bigint`,
164
200
  base64 `bytes` strings become `ArrayBuffer`, and native Convex results use
165
201
  Convex's lossless tagged JSON encoding.
166
202
 
167
- ### Pagination
203
+ ### Tool-list pagination
168
204
 
169
205
  `PaginationConfig` opts `tools/list` into cursor pagination. `tools/list`
170
206
  **without** a cursor always returns ALL tools (backward-compatible); pagination
@@ -177,6 +213,14 @@ activates only when the client sends a cursor.
177
213
 
178
214
  Cursors are HMAC-signed per server instance and verified in constant time.
179
215
 
216
+ ### Exported types
217
+
218
+ `AuthConfig`, `CallContext`, `ConvexClient`, `ConvexMCPServer` (the
219
+ `{ handler() }` return of `createMCPServer`), `ConvexValidator`, `FunctionType`
220
+ (`"query" | "mutation" | "action"`), `LifecycleHooks`, `OnCallResult`,
221
+ `PaginationConfig`, `ResourceDef`, `ServerConfig`, `ToolDef`, `ToolPage` and
222
+ `ToolSummary`.
223
+
180
224
  ### Validator utilities
181
225
 
182
226
  | Export | Description |
@@ -185,14 +229,14 @@ Cursors are HMAC-signed per server instance and verified in constant time.
185
229
  | `convexArgsToZod(argsValidator)` | Convert a `v.object()` args validator to a `zod` object schema. |
186
230
  | `UnsupportedValidatorError` | Thrown for validator kinds with no MCP/JSON-Schema mapping. |
187
231
 
188
- ### Request behavior & error codes
232
+ ### Request behavior and error codes
189
233
 
190
- | Condition | Response |
191
- | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
192
- | Missing/malformed `Authorization: Bearer <key>` | `401` `{ error }` |
193
- | `auth.validate` returns false | `401` `{ error: "Invalid API key." }` |
194
- | `POST` without `application/json` | `415` JSON-RPC error `-32700` |
195
- | Convex execution failure | Generic message by default; hooks see the real error and may explicitly return a public message. No raw error logging. |
234
+ | Condition | Response |
235
+ | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
236
+ | Missing/malformed `Authorization: Bearer <key>` | `401` `{ error }` |
237
+ | `auth.validate` returns false | `401` `{ error: "Invalid API key." }` |
238
+ | `POST` whose `Content-Type` lacks `application/json` (checked after auth) | `415` JSON-RPC error `-32700` |
239
+ | Convex execution failure | Generic message by default; hooks see the real error and may explicitly return a public message. No raw error logging. |
196
240
 
197
241
  Auth and lifecycle callbacks have a 10-second deadline per callback. Thrown or
198
242
  stalled `before` hooks fail closed with `Tool call rejected`, without dispatch.
@@ -227,11 +271,23 @@ you control. These are syntax helpers, not proof of ownership or CSRF
227
271
  protection. Returning undefined leaves host/provider defaults in effect; it is
228
272
  not a deny-all trusted-origin configuration.
229
273
 
274
+ Exported type: `CookieSettings` (the return of `cookieSettingsForSite`).
275
+
230
276
  ```ts
231
277
  import {
232
278
  cookieSettingsForSite,
233
279
  trustedOriginsFromCsv,
234
280
  } from "@vllnt/convex-helpers/better-auth";
281
+
282
+ const siteUrl = process.env.CONVEX_SITE_URL ?? "http://localhost:3211";
283
+
284
+ export const originOptions = {
285
+ ...cookieSettingsForSite(siteUrl),
286
+ trustedOrigins: trustedOriginsFromCsv(
287
+ siteUrl,
288
+ process.env.BETTER_AUTH_TRUSTED_ORIGINS ?? "",
289
+ ),
290
+ };
235
291
  ```
236
292
 
237
293
  ## `./identity` (shipped)
@@ -254,6 +310,9 @@ their own code. The host configures Better Auth and its anonymous plugin.
254
310
  | `requireFromAuth(ctx, lookup)` | Same row, or `USER_NOT_INITIALIZED` (also for missing session). |
255
311
  | `getOrCreateFromAuth(ctx, { lookup, insert })` | Lookup then insert if absent; both callbacks receive subject. |
256
312
  | `retargetRows(rows, apply)` | At most 1000 rows, sequential callbacks returning `deleted`, `patched`, or `skipped`; returns counts. Oversized pages reject before callbacks. |
313
+ | `isAnonymousIdentity(identity)` | `true` only for a literal boolean `isAnonymous: true` claim. |
314
+
315
+ Exported types: `AuthCtx` (`{ auth, trustedIssuer }`) and `AuthIdentity`.
257
316
 
258
317
  Race-safe bootstrap requires the same Convex mutation transaction for indexed
259
318
  lookup and insert, with every competing creator using that lookup. Remote calls
@@ -265,20 +324,31 @@ host owns observability; helpers do not log identity data or tokens. Tests are
265
324
  convex-test mock integration, not real Better Auth or backend OCC proof.
266
325
 
267
326
  ```ts
268
- import {
269
- getOrCreateFromAuth,
270
- retargetRows,
271
- } from "@vllnt/convex-helpers/identity";
272
-
273
- const user = await getOrCreateFromAuth(ctx, {
274
- lookup: (subject) =>
275
- ctx.db
276
- .query("users")
277
- .withIndex("by_betterauth_id", (q) => q.eq("betterAuthId", subject))
278
- .unique(),
279
- insert: async (subject) => {
280
- const id = await ctx.db.insert("users", { betterAuthId: subject });
281
- return (await ctx.db.get(id))!;
327
+ import { nullThrows } from "@vllnt/convex-helpers";
328
+ import { getOrCreateFromAuth } from "@vllnt/convex-helpers/identity";
329
+
330
+ import { mutation } from "./_generated/server";
331
+
332
+ const trustedIssuer = process.env.CONVEX_SITE_URL ?? "";
333
+
334
+ export const ensureUser = mutation({
335
+ args: {},
336
+ handler: async (ctx) => {
337
+ const user = await getOrCreateFromAuth(
338
+ { auth: ctx.auth, trustedIssuer },
339
+ {
340
+ insert: async (subject) => {
341
+ const id = await ctx.db.insert("users", { subject });
342
+ return nullThrows(await ctx.db.get("users", id));
343
+ },
344
+ lookup: (subject) =>
345
+ ctx.db
346
+ .query("users")
347
+ .withIndex("by_subject", (q) => q.eq("subject", subject))
348
+ .unique(),
349
+ },
350
+ );
351
+ return user._id;
282
352
  },
283
353
  });
284
354
  ```
@@ -287,7 +357,7 @@ const user = await getOrCreateFromAuth(ctx, {
287
357
 
288
358
  Wrap a Convex function builder so every function made with it receives extra
289
359
  `ctx` fields and, optionally, consumes extra args. Signatures and runtime
290
- behaviour match `convex-helpers/server/customFunctions` 0.1.124; a parity test
360
+ behaviour match `convex-helpers/server/customFunctions` 0.1.136; a parity test
291
361
  runs both on the same convex-test backend.
292
362
 
293
363
  | Export | Contract |
@@ -298,30 +368,33 @@ runs both on the same convex-test backend.
298
368
  | `customCtx(modifyCtx)` | Customization with no args: `modifyCtx(ctx, extra)` returns the ctx fields to add. `extra` holds the definition's keys other than `args`, `handler` and `returns`. |
299
369
  | `Customization` | `{ args, input }`. `args` (property validators) are merged into the function's args and taken out of the handler's args; `input(ctx, consumedArgs, extra)` returns `{ ctx, args, onSuccess? }`. `onSuccess` runs after the handler. |
300
370
  | `CustomBuilder`, `CustomCtx<Builder>` | Types of a custom builder and of the ctx its handlers receive. |
371
+ | `CustomInput`, `Registration` | Types of the `input` callback's return and of a registered function. |
301
372
 
302
- Merging fails with an error when a consumed arg and a function arg share a name
303
- but not a validator kind, when the function's args validator is neither an
304
- object nor a union, or when the customization consumes args but the function
305
- declares none. Builders add no authorization of their own.
373
+ When the customization consumes args, merging fails with an error when a
374
+ consumed arg and a function arg share a name but not a validator kind, when the
375
+ function's args validator is neither an object nor a union, or when the
376
+ function declares no args. Builders add no authorization of their own.
306
377
 
307
378
  ## `./validators` (shipped)
308
379
 
309
- | Export | Contract |
310
- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
311
- | `validate(validator, value, options?)` | `true` when `value` matches (type guard). `options.throw` throws `ValidationError` on the first mismatch; `options.allowUnknownFields` accepts undeclared object fields. Undefined fields pass. |
312
- | `parse(validator, value)` | Validates with unknown fields allowed, throws `ValidationError` on mismatch, and returns a copy without undeclared fields (through arrays, records and unions). |
313
- | `doc(schema, tableName)` | The table's validator plus `_id` and `_creationTime`; union tables get them on every member. Throws for other validator kinds. |
314
- | `ValidationError` | Has `expected`, `got` and an optional `path`; the message names all three. |
315
-
316
- Behaviour matches `convex-helpers/validators` 0.1.124 for these exports, held by
317
- a parity test, with two fail-closed differences:
318
-
319
- - Declared object fields are looked up as own properties. Upstream also treats
320
- inherited names (`constructor`, `toString`, `__proto__`) as declared, so it
321
- accepts and keeps them; here they are unknown fields (rejected by a strict
322
- `validate`, dropped by `parse`).
323
- - The `db` option (checking a `v.id`'s table) is refused with an error instead
324
- of supported; `v.id` checks for a string.
380
+ | Export | Contract |
381
+ | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
382
+ | `validate(validator, value, options?)` | `true` when `value` matches (type guard). `options.throw` throws `ValidationError` on the first mismatch; `options.allowUnknownFields` accepts undeclared object fields. Undeclared fields whose value is `undefined` pass. |
383
+ | `parse(validator, value)` | Validates with unknown fields allowed, throws `ValidationError` on mismatch, and returns a copy without undeclared fields (through arrays, records and unions). |
384
+ | `doc(schema, tableName)` | The table's validator plus `_id` and `_creationTime`; union tables get them on every member. Throws for other validator kinds. |
385
+ | `ValidationError` | Has `expected`, `got` and an optional `path`; the message names `expected`, `got`, and `path` when set. |
386
+
387
+ Exported types: `AnyValidator`, `ValidateOptions`, `SystemFields` and
388
+ `AddFieldsToValidator`.
389
+
390
+ Behaviour matches `convex-helpers/validators` 0.1.136 for these exports, held by
391
+ a parity test. Declared object fields are looked up as own properties, so
392
+ inherited names (`constructor`, `toString`, `__proto__`) are unknown fields
393
+ (rejected by a strict `validate`, dropped by `parse`). Records accept only plain
394
+ objects: arrays and class instances such as `Date` or `Map` fail with
395
+ `` Expected `record` ``. One fail-closed difference: the `db` option (checking a
396
+ `v.id`'s table) is refused with an error instead of supported; `v.id` checks for
397
+ a string.
325
398
 
326
399
  `ValidationError.expected` is always a string (upstream passes a literal's raw
327
400
  value); messages are identical.
@@ -329,7 +402,8 @@ value); messages are identical.
329
402
  ## Planned modules
330
403
 
331
404
  The following modules are on the roadmap but not yet shipped. See
332
- [ROADMAP.md](../ROADMAP.md) for milestones and exit criteria.
405
+ [ROADMAP.md](https://github.com/vllnt/convex-helpers/blob/main/ROADMAP.md) (in
406
+ the repository, not the package) for milestones and exit criteria.
333
407
 
334
408
  | Module | Status | Description |
335
409
  | ----------------- | ------------------------ | --------------------------------------------------------- |
package/llms.txt CHANGED
@@ -1,47 +1,83 @@
1
1
  # @vllnt/convex-helpers
2
2
 
3
- > Typed Convex host-side utilities, trusted-origin and cookie configuration helpers,
4
- > identity-row glue, and optional MCP tools.
5
-
6
- `@vllnt/convex-helpers` is a helpers library (not a sandboxed Convex component) for
7
- Convex backends. It provides pure functions and host-`ctx` glue utilities that run with the host's
8
- `ctx` — no own tables, no `app.use()` mounting. The library targets `convex@^1.45.0`. Stateful
9
- concerns (rate limiting, idempotency, flags, etc.) belong in `@convex-dev/*` or `@vllnt/convex-*`
10
- components. Optional entries: `./better-auth` (trusted origins + HTTPS cookies), `./identity` (`getOrCreateFromAuth` / `retargetRows`), `./builders` (`customQuery` / `customMutation` / `customAction` / `customCtx`, matching `convex-helpers/server/customFunctions`), `./validators` (`validate` / `parse` / `doc`, matching `convex-helpers/validators`; it refuses the `db` id-table option and treats inherited names such as `constructor` as unknown fields), and a tree-shakeable `./mcp` entry exposes Convex functions as Model Context
11
- Protocol tools (`@vllnt/convex-helpers/mcp`); it needs the optional peer deps
12
- `@modelcontextprotocol/sdk` and `zod`, so backend-only consumers pull neither.
13
-
14
- Identity callbacks require a trusted single issuer and one Convex mutation transaction
15
- for race-safe bootstrap. Host-owned `AuthCtx.trustedIssuer` is required; helpers fail closed when it is
16
- missing or empty and enforce issuer matching before lookup/insert. MCP resources
17
- run no lifecycle hooks (authorize in the backing function), and the MCP endpoint
18
- sets no body/stream/deadline caps. MCP auth/hooks have a 10-second deadline; failing
19
- before hooks deny dispatch and raw exceptions are not logged. `retargetRows` processes at most 1000 rows sequentially; it
20
- is not an authorized account merge. Hosts install/configure Better Auth themselves.
21
- Origin helpers validate syntax, not deployment ownership; cross-site cookie attributes
22
- are not CSRF protection. Existing identity integration tests use convex-test mocks,
23
- not real Better Auth or backend OCC proof. Errors/env/tracing remain planned. Builders add no authorization: the host's
24
- `input` decides who may call.
25
-
26
- ## Release channels
27
-
28
- This index describes current main. `./better-auth`, `./identity`, `./builders` and
29
- `./validators` first ship in `0.2.0`; `0.1.0` has only the root utilities and `./mcp`. Prereleases are published
30
- to the `canary` dist-tag; pin and test them before deployment.
31
- MCP requires optional peers `@modelcontextprotocol/sdk@^1.29.0` and `zod@^4.3.6`;
32
- the package is ESM-only and requires `convex@^1.45.0`.
3
+ > TypeScript helpers for Convex backends: custom function builders, runtime
4
+ > validators, auth identity rows, Better Auth origins and an MCP tool server.
5
+
6
+ `@vllnt/convex-helpers` is a helpers library for Convex backends, not a Convex
7
+ component: it runs with the host's `ctx`, owns no tables and needs no
8
+ `app.use()`. It requires `convex@^1.45.0` and is ESM-only. Entries: the root
9
+ (`asyncMap`, `pruneNull`, `nullThrows`), `./builders` (`customQuery`,
10
+ `customMutation`, `customAction`, `customCtx`, matching
11
+ `convex-helpers/server/customFunctions` 0.1.136), `./validators` (`validate`,
12
+ `parse`, `doc`, matching `convex-helpers/validators` 0.1.136 except that the
13
+ `db` option is refused), `./identity` (`requireIdentity`, `getFromAuth`,
14
+ `requireFromAuth`, `getOrCreateFromAuth`, `retargetRows`), `./better-auth`
15
+ (trusted origins and HTTPS cookie options for `@convex-dev/better-auth`) and
16
+ `./mcp` (Convex functions as Model Context Protocol tools over Streamable HTTP;
17
+ needs the optional peers `@modelcontextprotocol/sdk@^1.29.0` and `zod@^4.3.6`).
18
+
19
+ ## For coding agents
20
+
21
+ Docs for the installed version ship in the package: `README.md`, `docs/API.md`,
22
+ `CHANGELOG.md` and this `llms.txt`. Types are in `dist/`, source in `src/`.
23
+
24
+ ## When to use
25
+
26
+ - Use it for Convex function builders with shared `ctx` fields (`./builders`)
27
+ and runtime checks against `v.*` validators (`./validators`).
28
+ - Use it to map the signed-in identity to a host user row (`./identity`).
29
+ - Use it for `@convex-dev/better-auth` origins and cookies (`./better-auth`), or
30
+ to serve Convex functions as MCP tools over Streamable HTTP (`./mcp`).
31
+ - Do not use it for state. Rate limits: `@convex-dev/rate-limiter`. API keys:
32
+ `@vllnt/convex-api-keys`. Other: a `@convex-dev/*` or `@vllnt/convex-*` component.
33
+ - Do not use it for relationships, RLS or triggers: use `convex-helpers`.
34
+
35
+ ## Limits
36
+
37
+ - `./identity` needs a host-configured, non-empty `AuthCtx.trustedIssuer`; it
38
+ fails closed with `UNAUTHENTICATED` when missing, empty or mismatched.
39
+ `getOrCreateFromAuth` creates one row only when lookup and insert run in the
40
+ same mutation. `retargetRows` takes at most 1000 rows in sequence and is not
41
+ an account merge.
42
+ - `./better-auth` checks origin syntax, not deployment ownership; SameSite=None
43
+ cookies are not CSRF protection. The host constructs `betterAuth(...)`.
44
+ - `./builders` adds no authorization.
45
+ - `./mcp`: resources run no lifecycle hooks; no body, stream or deadline caps;
46
+ auth and hook callbacks have a 10-second deadline; raw errors are not logged.
47
+ - On GitHub this file describes `main`; the copy in each npm version describes
48
+ that version. `./better-auth`, `./identity`, `./builders` and `./validators`
49
+ first ship in 0.2.0. The `canary` dist-tag moves: pin the exact version.
33
50
 
34
51
  ## Docs
35
52
 
36
- - [README](README.md): Project overview, installation, usage examples, and planned surface
37
- - [API Reference](docs/API.md): Exported utilities, signatures, and compatibility
38
- - [Changelog](CHANGELOG.md): Version history and release notes
39
- - [Roadmap](ROADMAP.md): Planned modules and milestones
40
- - [Contributing](CONTRIBUTING.md): Development setup, validation commands, and release workflow
53
+ - [API reference](./docs/API.md): every export with signatures and behavior
54
+ - [Errors and fixes](./README.md#errors-and-fixes): every error text, its cause
55
+ and its fix
56
+ - [README](./README.md): install, quick start, common tasks, limits and
57
+ compatibility
58
+ - [Changelog](./CHANGELOG.md): version history
59
+ - [Notice](./NOTICE): attribution for the convex-helpers behavior and types
60
+ these entries follow
61
+ - [License](./LICENSE): MIT
41
62
 
42
63
  ## Optional
43
64
 
44
- - [AGENTS](AGENTS.md): Canonical agent instructions for this repository
45
- - [Security Policy](SECURITY.md): Vulnerability reporting policy
46
- - [Code of Conduct](CODE_OF_CONDUCT.md): Community participation guidelines
47
- - [License](LICENSE): MIT license
65
+ Repository files, not in the npm package; they describe `main`.
66
+
67
+ - [Roadmap](https://github.com/vllnt/convex-helpers/blob/main/ROADMAP.md):
68
+ planned modules
69
+ - [Contributing](https://github.com/vllnt/convex-helpers/blob/main/CONTRIBUTING.md):
70
+ development setup, checks and release workflow
71
+ - [Security policy](https://github.com/vllnt/convex-helpers/blob/main/SECURITY.md):
72
+ vulnerability reporting
73
+ - [Code of Conduct](https://github.com/vllnt/convex-helpers/blob/main/CODE_OF_CONDUCT.md):
74
+ community participation guidelines
75
+
76
+ ## Ecosystem
77
+
78
+ - [Package page](https://oss.vllnt.com/packages/convex-helpers)
79
+ - [Release feed](https://oss.vllnt.com/packages/convex-helpers/rss.xml)
80
+ - [All @vllnt packages](https://oss.vllnt.com/llms.txt)
81
+ - [Search vllnt packages and docs](https://index.vllnt.com)
82
+ - [vllnt](https://vllnt.com/llms.txt)
83
+ - [Author](https://bntvllnt.com)
package/package.json CHANGED
@@ -1,18 +1,18 @@
1
1
  {
2
2
  "name": "@vllnt/convex-helpers",
3
- "version": "0.2.0",
4
- "description": "Typed Convex host-side utilities, trusted-origin and cookie configuration helpers, identity-row glue, and optional MCP tools.",
3
+ "version": "0.2.1-canary.2ee4768",
4
+ "description": "TypeScript helpers for Convex backends: custom function builders, runtime validators, auth identity rows, Better Auth origins and an MCP tool server.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
- "packageManager": "pnpm@10.34.8",
7
+ "packageManager": "pnpm@10.34.9",
8
8
  "files": [
9
9
  "dist",
10
10
  "src",
11
- "!src/**/*.test.ts",
12
- "docs",
11
+ "docs/API.md",
13
12
  "CHANGELOG.md",
14
13
  "NOTICE",
15
14
  "llms.txt",
15
+ "!src/**/*.test.*",
16
16
  "!src/**/*.spec.*"
17
17
  ],
18
18
  "exports": {
@@ -49,12 +49,13 @@
49
49
  "build": "tsc --project ./tsconfig.build.json",
50
50
  "typecheck": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck.tsbuildinfo && tsc --noEmit --project tests/tsconfig.json",
51
51
  "typecheck:ci": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck-ci.tsbuildinfo --project tsconfig.ci.json && tsc --noEmit --project tests/tsconfig.json",
52
- "lint": "pnpm check:agents && pnpm check:docs && eslint --cache --cache-location node_modules/.cache/eslint/ .",
52
+ "lint": "pnpm check:agents && pnpm check:docs && pnpm check:package && eslint --cache --cache-location node_modules/.cache/eslint/ .",
53
53
  "test": "vitest run --passWithNoTests",
54
54
  "test:watch": "vitest --typecheck --clearScreen false",
55
55
  "test:coverage": "vitest run --coverage --coverage.reporter=text",
56
56
  "generate:llms": "node scripts/generate-llms.mjs",
57
57
  "check:docs": "node scripts/check-docs.mjs",
58
+ "check:package": "node scripts/check-package.mjs",
58
59
  "preversion": "pnpm install --frozen-lockfile && pnpm build && pnpm test && pnpm typecheck && pnpm generate:llms",
59
60
  "check:agents": "node -e \"const f=require('node:fs');if(!f.existsSync('AGENTS.md')||f.existsSync('CLAUDE.md')||f.existsSync('.claude'))process.exit(1)\""
60
61
  },
@@ -75,17 +76,17 @@
75
76
  "@modelcontextprotocol/sdk": "^1.32.2",
76
77
  "@types/node": "^26.6.6",
77
78
  "@typescript/native": "npm:typescript@7.0.2",
78
- "@vitest/coverage-v8": "^5.1.0",
79
+ "@vitest/coverage-v8": "^5.1.1",
79
80
  "@vllnt/eslint-config": "2.1.0",
80
- "@vllnt/typescript": "2.0.0",
81
- "convex": "^1.50.0",
82
- "convex-helpers": "0.1.124",
83
- "convex-test": "^0.0.71",
81
+ "@vllnt/typescript": "3.0.0",
82
+ "convex": "^1.51.0",
83
+ "convex-helpers": "0.1.136",
84
+ "convex-test": "^0.0.73",
84
85
  "eslint": "^9.39.5",
85
86
  "prettier": "^3.10.1",
86
87
  "typescript": "npm:@typescript/typescript6@^6.0.2",
87
88
  "vite": "^8.3.8",
88
- "vitest": "^5.1.0",
89
+ "vitest": "^5.1.1",
89
90
  "zod": "^4.6.7"
90
91
  },
91
92
  "pnpm": {
@@ -94,9 +95,7 @@
94
95
  "@vllnt/*"
95
96
  ],
96
97
  "overrides": {
97
- "minimatch@>=7.0.0 <11.0.1": "11.0.5",
98
- "hono": "4.13.19",
99
- "@hono/node-server": "2.1.8",
98
+ "minimatch@>=7.0.0 <11.0.1": "11.0.9",
100
99
  "deepmerge-ts@<8.0.0": "8.0.2",
101
100
  "handlebars@<4.7.10": "4.7.10"
102
101
  },
@@ -105,12 +104,12 @@
105
104
  ]
106
105
  },
107
106
  "engines": {
108
- "node": ">=18"
107
+ "node": ">=20"
109
108
  },
110
109
  "publishConfig": {
111
110
  "access": "public"
112
111
  },
113
- "homepage": "https://github.com/vllnt/convex-helpers#readme",
112
+ "homepage": "https://oss.vllnt.com/packages/convex-helpers",
114
113
  "bugs": {
115
114
  "url": "https://github.com/vllnt/convex-helpers/issues"
116
115
  },
@@ -131,7 +130,10 @@
131
130
  "convex-helpers",
132
131
  "typescript",
133
132
  "backend",
134
- "utils",
133
+ "custom-functions",
134
+ "validators",
135
+ "identity",
136
+ "better-auth",
135
137
  "mcp",
136
138
  "model-context-protocol"
137
139
  ]