zodvex 0.7.8-beta.0 → 0.7.8-beta.3
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.
- package/README.md +15 -10
- package/dist/cli/index.js +133 -86
- package/dist/cli/index.js.map +1 -1
- package/dist/client/index.js +17 -6
- package/dist/client/index.js.map +1 -1
- package/dist/codegen/index.js +7 -4
- package/dist/codegen/index.js.map +1 -1
- package/dist/core/index.js +13 -5
- package/dist/core/index.js.map +1 -1
- package/dist/index.js +13 -5
- package/dist/index.js.map +1 -1
- package/dist/internal/boundaryHelpers.d.ts +9 -0
- package/dist/internal/boundaryHelpers.d.ts.map +1 -1
- package/dist/internal/db.d.ts +27 -18
- package/dist/internal/db.d.ts.map +1 -1
- package/dist/internal/rules.d.ts.map +1 -1
- package/dist/labs/index.js +122 -78
- package/dist/labs/index.js.map +1 -1
- package/dist/mini/client/index.js +17 -6
- package/dist/mini/client/index.js.map +1 -1
- package/dist/mini/index.js +13 -5
- package/dist/mini/index.js.map +1 -1
- package/dist/mini/react/index.js +23 -13
- package/dist/mini/react/index.js.map +1 -1
- package/dist/mini/server/index.js +38 -22
- package/dist/mini/server/index.js.map +1 -1
- package/dist/public/client/zodvexClient.d.ts.map +1 -1
- package/dist/public/codegen/zodToSource.d.ts.map +1 -1
- package/dist/public/react/hooks.d.ts.map +1 -1
- package/dist/public/react/zodvexReactClient.d.ts.map +1 -1
- package/dist/public/server/index.d.ts +1 -1
- package/dist/public/server/index.d.ts.map +1 -1
- package/dist/react/index.js +23 -13
- package/dist/react/index.js.map +1 -1
- package/dist/server/index.js +38 -22
- package/dist/server/index.js.map +1 -1
- package/package.json +2 -1
- package/src/internal/boundaryHelpers.ts +25 -5
- package/src/internal/db.ts +67 -25
- package/src/internal/rules.ts +19 -11
- package/src/public/client/zodvexClient.ts +4 -1
- package/src/public/codegen/zodToSource.ts +12 -4
- package/src/public/react/hooks.ts +8 -11
- package/src/public/react/zodvexReactClient.ts +6 -2
- package/src/public/server/index.ts +5 -1
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
#### [Zod](https://zod.dev/) + [Convex](https://www.convex.dev/)
|
|
4
4
|
|
|
5
|
-
Use Zod v4 as your schema language for Convex — define your data once and use it end to end, with automatic validation and
|
|
5
|
+
Use Zod v4 as your schema language for Convex — define your data once and use it end to end, with automatic function validation and a codec-aware database.
|
|
6
6
|
|
|
7
7
|
[](https://www.npmjs.com/package/zodvex)
|
|
8
8
|
[](https://github.com/panzacoder/zodvex/actions/workflows/ci.yml)
|
|
@@ -12,20 +12,20 @@ Use Zod v4 as your schema language for Convex — define your data once and use
|
|
|
12
12
|
|
|
13
13
|
**Your Zod schemas are the source of truth** — tables, function arguments, and return types defined once, used database to frontend. Two things make that real:
|
|
14
14
|
|
|
15
|
-
- **Functions
|
|
15
|
+
- **Functions execute your Zod schemas.** Wrappers parse declared arguments before the handler and encode declared returns. Zod refinements and codec logic run alongside Convex’s structural checks. Parsing and encoding have different transform/default behavior; current wrappers use synchronous Zod operations.
|
|
16
16
|
|
|
17
|
-
- **
|
|
17
|
+
- **Modeled database reads run full Zod validation.** The wrapped `ctx.db` parses modeled documents on reads and encodes insert/replace values through the model schema. Codecs live in the schema itself, so handlers can work with `Date` objects while Convex stores plain values.
|
|
18
18
|
|
|
19
19
|
What you gain over Convex out of the box:
|
|
20
20
|
|
|
21
21
|
| | Convex | with zodvex |
|
|
22
22
|
|---|---|---|
|
|
23
23
|
| Type safety | end-to-end inference | same — driven by your Zod schemas |
|
|
24
|
-
| Runtime validation | structural checks |
|
|
25
|
-
| End-to-end validation | per-function validators |
|
|
26
|
-
| Client calls | `useQuery(api.fn)` infers types |
|
|
24
|
+
| Runtime validation | structural checks | Zod parsing/encoding for declared function schemas and modeled data |
|
|
25
|
+
| End-to-end validation | per-function validators | shared Zod definitions across configured client, function, and database paths |
|
|
26
|
+
| Client calls | `useQuery(api.fn)` infers types | registry args encoded and results parsed, with a configurable decode-error policy |
|
|
27
27
|
| Dates & custom types | `number` timestamps | `Date` objects and custom codecs (`zx.date()`, `zx.codec()`) |
|
|
28
|
-
| Rows on read | as stored | parsed & decoded through your schema |
|
|
28
|
+
| Rows on read | as stored | modeled documents parsed & decoded through your schema |
|
|
29
29
|
| Row-level rules & audit | build your own | `.withRules()` / `.audit()` on `ctx.db` |
|
|
30
30
|
|
|
31
31
|
All of it wired once with `initZodvex` — see [Features](#features).
|
|
@@ -150,20 +150,22 @@ Two deprecated paths remain for migration only:
|
|
|
150
150
|
|
|
151
151
|
### Codec-Aware Database
|
|
152
152
|
|
|
153
|
-
`initZodvex` wraps `ctx.db` so reads decode automatically and
|
|
153
|
+
`initZodvex` wraps `ctx.db` so modeled reads decode automatically and insert/replace values encode automatically. Codecs are opt-in per field — schemas without them get the same validation, typed IDs, and correct optional/nullable mapping through the exact same setup.
|
|
154
154
|
|
|
155
155
|
- **`zx.date()`** — Date ↔ timestamp codec. Stored as `v.float64()`, used as `Date` in handlers.
|
|
156
156
|
- **`zx.codec(wire, runtime, transforms)`** — Custom codecs for complex transformations (encryption, serialization, etc.).
|
|
157
157
|
- **`zx.id('table')`** — Typed Convex ID validator with `GenericId<T>` branding — no wire transform (not a codec).
|
|
158
158
|
|
|
159
|
+
Object patches encode supplied fields without validating the merged document or retaining outer object refinements; union patches use full encoding. Unmodeled tables and system access pass through. `unwrap()` or `wrapDb: false` bypass wrapping. See the [boundary contract](./docs/decisions/2026-09-07-boundary-contract.md).
|
|
160
|
+
|
|
159
161
|
Guides: [Custom Codecs](./docs/guide/custom-codecs.md), [Date Handling](./docs/guide/date-handling.md)
|
|
160
162
|
|
|
161
163
|
### Row-Level Rules & Audit
|
|
162
164
|
|
|
163
|
-
The same wrapped `ctx.db` carries per-row
|
|
165
|
+
The same wrapped `ctx.db` carries per-row rules and audit hooks. Modeled reads and supplied write values use decoded runtime types:
|
|
164
166
|
|
|
165
167
|
- **`.withRules(ruleCtx, rules)`** — gate and transform reads and writes per table (`read`, `insert`, `patch`, `replace`, `delete`), with an optional deny-by-default policy.
|
|
166
|
-
- **`.audit({ afterRead, afterWrite })`** — observe
|
|
168
|
+
- **`.audit({ afterRead, afterWrite })`** — observe completed inner reads and writes. Composition order determines what audit sees; an audit layer outside `.withRules()` observes the rules-processed results.
|
|
167
169
|
|
|
168
170
|
Guide: [Rules & Audit](./docs/guide/rules-and-audit.md)
|
|
169
171
|
|
|
@@ -187,9 +189,12 @@ Guide: [Builders — Composing with triggers](./docs/guide/builders.md#composing
|
|
|
187
189
|
zodvex includes an optional CLI that generates typed client code:
|
|
188
190
|
|
|
189
191
|
- **Typed hooks** — `useZodQuery`, `useZodMutation`, generated into `convex/_zodvex/client` — import them from there; args are encoded and results decoded automatically
|
|
192
|
+
Invalid query arguments throw during render and can be handled by a React error boundary. Pass `'skip'` explicitly while required inputs are unavailable; encoding failures no longer silently look like a loading query.
|
|
190
193
|
- **Boundary helpers** — `encodeArgs`, `decodeResult` for custom client integrations
|
|
191
194
|
- **Cross-function auto-codec** — `ctx.runQuery` / `ctx.runMutation` encode args + decode results, and `ctx.scheduler.runAfter` / `ctx.scheduler.runAt` encode args, via the registry. Pass natural decoded values; zodvex encodes them to wire at the call site.
|
|
192
195
|
|
|
196
|
+
Registry-backed clients and outbound helpers warn and return raw wire data when result parsing fails by default; use `onDecodeError: 'throw'` to reject failed result parses. Missing registry schemas pass through unchanged.
|
|
197
|
+
|
|
193
198
|
```bash
|
|
194
199
|
zodvex generate # one-shot generation
|
|
195
200
|
zodvex dev # watch mode
|
package/dist/cli/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import fs3, { readFileSync, writeFileSync, existsSync } from 'fs';
|
|
3
3
|
import path4, { resolve, relative, join } from 'path';
|
|
4
|
-
import { Project, SyntaxKind } from 'ts-morph';
|
|
4
|
+
import { Project, SyntaxKind, Node } from 'ts-morph';
|
|
5
5
|
import { globSync } from 'tinyglobby';
|
|
6
6
|
import { spawn } from 'child_process';
|
|
7
7
|
import { fileURLToPath } from 'url';
|
|
@@ -323,25 +323,15 @@ function getMethodName(call) {
|
|
|
323
323
|
function transformWrappers(file, typeChecker) {
|
|
324
324
|
let count = 0;
|
|
325
325
|
const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse();
|
|
326
|
+
const receivers = analyzeCallReceivers(calls, WRAPPER_METHODS, typeChecker);
|
|
326
327
|
for (const call of calls) {
|
|
327
|
-
if (call.wasForgotten()) continue;
|
|
328
|
+
if (call.wasForgotten() || !receivers.get(call)?.schema) continue;
|
|
328
329
|
const method = getMethodName(call);
|
|
329
330
|
if (!method || !WRAPPER_METHODS.includes(method)) continue;
|
|
330
331
|
if (call.getArguments().length > 0) continue;
|
|
331
332
|
const obj = getCallObject(call);
|
|
332
333
|
if (!obj) continue;
|
|
333
334
|
if (isNamespaceCall(obj)) continue;
|
|
334
|
-
let isSchema;
|
|
335
|
-
if (typeChecker) {
|
|
336
|
-
const typeResult = isZodSchemaByType(call, typeChecker);
|
|
337
|
-
isSchema = typeResult === true || typeResult === null && isLikelySchemaExpr(obj);
|
|
338
|
-
} else {
|
|
339
|
-
isSchema = isLikelySchemaExpr(obj);
|
|
340
|
-
}
|
|
341
|
-
if (!isSchema && isSchemaVariable(call, obj.trim())) {
|
|
342
|
-
isSchema = true;
|
|
343
|
-
}
|
|
344
|
-
if (!isSchema) continue;
|
|
345
335
|
call.replaceWithText(`z.${method}(${obj})`);
|
|
346
336
|
count++;
|
|
347
337
|
}
|
|
@@ -350,43 +340,97 @@ function transformWrappers(file, typeChecker) {
|
|
|
350
340
|
function isNamespaceCall(obj) {
|
|
351
341
|
return NAMESPACE_IDENTIFIERS.has(obj.trim());
|
|
352
342
|
}
|
|
353
|
-
function
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
if (
|
|
357
|
-
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
343
|
+
function schemaKind(node, seen = /* @__PURE__ */ new Set(), context = /* @__PURE__ */ new Map()) {
|
|
344
|
+
if (seen.has(node)) return null;
|
|
345
|
+
seen.add(node);
|
|
346
|
+
if (Node.isParenthesizedExpression(node) || Node.isAsExpression(node) || Node.isNonNullExpression(node)) {
|
|
347
|
+
return schemaKind(node.getExpression(), seen, context);
|
|
348
|
+
}
|
|
349
|
+
if (Node.isIdentifier(node)) {
|
|
350
|
+
for (const decl of node.getSymbol()?.getDeclarations() ?? []) {
|
|
351
|
+
if (Node.isVariableDeclaration(decl)) {
|
|
352
|
+
const init2 = decl.getInitializer();
|
|
353
|
+
if (init2) return schemaKind(init2, seen, context);
|
|
354
|
+
}
|
|
355
|
+
if (Node.isParameterDeclaration(decl)) {
|
|
356
|
+
const annotation = decl.getTypeNode()?.getText();
|
|
357
|
+
if (annotation && /^z\.Zod(?:Mini)?\w+/.test(annotation)) return "schema";
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return null;
|
|
361
|
+
}
|
|
362
|
+
if (!Node.isCallExpression(node)) return null;
|
|
363
|
+
const expr = node.getExpression();
|
|
364
|
+
if (!Node.isPropertyAccessExpression(expr)) return null;
|
|
365
|
+
const receiver = expr.getExpression();
|
|
366
|
+
const name = expr.getName();
|
|
367
|
+
if (Node.isIdentifier(receiver) && NAMESPACE_IDENTIFIERS.has(receiver.getText())) {
|
|
368
|
+
const file = node.getSourceFile();
|
|
369
|
+
let localNamespaces = context.get(file);
|
|
370
|
+
if (!localNamespaces) {
|
|
371
|
+
localNamespaces = /* @__PURE__ */ new Set();
|
|
372
|
+
for (const declaration of file.getDescendants()) {
|
|
373
|
+
if (Node.isVariableDeclaration(declaration) || Node.isParameterDeclaration(declaration) || Node.isFunctionDeclaration(declaration) || Node.isBindingElement(declaration) || Node.isClassDeclaration(declaration) || Node.isEnumDeclaration(declaration)) {
|
|
374
|
+
const name2 = declaration.getName();
|
|
375
|
+
if (name2 && NAMESPACE_IDENTIFIERS.has(name2)) localNamespaces.add(name2);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
context.set(file, localNamespaces);
|
|
379
|
+
}
|
|
380
|
+
if (localNamespaces.has(receiver.getText())) {
|
|
381
|
+
const declarations = receiver.getSymbol()?.getDeclarations() ?? [];
|
|
382
|
+
if (declarations.some((d) => !Node.isImportSpecifier(d) && !Node.isNamespaceImport(d))) return null;
|
|
383
|
+
}
|
|
384
|
+
if (["parse", "safeParse", "parseAsync", "safeParseAsync", "encode", "decode"].includes(name)) return null;
|
|
385
|
+
if (["string", "number", "bigint", "array", "set", "date"].includes(name)) return name;
|
|
386
|
+
return "schema";
|
|
387
|
+
}
|
|
388
|
+
if (["parse", "safeParse", "parseAsync", "safeParseAsync", "encode", "decode"].includes(name)) return null;
|
|
389
|
+
if (name === "array" && schemaKind(receiver, seen, context)) return "array";
|
|
390
|
+
return schemaKind(receiver, seen, context);
|
|
391
|
+
}
|
|
392
|
+
function isSchemaReceiver(call, typeChecker, context = /* @__PURE__ */ new Map()) {
|
|
374
393
|
const expr = call.getExpression();
|
|
375
|
-
if (
|
|
394
|
+
if (!Node.isPropertyAccessExpression(expr)) return false;
|
|
376
395
|
const receiver = expr.getExpression();
|
|
377
|
-
|
|
396
|
+
if (typeChecker) {
|
|
378
397
|
const type = typeChecker.getTypeAtLocation(receiver);
|
|
379
|
-
if (type.isAny()) return
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
398
|
+
if (!type.isAny() && !type.isUnknown()) return type.getProperty("_zod") !== void 0;
|
|
399
|
+
}
|
|
400
|
+
return schemaKind(receiver, /* @__PURE__ */ new Set(), context) !== null;
|
|
401
|
+
}
|
|
402
|
+
function receiverKind(call, typeChecker, context = /* @__PURE__ */ new Map()) {
|
|
403
|
+
const expr = call.getExpression();
|
|
404
|
+
if (!Node.isPropertyAccessExpression(expr)) return null;
|
|
405
|
+
const receiver = expr.getExpression();
|
|
406
|
+
if (typeChecker) {
|
|
407
|
+
const type = typeChecker.getTypeAtLocation(receiver);
|
|
408
|
+
const def = type.getProperty("_zod")?.getTypeAtLocation(receiver).getProperty("def")?.getTypeAtLocation(receiver);
|
|
409
|
+
const kind = def?.getProperty("type")?.getTypeAtLocation(receiver).getLiteralValue();
|
|
410
|
+
if (typeof kind === "string") return kind;
|
|
411
|
+
}
|
|
412
|
+
return schemaKind(receiver, /* @__PURE__ */ new Set(), context);
|
|
413
|
+
}
|
|
414
|
+
function analyzeCallReceivers(calls, methods, typeChecker) {
|
|
415
|
+
const context = /* @__PURE__ */ new Map();
|
|
416
|
+
const receivers = /* @__PURE__ */ new Map();
|
|
417
|
+
for (const call of calls) {
|
|
418
|
+
const method = getMethodName(call);
|
|
419
|
+
if (!method || !methods.includes(method)) continue;
|
|
420
|
+
const obj = getCallObject(call);
|
|
421
|
+
if (!obj || isNamespaceCall(obj)) continue;
|
|
422
|
+
const schema = isSchemaReceiver(call, typeChecker, context);
|
|
423
|
+
const kind = schema && (method === "min" || method === "max") ? receiverKind(call, typeChecker, context) : null;
|
|
424
|
+
receivers.set(call, { schema, kind });
|
|
383
425
|
}
|
|
426
|
+
return receivers;
|
|
384
427
|
}
|
|
385
|
-
function transformChecks(file) {
|
|
428
|
+
function transformChecks(file, typeChecker) {
|
|
386
429
|
let count = 0;
|
|
387
430
|
const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse();
|
|
431
|
+
const receivers = analyzeCallReceivers(calls, [...ZOD_ONLY_CHECK_METHODS, ...AMBIGUOUS_CHECK_METHODS, "min", "max"], typeChecker);
|
|
388
432
|
for (const call of calls) {
|
|
389
|
-
if (call.wasForgotten()) continue;
|
|
433
|
+
if (call.wasForgotten() || !receivers.get(call)?.schema) continue;
|
|
390
434
|
const method = getMethodName(call);
|
|
391
435
|
if (!method) continue;
|
|
392
436
|
const obj = getCallObject(call);
|
|
@@ -394,19 +438,21 @@ function transformChecks(file) {
|
|
|
394
438
|
if (isNamespaceCall(obj)) continue;
|
|
395
439
|
const args = call.getArguments().map((a) => a.getText());
|
|
396
440
|
const argsStr = args.length > 0 ? args.join(", ") : "";
|
|
441
|
+
if (![...ZOD_ONLY_CHECK_METHODS, ...AMBIGUOUS_CHECK_METHODS, "min", "max"].includes(method)) continue;
|
|
397
442
|
if (ZOD_ONLY_CHECK_METHODS.includes(method)) {
|
|
398
443
|
call.replaceWithText(`${obj}.check(z.${method}(${argsStr}))`);
|
|
399
444
|
count++;
|
|
400
445
|
continue;
|
|
401
446
|
}
|
|
402
|
-
if (AMBIGUOUS_CHECK_METHODS.includes(method)
|
|
447
|
+
if (AMBIGUOUS_CHECK_METHODS.includes(method)) {
|
|
403
448
|
call.replaceWithText(`${obj}.check(z.${method}(${argsStr}))`);
|
|
404
449
|
count++;
|
|
405
450
|
continue;
|
|
406
451
|
}
|
|
407
|
-
if (
|
|
408
|
-
const
|
|
409
|
-
const checkName =
|
|
452
|
+
if (method === "min" || method === "max") {
|
|
453
|
+
const kind = receivers.get(call)?.kind;
|
|
454
|
+
const checkName = kind === "string" || kind === "array" ? STRING_RENAME[method] : kind === "number" || kind === "bigint" ? NUMBER_RENAME[method] : kind === "set" ? method === "min" ? "minSize" : "maxSize" : null;
|
|
455
|
+
if (!checkName) continue;
|
|
410
456
|
call.replaceWithText(`${obj}.check(z.${checkName}(${argsStr}))`);
|
|
411
457
|
count++;
|
|
412
458
|
continue;
|
|
@@ -417,32 +463,17 @@ function transformChecks(file) {
|
|
|
417
463
|
function transformMethods(file, typeChecker) {
|
|
418
464
|
let count = 0;
|
|
419
465
|
const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse();
|
|
466
|
+
const receivers = analyzeCallReceivers(calls, [...TOP_LEVEL_METHODS, ...RENAMED_METHODS.keys(), TRANSFORM_METHOD, "unwrap", ...CHECK_WRAP_METHODS], typeChecker);
|
|
420
467
|
for (const call of calls) {
|
|
421
|
-
if (call.wasForgotten()) continue;
|
|
468
|
+
if (call.wasForgotten() || !receivers.get(call)?.schema) continue;
|
|
422
469
|
const method = getMethodName(call);
|
|
423
470
|
if (!method) continue;
|
|
424
471
|
const obj = getCallObject(call);
|
|
425
472
|
if (!obj) continue;
|
|
426
473
|
if (isNamespaceCall(obj)) continue;
|
|
427
474
|
const args = call.getArguments().map((a) => a.getText());
|
|
428
|
-
if (
|
|
429
|
-
|
|
430
|
-
call.replaceWithText(`z.${method}(${obj}${argsStr})`);
|
|
431
|
-
count++;
|
|
432
|
-
continue;
|
|
433
|
-
}
|
|
434
|
-
if (AMBIGUOUS_TOP_LEVEL.includes(method)) {
|
|
435
|
-
let isSchema;
|
|
436
|
-
if (typeChecker) {
|
|
437
|
-
const typeResult = isZodSchemaByType(call, typeChecker);
|
|
438
|
-
isSchema = typeResult === true || typeResult === null && isLikelySchemaExpr(obj);
|
|
439
|
-
} else {
|
|
440
|
-
isSchema = isLikelySchemaExpr(obj);
|
|
441
|
-
}
|
|
442
|
-
if (!isSchema && isSchemaVariable(call, obj.trim())) {
|
|
443
|
-
isSchema = true;
|
|
444
|
-
}
|
|
445
|
-
if (!isSchema) continue;
|
|
475
|
+
if (![...TOP_LEVEL_METHODS, ...RENAMED_METHODS.keys(), TRANSFORM_METHOD, "unwrap", ...CHECK_WRAP_METHODS].includes(method)) continue;
|
|
476
|
+
if (TOP_LEVEL_METHODS.includes(method)) {
|
|
446
477
|
const argsStr = args.length > 0 ? `, ${args.join(", ")}` : "";
|
|
447
478
|
call.replaceWithText(`z.${method}(${obj}${argsStr})`);
|
|
448
479
|
count++;
|
|
@@ -475,15 +506,17 @@ function transformMethods(file, typeChecker) {
|
|
|
475
506
|
}
|
|
476
507
|
return count;
|
|
477
508
|
}
|
|
478
|
-
function transformConstructorReplacements(file) {
|
|
509
|
+
function transformConstructorReplacements(file, typeChecker) {
|
|
479
510
|
let count = 0;
|
|
480
511
|
const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression).reverse();
|
|
512
|
+
const receivers = analyzeCallReceivers(calls, [...Object.keys(CONSTRUCTOR_REPLACEMENTS), "datetime"], typeChecker);
|
|
481
513
|
for (const call of calls) {
|
|
482
|
-
if (call.wasForgotten()) continue;
|
|
514
|
+
if (call.wasForgotten() || !receivers.get(call)?.schema) continue;
|
|
483
515
|
const method = getMethodName(call);
|
|
484
516
|
if (!method) continue;
|
|
485
517
|
const obj = getCallObject(call);
|
|
486
518
|
if (!obj) continue;
|
|
519
|
+
if (!(method in CONSTRUCTOR_REPLACEMENTS) && method !== "datetime") continue;
|
|
487
520
|
if (method in CONSTRUCTOR_REPLACEMENTS && call.getArguments().length === 0) {
|
|
488
521
|
const match = obj.match(/^z\s*\.object\(([\s\S]*)\)$/);
|
|
489
522
|
if (!match) continue;
|
|
@@ -528,9 +561,9 @@ function transformPropertyAccessors(file, typeChecker) {
|
|
|
528
561
|
let isSchema;
|
|
529
562
|
if (typeChecker) {
|
|
530
563
|
const typeResult = isZodSchemaByTypePA(pa, typeChecker);
|
|
531
|
-
isSchema = typeResult === true || typeResult === null &&
|
|
564
|
+
isSchema = typeResult === true || typeResult === null && schemaKind(receiver) !== null;
|
|
532
565
|
} else {
|
|
533
|
-
isSchema =
|
|
566
|
+
isSchema = schemaKind(receiver) !== null;
|
|
534
567
|
}
|
|
535
568
|
if (!isSchema) continue;
|
|
536
569
|
pa.replaceWithText(`${receiverText}.${replacement}`);
|
|
@@ -549,7 +582,7 @@ function findInternalPropertyAccess(file, typeChecker) {
|
|
|
549
582
|
const receiverText = receiver.getText();
|
|
550
583
|
if (NAMESPACE_IDENTIFIERS.has(receiverText.trim())) continue;
|
|
551
584
|
if (receiverText.includes("._zod.def.") || receiverText.endsWith("._zod.def")) continue;
|
|
552
|
-
if (
|
|
585
|
+
if (schemaKind(receiver) !== null) continue;
|
|
553
586
|
if (typeChecker) {
|
|
554
587
|
const typeResult = isZodSchemaByTypePA(pa, typeChecker);
|
|
555
588
|
if (typeResult === false) continue;
|
|
@@ -562,12 +595,14 @@ function findInternalPropertyAccess(file, typeChecker) {
|
|
|
562
595
|
}
|
|
563
596
|
return results;
|
|
564
597
|
}
|
|
565
|
-
function findObjectOnlyMethods(file) {
|
|
598
|
+
function findObjectOnlyMethods(file, typeChecker) {
|
|
566
599
|
const results = [];
|
|
567
600
|
const calls = file.getDescendantsOfKind(SyntaxKind.CallExpression);
|
|
601
|
+
const bounds = analyzeCallReceivers(calls, ["min", "max"], typeChecker);
|
|
568
602
|
for (const call of calls) {
|
|
569
603
|
const method = getMethodName(call);
|
|
570
|
-
if (!method
|
|
604
|
+
if (!method) continue;
|
|
605
|
+
if (!WARN_METHODS.includes(method) && bounds.get(call)?.kind !== "date") continue;
|
|
571
606
|
results.push({
|
|
572
607
|
line: call.getStartLineNumber(),
|
|
573
608
|
method,
|
|
@@ -603,42 +638,49 @@ function transformClassRefs(file) {
|
|
|
603
638
|
let count = 0;
|
|
604
639
|
const runtimeCoreImports = /* @__PURE__ */ new Set();
|
|
605
640
|
const typeOnlyCoreImports = /* @__PURE__ */ new Set();
|
|
641
|
+
const replacements = [];
|
|
642
|
+
const queueReplacement = (node, newText) => {
|
|
643
|
+
replacements.push({ span: { start: node.getStart(), length: node.getWidth() }, newText });
|
|
644
|
+
};
|
|
606
645
|
const propAccesses = file.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression);
|
|
607
646
|
for (const pa of propAccesses) {
|
|
608
647
|
if (pa.wasForgotten()) continue;
|
|
609
648
|
const text = pa.getText();
|
|
610
649
|
const miniReplacement = MINI_CLASS_RENAMES[text];
|
|
611
650
|
if (miniReplacement) {
|
|
612
|
-
pa
|
|
651
|
+
queueReplacement(pa, miniReplacement);
|
|
613
652
|
count++;
|
|
614
653
|
continue;
|
|
615
654
|
}
|
|
616
655
|
const coreReplacement = CORE_CLASS_RENAMES[text];
|
|
617
656
|
if (coreReplacement) {
|
|
618
|
-
pa
|
|
657
|
+
queueReplacement(pa, coreReplacement);
|
|
619
658
|
runtimeCoreImports.add(coreReplacement);
|
|
620
659
|
count++;
|
|
621
660
|
}
|
|
622
661
|
}
|
|
662
|
+
if (replacements.length > 0) file.applyTextChanges(replacements);
|
|
663
|
+
replacements.length = 0;
|
|
623
664
|
const qualNames = file.getDescendantsOfKind(SyntaxKind.QualifiedName);
|
|
624
665
|
for (const qn of qualNames) {
|
|
625
666
|
if (qn.wasForgotten()) continue;
|
|
626
667
|
const text = qn.getText();
|
|
627
668
|
const miniReplacement = MINI_CLASS_RENAMES[text];
|
|
628
669
|
if (miniReplacement) {
|
|
629
|
-
qn
|
|
670
|
+
queueReplacement(qn, miniReplacement);
|
|
630
671
|
count++;
|
|
631
672
|
continue;
|
|
632
673
|
}
|
|
633
674
|
const coreReplacement = CORE_CLASS_RENAMES[text];
|
|
634
675
|
if (coreReplacement) {
|
|
635
|
-
qn
|
|
676
|
+
queueReplacement(qn, coreReplacement);
|
|
636
677
|
if (!runtimeCoreImports.has(coreReplacement)) {
|
|
637
678
|
typeOnlyCoreImports.add(coreReplacement);
|
|
638
679
|
}
|
|
639
680
|
count++;
|
|
640
681
|
}
|
|
641
682
|
}
|
|
683
|
+
if (replacements.length > 0) file.applyTextChanges(replacements);
|
|
642
684
|
const importTypes = file.getDescendantsOfKind(SyntaxKind.ImportType);
|
|
643
685
|
for (const itn of importTypes) {
|
|
644
686
|
if (itn.wasForgotten()) continue;
|
|
@@ -733,9 +775,9 @@ function transformFile(file, typeChecker) {
|
|
|
733
775
|
let methods = 0;
|
|
734
776
|
let propertyAccessors = 0;
|
|
735
777
|
for (let i = 0; i < 10; i++) {
|
|
736
|
-
const cr = transformConstructorReplacements(file);
|
|
778
|
+
const cr = transformConstructorReplacements(file, typeChecker);
|
|
737
779
|
const w = transformWrappers(file, typeChecker);
|
|
738
|
-
const c = transformChecks(file);
|
|
780
|
+
const c = transformChecks(file, typeChecker);
|
|
739
781
|
const m = transformMethods(file, typeChecker);
|
|
740
782
|
const pa = transformPropertyAccessors(file, typeChecker);
|
|
741
783
|
constructorReplacements += cr;
|
|
@@ -746,7 +788,7 @@ function transformFile(file, typeChecker) {
|
|
|
746
788
|
if (cr + w + c + m + pa === 0) break;
|
|
747
789
|
}
|
|
748
790
|
const classRefs = transformClassRefs(file);
|
|
749
|
-
const objectOnlyWarnings = findObjectOnlyMethods(file);
|
|
791
|
+
const objectOnlyWarnings = findObjectOnlyMethods(file, typeChecker);
|
|
750
792
|
const propertyAccessWarnings = findInternalPropertyAccess(file, typeChecker);
|
|
751
793
|
ensureZImport(file);
|
|
752
794
|
const imports = 0;
|
|
@@ -768,6 +810,9 @@ function transformCode(code, options) {
|
|
|
768
810
|
try {
|
|
769
811
|
const project = options?.project ?? new Project({
|
|
770
812
|
useInMemoryFileSystem: true,
|
|
813
|
+
// Syntax-only mode needs local binding symbols, not standard-library types.
|
|
814
|
+
// Loading the libs for each file dominates alias resolution in this mode.
|
|
815
|
+
skipLoadingLibFiles: true,
|
|
771
816
|
compilerOptions: { strict: false }
|
|
772
817
|
});
|
|
773
818
|
const filename = options?.filename ?? "transform.ts";
|
|
@@ -789,7 +834,7 @@ function transformCode(code, options) {
|
|
|
789
834
|
return { code, changed: false };
|
|
790
835
|
}
|
|
791
836
|
}
|
|
792
|
-
var WRAPPER_METHODS, NAMESPACE_IDENTIFIERS, ZOD_ONLY_CHECK_METHODS, AMBIGUOUS_CHECK_METHODS, STRING_RENAME, NUMBER_RENAME,
|
|
837
|
+
var WRAPPER_METHODS, NAMESPACE_IDENTIFIERS, ZOD_ONLY_CHECK_METHODS, AMBIGUOUS_CHECK_METHODS, STRING_RENAME, NUMBER_RENAME, TOP_LEVEL_METHODS, RENAMED_METHODS, TRANSFORM_METHOD, CHECK_WRAP_METHODS, CONSTRUCTOR_REPLACEMENTS, INTERNAL_PROPERTY_ACCESSORS, WARN_METHODS, MINI_CLASS_RENAMES, CORE_CLASS_RENAMES;
|
|
793
838
|
var init_transforms = __esm({
|
|
794
839
|
"../zod-to-mini/src/transforms.ts"() {
|
|
795
840
|
WRAPPER_METHODS = ["optional", "nullable"];
|
|
@@ -835,8 +880,7 @@ var init_transforms = __esm({
|
|
|
835
880
|
min: "gte",
|
|
836
881
|
max: "lte"
|
|
837
882
|
};
|
|
838
|
-
|
|
839
|
-
AMBIGUOUS_TOP_LEVEL = ["partial", "extend", "catchall", "omit", "pick"];
|
|
883
|
+
TOP_LEVEL_METHODS = ["pipe", "brand", "parse", "safeParse", "partial", "extend", "catchall", "omit", "pick"];
|
|
840
884
|
RENAMED_METHODS = /* @__PURE__ */ new Map([
|
|
841
885
|
["default", "_default"]
|
|
842
886
|
]);
|
|
@@ -1878,7 +1922,7 @@ function zodToSource(schema, ctx) {
|
|
|
1878
1922
|
if (schema instanceof $ZodString) {
|
|
1879
1923
|
const tableName = schema._tableName ?? (schema.description?.startsWith("convexId:") ? schema.description.slice("convexId:".length) : void 0);
|
|
1880
1924
|
if (tableName) {
|
|
1881
|
-
return `zx.id(
|
|
1925
|
+
return `zx.id(${JSON.stringify(tableName)})`;
|
|
1882
1926
|
}
|
|
1883
1927
|
}
|
|
1884
1928
|
if (schema instanceof $ZodCodec && isZxDateCodec(schema)) {
|
|
@@ -1907,7 +1951,10 @@ function zodToSource(schema, ctx) {
|
|
|
1907
1951
|
if (schema instanceof $ZodAny) return "z.any()";
|
|
1908
1952
|
if (schema instanceof $ZodObject) {
|
|
1909
1953
|
const shape = schema._zod.def.shape;
|
|
1910
|
-
const fields = Object.entries(shape).map(([key, value]) =>
|
|
1954
|
+
const fields = Object.entries(shape).map(([key, value]) => {
|
|
1955
|
+
const property = key === "__proto__" ? `[${JSON.stringify(key)}]` : /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key);
|
|
1956
|
+
return `${property}: ${zodToSource(value, ctx)}`;
|
|
1957
|
+
}).join(", ");
|
|
1911
1958
|
return `z.object({ ${fields} })`;
|
|
1912
1959
|
}
|
|
1913
1960
|
if (schema instanceof $ZodArray) {
|
|
@@ -1915,13 +1962,13 @@ function zodToSource(schema, ctx) {
|
|
|
1915
1962
|
}
|
|
1916
1963
|
if (schema instanceof $ZodEnum) {
|
|
1917
1964
|
const entries = schema._zod.def.entries;
|
|
1918
|
-
const values = Object.values(entries).map((v7) =>
|
|
1965
|
+
const values = Object.values(entries).map((v7) => JSON.stringify(v7)).join(", ");
|
|
1919
1966
|
return `z.enum([${values}])`;
|
|
1920
1967
|
}
|
|
1921
1968
|
if (schema instanceof $ZodLiteral) {
|
|
1922
1969
|
const values = schema._zod.def.values;
|
|
1923
1970
|
const value = values.values().next().value;
|
|
1924
|
-
if (typeof value === "string") return `z.literal(
|
|
1971
|
+
if (typeof value === "string") return `z.literal(${JSON.stringify(value)})`;
|
|
1925
1972
|
return `z.literal(${value})`;
|
|
1926
1973
|
}
|
|
1927
1974
|
if (schema instanceof $ZodUnion) {
|