zod-compiler 1.22.0 → 1.22.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.
- package/README.md +154 -588
- package/dist/cli/commands/generate.d.ts +0 -2
- package/dist/cli/commands/generate.d.ts.map +1 -1
- package/dist/cli/commands/generate.js +0 -2
- package/dist/cli/commands/generate.js.map +1 -1
- package/dist/cli/commands/watch.d.ts +0 -1
- package/dist/cli/commands/watch.d.ts.map +1 -1
- package/dist/cli/commands/watch.js +0 -2
- package/dist/cli/commands/watch.js.map +1 -1
- package/dist/cli/index.js +0 -7
- package/dist/cli/index.js.map +1 -1
- package/dist/core/codegen/build-path.d.ts +48 -0
- package/dist/core/codegen/build-path.d.ts.map +1 -0
- package/dist/core/codegen/build-path.js +642 -0
- package/dist/core/codegen/build-path.js.map +1 -0
- package/dist/core/codegen/context.d.ts +106 -9
- package/dist/core/codegen/context.d.ts.map +1 -1
- package/dist/core/codegen/context.js +89 -39
- package/dist/core/codegen/context.js.map +1 -1
- package/dist/core/codegen/dedupe.d.ts +7 -0
- package/dist/core/codegen/dedupe.d.ts.map +1 -1
- package/dist/core/codegen/dedupe.js +7 -0
- package/dist/core/codegen/dedupe.js.map +1 -1
- package/dist/core/codegen/fast-path.d.ts.map +1 -1
- package/dist/core/codegen/fast-path.js +11 -5
- package/dist/core/codegen/fast-path.js.map +1 -1
- package/dist/core/codegen/index.d.ts.map +1 -1
- package/dist/core/codegen/index.js +95 -5
- package/dist/core/codegen/index.js.map +1 -1
- package/dist/core/codegen/issue-decls.d.ts +40 -0
- package/dist/core/codegen/issue-decls.d.ts.map +1 -1
- package/dist/core/codegen/issue-decls.js +70 -0
- package/dist/core/codegen/issue-decls.js.map +1 -1
- package/dist/core/codegen/regex-unroll.d.ts +36 -0
- package/dist/core/codegen/regex-unroll.d.ts.map +1 -0
- package/dist/core/codegen/regex-unroll.js +231 -0
- package/dist/core/codegen/regex-unroll.js.map +1 -0
- package/dist/core/codegen/schemas/array.d.ts.map +1 -1
- package/dist/core/codegen/schemas/array.js +22 -5
- package/dist/core/codegen/schemas/array.js.map +1 -1
- package/dist/core/codegen/schemas/default.d.ts +15 -0
- package/dist/core/codegen/schemas/default.d.ts.map +1 -1
- package/dist/core/codegen/schemas/default.js +26 -5
- package/dist/core/codegen/schemas/default.js.map +1 -1
- package/dist/core/codegen/schemas/discriminated-union.d.ts.map +1 -1
- package/dist/core/codegen/schemas/discriminated-union.js +3 -3
- package/dist/core/codegen/schemas/discriminated-union.js.map +1 -1
- package/dist/core/codegen/schemas/map.d.ts +17 -0
- package/dist/core/codegen/schemas/map.d.ts.map +1 -1
- package/dist/core/codegen/schemas/map.js +62 -7
- package/dist/core/codegen/schemas/map.js.map +1 -1
- package/dist/core/codegen/schemas/nullable.d.ts.map +1 -1
- package/dist/core/codegen/schemas/nullable.js +2 -4
- package/dist/core/codegen/schemas/nullable.js.map +1 -1
- package/dist/core/codegen/schemas/number.d.ts.map +1 -1
- package/dist/core/codegen/schemas/number.js +25 -0
- package/dist/core/codegen/schemas/number.js.map +1 -1
- package/dist/core/codegen/schemas/object.d.ts.map +1 -1
- package/dist/core/codegen/schemas/object.js +27 -18
- package/dist/core/codegen/schemas/object.js.map +1 -1
- package/dist/core/codegen/schemas/optional.d.ts +10 -0
- package/dist/core/codegen/schemas/optional.d.ts.map +1 -1
- package/dist/core/codegen/schemas/optional.js +4 -6
- package/dist/core/codegen/schemas/optional.js.map +1 -1
- package/dist/core/codegen/schemas/record.d.ts.map +1 -1
- package/dist/core/codegen/schemas/record.js +11 -5
- package/dist/core/codegen/schemas/record.js.map +1 -1
- package/dist/core/codegen/schemas/set.d.ts.map +1 -1
- package/dist/core/codegen/schemas/set.js +11 -7
- package/dist/core/codegen/schemas/set.js.map +1 -1
- package/dist/core/codegen/schemas/string.d.ts +13 -2
- package/dist/core/codegen/schemas/string.d.ts.map +1 -1
- package/dist/core/codegen/schemas/string.js +68 -56
- package/dist/core/codegen/schemas/string.js.map +1 -1
- package/dist/core/codegen/schemas/template-literal.d.ts.map +1 -1
- package/dist/core/codegen/schemas/template-literal.js +9 -1
- package/dist/core/codegen/schemas/template-literal.js.map +1 -1
- package/dist/core/codegen/schemas/tuple.d.ts.map +1 -1
- package/dist/core/codegen/schemas/tuple.js +4 -3
- package/dist/core/codegen/schemas/tuple.js.map +1 -1
- package/dist/core/codegen/schemas/union.d.ts.map +1 -1
- package/dist/core/codegen/schemas/union.js +2 -1
- package/dist/core/codegen/schemas/union.js.map +1 -1
- package/dist/core/codegen/well-known-regex.d.ts +22 -4
- package/dist/core/codegen/well-known-regex.d.ts.map +1 -1
- package/dist/core/codegen/well-known-regex.js +27 -5
- package/dist/core/codegen/well-known-regex.js.map +1 -1
- package/dist/core/extract/extractors/default.d.ts.map +1 -1
- package/dist/core/extract/extractors/default.js +6 -1
- package/dist/core/extract/extractors/default.js.map +1 -1
- package/dist/core/extract/extractors/object.d.ts.map +1 -1
- package/dist/core/extract/extractors/object.js +11 -5
- package/dist/core/extract/extractors/object.js.map +1 -1
- package/dist/core/extract/index.d.ts +3 -3
- package/dist/core/extract/index.d.ts.map +1 -1
- package/dist/core/extract/index.js +2 -2
- package/dist/core/extract/index.js.map +1 -1
- package/dist/core/extract/registry.d.ts +2 -2
- package/dist/core/extract/registry.d.ts.map +1 -1
- package/dist/core/extract/registry.js +4 -5
- package/dist/core/extract/registry.js.map +1 -1
- package/dist/core/extract/types.d.ts +0 -11
- package/dist/core/extract/types.d.ts.map +1 -1
- package/dist/core/iife.d.ts.map +1 -1
- package/dist/core/iife.js +3 -2
- package/dist/core/iife.js.map +1 -1
- package/dist/core/pipeline.d.ts +0 -2
- package/dist/core/pipeline.d.ts.map +1 -1
- package/dist/core/pipeline.js +1 -3
- package/dist/core/pipeline.js.map +1 -1
- package/dist/core/types.d.ts +11 -0
- package/dist/core/types.d.ts.map +1 -1
- package/dist/swc.d.ts.map +1 -1
- package/dist/swc.js +0 -1
- package/dist/swc.js.map +1 -1
- package/dist/unplugin/hoist-compile.d.ts +1 -1
- package/dist/unplugin/hoist-compile.d.ts.map +1 -1
- package/dist/unplugin/hoist-compile.js +4 -4
- package/dist/unplugin/hoist-compile.js.map +1 -1
- package/dist/unplugin/index.d.ts.map +1 -1
- package/dist/unplugin/index.js +0 -3
- package/dist/unplugin/index.js.map +1 -1
- package/dist/unplugin/transform.d.ts.map +1 -1
- package/dist/unplugin/transform.js +1 -2
- package/dist/unplugin/transform.js.map +1 -1
- package/dist/unplugin/types.d.ts +0 -23
- package/dist/unplugin/types.d.ts.map +1 -1
- package/dist/unplugin/types.js.map +1 -1
- package/dist/unplugin/virtual.d.ts.map +1 -1
- package/dist/unplugin/virtual.js +11 -7
- package/dist/unplugin/virtual.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build Path: one uninstrumented pass that VALIDATES and BUILDS the stripped
|
|
3
|
+
* output together, abandoning the whole parse at the first failing check.
|
|
4
|
+
*
|
|
5
|
+
* `z.object()` strips unknown keys, so a successful parse cannot return the
|
|
6
|
+
* input by reference — it must produce a fresh object. That rules out the Fast
|
|
7
|
+
* Path (whose contract is `data === input`), and before this the only remaining
|
|
8
|
+
* option was the eager slow walk: a fully instrumented traversal that collects
|
|
9
|
+
* issues on every parse, valid or not.
|
|
10
|
+
*
|
|
11
|
+
* Two passes are wasteful in either direction. Validating first and building
|
|
12
|
+
* afterwards reads every property twice (measured 29.7 ns vs 21.6 for the slow
|
|
13
|
+
* walk on a 6-field object). Building with issue collection pays the
|
|
14
|
+
* instrumentation even when nothing fails. Doing both in ONE pass, with a
|
|
15
|
+
* sentinel instead of an issues array, beats both — and a failure costs only
|
|
16
|
+
* the checks up to the first bad one, because the issue-producing walk is
|
|
17
|
+
* deferred into `.error` exactly as `__zcFinD` does for mutation-free schemas:
|
|
18
|
+
*
|
|
19
|
+
* object clean object invalid array(8) invalid
|
|
20
|
+
* slow walk 21.6 ns 30.4 ns 197.5 ns
|
|
21
|
+
* build path 18.1 ns 7.7 ns 9.8 ns
|
|
22
|
+
*
|
|
23
|
+
* A subtree that rebuilds nothing is validated with its existing Fast Path
|
|
24
|
+
* expression and passed through by reference, so only nodes that genuinely
|
|
25
|
+
* produce a new value need code here; anything else returns null and keeps the
|
|
26
|
+
* eager walk.
|
|
27
|
+
*
|
|
28
|
+
* Coverage is what decides whether this pass is reached at all, because it is
|
|
29
|
+
* all-or-nothing per schema: ONE unmodelled node anywhere in the tree costs the
|
|
30
|
+
* whole schema its single-pass parse. Modelled, beyond the stripping containers
|
|
31
|
+
* this started with: array size checks and `.refine()`, object-level `.refine()`,
|
|
32
|
+
* `.default()` substitution, ordered string rewrites (`.trim()`,
|
|
33
|
+
* `.toLowerCase()`), and sync `.transform()`. Still declined, via
|
|
34
|
+
* {@link mutatesBeyondStrip} — coerce, `.catch()` (its callback wants the inner
|
|
35
|
+
* schema's issue list, which this pass never builds), `z.url()`, and
|
|
36
|
+
* `superRefine`.
|
|
37
|
+
*/
|
|
38
|
+
import { declareFastTemps, emitEffectCallable, emitEffectFn, emitRuntimeHelper, emitTemp, escapeString, keyMembershipTest, outputAlwaysDefined, rejectsUndefined, } from "./context.js";
|
|
39
|
+
import { createFastGen, generateFast } from "./fast-path.js";
|
|
40
|
+
import { EXTRACT_CAP, estimateFastCost, MIN_EXTRACT, predictedInlineSize } from "./fast-size.js";
|
|
41
|
+
import { ZC_HOP_DECL } from "./issue-decls.js";
|
|
42
|
+
import { defaultValueExpr, needsPostInnerDefault } from "./schemas/default.js";
|
|
43
|
+
import { innerAppliesDefaultOnUndefined } from "./schemas/optional.js";
|
|
44
|
+
import { fastStringCheck } from "./schemas/string.js";
|
|
45
|
+
/**
|
|
46
|
+
* Which nodes of `root` produce a value that is not their input — i.e. are, or
|
|
47
|
+
* contain, a stripping object. Everything else can be validated in place and
|
|
48
|
+
* passed through, which is what keeps this generator small.
|
|
49
|
+
*
|
|
50
|
+
* Computed as a fixpoint rather than a plain walk because of recursion: a
|
|
51
|
+
* `recursiveRef` is a back-edge with no children, so a local walk reads false
|
|
52
|
+
* for it and would pass the whole recursive subtree through by reference —
|
|
53
|
+
* leaving every nested value unstripped while the outermost one was rebuilt.
|
|
54
|
+
* Resolving the ref against its target closes the cycle, and iterating to a
|
|
55
|
+
* fixpoint settles the mutual dependency between the two.
|
|
56
|
+
*/
|
|
57
|
+
function rebuildSet(root) {
|
|
58
|
+
const targets = new Map([[0, root]]);
|
|
59
|
+
const nodes = [];
|
|
60
|
+
const seen = new Set();
|
|
61
|
+
const collect = (node) => {
|
|
62
|
+
if (seen.has(node))
|
|
63
|
+
return;
|
|
64
|
+
seen.add(node);
|
|
65
|
+
nodes.push(node);
|
|
66
|
+
if (node.type === "recursionTarget")
|
|
67
|
+
targets.set(node.refId, node.inner);
|
|
68
|
+
for (const child of children(node))
|
|
69
|
+
collect(child);
|
|
70
|
+
};
|
|
71
|
+
collect(root);
|
|
72
|
+
const rebuilds = new Set();
|
|
73
|
+
for (let changed = true; changed;) {
|
|
74
|
+
changed = false;
|
|
75
|
+
for (const node of nodes) {
|
|
76
|
+
if (rebuilds.has(node))
|
|
77
|
+
continue;
|
|
78
|
+
const target = node.type === "recursiveRef" ? targets.get(node.refId ?? 0) : undefined;
|
|
79
|
+
const rebuild = (node.type === "object" && node.stripUnknownKeys === true) ||
|
|
80
|
+
// `.default()` substitutes its own value for `undefined`, so its output
|
|
81
|
+
// is not its input even when the inner schema passes through — it must
|
|
82
|
+
// never be handed to `passthrough`, whose fast check would reject the
|
|
83
|
+
// absent value outright.
|
|
84
|
+
node.type === "default" ||
|
|
85
|
+
// An overwrite effect (`.trim()`, `.toLowerCase()`) rewrites the string,
|
|
86
|
+
// so the node's output is a new value: it has to be BUILT rather than
|
|
87
|
+
// validated in place (see buildString).
|
|
88
|
+
(node.type === "string" && node.checks.some((c) => c.kind === "overwrite_effect")) ||
|
|
89
|
+
// `.transform(fn)` replaces the value with the callback's result.
|
|
90
|
+
node.type === "effect" ||
|
|
91
|
+
(target !== undefined && rebuilds.has(target)) ||
|
|
92
|
+
children(node).some((child) => rebuilds.has(child));
|
|
93
|
+
if (rebuild) {
|
|
94
|
+
rebuilds.add(node);
|
|
95
|
+
changed = true;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return rebuilds;
|
|
100
|
+
}
|
|
101
|
+
/** Does `ir`, taken as a whole schema, produce a value that is not its input? */
|
|
102
|
+
export function rebuildsOutput(ir) {
|
|
103
|
+
return rebuildSet(ir).has(ir);
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* True when the subtree mutates for any reason the build pass cannot reproduce —
|
|
107
|
+
* coerce, `.catch()`, `z.url()`, `superRefine`. Those rewrite values in ways this
|
|
108
|
+
* pass (which validates, substitutes declared defaults, applies ordered string
|
|
109
|
+
* rewrites and copies) does not model, so the schema keeps the eager walk.
|
|
110
|
+
*/
|
|
111
|
+
function mutatesBeyondStrip(ir) {
|
|
112
|
+
return mutatesHere(ir) || children(ir).some(mutatesBeyondStrip);
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Does this node rewrite values on its own account (ignoring its children, and
|
|
116
|
+
* ignoring the reshaping a strip object does)? Mirrors the node-local half of
|
|
117
|
+
* `hasMutation`; the recursion above supplies the other half.
|
|
118
|
+
*/
|
|
119
|
+
function mutatesHere(ir) {
|
|
120
|
+
switch (ir.type) {
|
|
121
|
+
case "string":
|
|
122
|
+
// Overwrite effects are absent: `buildString` applies them in order. A
|
|
123
|
+
// `z.url()` check still is not — it trims, normalizes and needs try/catch.
|
|
124
|
+
return (ir.coerce === true ||
|
|
125
|
+
superRefines(ir.checks) ||
|
|
126
|
+
ir.checks.some((c) => c.kind === "string_format" && c.format === "url"));
|
|
127
|
+
case "number":
|
|
128
|
+
return ir.coerce === true || superRefines(ir.checks);
|
|
129
|
+
case "boolean":
|
|
130
|
+
case "bigint":
|
|
131
|
+
case "date":
|
|
132
|
+
return ir.coerce === true;
|
|
133
|
+
// `default` and `effect` are absent: substituting a constant for `undefined`
|
|
134
|
+
// and applying a sync transform are both modelled (see buildDefault /
|
|
135
|
+
// buildEffect), and their inners are reached through `children`.
|
|
136
|
+
//
|
|
137
|
+
// `catch` is NOT: its catchValue callback receives a ctx carrying the inner
|
|
138
|
+
// schema's collected issues, and this pass produces a sentinel instead of an
|
|
139
|
+
// issue list — there is nothing to hand it.
|
|
140
|
+
case "catch":
|
|
141
|
+
case "fallback":
|
|
142
|
+
case "stringBool":
|
|
143
|
+
return true;
|
|
144
|
+
case "object":
|
|
145
|
+
case "array":
|
|
146
|
+
return superRefines(ir.checks);
|
|
147
|
+
default:
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function superRefines(checks) {
|
|
152
|
+
return checks !== undefined && checks.some((c) => c.kind === "super_refine_effect");
|
|
153
|
+
}
|
|
154
|
+
function children(ir) {
|
|
155
|
+
switch (ir.type) {
|
|
156
|
+
case "object":
|
|
157
|
+
return ir.catchall
|
|
158
|
+
? [...Object.values(ir.properties), ir.catchall]
|
|
159
|
+
: Object.values(ir.properties);
|
|
160
|
+
case "array":
|
|
161
|
+
return [ir.element];
|
|
162
|
+
case "tuple":
|
|
163
|
+
return ir.rest === null ? ir.items : [...ir.items, ir.rest];
|
|
164
|
+
case "record":
|
|
165
|
+
case "map":
|
|
166
|
+
return [ir.keyType, ir.valueType];
|
|
167
|
+
case "set":
|
|
168
|
+
return [ir.valueType];
|
|
169
|
+
case "union":
|
|
170
|
+
case "discriminatedUnion":
|
|
171
|
+
return ir.options;
|
|
172
|
+
case "intersection":
|
|
173
|
+
return [ir.left, ir.right];
|
|
174
|
+
case "optional":
|
|
175
|
+
case "nullable":
|
|
176
|
+
case "readonly":
|
|
177
|
+
case "default":
|
|
178
|
+
case "catch":
|
|
179
|
+
case "effect":
|
|
180
|
+
case "recursionTarget":
|
|
181
|
+
return [ir.inner];
|
|
182
|
+
case "pipe":
|
|
183
|
+
return [ir.in, ir.out];
|
|
184
|
+
default:
|
|
185
|
+
return [];
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Host the whole schema as `function NAME(input){…}` returning the built value
|
|
190
|
+
* or the FAIL sentinel. Returns the function name, or null when the schema is
|
|
191
|
+
* not expressible as a single build pass.
|
|
192
|
+
*/
|
|
193
|
+
export function generateBuild(ir, ctx) {
|
|
194
|
+
const rebuilds = rebuildSet(ir);
|
|
195
|
+
if (!rebuilds.has(ir) || mutatesBeyondStrip(ir))
|
|
196
|
+
return null;
|
|
197
|
+
const fail = emitFailSentinel(ctx);
|
|
198
|
+
const scope = { temps: [], used: 0 };
|
|
199
|
+
const built = build(ir, "input", { ctx, extractable: false, fail, rebuilds, scope });
|
|
200
|
+
if (built === null)
|
|
201
|
+
return null;
|
|
202
|
+
const name = emitTemp(ctx, "vb");
|
|
203
|
+
ctx.preamble.push(`function ${name}(input){${declareFastTemps(scope)}${built.code}return ${built.value};}`);
|
|
204
|
+
return name;
|
|
205
|
+
}
|
|
206
|
+
/** One `{}` per validator, compared by identity — no parse output can equal it. */
|
|
207
|
+
function emitFailSentinel(ctx) {
|
|
208
|
+
if (ctx.buildFailName === undefined) {
|
|
209
|
+
ctx.buildFailName = `__bf_${ctx.counter++}`;
|
|
210
|
+
ctx.preamble.push(`var ${ctx.buildFailName}={};`);
|
|
211
|
+
}
|
|
212
|
+
return ctx.buildFailName;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Statements producing the built value of `ir` read from `input`, or null.
|
|
216
|
+
*
|
|
217
|
+
* Size-gated exactly like the fast path: once inlining `ir` would push the
|
|
218
|
+
* function being assembled past EXTRACT_CAP, the sub-build is hosted as its own
|
|
219
|
+
* `__vb_N(p)` returning value-or-FAIL and replaced by a call. Without this a
|
|
220
|
+
* deeply nested schema emits one enormous build function — measured at 113 KB
|
|
221
|
+
* and 354 KB on the deep fixtures — far past the bytecode size where V8 stops
|
|
222
|
+
* running TurboFan on it, which would forfeit the speed this path exists for.
|
|
223
|
+
*/
|
|
224
|
+
function build(ir, input, g) {
|
|
225
|
+
// Resolved before the passthrough shortcut below. A back-edge carries no
|
|
226
|
+
// children, so `rebuildsOutput` reads false for it — and passing it through by
|
|
227
|
+
// reference would leave every nested recursive value unstripped while the
|
|
228
|
+
// outermost one was rebuilt.
|
|
229
|
+
if (ir.type === "recursiveRef")
|
|
230
|
+
return buildRecursiveCall(ir.refId ?? 0, input, g);
|
|
231
|
+
if (ir.type === "recursionTarget")
|
|
232
|
+
return buildRecursionTarget(ir, input, g);
|
|
233
|
+
if (!g.rebuilds.has(ir))
|
|
234
|
+
return passthrough(ir, input, g);
|
|
235
|
+
const cache = (g.ctx.fastSizeCache ??= new WeakMap());
|
|
236
|
+
if (g.extractable &&
|
|
237
|
+
g.scope.used + predictedInlineSize(ir, input.length, cache) > EXTRACT_CAP &&
|
|
238
|
+
(g.scope.used > EXTRACT_CAP || estimateFastCost(ir, cache) >= MIN_EXTRACT)) {
|
|
239
|
+
const hosted = hostBuild(ir, g);
|
|
240
|
+
if (hosted !== null) {
|
|
241
|
+
const slot = local(g, "bh");
|
|
242
|
+
const code = `${slot}=${hosted}(${input});if(${slot}===${g.fail})return ${g.fail};`;
|
|
243
|
+
g.scope.used += code.length;
|
|
244
|
+
return { code, value: slot };
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
// This node's extraction decision is made; its descendants get to make their
|
|
248
|
+
// own, so an oversized hosted helper keeps splitting.
|
|
249
|
+
const before = g.scope.used;
|
|
250
|
+
const out = buildInline(ir, input, { ...g, extractable: true });
|
|
251
|
+
if (out !== null)
|
|
252
|
+
g.scope.used = before + out.code.length;
|
|
253
|
+
return out;
|
|
254
|
+
}
|
|
255
|
+
/** Host `ir`'s build in its own function over a fresh parameter; returns its name. */
|
|
256
|
+
function hostBuild(ir, g) {
|
|
257
|
+
const param = emitTemp(g.ctx, "bp");
|
|
258
|
+
const scope = { temps: [], used: 0 };
|
|
259
|
+
const inner = build(ir, param, { ...g, extractable: false, scope });
|
|
260
|
+
if (inner === null)
|
|
261
|
+
return null;
|
|
262
|
+
const name = emitTemp(g.ctx, "vb");
|
|
263
|
+
g.ctx.preamble.push(`function ${name}(${param}){${declareFastTemps(scope)}${inner.code}return ${inner.value};}`);
|
|
264
|
+
return name;
|
|
265
|
+
}
|
|
266
|
+
function buildInline(ir, input, g) {
|
|
267
|
+
switch (ir.type) {
|
|
268
|
+
case "object":
|
|
269
|
+
return buildObject(ir, input, g);
|
|
270
|
+
case "array":
|
|
271
|
+
return buildArray(ir, input, g);
|
|
272
|
+
case "tuple":
|
|
273
|
+
return buildTuple(ir, input, g);
|
|
274
|
+
case "record":
|
|
275
|
+
return buildRecord(ir, input, g);
|
|
276
|
+
case "optional":
|
|
277
|
+
// A default further down the chain consumes undefined into a value, so
|
|
278
|
+
// the `undefined → undefined` shortcut must not fire — same rule (and
|
|
279
|
+
// same helper) the slow and fast paths already apply.
|
|
280
|
+
return innerAppliesDefaultOnUndefined(ir.inner)
|
|
281
|
+
? build(ir.inner, input, g)
|
|
282
|
+
: buildSentinel(ir.inner, input, g, "===undefined", "undefined");
|
|
283
|
+
case "nullable":
|
|
284
|
+
// `null` short-circuits unconditionally in zod, whatever the inner is;
|
|
285
|
+
// undefined flows through, so an inner default still fires.
|
|
286
|
+
return buildSentinel(ir.inner, input, g, "===null", "null");
|
|
287
|
+
case "default":
|
|
288
|
+
return buildDefault(ir, input, g);
|
|
289
|
+
case "string":
|
|
290
|
+
return buildString(ir, input, g);
|
|
291
|
+
case "effect":
|
|
292
|
+
return buildEffect(ir, input, g);
|
|
293
|
+
case "readonly":
|
|
294
|
+
return build(ir.inner, input, g);
|
|
295
|
+
case "union":
|
|
296
|
+
case "discriminatedUnion":
|
|
297
|
+
return buildUnion(ir, input, g);
|
|
298
|
+
default:
|
|
299
|
+
// A rebuilding intersection, map or set: expressible in principle, but
|
|
300
|
+
// each needs its own output-shaping rules, so they keep the eager walk
|
|
301
|
+
// until there is a measured reason to add them.
|
|
302
|
+
return null;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Host the target's build once under a name registered BEFORE its body is
|
|
307
|
+
* generated, so the back-edges inside that body resolve to it.
|
|
308
|
+
*/
|
|
309
|
+
function buildRecursionTarget(ir, input, g) {
|
|
310
|
+
const table = (g.ctx.buildRecNames ??= new Map());
|
|
311
|
+
if (!table.has(ir.refId)) {
|
|
312
|
+
const name = emitTemp(g.ctx, "vbr");
|
|
313
|
+
table.set(ir.refId, name);
|
|
314
|
+
const param = emitTemp(g.ctx, "bp");
|
|
315
|
+
const scope = { temps: [], used: 0 };
|
|
316
|
+
const inner = build(ir.inner, param, { ...g, extractable: false, scope });
|
|
317
|
+
if (inner === null) {
|
|
318
|
+
table.delete(ir.refId);
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
g.ctx.preamble.push(`function ${name}(${param}){${declareFastTemps(scope)}${inner.code}return ${inner.value};}`);
|
|
322
|
+
}
|
|
323
|
+
return buildRecursiveCall(ir.refId, input, g);
|
|
324
|
+
}
|
|
325
|
+
/** Call the hosted build for a recursion target, propagating its FAIL. */
|
|
326
|
+
function buildRecursiveCall(refId, input, g) {
|
|
327
|
+
const name = g.ctx.buildRecNames?.get(refId);
|
|
328
|
+
if (name === undefined)
|
|
329
|
+
return null;
|
|
330
|
+
const slot = local(g, "bh");
|
|
331
|
+
return {
|
|
332
|
+
code: `${slot}=${name}(${input});if(${slot}===${g.fail})return ${g.fail};`,
|
|
333
|
+
value: slot,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Try each option in declaration order and take the first that builds — which
|
|
338
|
+
* is what zod's union does with the first option that parses.
|
|
339
|
+
*
|
|
340
|
+
* Every option is HOSTED rather than inlined, and that is load-bearing: a
|
|
341
|
+
* failing build signals with `return FAIL`, which inside the enclosing function
|
|
342
|
+
* would abandon the whole parse instead of moving on to the next option. Behind
|
|
343
|
+
* a call, the same signal is just a value to test.
|
|
344
|
+
*
|
|
345
|
+
* A discriminated union gets the same treatment rather than a switch: the
|
|
346
|
+
* options still have to be probed by call, and its dispatch advantage is
|
|
347
|
+
* already spent by the enclosing container's own work.
|
|
348
|
+
*/
|
|
349
|
+
function buildUnion(ir, input, g) {
|
|
350
|
+
const hosted = [];
|
|
351
|
+
for (const option of ir.options) {
|
|
352
|
+
const fn = g.rebuilds.has(option) ? hostBuild(option, g) : hostPassthrough(option, g);
|
|
353
|
+
if (fn === null)
|
|
354
|
+
return null;
|
|
355
|
+
hosted.push(fn);
|
|
356
|
+
}
|
|
357
|
+
if (hosted.length === 0)
|
|
358
|
+
return null;
|
|
359
|
+
const out = local(g, "bu");
|
|
360
|
+
let code = `${out}=${hosted[0]}(${input});`;
|
|
361
|
+
for (const fn of hosted.slice(1)) {
|
|
362
|
+
code += `if(${out}===${g.fail}){${out}=${fn}(${input});}`;
|
|
363
|
+
}
|
|
364
|
+
code += `if(${out}===${g.fail})return ${g.fail};`;
|
|
365
|
+
return { code, value: out };
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Host a non-rebuilding option as `value-or-FAIL`, so a union can probe it with
|
|
369
|
+
* the same protocol as a rebuilding one.
|
|
370
|
+
*/
|
|
371
|
+
function hostPassthrough(ir, g) {
|
|
372
|
+
const param = emitTemp(g.ctx, "bp");
|
|
373
|
+
const scope = { temps: [], used: 0 };
|
|
374
|
+
const expr = generateFast(ir, createFastGen(param, g.ctx, true, scope));
|
|
375
|
+
if (expr === null)
|
|
376
|
+
return null;
|
|
377
|
+
const name = emitTemp(g.ctx, "vp");
|
|
378
|
+
g.ctx.preamble.push(`function ${name}(${param}){${declareFastTemps(scope)}return ${expr === "true" ? param : `(${expr})?${param}:${g.fail}`};}`);
|
|
379
|
+
return name;
|
|
380
|
+
}
|
|
381
|
+
/** Validate in place with the Fast Path and hand the input straight back. */
|
|
382
|
+
function passthrough(ir, input, g) {
|
|
383
|
+
const scoped = createFastGen(input, g.ctx, true, g.scope);
|
|
384
|
+
const expr = generateFast(ir, scoped);
|
|
385
|
+
if (expr === null)
|
|
386
|
+
return null;
|
|
387
|
+
return { code: expr === "true" ? "" : `if(!(${expr}))return ${g.fail};`, value: input };
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Rebuild from the declared keys. Sound for a stripping object (that IS the
|
|
391
|
+
* output) and for a strict one (unknown keys are rejected, so the declared keys
|
|
392
|
+
* are the whole key set). A loose object or one with a `.catchall()` keeps keys
|
|
393
|
+
* this pass does not enumerate, so those bail.
|
|
394
|
+
*/
|
|
395
|
+
function buildObject(ir, input, g) {
|
|
396
|
+
if (ir.catchall !== undefined)
|
|
397
|
+
return null;
|
|
398
|
+
if (ir.stripUnknownKeys !== true && ir.strict !== true)
|
|
399
|
+
return null;
|
|
400
|
+
if (ir.suppressAbsentKeys !== undefined && ir.suppressAbsentKeys.length > 0)
|
|
401
|
+
return null;
|
|
402
|
+
// Object-level `.refine()` runs on the assembled output (below). superRefine
|
|
403
|
+
// rewrites the payload, which this pass does not model — mutatesBeyondStrip
|
|
404
|
+
// already rejects it, so this is a belt-and-braces narrowing of the type.
|
|
405
|
+
const refines = ir.checks ?? [];
|
|
406
|
+
if (refines.some((check) => check.kind !== "refine_effect"))
|
|
407
|
+
return null;
|
|
408
|
+
let code = `if(typeof ${input}!=="object"||${input}===null||Array.isArray(${input}))return ${g.fail};`;
|
|
409
|
+
if (ir.strict === true) {
|
|
410
|
+
const keyVar = local(g, "bk");
|
|
411
|
+
code += `for(${keyVar} in ${input}){if(!(${keyMembershipTest(g.ctx, Object.keys(ir.properties), keyVar)}))return ${g.fail};}`;
|
|
412
|
+
}
|
|
413
|
+
const slots = [];
|
|
414
|
+
for (const [key, propIR] of Object.entries(ir.properties)) {
|
|
415
|
+
const keyStr = escapeString(key);
|
|
416
|
+
const slot = local(g, "bv");
|
|
417
|
+
code += `${slot}=${input}[${keyStr}];`;
|
|
418
|
+
const propBuilt = build(propIR, slot, g);
|
|
419
|
+
if (propBuilt === null)
|
|
420
|
+
return null;
|
|
421
|
+
code += propBuilt.code;
|
|
422
|
+
slots.push({ always: outputAlwaysDefined(propIR), keyStr, value: propBuilt.value });
|
|
423
|
+
}
|
|
424
|
+
// Same assembly the eager strip walk uses: the longest LEADING run of
|
|
425
|
+
// always-present keys goes into one object literal (V8 stamps it from a
|
|
426
|
+
// cached boilerplate map in a single allocation), and everything after the
|
|
427
|
+
// first conditional key is appended so insertion order still matches zod.
|
|
428
|
+
// The per-key test is zod's own — keep the key when the parsed value is
|
|
429
|
+
// defined, or when it was present on the input at all.
|
|
430
|
+
const out = local(g, "bo");
|
|
431
|
+
const literal = [];
|
|
432
|
+
let appends = "";
|
|
433
|
+
let leading = true;
|
|
434
|
+
for (const slot of slots) {
|
|
435
|
+
if (leading && slot.always) {
|
|
436
|
+
literal.push(`${slot.keyStr}:${slot.value}`);
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
leading = false;
|
|
440
|
+
appends += slot.always
|
|
441
|
+
? `${out}[${slot.keyStr}]=${slot.value};`
|
|
442
|
+
: `if(${slot.value}!==undefined||(${slot.keyStr} in ${input})){${out}[${slot.keyStr}]=${slot.value};}`;
|
|
443
|
+
}
|
|
444
|
+
code += `${out}={${literal.join(",")}};${appends}`;
|
|
445
|
+
// Zod parses the properties into the payload first and skips the check chain
|
|
446
|
+
// when that produced issues, so a bad property suppresses the refine — which
|
|
447
|
+
// this pass gets for free, having already returned FAIL at that property.
|
|
448
|
+
for (const check of refines) {
|
|
449
|
+
code += `if(!${emitEffectCallable(g.ctx, check)}(${out}))return ${g.fail};`;
|
|
450
|
+
}
|
|
451
|
+
return { code, value: out };
|
|
452
|
+
}
|
|
453
|
+
function buildArray(ir, input, g) {
|
|
454
|
+
// Length checks are pure predicates over `input.length`, so they hoist ahead
|
|
455
|
+
// of the element loop: a size mismatch bails before a single element is
|
|
456
|
+
// validated. Zod reports the per-element issue first when both fail, but the
|
|
457
|
+
// build pass produces no issues — only the sentinel — and the deferred walk
|
|
458
|
+
// that does produce them keeps zod's order.
|
|
459
|
+
let sizes = "";
|
|
460
|
+
const refines = [];
|
|
461
|
+
for (const check of ir.checks) {
|
|
462
|
+
switch (check.kind) {
|
|
463
|
+
case "min_length":
|
|
464
|
+
sizes += `if(${input}.length<${check.minimum})return ${g.fail};`;
|
|
465
|
+
break;
|
|
466
|
+
case "max_length":
|
|
467
|
+
sizes += `if(${input}.length>${check.maximum})return ${g.fail};`;
|
|
468
|
+
break;
|
|
469
|
+
case "length_equals":
|
|
470
|
+
sizes += `if(${input}.length!==${check.length})return ${g.fail};`;
|
|
471
|
+
break;
|
|
472
|
+
case "refine_effect":
|
|
473
|
+
refines.push(check);
|
|
474
|
+
break;
|
|
475
|
+
default:
|
|
476
|
+
// super_refine (rewrites the value) or a check kind not modelled here.
|
|
477
|
+
return null;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
const out = local(g, "ba");
|
|
481
|
+
const index = local(g, "bi");
|
|
482
|
+
const elem = local(g, "be");
|
|
483
|
+
const inner = build(ir.element, elem, g);
|
|
484
|
+
if (inner === null)
|
|
485
|
+
return null;
|
|
486
|
+
let code = `if(!Array.isArray(${input}))return ${g.fail};` +
|
|
487
|
+
sizes +
|
|
488
|
+
`${out}=new Array(${input}.length);` +
|
|
489
|
+
`for(${index}=0;${index}<${input}.length;${index}++){` +
|
|
490
|
+
`${elem}=${input}[${index}];${inner.code}${out}[${index}]=${inner.value};}`;
|
|
491
|
+
// `.refine()` sees the parsed payload, which for a rebuilding element is the
|
|
492
|
+
// freshly assembled array — the same value zod hands its checks.
|
|
493
|
+
for (const check of refines) {
|
|
494
|
+
code += `if(!${emitEffectCallable(g.ctx, check)}(${out}))return ${g.fail};`;
|
|
495
|
+
}
|
|
496
|
+
return { code, value: out };
|
|
497
|
+
}
|
|
498
|
+
function buildTuple(ir, input, g) {
|
|
499
|
+
// Trailing-optional and rest handling shape the output length; keep those on
|
|
500
|
+
// the eager walk rather than restating the rules here.
|
|
501
|
+
if (ir.rest !== null)
|
|
502
|
+
return null;
|
|
503
|
+
if (ir.items.some((item) => !rejectsUndefined(item)))
|
|
504
|
+
return null;
|
|
505
|
+
let code = `if(!Array.isArray(${input})||${input}.length!==${ir.items.length})return ${g.fail};`;
|
|
506
|
+
const values = [];
|
|
507
|
+
for (const [index, itemIR] of ir.items.entries()) {
|
|
508
|
+
const slot = local(g, "bt");
|
|
509
|
+
code += `${slot}=${input}[${index}];`;
|
|
510
|
+
const inner = build(itemIR, slot, g);
|
|
511
|
+
if (inner === null)
|
|
512
|
+
return null;
|
|
513
|
+
code += inner.code;
|
|
514
|
+
values.push(inner.value);
|
|
515
|
+
}
|
|
516
|
+
const out = local(g, "bl");
|
|
517
|
+
code += `${out}=[${values.join(",")}];`;
|
|
518
|
+
return { code, value: out };
|
|
519
|
+
}
|
|
520
|
+
function buildRecord(ir, input, g) {
|
|
521
|
+
const plainStringKey = ir.keyType.type === "string" && ir.keyType.checks.length === 0 && ir.keyType.coerce !== true;
|
|
522
|
+
if (!plainStringKey)
|
|
523
|
+
return null;
|
|
524
|
+
const out = local(g, "br");
|
|
525
|
+
const keyVar = local(g, "brk");
|
|
526
|
+
const valVar = local(g, "brv");
|
|
527
|
+
const inner = build(ir.valueType, valVar, g);
|
|
528
|
+
if (inner === null)
|
|
529
|
+
return null;
|
|
530
|
+
const hop = emitRuntimeHelper(g.ctx, "__zcHop", ZC_HOP_DECL);
|
|
531
|
+
const code = `if(typeof ${input}!=="object"||${input}===null||Array.isArray(${input}))return ${g.fail};` +
|
|
532
|
+
`${out}={};` +
|
|
533
|
+
`for(${keyVar} in ${input}){if(${hop}.call(${input},${keyVar})){` +
|
|
534
|
+
`${valVar}=${input}[${keyVar}];${inner.code}${out}[${keyVar}]=${inner.value};}}`;
|
|
535
|
+
return { code, value: out };
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* `.transform(fn)`: validate the inner schema, then hand its parsed value to the
|
|
539
|
+
* callback. Zod's transform is a pipe whose `in` failing aborts the whole thing,
|
|
540
|
+
* which is exactly what returning FAIL from the inner build does — so the
|
|
541
|
+
* callback runs only on a clean parse, as `slowEffect` guarantees with its issue
|
|
542
|
+
* count.
|
|
543
|
+
*
|
|
544
|
+
* The IR reaches here only for a synchronous single-argument callback: a
|
|
545
|
+
* `ctx`-taking or async transform is extracted as a `fallback` instead
|
|
546
|
+
* (see extractPipe), so there is no parse context to reproduce.
|
|
547
|
+
*/
|
|
548
|
+
function buildEffect(ir, input, g) {
|
|
549
|
+
const inner = build(ir.inner, input, g);
|
|
550
|
+
if (inner === null)
|
|
551
|
+
return null;
|
|
552
|
+
const out = local(g, "bx");
|
|
553
|
+
return {
|
|
554
|
+
code: `${inner.code}${out}=${emitEffectCallable(g.ctx, ir)}(${inner.value});`,
|
|
555
|
+
value: out,
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* A string carrying an overwrite effect (`.trim()`, `.toLowerCase()`, ...): the
|
|
560
|
+
* checks are emitted one statement at a time in DECLARATION order, interleaved
|
|
561
|
+
* with the rewrites, because a rewrite is visible to every check after it —
|
|
562
|
+
* `z.string().trim().min(1)` rejects `" "` where `z.string().min(1).trim()`
|
|
563
|
+
* accepts it. That ordering is exactly why the fast path, which sorts checks
|
|
564
|
+
* cheapest-first and returns the input unchanged, has to decline these.
|
|
565
|
+
*
|
|
566
|
+
* Only reached for a rewriting string; a check-only one never enters the rebuild
|
|
567
|
+
* set and is validated in place by `passthrough`.
|
|
568
|
+
*/
|
|
569
|
+
function buildString(ir, input, g) {
|
|
570
|
+
if (ir.coerce === true)
|
|
571
|
+
return null;
|
|
572
|
+
const value = local(g, "bs");
|
|
573
|
+
let code = `if(typeof ${input}!=="string")return ${g.fail};${value}=${input};`;
|
|
574
|
+
for (const check of ir.checks) {
|
|
575
|
+
switch (check.kind) {
|
|
576
|
+
case "overwrite_effect":
|
|
577
|
+
code += `${value}=${emitEffectFn(g.ctx, check.source)}(${value});`;
|
|
578
|
+
break;
|
|
579
|
+
case "refine_effect":
|
|
580
|
+
code += `if(!${emitEffectCallable(g.ctx, check)}(${value}))return ${g.fail};`;
|
|
581
|
+
break;
|
|
582
|
+
case "super_refine_effect":
|
|
583
|
+
// Rewrites through zod's payload; mutatesBeyondStrip already rejects it.
|
|
584
|
+
return null;
|
|
585
|
+
default: {
|
|
586
|
+
const expr = fastStringCheck(check, value, g.ctx);
|
|
587
|
+
if (expr === null)
|
|
588
|
+
return null; // z.url(), unknown format
|
|
589
|
+
code += `if(!(${expr}))return ${g.fail};`;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
return { code, value };
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* `.default(v)`: `undefined` yields the declared value without running the
|
|
597
|
+
* inner schema, anything else parses normally — the same two branches
|
|
598
|
+
* `slowDefault` emits, reading the value off the retained schema so a
|
|
599
|
+
* reference-typed default keeps zod's identity (one shared object, not a copy).
|
|
600
|
+
*
|
|
601
|
+
* The substituted value is not validated, so it makes the fast path a PARTIAL
|
|
602
|
+
* predicate (`fc(undefined)` is false where the schema accepts) — which is why
|
|
603
|
+
* this records {@link CodeGenContext.buildSubstitutesValue}, on which
|
|
604
|
+
* `generateValidator` withholds `.is()`.
|
|
605
|
+
*/
|
|
606
|
+
function buildDefault(ir, input, g) {
|
|
607
|
+
const inner = build(ir.inner, input, g);
|
|
608
|
+
if (inner === null)
|
|
609
|
+
return null;
|
|
610
|
+
// Every `default` node is in the rebuild set, so it is always BUILT and never
|
|
611
|
+
// passed through — which makes this flag an exact record of whether the
|
|
612
|
+
// finished pass substitutes a value.
|
|
613
|
+
g.ctx.buildSubstitutesValue = true;
|
|
614
|
+
const out = local(g, "bq");
|
|
615
|
+
const value = defaultValueExpr(ir);
|
|
616
|
+
// Zod re-applies the default when the inner returns undefined for a defined
|
|
617
|
+
// input; only emitted when the inner can actually do that.
|
|
618
|
+
const reapply = needsPostInnerDefault(ir) ? `if(${out}===undefined){${out}=${value};}` : "";
|
|
619
|
+
return {
|
|
620
|
+
code: `if(${input}===undefined){${out}=${value};}` +
|
|
621
|
+
`else{${inner.code}${out}=${inner.value};${reapply}}`,
|
|
622
|
+
value: out,
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
/** `optional` / `nullable` around a rebuilding inner: pass the sentinel through. */
|
|
626
|
+
function buildSentinel(innerIR, input, g, test, sentinel) {
|
|
627
|
+
const inner = build(innerIR, input, g);
|
|
628
|
+
if (inner === null)
|
|
629
|
+
return null;
|
|
630
|
+
const out = local(g, "bw");
|
|
631
|
+
return {
|
|
632
|
+
code: `if(${input}${test}){${out}=${sentinel};}else{${inner.code}${out}=${inner.value};}`,
|
|
633
|
+
value: out,
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
/** Allocate a `var` the hosted build function declares. */
|
|
637
|
+
function local(g, prefix) {
|
|
638
|
+
const name = emitTemp(g.ctx, prefix);
|
|
639
|
+
g.scope.temps.push(name);
|
|
640
|
+
return name;
|
|
641
|
+
}
|
|
642
|
+
//# sourceMappingURL=build-path.js.map
|