zodvex 0.7.7 → 0.7.8-beta.2

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 +30 -10
  2. package/dist/cli/index.js +133 -86
  3. package/dist/cli/index.js.map +1 -1
  4. package/dist/client/index.js +17 -6
  5. package/dist/client/index.js.map +1 -1
  6. package/dist/codegen/index.js +7 -4
  7. package/dist/codegen/index.js.map +1 -1
  8. package/dist/core/index.js +13 -5
  9. package/dist/core/index.js.map +1 -1
  10. package/dist/index.js +13 -5
  11. package/dist/index.js.map +1 -1
  12. package/dist/internal/boundaryHelpers.d.ts +9 -0
  13. package/dist/internal/boundaryHelpers.d.ts.map +1 -1
  14. package/dist/internal/customization.d.ts +27 -1
  15. package/dist/internal/customization.d.ts.map +1 -1
  16. package/dist/internal/db.d.ts +43 -17
  17. package/dist/internal/db.d.ts.map +1 -1
  18. package/dist/internal/init.d.ts +15 -1
  19. package/dist/internal/init.d.ts.map +1 -1
  20. package/dist/internal/rules.d.ts.map +1 -1
  21. package/dist/labs/index.js +122 -78
  22. package/dist/labs/index.js.map +1 -1
  23. package/dist/mini/client/index.js +17 -6
  24. package/dist/mini/client/index.js.map +1 -1
  25. package/dist/mini/index.js +13 -5
  26. package/dist/mini/index.js.map +1 -1
  27. package/dist/mini/react/index.js +23 -13
  28. package/dist/mini/react/index.js.map +1 -1
  29. package/dist/mini/server/index.js +78 -27
  30. package/dist/mini/server/index.js.map +1 -1
  31. package/dist/public/client/zodvexClient.d.ts.map +1 -1
  32. package/dist/public/codegen/zodToSource.d.ts.map +1 -1
  33. package/dist/public/react/hooks.d.ts.map +1 -1
  34. package/dist/public/react/zodvexReactClient.d.ts.map +1 -1
  35. package/dist/public/server/index.d.ts +2 -2
  36. package/dist/public/server/index.d.ts.map +1 -1
  37. package/dist/react/index.js +23 -13
  38. package/dist/react/index.js.map +1 -1
  39. package/dist/server/index.js +78 -27
  40. package/dist/server/index.js.map +1 -1
  41. package/package.json +2 -1
  42. package/src/internal/boundaryHelpers.ts +25 -5
  43. package/src/internal/customization.ts +42 -3
  44. package/src/internal/db.ts +88 -25
  45. package/src/internal/init.ts +40 -5
  46. package/src/internal/rules.ts +19 -11
  47. package/src/public/client/zodvexClient.ts +4 -1
  48. package/src/public/codegen/zodToSource.ts +12 -4
  49. package/src/public/react/hooks.ts +8 -11
  50. package/src/public/react/zodvexReactClient.ts +6 -2
  51. package/src/public/server/index.ts +7 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zodvex",
3
- "version": "0.7.7",
3
+ "version": "0.7.8-beta.2",
4
4
  "description": "Codec-first Zod v4 integration for Convex -- type-safe validation, encoding, DB wrapping, and codegen.",
5
5
  "keywords": ["zod", "convex", "validators", "codec", "mapping", "schema", "validation"],
6
6
  "homepage": "https://github.com/panzacoder/zodvex#readme",
@@ -115,6 +115,7 @@
115
115
  "ts-morph": "^25.0.0"
116
116
  },
