zod-compiler 2.0.0 → 2.0.1

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.
@@ -1,11 +1,12 @@
1
1
  import { declareFastTemps, emitEffectCallable, emitEffectFn, emitPooledConstant, emitRuntimeHelper, emitTemp, escapeString, hasMutation, keyMembershipTest, literalToJs, needsProtoScrub, outputAlwaysDefined, rejectsUndefined, tupleRewritesShortInput } from "./context.js";
2
2
  import { ZC_HOP_DECL, ZC_PLAIN_DECL, ZC_PROTO_SCRUB_DECL } from "./issue-decls.js";
3
3
  import { defaultValueExpr, needsPostInnerDefault } from "./schemas/default.js";
4
+ import { detectUnionDiscriminator } from "./schemas/discriminated-union.js";
4
5
  import { estimateFastCost, predictedInlineSize } from "./fast-size.js";
5
6
  import { parsedProperties } from "./schemas/object.js";
6
7
  import { innerAppliesDefaultOnUndefined } from "./schemas/optional.js";
7
8
  import { fastStringCheck } from "./schemas/string.js";
8
- import { emitStringBoolMap, stringBoolUsesInline } from "./schemas/string-bool.js";
9
+ import { emitStringBoolMap, stringBoolInlineHit, stringBoolUsesInline } from "./schemas/string-bool.js";
9
10
  import { createFastGen, generateFast } from "./fast-path.js";
10
11
  //#region src/core/codegen/build-path.ts
11
12
  /**
@@ -331,11 +332,25 @@ function buildRecursiveCall(refId, input, g) {
331
332
  * would abandon the whole parse instead of moving on to the next option. Behind
332
333
  * a call, the same signal is just a value to test.
333
334
  *
334
- * PLAIN unions only. A discriminated union must not reach here: zod resolves it
335
- * by dispatch, not by probing, and the two disagree see
335
+ * A union of objects that all pin one shared key to disjoint required literals
336
+ * is dispatched instead of probed, exactly as the fast path does (see
337
+ * detectUnionDiscriminator). Disjointness is what makes that zod's answer and
338
+ * not merely a faster one: at most ONE option can accept a given input, so the
339
+ * first option to succeed is the option the discriminator selects, and an
340
+ * input whose discriminator matches no case is rejected by every option — the
341
+ * two outcomes a probe could have produced. Unlike the fast path there is no
342
+ * minimum option count: the options are hosted calls either way, and a switch
343
+ * only ever replaces a run of them with one. Measured on the eight-option
344
+ * tagged union in the benchmarks: 15.5 → 10 ns per parse, the same as the
345
+ * `z.discriminatedUnion` spelling of it.
346
+ *
347
+ * PLAIN unions only. A discriminated union must not reach the probe below: zod
348
+ * resolves it by dispatch, not by probing, and the two disagree — see
336
349
  * {@link buildDiscriminatedUnion}.
337
350
  */
