You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit e0e51a5
Browse filesBrowse the repository at this point in the historyBrowse files
docs(v4): cut the compile comments down to what they explain (#6449)
The comments added with `z.compile` had become an account of how each decision was reached β a setup sentence, the approach tried first, then the same point restated. The longest ran 1155 characters.
Nothing over 300 remains in these three files. What each comment guards is kept: the issue numbers, the measured figures behind `stringLengthInCodePoints`, and the reason a construct is refused rather than compiled.
Code is byte-identical β stripping every comment from both revisions leaves the three files unchanged.
Follows the rule added in 463ebb3.
Copy file name to clipboardExpand all lines: packages/zod/src/compile.ts
+2-2Lines changed: 2 additions & 2 deletions
Original file line number
Diff line number
Diff line change
@@ -1,4 +1,4 @@
1
-
// Side-effect-only module: enables AOT compilation for every schema constructed after this import. The only operation is installing a post-processor on `globalConfig`. Bundlers preserve this import because the file is listed in `package.json`'s `sideEffects` array; nothing else in `zod` references it, so apps that don't `import "zod/compile"` drop the entire compiler.
1
+
// Side-effect-only: installs the post-processor on `globalConfig`. Listed in `package.json`'s `sideEffects`, and nothing else references it, so apps that never import it drop the compiler.
// Only the run wrapper is installed. Copying the compiled parse/safeParse closures here would make their INVALID fallback re-enter this instance's methods β which now route through the compiled run β executing user callbacks a third time on invalid input. The method β wrapper path runs them exactly twice.
37
+
// Only the run wrapper. Copying the compiled parse/safeParse closures would make their fallback re-enter this instance and run user callbacks a third time.
Copy file name to clipboardExpand all lines: packages/zod/src/v4/core/compile.ts
+17-19Lines changed: 17 additions & 19 deletions
Original file line number
Diff line number
Diff line change
@@ -121,7 +121,7 @@ export function compile<T extends SomeType>(schema: T): T {
121
121
returnoriginalRun(payload,ctx);
122
122
}
123
123
124
-
// The value is a placeholder the runtime memoizer is still filling in, so a reference cycle closes here. Only the runtime can finish it β and a transform on the cycle has to raise $ZodCyclicError from its own parse, which a compiled node would skip. Cheap to ask: no memo state on the ctx means no cycle in flight, which is every ordinary parse.
124
+
// A memoized back-edge: only the runtime can close a reference cycle, and a transform on one must raise $ZodCyclicError from its own parse.
125
125
if(ctx&&isBackEdge(ctx,payload.value)){
126
126
returnoriginalRun(payload,ctx);
127
127
}
@@ -185,7 +185,7 @@ export function compileFastpass<T extends SomeType>(
185
185
schema: T,
186
186
options?: CompileFastpassOptions
187
187
): CompiledFastpass<core.output<T>>{
188
-
// A recursive schema can be re-entered by a single parse, which is how input containing a reference cycle terminates: the runtime memoizer registers each in-progress output before its children run, keyed on the parse context every schema in that call shares. The generated fast path takes an input and returns a value β it has no context to key on, so it would follow the cycle in the input until the stack ran out. Hand the whole schema to the runtime. Walking the graph reads `shape`, which some schemas define as a getter that throws (`z.pick()` with an unrecognized mask key). Treat "can't tell" as recursive: the runtime raises that error from the parse where it belongs, and every escape from here stays a ZodCompileUnsupportedError.
188
+
// Cycle-breaking is keyed on the parse context, which generated code never receives. `shape` can be a getter that throws (z.pick() with an unrecognized mask key), so treat "can't tell" as recursive.
189
189
letrecursive=true;
190
190
try{
191
191
recursive=isRecursiveSchema(schemaasany);
@@ -245,7 +245,7 @@ function newVar(ctx: CompileContext): string {
245
245
return`v${ctx.varCounter++}`;
246
246
}
247
247
248
-
// Runtime helper called from inside the compiled fast path. Black-boxes a child schema by running its `_zod.run` with a fresh payload. Returns either the parsed value, INVALID (validation failed, triggers outer fallback), or signals async-boundary-violation by returning INVALID when the run resolves asynchronously. Used by the runtime-island pattern (see `compileChild`).
248
+
// Runs a child schema as a black box: its value, or INVALID for a failure or an asyncrun.
// Custom `when` gates make the runtime skip a check conditionally; the fast path always runs it, which diverges (dangerously so for value-mutating checks). The six size/length classes auto-default `when` to "skip after aborting issues" β satisfied by the fast path's bail-on-first-failure, and they never mutate values, so they stay compilable.
312
+
// A custom `when` skips a check the fast path always runs; the one auto-defaulted on size/length classes matches its bail-on-first-failure.
// Formats whose `pattern` IS the entire check, so testing the regex is exact. A pattern is not on its own evidence of that: `credit_card` advertises a shape-only pattern and validates the Luhn digit separately, and `base64`, `ipv6` and friends do the same. Emitting the regex for one of those silently accepts invalid input, which is why this is an allowlist rather than an `if (def.pattern)` catch-all β an unrecognized format falls through to the throw below and takes the runtime path instead of a wrong fast one.
743
+
// Formats whose `pattern` IS the whole check. An allowlist rather than `if (def.pattern)`, because credit_card, base64 and ipv6 carry a shape-only pattern and validate the rest separately.
// Coercion is modelled nowhere: a coercing schema would compile to the bare type test and reject everything it was supposed to convert. Standalone the wrapper hides that, but inside a union a rejected branch is indistinguishable from one the runtime rejected, so a later branch wins and the parse silently returns a different value. Refuse at codegen time, which the union honours.
829
+
// A coercing schema would compile to the bare type test and reject what it should convert; inside a union that reads as a rejected branch, so refuse at codegen.
// A string-format schema (z.email(), z.creditCard(), z.hostname(), β¦) carries its format on its own def rather than in def.checks, while z.string().email() puts it in def.checks. Both route through generateStringFormatCheck so the two can never drift: keeping a second copy of the format table here is what let z.creditCard() compile to its shape-only regex without the Luhn digit.
969
+
// z.email()carries its format on the def, z.string().email() in def.checks; both route here so the format table has no second copy to drift from.
// Any rung of the optin ladder means the container may omit this key. The runtime runs such properties even when absent, then ignores issues on absent keys only when the output is optional too. This is what makes exactOptional compositional: the child rejects explicit undefined, while the object layer suppresses that failure only for an actually absent key.
1067
+
// Any optin rung means the key may be omitted. The runtime runs the property anyway and ignores issues only when the key is genuinely absent, which is what makes exactOptional compositional.
1068
1068
constoutputVar=newVar(ctx);
1069
1069
doc.write(`let ${outputVar} = (() => {`);
1070
1070
doc.indented((d)=>{
@@ -1103,7 +1103,7 @@ function generateObjectCheck(doc: Doc, ctx: CompileContext, schema: SomeType, ac
1103
1103
constcatchallType=catchall._zod.def.type;
1104
1104
1105
1105
if(catchallType==="never"){
1106
-
// Strict object: reject unknown keys. Runtime iterates with for...in, so inherited enumerable keys count as unrecognized. An undeclared `__proto__` counts too (handleCatchall reports it before skipping the copy, see #6221) β it is only excluded from the *output*, never from this scan. A declared `__proto__` can't reach here; the shape key is rejected at compile time above. One `for...in` for every shape, which is what the runtime does. An own-key count is faster but only equivalent for a plain prototype, and guarding on the prototype meant rejecting a class instance whose own enumerable keys match β input the runtime accepts. Standalone the wrapper hid that; inside a union the branch merely looked rejected and a later one won, so the parse returned a different value with no error at all. `|| "true"` for an empty shape: with no keys the join is "" and the emitted `if () return INVALID;` is a syntax error, which the single top-level `new Function` rejects long after compileChild's per-branch catch could island it β so the whole tree lost its fast path. An empty strict object rejects any own enumerable key, which is what `true` says.
1106
+
// Strict: one `for...in`, as the runtime does, so inherited enumerable keys count. An undeclared `__proto__` is reported here and excluded only from the output (#6221); an own-key count would wrongly reject a class instance.
@@ -1118,7 +1118,7 @@ function generateObjectCheck(doc: Doc, ctx: CompileContext, schema: SomeType, ac
1118
1118
}
1119
1119
// else: strip mode (no catchall) - unknown keys ignored, only include known keys
1120
1120
1121
-
// Build the output: shape keys first in declared order (the runtime assigns them before its catchall loop), then unknown keys in for...in order. Runtime inclusion rule (handlePropertyResult): a key on the middlerung is included iff the key is present on the input; otherwise iff its output value !== undefined OR the key is present. Props that can never output undefined keep the fast object-literal form.
1121
+
// Shape keys in declared order, then unknown keys in for...in order. A middle-rung key is included iff present on the input, else iff its output is not undefined.
// A required object key whose value-level fast path would silently accept an absent key (which reads as `undefined`) needs an explicit `key in input` guard. Without it, schemas like `z.undefined()` / `z.any()` / unions containing undefined would pass for missing properties even though the runtime rejects them.
1211
+
// A value-level fast path reads an absent key as `undefined`, so z.undefined(), z.any() and unions containing undefined would accept a missing property the runtime rejects.
// A coercing schema materialises a value out of an absent key β `z.coerce.string()` turns one into "undefined" β but the runtime object refuses to let a coercion fill a key that was not there (#6405). Compilation refuses coercion, so the child becomes a runtime island, and an island is handed `input[key]` with no way to tell absent from explicitly undefined. Report it as absence-accepting so the object emits the presence guard that keeps the two apart.
1217
+
// An islandis handed `input[key]` and cannot tell absent from explicitly undefined, so report absence-accepting and let the object emit the presence guard (#6405).
// `_zod.values` is cleared by z.partialRecord and similar helpers when they want a schema that *infers* like an enum but isn't structurally enumerated. Without a known value set the fast path can't check membership. Throw (rather than emit `return INVALID`) so containers island this child and unions fall back whole β a falsely-rejecting branch inside xor would otherwise corrupt the match count into a false accept.
1417
+
// z.partialRecord and friends clear `_zod.values`, leaving no set to test membership against. Throw rather than emit INVALID so a union falls back whole instead of counting a false rejection.
1418
1418
if(!values){
1419
1419
thrownewZodCompileUnsupportedError("enum schema without enumerated values");
1420
1420
}
@@ -1486,7 +1486,7 @@ function generateDefaultCheck(doc: Doc, ctx: CompileContext, schema: SomeType, a
// The runtime inspects what the inner *produced*, not what it was given. Both directions matter: an inner catch or transform can turn a defined input into `undefined`, which has to be rejected, and an inner default turns an absent input into a value, which has to be accepted. Testing the input did neither.
1489
+
// The runtime inspects what the inner produced, not what it was given: a catch can turn a defined input into undefined, a default an absent one into a value.
@@ -1748,7 +1748,7 @@ function generateRecordCheck(doc: Doc, ctx: CompileContext, schema: SomeType, ac
1748
1748
1749
1749
doc.write(`const ${outputVar} = {};`);
1750
1750
1751
-
// Exhaustive records: keyType has a known value set (enum/literal/etc.). Runtime validates every known key, applies key transforms to choose the output key, and rejects unrecognized string keys. Generate the same shape. The runtime gates this on `values && !def.partial`: z.partialRecord keeps its value set but every key is optional, so required-key codegen would reject a record missing one. A loose record passes an unrecognized key through rather than rejecting it, which the scan below cannot express either.
1751
+
// Exhaustive record. The runtime gates this on `values && !def.partial`, since z.partialRecord keeps its value set but makes every key optional; a loose record passes unrecognized keys through, which the per-key scan cannot express.
// `mode: "loose"` only changes what happens to *unrecognized* keys β it still requires every enumerated key, so it belongs on this path rather than the per-present-key scan, which has no notion of a declared-but-absent key. Passing it through here matches the runtime, which copies the extra key across and skips `__proto__` so the assignment cannot reseat the output's prototype.
1777
+
// `mode: "loose"` changes only what happens to unrecognized keys, so it belongs here rather than the per-present-key scan. Passing them through matches the runtime, which skips `__proto__`.
// `.catch(value)` synthesises a tagged thunk for a constant, so anything untagged is a user callback. Every callback is refused, not just one that reads `ctx.error`: whether it does is undecidable here, and a callback that reads it needs issues finalized against the caller's per-parse error map, which generated code never sees. Producing them here gives a different message than `.parse(input, { error })` and, because catch *succeeds*, nothing downstream can notice. Refuse at codegen instead: returning INVALID would be a bail-out, and a union reads that as a rejected branch rather than a reason to hand the whole parse back.
2027
-
//
2028
-
// Not islandable either. A runtime island runs only this node through the runtime, and `runtimeRun` has no parse context to hand it, so an islanded catch finalizes against an empty context and *succeeds* with the wrong message β the same divergence, reintroduced by the container that was trying to tolerate it.
2026
+
// An untagged catchValue is a user callback, and one reading `ctx.error` needs the caller's per-parse error map. Catch *succeeds*, so a wrong message there is unobservable β refuse at codegen, and not islandable either, since `runtimeRun` has no context to hand it.
0 commit comments