117
117
  "devDependencies": {
118
+ "zod": "4.5.4",
118
119
  "zod-to-mini": "workspace:*",
119
120
  "@biomejs/biome": "^2.2.6",
120
121
  "@types/bun": "^1.3.0",
@@ -32,6 +32,15 @@ export type BoundaryHelpersOptions = {
32
32
  * - `'throw'`: throw a ZodvexDecodeError (extends z.ZodError). // zod-ok
33
33
  */
34
34
  onDecodeError?: 'warn' | 'throw'
35
+ /**
36
+ * Include a truncated preview of the raw wire data in the decode-failure
37
+ * `warn` log (only relevant when `onDecodeError` is `'warn'`, the default).
38
+ *
39
+ * Off by default because wire values may be sensitive — the default warn
40
+ * message only carries the function path and zod issue list. Enable only
41
+ * when debugging a decode skew and you need to see the offending values.
42
+ */
43
+ warnWirePreview?: boolean
35
44
  }
36
45
 
37
46
  /**
@@ -80,6 +89,7 @@ export function __resetRegistryMissWarnings(): void {
80
89
 
81
90
  export function createBoundaryHelpers(registry: AnyRegistry, options?: BoundaryHelpersOptions) {
82
91
  const onDecodeError = options?.onDecodeError ?? 'warn'
92
+ const warnWirePreview = options?.warnWirePreview === true
83
93
 
84
94
  /**
85
95
  * Encode args from runtime types to wire format.
@@ -137,11 +147,21 @@ export function createBoundaryHelpers(registry: AnyRegistry, options?: BoundaryH
137
147
  }
138
148
 
139
149
  // Default: warn and return raw wire data
140
- const preview = JSON.stringify(wireResult)
141
- const truncated = preview.length > 200 ? `${preview.slice(0, 200)}...` : preview
142
- console.warn(
143
- `[zodvex] Decode failed for ${path}: ${result.error.issues.map((i: $ZodIssue) => `${i.path.join('.')}: ${i.message}`).join(', ')}. Returning raw wire data. Preview: ${truncated}`
144
- )
150
+ const issueList = result.error.issues
151
+ .map((i: $ZodIssue) => `${i.path.join('.')}: ${i.message}`)
152
+ .join(', ')
153
+ let message = `[zodvex] Decode failed for ${path}: ${issueList}. Returning raw wire data.`
154
+ if (warnWirePreview) {
155
+ let preview = '[unavailable]'
156
+ try {
157
+ preview = JSON.stringify(wireResult) ?? '[unavailable]'
158
+ } catch {
159
+ // Debug logging must not change warn-mode behavior for non-JSON values.
160
+ }
161
+ const truncated = preview.length > 200 ? `${preview.slice(0, 200)}...` : preview
162
+ message += ` Preview: ${truncated}`
163
+ }
164
+ console.warn(message)
145
165
  return wireResult
146
166
  }
147
167
 
@@ -1,11 +1,41 @@
1
+ import type { GenericDatabaseReader, GenericDatabaseWriter } from 'convex/server'
1
2
  import { ZodvexDatabaseReader, ZodvexDatabaseWriter } from './db'
2
3
  import type { ZodTableMap } from './schema'
3
4
 
5
+ /**
6
+ * Resolvers for the database the codec wrapper delegates to (#92).
7
+ *
8
+ * Each resolver receives the raw Convex ctx (untouched by zodvex) and returns
9
+ * the db the codec reader/writer should wrap instead of `ctx.db`. This lets
10
+ * native-shape layers — e.g. `convex-helpers/server/triggers` — sit UNDER the
11
+ * codec layer: codec on top → triggers → real db. The trigger layer sees
12
+ * wire-format writes, exactly what it is written against.
13
+ *
14
+ * ```ts
15
+ * const triggers = new Triggers<DataModel>()
16
+ * initZodvex(schema, server, {
17
+ * underlyingDb: { mutation: (ctx) => triggers.wrapDB(ctx).db }
18
+ * })
19
+ * ```
20
+ */
21
+ export type ZodvexUnderlyingDb<
22
+ QueryCtx = any,
23
+ MutationCtx = any,
24
+ Reader extends GenericDatabaseReader<any> = GenericDatabaseReader<any>,
25
+ Writer extends GenericDatabaseWriter<any> = GenericDatabaseWriter<any>
26
+ > = {
27
+ query?: (ctx: QueryCtx) => Reader
28
+ mutation?: (ctx: MutationCtx) => Writer
29
+ }
30
+
4
31
  /**
5
32
  * Creates Convex Customization objects that wrap ctx.db with codec
6
33
  * readers/writers. Returns { query, mutation } for use with
7
34
  * zCustomQuery/zCustomMutation or manual composition.
8
35
  *
36
+ * When `options.underlyingDb` is provided, the codec wrapper delegates to the
37
+ * resolved db instead of `ctx.db` (see {@link ZodvexUnderlyingDb}).
38
+ *
9
39
  * @example
10
40
  * ```typescript
11
41
  * const codec = createZodvexCustomization(schema.__zodTableMap)
@@ -19,19 +49,28 @@ import type { ZodTableMap } from './schema'
19
49
  * })
20
50
  * ```
21
51
  */
22
- export function createZodvexCustomization(tableMap: ZodTableMap) {
52
+ export function createZodvexCustomization(
53
+ tableMap: ZodTableMap,
54
+ options?: { underlyingDb?: ZodvexUnderlyingDb }
55
+ ) {
56
+ const resolveReaderDb = options?.underlyingDb?.query
57
+ const resolveWriterDb = options?.underlyingDb?.mutation
23
58
  return {
24
59
  query: {
25
60
  args: {} as Record<string, never>,
26
61
  input: async (ctx: any, _args: any, _extra?: any) => ({
27
- ctx: { db: new ZodvexDatabaseReader(ctx.db, tableMap) },
62
+ ctx: {
63
+ db: new ZodvexDatabaseReader(resolveReaderDb ? resolveReaderDb(ctx) : ctx.db, tableMap)
64
+ },
28
65
  args: {}
29
66
  })
30
67
  },
31
68
  mutation: {
32
69
  args: {} as Record<string, never>,
33
70
  input: async (ctx: any, _args: any, _extra?: any) => ({
34
- ctx: { db: new ZodvexDatabaseWriter(ctx.db, tableMap) },
71
+ ctx: {
72
+ db: new ZodvexDatabaseWriter(resolveWriterDb ? resolveWriterDb(ctx) : ctx.db, tableMap)
73
+ },
35
74
  args: {}
36
75
  })
37
76
  }
@@ -246,8 +246,12 @@ function wrapIndexRangeBuilder(inner: any, schema: $ZodType): any {
246
246
  })
247
247
  }
248
248
 
249
- function extractFieldPath(expr: any): string | null {
250
- if (expr && typeof expr.serialize === 'function') {
249
+ function isFilterExpression(value: any, expressionPrototype: object): boolean {
250
+ return value != null && Object.prototype.isPrototypeOf.call(expressionPrototype, value)
251
+ }
252
+
253
+ function extractFieldPath(expr: any, expressionPrototype: object): string | null {
254
+ if (isFilterExpression(expr, expressionPrototype)) {
251
255
  const inner = expr.serialize()
252
256
  if (inner && typeof inner === 'object' && '$field' in inner) {
253
257
  return inner.$field
@@ -257,15 +261,18 @@ function extractFieldPath(expr: any): string | null {
257
261
  }
258
262
 
259
263
  function wrapFilterBuilder(inner: any, schema: $ZodType): any {
264
+ // Use the builder's own expression type, including expressions created outside
265
+ // this wrapper. A codec's runtime value may also have a serialize() method.
266
+ const expressionPrototype = Object.getPrototypeOf(inner.field('_id'))
260
267
  return new Proxy(inner, {
261
268
  get(target, prop, receiver) {
262
269
  if (typeof prop === 'string' && ['eq', 'neq', 'lt', 'lte', 'gt', 'gte'].includes(prop)) {
263
270
  return (l: any, r: any) => {
264
- const lField = extractFieldPath(l)
265
- const rField = extractFieldPath(r)
266
- if (lField && !rField) {
271
+ const lField = extractFieldPath(l, expressionPrototype)
272
+ const rField = extractFieldPath(r, expressionPrototype)
273
+ if (lField && !isFilterExpression(r, expressionPrototype)) {
267
274
  r = encodeIndexValue(schema, lField, r)
268
- } else if (rField && !lField) {
275
+ } else if (rField && !isFilterExpression(l, expressionPrototype)) {
269
276
  l = encodeIndexValue(schema, rField, l)
270
277
  }
271
278
  return target[prop](l, r)
@@ -419,19 +426,43 @@ export type ResolveDecodedDoc<
419
426
  /** System fields auto-managed by Convex — not writable by consumers. */
420
427
  type SystemFields = '_id' | '_creationTime'
421
428
 
422
- /** Decoded doc without system fields — for insert and replace values. */
423
- type DecodedWriteValue<
429
+ /** Preserve variant fields, including named fields alongside a string index signature. */
430
+ type WithoutSystemFields<Doc> = Doc extends unknown
431
+ ? { [Key in keyof Doc as Key extends SystemFields ? never : Key]: Doc[Key] }
432
+ : never
433
+
434
+ /** Value accepted by insert and replace: decoded document without Convex-managed fields. */
435
+ export type ZodvexWriteValue<
424
436
  DataModel extends GenericDataModel,
425
437
  DecodedDocs extends Record<string, any>,
426
438
  TableName extends TableNamesInDataModel<DataModel>
427
- > = Omit<ResolveDecodedDoc<DataModel, DecodedDocs, TableName>, SystemFields>
439
+ > = WithoutSystemFields<ResolveDecodedDoc<DataModel, DecodedDocs, TableName>>
440
+
441
+ /** Check the whole document against each member without collapsing variant fields. */
442
+ type IsUnion<Doc, Whole = Doc> = Doc extends unknown
443
+ ? [Whole] extends [Doc]
444
+ ? false
445
+ : true
446
+ : never
428
447
 
429
- /** Partial decoded doc without system fields — for patch values. */
430
- type DecodedPatchValue<
448
+ /** Known decoded unions use full encoding; ordinary object documents accept partials. */
449
+ type ModeledPatchValue<Doc> =
450
+ true extends IsUnion<Doc> ? WithoutSystemFields<Doc> : Partial<WithoutSystemFields<Doc>>
451
+
452
+ /**
453
+ * Value accepted by patch: partial decoded object without Convex-managed fields.
454
+ * Union patches need a complete variant because encodePartialDoc uses full encoding.
455
+ * Only decoded output types are available here: erased/collapsed schema unions cannot
456
+ * be detected, and runtime encoding remains authoritative. Unmodeled tables retain
457
+ * native partial patch values.
458
+ */
459
+ export type ZodvexPatchValue<
431
460
  DataModel extends GenericDataModel,
432
461
  DecodedDocs extends Record<string, any>,
433
462
  TableName extends TableNamesInDataModel<DataModel>
434
- > = Partial<Omit<ResolveDecodedDoc<DataModel, DecodedDocs, TableName>, SystemFields>>
463
+ > = TableName extends keyof DecodedDocs
464
+ ? ModeledPatchValue<DecodedDocs[TableName]>
465
+ : Partial<WithoutSystemFields<ResolveDecodedDoc<DataModel, DecodedDocs, TableName>>>
435
466
 
436
467
  /**
437
468
  * Resolves a table name from a GenericId by iterating the tableMap
@@ -484,6 +515,18 @@ export class ZodvexDatabaseReader<
484
515
  return { db: this.db, tableMap: this.tableMap }
485
516
  }
486
517
 
518
+ /**
519
+ * Escape hatch (#85/#92): returns the database this codec wrapper delegates
520
+ * to — the composed underlying stack when `underlyingDb` is configured (e.g.
521
+ * a trigger-wrapped writer), the bare Convex db otherwise.
522
+ *
523
+ * The returned db is native-shape: reads are undecoded wire documents and it
524
+ * bypasses codec, `.withRules()`, and `.audit()` layers entirely.
525
+ */
526
+ unwrap(): GenericDatabaseReader<DataModel> {
527
+ return this.db
528
+ }
529
+
487
530
  normalizeId<TableName extends TableNamesInDataModel<DataModel>>(
488
531
  tableName: TableName,
489
532
  id: string
@@ -494,8 +537,10 @@ export class ZodvexDatabaseReader<
494
537
  get<TableName extends TableNamesInDataModel<DataModel>>(
495
538
  id: GenericId<TableName>
496
539
  ): Promise<ResolveDecodedDoc<DataModel, DecodedDocs, TableName> | null>
497
- /** @internal 2-arg form for table-first lookups */
498
- get(idOrTable: any, maybeId?: any): Promise<any>
540
+ get<TableName extends TableNamesInDataModel<DataModel>>(
541
+ table: TableName,
542
+ id: GenericId<NoInfer<TableName>>
543
+ ): Promise<ResolveDecodedDoc<DataModel, DecodedDocs, TableName> | null>
499
544
  async get(idOrTable: any, maybeId?: any): Promise<any> {
500
545
  let tableName: string | null
501
546
  let doc: any
@@ -600,14 +645,24 @@ export class ZodvexDatabaseWriter<
600
645
  return { db: this.writerDb, tableMap: this.tableMap, reader: this }
601
646
  }
602
647
 
648
+ /**
649
+ * Escape hatch (#85/#92): returns the writer this codec wrapper delegates
650
+ * to — the composed underlying stack when `underlyingDb` is configured (e.g.
651
+ * a trigger-wrapped writer), the bare Convex db otherwise.
652
+ *
653
+ * The returned db is native-shape: writes must be wire-format and it
654
+ * bypasses codec, `.withRules()`, and `.audit()` layers entirely.
655
+ */
656
+ override unwrap(): GenericDatabaseWriter<DataModel> {
657
+ return this.writerDb
658
+ }
659
+
603
660
  // --- Write methods: encode before delegating ---
604
661
 
605
662
  insert<TableName extends TableNamesInDataModel<DataModel>>(
606
663
  table: TableName,
607
- value: DecodedWriteValue<DataModel, DecodedDocs, TableName>
664
+ value: ZodvexWriteValue<DataModel, DecodedDocs, NoInfer<TableName>>
608
665
  ): Promise<GenericId<TableName>>
609
- /** @internal untyped fallback */
610
- insert(table: any, value: any): Promise<any>
611
666
  async insert(table: any, value: any): Promise<any> {
612
667
  const schemas = this.tableMap[table as string]
613
668
  const wireValue = schemas ? encodeDoc(schemas.insert, value) : value
@@ -616,10 +671,13 @@ export class ZodvexDatabaseWriter<
616
671
 
617
672
  patch<TableName extends TableNamesInDataModel<DataModel>>(
618
673
  id: GenericId<TableName>,
619
- value: DecodedPatchValue<DataModel, DecodedDocs, TableName>
674
+ value: ZodvexPatchValue<DataModel, DecodedDocs, NoInfer<TableName>>
675
+ ): Promise<void>
676
+ patch<TableName extends TableNamesInDataModel<DataModel>>(
677
+ table: TableName,
678
+ id: GenericId<NoInfer<TableName>>,
679
+ value: ZodvexPatchValue<DataModel, DecodedDocs, NoInfer<TableName>>
620
680
  ): Promise<void>
621
- /** @internal 3-arg form for table-first patches */
622
- patch(idOrTable: any, idOrValue: any, maybeValue?: any): Promise<void>
623
681
  async patch(idOrTable: any, idOrValue: any, maybeValue?: any): Promise<void> {
624
682
  let tableName: string | null
625
683
  let id: any
@@ -649,10 +707,13 @@ export class ZodvexDatabaseWriter<
649
707
 
650
708
  replace<TableName extends TableNamesInDataModel<DataModel>>(
651
709
  id: GenericId<TableName>,
652
- value: DecodedWriteValue<DataModel, DecodedDocs, TableName>
710
+ value: ZodvexWriteValue<DataModel, DecodedDocs, NoInfer<TableName>>
711
+ ): Promise<void>
712
+ replace<TableName extends TableNamesInDataModel<DataModel>>(
713
+ table: TableName,
714
+ id: GenericId<NoInfer<TableName>>,
715
+ value: ZodvexWriteValue<DataModel, DecodedDocs, NoInfer<TableName>>
653
716
  ): Promise<void>
654
- /** @internal 3-arg form for table-first replaces */
655
- replace(idOrTable: any, idOrValue: any, maybeValue?: any): Promise<void>
656
717
  async replace(idOrTable: any, idOrValue: any, maybeValue?: any): Promise<void> {
657
718
  let tableName: string | null
658
719
  let id: any
@@ -681,8 +742,10 @@ export class ZodvexDatabaseWriter<
681
742
  delete<TableName extends TableNamesInDataModel<DataModel>>(
682
743
  id: GenericId<TableName>
683
744
  ): Promise<void>
684
- /** @internal 2-arg form for table-first deletes */
685
- delete(idOrTable: any, maybeId?: any): Promise<void>
745
+ delete<TableName extends TableNamesInDataModel<DataModel>>(
746
+ table: TableName,
747
+ id: GenericId<NoInfer<TableName>>
748
+ ): Promise<void>
686
749
  async delete(idOrTable: any, maybeId?: any): Promise<void> {
687
750
  if (maybeId !== undefined) {
688
751
  // 2-arg form (table, id) is @internal in Convex types — cast required
@@ -2,6 +2,8 @@ import type {
2
2
  ActionBuilder,
3
3
  FunctionVisibility,
4
4
  GenericActionCtx,
5
+ GenericDatabaseReader,
6
+ GenericDatabaseWriter,
5
7
  GenericDataModel,
6
8
  GenericMutationCtx,
7
9
  GenericQueryCtx,
@@ -13,7 +15,7 @@ import type { z } from 'zod'
13
15
  import { createCodecCallOverrides } from './actionCtx'
14
16
  import type { CustomBuilder } from './custom'
15
17
  import { zCustomAction, zCustomMutation, zCustomQuery } from './custom'
16
- import { createZodvexCustomization } from './customization'
18
+ import { createZodvexCustomization, type ZodvexUnderlyingDb } from './customization'
17
19
  import type { ZodvexDatabaseReader, ZodvexDatabaseWriter } from './db'
18
20
  import type { ZodValidator } from './mapping'
19
21
  import type { ZodTableMap } from './schema'
@@ -255,7 +257,28 @@ export function initZodvex<
255
257
  internalMutation: MutationBuilder<DM, 'internal'>
256
258
  internalAction: ActionBuilder<DM, 'internal'>
257
259
  },
258
- options?: { wrapDb?: true; registry?: () => AnyRegistry }
260
+ options?: {
261
+ wrapDb?: true
262
+ registry?: () => AnyRegistry
263
+ /**
264
+ * Resolve the database the codec wrapper delegates to, instead of `ctx.db`.
265
+ * Lets native-shape layers (e.g. convex-helpers triggers) sit under the
266
+ * codec layer — codec on top → triggers → real db. See #92.
267
+ *
268
+ * ```ts
269
+ * const triggers = new Triggers<DataModel>()
270
+ * initZodvex(schema, server, {
271
+ * underlyingDb: { mutation: (ctx) => triggers.wrapDB(ctx).db }
272
+ * })
273
+ * ```
274
+ */
275
+ underlyingDb?: ZodvexUnderlyingDb<
276
+ GenericQueryCtx<DM>,
277
+ GenericMutationCtx<DM>,
278
+ GenericDatabaseReader<DM>,
279
+ GenericDatabaseWriter<DM>
280
+ >
281
+ }
259
282
  ): {
260
283
  zq: ZodvexBuilder<'query', { db: ZodvexDatabaseReader<DM, DD> }, GenericQueryCtx<DM>, 'public'>
261
284
  zm: ZodvexBuilder<
@@ -279,11 +302,23 @@ export function initZodvex<
279
302
  export function initZodvex(
280
303
  schema: { __zodTableMap: ZodTableMap },
281
304
  server: InitServerBuilders,
282
- options?: { wrapDb?: boolean; registry?: () => AnyRegistry }
305
+ options?: {
306
+ wrapDb?: boolean
307
+ registry?: () => AnyRegistry
308
+ underlyingDb?: ZodvexUnderlyingDb
309
+ }
283
310
  ) {
284
- const codec = createZodvexCustomization(schema.__zodTableMap)
285
- const noOp = createNoOpCustomization()
286
311
  const wrap = options?.wrapDb !== false
312
+ if (!wrap && options?.underlyingDb) {
313
+ throw new Error(
314
+ '[zodvex] initZodvex: `underlyingDb` requires the codec db wrapper — ' +
315
+ 'remove `wrapDb: false` or drop `underlyingDb`.'
316
+ )
317
+ }
318
+ const codec = createZodvexCustomization(schema.__zodTableMap, {
319
+ underlyingDb: options?.underlyingDb
320
+ })
321
+ const noOp = createNoOpCustomization()
287
322
 
288
323
  const registryThunk = options?.registry
289
324
  const actionCust = createActionCustomization(registryThunk, noOp)
@@ -175,10 +175,14 @@ export function installRulesSubclasses(bases: {
175
175
  }
176
176
 
177
177
  async take(n: number): Promise<Doc[]> {
178
+ if (!Number.isInteger(n) || n < 0) {
179
+ throw new Error('take requires a non-negative integer')
180
+ }
178
181
  const results: Doc[] = []
182
+ if (n === 0) return results
179
183
  for await (const doc of this as any) {
180
- if (results.length >= n) break
181
184
  results.push(doc)
185
+ if (results.length >= n) break
182
186
  }
183
187
  return results
184
188
  }
@@ -201,10 +205,7 @@ export function installRulesSubclasses(bases: {
201
205
  }
202
206
 
203
207
  async *[Symbol.asyncIterator](): AsyncIterator<Doc> {
204
- const iter = super[Symbol.asyncIterator]()
205
- while (true) {
206
- const { value, done } = await iter.next()
207
- if (done) break
208
+ for await (const value of super[Symbol.asyncIterator]()) {
208
209
  const result = normalizeReadResult(await this.readRule(this.ctx, value), value)
209
210
  if (result !== null) yield result
210
211
  }
@@ -328,7 +329,12 @@ export function installRulesSubclasses(bases: {
328
329
 
329
330
  if (tableRules?.insert) {
330
331
  const transformed = await tableRules.insert(this.ctx, value)
331
- return this.inner.insert(table, transformed)
332
+ // Rules are stored with erased table types; the codec boundary validates
333
+ // the transformed document against this table's insert schema.
334
+ return this.inner.insert(
335
+ table,
336
+ transformed as Parameters<ZodvexDatabaseWriter<DataModel, DecodedDocs>['insert']>[1]
337
+ )
332
338
  }
333
339
 
334
340
  if ((this.rulesConfig.defaultPolicy ?? 'allow') === 'deny') {
@@ -360,7 +366,12 @@ export function installRulesSubclasses(bases: {
360
366
 
361
367
  if (tableRules?.patch) {
362
368
  const transformed = await tableRules.patch(this.ctx, doc, value)
363
- return this.inner.patch(id, transformed)
369
+ // Rules erase table types; the inner encoder still validates transformed
370
+ // patches, including the complete-variant requirement for union schemas.
371
+ return this.inner.patch(
372
+ id,
373
+ transformed as Parameters<ZodvexDatabaseWriter<DataModel, DecodedDocs>['patch']>[2]
374
+ )
364
375
  }
365
376
 
366
377
  if ((this.rulesConfig.defaultPolicy ?? 'allow') === 'deny') {
@@ -512,10 +523,7 @@ export function installRulesSubclasses(bases: {
512
523
  }
513
524
 
514
525
  async *[Symbol.asyncIterator](): AsyncIterator<Doc> {
515
- const iter = super[Symbol.asyncIterator]()
516
- while (true) {
517
- const { value, done } = await iter.next()
518
- if (done) break
526
+ for await (const value of super[Symbol.asyncIterator]()) {
519
527
  await this.afterRead(this.tableName, value)
520
528
  yield value
521
529
  }
@@ -24,7 +24,10 @@ export class ZodvexClient<R extends AnyRegistry = AnyRegistry> {
24
24
  private pendingAuthOnChange?: (isAuthenticated: boolean) => void
25
25
 
26
26
  constructor(registry: R, options: ZodvexClientOptions) {
27
- this.codec = createBoundaryHelpers(registry, { onDecodeError: options.onDecodeError })
27
+ this.codec = createBoundaryHelpers(registry, {
28
+ onDecodeError: options.onDecodeError,
29
+ warnWirePreview: options.warnWirePreview
30
+ })
28
31
  if ('client' in options) {
29
32
  this.innerClient = options.client
30
33
  } else {
@@ -73,7 +73,7 @@ export function zodToSource(schema: $ZodType, ctx?: ZodToSourceContext): string
73
73
  ? (schema as any).description.slice('convexId:'.length)
74
74
  : undefined)
75
75
  if (tableName) {
76
- return `zx.id("${tableName}")`
76
+ return `zx.id(${JSON.stringify(tableName)})`
77
77
  }
78
78
  }
79
79
 
@@ -115,7 +115,15 @@ export function zodToSource(schema: $ZodType, ctx?: ZodToSourceContext): string
115
115
  if (schema instanceof $ZodObject) {
116
116
  const shape = schema._zod.def.shape
117
117
  const fields = Object.entries(shape)
118
- .map(([key, value]) => `${key}: ${zodToSource(value, ctx)}`)
118
+ .map(([key, value]) => {
119
+ const property =
120
+ key === '__proto__'
121
+ ? `[${JSON.stringify(key)}]`
122
+ : /^[A-Za-z_$][\w$]*$/.test(key)
123
+ ? key
124
+ : JSON.stringify(key)
125
+ return `${property}: ${zodToSource(value, ctx)}`
126
+ })
119
127
  .join(', ')
120
128
  return `z.object({ ${fields} })`
121
129
  }
@@ -128,7 +136,7 @@ export function zodToSource(schema: $ZodType, ctx?: ZodToSourceContext): string
128
136
  // Enums
129
137
  if (schema instanceof $ZodEnum) {
130
138
  const entries = schema._zod.def.entries
131
- const values = (Object.values(entries) as string[]).map((v: string) => `"${v}"`).join(', ')
139
+ const values = (Object.values(entries) as string[]).map(v => JSON.stringify(v)).join(', ')
132
140
  return `z.enum([${values}])`
133
141
  }
134
142
 
@@ -136,7 +144,7 @@ export function zodToSource(schema: $ZodType, ctx?: ZodToSourceContext): string
136
144
  if (schema instanceof $ZodLiteral) {
137
145
  const values = schema._zod.def.values
138
146
  const value = values.values().next().value
139
- if (typeof value === 'string') return `z.literal("${value}")`
147
+ if (typeof value === 'string') return `z.literal(${JSON.stringify(value)})`
140
148
  return `z.literal(${value})`
141
149
  }
142
150
 
@@ -1,7 +1,6 @@
1
1
  import type { OptionalRestArgsOrSkip } from 'convex/react'
2
2
  import { useMutation, useQuery } from 'convex/react'
3
3
  import type { FunctionArgs, FunctionReference, FunctionReturnType } from 'convex/server'
4
- import { getFunctionName } from 'convex/server'
5
4
  import type { BoundaryHelpersOptions } from '../../internal/boundaryHelpers'
6
5
  import { createBoundaryHelpers } from '../../internal/boundaryHelpers'
7
6
  import type { AnyRegistry } from '../../internal/types'
@@ -45,6 +44,7 @@ export function createZodvexHooks<R extends AnyRegistry>(
45
44
  * 2. Union args (composable): `useZodQuery(ref, args | 'skip')` — for wrappers
46
45
  * and conditional skip patterns where the decision is made upstream.
47
46
  *
47
+ * - Invalid arguments throw during render; use a React error boundary to handle them.
48
48
  * - Loading state (`undefined`) passes through unchanged.
49
49
  * - Functions not in the registry return the raw wire result.
50
50
  */
@@ -62,20 +62,15 @@ export function createZodvexHooks<R extends AnyRegistry>(
62
62
  function useZodQuery(ref: FunctionReference<'query', any, any, any>, ...restArgs: any[]) {
63
63
  const args = restArgs[0]
64
64
 
65
- // Encode args: runtime types -> wire format (e.g., Date -> timestamp).
66
- // Unlike mutations (imperative, user-triggered), hooks fire synchronously
67
- // during render — an encode error would crash the page. On failure, warn
68
- // and auto-skip the query (return undefined = loading state).
65
+ // Always call useQuery, including failed encodes, to preserve hook order.
66
+ // Then surface the error to React's error boundary instead of appearing to load forever.
69
67
  let wireArgs: any = 'skip'
68
+ let encodeFailure: { error: unknown } | undefined
70
69
  if (args !== 'skip') {
71
70
  try {
72
71
  wireArgs = codec.encodeArgs(ref, args)
73
- } catch (err) {
74
- const path = getFunctionName(ref)
75
- console.debug(
76
- `[zodvex] Encode args failed for ${path}, auto-skipping query: ${err instanceof Error ? err.message : String(err)}`
77
- )
78
- // wireArgs stays 'skip' — DO NOT early-return, useQuery must run every render
72
+ } catch (error) {
73
+ encodeFailure = { error }
79
74
  }
80
75
  }
81
76
 
@@ -84,6 +79,8 @@ export function createZodvexHooks<R extends AnyRegistry>(
84
79
  ...((wireArgs === 'skip' ? ['skip'] : [wireArgs]) as OptionalRestArgsOrSkip<typeof ref>)
85
80
  )
86
81
 
82
+ if (encodeFailure) throw encodeFailure.error
83
+
87
84
  // Loading state — Convex returns undefined while the subscription is pending
88
85
  if (wireResult === undefined) return undefined
89
86
 
@@ -19,7 +19,10 @@ export class ZodvexReactClient<R extends AnyRegistry = AnyRegistry> {
19
19
  }
20
20
 
21
21
  constructor(registry: R, options: ZodvexReactClientOptions) {
22
- this.codec = createBoundaryHelpers(registry, { onDecodeError: options.onDecodeError })
22
+ this.codec = createBoundaryHelpers(registry, {
23
+ onDecodeError: options.onDecodeError,
24
+ warnWirePreview: options.warnWirePreview
25
+ })
23
26
  this.options = options
24
27
  if ('client' in options) {
25
28
  this.innerClient = options.client
@@ -120,8 +123,9 @@ export class ZodvexReactClient<R extends AnyRegistry = AnyRegistry> {
120
123
  localQueryResult: () => {
121
124
  const wire = innerWatch.localQueryResult()
122
125
  if (wire === lastWire) return lastDecoded
126
+ const decoded = wire === undefined ? undefined : this.codec.decodeResult(ref, wire)
123
127
  lastWire = wire
124
- lastDecoded = wire === undefined ? undefined : this.codec.decodeResult(ref, wire)
128
+ lastDecoded = decoded
125
129
  return lastDecoded
126
130
  },
127
131
  journal: () => innerWatch.journal()
@@ -31,7 +31,10 @@ export {
31
31
  zCustomQuery
32
32
  } from '../../internal/custom'
33
33
  // Codec customization (manual composition escape hatch)
34
- export { createZodvexCustomization } from '../../internal/customization'
34
+ export {
35
+ createZodvexCustomization,
36
+ type ZodvexUnderlyingDb
37
+ } from '../../internal/customization'
35
38
  // Database wrappers (ZodvexDatabaseReader, ZodvexDatabaseWriter, etc.)
36
39
  export {
37
40
  createZodDbReader,
@@ -44,8 +47,10 @@ export {
44
47
  type ZodvexIndexFieldValue,
45
48
  type ZodvexIndexRangeBuilder,
46
49
  type ZodvexLowerBoundBuilder,
50
+ type ZodvexPatchValue,
47
51
  ZodvexQueryChain,
48
- type ZodvexUpperBoundBuilder
52
+ type ZodvexUpperBoundBuilder,
53
+ type ZodvexWriteValue
49
54
  } from '../../internal/db'
50
55
  // One-time setup + types
51
56
  export {