338
351
  function buildUnion(ir, input, g) {
352
+ const discriminated = detectUnionDiscriminator(ir.options, 2);
353
+ if (discriminated !== null) return buildDispatch(discriminated.discriminator, discriminated.cases, ir.options, input, g);
339
354
  const hosted = [];
340
355
  for (const option of ir.options) {
341
356
  const fn = g.rebuilds.has(option) ? hostBuild(option, g) : hostPassthrough(option, g);
@@ -382,13 +397,23 @@ function buildUnion(ir, input, g) {
382
397
  * because the property read would throw on `null`/`undefined`.
383
398
  */
384
399
  function buildDiscriminatedUnion(ir, input, g) {
400
+ return buildDispatch(ir.discriminator, ir.cases, ir.options, input, g);
401
+ }
402
+ /**
403
+ * The switch behind {@link buildDiscriminatedUnion} and a dispatched
404
+ * {@link buildUnion}: prove object-ness, select the option the discriminator
405
+ * names, and build that option alone. Switches over the literal labels, as the
406
+ * fast path does — see `emitFastDiscriminatedSwitch` for the measurement that
407
+ * retired the ordinal-table form.
408
+ */
409
+ function buildDispatch(discriminator, cases, options, input, g) {
385
410
  const out = local(g, "bd");
386
411
  const hostedByOption = /* @__PURE__ */ new Map();
387
412
  let arms = "";
388
- for (const { value, option: index } of ir.cases) {
413
+ for (const { value, option: index } of cases) {
389
414
  let fn = hostedByOption.get(index);
390
415
  if (fn === void 0) {
391
- const option = ir.options[index];
416
+ const option = options[index];
392
417
  if (option === void 0) return null;
393
418
  const hosted = g.rebuilds.has(option) ? hostBuild(option, g) : hostPassthrough(option, g);
394
419
  if (hosted === null) return null;
@@ -399,7 +424,7 @@ function buildDiscriminatedUnion(ir, input, g) {
399
424
  }
400
425
  if (arms === "") return null;
401
426
  return {
402
- code: `if(typeof ${input}!=="object"||${input}===null||Array.isArray(${input}))return ${g.fail};switch(${input}[${escapeString(ir.discriminator)}]){${arms}default:return ${g.fail};}if(${out}===${g.fail})return ${g.fail};`,
427
+ code: `if(typeof ${input}!=="object"||${input}===null||Array.isArray(${input}))return ${g.fail};switch(${input}[${escapeString(discriminator)}]){${arms}default:return ${g.fail};}if(${out}===${g.fail})return ${g.fail};`,
403
428
  value: out
404
429
  };
405
430
  }
@@ -641,21 +666,39 @@ function buildString(ir, input, g) {
641
666
  * return the boolean directly. The ordinary Fast Path cannot host this codec
642
667
  * because its contract returns the original input by reference; the build path
643
668
  * is designed for exactly this kind of small output rewrite.
669
+ *
670
+ * Case-insensitive codecs look the input up VERBATIM before lowercasing it.
671
+ * The accepted spellings are all lowercase (see extractStringBool), so an
672
+ * exact hit is what `toLowerCase()` would have produced anyway, and the common
673
+ * config flag or query parameter is spelled that way already. For the hashed
674
+ * form that is one `Map.get` in place of `toLowerCase()` plus one. A miss
675
+ * lowercases and looks up again — unless lowercasing changed nothing, in which
676
+ * case the second lookup would only repeat the first, so a lowercase
677
+ * non-spelling is rejected for the price of the old path plus one string
678
+ * compare. Measured per value on V8: 10.8 → 7.5 ns over lowercase spellings,
679
+ * 13.5 → 10.7 ns over a mixed-case rotation. The inline form compares the raw
680
+ * string against its few spellings first — pointer compares on internalized
681
+ * strings — for the same trade.
644
682
  */
645
683
  function buildStringBool(ir, input, g) {
646
684
  let code = `if(typeof ${input}!=="string")return ${g.fail};`;
647
- let normalized = input;
648
- if (!ir.caseSensitive) {
649
- normalized = local(g, "bn");
650
- code += `${normalized}=${input}.toLowerCase();`;
651
- }
652
685
  const out = local(g, "bb");
653
686
  if (stringBoolUsesInline(ir)) {
687
+ let normalized = input;
688
+ if (!ir.caseSensitive) {
689
+ normalized = local(g, "bn");
690
+ code += `${normalized}=${stringBoolInlineHit(ir, input)}?${input}:${input}.toLowerCase();`;
691
+ }
654
692
  const membership = (values) => values.map((value) => `${normalized}===${escapeString(value)}`).join("||");
655
693
  code += `if(${membership(ir.truthy)}){${out}=true;}else if(${membership(ir.falsy)}){${out}=false;}else{return ${g.fail};}`;
656
694
  } else {
657
695
  const lookup = emitStringBoolMap(ir, g.ctx);
658
- code += `${out}=${lookup}.get(${normalized});if(${out}===undefined)return ${g.fail};`;
696
+ code += `${out}=${lookup}.get(${input});`;
697
+ if (!ir.caseSensitive) {
698
+ const lowered = local(g, "bn");
699
+ code += `if(${out}===undefined){${lowered}=${input}.toLowerCase();if(${lowered}!==${input}){${out}=${lookup}.get(${lowered});}}`;
700
+ }
701
+ code += `if(${out}===undefined)return ${g.fail};`;
659
702
  }
660
703
  return {
661
704
  code,
@@ -1 +1 @@
1
- {"version":3,"file":"build-path.js","names":[],"sources":["../../../src/core/codegen/build-path.ts"],"sourcesContent":["/**\n * Build Path: one uninstrumented pass that VALIDATES and BUILDS rewritten\n * output together, abandoning the whole parse at the first failing check.\n *\n * `z.object()` strips unknown keys, so a successful parse cannot return the\n * input by reference — it must produce a fresh object. That rules out the Fast\n * Path (whose contract is `data === input`), and before this the only remaining\n * option was the eager slow walk: a fully instrumented traversal that collects\n * issues on every parse, valid or not.\n *\n * Two passes are wasteful in either direction. Validating first and building\n * afterwards reads every property twice (measured 29.7 ns vs 21.6 for the slow\n * walk on a 6-field object). Building with issue collection pays the\n * instrumentation even when nothing fails. Doing both in ONE pass, with a\n * sentinel instead of an issues array, beats both — and a failure costs only\n * the checks up to the first bad one, because the issue-producing walk is\n * deferred into `.error` exactly as `__zcFinD` does for mutation-free schemas:\n *\n * object clean object invalid array(8) invalid\n * slow walk 21.6 ns 30.4 ns 197.5 ns\n * build path 18.1 ns 7.7 ns 9.8 ns\n *\n * A subtree that rebuilds nothing is validated with its existing Fast Path\n * expression and passed through by reference, so only nodes that genuinely\n * produce a new value need code here; anything else returns null and keeps the\n * eager walk.\n *\n * Coverage is what decides whether this pass is reached at all, because it is\n * all-or-nothing per schema: ONE unmodelled node anywhere in the tree costs the\n * whole schema its single-pass parse. Modelled, beyond the stripping containers\n * this started with: array size checks and `.refine()`, object-level `.refine()`,\n * `.default()` substitution, ordered string rewrites (`.trim()`,\n * `.toLowerCase()`), sync `.transform()`, `z.stringbool()`, and the five native\n * coercions (`string`, `number`, `boolean`, `bigint`, `date`). Still declined, via\n * {@link mutatesBeyondStrip} — `.catch()` (its callback wants the inner schema's\n * issue list, which this pass never builds), `z.url()`, and `superRefine`.\n */\n\nimport type { ObjectIR, RefineEffectCheckIR, SchemaIR, StringBoolIR } from \"../types.js\";\nimport type { CodeGenContext, FastScope } from \"./context.js\";\nimport {\n declareFastTemps,\n emitEffectCallable,\n emitEffectFn,\n emitPooledConstant,\n emitRuntimeHelper,\n emitTemp,\n escapeString,\n hasMutation,\n keyMembershipTest,\n literalToJs,\n needsProtoScrub,\n outputAlwaysDefined,\n rejectsUndefined,\n tupleRewritesShortInput,\n} from \"./context.js\";\nimport { createFastGen, generateFast } from \"./fast-path.js\";\nimport { EXTRACT_CAP, estimateFastCost, MIN_EXTRACT, predictedInlineSize } from \"./fast-size.js\";\nimport { ZC_HOP_DECL, ZC_PLAIN_DECL, ZC_PROTO_SCRUB_DECL } from \"./issue-decls.js\";\nimport { defaultValueExpr, needsPostInnerDefault } from \"./schemas/default.js\";\nimport { parsedProperties } from \"./schemas/object.js\";\nimport { innerAppliesDefaultOnUndefined } from \"./schemas/optional.js\";\nimport { fastStringCheck } from \"./schemas/string.js\";\nimport { emitStringBoolMap, stringBoolUsesInline } from \"./schemas/string-bool.js\";\n\n/** Statements that leave the built value in `value`, or `return <FAIL>` on failure. */\ninterface Built {\n code: string;\n value: string;\n}\n\ninterface BuildGen {\n ctx: CodeGenContext;\n /** Identifier of the per-validator FAIL sentinel. */\n fail: string;\n /** `var` temps and running emitted size of the function being assembled. */\n scope: FastScope;\n /**\n * May THIS node be hosted in its own function? False for the node a hosted\n * build was created for — it already IS that function, so re-hosting it would\n * recurse forever. Children are always extractable, letting an oversized\n * helper split further.\n */\n extractable: boolean;\n /** Nodes of the root schema that rebuild (see rebuildSet). */\n rebuilds: ReadonlySet<SchemaIR>;\n}\n\n/**\n * Which nodes of `root` produce a value that is not their input — a stripping\n * object, coercion, codec, default, overwrite or transform, including\n * containers that contain one. Everything else can be validated in place and\n * passed through, which is what keeps this generator small.\n *\n * Computed as a fixpoint rather than a plain walk because of recursion: a\n * `recursiveRef` is a back-edge with no children, so a local walk reads false\n * for it and would pass the whole recursive subtree through by reference —\n * leaving every nested value unstripped while the outermost one was rebuilt.\n * Resolving the ref against its target closes the cycle, and iterating to a\n * fixpoint settles the mutual dependency between the two.\n */\nfunction rebuildSet(root: SchemaIR, includeProtoScrub = true): ReadonlySet<SchemaIR> {\n const targets = new Map<number, SchemaIR>([[0, root]]);\n const nodes: SchemaIR[] = [];\n const seen = new Set<SchemaIR>();\n const collect = (node: SchemaIR): void => {\n if (seen.has(node)) return;\n seen.add(node);\n nodes.push(node);\n if (node.type === \"recursionTarget\") targets.set(node.refId, node.inner);\n for (const child of children(node)) collect(child);\n };\n collect(root);\n\n const rebuilds = new Set<SchemaIR>();\n for (let changed = true; changed;) {\n changed = false;\n for (const node of nodes) {\n if (rebuilds.has(node)) continue;\n const target = node.type === \"recursiveRef\" ? targets.get(node.refId ?? 0) : undefined;\n const rebuild =\n (node.type === \"object\" && node.stripUnknownKeys === true) ||\n // A freezing readonly's output is `Object.freeze(inner)` — a value the\n // caller never handed us, so it must be BUILT rather than passed\n // through. Marking it here is also what makes `rebuildsOutput` true and\n // so withholds every by-reference shortcut above it.\n (node.type === \"readonly\" && node.freeze === true) ||\n // `.default()` substitutes its own value for `undefined`, so its output\n // is not its input even when the inner schema passes through — it must\n // never be handed to `passthrough`, whose fast check would reject the\n // absent value outright.\n node.type === \"default\" ||\n // A tuple whose output can differ from a SHORT input it accepts —\n // `z.tuple([z.any()]).rest(z.number())` answers `[]` with `[undefined]`\n // — is not its own input either. `fastTuple` narrows exactly those\n // slots to \"present\" (sound for the root shortcut, which only reads a\n // TRUE result), so handing it to `passthrough`, which reads a FALSE one\n // as rejection, turned a valid short input into a failure with an empty\n // issue array. Marking it here makes `buildTuple`'s own bail propagate\n // instead.\n (node.type === \"tuple\" && tupleRewritesShortInput(node)) ||\n // A loose/catchall object or a record hands its input back, and zod's\n // output never carries an own `__proto__` — so its output is not its\n // input whenever the key is there. Marking it here is what stops\n // `passthrough` handing the raw container up through a PARENT that\n // never looks inside it (`z.array(z.looseObject(...))`); the parent\n // rebuilds instead, and each child is scrubbed as it is built.\n (includeProtoScrub && needsProtoScrub(node)) ||\n // `z.stringbool()` replaces its accepted string with a boolean.\n node.type === \"stringBool\" ||\n // An overwrite effect (`.trim()`, `.toLowerCase()`) rewrites the string,\n // so the node's output is a new value: it has to be BUILT rather than\n // validated in place (see buildString).\n (node.type === \"string\" &&\n (node.coerce === true || node.checks.some((c) => c.kind === \"overwrite_effect\"))) ||\n ((node.type === \"number\" ||\n node.type === \"boolean\" ||\n node.type === \"bigint\" ||\n node.type === \"date\") &&\n node.coerce === true) ||\n // `.transform(fn)` replaces the value with the callback's result.\n node.type === \"effect\" ||\n (target !== undefined && rebuilds.has(target)) ||\n children(node).some((child) => rebuilds.has(child));\n if (rebuild) {\n rebuilds.add(node);\n changed = true;\n }\n }\n }\n return rebuilds;\n}\n\n/** Does `ir`, taken as a whole schema, produce a value that is not its input? */\nexport function rebuildsOutput(ir: SchemaIR): boolean {\n return rebuildSet(ir).has(ir);\n}\n\n/**\n * Does a PASSING fast check prove that the parse returns its own input?\n *\n * This is the contract behind every by-reference shortcut: `safeParse`'s\n * `if(fc(input)) return {success:true,data:input}` and, through `fc` in\n * `__zcMkv`, `parse()` / `parseAsync()` / `~standard.validate()`. It is strictly\n * stronger than \"the fast check is sound\", and two things break it:\n *\n * 1. The schema REBUILDS its output. A stripping object is the common case, and\n * it is why `z.object({ a: z.number().catch(0) })` — a strip object the\n * build pass declines because of the `.catch()` — used to answer\n * `parse({a: 1, b: 2})` with the UNSTRIPPED input while its own `safeParse`\n * correctly returned `{a: 1}`.\n *\n * 2. A plain `z.union()` with a MUTATING option. The fast form is an `||` chain,\n * which reports that SOME option accepts the input; zod returns the value\n * produced by the FIRST option that succeeds. Those differ as soon as an\n * earlier option would have claimed the input and rewritten it —\n * `z.union([z.string().catch(\"c\"), z.number()])` answers `\"c\"` for every\n * input, catch being infallible, while the chain matches `1` against the\n * number arm and hands back `1`. A DISCRIMINATED union is exempt: its\n * dispatch selects exactly one option, so which arm zod runs is never in\n * doubt (and a rewriting object option is caught by (1) anyway).\n *\n * Withheld here rather than in `fastUnion` on purpose: the `||` chain is still a\n * correct VERDICT, which is all a nested conjunct or a `.is()` guard needs, so\n * declining to emit it would cost every union-of-objects its fast path (and the\n * size-gated `__fo_` split) to fix a shortcut that only the root takes.\n */\nexport function fastResultIsInput(ir: SchemaIR): boolean {\n if (rebuildsOutput(ir)) return false;\n // 3. The output needs an own `__proto__` removed. A loose/catchall object or\n // a record hands its input back, and zod's output never carries the key,\n // so `safeParse` filters the value through `__zcPs` — which makes `data`\n // a copy exactly when the key is present. `fc` may not promise identity\n // on top of that, so `.is()` and `parse()` derive from safeParse for\n // these shapes (see ZC_PROTO_SCRUB_DECL).\n if (needsProtoScrub(ir)) return false;\n const seen = new Set<SchemaIR>();\n const ordered = (node: SchemaIR): boolean => {\n if (seen.has(node)) return false;\n seen.add(node);\n if (node.type === \"union\" && node.options.some(hasMutation)) return true;\n return children(node).some(ordered);\n };\n return !ordered(ir);\n}\n\n/**\n * True when the subtree mutates for any reason the build pass cannot reproduce —\n * `.catch()`, `z.url()`, `superRefine`. Those rewrite values in ways this pass\n * (which validates, coerces, decodes string booleans, substitutes declared\n * defaults, applies ordered string rewrites and copies) does not model, so the\n * schema keeps the eager walk.\n */\nfunction mutatesBeyondStrip(ir: SchemaIR): boolean {\n return mutatesHere(ir) || children(ir).some(mutatesBeyondStrip);\n}\n\n/**\n * Does this node rewrite values on its own account (ignoring its children, and\n * ignoring the reshaping a strip object does)? Mirrors the node-local half of\n * `hasMutation`; the recursion above supplies the other half.\n */\nfunction mutatesHere(ir: SchemaIR): boolean {\n switch (ir.type) {\n case \"string\":\n // Coercion and overwrite effects are absent: `buildString` applies them\n // in order. A `z.url()` check still is not — it trims, normalizes and\n // needs its own normalization/error semantics.\n return (\n superRefines(ir.checks) ||\n ir.checks.some((c) => c.kind === \"string_format\" && c.format === \"url\")\n );\n case \"number\":\n return superRefines(ir.checks);\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return false;\n // `default` and `effect` are absent: substituting a constant for `undefined`\n // and applying a sync transform are both modelled (see buildDefault /\n // buildEffect), and their inners are reached through `children`.\n //\n // `catch` is NOT: its catchValue callback receives a ctx carrying the inner\n // schema's collected issues, and this pass produces a sentinel instead of an\n // issue list — there is nothing to hand it.\n case \"catch\":\n case \"fallback\":\n return true;\n case \"object\":\n case \"array\":\n return superRefines(ir.checks);\n default:\n return false;\n }\n}\n\nfunction superRefines(checks: readonly { kind: string }[] | undefined): boolean {\n return checks !== undefined && checks.some((c) => c.kind === \"super_refine_effect\");\n}\n\n/**\n * Does anything STRICTLY BELOW `ir` hand back a container needing a `__proto__`\n * scrub?\n *\n * The root's by-reference shortcut can filter the value it returns\n * (`data: __zcPs(input)`), but that only reaches the OUTER container — a nested\n * one is never touched, because the shortcut does not walk. So a schema with a\n * scrub-needing descendant keeps the eager slow walk, which scrubs at every\n * level. Only the root's own scrub is shortcut-compatible.\n */\nexport function nestedNeedsProtoScrub(ir: SchemaIR): boolean {\n const seen = new Set<SchemaIR>();\n const walk = (node: SchemaIR): boolean => {\n if (seen.has(node)) return false;\n seen.add(node);\n return children(node).some((child) => needsProtoScrub(child) || walk(child));\n };\n return walk(ir);\n}\n\nfunction children(ir: SchemaIR): readonly SchemaIR[] {\n switch (ir.type) {\n case \"object\":\n return ir.catchall\n ? [...Object.values(ir.properties), ir.catchall]\n : Object.values(ir.properties);\n case \"array\":\n return [ir.element];\n case \"tuple\":\n return ir.rest === null ? ir.items : [...ir.items, ir.rest];\n case \"record\":\n case \"map\":\n return [ir.keyType, ir.valueType];\n case \"set\":\n return [ir.valueType];\n case \"union\":\n case \"discriminatedUnion\":\n return ir.options;\n case \"intersection\":\n return [ir.left, ir.right];\n case \"optional\":\n case \"nullable\":\n case \"readonly\":\n case \"default\":\n case \"catch\":\n case \"effect\":\n case \"recursionTarget\":\n case \"zodDelegate\":\n return [ir.inner];\n case \"pipe\":\n return [ir.in, ir.out];\n default:\n return [];\n }\n}\n\n/**\n * Host the whole schema as `function NAME(input){…}` returning the built value\n * or the FAIL sentinel. Returns the function name, or null when the schema is\n * not expressible as a single build pass.\n */\nexport function generateBuild(ir: SchemaIR, ctx: CodeGenContext): string | null {\n const rebuilds = rebuildSet(ir);\n if (!rebuilds.has(ir) || mutatesBeyondStrip(ir)) return null;\n // When the ONLY reason the root rebuilds is its own `__proto__` scrub, decline\n // and let the mutation-free shortcut below take it: that one keeps the fast\n // check and filters the returned value through `__zcPs`, where building would\n // pay a full single-pass walk to achieve the same thing. Measured at ~2x on a\n // 5-key `z.looseObject`, which is precisely the shape that lost the shortcut.\n // Only the root is exempt; a nested scrub still forces its parent to rebuild,\n // which is what the clause in `rebuildSet` is for.\n if (needsProtoScrub(ir) && !rebuildSet(ir, false).has(ir)) return null;\n const fail = emitFailSentinel(ctx);\n const scope: FastScope = { temps: [], used: 0 };\n const built = build(ir, \"input\", { ctx, extractable: false, fail, rebuilds, scope });\n if (built === null) return null;\n const name = emitTemp(ctx, \"vb\");\n ctx.preamble.push(\n `function ${name}(input){${declareFastTemps(scope)}${built.code}return ${built.value};}`,\n );\n return name;\n}\n\n/**\n * The build path's FAIL marker: an object compared by identity, which the build\n * function returns in place of a value and `safeParse` tests for.\n *\n * Pooled at file level rather than declared per validator. Its whole contract is\n * \"nothing a parse can produce equals this\", and that is a property of the\n * object's freshness, not of how many there are — so one `{}` serves every\n * rebuilding validator in the file, where before each allocated its own at\n * module init. Pooling by initializer text is safe for the same reason: the only\n * way a merge could hurt is if some other `{}` constant were ever RETURNED by a\n * build function, and the pool's other members are lookup tables and value\n * lists, which are only ever read from.\n */\nfunction emitFailSentinel(ctx: CodeGenContext): string {\n ctx.buildFailName ??= emitPooledConstant(ctx, \"Bf\", \"bf\", \"{}\");\n return ctx.buildFailName;\n}\n\n/**\n * Statements producing the built value of `ir` read from `input`, or null.\n *\n * Size-gated exactly like the fast path: once inlining `ir` would push the\n * function being assembled past EXTRACT_CAP, the sub-build is hosted as its own\n * `__vb_N(p)` returning value-or-FAIL and replaced by a call. Without this a\n * deeply nested schema emits one enormous build function — measured at 113 KB\n * and 354 KB on the deep fixtures — far past the bytecode size where V8 stops\n * running TurboFan on it, which would forfeit the speed this path exists for.\n */\nfunction build(ir: SchemaIR, input: string, g: BuildGen): Built | null {\n // Resolved before the passthrough shortcut below. A back-edge carries no\n // children, so `rebuildsOutput` reads false for it — and passing it through by\n // reference would leave every nested recursive value unstripped while the\n // outermost one was rebuilt.\n if (ir.type === \"recursiveRef\") return buildRecursiveCall(ir.refId ?? 0, input, g);\n if (ir.type === \"recursionTarget\") return buildRecursionTarget(ir, input, g);\n if (!g.rebuilds.has(ir)) return passthrough(ir, input, g);\n\n const cache = (g.ctx.fastSizeCache ??= new WeakMap<SchemaIR, number>());\n if (\n g.extractable &&\n g.scope.used + predictedInlineSize(ir, input.length, cache) > EXTRACT_CAP &&\n (g.scope.used > EXTRACT_CAP || estimateFastCost(ir, cache) >= MIN_EXTRACT)\n ) {\n const hosted = hostBuild(ir, g);\n if (hosted !== null) {\n const slot = local(g, \"bh\");\n const code = `${slot}=${hosted}(${input});if(${slot}===${g.fail})return ${g.fail};`;\n g.scope.used += code.length;\n return { code, value: slot };\n }\n }\n\n // This node's extraction decision is made; its descendants get to make their\n // own, so an oversized hosted helper keeps splitting.\n // When the ONLY reason this node rebuilds is its own `__proto__` scrub —\n // nothing under it rebuilds — a validated passthrough plus that scrub IS the\n // rebuild. Taken BEFORE the builders so a plain record keeps handing its\n // input back by reference (buildRecord would copy into a fresh `{}`, which is\n // a different documented behaviour: see the output-identity divergence).\n if (needsProtoScrub(ir) && !children(ir).some((child) => g.rebuilds.has(child))) {\n return passthrough(ir, input, g);\n }\n\n const before = g.scope.used;\n const out = buildInline(ir, input, { ...g, extractable: true });\n if (out !== null) g.scope.used = before + out.code.length;\n return out;\n}\n\n/** Host `ir`'s build in its own function over a fresh parameter; returns its name. */\nfunction hostBuild(ir: SchemaIR, g: BuildGen): string | null {\n const param = emitTemp(g.ctx, \"bp\");\n const scope: FastScope = { temps: [], used: 0 };\n const inner = build(ir, param, { ...g, extractable: false, scope });\n if (inner === null) return null;\n const name = emitTemp(g.ctx, \"vb\");\n g.ctx.preamble.push(\n `function ${name}(${param}){${declareFastTemps(scope)}${inner.code}return ${inner.value};}`,\n );\n return name;\n}\n\nfunction buildInline(ir: SchemaIR, input: string, g: BuildGen): Built | null {\n switch (ir.type) {\n case \"object\":\n return buildObject(ir, input, g);\n case \"array\":\n return buildArray(ir, input, g);\n case \"tuple\":\n return buildTuple(ir, input, g);\n case \"record\":\n return buildRecord(ir, input, g);\n case \"optional\":\n // A default further down the chain consumes undefined into a value, so\n // the `undefined → undefined` shortcut must not fire — same rule (and\n // same helper) the slow and fast paths already apply.\n return innerAppliesDefaultOnUndefined(ir.inner)\n ? build(ir.inner, input, g)\n : buildSentinel(ir.inner, input, g, \"===undefined\", \"undefined\");\n case \"nullable\":\n // `null` short-circuits unconditionally in zod, whatever the inner is;\n // undefined flows through, so an inner default still fires.\n return buildSentinel(ir.inner, input, g, \"===null\", \"null\");\n case \"default\":\n return buildDefault(ir, input, g);\n case \"string\":\n return buildString(ir, input, g);\n case \"stringBool\":\n return buildStringBool(ir, input, g);\n case \"number\":\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return buildCoercedPrimitive(ir, input, g);\n case \"effect\":\n return buildEffect(ir, input, g);\n case \"readonly\":\n return buildReadonly(ir, input, g);\n case \"zodDelegate\":\n return build(ir.inner, input, g);\n case \"union\":\n return buildUnion(ir, input, g);\n case \"discriminatedUnion\":\n return buildDiscriminatedUnion(ir, input, g);\n default:\n // A rebuilding intersection, map or set: expressible in principle, but\n // each needs its own output-shaping rules, so they keep the eager walk\n // until there is a measured reason to add them.\n return null;\n }\n}\n\n/**\n * Host the target's build once under a name registered BEFORE its body is\n * generated, so the back-edges inside that body resolve to it.\n */\nfunction buildRecursionTarget(\n ir: SchemaIR & { type: \"recursionTarget\" },\n input: string,\n g: BuildGen,\n): Built | null {\n const table = (g.ctx.buildRecNames ??= new Map<number, string>());\n if (!table.has(ir.refId)) {\n const name = emitTemp(g.ctx, \"vbr\");\n table.set(ir.refId, name);\n const param = emitTemp(g.ctx, \"bp\");\n const scope: FastScope = { temps: [], used: 0 };\n const inner = build(ir.inner, param, { ...g, extractable: false, scope });\n if (inner === null) {\n table.delete(ir.refId);\n return null;\n }\n g.ctx.preamble.push(\n `function ${name}(${param}){${declareFastTemps(scope)}${inner.code}return ${inner.value};}`,\n );\n }\n return buildRecursiveCall(ir.refId, input, g);\n}\n\n/** Call the hosted build for a recursion target, propagating its FAIL. */\nfunction buildRecursiveCall(refId: number, input: string, g: BuildGen): Built | null {\n const name = g.ctx.buildRecNames?.get(refId);\n if (name === undefined) return null;\n const slot = local(g, \"bh\");\n return {\n code: `${slot}=${name}(${input});if(${slot}===${g.fail})return ${g.fail};`,\n value: slot,\n };\n}\n\n/**\n * Try each option in declaration order and take the first that builds — which\n * is what zod's union does with the first option that parses.\n *\n * Every option is HOSTED rather than inlined, and that is load-bearing: a\n * failing build signals with `return FAIL`, which inside the enclosing function\n * would abandon the whole parse instead of moving on to the next option. Behind\n * a call, the same signal is just a value to test.\n *\n * PLAIN unions only. A discriminated union must not reach here: zod resolves it\n * by dispatch, not by probing, and the two disagree — see\n * {@link buildDiscriminatedUnion}.\n */\nfunction buildUnion(ir: SchemaIR & { type: \"union\" }, input: string, g: BuildGen): Built | null {\n const hosted: string[] = [];\n for (const option of ir.options) {\n const fn = g.rebuilds.has(option) ? hostBuild(option, g) : hostPassthrough(option, g);\n if (fn === null) return null;\n hosted.push(fn);\n }\n if (hosted.length === 0) return null;\n\n const out = local(g, \"bu\");\n let code = `${out}=${hosted[0] as string}(${input});`;\n for (const fn of hosted.slice(1)) {\n code += `if(${out}===${g.fail}){${out}=${fn}(${input});}`;\n }\n code += `if(${out}===${g.fail})return ${g.fail};`;\n return { code, value: out };\n}\n\n/**\n * Dispatch on the discriminator and build ONLY the option that value selects,\n * failing outright when it selects none — mirroring zod, which resolves the\n * option through a `discriminator value → option` map built from each option's\n * `propValues` and pushes `invalid_union` (\"No matching discriminator\") without\n * ever running an option's parse when the lookup misses.\n *\n * Probing the options in order like {@link buildUnion} does is NOT equivalent,\n * because an option can accept more than its own dispatch values. A wrapper that\n * substitutes a value contributes only the value it wraps to `propValues` while\n * its parse also accepts the input it substitutes FOR:\n * `z.literal(\"a\").default(\"a\")` dispatches on `\"a\"` alone yet parses a MISSING\n * discriminator, so sequential probing accepted `{v:\"x\"}` — output `{t:\"a\",v:\"x\"}`\n * — where zod rejects it. `.prefault()` and `.catch()` have the same shape, and\n * only escape it because neither reaches this pass today (a prefaulted schema\n * delegates to zod wholesale, and `.catch()` is refused by\n * {@link mutatesBeyondStrip}); a `.default()` is exactly what pulls the build\n * path in. The switch cannot drift that way: the dispatch table IS zod's, so an\n * unlisted discriminator reaches `default:` and fails, whatever the options\n * would have accepted on their own.\n *\n * The reverse — rejecting what zod accepts — is why `.optional()`/`.nullable()`\n * discriminators stay compiled rather than being refused here: their\n * `undefined`/`null` are in `propValues`, so they arrive as ordinary cases.\n *\n * Object-ness is proved BEFORE the discriminator is read, both because zod\n * rejects a non-object with its own `invalid_type` ahead of the lookup and\n * because the property read would throw on `null`/`undefined`.\n */\nfunction buildDiscriminatedUnion(\n ir: SchemaIR & { type: \"discriminatedUnion\" },\n input: string,\n g: BuildGen,\n): Built | null {\n const out = local(g, \"bd\");\n // One hosted build per REACHABLE option, keyed by option index: a multi-value\n // literal (`z.literal([\"a\",\"c\"])`) contributes several cases selecting the\n // same option, and they share the one function rather than emitting it twice.\n const hostedByOption = new Map<number, string>();\n let arms = \"\";\n for (const { value, option: index } of ir.cases) {\n let fn = hostedByOption.get(index);\n if (fn === undefined) {\n const option = ir.options[index];\n if (option === undefined) return null;\n const hosted = g.rebuilds.has(option) ? hostBuild(option, g) : hostPassthrough(option, g);\n if (hosted === null) return null;\n fn = hosted;\n hostedByOption.set(index, fn);\n }\n arms += `case ${literalToJs(value)}:${out}=${fn}(${input});break;`;\n }\n if (arms === \"\") return null;\n\n return {\n code:\n `if(typeof ${input}!==\"object\"||${input}===null||Array.isArray(${input}))return ${g.fail};` +\n `switch(${input}[${escapeString(ir.discriminator)}]){${arms}default:return ${g.fail};}` +\n `if(${out}===${g.fail})return ${g.fail};`,\n value: out,\n };\n}\n\n/**\n * Host a non-rebuilding option as `value-or-FAIL`, so a union can probe it with\n * the same protocol as a rebuilding one.\n */\nfunction hostPassthrough(ir: SchemaIR, g: BuildGen): string | null {\n const param = emitTemp(g.ctx, \"bp\");\n const scope: FastScope = { temps: [], used: 0 };\n const expr = generateFast(ir, createFastGen(param, g.ctx, true, scope));\n if (expr === null) return null;\n const name = emitTemp(g.ctx, \"vp\");\n g.ctx.preamble.push(\n `function ${name}(${param}){${declareFastTemps(scope)}return ${expr === \"true\" ? param : `(${expr})?${param}:${g.fail}`};}`,\n );\n return name;\n}\n\n/**\n * Validate in place with the Fast Path and hand the input straight back —\n * filtered through `__zcPs` for a container zod would have stripped an own\n * `__proto__` from (see ZC_PROTO_SCRUB_DECL). The filter copies only when the\n * key is present, so the ordinary value is still returned by reference.\n */\nfunction passthrough(ir: SchemaIR, input: string, g: BuildGen): Built | null {\n const scoped = createFastGen(input, g.ctx, true, g.scope);\n const expr = generateFast(ir, scoped);\n if (expr === null) return null;\n const guard = expr === \"true\" ? \"\" : `if(!(${expr}))return ${g.fail};`;\n if (!needsProtoScrub(ir)) return { code: guard, value: input };\n const slot = local(g, \"bs\");\n const scrub = emitRuntimeHelper(g.ctx, \"__zcPs\", ZC_PROTO_SCRUB_DECL);\n return { code: `${guard}${slot}=${scrub}(${input});`, value: slot };\n}\n\n/**\n * Rebuild from the declared keys. Sound for a stripping object (that IS the\n * output) and for a strict one (unknown keys are rejected, so the declared keys\n * are the whole key set). A loose object or one with a `.catchall()` keeps keys\n * this pass does not enumerate, so those bail.\n */\n/**\n * Freeze the inner's built value, matching zod's `Object.freeze(payload.value)`.\n *\n * Sound only because `freeze` is set exclusively over a stripping object, whose\n * build ALWAYS allocates (`buildObject` assembles a fresh `__bo_N`) — so the\n * frozen value is never the caller's input. A pass-through inner would return\n * `input` here and freezing it would mutate data the caller still owns, which\n * is why the extractor withholds the flag for every other container.\n */\nfunction buildReadonly(\n ir: SchemaIR & { type: \"readonly\" },\n input: string,\n g: BuildGen,\n): Built | null {\n const built = build(ir.inner, input, g);\n if (built === null || ir.freeze !== true) return built;\n const slot = local(g, \"bz\");\n return { code: `${built.code}${slot}=Object.freeze(${built.value});`, value: slot };\n}\n\nfunction buildObject(ir: ObjectIR, input: string, g: BuildGen): Built | null {\n if (ir.catchall !== undefined) return null;\n if (ir.stripUnknownKeys !== true && ir.strict !== true) return null;\n // Both swallow an absent key's failure, which a single-pass build that fails\n // at the first bad check cannot model.\n if (ir.skipAbsentKeys !== undefined && ir.skipAbsentKeys.length > 0) return null;\n if (ir.suppressAbsentKeys !== undefined && ir.suppressAbsentKeys.length > 0) return null;\n const nonoptional = new Set(ir.nonoptionalKeys ?? []);\n // Object-level `.refine()` runs on the assembled output (below). superRefine\n // rewrites the payload, which this pass does not model — mutatesBeyondStrip\n // already rejects it, so this is a belt-and-braces narrowing of the type.\n const refines = ir.checks ?? [];\n if (refines.some((check) => check.kind !== \"refine_effect\")) return null;\n\n let code = `if(typeof ${input}!==\"object\"||${input}===null||Array.isArray(${input}))return ${g.fail};`;\n\n if (ir.strict === true) {\n const keyVar = local(g, \"bk\");\n code += `for(${keyVar} in ${input}){if(!(${keyMembershipTest(g.ctx, Object.keys(ir.properties), keyVar)}))return ${g.fail};}`;\n }\n\n const slots: { always: boolean; keyStr: string; value: string }[] = [];\n for (const [key, propIR] of parsedProperties(ir)) {\n const keyStr = escapeString(key);\n const slot = local(g, \"bv\");\n // A required key has to be present whatever its schema makes of `undefined`.\n if (nonoptional.has(key)) code += `if(!(${keyStr} in ${input}))return ${g.fail};`;\n code += `${slot}=${input}[${keyStr}];`;\n const propBuilt = build(propIR, slot, g);\n if (propBuilt === null) return null;\n code += propBuilt.code;\n slots.push({ always: outputAlwaysDefined(propIR), keyStr, value: propBuilt.value });\n }\n\n // Same assembly the eager strip walk uses: the longest LEADING run of\n // always-present keys goes into one object literal (V8 stamps it from a\n // cached boilerplate map in a single allocation), and everything after the\n // first conditional key is appended so insertion order still matches zod.\n // The per-key test is zod's own — keep the key when the parsed value is\n // defined, or when it was present on the input at all.\n const out = local(g, \"bo\");\n const literal: string[] = [];\n let appends = \"\";\n let leading = true;\n for (const slot of slots) {\n if (leading && slot.always) {\n literal.push(`${slot.keyStr}:${slot.value}`);\n continue;\n }\n leading = false;\n appends += slot.always\n ? `${out}[${slot.keyStr}]=${slot.value};`\n : `if(${slot.value}!==undefined||(${slot.keyStr} in ${input})){${out}[${slot.keyStr}]=${slot.value};}`;\n }\n code += `${out}={${literal.join(\",\")}};${appends}`;\n // Zod parses the properties into the payload first and skips the check chain\n // when that produced issues, so a bad property suppresses the refine — which\n // this pass gets for free, having already returned FAIL at that property.\n for (const check of refines) {\n code += `if(!${emitEffectCallable(g.ctx, check as RefineEffectCheckIR)}(${out}))return ${g.fail};`;\n }\n return { code, value: out };\n}\n\nfunction buildArray(ir: SchemaIR & { type: \"array\" }, input: string, g: BuildGen): Built | null {\n // Length checks are pure predicates over `input.length`, so they hoist ahead\n // of the element loop: a size mismatch bails before a single element is\n // validated. Zod reports the per-element issue first when both fail, but the\n // build pass produces no issues — only the sentinel — and the deferred walk\n // that does produce them keeps zod's order.\n let sizes = \"\";\n const refines: RefineEffectCheckIR[] = [];\n for (const check of ir.checks) {\n switch (check.kind) {\n case \"min_length\":\n sizes += `if(${input}.length<${check.minimum})return ${g.fail};`;\n break;\n case \"max_length\":\n sizes += `if(${input}.length>${check.maximum})return ${g.fail};`;\n break;\n case \"length_equals\":\n sizes += `if(${input}.length!==${check.length})return ${g.fail};`;\n break;\n case \"refine_effect\":\n refines.push(check);\n break;\n default:\n // super_refine (rewrites the value) or a check kind not modelled here.\n return null;\n }\n }\n\n const out = local(g, \"ba\");\n const index = local(g, \"bi\");\n const elem = local(g, \"be\");\n const inner = build(ir.element, elem, g);\n if (inner === null) return null;\n let code =\n `if(!Array.isArray(${input}))return ${g.fail};` +\n sizes +\n `${out}=new Array(${input}.length);` +\n `for(${index}=0;${index}<${input}.length;${index}++){` +\n `${elem}=${input}[${index}];${inner.code}${out}[${index}]=${inner.value};}`;\n // `.refine()` sees the parsed payload, which for a rebuilding element is the\n // freshly assembled array — the same value zod hands its checks.\n for (const check of refines) {\n code += `if(!${emitEffectCallable(g.ctx, check)}(${out}))return ${g.fail};`;\n }\n return { code, value: out };\n}\n\nfunction buildTuple(ir: SchemaIR & { type: \"tuple\" }, input: string, g: BuildGen): Built | null {\n // Trailing-optional and rest handling shape the output length; keep those on\n // the eager walk rather than restating the rules here.\n if (ir.rest !== null) return null;\n if (ir.optStart !== ir.items.length) return null;\n if (ir.items.some((item) => !rejectsUndefined(item))) return null;\n\n let code = `if(!Array.isArray(${input})||${input}.length!==${ir.items.length})return ${g.fail};`;\n const values: string[] = [];\n for (const [index, itemIR] of ir.items.entries()) {\n const slot = local(g, \"bt\");\n code += `${slot}=${input}[${index}];`;\n const inner = build(itemIR as SchemaIR, slot, g);\n if (inner === null) return null;\n code += inner.code;\n values.push(inner.value);\n }\n const out = local(g, \"bl\");\n code += `${out}=[${values.join(\",\")}];`;\n return { code, value: out };\n}\n\nfunction buildRecord(ir: SchemaIR & { type: \"record\" }, input: string, g: BuildGen): Built | null {\n const plainStringKey =\n ir.keyType.type === \"string\" && ir.keyType.checks.length === 0 && ir.keyType.coerce !== true;\n if (!plainStringKey) return null;\n\n const out = local(g, \"br\");\n const keyVar = local(g, \"brk\");\n const valVar = local(g, \"brv\");\n const inner = build(ir.valueType, valVar, g);\n if (inner === null) return null;\n const hop = emitRuntimeHelper(g.ctx, \"__zcHop\", ZC_HOP_DECL);\n // `$ZodRecord` gates on `util.isPlainObject`, not the `util.isObject` the\n // object/discriminated-union builds above use — see ZC_PLAIN_DECL. And it\n // skips `__proto__` outright: here that guard is load-bearing twice over,\n // since `out[key]=value` for that key would not add a property at all but\n // REDEFINE the built object's prototype.\n const plain = emitRuntimeHelper(g.ctx, \"__zcPlain\", ZC_PLAIN_DECL);\n const code =\n `if(!${plain}(${input}))return ${g.fail};` +\n `${out}={};` +\n `for(${keyVar} in ${input}){if(${keyVar}!==\"__proto__\"&&${hop}.call(${input},${keyVar})){` +\n `${valVar}=${input}[${keyVar}];${inner.code}${out}[${keyVar}]=${inner.value};}}`;\n return { code, value: out };\n}\n\n/**\n * `.transform(fn)`: validate the inner schema, then hand its parsed value to the\n * callback. `z.preprocess(fn, schema)` reverses those two steps: call first,\n * then validate the callback's output. Returning FAIL from the inner build\n * preserves the corresponding pipe short-circuit in either direction.\n *\n * The IR reaches here only for a synchronous single-argument callback: a\n * `ctx`-taking or async transform is extracted as a `fallback` instead\n * (see extractPipe), so there is no parse context to reproduce.\n */\nfunction buildEffect(ir: SchemaIR & { type: \"effect\" }, input: string, g: BuildGen): Built | null {\n if (ir.effectKind === \"preprocess\") {\n const value = local(g, \"bpv\");\n const inner = build(ir.inner, value, g);\n if (inner === null) return null;\n return {\n code: `${value}=${emitEffectCallable(g.ctx, ir)}(${input});${inner.code}`,\n value: inner.value,\n };\n }\n\n const inner = build(ir.inner, input, g);\n if (inner === null) return null;\n const out = local(g, \"bx\");\n return {\n code: `${inner.code}${out}=${emitEffectCallable(g.ctx, ir)}(${inner.value});`,\n value: out,\n };\n}\n\n/**\n * A coercing and/or overwrite string (`z.coerce.string()`, `.trim()`,\n * `.toLowerCase()`, ...): coerce first, then emit checks one statement at a time\n * in DECLARATION order, interleaved with rewrites, because a rewrite is visible\n * to every check after it — `z.string().trim().min(1)` rejects `\" \"` where\n * `z.string().min(1).trim()` accepts it. That ordering is exactly why the fast\n * path, which sorts checks cheapest-first and returns the input unchanged, has\n * to decline these.\n *\n * Only reached for a rewriting string; a non-coercing, check-only one never\n * enters the rebuild set and is validated in place by `passthrough`.\n */\nfunction buildString(ir: SchemaIR & { type: \"string\" }, input: string, g: BuildGen): Built | null {\n const value = local(g, \"bs\");\n let code =\n ir.coerce === true\n ? `try{${value}=String(${input});}catch(_){return ${g.fail};}`\n : `if(typeof ${input}!==\"string\")return ${g.fail};${value}=${input};`;\n for (const check of ir.checks) {\n switch (check.kind) {\n case \"overwrite_effect\":\n code += `${value}=${emitEffectFn(g.ctx, check.source)}(${value});`;\n break;\n case \"refine_effect\":\n code += `if(!${emitEffectCallable(g.ctx, check)}(${value}))return ${g.fail};`;\n break;\n case \"super_refine_effect\":\n // Rewrites through zod's payload; mutatesBeyondStrip already rejects it.\n return null;\n default: {\n const expr = fastStringCheck(check, value, g.ctx);\n if (expr === null) return null; // z.url(), unknown format\n code += `if(!(${expr}))return ${g.fail};`;\n }\n }\n }\n return { code, value };\n}\n\n/**\n * `z.stringbool()`: normalize once, select the declared truthy/falsy side, and\n * return the boolean directly. The ordinary Fast Path cannot host this codec\n * because its contract returns the original input by reference; the build path\n * is designed for exactly this kind of small output rewrite.\n */\nfunction buildStringBool(ir: StringBoolIR, input: string, g: BuildGen): Built {\n let code = `if(typeof ${input}!==\"string\")return ${g.fail};`;\n let normalized = input;\n if (!ir.caseSensitive) {\n normalized = local(g, \"bn\");\n code += `${normalized}=${input}.toLowerCase();`;\n }\n\n const out = local(g, \"bb\");\n if (stringBoolUsesInline(ir)) {\n const membership = (values: readonly string[]): string =>\n values.map((value) => `${normalized}===${escapeString(value)}`).join(\"||\");\n code +=\n `if(${membership(ir.truthy)}){${out}=true;}` +\n `else if(${membership(ir.falsy)}){${out}=false;}` +\n `else{return ${g.fail};}`;\n } else {\n const lookup = emitStringBoolMap(ir, g.ctx);\n code += `${out}=${lookup}.get(${normalized});if(${out}===undefined)return ${g.fail};`;\n }\n return { code, value: out };\n}\n\n/** Primitive nodes whose `coerce` flag rewrites their output before checks run. */\ntype CoercedPrimitiveIR = Extract<SchemaIR, { type: \"number\" | \"boolean\" | \"bigint\" | \"date\" }>;\n\n/**\n * Coerce once into a local, then reuse the ordinary Fast Path as the acceptance\n * predicate over the converted value. The build path only needs a verdict on\n * its hot pass; if it fails, the existing deferred slow walk reruns the original\n * coercing schema and produces Zod-identical issues.\n *\n * Number/BigInt/Date conversion can invoke user hooks and throw. Zod catches\n * those throws and reports invalid_type, so the sentinel branch does the same\n * without allocating an issue. Boolean never invokes conversion hooks.\n */\nfunction buildCoercedPrimitive(ir: CoercedPrimitiveIR, input: string, g: BuildGen): Built | null {\n if (ir.coerce !== true) return null;\n const value = local(g, \"bc\");\n let conversion: string;\n switch (ir.type) {\n case \"number\":\n conversion = `Number(${input})`;\n break;\n case \"boolean\":\n conversion = `Boolean(${input})`;\n break;\n case \"bigint\":\n conversion = `BigInt(${input})`;\n break;\n case \"date\":\n conversion = `new Date(${input})`;\n break;\n }\n\n // A fresh shallow node is intentional: only the coerce flag changes. The\n // existing primitive generator remains the single source of truth for every\n // range, format, refine and finite/valid-date check.\n const predicate = generateFast(\n { ...ir, coerce: false },\n createFastGen(value, g.ctx, true, g.scope),\n );\n if (predicate === null) return null;\n\n const assign = `${value}=${conversion};`;\n const code = ir.type === \"boolean\" ? assign : `try{${assign}}catch(_){return ${g.fail};}`;\n return {\n code: code + (predicate === \"true\" ? \"\" : `if(!(${predicate}))return ${g.fail};`),\n value,\n };\n}\n\n/**\n * `.default(v)`: `undefined` yields the declared value without running the\n * inner schema, anything else parses normally — the same two branches\n * `slowDefault` emits, reading the value off the retained schema so a\n * reference-typed default keeps zod's identity (one shared object, not a copy).\n *\n * The substituted value is not validated, so it makes the fast path a PARTIAL\n * predicate (`fc(undefined)` is false where the schema accepts) — which is why\n * this records {@link CodeGenContext.buildSubstitutesValue}, on which\n * `generateValidator` withholds `.is()`.\n */\nfunction buildDefault(\n ir: SchemaIR & { type: \"default\" },\n input: string,\n g: BuildGen,\n): Built | null {\n const inner = build(ir.inner, input, g);\n if (inner === null) return null;\n // Every `default` node is in the rebuild set, so it is always BUILT and never\n // passed through — which makes this flag an exact record of whether the\n // finished pass substitutes a value.\n g.ctx.buildSubstitutesValue = true;\n const out = local(g, \"bq\");\n const value = defaultValueExpr(ir);\n // Zod re-applies the default when the inner returns undefined for a defined\n // input; only emitted when the inner can actually do that.\n const reapply = needsPostInnerDefault(ir) ? `if(${out}===undefined){${out}=${value};}` : \"\";\n return {\n code:\n `if(${input}===undefined){${out}=${value};}` +\n `else{${inner.code}${out}=${inner.value};${reapply}}`,\n value: out,\n };\n}\n\n/** `optional` / `nullable` around a rebuilding inner: pass the sentinel through. */\nfunction buildSentinel(\n innerIR: SchemaIR,\n input: string,\n g: BuildGen,\n test: string,\n sentinel: string,\n): Built | null {\n const inner = build(innerIR, input, g);\n if (inner === null) return null;\n const out = local(g, \"bw\");\n return {\n code: `if(${input}${test}){${out}=${sentinel};}else{${inner.code}${out}=${inner.value};}`,\n value: out,\n };\n}\n\n/** Allocate a `var` the hosted build function declares. */\nfunction local(g: BuildGen, prefix: string): string {\n const name = emitTemp(g.ctx, prefix);\n g.scope.temps.push(name);\n return name;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqGA,SAAS,WAAW,MAAgB,oBAAoB,MAA6B;CACnF,MAAM,0BAAU,IAAI,IAAsB,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;CACrD,MAAM,QAAoB,CAAC;CAC3B,MAAM,uBAAO,IAAI,IAAc;CAC/B,MAAM,WAAW,SAAyB;EACxC,IAAI,KAAK,IAAI,IAAI,GAAG;EACpB,KAAK,IAAI,IAAI;EACb,MAAM,KAAK,IAAI;EACf,IAAI,KAAK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OAAO;EACL,MAAM,MAAM,QAAQ,KAAK,IAAI,IAAI,GAAG,SAAS,SAAS,MAAM,OAAO,IAAI,GAAG,MAAM,MAAM;EACtF,OAAO;CACT;AACF;;AAGA,SAAS,MAAM,GAAa,QAAwB;CAClD,MAAM,OAAO,SAAS,EAAE,KAAK,MAAM;CACnC,EAAE,MAAM,MAAM,KAAK,IAAI;CACvB,OAAO;AACT"}
1
+ {"version":3,"file":"build-path.js","names":[],"sources":["../../../src/core/codegen/build-path.ts"],"sourcesContent":["/**\n * Build Path: one uninstrumented pass that VALIDATES and BUILDS rewritten\n * output together, abandoning the whole parse at the first failing check.\n *\n * `z.object()` strips unknown keys, so a successful parse cannot return the\n * input by reference — it must produce a fresh object. That rules out the Fast\n * Path (whose contract is `data === input`), and before this the only remaining\n * option was the eager slow walk: a fully instrumented traversal that collects\n * issues on every parse, valid or not.\n *\n * Two passes are wasteful in either direction. Validating first and building\n * afterwards reads every property twice (measured 29.7 ns vs 21.6 for the slow\n * walk on a 6-field object). Building with issue collection pays the\n * instrumentation even when nothing fails. Doing both in ONE pass, with a\n * sentinel instead of an issues array, beats both — and a failure costs only\n * the checks up to the first bad one, because the issue-producing walk is\n * deferred into `.error` exactly as `__zcFinD` does for mutation-free schemas:\n *\n * object clean object invalid array(8) invalid\n * slow walk 21.6 ns 30.4 ns 197.5 ns\n * build path 18.1 ns 7.7 ns 9.8 ns\n *\n * A subtree that rebuilds nothing is validated with its existing Fast Path\n * expression and passed through by reference, so only nodes that genuinely\n * produce a new value need code here; anything else returns null and keeps the\n * eager walk.\n *\n * Coverage is what decides whether this pass is reached at all, because it is\n * all-or-nothing per schema: ONE unmodelled node anywhere in the tree costs the\n * whole schema its single-pass parse. Modelled, beyond the stripping containers\n * this started with: array size checks and `.refine()`, object-level `.refine()`,\n * `.default()` substitution, ordered string rewrites (`.trim()`,\n * `.toLowerCase()`), sync `.transform()`, `z.stringbool()`, and the five native\n * coercions (`string`, `number`, `boolean`, `bigint`, `date`). Still declined, via\n * {@link mutatesBeyondStrip} — `.catch()` (its callback wants the inner schema's\n * issue list, which this pass never builds), `z.url()`, and `superRefine`.\n */\n\nimport type {\n DiscriminatedUnionIR,\n ObjectIR,\n RefineEffectCheckIR,\n SchemaIR,\n StringBoolIR,\n} from \"../types.js\";\nimport type { CodeGenContext, FastScope } from \"./context.js\";\nimport {\n declareFastTemps,\n emitEffectCallable,\n emitEffectFn,\n emitPooledConstant,\n emitRuntimeHelper,\n emitTemp,\n escapeString,\n hasMutation,\n keyMembershipTest,\n literalToJs,\n needsProtoScrub,\n outputAlwaysDefined,\n rejectsUndefined,\n tupleRewritesShortInput,\n} from \"./context.js\";\nimport { createFastGen, generateFast } from \"./fast-path.js\";\nimport { EXTRACT_CAP, estimateFastCost, MIN_EXTRACT, predictedInlineSize } from \"./fast-size.js\";\nimport { ZC_HOP_DECL, ZC_PLAIN_DECL, ZC_PROTO_SCRUB_DECL } from \"./issue-decls.js\";\nimport { defaultValueExpr, needsPostInnerDefault } from \"./schemas/default.js\";\nimport { parsedProperties } from \"./schemas/object.js\";\nimport { innerAppliesDefaultOnUndefined } from \"./schemas/optional.js\";\nimport { detectUnionDiscriminator } from \"./schemas/discriminated-union.js\";\nimport { fastStringCheck } from \"./schemas/string.js\";\nimport {\n emitStringBoolMap,\n stringBoolInlineHit,\n stringBoolUsesInline,\n} from \"./schemas/string-bool.js\";\n\n/** Statements that leave the built value in `value`, or `return <FAIL>` on failure. */\ninterface Built {\n code: string;\n value: string;\n}\n\ninterface BuildGen {\n ctx: CodeGenContext;\n /** Identifier of the per-validator FAIL sentinel. */\n fail: string;\n /** `var` temps and running emitted size of the function being assembled. */\n scope: FastScope;\n /**\n * May THIS node be hosted in its own function? False for the node a hosted\n * build was created for — it already IS that function, so re-hosting it would\n * recurse forever. Children are always extractable, letting an oversized\n * helper split further.\n */\n extractable: boolean;\n /** Nodes of the root schema that rebuild (see rebuildSet). */\n rebuilds: ReadonlySet<SchemaIR>;\n}\n\n/**\n * Which nodes of `root` produce a value that is not their input — a stripping\n * object, coercion, codec, default, overwrite or transform, including\n * containers that contain one. Everything else can be validated in place and\n * passed through, which is what keeps this generator small.\n *\n * Computed as a fixpoint rather than a plain walk because of recursion: a\n * `recursiveRef` is a back-edge with no children, so a local walk reads false\n * for it and would pass the whole recursive subtree through by reference —\n * leaving every nested value unstripped while the outermost one was rebuilt.\n * Resolving the ref against its target closes the cycle, and iterating to a\n * fixpoint settles the mutual dependency between the two.\n */\nfunction rebuildSet(root: SchemaIR, includeProtoScrub = true): ReadonlySet<SchemaIR> {\n const targets = new Map<number, SchemaIR>([[0, root]]);\n const nodes: SchemaIR[] = [];\n const seen = new Set<SchemaIR>();\n const collect = (node: SchemaIR): void => {\n if (seen.has(node)) return;\n seen.add(node);\n nodes.push(node);\n if (node.type === \"recursionTarget\") targets.set(node.refId, node.inner);\n for (const child of children(node)) collect(child);\n };\n collect(root);\n\n const rebuilds = new Set<SchemaIR>();\n for (let changed = true; changed;) {\n changed = false;\n for (const node of nodes) {\n if (rebuilds.has(node)) continue;\n const target = node.type === \"recursiveRef\" ? targets.get(node.refId ?? 0) : undefined;\n const rebuild =\n (node.type === \"object\" && node.stripUnknownKeys === true) ||\n // A freezing readonly's output is `Object.freeze(inner)` — a value the\n // caller never handed us, so it must be BUILT rather than passed\n // through. Marking it here is also what makes `rebuildsOutput` true and\n // so withholds every by-reference shortcut above it.\n (node.type === \"readonly\" && node.freeze === true) ||\n // `.default()` substitutes its own value for `undefined`, so its output\n // is not its input even when the inner schema passes through — it must\n // never be handed to `passthrough`, whose fast check would reject the\n // absent value outright.\n node.type === \"default\" ||\n // A tuple whose output can differ from a SHORT input it accepts —\n // `z.tuple([z.any()]).rest(z.number())` answers `[]` with `[undefined]`\n // — is not its own input either. `fastTuple` narrows exactly those\n // slots to \"present\" (sound for the root shortcut, which only reads a\n // TRUE result), so handing it to `passthrough`, which reads a FALSE one\n // as rejection, turned a valid short input into a failure with an empty\n // issue array. Marking it here makes `buildTuple`'s own bail propagate\n // instead.\n (node.type === \"tuple\" && tupleRewritesShortInput(node)) ||\n // A loose/catchall object or a record hands its input back, and zod's\n // output never carries an own `__proto__` — so its output is not its\n // input whenever the key is there. Marking it here is what stops\n // `passthrough` handing the raw container up through a PARENT that\n // never looks inside it (`z.array(z.looseObject(...))`); the parent\n // rebuilds instead, and each child is scrubbed as it is built.\n (includeProtoScrub && needsProtoScrub(node)) ||\n // `z.stringbool()` replaces its accepted string with a boolean.\n node.type === \"stringBool\" ||\n // An overwrite effect (`.trim()`, `.toLowerCase()`) rewrites the string,\n // so the node's output is a new value: it has to be BUILT rather than\n // validated in place (see buildString).\n (node.type === \"string\" &&\n (node.coerce === true || node.checks.some((c) => c.kind === \"overwrite_effect\"))) ||\n ((node.type === \"number\" ||\n node.type === \"boolean\" ||\n node.type === \"bigint\" ||\n node.type === \"date\") &&\n node.coerce === true) ||\n // `.transform(fn)` replaces the value with the callback's result.\n node.type === \"effect\" ||\n (target !== undefined && rebuilds.has(target)) ||\n children(node).some((child) => rebuilds.has(child));\n if (rebuild) {\n rebuilds.add(node);\n changed = true;\n }\n }\n }\n return rebuilds;\n}\n\n/** Does `ir`, taken as a whole schema, produce a value that is not its input? */\nexport function rebuildsOutput(ir: SchemaIR): boolean {\n return rebuildSet(ir).has(ir);\n}\n\n/**\n * Does a PASSING fast check prove that the parse returns its own input?\n *\n * This is the contract behind every by-reference shortcut: `safeParse`'s\n * `if(fc(input)) return {success:true,data:input}` and, through `fc` in\n * `__zcMkv`, `parse()` / `parseAsync()` / `~standard.validate()`. It is strictly\n * stronger than \"the fast check is sound\", and two things break it:\n *\n * 1. The schema REBUILDS its output. A stripping object is the common case, and\n * it is why `z.object({ a: z.number().catch(0) })` — a strip object the\n * build pass declines because of the `.catch()` — used to answer\n * `parse({a: 1, b: 2})` with the UNSTRIPPED input while its own `safeParse`\n * correctly returned `{a: 1}`.\n *\n * 2. A plain `z.union()` with a MUTATING option. The fast form is an `||` chain,\n * which reports that SOME option accepts the input; zod returns the value\n * produced by the FIRST option that succeeds. Those differ as soon as an\n * earlier option would have claimed the input and rewritten it —\n * `z.union([z.string().catch(\"c\"), z.number()])` answers `\"c\"` for every\n * input, catch being infallible, while the chain matches `1` against the\n * number arm and hands back `1`. A DISCRIMINATED union is exempt: its\n * dispatch selects exactly one option, so which arm zod runs is never in\n * doubt (and a rewriting object option is caught by (1) anyway).\n *\n * Withheld here rather than in `fastUnion` on purpose: the `||` chain is still a\n * correct VERDICT, which is all a nested conjunct or a `.is()` guard needs, so\n * declining to emit it would cost every union-of-objects its fast path (and the\n * size-gated `__fo_` split) to fix a shortcut that only the root takes.\n */\nexport function fastResultIsInput(ir: SchemaIR): boolean {\n if (rebuildsOutput(ir)) return false;\n // 3. The output needs an own `__proto__` removed. A loose/catchall object or\n // a record hands its input back, and zod's output never carries the key,\n // so `safeParse` filters the value through `__zcPs` — which makes `data`\n // a copy exactly when the key is present. `fc` may not promise identity\n // on top of that, so `.is()` and `parse()` derive from safeParse for\n // these shapes (see ZC_PROTO_SCRUB_DECL).\n if (needsProtoScrub(ir)) return false;\n const seen = new Set<SchemaIR>();\n const ordered = (node: SchemaIR): boolean => {\n if (seen.has(node)) return false;\n seen.add(node);\n if (node.type === \"union\" && node.options.some(hasMutation)) return true;\n return children(node).some(ordered);\n };\n return !ordered(ir);\n}\n\n/**\n * True when the subtree mutates for any reason the build pass cannot reproduce —\n * `.catch()`, `z.url()`, `superRefine`. Those rewrite values in ways this pass\n * (which validates, coerces, decodes string booleans, substitutes declared\n * defaults, applies ordered string rewrites and copies) does not model, so the\n * schema keeps the eager walk.\n */\nfunction mutatesBeyondStrip(ir: SchemaIR): boolean {\n return mutatesHere(ir) || children(ir).some(mutatesBeyondStrip);\n}\n\n/**\n * Does this node rewrite values on its own account (ignoring its children, and\n * ignoring the reshaping a strip object does)? Mirrors the node-local half of\n * `hasMutation`; the recursion above supplies the other half.\n */\nfunction mutatesHere(ir: SchemaIR): boolean {\n switch (ir.type) {\n case \"string\":\n // Coercion and overwrite effects are absent: `buildString` applies them\n // in order. A `z.url()` check still is not — it trims, normalizes and\n // needs its own normalization/error semantics.\n return (\n superRefines(ir.checks) ||\n ir.checks.some((c) => c.kind === \"string_format\" && c.format === \"url\")\n );\n case \"number\":\n return superRefines(ir.checks);\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return false;\n // `default` and `effect` are absent: substituting a constant for `undefined`\n // and applying a sync transform are both modelled (see buildDefault /\n // buildEffect), and their inners are reached through `children`.\n //\n // `catch` is NOT: its catchValue callback receives a ctx carrying the inner\n // schema's collected issues, and this pass produces a sentinel instead of an\n // issue list — there is nothing to hand it.\n case \"catch\":\n case \"fallback\":\n return true;\n case \"object\":\n case \"array\":\n return superRefines(ir.checks);\n default:\n return false;\n }\n}\n\nfunction superRefines(checks: readonly { kind: string }[] | undefined): boolean {\n return checks !== undefined && checks.some((c) => c.kind === \"super_refine_effect\");\n}\n\n/**\n * Does anything STRICTLY BELOW `ir` hand back a container needing a `__proto__`\n * scrub?\n *\n * The root's by-reference shortcut can filter the value it returns\n * (`data: __zcPs(input)`), but that only reaches the OUTER container — a nested\n * one is never touched, because the shortcut does not walk. So a schema with a\n * scrub-needing descendant keeps the eager slow walk, which scrubs at every\n * level. Only the root's own scrub is shortcut-compatible.\n */\nexport function nestedNeedsProtoScrub(ir: SchemaIR): boolean {\n const seen = new Set<SchemaIR>();\n const walk = (node: SchemaIR): boolean => {\n if (seen.has(node)) return false;\n seen.add(node);\n return children(node).some((child) => needsProtoScrub(child) || walk(child));\n };\n return walk(ir);\n}\n\nfunction children(ir: SchemaIR): readonly SchemaIR[] {\n switch (ir.type) {\n case \"object\":\n return ir.catchall\n ? [...Object.values(ir.properties), ir.catchall]\n : Object.values(ir.properties);\n case \"array\":\n return [ir.element];\n case \"tuple\":\n return ir.rest === null ? ir.items : [...ir.items, ir.rest];\n case \"record\":\n case \"map\":\n return [ir.keyType, ir.valueType];\n case \"set\":\n return [ir.valueType];\n case \"union\":\n case \"discriminatedUnion\":\n return ir.options;\n case \"intersection\":\n return [ir.left, ir.right];\n case \"optional\":\n case \"nullable\":\n case \"readonly\":\n case \"default\":\n case \"catch\":\n case \"effect\":\n case \"recursionTarget\":\n case \"zodDelegate\":\n return [ir.inner];\n case \"pipe\":\n return [ir.in, ir.out];\n default:\n return [];\n }\n}\n\n/**\n * Host the whole schema as `function NAME(input){…}` returning the built value\n * or the FAIL sentinel. Returns the function name, or null when the schema is\n * not expressible as a single build pass.\n */\nexport function generateBuild(ir: SchemaIR, ctx: CodeGenContext): string | null {\n const rebuilds = rebuildSet(ir);\n if (!rebuilds.has(ir) || mutatesBeyondStrip(ir)) return null;\n // When the ONLY reason the root rebuilds is its own `__proto__` scrub, decline\n // and let the mutation-free shortcut below take it: that one keeps the fast\n // check and filters the returned value through `__zcPs`, where building would\n // pay a full single-pass walk to achieve the same thing. Measured at ~2x on a\n // 5-key `z.looseObject`, which is precisely the shape that lost the shortcut.\n // Only the root is exempt; a nested scrub still forces its parent to rebuild,\n // which is what the clause in `rebuildSet` is for.\n if (needsProtoScrub(ir) && !rebuildSet(ir, false).has(ir)) return null;\n const fail = emitFailSentinel(ctx);\n const scope: FastScope = { temps: [], used: 0 };\n const built = build(ir, \"input\", { ctx, extractable: false, fail, rebuilds, scope });\n if (built === null) return null;\n const name = emitTemp(ctx, \"vb\");\n ctx.preamble.push(\n `function ${name}(input){${declareFastTemps(scope)}${built.code}return ${built.value};}`,\n );\n return name;\n}\n\n/**\n * The build path's FAIL marker: an object compared by identity, which the build\n * function returns in place of a value and `safeParse` tests for.\n *\n * Pooled at file level rather than declared per validator. Its whole contract is\n * \"nothing a parse can produce equals this\", and that is a property of the\n * object's freshness, not of how many there are — so one `{}` serves every\n * rebuilding validator in the file, where before each allocated its own at\n * module init. Pooling by initializer text is safe for the same reason: the only\n * way a merge could hurt is if some other `{}` constant were ever RETURNED by a\n * build function, and the pool's other members are lookup tables and value\n * lists, which are only ever read from.\n */\nfunction emitFailSentinel(ctx: CodeGenContext): string {\n ctx.buildFailName ??= emitPooledConstant(ctx, \"Bf\", \"bf\", \"{}\");\n return ctx.buildFailName;\n}\n\n/**\n * Statements producing the built value of `ir` read from `input`, or null.\n *\n * Size-gated exactly like the fast path: once inlining `ir` would push the\n * function being assembled past EXTRACT_CAP, the sub-build is hosted as its own\n * `__vb_N(p)` returning value-or-FAIL and replaced by a call. Without this a\n * deeply nested schema emits one enormous build function — measured at 113 KB\n * and 354 KB on the deep fixtures — far past the bytecode size where V8 stops\n * running TurboFan on it, which would forfeit the speed this path exists for.\n */\nfunction build(ir: SchemaIR, input: string, g: BuildGen): Built | null {\n // Resolved before the passthrough shortcut below. A back-edge carries no\n // children, so `rebuildsOutput` reads false for it — and passing it through by\n // reference would leave every nested recursive value unstripped while the\n // outermost one was rebuilt.\n if (ir.type === \"recursiveRef\") return buildRecursiveCall(ir.refId ?? 0, input, g);\n if (ir.type === \"recursionTarget\") return buildRecursionTarget(ir, input, g);\n if (!g.rebuilds.has(ir)) return passthrough(ir, input, g);\n\n const cache = (g.ctx.fastSizeCache ??= new WeakMap<SchemaIR, number>());\n if (\n g.extractable &&\n g.scope.used + predictedInlineSize(ir, input.length, cache) > EXTRACT_CAP &&\n (g.scope.used > EXTRACT_CAP || estimateFastCost(ir, cache) >= MIN_EXTRACT)\n ) {\n const hosted = hostBuild(ir, g);\n if (hosted !== null) {\n const slot = local(g, \"bh\");\n const code = `${slot}=${hosted}(${input});if(${slot}===${g.fail})return ${g.fail};`;\n g.scope.used += code.length;\n return { code, value: slot };\n }\n }\n\n // This node's extraction decision is made; its descendants get to make their\n // own, so an oversized hosted helper keeps splitting.\n // When the ONLY reason this node rebuilds is its own `__proto__` scrub —\n // nothing under it rebuilds — a validated passthrough plus that scrub IS the\n // rebuild. Taken BEFORE the builders so a plain record keeps handing its\n // input back by reference (buildRecord would copy into a fresh `{}`, which is\n // a different documented behaviour: see the output-identity divergence).\n if (needsProtoScrub(ir) && !children(ir).some((child) => g.rebuilds.has(child))) {\n return passthrough(ir, input, g);\n }\n\n const before = g.scope.used;\n const out = buildInline(ir, input, { ...g, extractable: true });\n if (out !== null) g.scope.used = before + out.code.length;\n return out;\n}\n\n/** Host `ir`'s build in its own function over a fresh parameter; returns its name. */\nfunction hostBuild(ir: SchemaIR, g: BuildGen): string | null {\n const param = emitTemp(g.ctx, \"bp\");\n const scope: FastScope = { temps: [], used: 0 };\n const inner = build(ir, param, { ...g, extractable: false, scope });\n if (inner === null) return null;\n const name = emitTemp(g.ctx, \"vb\");\n g.ctx.preamble.push(\n `function ${name}(${param}){${declareFastTemps(scope)}${inner.code}return ${inner.value};}`,\n );\n return name;\n}\n\nfunction buildInline(ir: SchemaIR, input: string, g: BuildGen): Built | null {\n switch (ir.type) {\n case \"object\":\n return buildObject(ir, input, g);\n case \"array\":\n return buildArray(ir, input, g);\n case \"tuple\":\n return buildTuple(ir, input, g);\n case \"record\":\n return buildRecord(ir, input, g);\n case \"optional\":\n // A default further down the chain consumes undefined into a value, so\n // the `undefined → undefined` shortcut must not fire — same rule (and\n // same helper) the slow and fast paths already apply.\n return innerAppliesDefaultOnUndefined(ir.inner)\n ? build(ir.inner, input, g)\n : buildSentinel(ir.inner, input, g, \"===undefined\", \"undefined\");\n case \"nullable\":\n // `null` short-circuits unconditionally in zod, whatever the inner is;\n // undefined flows through, so an inner default still fires.\n return buildSentinel(ir.inner, input, g, \"===null\", \"null\");\n case \"default\":\n return buildDefault(ir, input, g);\n case \"string\":\n return buildString(ir, input, g);\n case \"stringBool\":\n return buildStringBool(ir, input, g);\n case \"number\":\n case \"boolean\":\n case \"bigint\":\n case \"date\":\n return buildCoercedPrimitive(ir, input, g);\n case \"effect\":\n return buildEffect(ir, input, g);\n case \"readonly\":\n return buildReadonly(ir, input, g);\n case \"zodDelegate\":\n return build(ir.inner, input, g);\n case \"union\":\n return buildUnion(ir, input, g);\n case \"discriminatedUnion\":\n return buildDiscriminatedUnion(ir, input, g);\n default:\n // A rebuilding intersection, map or set: expressible in principle, but\n // each needs its own output-shaping rules, so they keep the eager walk\n // until there is a measured reason to add them.\n return null;\n }\n}\n\n/**\n * Host the target's build once under a name registered BEFORE its body is\n * generated, so the back-edges inside that body resolve to it.\n */\nfunction buildRecursionTarget(\n ir: SchemaIR & { type: \"recursionTarget\" },\n input: string,\n g: BuildGen,\n): Built | null {\n const table = (g.ctx.buildRecNames ??= new Map<number, string>());\n if (!table.has(ir.refId)) {\n const name = emitTemp(g.ctx, \"vbr\");\n table.set(ir.refId, name);\n const param = emitTemp(g.ctx, \"bp\");\n const scope: FastScope = { temps: [], used: 0 };\n const inner = build(ir.inner, param, { ...g, extractable: false, scope });\n if (inner === null) {\n table.delete(ir.refId);\n return null;\n }\n g.ctx.preamble.push(\n `function ${name}(${param}){${declareFastTemps(scope)}${inner.code}return ${inner.value};}`,\n );\n }\n return buildRecursiveCall(ir.refId, input, g);\n}\n\n/** Call the hosted build for a recursion target, propagating its FAIL. */\nfunction buildRecursiveCall(refId: number, input: string, g: BuildGen): Built | null {\n const name = g.ctx.buildRecNames?.get(refId);\n if (name === undefined) return null;\n const slot = local(g, \"bh\");\n return {\n code: `${slot}=${name}(${input});if(${slot}===${g.fail})return ${g.fail};`,\n value: slot,\n };\n}\n\n/**\n * Try each option in declaration order and take the first that builds — which\n * is what zod's union does with the first option that parses.\n *\n * Every option is HOSTED rather than inlined, and that is load-bearing: a\n * failing build signals with `return FAIL`, which inside the enclosing function\n * would abandon the whole parse instead of moving on to the next option. Behind\n * a call, the same signal is just a value to test.\n *\n * A union of objects that all pin one shared key to disjoint required literals\n * is dispatched instead of probed, exactly as the fast path does (see\n * detectUnionDiscriminator). Disjointness is what makes that zod's answer and\n * not merely a faster one: at most ONE option can accept a given input, so the\n * first option to succeed is the option the discriminator selects, and an\n * input whose discriminator matches no case is rejected by every option — the\n * two outcomes a probe could have produced. Unlike the fast path there is no\n * minimum option count: the options are hosted calls either way, and a switch\n * only ever replaces a run of them with one. Measured on the eight-option\n * tagged union in the benchmarks: 15.5 → 10 ns per parse, the same as the\n * `z.discriminatedUnion` spelling of it.\n *\n * PLAIN unions only. A discriminated union must not reach the probe below: zod\n * resolves it by dispatch, not by probing, and the two disagree — see\n * {@link buildDiscriminatedUnion}.\n */\nfunction buildUnion(ir: SchemaIR & { type: \"union\" }, input: string, g: BuildGen): Built | null {\n const discriminated = detectUnionDiscriminator(ir.options, 2);\n if (discriminated !== null) {\n return buildDispatch(discriminated.discriminator, discriminated.cases, ir.options, input, g);\n }\n\n const hosted: string[] = [];\n for (const option of ir.options) {\n const fn = g.rebuilds.has(option) ? hostBuild(option, g) : hostPassthrough(option, g);\n if (fn === null) return null;\n hosted.push(fn);\n }\n if (hosted.length === 0) return null;\n\n const out = local(g, \"bu\");\n let code = `${out}=${hosted[0] as string}(${input});`;\n for (const fn of hosted.slice(1)) {\n code += `if(${out}===${g.fail}){${out}=${fn}(${input});}`;\n }\n code += `if(${out}===${g.fail})return ${g.fail};`;\n return { code, value: out };\n}\n\n/**\n * Dispatch on the discriminator and build ONLY the option that value selects,\n * failing outright when it selects none — mirroring zod, which resolves the\n * option through a `discriminator value → option` map built from each option's\n * `propValues` and pushes `invalid_union` (\"No matching discriminator\") without\n * ever running an option's parse when the lookup misses.\n *\n * Probing the options in order like {@link buildUnion} does is NOT equivalent,\n * because an option can accept more than its own dispatch values. A wrapper that\n * substitutes a value contributes only the value it wraps to `propValues` while\n * its parse also accepts the input it substitutes FOR:\n * `z.literal(\"a\").default(\"a\")` dispatches on `\"a\"` alone yet parses a MISSING\n * discriminator, so sequential probing accepted `{v:\"x\"}` — output `{t:\"a\",v:\"x\"}`\n * — where zod rejects it. `.prefault()` and `.catch()` have the same shape, and\n * only escape it because neither reaches this pass today (a prefaulted schema\n * delegates to zod wholesale, and `.catch()` is refused by\n * {@link mutatesBeyondStrip}); a `.default()` is exactly what pulls the build\n * path in. The switch cannot drift that way: the dispatch table IS zod's, so an\n * unlisted discriminator reaches `default:` and fails, whatever the options\n * would have accepted on their own.\n *\n * The reverse — rejecting what zod accepts — is why `.optional()`/`.nullable()`\n * discriminators stay compiled rather than being refused here: their\n * `undefined`/`null` are in `propValues`, so they arrive as ordinary cases.\n *\n * Object-ness is proved BEFORE the discriminator is read, both because zod\n * rejects a non-object with its own `invalid_type` ahead of the lookup and\n * because the property read would throw on `null`/`undefined`.\n */\nfunction buildDiscriminatedUnion(\n ir: SchemaIR & { type: \"discriminatedUnion\" },\n input: string,\n g: BuildGen,\n): Built | null {\n return buildDispatch(ir.discriminator, ir.cases, ir.options, input, g);\n}\n\n/**\n * The switch behind {@link buildDiscriminatedUnion} and a dispatched\n * {@link buildUnion}: prove object-ness, select the option the discriminator\n * names, and build that option alone. Switches over the literal labels, as the\n * fast path does — see `emitFastDiscriminatedSwitch` for the measurement that\n * retired the ordinal-table form.\n */\nfunction buildDispatch(\n discriminator: string,\n cases: DiscriminatedUnionIR[\"cases\"],\n options: readonly SchemaIR[],\n input: string,\n g: BuildGen,\n): Built | null {\n const out = local(g, \"bd\");\n // One hosted build per REACHABLE option, keyed by option index: a multi-value\n // literal (`z.literal([\"a\",\"c\"])`) contributes several cases selecting the\n // same option, and they share the one function rather than emitting it twice.\n const hostedByOption = new Map<number, string>();\n let arms = \"\";\n for (const { value, option: index } of cases) {\n let fn = hostedByOption.get(index);\n if (fn === undefined) {\n const option = options[index];\n if (option === undefined) return null;\n const hosted = g.rebuilds.has(option) ? hostBuild(option, g) : hostPassthrough(option, g);\n if (hosted === null) return null;\n fn = hosted;\n hostedByOption.set(index, fn);\n }\n arms += `case ${literalToJs(value)}:${out}=${fn}(${input});break;`;\n }\n if (arms === \"\") return null;\n\n return {\n code:\n `if(typeof ${input}!==\"object\"||${input}===null||Array.isArray(${input}))return ${g.fail};` +\n `switch(${input}[${escapeString(discriminator)}]){${arms}default:return ${g.fail};}` +\n `if(${out}===${g.fail})return ${g.fail};`,\n value: out,\n };\n}\n\n/**\n * Host a non-rebuilding option as `value-or-FAIL`, so a union can probe it with\n * the same protocol as a rebuilding one.\n */\nfunction hostPassthrough(ir: SchemaIR, g: BuildGen): string | null {\n const param = emitTemp(g.ctx, \"bp\");\n const scope: FastScope = { temps: [], used: 0 };\n const expr = generateFast(ir, createFastGen(param, g.ctx, true, scope));\n if (expr === null) return null;\n const name = emitTemp(g.ctx, \"vp\");\n g.ctx.preamble.push(\n `function ${name}(${param}){${declareFastTemps(scope)}return ${expr === \"true\" ? param : `(${expr})?${param}:${g.fail}`};}`,\n );\n return name;\n}\n\n/**\n * Validate in place with the Fast Path and hand the input straight back —\n * filtered through `__zcPs` for a container zod would have stripped an own\n * `__proto__` from (see ZC_PROTO_SCRUB_DECL). The filter copies only when the\n * key is present, so the ordinary value is still returned by reference.\n */\nfunction passthrough(ir: SchemaIR, input: string, g: BuildGen): Built | null {\n const scoped = createFastGen(input, g.ctx, true, g.scope);\n const expr = generateFast(ir, scoped);\n if (expr === null) return null;\n const guard = expr === \"true\" ? \"\" : `if(!(${expr}))return ${g.fail};`;\n if (!needsProtoScrub(ir)) return { code: guard, value: input };\n const slot = local(g, \"bs\");\n const scrub = emitRuntimeHelper(g.ctx, \"__zcPs\", ZC_PROTO_SCRUB_DECL);\n return { code: `${guard}${slot}=${scrub}(${input});`, value: slot };\n}\n\n/**\n * Rebuild from the declared keys. Sound for a stripping object (that IS the\n * output) and for a strict one (unknown keys are rejected, so the declared keys\n * are the whole key set). A loose object or one with a `.catchall()` keeps keys\n * this pass does not enumerate, so those bail.\n */\n/**\n * Freeze the inner's built value, matching zod's `Object.freeze(payload.value)`.\n *\n * Sound only because `freeze` is set exclusively over a stripping object, whose\n * build ALWAYS allocates (`buildObject` assembles a fresh `__bo_N`) — so the\n * frozen value is never the caller's input. A pass-through inner would return\n * `input` here and freezing it would mutate data the caller still owns, which\n * is why the extractor withholds the flag for every other container.\n */\nfunction buildReadonly(\n ir: SchemaIR & { type: \"readonly\" },\n input: string,\n g: BuildGen,\n): Built | null {\n const built = build(ir.inner, input, g);\n if (built === null || ir.freeze !== true) return built;\n const slot = local(g, \"bz\");\n return { code: `${built.code}${slot}=Object.freeze(${built.value});`, value: slot };\n}\n\nfunction buildObject(ir: ObjectIR, input: string, g: BuildGen): Built | null {\n if (ir.catchall !== undefined) return null;\n if (ir.stripUnknownKeys !== true && ir.strict !== true) return null;\n // Both swallow an absent key's failure, which a single-pass build that fails\n // at the first bad check cannot model.\n if (ir.skipAbsentKeys !== undefined && ir.skipAbsentKeys.length > 0) return null;\n if (ir.suppressAbsentKeys !== undefined && ir.suppressAbsentKeys.length > 0) return null;\n const nonoptional = new Set(ir.nonoptionalKeys ?? []);\n // Object-level `.refine()` runs on the assembled output (below). superRefine\n // rewrites the payload, which this pass does not model — mutatesBeyondStrip\n // already rejects it, so this is a belt-and-braces narrowing of the type.\n const refines = ir.checks ?? [];\n if (refines.some((check) => check.kind !== \"refine_effect\")) return null;\n\n let code = `if(typeof ${input}!==\"object\"||${input}===null||Array.isArray(${input}))return ${g.fail};`;\n\n if (ir.strict === true) {\n const keyVar = local(g, \"bk\");\n code += `for(${keyVar} in ${input}){if(!(${keyMembershipTest(g.ctx, Object.keys(ir.properties), keyVar)}))return ${g.fail};}`;\n }\n\n const slots: { always: boolean; keyStr: string; value: string }[] = [];\n for (const [key, propIR] of parsedProperties(ir)) {\n const keyStr = escapeString(key);\n const slot = local(g, \"bv\");\n // A required key has to be present whatever its schema makes of `undefined`.\n if (nonoptional.has(key)) code += `if(!(${keyStr} in ${input}))return ${g.fail};`;\n code += `${slot}=${input}[${keyStr}];`;\n const propBuilt = build(propIR, slot, g);\n if (propBuilt === null) return null;\n code += propBuilt.code;\n slots.push({ always: outputAlwaysDefined(propIR), keyStr, value: propBuilt.value });\n }\n\n // Same assembly the eager strip walk uses: the longest LEADING run of\n // always-present keys goes into one object literal (V8 stamps it from a\n // cached boilerplate map in a single allocation), and everything after the\n // first conditional key is appended so insertion order still matches zod.\n // The per-key test is zod's own — keep the key when the parsed value is\n // defined, or when it was present on the input at all.\n const out = local(g, \"bo\");\n const literal: string[] = [];\n let appends = \"\";\n let leading = true;\n for (const slot of slots) {\n if (leading && slot.always) {\n literal.push(`${slot.keyStr}:${slot.value}`);\n continue;\n }\n leading = false;\n appends += slot.always\n ? `${out}[${slot.keyStr}]=${slot.value};`\n : `if(${slot.value}!==undefined||(${slot.keyStr} in ${input})){${out}[${slot.keyStr}]=${slot.value};}`;\n }\n code += `${out}={${literal.join(\",\")}};${appends}`;\n // Zod parses the properties into the payload first and skips the check chain\n // when that produced issues, so a bad property suppresses the refine — which\n // this pass gets for free, having already returned FAIL at that property.\n for (const check of refines) {\n code += `if(!${emitEffectCallable(g.ctx, check as RefineEffectCheckIR)}(${out}))return ${g.fail};`;\n }\n return { code, value: out };\n}\n\nfunction buildArray(ir: SchemaIR & { type: \"array\" }, input: string, g: BuildGen): Built | null {\n // Length checks are pure predicates over `input.length`, so they hoist ahead\n // of the element loop: a size mismatch bails before a single element is\n // validated. Zod reports the per-element issue first when both fail, but the\n // build pass produces no issues — only the sentinel — and the deferred walk\n // that does produce them keeps zod's order.\n let sizes = \"\";\n const refines: RefineEffectCheckIR[] = [];\n for (const check of ir.checks) {\n switch (check.kind) {\n case \"min_length\":\n sizes += `if(${input}.length<${check.minimum})return ${g.fail};`;\n break;\n case \"max_length\":\n sizes += `if(${input}.length>${check.maximum})return ${g.fail};`;\n break;\n case \"length_equals\":\n sizes += `if(${input}.length!==${check.length})return ${g.fail};`;\n break;\n case \"refine_effect\":\n refines.push(check);\n break;\n default:\n // super_refine (rewrites the value) or a check kind not modelled here.\n return null;\n }\n }\n\n const out = local(g, \"ba\");\n const index = local(g, \"bi\");\n const elem = local(g, \"be\");\n const inner = build(ir.element, elem, g);\n if (inner === null) return null;\n let code =\n `if(!Array.isArray(${input}))return ${g.fail};` +\n sizes +\n `${out}=new Array(${input}.length);` +\n `for(${index}=0;${index}<${input}.length;${index}++){` +\n `${elem}=${input}[${index}];${inner.code}${out}[${index}]=${inner.value};}`;\n // `.refine()` sees the parsed payload, which for a rebuilding element is the\n // freshly assembled array — the same value zod hands its checks.\n for (const check of refines) {\n code += `if(!${emitEffectCallable(g.ctx, check)}(${out}))return ${g.fail};`;\n }\n return { code, value: out };\n}\n\nfunction buildTuple(ir: SchemaIR & { type: \"tuple\" }, input: string, g: BuildGen): Built | null {\n // Trailing-optional and rest handling shape the output length; keep those on\n // the eager walk rather than restating the rules here.\n if (ir.rest !== null) return null;\n if (ir.optStart !== ir.items.length) return null;\n if (ir.items.some((item) => !rejectsUndefined(item))) return null;\n\n let code = `if(!Array.isArray(${input})||${input}.length!==${ir.items.length})return ${g.fail};`;\n const values: string[] = [];\n for (const [index, itemIR] of ir.items.entries()) {\n const slot = local(g, \"bt\");\n code += `${slot}=${input}[${index}];`;\n const inner = build(itemIR as SchemaIR, slot, g);\n if (inner === null) return null;\n code += inner.code;\n values.push(inner.value);\n }\n const out = local(g, \"bl\");\n code += `${out}=[${values.join(\",\")}];`;\n return { code, value: out };\n}\n\nfunction buildRecord(ir: SchemaIR & { type: \"record\" }, input: string, g: BuildGen): Built | null {\n const plainStringKey =\n ir.keyType.type === \"string\" && ir.keyType.checks.length === 0 && ir.keyType.coerce !== true;\n if (!plainStringKey) return null;\n\n const out = local(g, \"br\");\n const keyVar = local(g, \"brk\");\n const valVar = local(g, \"brv\");\n const inner = build(ir.valueType, valVar, g);\n if (inner === null) return null;\n const hop = emitRuntimeHelper(g.ctx, \"__zcHop\", ZC_HOP_DECL);\n // `$ZodRecord` gates on `util.isPlainObject`, not the `util.isObject` the\n // object/discriminated-union builds above use — see ZC_PLAIN_DECL. And it\n // skips `__proto__` outright: here that guard is load-bearing twice over,\n // since `out[key]=value` for that key would not add a property at all but\n // REDEFINE the built object's prototype.\n const plain = emitRuntimeHelper(g.ctx, \"__zcPlain\", ZC_PLAIN_DECL);\n const code =\n `if(!${plain}(${input}))return ${g.fail};` +\n `${out}={};` +\n `for(${keyVar} in ${input}){if(${keyVar}!==\"__proto__\"&&${hop}.call(${input},${keyVar})){` +\n `${valVar}=${input}[${keyVar}];${inner.code}${out}[${keyVar}]=${inner.value};}}`;\n return { code, value: out };\n}\n\n/**\n * `.transform(fn)`: validate the inner schema, then hand its parsed value to the\n * callback. `z.preprocess(fn, schema)` reverses those two steps: call first,\n * then validate the callback's output. Returning FAIL from the inner build\n * preserves the corresponding pipe short-circuit in either direction.\n *\n * The IR reaches here only for a synchronous single-argument callback: a\n * `ctx`-taking or async transform is extracted as a `fallback` instead\n * (see extractPipe), so there is no parse context to reproduce.\n */\nfunction buildEffect(ir: SchemaIR & { type: \"effect\" }, input: string, g: BuildGen): Built | null {\n if (ir.effectKind === \"preprocess\") {\n const value = local(g, \"bpv\");\n const inner = build(ir.inner, value, g);\n if (inner === null) return null;\n return {\n code: `${value}=${emitEffectCallable(g.ctx, ir)}(${input});${inner.code}`,\n value: inner.value,\n };\n }\n\n const inner = build(ir.inner, input, g);\n if (inner === null) return null;\n const out = local(g, \"bx\");\n return {\n code: `${inner.code}${out}=${emitEffectCallable(g.ctx, ir)}(${inner.value});`,\n value: out,\n };\n}\n\n/**\n * A coercing and/or overwrite string (`z.coerce.string()`, `.trim()`,\n * `.toLowerCase()`, ...): coerce first, then emit checks one statement at a time\n * in DECLARATION order, interleaved with rewrites, because a rewrite is visible\n * to every check after it — `z.string().trim().min(1)` rejects `\" \"` where\n * `z.string().min(1).trim()` accepts it. That ordering is exactly why the fast\n * path, which sorts checks cheapest-first and returns the input unchanged, has\n * to decline these.\n *\n * Only reached for a rewriting string; a non-coercing, check-only one never\n * enters the rebuild set and is validated in place by `passthrough`.\n */\nfunction buildString(ir: SchemaIR & { type: \"string\" }, input: string, g: BuildGen): Built | null {\n const value = local(g, \"bs\");\n let code =\n ir.coerce === true\n ? `try{${value}=String(${input});}catch(_){return ${g.fail};}`\n : `if(typeof ${input}!==\"string\")return ${g.fail};${value}=${input};`;\n for (const check of ir.checks) {\n switch (check.kind) {\n case \"overwrite_effect\":\n code += `${value}=${emitEffectFn(g.ctx, check.source)}(${value});`;\n break;\n case \"refine_effect\":\n code += `if(!${emitEffectCallable(g.ctx, check)}(${value}))return ${g.fail};`;\n break;\n case \"super_refine_effect\":\n // Rewrites through zod's payload; mutatesBeyondStrip already rejects it.\n return null;\n default: {\n const expr = fastStringCheck(check, value, g.ctx);\n if (expr === null) return null; // z.url(), unknown format\n code += `if(!(${expr}))return ${g.fail};`;\n }\n }\n }\n return { code, value };\n}\n\n/**\n * `z.stringbool()`: normalize once, select the declared truthy/falsy side, and\n * return the boolean directly. The ordinary Fast Path cannot host this codec\n * because its contract returns the original input by reference; the build path\n * is designed for exactly this kind of small output rewrite.\n *\n * Case-insensitive codecs look the input up VERBATIM before lowercasing it.\n * The accepted spellings are all lowercase (see extractStringBool), so an\n * exact hit is what `toLowerCase()` would have produced anyway, and the common\n * config flag or query parameter is spelled that way already. For the hashed\n * form that is one `Map.get` in place of `toLowerCase()` plus one. A miss\n * lowercases and looks up again — unless lowercasing changed nothing, in which\n * case the second lookup would only repeat the first, so a lowercase\n * non-spelling is rejected for the price of the old path plus one string\n * compare. Measured per value on V8: 10.8 → 7.5 ns over lowercase spellings,\n * 13.5 → 10.7 ns over a mixed-case rotation. The inline form compares the raw\n * string against its few spellings first — pointer compares on internalized\n * strings — for the same trade.\n */\nfunction buildStringBool(ir: StringBoolIR, input: string, g: BuildGen): Built {\n let code = `if(typeof ${input}!==\"string\")return ${g.fail};`;\n const out = local(g, \"bb\");\n if (stringBoolUsesInline(ir)) {\n let normalized = input;\n if (!ir.caseSensitive) {\n normalized = local(g, \"bn\");\n code += `${normalized}=${stringBoolInlineHit(ir, input)}?${input}:${input}.toLowerCase();`;\n }\n const membership = (values: readonly string[]): string =>\n values.map((value) => `${normalized}===${escapeString(value)}`).join(\"||\");\n code +=\n `if(${membership(ir.truthy)}){${out}=true;}` +\n `else if(${membership(ir.falsy)}){${out}=false;}` +\n `else{return ${g.fail};}`;\n } else {\n const lookup = emitStringBoolMap(ir, g.ctx);\n code += `${out}=${lookup}.get(${input});`;\n if (!ir.caseSensitive) {\n const lowered = local(g, \"bn\");\n code +=\n `if(${out}===undefined){${lowered}=${input}.toLowerCase();` +\n `if(${lowered}!==${input}){${out}=${lookup}.get(${lowered});}}`;\n }\n code += `if(${out}===undefined)return ${g.fail};`;\n }\n return { code, value: out };\n}\n\n/** Primitive nodes whose `coerce` flag rewrites their output before checks run. */\ntype CoercedPrimitiveIR = Extract<SchemaIR, { type: \"number\" | \"boolean\" | \"bigint\" | \"date\" }>;\n\n/**\n * Coerce once into a local, then reuse the ordinary Fast Path as the acceptance\n * predicate over the converted value. The build path only needs a verdict on\n * its hot pass; if it fails, the existing deferred slow walk reruns the original\n * coercing schema and produces Zod-identical issues.\n *\n * Number/BigInt/Date conversion can invoke user hooks and throw. Zod catches\n * those throws and reports invalid_type, so the sentinel branch does the same\n * without allocating an issue. Boolean never invokes conversion hooks.\n */\nfunction buildCoercedPrimitive(ir: CoercedPrimitiveIR, input: string, g: BuildGen): Built | null {\n if (ir.coerce !== true) return null;\n const value = local(g, \"bc\");\n let conversion: string;\n switch (ir.type) {\n case \"number\":\n conversion = `Number(${input})`;\n break;\n case \"boolean\":\n conversion = `Boolean(${input})`;\n break;\n case \"bigint\":\n conversion = `BigInt(${input})`;\n break;\n case \"date\":\n conversion = `new Date(${input})`;\n break;\n }\n\n // A fresh shallow node is intentional: only the coerce flag changes. The\n // existing primitive generator remains the single source of truth for every\n // range, format, refine and finite/valid-date check.\n const predicate = generateFast(\n { ...ir, coerce: false },\n createFastGen(value, g.ctx, true, g.scope),\n );\n if (predicate === null) return null;\n\n const assign = `${value}=${conversion};`;\n const code = ir.type === \"boolean\" ? assign : `try{${assign}}catch(_){return ${g.fail};}`;\n return {\n code: code + (predicate === \"true\" ? \"\" : `if(!(${predicate}))return ${g.fail};`),\n value,\n };\n}\n\n/**\n * `.default(v)`: `undefined` yields the declared value without running the\n * inner schema, anything else parses normally — the same two branches\n * `slowDefault` emits, reading the value off the retained schema so a\n * reference-typed default keeps zod's identity (one shared object, not a copy).\n *\n * The substituted value is not validated, so it makes the fast path a PARTIAL\n * predicate (`fc(undefined)` is false where the schema accepts) — which is why\n * this records {@link CodeGenContext.buildSubstitutesValue}, on which\n * `generateValidator` withholds `.is()`.\n */\nfunction buildDefault(\n ir: SchemaIR & { type: \"default\" },\n input: string,\n g: BuildGen,\n): Built | null {\n const inner = build(ir.inner, input, g);\n if (inner === null) return null;\n // Every `default` node is in the rebuild set, so it is always BUILT and never\n // passed through — which makes this flag an exact record of whether the\n // finished pass substitutes a value.\n g.ctx.buildSubstitutesValue = true;\n const out = local(g, \"bq\");\n const value = defaultValueExpr(ir);\n // Zod re-applies the default when the inner returns undefined for a defined\n // input; only emitted when the inner can actually do that.\n const reapply = needsPostInnerDefault(ir) ? `if(${out}===undefined){${out}=${value};}` : \"\";\n return {\n code:\n `if(${input}===undefined){${out}=${value};}` +\n `else{${inner.code}${out}=${inner.value};${reapply}}`,\n value: out,\n };\n}\n\n/** `optional` / `nullable` around a rebuilding inner: pass the sentinel through. */\nfunction buildSentinel(\n innerIR: SchemaIR,\n input: string,\n g: BuildGen,\n test: string,\n sentinel: string,\n): Built | null {\n const inner = build(innerIR, input, g);\n if (inner === null) return null;\n const out = local(g, \"bw\");\n return {\n code: `if(${input}${test}){${out}=${sentinel};}else{${inner.code}${out}=${inner.value};}`,\n value: out,\n };\n}\n\n/** Allocate a `var` the hosted build function declares. */\nfunction local(g: BuildGen, prefix: string): string {\n const name = emitTemp(g.ctx, prefix);\n g.scope.temps.push(name);\n return name;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAgHA,SAAS,WAAW,MAAgB,oBAAoB,MAA6B;CACnF,MAAM,0BAAU,IAAI,IAAsB,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;CACrD,MAAM,QAAoB,CAAC;CAC3B,MAAM,uBAAO,IAAI,IAAc;CAC/B,MAAM,WAAW,SAAyB;EACxC,IAAI,KAAK,IAAI,IAAI,GAAG;EACpB,KAAK,IAAI,IAAI;EACb,MAAM,KAAK,IAAI;EACf,IAAI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OAAO,CAAC;CACtC,IAAI,UAAU,MAAM,OAAO;CAI3B,EAAE,IAAI,wBAAwB;CAC9B,MAAM,MAAM,MAAM,GAAG,IAAI;CACzB,MAAM,QAAQ,iBAAiB,EAAE;CAGjC,MAAM,UAAU,sBAAsB,EAAE,IAAI,MAAM,IAAI,gBAAgB,IAAI,GAAG,MAAM,MAAM;CACzF,OAAO;EACL,MACE,MAAM,MAAM,gBAAgB,IAAI,GAAG,MAAM,SACjC,MAAM,OAAO,IAAI,GAAG,MAAM,MAAM,GAAG,QAAQ;EACrD,OAAO;CACT;AACF;;AAGA,SAAS,cACP,SACA,OACA,GACA,MACA,UACc;CACd,MAAM,QAAQ,MAAM,SAAS,OAAO,CAAC;CACrC,IAAI,UAAU,MAAM,OAAO;CAC3B,MAAM,MAAM,MAAM,GAAG,IAAI;CACzB,OAAO;EACL,MAAM,MAAM,QAAQ,KAAK,IAAI,IAAI,GAAG,SAAS,SAAS,MAAM,OAAO,IAAI,GAAG,MAAM,MAAM;EACtF,OAAO;CACT;AACF;;AAGA,SAAS,MAAM,GAAa,QAAwB;CAClD,MAAM,OAAO,SAAS,EAAE,KAAK,MAAM;CACnC,EAAE,MAAM,MAAM,KAAK,IAAI;CACvB,OAAO;AACT"}
@@ -78,12 +78,54 @@ declare const ZC_HOP_DECL = "const __zcHop=Object.prototype.hasOwnProperty;";
78
78
  * than `Object.getPrototypeOf(o) === Object.prototype` is what lets a plain
79
79
  * object from another realm (a vm context, an iframe) still count as plain.
80
80
  *
81
+ * `c===Object` is a short-cut, not a fourth rule: it is exactly the case where
82
+ * zod's remaining steps are foregone — `Object.prototype` is an object and has
83
+ * its own `isPrototypeOf` — so the answer is `true` either way. It is also the
84
+ * case every ordinary record takes (an object literal, `JSON.parse` output, a
85
+ * `Map`-free DTO), and taking it saves the `prototype` load and the
86
+ * `hasOwnProperty` call: measured 9.6 → 5.7 ns on a monomorphic record and
87
+ * 15.7 → 9.2 ns across 16 shapes, i.e. 22% of a five-key record's whole parse.
88
+ * A plain object from another realm has a different `Object` and simply takes
89
+ * the long road to the same verdict, as before.
90
+ *
81
91
  * Self-contained (`Object.prototype.hasOwnProperty` spelled out rather than
82
92
  * reusing `__zcHop`) so inline mode can emit this decl alone: `emitRuntimeHelper`
83
93
  * pushes only the decl it is asked for, and a helper that closed over another
84
94
  * name would dangle wherever that one was not also emitted.
85
95
  */
86
96
  declare const ZC_PLAIN_DECL: string;
97
+ /**
98
+ * `z.email()`'s default validator, `regexes.email`, as a single linear scan.
99
+ *
100
+ * Zod's pattern is
101
+ * `^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$`,
102
+ * and even its lookahead-free rewrite (EMAIL_FAST_REGEX_SOURCE) backtracks at
103
+ * every dot it fails to find: `(?:[X]+\.)*` re-tries the run one character
104
+ * shorter each time, and the domain's `(?:label\.)+` does the same over the
105
+ * TLD. Written as a scanner the language is:
106
+ *
107
+ * local — `[A-Za-z0-9_'+.-]+`, no leading `.`, no `..`, and the character
108
+ * before `@` is neither `.` nor `'` (that last is the `[A-Za-z0-9_+-]`
109
+ * the pattern demands there);
110
+ * domain — one or more labels `[A-Za-z0-9][A-Za-z0-9-]*` each ending in `.`,
111
+ * then a TLD of two or more letters running to the end.
112
+ *
113
+ * A trailing `\n` is not accepted: the pattern has no `m` flag, so its `$`
114
+ * matches only at the end of input, and the scan reads to `length`.
115
+ *
116
+ * Measured against the fast regex on V8: 32 → 16 ns for `alice@example.com`,
117
+ * 48 → 40 for `bob_smith-99@mail-server.io`, 39 → 20 for a non-address, and a
118
+ * tie from ~35 characters up (the regex's per-character work is cheaper than a
119
+ * `charCodeAt` loop's; its fixed dispatch cost is what the scanner avoids). A
120
+ * lookbehind rewrite runs about as fast but needs ES2018 regex support, which
121
+ * the CLI's React Native / Hermes and older-Safari consumers cannot assume.
122
+ *
123
+ * Equivalence to zod's regex — every string, both verdicts — is pinned by
124
+ * tests/core/codegen/email-scanner.test.ts. Reached only behind a `typeof`
125
+ * string guard, like the `.test()` it replaces; issue sites keep reporting
126
+ * zod's own pattern string (see `emitRegexSourceString`).
127
+ */
128
+ declare const ZC_EMAIL_DECL: string;
87
129
  /**
88
130
  * Ports of `util.getLengthableOrigin` / `util.getSizableOrigin` — the `origin` a
89
131
  * length/size check puts on its issue, computed from the RUNTIME INPUT rather
@@ -229,5 +271,5 @@ declare const ZC_SR_DECL: string;
229
271
  /** Non-issue runtime helper declarations hosted in the virtual module. */
230
272
  declare const RUNTIME_HELPER_DECLS: Readonly<Record<string, string>>;
231
273
  //#endregion
232
- export { ISSUE_DECLS, RUNTIME_HELPER_DECLS, ZC_AB_DECL, ZC_CPL_DECL, ZC_CUSTOM_OK_DECL, ZC_FSR_DECL, ZC_FZ_DECL, ZC_HOP_DECL, ZC_LENGTH_ORIGIN_DECL, ZC_PFX_DECL, ZC_PLAIN_DECL, ZC_PROTO_SCRUB_DECL, ZC_SIZE_ORIGIN_DECL, ZC_SR_DECL, ZC_SR_OK_DECL, ZC_SR_RUN_DECL, abortingCodeTest, propertyKeyTest };
274
+ export { ISSUE_DECLS, RUNTIME_HELPER_DECLS, ZC_AB_DECL, ZC_CPL_DECL, ZC_CUSTOM_OK_DECL, ZC_EMAIL_DECL, ZC_FSR_DECL, ZC_FZ_DECL, ZC_HOP_DECL, ZC_LENGTH_ORIGIN_DECL, ZC_PFX_DECL, ZC_PLAIN_DECL, ZC_PROTO_SCRUB_DECL, ZC_SIZE_ORIGIN_DECL, ZC_SR_DECL, ZC_SR_OK_DECL, ZC_SR_RUN_DECL, abortingCodeTest, propertyKeyTest };
233
275
  //# sourceMappingURL=issue-decls.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"issue-decls.d.ts","names":[],"sources":["../../../src/core/codegen/issue-decls.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAkGa,aAAa,SAAS;;;;;;;;;;;;;cA0BtB;;;;;;;;;;cAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA8BA;;;;;;;;;;;;;;;;;;cAuBA;;;;;;;;;;;;;;;;;cAmBA;;;;;;;;cAWA;cAGA;;iBA+BG,iBAAiB;;;;;;;;;;;;;;;cAkBpB;;;;;;;;;;;;;;;;;cAkBA;;;;;;;;;cAaA;;iBAIG,gBAAgB;;;;;;;;;;;;;;;;cAmBnB;;;;;;;;;;;;;cAgBA;;;;;;cASA;;;;;;;;;;;;;;;;;;cAqBA;;cASA,sBAAsB,SAAS"}
1
+ {"version":3,"file":"issue-decls.d.ts","names":[],"sources":["../../../src/core/codegen/issue-decls.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAkGa,aAAa,SAAS;;;;;;;;;;;;;cA0BtB;;;;;;;;;;cAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAwCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAqCA;;;;;;;;;;;;;;;;;;cAkCA;;;;;;;;;;;;;;;;;cAmBA;;;;;;;;cAWA;cAGA;;iBA+BG,iBAAiB;;;;;;;;;;;;;;;cAkBpB;;;;;;;;;;;;;;;;;cAkBA;;;;;;;;;cAaA;;iBAIG,gBAAgB;;;;;;;;;;;;;;;;cAmBnB;;;;;;;;;;;;;cAgBA;;;;;;cASA;;;;;;;;;;;;;;;;;;cAqBA;;cASA,sBAAsB,SAAS"}
@@ -58,12 +58,54 @@ const ZC_HOP_DECL = "const __zcHop=Object.prototype.hasOwnProperty;";
58
58
  * than `Object.getPrototypeOf(o) === Object.prototype` is what lets a plain
59
59
  * object from another realm (a vm context, an iframe) still count as plain.
60
60
  *
61
+ * `c===Object` is a short-cut, not a fourth rule: it is exactly the case where
62
+ * zod's remaining steps are foregone — `Object.prototype` is an object and has
63
+ * its own `isPrototypeOf` — so the answer is `true` either way. It is also the
64
+ * case every ordinary record takes (an object literal, `JSON.parse` output, a
65
+ * `Map`-free DTO), and taking it saves the `prototype` load and the
66
+ * `hasOwnProperty` call: measured 9.6 → 5.7 ns on a monomorphic record and
67
+ * 15.7 → 9.2 ns across 16 shapes, i.e. 22% of a five-key record's whole parse.
68
+ * A plain object from another realm has a different `Object` and simply takes
69
+ * the long road to the same verdict, as before.
70
+ *
61
71
  * Self-contained (`Object.prototype.hasOwnProperty` spelled out rather than
62
72
  * reusing `__zcHop`) so inline mode can emit this decl alone: `emitRuntimeHelper`
63
73
  * pushes only the decl it is asked for, and a helper that closed over another
64
74
  * name would dangle wherever that one was not also emitted.
65
75
  */
66
- const ZC_PLAIN_DECL = "function __zcPlain(o){if(typeof o!==\"object\"||o===null||Array.isArray(o))return false;var c=o.constructor;if(c===undefined||typeof c!==\"function\")return true;var p=c.prototype;if(typeof p!==\"object\"||p===null||Array.isArray(p))return false;return Object.prototype.hasOwnProperty.call(p,\"isPrototypeOf\");}";
76
+ const ZC_PLAIN_DECL = "function __zcPlain(o){if(typeof o!==\"object\"||o===null||Array.isArray(o))return false;var c=o.constructor;if(c===Object||c===undefined||typeof c!==\"function\")return true;var p=c.prototype;if(typeof p!==\"object\"||p===null||Array.isArray(p))return false;return Object.prototype.hasOwnProperty.call(p,\"isPrototypeOf\");}";
77
+ /**
78
+ * `z.email()`'s default validator, `regexes.email`, as a single linear scan.
79
+ *
80
+ * Zod's pattern is
81
+ * `^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$`,
82
+ * and even its lookahead-free rewrite (EMAIL_FAST_REGEX_SOURCE) backtracks at
83
+ * every dot it fails to find: `(?:[X]+\.)*` re-tries the run one character
84
+ * shorter each time, and the domain's `(?:label\.)+` does the same over the
85
+ * TLD. Written as a scanner the language is:
86
+ *
87
+ * local — `[A-Za-z0-9_'+.-]+`, no leading `.`, no `..`, and the character
88
+ * before `@` is neither `.` nor `'` (that last is the `[A-Za-z0-9_+-]`
89
+ * the pattern demands there);
90
+ * domain — one or more labels `[A-Za-z0-9][A-Za-z0-9-]*` each ending in `.`,
91
+ * then a TLD of two or more letters running to the end.
92
+ *
93
+ * A trailing `\n` is not accepted: the pattern has no `m` flag, so its `$`
94
+ * matches only at the end of input, and the scan reads to `length`.
95
+ *
96
+ * Measured against the fast regex on V8: 32 → 16 ns for `alice@example.com`,
97
+ * 48 → 40 for `bob_smith-99@mail-server.io`, 39 → 20 for a non-address, and a
98
+ * tie from ~35 characters up (the regex's per-character work is cheaper than a
99
+ * `charCodeAt` loop's; its fixed dispatch cost is what the scanner avoids). A
100
+ * lookbehind rewrite runs about as fast but needs ES2018 regex support, which
101
+ * the CLI's React Native / Hermes and older-Safari consumers cannot assume.
102
+ *
103
+ * Equivalence to zod's regex — every string, both verdicts — is pinned by
104
+ * tests/core/codegen/email-scanner.test.ts. Reached only behind a `typeof`
105
+ * string guard, like the `.test()` it replaces; issue sites keep reporting
106
+ * zod's own pattern string (see `emitRegexSourceString`).
107
+ */
108
+ const ZC_EMAIL_DECL = "function __zcEmail(s){var n=s.length,i=0,c,p=46;for(;;){if(i===n)return false;c=s.charCodeAt(i);if(c===64)break;if(c===46){if(p===46)return false;}else if(!((c>=97&&c<=122)||(c>=65&&c<=90)||(c>=48&&c<=57)||c===95||c===39||c===43||c===45))return false;p=c;i++;}if(p===46||p===39)return false;var l=++i,d=0,t=true;for(;i<n;i++){c=s.charCodeAt(i);if((c>=97&&c<=122)||(c>=65&&c<=90))continue;if(c===46){if(i===l)return false;d++;l=i+1;t=true;continue;}if((c>=48&&c<=57)||c===45){if(c===45&&i===l)return false;t=false;continue;}return false;}return d>0&&t&&n-l>=2;}";
67
109
  /**
68
110
  * Ports of `util.getLengthableOrigin` / `util.getSizableOrigin` — the `origin` a
69
111
  * length/size check puts on its issue, computed from the RUNTIME INPUT rather
@@ -244,6 +286,7 @@ const RUNTIME_HELPER_DECLS = {
244
286
  __zcLo: ZC_LENGTH_ORIGIN_DECL,
245
287
  __zcSo: ZC_SIZE_ORIGIN_DECL,
246
288
  __zcCpl: ZC_CPL_DECL,
289
+ __zcEmail: ZC_EMAIL_DECL,
247
290
  __zcPs: ZC_PROTO_SCRUB_DECL,
248
291
  __zcPlain: ZC_PLAIN_DECL,
249
292
  __zcPfx: ZC_PFX_DECL,
@@ -252,6 +295,6 @@ const RUNTIME_HELPER_DECLS = {
252
295
  __zcSrOk: ZC_SR_OK_DECL
253
296
  };
254
297
  //#endregion
255
- export { ISSUE_DECLS, RUNTIME_HELPER_DECLS, ZC_AB_DECL, ZC_CPL_DECL, ZC_CUSTOM_OK_DECL, ZC_FSR_DECL, ZC_FZ_DECL, ZC_HOP_DECL, ZC_LENGTH_ORIGIN_DECL, ZC_PFX_DECL, ZC_PLAIN_DECL, ZC_PROTO_SCRUB_DECL, ZC_SIZE_ORIGIN_DECL, ZC_SR_DECL, ZC_SR_OK_DECL, ZC_SR_RUN_DECL, abortingCodeTest, propertyKeyTest };
298
+ export { ISSUE_DECLS, RUNTIME_HELPER_DECLS, ZC_AB_DECL, ZC_CPL_DECL, ZC_CUSTOM_OK_DECL, ZC_EMAIL_DECL, ZC_FSR_DECL, ZC_FZ_DECL, ZC_HOP_DECL, ZC_LENGTH_ORIGIN_DECL, ZC_PFX_DECL, ZC_PLAIN_DECL, ZC_PROTO_SCRUB_DECL, ZC_SIZE_ORIGIN_DECL, ZC_SR_DECL, ZC_SR_OK_DECL, ZC_SR_RUN_DECL, abortingCodeTest, propertyKeyTest };
256
299
 
257
300
  //# sourceMappingURL=issue-decls.js.map