zod-compiler 1.28.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +59 -53
  2. package/dist/core/codegen/build-path.d.ts +12 -1
  3. package/dist/core/codegen/build-path.d.ts.map +1 -1
  4. package/dist/core/codegen/build-path.js +47 -9
  5. package/dist/core/codegen/build-path.js.map +1 -1
  6. package/dist/core/codegen/context.d.ts +31 -16
  7. package/dist/core/codegen/context.d.ts.map +1 -1
  8. package/dist/core/codegen/context.js +43 -18
  9. package/dist/core/codegen/context.js.map +1 -1
  10. package/dist/core/codegen/emit-issue.d.ts +17 -20
  11. package/dist/core/codegen/emit-issue.d.ts.map +1 -1
  12. package/dist/core/codegen/emit-issue.js +13 -13
  13. package/dist/core/codegen/emit-issue.js.map +1 -1
  14. package/dist/core/codegen/index.d.ts.map +1 -1
  15. package/dist/core/codegen/index.js +9 -7
  16. package/dist/core/codegen/index.js.map +1 -1
  17. package/dist/core/codegen/issue-decls.d.ts +41 -7
  18. package/dist/core/codegen/issue-decls.d.ts.map +1 -1
  19. package/dist/core/codegen/issue-decls.js +49 -9
  20. package/dist/core/codegen/issue-decls.js.map +1 -1
  21. package/dist/core/codegen/schemas/array.js +1 -1
  22. package/dist/core/codegen/schemas/array.js.map +1 -1
  23. package/dist/core/codegen/schemas/bigint.d.ts.map +1 -1
  24. package/dist/core/codegen/schemas/bigint.js +15 -4
  25. package/dist/core/codegen/schemas/bigint.js.map +1 -1
  26. package/dist/core/codegen/schemas/catch.d.ts.map +1 -1
  27. package/dist/core/codegen/schemas/catch.js +3 -2
  28. package/dist/core/codegen/schemas/catch.js.map +1 -1
  29. package/dist/core/codegen/schemas/discriminated-union.d.ts.map +1 -1
  30. package/dist/core/codegen/schemas/discriminated-union.js +2 -1
  31. package/dist/core/codegen/schemas/discriminated-union.js.map +1 -1
  32. package/dist/core/codegen/schemas/effect.d.ts.map +1 -1
  33. package/dist/core/codegen/schemas/effect.js +4 -2
  34. package/dist/core/codegen/schemas/effect.js.map +1 -1
  35. package/dist/core/codegen/schemas/file.js +2 -8
  36. package/dist/core/codegen/schemas/file.js.map +1 -1
  37. package/dist/core/codegen/schemas/number.js +4 -3
  38. package/dist/core/codegen/schemas/number.js.map +1 -1
  39. package/dist/core/codegen/schemas/object.d.ts +11 -1
  40. package/dist/core/codegen/schemas/object.d.ts.map +1 -1
  41. package/dist/core/codegen/schemas/object.js +58 -14
  42. package/dist/core/codegen/schemas/object.js.map +1 -1
  43. package/dist/core/codegen/schemas/readonly.d.ts.map +1 -1
  44. package/dist/core/codegen/schemas/readonly.js.map +1 -1
  45. package/dist/core/codegen/schemas/record.d.ts.map +1 -1
  46. package/dist/core/codegen/schemas/record.js +8 -3
  47. package/dist/core/codegen/schemas/record.js.map +1 -1
  48. package/dist/core/codegen/schemas/sizeable.d.ts +49 -3
  49. package/dist/core/codegen/schemas/sizeable.d.ts.map +1 -1
  50. package/dist/core/codegen/schemas/sizeable.js +101 -8
  51. package/dist/core/codegen/schemas/sizeable.js.map +1 -1
  52. package/dist/core/codegen/schemas/string.d.ts.map +1 -1
  53. package/dist/core/codegen/schemas/string.js +45 -16
  54. package/dist/core/codegen/schemas/string.js.map +1 -1
  55. package/dist/core/codegen/schemas/tuple.d.ts +14 -11
  56. package/dist/core/codegen/schemas/tuple.d.ts.map +1 -1
  57. package/dist/core/codegen/schemas/tuple.js +99 -49
  58. package/dist/core/codegen/schemas/tuple.js.map +1 -1
  59. package/dist/core/codegen/well-known-regex.d.ts +7 -0
  60. package/dist/core/codegen/well-known-regex.d.ts.map +1 -1
  61. package/dist/core/codegen/well-known-regex.js +10 -3
  62. package/dist/core/codegen/well-known-regex.js.map +1 -1
  63. package/dist/core/extract/checks.d.ts.map +1 -1
  64. package/dist/core/extract/checks.js +1 -0
  65. package/dist/core/extract/checks.js.map +1 -1
  66. package/dist/core/extract/extractors/intersection.js +21 -6
  67. package/dist/core/extract/extractors/intersection.js.map +1 -1
  68. package/dist/core/extract/extractors/object.d.ts.map +1 -1
  69. package/dist/core/extract/extractors/object.js +25 -9
  70. package/dist/core/extract/extractors/object.js.map +1 -1
  71. package/dist/core/extract/extractors/optional.d.ts.map +1 -1
  72. package/dist/core/extract/extractors/optional.js +1 -28
  73. package/dist/core/extract/extractors/optional.js.map +1 -1
  74. package/dist/core/extract/extractors/record.js +9 -3
  75. package/dist/core/extract/extractors/record.js.map +1 -1
  76. package/dist/core/extract/extractors/tuple.d.ts.map +1 -1
  77. package/dist/core/extract/extractors/tuple.js +16 -20
  78. package/dist/core/extract/extractors/tuple.js.map +1 -1
  79. package/dist/core/extract/types.d.ts +16 -8
  80. package/dist/core/extract/types.d.ts.map +1 -1
  81. package/dist/core/iife.d.ts +2 -1
  82. package/dist/core/iife.d.ts.map +1 -1
  83. package/dist/core/iife.js +2 -1
  84. package/dist/core/iife.js.map +1 -1
  85. package/dist/core/types.d.ts +70 -21
  86. package/dist/core/types.d.ts.map +1 -1
  87. package/dist/jit.d.ts.map +1 -1
  88. package/dist/jit.js +47 -12
  89. package/dist/jit.js.map +1 -1
  90. package/dist/runtime.d.ts +3 -1
  91. package/dist/runtime.js +12 -10
  92. package/package.json +2 -2
@@ -1,31 +1,27 @@
1
1
  //#region src/core/extract/extractors/tuple.ts
2
2
  /**
3
- * Port of `$ZodTuple`'s own `optStart` computation, run against the LIVE item
4
- * schemas:
5
- *
6
- * ```js
7
- * const reversedIndex = [...items].reverse().findIndex((i) => i._zod.optin !== "optional");
8
- * const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;
9
- * ```
10
- *
11
- * i.e. the start of the trailing run of optional-in items (0 when every item is
12
- * optional-in). See {@link TupleIR.optStart} for why this is read from the zod
3
+ * Port of `$ZodTuple`'s `getTupleOptStart`, run against the LIVE item schemas:
4
+ * the index after the last item that fails `omittable`, or 0 when every item
5
+ * passes it. See {@link TupleIR.optStart} for why this is read from the zod
13
6
  * schema rather than inferred from the extracted IR.
14
7
  */
15
- function computeOptStart(items) {
16
- let start = items.length;
17
- for (let i = items.length - 1; i >= 0; i--) {
18
- if (items[i]?._zod?.optin !== "optional") break;
19
- start--;
20
- }
21
- return start;
8
+ function optStart(items, omittable) {
9
+ for (let i = items.length - 1; i >= 0; i--) if (!omittable(items[i]._zod)) return i + 1;
10
+ return 0;
22
11
  }
23
12
  function extractTuple(def, ctx) {
13
+ const items = def.items.map((item, i) => ctx.visit(item, `._zod.def.items[${i}]`));
14
+ const rest = def.rest ? ctx.visit(def.rest, "._zod.def.rest") : null;
15
+ const optinStart = optStart(def.items, (z) => z.optin !== void 0);
16
+ const optoutStart = optStart(def.items, (z) => z.optout === "optional");
17
+ const optionalIn = def.items.flatMap((item, i) => item._zod.optin === "optional" ? [i] : []);
24
18
  return {
25
19
  type: "tuple",
26
- items: def.items.map((item, i) => ctx.visit(item, `._zod.def.items[${i}]`)),
27
- rest: def.rest ? ctx.visit(def.rest, "._zod.def.rest") : null,
28
- optStart: computeOptStart(def.items)
20
+ items,
21
+ rest,
22
+ optStart: optinStart,
23
+ ...optoutStart < def.items.length ? { optoutStart } : {},
24
+ ...optionalIn.length > 0 ? { optionalIn } : {}
29
25
  };
30
26
  }
31
27
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"tuple.js","names":[],"sources":["../../../../src/core/extract/extractors/tuple.ts"],"sourcesContent":["import type { SchemaIR } from \"../../types.js\";\nimport type { ExtractorContext, ZodDef, ZodSchema } from \"../types.js\";\n\n/**\n * Port of `$ZodTuple`'s own `optStart` computation, run against the LIVE item\n * schemas:\n *\n * ```js\n * const reversedIndex = [...items].reverse().findIndex((i) => i._zod.optin !== \"optional\");\n * const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;\n * ```\n *\n * i.e. the start of the trailing run of optional-in items (0 when every item is\n * optional-in). See {@link TupleIR.optStart} for why this is read from the zod\n * schema rather than inferred from the extracted IR.\n */\nfunction computeOptStart(items: unknown[]): number {\n let start = items.length;\n for (let i = items.length - 1; i >= 0; i--) {\n if ((items[i] as ZodSchema | undefined)?._zod?.optin !== \"optional\") break;\n start--;\n }\n return start;\n}\n\nexport function extractTuple(def: ZodDef, ctx: ExtractorContext): SchemaIR {\n const items = def.items.map((item, i) => ctx.visit(item, `._zod.def.items[${i}]`));\n const rest = def.rest ? ctx.visit(def.rest, \"._zod.def.rest\") : null;\n return { type: \"tuple\", items, rest, optStart: computeOptStart(def.items) };\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,SAAS,gBAAgB,OAA0B;CACjD,IAAI,QAAQ,MAAM;CAClB,KAAK,IAAI,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK;EAC1C,IAAK,MAAM,EAAE,EAA4B,MAAM,UAAU,YAAY;EACrE;CACF;CACA,OAAO;AACT;AAEA,SAAgB,aAAa,KAAa,KAAiC;CAGzE,OAAO;EAAE,MAAM;EAAS,OAFV,IAAI,MAAM,KAAK,MAAM,MAAM,IAAI,MAAM,MAAM,mBAAmB,EAAE,EAAE,CAEpD;EAAG,MADlB,IAAI,OAAO,IAAI,MAAM,IAAI,MAAM,gBAAgB,IAAI;EAC3B,UAAU,gBAAgB,IAAI,KAAK;CAAE;AAC5E"}
1
+ {"version":3,"file":"tuple.js","names":[],"sources":["../../../../src/core/extract/extractors/tuple.ts"],"sourcesContent":["import type { SchemaIR } from \"../../types.js\";\nimport type { ExtractorContext, ZodDef, ZodSchema } from \"../types.js\";\n\n/**\n * Port of `$ZodTuple`'s `getTupleOptStart`, run against the LIVE item schemas:\n * the index after the last item that fails `omittable`, or 0 when every item\n * passes it. See {@link TupleIR.optStart} for why this is read from the zod\n * schema rather than inferred from the extracted IR.\n */\nfunction optStart(items: unknown[], omittable: (item: ZodSchema[\"_zod\"]) => boolean): number {\n for (let i = items.length - 1; i >= 0; i--) {\n if (!omittable((items[i] as ZodSchema)._zod)) return i + 1;\n }\n return 0;\n}\n\nexport function extractTuple(def: ZodDef, ctx: ExtractorContext): SchemaIR {\n const items = def.items.map((item, i) => ctx.visit(item, `._zod.def.items[${i}]`));\n const rest = def.rest ? ctx.visit(def.rest, \"._zod.def.rest\") : null;\n // optin is a three-rung ladder, so any rung above `undefined` permits an\n // absent slot; optout stays two-valued.\n const optinStart = optStart(def.items, (z) => z.optin !== undefined);\n const optoutStart = optStart(def.items, (z) => z.optout === \"optional\");\n const optionalIn = def.items.flatMap((item, i) =>\n (item as ZodSchema)._zod.optin === \"optional\" ? [i] : [],\n );\n return {\n type: \"tuple\",\n items,\n rest,\n optStart: optinStart,\n ...(optoutStart < def.items.length ? { optoutStart } : {}),\n ...(optionalIn.length > 0 ? { optionalIn } : {}),\n };\n}\n"],"mappings":";;;;;;;AASA,SAAS,SAAS,OAAkB,WAAyD;CAC3F,KAAK,IAAI,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KACrC,IAAI,CAAC,UAAW,MAAM,EAAE,CAAe,IAAI,GAAG,OAAO,IAAI;CAE3D,OAAO;AACT;AAEA,SAAgB,aAAa,KAAa,KAAiC;CACzE,MAAM,QAAQ,IAAI,MAAM,KAAK,MAAM,MAAM,IAAI,MAAM,MAAM,mBAAmB,EAAE,EAAE,CAAC;CACjF,MAAM,OAAO,IAAI,OAAO,IAAI,MAAM,IAAI,MAAM,gBAAgB,IAAI;CAGhE,MAAM,aAAa,SAAS,IAAI,QAAQ,MAAM,EAAE,UAAU,KAAA,CAAS;CACnE,MAAM,cAAc,SAAS,IAAI,QAAQ,MAAM,EAAE,WAAW,UAAU;CACtE,MAAM,aAAa,IAAI,MAAM,SAAS,MAAM,MACzC,KAAmB,KAAK,UAAU,aAAa,CAAC,CAAC,IAAI,CAAC,CACzD;CACA,OAAO;EACL,MAAM;EACN;EACA;EACA,UAAU;EACV,GAAI,cAAc,IAAI,MAAM,SAAS,EAAE,YAAY,IAAI,CAAC;EACxD,GAAI,WAAW,SAAS,IAAI,EAAE,WAAW,IAAI,CAAC;CAChD;AACF"}
@@ -77,6 +77,10 @@ interface ZodDef {
77
77
  rest: ZodSchema | null;
78
78
  keyType: ZodSchema;
79
79
  valueType: ZodSchema;
80
+ /** `z.partialRecord()`: the key schema's values are not required to be present. */
81
+ partial?: boolean;
82
+ /** `z.looseRecord()`: an unrecognized key is copied through, not reported. */
83
+ mode?: "loose" | undefined;
80
84
  left: ZodSchema;
81
85
  right: ZodSchema;
82
86
  discriminator: string;
@@ -109,16 +113,20 @@ interface ZodSchema {
109
113
  /** Class trait names from zod's $constructor (e.g. "$ZodExactOptional"). */
110
114
  traits?: Set<string>;
111
115
  /** "optional" when the key may be absent in object output (zod optout). */
112
- optout?: string;
116
+ optout?: "optional" | undefined;
113
117
  /**
114
- * "optional" when the schema ACCEPTS an absent/undefined input — zod's
115
- * `optin`. Set outright by `z.optional()`, `z.exactOptional()`,
116
- * `z.undefined()`, `.default()` and `.prefault()`, and propagated by
117
- * `.nullable()`, `.readonly()`, `.nonoptional()`, `z.lazy()`, a pipe (from
118
- * its `in`) and a union (when ANY option has it). Drives which tuple items
119
- * may be omitted and which branch `$ZodOptional` takes.
118
+ * zod's `optin`, a three-rung ladder: `undefined` (the slot must be
119
+ * present), `"optional"` (absence permitted, nothing supplied in its place
120
+ * — `z.optional()`, `z.exactOptional()`, `.catch()` over a plain schema)
121
+ * and `"defaulted"` (absence permitted, a value substituted — `.default()`,
122
+ * `.prefault()`, and `.optional()`/`.catch()` over one of those).
123
+ * Propagated by `.nullable()`, `.readonly()`, `z.lazy()`, a pipe (from its
124
+ * `in`) and a union (the highest rung any option reaches). `z.undefined()`,
125
+ * `z.any()` and `.nonoptional()` sit on the bottom rung. Drives which tuple
126
+ * items may be omitted, how an absent object key is treated and whether
127
+ * `$ZodOptional` short-circuits `undefined`.
120
128
  */
121
- optin?: string;
129
+ optin?: "optional" | "defaulted" | undefined;
122
130
  /** Discriminator dispatch values per property key (discriminated unions). */
123
131
  propValues?: Record<string, Set<unknown> | undefined>;
124
132
  };
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/core/extract/types.ts"],"mappings":";;UAEiB;EACf;EACA;EACA;EACA,SAAS;EACT;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;;EAEA,WAAW;EACX,WAAW;EACX;EACA;;UAGe;EACf;IACE,KAAK;;;;;;IAML;;;UAIa;EACf;;EAEA;;EAEA;;EAEA;EACA,QAAQ;EACR;EACA;EACA,SAAS;;EAET;;EAEA,WAAW;EACX,OAAO,eAAe;EACtB,SAAS;EACT,SAAS;EACT,WAAW;;;;;;EAMX,QAAQ;EACR,SAAS;EACT,IAAI;EACJ,KAAK;EACL,OAAO;EACP,MAAM;EACN,SAAS;EACT,WAAW;EACX,MAAM;EACN,OAAO;EACP;;;;;;EAMA;;EAEA;EACA;EACA;EACA,cAAc;;EAEd;;EAEA;;UAGe;EACf;IACE,KAAK;IACL,MAAM;;IAEN,YAAY;;IAEZ,UAAU;;IAEV,SAAS;;IAET,SAAS;;IAET;;;;;;;;;IASA;;IAEA,aAAa,eAAe;;;;UAKf;;EAEf;;EAEA;;;KAMU;;;;;;;;;;UA8CK;;WAEN;;WAEA,SAAS;;EAElB;;;UAMe;;WAEN;;WAEA;;WAEA,MAAM;;WAEN,UAAU;;WAEV,WAAW;;EAGpB,MAAM,sBAAsB,sBAHR;;EAMpB,SAAS,QAH+D,uBAGjC;;;KAI7B,aAAa,KAAK,QAAQ,KAAK,qBAAA"}
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/core/extract/types.ts"],"mappings":";;UAEiB;EACf;EACA;EACA;EACA,SAAS;EACT;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;EACA;;EAEA,WAAW;EACX,WAAW;EACX;EACA;;UAGe;EACf;IACE,KAAK;;;;;;IAML;;;UAIa;EACf;;EAEA;;EAEA;;EAEA;EACA,QAAQ;EACR;EACA;EACA,SAAS;;EAET;;EAEA,WAAW;EACX,OAAO,eAAe;EACtB,SAAS;EACT,SAAS;EACT,WAAW;;;;;;EAMX,QAAQ;EACR,SAAS;EACT,IAAI;EACJ,KAAK;EACL,OAAO;EACP,MAAM;EACN,SAAS;EACT,WAAW;;EAEX;;EAEA;EACA,MAAM;EACN,OAAO;EACP;;;;;;EAMA;;EAEA;EACA;EACA;EACA,cAAc;;EAEd;;EAEA;;UAGe;EACf;IACE,KAAK;IACL,MAAM;;IAEN,YAAY;;IAEZ,UAAU;;IAEV,SAAS;;IAET,SAAS;;IAET;;;;;;;;;;;;;IAaA;;IAEA,aAAa,eAAe;;;;UAKf;;EAEf;;EAEA;;;KAMU;;;;;;;;;;UA8CK;;WAEN;;WAEA,SAAS;;EAElB;;;UAMe;;WAEN;;WAEA;;WAEA,MAAM;;WAEN,UAAU;;WAEV,WAAW;;EAGpB,MAAM,sBAAsB,sBAHR;;EAMpB,SAAS,QAH+D,uBAGjC;;;KAI7B,aAAa,KAAK,QAAQ,KAAK,qBAAA"}
@@ -222,7 +222,8 @@ declare const MK_VALIDATOR_DECL: string;
222
222
  * descriptor, so ONE `.shape` read fires ALL of an object's recursion getters).
223
223
  * Binding `__zs` itself does not: constructing the schema leaves deferred
224
224
  * callbacks unforced, and `usesRetainedSchema`'s only read is `__zs.safeParse`,
225
- * an own property zod assigns during `ZodType.init`.
225
+ * a prototype getter that binds the method and installs the bound copy on the
226
+ * instance without touching the schema's structure.
226
227
  *
227
228
  * The distinction decides whether the IIFE may be evaluated inside the
228
229
  * INITIALIZER of the binding the schema's own deferred callbacks close over —
@@ -1 +1 @@
1
- {"version":3,"file":"iife.d.ts","names":[],"sources":["../../src/core/iife.ts"],"mappings":";;;;;;;;cAca;;;;;;;;;;;;;;;;;;;;cAsBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA8CA;;;cAUA;;;;;;;;;;;;;;;;;;;;;;;cAyBA;;;;;;;;;;;;;;;;;;;;;;;;;;cA2BA;;cAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA6FA;;;;;;;;;;;;;;;;iBA4BG,iBAAiB,QAAQ;;;;;;;;;;;;;iBAgBzB,aACd,oBACA,QAAQ,oBACR;EAAY;EAAiC"}
1
+ {"version":3,"file":"iife.d.ts","names":[],"sources":["../../src/core/iife.ts"],"mappings":";;;;;;;;cAca;;;;;;;;;;;;;;;;;;;;cAsBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA8CA;;;cAUA;;;;;;;;;;;;;;;;;;;;;;;cAyBA;;;;;;;;;;;;;;;;;;;;;;;;;;cA2BA;;cAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA6FA;;;;;;;;;;;;;;;;;iBA6BG,iBAAiB,QAAQ;;;;;;;;;;;;;iBAgBzB,aACd,oBACA,QAAQ,oBACR;EAAY;EAAiC"}
package/dist/core/iife.js CHANGED
@@ -231,7 +231,8 @@ function extractFunctionName(functionDef) {
231
231
  * descriptor, so ONE `.shape` read fires ALL of an object's recursion getters).
232
232
  * Binding `__zs` itself does not: constructing the schema leaves deferred
233
233
  * callbacks unforced, and `usesRetainedSchema`'s only read is `__zs.safeParse`,
234
- * an own property zod assigns during `ZodType.init`.
234
+ * a prototype getter that binds the method and installs the bound copy on the
235
+ * instance without touching the schema's structure.
235
236
  *
236
237
  * The distinction decides whether the IIFE may be evaluated inside the
237
238
  * INITIALIZER of the binding the schema's own deferred callbacks close over —
@@ -1 +1 @@
1
- {"version":3,"file":"iife.js","names":[],"sources":["../../src/core/iife.ts"],"sourcesContent":["/**\n * Shared CompiledSchema<T> IIFE generation.\n * Used by both CLI emitter and unplugin transform.\n */\n\nimport { RETAINED_SCHEMA_VAR } from \"./codegen/context.js\";\nimport type { CompiledSchemaInfo } from \"./pipeline.js\";\n\n/**\n * Import statement required by generateIIFE output (references\n * __zodCompilerConfig). `core` is bound for $ZodAsyncError: superRefine and\n * custom callbacks may only reveal that they are async through the promise\n * they return, at which point zod's own synchronous parse raises.\n */\nexport const ZOD_CONFIG_IMPORT =\n 'import { config as __zodCompilerConfig, core as __zcCore, ZodRealError as __zcZodError } from \"zod\";';\n\n/**\n * File-level `__zcMsg` declaration (must appear once after ZOD_CONFIG_IMPORT):\n * the message an issue gets when nothing was baked into it at build time.\n *\n * Resolves zod's tail of `finalizeIssue` — `config.customError` then\n * `config.localeError` then \"Invalid input\" — and does it PER CALL, because the\n * config is mutable: `z.config({ localeError })` in an entry point runs after\n * the schema modules it imports, so a value snapshotted at module init misses\n * it. Reading a captured `localeError` alone also dropped `customError`\n * outright, silently ignoring the global map most i18n setups install.\n *\n * The head of zod's chain — the schema's own `error` option — is baked into the\n * issue at build time and short-circuits this. The one link that cannot be\n * reproduced is a per-CALL `ctx.error`, which would have to travel through\n * `safeParse`; that entry point sits at V8's inlining budget, where even an\n * unused extra parameter measured ~12% on every parse.\n *\n * Only ever called while building an error, never on a successful parse.\n */\nexport const ZOD_MSG_DECLARATION =\n 'function __zcUw(m){return typeof m===\"string\"?m:(m===undefined||m===null?undefined:m.message);}' +\n \"var __zcMsg=function(iss){var c=__zodCompilerConfig(),m;\" +\n \"if(c.customError){m=__zcUw(c.customError(iss));if(m!==undefined&&m!==null)return m;}\" +\n \"if(c.localeError){m=__zcUw(c.localeError(iss));if(m!==undefined&&m!==null)return m;}\" +\n 'return \"Invalid input\";};';\n\n/**\n * Shared failure-result for __zcFin / __zcFinD. Inline mode (CLI emitter)\n * declares it once per compiled file; lean mode (all unplugin bundlers) declares\n * it once per bundle in the plugin-materialized runtime module (module-local —\n * generated code only ever references __zcFin/__zcFinD, never __ZcFail).\n *\n * Why a prototype getter and not `{success:false, get error(){...}}`: an object\n * literal with an inline accessor forces V8 down its slow accessor-defining\n * allocation path — ~110ns per failure, measured — which dominates the entire\n * invalid-input cost whenever callers never read `.error`. Hosting `error` on\n * the prototype turns each failure into a plain field-only instantiation (~2ns,\n * ~13x), with the lazy-cache semantics intact. (Trade-off: `error` is a\n * prototype accessor, so it no longer shows up in `Object.keys(result)` / spread\n * / JSON.stringify of the result wrapper — `.success`/`.error`/`.data` access,\n * destructuring, and `in` are unaffected.)\n *\n * One class serves both finalizers, so the instances share one hidden class:\n * __zcFin passes pre-collected issues in `_e` (with `_f===null`); __zcFinD\n * passes the hosted slow-walk in `_f` plus the input in `_i`, and the getter\n * runs the walk on first `.error` read. The whole finalization — locale fill\n * (__zcMsg applied ONLY when an issue carries no message, never overwriting a\n * baked-in custom/fallback message), input strip, and ZodError construction\n * (zod v4 JSON.stringifies every issue into `message` and captures a stack\n * trace) — stays deferred inside the cached accessor exactly as before, since\n * the issues array is observable solely through `.error`.\n *\n * `input` is `delete`d, not assigned `undefined`. Key PRESENCE is observable —\n * `\"input\" in issue`, `Object.keys(issue)`, object spread, `toStrictEqual`\n * against a zod issue — and zod's `util.finalizeIssue` does `delete full.input`\n * whenever `reportInput` is off, so assignment left every compiled issue one\n * enumerable key wider than zod's. The delete's dictionary-mode transition is\n * affordable precisely BECAUSE of the deferral above: it runs only after a\n * caller asks for `.error` on a failed parse, and is memoised in `_c`. Neither\n * a successful parse nor a `.success`/`.is()` check on a rejected one reaches\n * it — measured, the two are unchanged, while the `.error` read itself goes\n * ~3.95us -> ~4.19us per failure, i.e. ~6% of a path whose cost is already\n * dominated by the ZodError construction on the next line (stack capture plus a\n * JSON.stringify of every issue).\n */\nexport const FAIL_CLASS_DECL =\n \"function __ZcFail(e,f,i){this.success=false;this._e=e;this._f=f;this._i=i;this._c=undefined;}\" +\n 'Object.defineProperty(__ZcFail.prototype,\"error\",{configurable:true,get:function(){' +\n \"if(this._c)return this._c;\" +\n \"var e=this._f!==null?this._f(this._i):this._e;\" +\n 'for(var i=0;i<e.length;i++){if(e[i].message===undefined&&typeof __zcMsg===\"function\")e[i].message=__zcMsg(e[i]);delete e[i].input;delete e[i].continue;}' +\n \"return this._c=new __zcZodError(e);}});\";\n\n/** Eager finalizer (mutation / partial-fast-path schemas): issues already\n * collected in `e`; success short-circuits to a plain result literal. */\nexport const FIN_DECL =\n \"function __zcFin(e,d){if(!e.length)return{success:true,data:d};return new __ZcFail(e,null,null);}\";\n\n/**\n * Deferred-collection finalizer for Fast-Path-eligible schemas. When the\n * fast check fails, the ENTIRE slow path (the issue-collecting re-walk) is\n * pushed into the cached `.error` accessor instead of running eagerly:\n * fast-eligible schemas never mutate, so the walk's only output is the\n * issues array, which is observable solely through `.error` — one step\n * further along the same lazy boundary `__zcFin` already established (locale\n * fill, input strip, ZodError construction). A failed safeParse whose\n * `.error` is never read costs the fast check alone.\n *\n * Takes the schema's HOSTED slow-walk function plus the input — NOT a\n * per-call closure: `__zcFinD(__sw_N, input)` allocates only the result\n * object, where `__zcFinD(function(){...})` paid a closure environment and\n * function object per failure. Hosting the walk also shrinks safeParse to\n * two statements, within V8's inlining budget (the success-path result\n * literal becomes escape-analyzable at monomorphic call sites).\n *\n * The walk re-reads `input` at `.error`-read time; a caller that mutates\n * the input between safeParse and reading `.error` sees issues for the\n * mutated value (zod materializes at parse time). Same caveat class as the\n * documented __zcFin deferral.\n */\nexport const FIN_DEFERRED_DECL = \"function __zcFinD(f,inp){return new __ZcFail(null,f,inp);}\";\n\n/**\n * Compact-mode failure class — a lazy failure that delegates error reporting to\n * the ORIGINAL Zod schema's `safeParse`. Used by `output: \"compact\"`, where the\n * compiled slow walk is dropped entirely: a mutation-free schema's fast check\n * is the only generated validation, and on a fast-check failure the cold error\n * path is produced by the retained Zod schema itself (`zod` is the source of\n * truth, so the issues are byte-identical — no second validation engine).\n *\n * `_z` is the schema's PRISTINE safeParse method, captured by\n * emitRetainedMethod (see context.ts), and `_r` is its receiver — the `__zs`\n * binding generateIIFE places above that capture. Both are read before the\n * trailing `__zcMkv` call installs anything, so the method is zod's own\n * implementation, never the compiled delegate, avoiding infinite recursion\n * without allocating a bound function. The zod parse is deferred until `.error`\n * is read and cached, so\n * the common `safeParse(x).success`/`.is(x)` checks on invalid input cost only\n * the fast check (zod never runs) — the same deferral boundary `__zcFinD`\n * establishes for the compiled slow walk. Sound because compact mode is gated\n * on a TOTAL fast path: `fc(input) === false` ⟹ zod rejects, so `success:false`\n * holds without consulting zod.\n *\n * The getter returns zod's OWN ZodError verbatim (no locale fill / input strip /\n * re-wrap — zod already finalized it), so a delegated failure is exactly what\n * the unaltered schema would have produced.\n */\nexport const FAILZ_CLASS_DECL =\n \"function __ZcFailZ(z,r,i){this.success=false;this._z=z;this._r=r;this._i=i;this._c=undefined;}\" +\n 'Object.defineProperty(__ZcFailZ.prototype,\"error\",{configurable:true,get:function(){' +\n \"return this._c||(this._c=this._z.call(this._r,this._i).error);}});\";\n\n/** Compact-mode finalizer: retain a pristine safeParse, its receiver, and input lazily. */\nexport const FINZ_DECL = \"function __zcFinZ(z,r,i){return new __ZcFailZ(z,r,i);}\";\n\n/**\n * Validator factory. Inline mode (CLI emitter) declares it once per compiled\n * file; lean mode (all unplugin bundlers) exports it once per bundle from the\n * plugin-materialized runtime module — generated code never imports it from\n * the zod-compiler package itself, so zod-compiler stays a devDependency and\n * the helper set is always version-locked to the codegen that calls it.\n * Wraps a safeParse function into the CompiledSchema interface.\n *\n * IDENTITY-PRESERVING: with zodCompat (schema != null) the compiled\n * parse/safeParse/parseAsync/safeParseAsync are installed as OWN properties\n * on the original schema object, which is returned as-is. zod v4 keys\n * several APIs on object identity — toJSONSchema's ctx.seen registers the\n * object it is handed while each processor closure captures the original\n * inst (a wrapper crashes `optionalProcessor` with \"Cannot set properties\n * of undefined (setting 'ref')\" the moment a compiled schema is composed\n * into another schema), and globalRegistry/.meta() is a WeakMap keyed by\n * the schema instance (a wrapper silently loses OpenAPI titles/ids). An\n * Object.create wrapper breaks both; mutating the original breaks neither\n * (zod's internal parsing flows through _zod.run, never the public\n * methods, and derived schemas — .optional(), .extend() — are fresh\n * instances that fall back to plain zod). schema=null (zodCompat: false)\n * still produces a plain method-bag object.\n *\n * fc is the schema's hosted fast-check boolean function (null when no Fast\n * Path exists). parse()/parseAsync() try it first and return the input\n * directly on success: fc is small enough for V8 to inline, so the hot parse\n * path runs with zero allocations — calling fn would allocate an intermediate\n * SafeParseResult that escape analysis cannot remove (fn never inlines).\n * Fast-path-eligible schemas never mutate, so fc(input) ⟹ data === input.\n *\n * is is the TOTAL fast-check predicate (fc when the fast path is total, else\n * null). Installed as `.is()` — a zero-allocation boolean type guard. When\n * null (partial fast path or none) `.is()` derives from fn(input).success: a\n * partial fc can pass-through valid input but its `false` does not imply\n * rejection (a default/catch may still succeed), so it would be unsound as a\n * standalone guard.\n *\n * parseAsync/safeParseAsync wrap the SYNC validator, which is right for every\n * schema the compiler can reproduce — none of them are async. It is wrong for\n * the ones it cannot: an `async` refinement or a `z.promise()` extracts to a\n * Zod delegate, and delegating means calling Zod's SYNCHRONOUS safeParse, which\n * raises `$ZodAsyncError` by design. Wrapping that gave the compiled schema an\n * async pair that rejected with `$ZodAsyncError` for EVERY input — including\n * valid ones — where Zod resolves normally, so `await UserSchema.parseAsync(x)`\n * stopped working the moment any part of the schema went async.\n *\n * So both are guarded: a synchronous throw hands off to the schema's ORIGINAL\n * async method, captured before these are installed — the same escape hatch\n * `~standard` already uses for its throw path, and for the same reason (the\n * compiled validator has no async mode to offer, and Zod's is exact). It also\n * fixes the smaller wart that a throwing `fn` made `parseAsync` throw\n * SYNCHRONOUSLY rather than return a rejected promise. With `zodCompat: false`\n * there is no schema to delegate to and the throw propagates as before.\n *\n * `~standard` is REPLACED, not merely preserved. Zod builds it lazily as\n * `validate: (v) => safeParse(inst, v)` — the core FUNCTION, which goes straight\n * to `inst._zod.run`. It never reads the schema's own `safeParse` property, so\n * installing the compiled one leaves this route entirely uncompiled: measured\n * 271.7 ns against the compiled 26.6 ns on the same schema, i.e. Standard Schema\n * consumers (tRPC, Hono, TanStack) were getting plain Zod.\n *\n * Zod's own `~standard` is never READ, only overwritten. Zod installs the slot\n * with `util.defineLazy` — commented there as \"avoid creating objects for every\n * schema\" — so it is an accessor that builds `{version, vendor, validate}` plus\n * its closure on first touch. Reading it to capture a fallback fired that getter\n * for every compiled schema while the module was still initializing.\n *\n * How much that costs depends on the entry point, and only one of them is free:\n * classic `zod` forces the slot itself during `ZodType.init` (it does\n * `Object.assign(inst[\"~standard\"], { jsonSchema })`), so there the read hit an\n * already-built object and cost only an accessor call. `zod/mini` and raw\n * `zod/v4/core` never touch it, so for those the read built — and retained — an\n * object and a closure per schema, purely to capture a fallback the schema will\n * most likely never expose to a Standard Schema consumer.\n *\n * The throw path is rebuilt instead of captured. Zod's validate catches a\n * synchronous throw and retries through `safeParseAsync` — that is how an async\n * refinement resolves and how a throwing check surfaces as a rejected promise\n * rather than a synchronous throw — so calling the already-captured `zspa` and\n * mapping its result is the same route to the same result. `vendor` is likewise\n * a constant: schema discovery only ever admits zod schemas, and classic, mini\n * and core all hardcode `vendor: \"zod\"` themselves.\n *\n * Not carried over (unchanged by this, and pre-dating it): classic's\n * `~standard.jsonSchema` extension, which the replacement object has never\n * reproduced.\n *\n * Installed with defineProperty rather than assignment: Zod's lazy setter\n * redefines the slot as non-writable, so a second `__zcMkv` on the same schema\n * object — two exports aliasing one schema — would throw under ESM strict mode.\n */\nexport const MK_VALIDATOR_DECL =\n \"function __zcMkv(fn,schema,fc,is){var w=schema||{};var zpa=w.parseAsync,zspa=w.safeParseAsync;w.parse=fc?function(input){if(fc(input))return input;var r=fn(input);if(r.success)return r.data;throw r.error;}:function(input){var r=fn(input);if(r.success)return r.data;throw r.error;};w.safeParse=fn;w.safeParseAsync=function(input){try{return Promise.resolve(fn(input));}catch(e){if(zspa)return zspa(input);throw e;}};w.parseAsync=fc?function(input){try{if(fc(input))return Promise.resolve(input);var r=fn(input);if(r.success)return Promise.resolve(r.data);return Promise.reject(r.error);}catch(e){if(zpa)return zpa(input);throw e;}}:function(input){try{var r=fn(input);if(r.success)return Promise.resolve(r.data);return Promise.reject(r.error);}catch(e){if(zpa)return zpa(input);throw e;}};w.is=is||function(input){return fn(input).success;};\" +\n 'Object.defineProperty(w,\"~standard\",{configurable:true,value:{version:1,vendor:\"zod\",validate:function(input){var r;try{if(fc&&fc(input))return{value:input};r=fn(input);}catch(e){if(zspa)return zspa(input).then(function(q){return q.success?{value:q.data}:{issues:q.error.issues};});throw e;}return r.success?{value:r.data}:{issues:r.error.issues};}}});' +\n \"return w;}\";\n\nfunction extractFunctionName(functionDef: string): string {\n const match = /^function\\s+(\\w+)\\s*\\(/.exec(functionDef);\n if (!match?.[1]) {\n throw new Error(\"Cannot extract function name from generated code\");\n }\n return match[1];\n}\n\n/**\n * Does the IIFE's preamble DEREFERENCE the retained schema at evaluation time?\n *\n * Only `__rf` does: every entry is `__zs<accessPath>`, and an access path walks\n * the schema's structure — `._zod.innerType` fires a `z.lazy()` getter,\n * `.shape` materializes a `z.object()` shape (zod v4 reads every property\n * descriptor, so ONE `.shape` read fires ALL of an object's recursion getters).\n * Binding `__zs` itself does not: constructing the schema leaves deferred\n * callbacks unforced, and `usesRetainedSchema`'s only read is `__zs.safeParse`,\n * an own property zod assigns during `ZodType.init`.\n *\n * The distinction decides whether the IIFE may be evaluated inside the\n * INITIALIZER of the binding the schema's own deferred callbacks close over —\n * see the self-referential path in the unplugin's autoDiscover rewrite.\n */\nexport function iifeDerefsSchema(schema: CompiledSchemaInfo): boolean {\n return schema.refEntries.length > 0;\n}\n\n/**\n * Generate a `/* @__PURE__ * /` IIFE wrapping a compiled validator.\n *\n * @param schemaExpr - Expression resolving to the original Zod schema\n * (e.g. `\"UserSchema\"` in unplugin, `\"(__src_X as any).schema\"` in CLI)\n * @param schema\n * @param options - `pure: false` drops the `/* @__PURE__ * /` annotation, for\n * the one caller that emits the IIFE as a STATEMENT following the\n * declaration rather than as its initializer: there the call's whole point is\n * its side effect (`__zcMkv` installing the compiled methods on the schema),\n * and a bundler that believed it pure would drop the compilation outright.\n */\nexport function generateIIFE(\n schemaExpr: string,\n schema: CompiledSchemaInfo,\n options?: { zodCompat?: boolean | undefined; pure?: boolean | undefined },\n): string {\n const { codegenResult, refEntries } = schema;\n const fnName = extractFunctionName(codegenResult.functionDef);\n const zodCompat = options?.zodCompat !== false;\n // Every fallback access starts from the same source schema, and compact\n // delegation names it outright. Capture it once whenever either needs it, so\n // an inline initializer is not reconstructed for each path and again for the\n // identity-preserving __zcMkv target.\n const bindsSchema = refEntries.length > 0 || codegenResult.usesRetainedSchema === true;\n const retainedSchema = bindsSchema ? RETAINED_SCHEMA_VAR : schemaExpr;\n const schemaArg = zodCompat ? retainedSchema : \"null\";\n const fcArg = codegenResult.fastFnName ?? \"null\";\n // `.is()` gets the fast-check directly only when it is a total predicate;\n // partial/none falls back to safeParse().success inside __zcMkv. A rebuilding\n // schema has no by-reference `fc` but still names its predicate separately.\n const isArg = codegenResult.isFnName ?? (codegenResult.fastTotal ? fcArg : \"null\");\n\n return [\n options?.pure === false ? \"(() => {\" : \"/* @__PURE__ */ (() => {\",\n ...(bindsSchema ? [`var ${RETAINED_SCHEMA_VAR}=${schemaExpr};`] : []),\n // Only fallback refs need the array; a compact validator with none of its\n // own reads `__zs` directly rather than allocating `[__zs]` to index into.\n ...(refEntries.length > 0\n ? [`var __rf=[${refEntries.map((fb) => `${retainedSchema}${fb.accessPath}`).join(\",\")}];`]\n : []),\n ...codegenResult.code\n .split(\"\\n\")\n .filter((l) => l.trim() !== \"\" && l.trim() !== \"/* zod-compiler */\"),\n codegenResult.functionDef,\n `return __zcMkv(${fnName},${schemaArg},${fcArg},${isArg});`,\n \"})()\",\n ].join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;AAcA,MAAa,oBACX;;;;;;;;;;;;;;;;;;;;AAqBF,MAAa,sBACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CF,MAAa,kBACX;;;AASF,MAAa,WACX;;;;;;;;;;;;;;;;;;;;;;;AAwBF,MAA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C,CAAC,KAAK,IAAI;AACb"}
1
+ {"version":3,"file":"iife.js","names":[],"sources":["../../src/core/iife.ts"],"sourcesContent":["/**\n * Shared CompiledSchema<T> IIFE generation.\n * Used by both CLI emitter and unplugin transform.\n */\n\nimport { RETAINED_SCHEMA_VAR } from \"./codegen/context.js\";\nimport type { CompiledSchemaInfo } from \"./pipeline.js\";\n\n/**\n * Import statement required by generateIIFE output (references\n * __zodCompilerConfig). `core` is bound for $ZodAsyncError: superRefine and\n * custom callbacks may only reveal that they are async through the promise\n * they return, at which point zod's own synchronous parse raises.\n */\nexport const ZOD_CONFIG_IMPORT =\n 'import { config as __zodCompilerConfig, core as __zcCore, ZodRealError as __zcZodError } from \"zod\";';\n\n/**\n * File-level `__zcMsg` declaration (must appear once after ZOD_CONFIG_IMPORT):\n * the message an issue gets when nothing was baked into it at build time.\n *\n * Resolves zod's tail of `finalizeIssue` — `config.customError` then\n * `config.localeError` then \"Invalid input\" — and does it PER CALL, because the\n * config is mutable: `z.config({ localeError })` in an entry point runs after\n * the schema modules it imports, so a value snapshotted at module init misses\n * it. Reading a captured `localeError` alone also dropped `customError`\n * outright, silently ignoring the global map most i18n setups install.\n *\n * The head of zod's chain — the schema's own `error` option — is baked into the\n * issue at build time and short-circuits this. The one link that cannot be\n * reproduced is a per-CALL `ctx.error`, which would have to travel through\n * `safeParse`; that entry point sits at V8's inlining budget, where even an\n * unused extra parameter measured ~12% on every parse.\n *\n * Only ever called while building an error, never on a successful parse.\n */\nexport const ZOD_MSG_DECLARATION =\n 'function __zcUw(m){return typeof m===\"string\"?m:(m===undefined||m===null?undefined:m.message);}' +\n \"var __zcMsg=function(iss){var c=__zodCompilerConfig(),m;\" +\n \"if(c.customError){m=__zcUw(c.customError(iss));if(m!==undefined&&m!==null)return m;}\" +\n \"if(c.localeError){m=__zcUw(c.localeError(iss));if(m!==undefined&&m!==null)return m;}\" +\n 'return \"Invalid input\";};';\n\n/**\n * Shared failure-result for __zcFin / __zcFinD. Inline mode (CLI emitter)\n * declares it once per compiled file; lean mode (all unplugin bundlers) declares\n * it once per bundle in the plugin-materialized runtime module (module-local —\n * generated code only ever references __zcFin/__zcFinD, never __ZcFail).\n *\n * Why a prototype getter and not `{success:false, get error(){...}}`: an object\n * literal with an inline accessor forces V8 down its slow accessor-defining\n * allocation path — ~110ns per failure, measured — which dominates the entire\n * invalid-input cost whenever callers never read `.error`. Hosting `error` on\n * the prototype turns each failure into a plain field-only instantiation (~2ns,\n * ~13x), with the lazy-cache semantics intact. (Trade-off: `error` is a\n * prototype accessor, so it no longer shows up in `Object.keys(result)` / spread\n * / JSON.stringify of the result wrapper — `.success`/`.error`/`.data` access,\n * destructuring, and `in` are unaffected.)\n *\n * One class serves both finalizers, so the instances share one hidden class:\n * __zcFin passes pre-collected issues in `_e` (with `_f===null`); __zcFinD\n * passes the hosted slow-walk in `_f` plus the input in `_i`, and the getter\n * runs the walk on first `.error` read. The whole finalization — locale fill\n * (__zcMsg applied ONLY when an issue carries no message, never overwriting a\n * baked-in custom/fallback message), input strip, and ZodError construction\n * (zod v4 JSON.stringifies every issue into `message` and captures a stack\n * trace) — stays deferred inside the cached accessor exactly as before, since\n * the issues array is observable solely through `.error`.\n *\n * `input` is `delete`d, not assigned `undefined`. Key PRESENCE is observable —\n * `\"input\" in issue`, `Object.keys(issue)`, object spread, `toStrictEqual`\n * against a zod issue — and zod's `util.finalizeIssue` does `delete full.input`\n * whenever `reportInput` is off, so assignment left every compiled issue one\n * enumerable key wider than zod's. The delete's dictionary-mode transition is\n * affordable precisely BECAUSE of the deferral above: it runs only after a\n * caller asks for `.error` on a failed parse, and is memoised in `_c`. Neither\n * a successful parse nor a `.success`/`.is()` check on a rejected one reaches\n * it — measured, the two are unchanged, while the `.error` read itself goes\n * ~3.95us -> ~4.19us per failure, i.e. ~6% of a path whose cost is already\n * dominated by the ZodError construction on the next line (stack capture plus a\n * JSON.stringify of every issue).\n */\nexport const FAIL_CLASS_DECL =\n \"function __ZcFail(e,f,i){this.success=false;this._e=e;this._f=f;this._i=i;this._c=undefined;}\" +\n 'Object.defineProperty(__ZcFail.prototype,\"error\",{configurable:true,get:function(){' +\n \"if(this._c)return this._c;\" +\n \"var e=this._f!==null?this._f(this._i):this._e;\" +\n 'for(var i=0;i<e.length;i++){if(e[i].message===undefined&&typeof __zcMsg===\"function\")e[i].message=__zcMsg(e[i]);delete e[i].input;delete e[i].continue;}' +\n \"return this._c=new __zcZodError(e);}});\";\n\n/** Eager finalizer (mutation / partial-fast-path schemas): issues already\n * collected in `e`; success short-circuits to a plain result literal. */\nexport const FIN_DECL =\n \"function __zcFin(e,d){if(!e.length)return{success:true,data:d};return new __ZcFail(e,null,null);}\";\n\n/**\n * Deferred-collection finalizer for Fast-Path-eligible schemas. When the\n * fast check fails, the ENTIRE slow path (the issue-collecting re-walk) is\n * pushed into the cached `.error` accessor instead of running eagerly:\n * fast-eligible schemas never mutate, so the walk's only output is the\n * issues array, which is observable solely through `.error` — one step\n * further along the same lazy boundary `__zcFin` already established (locale\n * fill, input strip, ZodError construction). A failed safeParse whose\n * `.error` is never read costs the fast check alone.\n *\n * Takes the schema's HOSTED slow-walk function plus the input — NOT a\n * per-call closure: `__zcFinD(__sw_N, input)` allocates only the result\n * object, where `__zcFinD(function(){...})` paid a closure environment and\n * function object per failure. Hosting the walk also shrinks safeParse to\n * two statements, within V8's inlining budget (the success-path result\n * literal becomes escape-analyzable at monomorphic call sites).\n *\n * The walk re-reads `input` at `.error`-read time; a caller that mutates\n * the input between safeParse and reading `.error` sees issues for the\n * mutated value (zod materializes at parse time). Same caveat class as the\n * documented __zcFin deferral.\n */\nexport const FIN_DEFERRED_DECL = \"function __zcFinD(f,inp){return new __ZcFail(null,f,inp);}\";\n\n/**\n * Compact-mode failure class — a lazy failure that delegates error reporting to\n * the ORIGINAL Zod schema's `safeParse`. Used by `output: \"compact\"`, where the\n * compiled slow walk is dropped entirely: a mutation-free schema's fast check\n * is the only generated validation, and on a fast-check failure the cold error\n * path is produced by the retained Zod schema itself (`zod` is the source of\n * truth, so the issues are byte-identical — no second validation engine).\n *\n * `_z` is the schema's PRISTINE safeParse method, captured by\n * emitRetainedMethod (see context.ts), and `_r` is its receiver — the `__zs`\n * binding generateIIFE places above that capture. Both are read before the\n * trailing `__zcMkv` call installs anything, so the method is zod's own\n * implementation, never the compiled delegate, avoiding infinite recursion\n * without allocating a bound function. The zod parse is deferred until `.error`\n * is read and cached, so\n * the common `safeParse(x).success`/`.is(x)` checks on invalid input cost only\n * the fast check (zod never runs) — the same deferral boundary `__zcFinD`\n * establishes for the compiled slow walk. Sound because compact mode is gated\n * on a TOTAL fast path: `fc(input) === false` ⟹ zod rejects, so `success:false`\n * holds without consulting zod.\n *\n * The getter returns zod's OWN ZodError verbatim (no locale fill / input strip /\n * re-wrap — zod already finalized it), so a delegated failure is exactly what\n * the unaltered schema would have produced.\n */\nexport const FAILZ_CLASS_DECL =\n \"function __ZcFailZ(z,r,i){this.success=false;this._z=z;this._r=r;this._i=i;this._c=undefined;}\" +\n 'Object.defineProperty(__ZcFailZ.prototype,\"error\",{configurable:true,get:function(){' +\n \"return this._c||(this._c=this._z.call(this._r,this._i).error);}});\";\n\n/** Compact-mode finalizer: retain a pristine safeParse, its receiver, and input lazily. */\nexport const FINZ_DECL = \"function __zcFinZ(z,r,i){return new __ZcFailZ(z,r,i);}\";\n\n/**\n * Validator factory. Inline mode (CLI emitter) declares it once per compiled\n * file; lean mode (all unplugin bundlers) exports it once per bundle from the\n * plugin-materialized runtime module — generated code never imports it from\n * the zod-compiler package itself, so zod-compiler stays a devDependency and\n * the helper set is always version-locked to the codegen that calls it.\n * Wraps a safeParse function into the CompiledSchema interface.\n *\n * IDENTITY-PRESERVING: with zodCompat (schema != null) the compiled\n * parse/safeParse/parseAsync/safeParseAsync are installed as OWN properties\n * on the original schema object, which is returned as-is. zod v4 keys\n * several APIs on object identity — toJSONSchema's ctx.seen registers the\n * object it is handed while each processor closure captures the original\n * inst (a wrapper crashes `optionalProcessor` with \"Cannot set properties\n * of undefined (setting 'ref')\" the moment a compiled schema is composed\n * into another schema), and globalRegistry/.meta() is a WeakMap keyed by\n * the schema instance (a wrapper silently loses OpenAPI titles/ids). An\n * Object.create wrapper breaks both; mutating the original breaks neither\n * (zod's internal parsing flows through _zod.run, never the public\n * methods, and derived schemas — .optional(), .extend() — are fresh\n * instances that fall back to plain zod). schema=null (zodCompat: false)\n * still produces a plain method-bag object.\n *\n * fc is the schema's hosted fast-check boolean function (null when no Fast\n * Path exists). parse()/parseAsync() try it first and return the input\n * directly on success: fc is small enough for V8 to inline, so the hot parse\n * path runs with zero allocations — calling fn would allocate an intermediate\n * SafeParseResult that escape analysis cannot remove (fn never inlines).\n * Fast-path-eligible schemas never mutate, so fc(input) ⟹ data === input.\n *\n * is is the TOTAL fast-check predicate (fc when the fast path is total, else\n * null). Installed as `.is()` — a zero-allocation boolean type guard. When\n * null (partial fast path or none) `.is()` derives from fn(input).success: a\n * partial fc can pass-through valid input but its `false` does not imply\n * rejection (a default/catch may still succeed), so it would be unsound as a\n * standalone guard.\n *\n * parseAsync/safeParseAsync wrap the SYNC validator, which is right for every\n * schema the compiler can reproduce — none of them are async. It is wrong for\n * the ones it cannot: an `async` refinement or a `z.promise()` extracts to a\n * Zod delegate, and delegating means calling Zod's SYNCHRONOUS safeParse, which\n * raises `$ZodAsyncError` by design. Wrapping that gave the compiled schema an\n * async pair that rejected with `$ZodAsyncError` for EVERY input — including\n * valid ones — where Zod resolves normally, so `await UserSchema.parseAsync(x)`\n * stopped working the moment any part of the schema went async.\n *\n * So both are guarded: a synchronous throw hands off to the schema's ORIGINAL\n * async method, captured before these are installed — the same escape hatch\n * `~standard` already uses for its throw path, and for the same reason (the\n * compiled validator has no async mode to offer, and Zod's is exact). It also\n * fixes the smaller wart that a throwing `fn` made `parseAsync` throw\n * SYNCHRONOUSLY rather than return a rejected promise. With `zodCompat: false`\n * there is no schema to delegate to and the throw propagates as before.\n *\n * `~standard` is REPLACED, not merely preserved. Zod builds it lazily as\n * `validate: (v) => safeParse(inst, v)` — the core FUNCTION, which goes straight\n * to `inst._zod.run`. It never reads the schema's own `safeParse` property, so\n * installing the compiled one leaves this route entirely uncompiled: measured\n * 271.7 ns against the compiled 26.6 ns on the same schema, i.e. Standard Schema\n * consumers (tRPC, Hono, TanStack) were getting plain Zod.\n *\n * Zod's own `~standard` is never READ, only overwritten. Zod installs the slot\n * with `util.defineLazy` — commented there as \"avoid creating objects for every\n * schema\" — so it is an accessor that builds `{version, vendor, validate}` plus\n * its closure on first touch. Reading it to capture a fallback fired that getter\n * for every compiled schema while the module was still initializing.\n *\n * How much that costs depends on the entry point, and only one of them is free:\n * classic `zod` forces the slot itself during `ZodType.init` (it does\n * `Object.assign(inst[\"~standard\"], { jsonSchema })`), so there the read hit an\n * already-built object and cost only an accessor call. `zod/mini` and raw\n * `zod/v4/core` never touch it, so for those the read built — and retained — an\n * object and a closure per schema, purely to capture a fallback the schema will\n * most likely never expose to a Standard Schema consumer.\n *\n * The throw path is rebuilt instead of captured. Zod's validate catches a\n * synchronous throw and retries through `safeParseAsync` — that is how an async\n * refinement resolves and how a throwing check surfaces as a rejected promise\n * rather than a synchronous throw — so calling the already-captured `zspa` and\n * mapping its result is the same route to the same result. `vendor` is likewise\n * a constant: schema discovery only ever admits zod schemas, and classic, mini\n * and core all hardcode `vendor: \"zod\"` themselves.\n *\n * Not carried over (unchanged by this, and pre-dating it): classic's\n * `~standard.jsonSchema` extension, which the replacement object has never\n * reproduced.\n *\n * Installed with defineProperty rather than assignment: Zod's lazy setter\n * redefines the slot as non-writable, so a second `__zcMkv` on the same schema\n * object — two exports aliasing one schema — would throw under ESM strict mode.\n */\nexport const MK_VALIDATOR_DECL =\n \"function __zcMkv(fn,schema,fc,is){var w=schema||{};var zpa=w.parseAsync,zspa=w.safeParseAsync;w.parse=fc?function(input){if(fc(input))return input;var r=fn(input);if(r.success)return r.data;throw r.error;}:function(input){var r=fn(input);if(r.success)return r.data;throw r.error;};w.safeParse=fn;w.safeParseAsync=function(input){try{return Promise.resolve(fn(input));}catch(e){if(zspa)return zspa(input);throw e;}};w.parseAsync=fc?function(input){try{if(fc(input))return Promise.resolve(input);var r=fn(input);if(r.success)return Promise.resolve(r.data);return Promise.reject(r.error);}catch(e){if(zpa)return zpa(input);throw e;}}:function(input){try{var r=fn(input);if(r.success)return Promise.resolve(r.data);return Promise.reject(r.error);}catch(e){if(zpa)return zpa(input);throw e;}};w.is=is||function(input){return fn(input).success;};\" +\n 'Object.defineProperty(w,\"~standard\",{configurable:true,value:{version:1,vendor:\"zod\",validate:function(input){var r;try{if(fc&&fc(input))return{value:input};r=fn(input);}catch(e){if(zspa)return zspa(input).then(function(q){return q.success?{value:q.data}:{issues:q.error.issues};});throw e;}return r.success?{value:r.data}:{issues:r.error.issues};}}});' +\n \"return w;}\";\n\nfunction extractFunctionName(functionDef: string): string {\n const match = /^function\\s+(\\w+)\\s*\\(/.exec(functionDef);\n if (!match?.[1]) {\n throw new Error(\"Cannot extract function name from generated code\");\n }\n return match[1];\n}\n\n/**\n * Does the IIFE's preamble DEREFERENCE the retained schema at evaluation time?\n *\n * Only `__rf` does: every entry is `__zs<accessPath>`, and an access path walks\n * the schema's structure — `._zod.innerType` fires a `z.lazy()` getter,\n * `.shape` materializes a `z.object()` shape (zod v4 reads every property\n * descriptor, so ONE `.shape` read fires ALL of an object's recursion getters).\n * Binding `__zs` itself does not: constructing the schema leaves deferred\n * callbacks unforced, and `usesRetainedSchema`'s only read is `__zs.safeParse`,\n * a prototype getter that binds the method and installs the bound copy on the\n * instance without touching the schema's structure.\n *\n * The distinction decides whether the IIFE may be evaluated inside the\n * INITIALIZER of the binding the schema's own deferred callbacks close over —\n * see the self-referential path in the unplugin's autoDiscover rewrite.\n */\nexport function iifeDerefsSchema(schema: CompiledSchemaInfo): boolean {\n return schema.refEntries.length > 0;\n}\n\n/**\n * Generate a `/* @__PURE__ * /` IIFE wrapping a compiled validator.\n *\n * @param schemaExpr - Expression resolving to the original Zod schema\n * (e.g. `\"UserSchema\"` in unplugin, `\"(__src_X as any).schema\"` in CLI)\n * @param schema\n * @param options - `pure: false` drops the `/* @__PURE__ * /` annotation, for\n * the one caller that emits the IIFE as a STATEMENT following the\n * declaration rather than as its initializer: there the call's whole point is\n * its side effect (`__zcMkv` installing the compiled methods on the schema),\n * and a bundler that believed it pure would drop the compilation outright.\n */\nexport function generateIIFE(\n schemaExpr: string,\n schema: CompiledSchemaInfo,\n options?: { zodCompat?: boolean | undefined; pure?: boolean | undefined },\n): string {\n const { codegenResult, refEntries } = schema;\n const fnName = extractFunctionName(codegenResult.functionDef);\n const zodCompat = options?.zodCompat !== false;\n // Every fallback access starts from the same source schema, and compact\n // delegation names it outright. Capture it once whenever either needs it, so\n // an inline initializer is not reconstructed for each path and again for the\n // identity-preserving __zcMkv target.\n const bindsSchema = refEntries.length > 0 || codegenResult.usesRetainedSchema === true;\n const retainedSchema = bindsSchema ? RETAINED_SCHEMA_VAR : schemaExpr;\n const schemaArg = zodCompat ? retainedSchema : \"null\";\n const fcArg = codegenResult.fastFnName ?? \"null\";\n // `.is()` gets the fast-check directly only when it is a total predicate;\n // partial/none falls back to safeParse().success inside __zcMkv. A rebuilding\n // schema has no by-reference `fc` but still names its predicate separately.\n const isArg = codegenResult.isFnName ?? (codegenResult.fastTotal ? fcArg : \"null\");\n\n return [\n options?.pure === false ? \"(() => {\" : \"/* @__PURE__ */ (() => {\",\n ...(bindsSchema ? [`var ${RETAINED_SCHEMA_VAR}=${schemaExpr};`] : []),\n // Only fallback refs need the array; a compact validator with none of its\n // own reads `__zs` directly rather than allocating `[__zs]` to index into.\n ...(refEntries.length > 0\n ? [`var __rf=[${refEntries.map((fb) => `${retainedSchema}${fb.accessPath}`).join(\",\")}];`]\n : []),\n ...codegenResult.code\n .split(\"\\n\")\n .filter((l) => l.trim() !== \"\" && l.trim() !== \"/* zod-compiler */\"),\n codegenResult.functionDef,\n `return __zcMkv(${fnName},${schemaArg},${fcArg},${isArg});`,\n \"})()\",\n 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AK,GAAG,EAAE,GAAG,IACvF,CAAC;EACL,GAAG,cAAc,KACd,MAAM,IAAI,CAAC,CACX,QAAQ,MAAM,EAAE,KAAK,MAAM,MAAM,EAAE,KAAK,MAAM,oBAAoB;EACrE,cAAc;EACd,kBAAkB,OAAO,GAAG,UAAU,GAAG,MAAM,GAAG,MAAM;EACxD;CACF,CAAC,CAAC,KAAK,IAAI;AACb"}
@@ -309,12 +309,35 @@ interface ObjectIR {
309
309
  */
310
310
  catchall?: SchemaIR;
311
311
  /**
312
- * Fallback-typed property keys whose zod schema is optional-out: when the
313
- * key is ABSENT from the input, their issues are suppressed (mirrors zod's
314
- * handlePropertyResult). Lets z.exactOptional() and friends fall back at
315
- * the property level without rejecting missing keys.
312
+ * Keys whose zod schema sits on the middle rung of `optin` ("optional") and is
313
+ * optional-out, and whose compiled property could still raise an issue or
314
+ * produce a value when handed `undefined` (a fallback, a union, a pipe). When
315
+ * the key is ABSENT the property is not run at all — zod's
316
+ * handlePropertyResult returns before looking at the result, so nothing it
317
+ * made of `undefined` is reported or kept. The plain `.optional()` property
318
+ * needs no entry: its compiled form already short-circuits `undefined`.
319
+ */
320
+ skipAbsentKeys?: string[];
321
+ /**
322
+ * Keys whose zod schema is "defaulted" (`.default()`, `.prefault()`, a union
323
+ * containing one) AND optional-out, and whose compiled property could raise
324
+ * an issue for `undefined`: when the key is ABSENT the property runs — the
325
+ * substitute must fire — but a failure is swallowed, issues and value alike
326
+ * (mirrors zod's handlePropertyResult). Lets `z.prefault().optional()` and
327
+ * friends fall back at the property level without rejecting missing keys.
316
328
  */
317
329
  suppressAbsentKeys?: string[];
330
+ /**
331
+ * Keys whose zod schema is NOT optional-in (`_zod.optin === undefined`) but
332
+ * whose compiled property might accept `undefined` — `z.any()`, `z.unknown()`,
333
+ * `z.undefined()`, a union with such an option. zod runs the property on the
334
+ * absent key's `undefined` and, when that raised nothing, reports
335
+ * `invalid_type` with `expected: "nonoptional"` at the key: a required key
336
+ * has to be PRESENT, whatever its schema thinks of `undefined`. Keys whose
337
+ * property rejects `undefined` outright are omitted — their own issue
338
+ * already stands in for the absence.
339
+ */
340
+ nonoptionalKeys?: string[];
318
341
  }
319
342
  interface ArrayIR {
320
343
  type: "array";
@@ -326,37 +349,63 @@ interface TupleIR {
326
349
  items: SchemaIR[];
327
350
  rest: SchemaIR | null;
328
351
  /**
329
- * Index where the omittable tail begins — zod's `optStart`, captured from the
330
- * live schemas at extraction time:
352
+ * zod's `optinStart`, captured from the live schemas at extraction time: the
353
+ * index after the last item whose `_zod.optin` is `undefined`.
331
354
  *
332
355
  * ```js
333
- * const reversedIndex = [...items].reverse().findIndex((i) => i._zod.optin !== "optional");
334
- * const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;
356
+ * for (let i = items.length - 1; i >= 0; i--) if (items[i]._zod.optin === undefined) return i + 1;
357
+ * return 0;
335
358
  * ```
336
359
  *
337
- * An item at or past this index is SKIPPED ENTIRELY when the input is shorter
338
- * than the tuple — zod never runs its schema, so no default/prefault fires for
339
- * it — and it also moves the under-length `too_small` threshold
340
- * (`input.length < optStart - 1`).
360
+ * Without a rest element an input shorter than this is rejected outright with
361
+ * a single `too_small` (`minimum: optStart`, `inclusive: true`) before any
362
+ * item runs. `optin` is a three-rung ladder — `undefined` (required),
363
+ * `"optional"` (absence permitted, nothing supplied) and `"defaulted"`
364
+ * (absence permitted, a value substituted) — and any rung above `undefined`
365
+ * lets the slot be absent.
341
366
  *
342
367
  * Read from `_zod.optin` rather than inferred from the item's IR type because
343
368
  * "optional-in" is a property of the ZOD schema, not of the shape the compiler
344
- * managed to compile: `z.exactOptional()`, `z.prefault()`, `.nonoptional()`
345
- * and pipes all extract to an opaque `fallback` leaf, `z.undefined()` and
346
- * `z.nullable(z.string().optional())` extract to nodes named nothing like
347
- * "optional", and a union is optional-in when ANY option is. The IR-type
348
- * inference this replaced recognised only `optional` and `default`, so every
349
- * other shape lost its omittable tail — `z.tuple([z.exactOptional(z.string())])`
350
- * rejected `[]` that zod accepts, `z.tuple([z.string().prefault("d")])` turned
351
- * `[]` into `["d"]`, and `z.tuple([z.string(), z.undefined()])` answered a
352
- * one-element input with a `too_small` where zod reports nothing.
369
+ * managed to compile: `z.exactOptional()`, `z.prefault()` and pipes extract to
370
+ * an opaque `fallback` leaf, `z.nullable(z.string().optional())` extracts to a
371
+ * node named nothing like "optional", and a union is optional-in when ANY
372
+ * option is.
353
373
  */
354
374
  optStart: number;
375
+ /**
376
+ * zod's `optoutStart`: the index after the last item whose `_zod.optout` is
377
+ * not `"optional"` — computed like {@link optStart} but over `optout`. Absent
378
+ * only when it equals `items.length` (every slot is required-out).
379
+ *
380
+ * From this index on, an absent slot can END the output: zod's
381
+ * `handleTupleResults` truncates the tail there when the item is on the
382
+ * "optional" rung (see {@link optionalIn}) or when running it on `undefined`
383
+ * failed, and afterwards drops trailing `undefined`s that absent slots
384
+ * produced. Below it an absent slot is materialized as `undefined` (or as
385
+ * whatever the item substituted), because a later required-out slot has to
386
+ * keep its index.
387
+ */
388
+ optoutStart?: number;
389
+ /**
390
+ * Indices whose item sits on the middle rung, `_zod.optin === "optional"`.
391
+ * Absent only when empty. At or past {@link optoutStart} such a slot, when
392
+ * absent, ends the output without running its schema; a "defaulted" slot
393
+ * there runs and keeps what it produced. Below `optoutStart` both run and
394
+ * write their result back.
395
+ */
396
+ optionalIn?: number[];
355
397
  }
356
398
  interface RecordIR {
357
399
  type: "record";
358
400
  keyType: SchemaIR;
359
401
  valueType: SchemaIR;
402
+ /**
403
+ * The key schema declares a finite key set (`_zod.values`), so a key outside
404
+ * it is reported as `unrecognized_keys` — one issue after the walk — rather
405
+ * than `invalid_key`. Only a partial record compiles with one; an exhaustive
406
+ * one, where every declared key must be present, delegates to zod.
407
+ */
408
+ enumerableKeys?: true;
360
409
  }
361
410
  interface SetIR {
362
411
  type: "set";
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../../src/core/types.ts"],"mappings":";;;;;;UAQiB;;EAEf;;UAG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A,oBACA,qBAEA,WACA,gBACA,oBACA,UACA,aACA,iBACA,oBACA;UAKW,iBAAiB;EAChC;EACA,MAAM;;UAGS;EACf;EACA,OAAO;;KAGG,gBAAgB,KAAK,iBAAiB,KAAK;UAEtC;EACf;EACA;EACA;GAEC;;UAGc;EACf,QAAQ;;UAGO;EACf;EACA;;UAGe,eAAe;EAC9B,MAAM,iBAAiB;EACvB,WAAW,iBAAiB,QAAQ;EACpC,UAAU,iBAAiB,gBAAgB;EAC3C,eAAe,iBAAiB,QAAQ,gBAAgB;;;;;;;;;;EAUxD,GAAG,iBAAiB,SAAS"}
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../../src/core/types.ts"],"mappings":";;;;;;UAQiB;;EAEf;;UAGe,uBAAuB;EACtC;EACA;;UAGe,uBAAuB;EACtC;EACA;;UAGe,0BAA0B;EACzC;EACA;;UAGe,yBAAyB;EACxC;EACA;EACA;;UAGe,sBAAsB;EACrC;EACA;EACA;;UAGe,wBAAwB;EACvC;EACA;;UAGe,0BAA0B;EACzC;EACA;;UAGe,0BAA0B;EACzC;EACA;EACA;;EAEA;;EAEA;EACA;;EAEA;EACA;;EAEA;;;;;;;;;;;;;;;;;;EAkBA;;UAGe,sBAAsB;EACrC;EACA;EACA;;UAGe,wBAAwB;EACvC;EACA;;UAGe,sBAAsB;EACrC;EACA;;KAGU,UACR,iBACA,iBACA,oBACA,mBACA,gBACA,kBACA,oBACA,oBACA,gBACA,kBACA;UAMa;EACf;;;;;;EAMA;;;;;;;;;EASA;;EAEA;;;;;;EAMA;;;;;;;;;EASA;;;;;;;;;;;;;UAce;EACf;;EAEA;;;;;;UAOe;EACf;;EAEA;;;KAIU,kBACR,UACA,sBACA,2BACA;UAIa,6BAA6B;EAC5C;EACA;EACA;EACA;;UAGe,0BAA0B;EACzC;EACA;EACA;EACA;;KAGU,cAAc,uBAAuB;UAIhC,+BAA+B;EAC9C;;EAEA;EACA;;UAGe,4BAA4B;EAC3C;;EAEA;EACA;;UAGe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,KAAK;;UAKU;EACf;EACA;;;;;EAKA;;;;;;;EAOA;;EAEA,OAAO;;UAGQ;EACf;EACA;;EAEA;;EAEA;;EAEA,OAAO;;;;;;UASQ;EACf;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;UAQe;EACf;EACA,OAAO;;EAEP;;UAGe;EACf;EACA;;EAUA;;UAGe;EACf;EACA;;UAGe;EACf;EACA,OAAO;;EAEP;;UAGe;EACf;;;;;;;;;EASA;;;;;;;;;;UAWe;EACf;EACA;EACA,OAAO;;UAGQ;EACf;EACA;EACA;EACA;;;;;;;;;UAYe;EACf;;KAGU,WAAW,sBAGjB,WACA,WACA,YACA,WACA,SACA,WACA,SACA,cACA,SACA,QACA,UACA,QACA,YACA,YACA,SAEA,WACA,UACA,UACA,WACA,QACA,QACA,SAEA,UACA,uBACA,iBAEA,aACA,aACA,aACA,YACA,SAEA,oBACA,qBAEA,WACA,gBACA,oBACA,UACA,aACA,iBACA,oBACA;UAKW,iBAAiB;EAChC;EACA,MAAM;;UAGS;EACf;EACA,OAAO;;KAGG,gBAAgB,KAAK,iBAAiB,KAAK;UAEtC;EACf;EACA;EACA;GAEC;;UAGc;EACf,QAAQ;;UAGO;EACf;EACA;;UAGe,eAAe;EAC9B,MAAM,iBAAiB;EACvB,WAAW,iBAAiB,QAAQ;EACpC,UAAU,iBAAiB,gBAAgB;EAC3C,eAAe,iBAAiB,QAAQ,gBAAgB;;;;;;;;;;EAUxD,GAAG,iBAAiB,SAAS"}
package/dist/jit.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"jit.d.ts","names":[],"sources":["../src/jit.ts"],"mappings":";;;UA6EiB;;;;;;;EAOf;;EAEA;;;;;;;;;;;;;;;;;;;;;;;iBAwBc,IAAI,UAAU,SAC5B,QAAQ,GACR,UAAU,aACT,IAAI,eAAe,OAAO;;;;;;;;;;;;;;iBA8Kb,OAAO,iBAAiB,UAAU"}
1
+ {"version":3,"file":"jit.d.ts","names":[],"sources":["../src/jit.ts"],"mappings":";;;UAoFiB;;;;;;;EAOf;;EAEA;;;;;;;;;;;;;;;;;;;;;;;iBAwBc,IAAI,UAAU,SAC5B,QAAQ,GACR,UAAU,aACT,IAAI,eAAe,OAAO;;;;;;;;;;;;;;iBAoNb,OAAO,iBAAiB,UAAU"}
package/dist/jit.js CHANGED
@@ -25,6 +25,13 @@ import { ZodRealError, config, core } from "zod";
25
25
  * ones. Importing a module of 500 schemas therefore costs nothing, and a
26
26
  * serverless invocation touching three of them pays for three.
27
27
  *
28
+ * Zod itself keeps the parse methods on the PROTOTYPE (since 4.4): each is a
29
+ * getter that binds the method on first read and installs the bound copy as an
30
+ * own data property, so a fresh schema carries no own `parse` / `safeParse` at
31
+ * all, while one that has been read already does. `jit()` meets both shapes —
32
+ * it snapshots whatever the slots hold, fronts them with its own accessors, and
33
+ * hands back exactly what it found whenever it has to step aside.
34
+ *
28
35
  * Runtime code generation is not always permitted — a strict CSP without
29
36
  * `unsafe-eval`, some edge runtimes. Zod v4 has the same constraint (its object
30
37
  * fast-pass is itself a `new Function`) and already exposes the two switches
@@ -124,19 +131,24 @@ function jit(schema, options) {
124
131
  /**
125
132
  * Front every installed method with a compile-on-read accessor. `trigger`
126
133
  * materializes the schema, which normally replaces these accessors with the
127
- * compiled methods (or restores Zod's own). When that replacement does not take,
128
- * the getter falls back to the snapshot rather than re-reading the slot — see
129
- * the re-entrancy note in the body.
134
+ * compiled methods (or restores what Zod had). When that replacement does not
135
+ * take, the getter serves Zod's own method rather than re-reading the slot —
136
+ * see the re-entrancy note in the body.
130
137
  */
131
138
  function installAccessors(target, original, trigger, cancel) {
132
139
  for (const slot of SLOTS) {
133
140
  let reading = false;
141
+ let stranded;
142
+ const serveZod = () => {
143
+ stranded ??= { value: fromZod(target, original, slot) };
144
+ return stranded.value;
145
+ };
134
146
  const read = function() {
135
- if (reading) return fromSnapshot(target, original, slot);
147
+ if (reading) return serveZod();
136
148
  reading = true;
137
149
  try {
138
150
  trigger();
139
- if (stillFrontedBy(target, slot, read)) return fromSnapshot(target, original, slot);
151
+ if (stillFrontedBy(target, slot, read)) return serveZod();
140
152
  return target[slot];
141
153
  } finally {
142
154
  reading = false;
@@ -148,6 +160,10 @@ function installAccessors(target, original, trigger, cancel) {
148
160
  get: read,
149
161
  set(value) {
150
162
  cancel();
163
+ if (!stillFrontedBy(target, slot, read)) {
164
+ target[slot] = value;
165
+ return;
166
+ }
151
167
  Object.defineProperty(target, slot, {
152
168
  configurable: true,
153
169
  enumerable: original.get(slot)?.enumerable ?? false,
@@ -172,14 +188,29 @@ function stillFrontedBy(target, slot, getter) {
172
188
  }
173
189
  }
174
190
  /**
175
- * What Zod had in `slot`, taken from the snapshot made before installation.
176
- * `undefined` for `is`, which no plain Zod schema carries — the same thing every
177
- * other degradation path leaves there.
191
+ * Zod's own value for `slot`, bypassing the accessor that fronts it.
192
+ *
193
+ * A slot the snapshot holds is answered from the snapshot. One it does not hold
194
+ * lives on the prototype, where Zod's getter binds the method to its receiver
195
+ * and installs the bound copy as an own property — on a target that accepts
196
+ * the install, that also replaces the stranded accessor with the copy, which is
197
+ * the handover materialize() could not make. A target that refuses the install
198
+ * (frozen, or a wrapper that vetoes `defineProperty`) makes Zod's getter throw
199
+ * instead; there the read goes through a stand-in that inherits from the target,
200
+ * so the copy lands on the stand-in and the method reaches `_zod` through the
201
+ * chain. `undefined` for `is`, which no plain Zod schema carries — the same
202
+ * thing every other degradation path leaves there.
178
203
  */
179
- function fromSnapshot(target, original, slot) {
204
+ function fromZod(target, original, slot) {
180
205
  const descriptor = original.get(slot);
181
- if (descriptor === void 0) return void 0;
182
- return descriptor.get === void 0 ? descriptor.value : descriptor.get.call(target);
206
+ if (descriptor !== void 0) return descriptor.get === void 0 ? descriptor.value : descriptor.get.call(target);
207
+ const proto = Object.getPrototypeOf(target);
208
+ if (proto === null) return void 0;
209
+ try {
210
+ return Reflect.get(proto, slot, target);
211
+ } catch {
212
+ return Reflect.get(proto, slot, Object.create(target));
213
+ }
183
214
  }
184
215
  /**
185
216
  * Compile every Zod schema found among an object's own values — typically a
@@ -197,7 +228,11 @@ function fromSnapshot(target, original, slot) {
197
228
  function jitAll(schemas, options) {
198
229
  for (const value of Object.values(schemas)) if (isZodSchema(value)) jit(value, options);
199
230
  }
200
- /** Put Zod's own descriptors back, dropping the compile-on-read accessors. */
231
+ /**
232
+ * Put back what the snapshot holds, dropping the compile-on-read accessors: the
233
+ * own copy Zod (or the build plugin) had installed, or nothing at all, so the
234
+ * slot reads through to Zod's prototype getter again.
235
+ */
201
236
  function restore(target, original) {
202
237
  for (const slot of SLOTS) try {
203
238
  const descriptor = original.get(slot);
package/dist/jit.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"jit.js","names":["zodCore","zodConfig"],"sources":["../src/jit.ts"],"sourcesContent":["/**\n * Runtime compilation — the same extract → codegen pipeline the build plugin\n * runs, executed in-process and evaluated through `new Function`.\n *\n * The AOT paths (unplugin, CLI) need a build step to fire. Plenty of everyday\n * code has none: `tsx server.ts`, `node --experimental-strip-types`, a Jest\n * suite, a serverless handler bundled by someone else's toolchain, a library\n * that ships schemas to consumers. There `compile()` is a no-op and every parse\n * runs plain Zod. `jit()` closes that gap — one call, no build integration,\n * measured 3-25x on everyday schemas at ~0.1-0.2 ms of one-time compilation.\n *\n * Nothing here re-implements validation: {@link compileSchemas} and\n * {@link generateIIFE} are the exact modules the plugin and CLI use, so the\n * generated validator, its Zod parity and its performance are identical to what\n * a build would have emitted. The only difference is *when* the code is\n * produced.\n *\n * Compilation is LAZY by default: `jit()` installs accessors that compile on\n * the first read of a parse method and replace themselves with the compiled\n * ones. Importing a module of 500 schemas therefore costs nothing, and a\n * serverless invocation touching three of them pays for three.\n *\n * Runtime code generation is not always permitted — a strict CSP without\n * `unsafe-eval`, some edge runtimes. Zod v4 has the same constraint (its object\n * fast-pass is itself a `new Function`) and already exposes the two switches\n * for it: the `core.util.allowsEval` probe and `z.config({ jitless: true })`.\n * `jit()` honours both and degrades to plain Zod, so one setting governs both\n * compilers. Those targets are where the build plugin belongs anyway — it emits\n * the same validator with no runtime evaluation at all.\n */\n\nimport { config as zodConfig, core as zodCore, ZodRealError, type output, type ZodType } from \"zod\";\nimport {\n FAIL_CLASS_DECL,\n FAILZ_CLASS_DECL,\n FIN_DECL,\n FIN_DEFERRED_DECL,\n FINZ_DECL,\n generateIIFE,\n MK_VALIDATOR_DECL,\n ZOD_MSG_DECLARATION,\n} from \"./core/iife.js\";\nimport { compileSchemas } from \"./core/pipeline.js\";\nimport type { CompiledSchema } from \"./core/types.js\";\nimport { isZodSchema } from \"./is-zod-schema.js\";\n\n/**\n * The declarations `ZOD_CONFIG_IMPORT` supplies to an emitted module, minus the\n * import itself — `zod`'s three bindings arrive as parameters instead, so the\n * evaluated code has no module scope to resolve. Byte-for-byte the same helper\n * source the CLI emitter writes into a `.compiled.ts`, so a JIT validator and\n * an AOT one share their entire runtime layer.\n */\nconst RUNTIME_PRELUDE = [\n ZOD_MSG_DECLARATION,\n FAIL_CLASS_DECL,\n MK_VALIDATOR_DECL,\n FIN_DECL,\n FIN_DEFERRED_DECL,\n FAILZ_CLASS_DECL,\n FINZ_DECL,\n].join(\"\\n\");\n\n/**\n * Methods `__zcMkv` installs. Each is fronted by a compile-on-read accessor\n * until the schema materializes.\n *\n * `~standard` earns its place: Zod builds it as a closure over `_zod.run`, not\n * over the schema's `safeParse` property, so a Standard Schema consumer (tRPC,\n * Hono, TanStack Form) that never touches `safeParse` would otherwise keep\n * running plain Zod forever behind a \"compiled\" schema.\n */\nconst SLOTS = [\"parse\", \"safeParse\", \"parseAsync\", \"safeParseAsync\", \"is\", \"~standard\"] as const;\n\n/** Schemas already handed to `jit()`, so a second call is a no-op rather than a recompile. */\nconst seen = new WeakSet<object>();\n\nexport interface JitOptions {\n /**\n * Compile immediately instead of on first use. Costs ~0.1-0.2 ms per schema\n * at import time; useful for a long-lived server that would rather pay during\n * startup than on the first request, or to surface a compilation failure\n * eagerly. Default `false`.\n */\n eager?: boolean | undefined;\n /** Use compact codegen and delegate cold error production to Zod. @default \"schema\" */\n output?: \"schema\" | \"compact\" | undefined;\n}\n\n/**\n * Compile `schema` in-process and install the compiled `parse` / `safeParse` /\n * `parseAsync` / `safeParseAsync` / `is` / `~standard` on it.\n *\n * Returns the SAME object — identity-preserving exactly as the build plugin is,\n * so `.shape`, `_zod`, `instanceof`, `z.toJSONSchema()`, `.meta()` and\n * composition into a larger schema all keep working, and every existing\n * reference to the schema picks the compiled methods up.\n *\n * ```ts\n * import { z } from \"zod\";\n * import { jit } from \"zod-compiler/jit\";\n *\n * export const UserSchema = jit(z.object({ name: z.string(), email: z.email() }));\n * UserSchema.safeParse(input); // compiled on this first call\n * ```\n *\n * Schemas the compiler cannot reproduce fall back to Zod per sub-schema, the\n * same way they do at build time; a schema that cannot be compiled at all is\n * left as plain Zod.\n */\nexport function jit<T extends ZodType>(\n schema: T,\n options?: JitOptions,\n): T & CompiledSchema<output<T>> {\n const target = schema as unknown as Record<string, unknown>;\n if (seen.has(target)) return schema as T & CompiledSchema<output<T>>;\n seen.add(target);\n\n if (options?.eager === true) {\n materialize(schema, options);\n return schema as T & CompiledSchema<output<T>>;\n }\n\n // Snapshot Zod's own descriptors first: materialize() restores them before\n // handing the object to `__zcMkv`, so the generated code sees a pristine\n // schema — it captures the original `parseAsync` / `safeParseAsync` as its\n // throw paths, and capturing a stub there would loop back into itself.\n const original = new Map<string, PropertyDescriptor | undefined>();\n try {\n for (const slot of SLOTS) {\n original.set(slot, Object.getOwnPropertyDescriptor(target, slot));\n }\n } catch {\n // The target answers a descriptor query with a throw — an exotic wrapper,\n // not anything Zod built. Without a snapshot there is nothing to roll back\n // to, so install nothing and hand back the schema exactly as it came.\n return schema as T & CompiledSchema<output<T>>;\n }\n\n // Installing the accessors is the step most likely to throw rather than\n // degrade: a slot locked non-configurable (a future Zod, another wrapper) makes\n // defineProperty raise, and `jit()` is called at module scope — so an\n // unhandled throw here takes down the importing app at boot. Roll back to\n // whatever Zod had and leave the schema alone instead.\n let pending = true;\n try {\n installAccessors(\n target,\n original,\n () => {\n if (!pending) return;\n pending = false;\n restore(target, original);\n materialize(schema, options);\n },\n () => {\n if (!pending) return;\n pending = false;\n // Restore EVERY slot, not just the one being written. A left-behind\n // accessor whose trigger has been cancelled would read `target[slot]`\n // and re-enter itself — unbounded recursion, which is what a later read\n // of an untouched slot (`~standard`, from a Standard Schema consumer)\n // would otherwise hit.\n //\n // Reached only when something WRITES a slot before anything reads one: a\n // test double, another wrapper, or an AOT `safeParse` assigned directly.\n // The build plugin's own `__zcMkv` does not land here — its first\n // statement READS `parseAsync`/`safeParseAsync` to capture their\n // originals, so it triggers materialization and then overwrites the\n // compiled-by-jit methods with the compiled-by-plugin ones.\n restore(target, original);\n },\n );\n } catch {\n pending = false;\n restore(target, original);\n }\n\n return schema as T & CompiledSchema<output<T>>;\n}\n\n/**\n * Front every installed method with a compile-on-read accessor. `trigger`\n * materializes the schema, which normally replaces these accessors with the\n * compiled methods (or restores Zod's own). When that replacement does not take,\n * the getter falls back to the snapshot rather than re-reading the slot — see\n * the re-entrancy note in the body.\n */\nfunction installAccessors(\n target: Record<string, unknown>,\n original: ReadonlyMap<string, PropertyDescriptor | undefined>,\n trigger: () => void,\n cancel: () => void,\n): void {\n for (const slot of SLOTS) {\n // Re-entrancy is settled structurally rather than by inspection. Reading the\n // slot again is how this getter normally hands over — to the compiled method\n // materialize() installed, or to Zod's own that restore() put back — but the\n // handover can fail to take: a target frozen after `jit()` refuses both, and\n // a second copy of this module in the graph leaves ITS accessor on the slot,\n // so the two bounce reads between them. `trigger()` is spent by then, so\n // either way the read recurses until the stack blows. While a read is already\n // in flight, serve Zod's own method from the snapshot: a schema that cannot\n // be compiled still parses.\n let reading = false;\n const read = function (): unknown {\n if (reading) return fromSnapshot(target, original, slot);\n reading = true;\n try {\n trigger();\n if (stillFrontedBy(target, slot, read)) return fromSnapshot(target, original, slot);\n return target[slot];\n } finally {\n reading = false;\n }\n };\n Object.defineProperty(target, slot, {\n configurable: true,\n // Preserve Zod's own visibility: parse/safeParse/... are enumerable own\n // properties, `~standard` is not. `is` does not exist on a Zod schema, so\n // it follows the non-enumerable convention `compile()` already uses.\n enumerable: original.get(slot)?.enumerable ?? false,\n get: read,\n set(value: unknown) {\n // Someone overwrote a method before first use (a test double, another\n // wrapper). Their value wins, and compilation is cancelled outright —\n // materializing later would restore Zod's descriptors over it.\n cancel();\n Object.defineProperty(target, slot, {\n configurable: true,\n enumerable: original.get(slot)?.enumerable ?? false,\n value,\n writable: true,\n });\n },\n });\n }\n}\n\n/**\n * Is `slot` still fronted by this very accessor — i.e. did the replacement that\n * `trigger()` was supposed to perform not take? A target that will not answer\n * the question is assumed to still hold it, since reading the slot to find out\n * is the recursion being avoided.\n */\nfunction stillFrontedBy(\n target: Record<string, unknown>,\n slot: string,\n getter: () => unknown,\n): boolean {\n try {\n return Object.getOwnPropertyDescriptor(target, slot)?.get === getter;\n } catch {\n return true;\n }\n}\n\n/**\n * What Zod had in `slot`, taken from the snapshot made before installation.\n * `undefined` for `is`, which no plain Zod schema carries — the same thing every\n * other degradation path leaves there.\n */\nfunction fromSnapshot(\n target: Record<string, unknown>,\n original: ReadonlyMap<string, PropertyDescriptor | undefined>,\n slot: string,\n): unknown {\n const descriptor = original.get(slot);\n if (descriptor === undefined) return undefined;\n // `~standard` is a lazy getter on a Zod schema, so invoke it rather than\n // reading a `value` it does not have.\n return descriptor.get === undefined ? descriptor.value : descriptor.get.call(target);\n}\n\n/**\n * Compile every Zod schema found among an object's own values — typically a\n * module namespace, so a whole schema file opts in with one call:\n *\n * ```ts\n * import * as schemas from \"./schemas.js\";\n * jitAll(schemas);\n * ```\n *\n * The namespace object itself is never written to (a module namespace is\n * read-only); `jit()` mutates the schema objects it holds, which is what every\n * importer of that module already references.\n */\nexport function jitAll(schemas: object, options?: JitOptions): void {\n for (const value of Object.values(schemas)) {\n if (isZodSchema(value)) jit(value, options);\n }\n}\n\n/** Put Zod's own descriptors back, dropping the compile-on-read accessors. */\nfunction restore(\n target: Record<string, unknown>,\n original: ReadonlyMap<string, PropertyDescriptor | undefined>,\n): void {\n for (const slot of SLOTS) {\n // Per slot, because this also runs as the rollback for a failed install: a\n // target that refuses one slot must not cost the others their restoration.\n // A slot left fronted by its accessor still reads correctly — the getter\n // serves Zod's own method from the snapshot — but it keeps a redundant\n // indirection, so restoring what can be restored is worth the try/catch.\n try {\n const descriptor = original.get(slot);\n if (descriptor === undefined) delete target[slot];\n else Object.defineProperty(target, slot, descriptor);\n } catch {\n // Nothing further to try for this slot.\n }\n }\n}\n\n/**\n * Whether runtime code generation is permitted here. Read per call, never\n * snapshotted: `z.config({ jitless: true })` runs in an entry point, after the\n * schema modules it imports have already been evaluated.\n */\nfunction codegenAllowed(): boolean {\n return zodCore.globalConfig.jitless !== true && zodCore.util.allowsEval.value;\n}\n\n/**\n * Run the pipeline and let the generated IIFE install its methods on `schema`.\n * Swallows failure: a schema that cannot be compiled keeps Zod's own methods,\n * which the caller already has, so there is nothing to report and nothing to\n * break.\n */\nfunction materialize(schema: unknown, options?: JitOptions): void {\n if (!codegenAllowed()) return;\n try {\n buildValidator(schema, options);\n } catch {\n // Left as plain Zod. Deliberately silent: `jit()` is an optimization, and a\n // schema using a construct the compiler declines is a supported outcome,\n // not an error.\n }\n}\n\n/**\n * Generate the validator and evaluate it, reproducing the module a\n * `.compiled.ts` would have been: helper preamble, the file-level shared block,\n * then the `__zcMkv` IIFE whose `__rf[]` bases and install target are the live\n * schema object passed in as `__schema`.\n */\nfunction buildValidator(schema: unknown, options?: JitOptions): void {\n const { schemas, shared } = compileSchemas([{ exportName: \"jit\", schema }], {\n compact: options?.output === \"compact\",\n mode: \"inline\",\n });\n const compiled = schemas[0];\n if (compiled === undefined) throw new Error(\"zod-compiler: schema produced no validator\");\n\n const body = [RUNTIME_PRELUDE, shared.code, `return ${generateIIFE(\"__schema\", compiled)};`].join(\n \"\\n\",\n );\n\n // The three bindings ZOD_CONFIG_IMPORT would have imported, passed in so the\n // evaluated code needs no module resolution of its own.\n // oxlint-disable-next-line no-new-func -- generating the validator IS the feature\n const factory = new Function(\n \"__zodCompilerConfig\",\n \"__zcCore\",\n \"__zcZodError\",\n \"__schema\",\n body,\n ) as (\n zodConfigFn: typeof zodConfig,\n zodCoreNs: typeof zodCore,\n zodErrorCtor: typeof ZodRealError,\n target: unknown,\n ) => unknown;\n\n factory(zodConfig, zodCore, ZodRealError, schema);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;;;;;;;;;;AAWX,MAAM,QAAQ;CAAC;CAAS;CAAa;CAAc;CAAkB;CAAM;AAAW;;AAGtF,MAAM,uBAAO,IAAI,QAAgB;;;;;;;;;;;;;;;;;;;;;;AAmCjC,SAAgB,IACd,QACA,SAC+B;CAC/B,MAAM,SAAS;CACf,IAAI,KAAK,IAAI,MAAM,GAAG,OAAO;CAC7B,KAAK,IAAI,MAAM;CAEf,IAAI,SAAS,UAAU,MAAM;EAC3B,YAAY,QAAQ,OAAO;EAC3B,OAAO;CACT;CAMA,MAAM,2BAAW,IAAI,IAA4C;CACjE,IAAI;EACF,KAAK,MAAM,QAAQ,OACjB,SAAS,IAAI,MAAM,OAAO,yBAAyB,QAAQ,IAAI,CAAC;CAEpE,QAAQ;EAIN,OAAO;CACT;CAOA,IAAI,UAAU;CACd,IAAI;EACF,iBACE,QACA,gBACM;GACJ,IAAI,CAAC,SAAS;GACd,UAAU;GACV,QAAQ,QAAQ,QAAQ;GACxB,YAAY,QAAQ,OAAO;EAC7B,SACM;GACJ,IAAI,CAAC,SAAS;GACd,UAAU;GAaV,QAAQ,QAAQ,QAAQ;EAC1B,CACF;CACF,QAAQ;EACN,UAAU;EACV,QAAQ,QAAQ,QAAQ;CAC1B;CAEA,OAAO;AACT;;;;;;;;AASA,SAAS,iBACP,QACA,UACA,SAC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ACrD,QAAQ,CAER;AAEJ;;;;;;AAOA,SAAS,iBAA0B;CACjC,OAAOA,KAAQ,aAAa,YAAY,QAAQA,KAAQ,KAAK,WAAW;AAC1E;;;;;;;AAQA,SAAS,YAAY,QAAiB,SAA4B;CAChE,IAAI,CAAC,eAAe,GAAG;CACvB,IAAI;EACF,eAAe,QAAQ,OAAO;CAChC,QAAQ,CAIR;AACF;;;;;;;AAQA,SAAS,eAAe,QAAiB,SAA4B;CACnE,MAAM,EAAE,SAAS,WAAW,eAAe,CAAC;EAAE,YAAY;EAAO;CAAO,CAAC,GAAG;EAC1E,SAAS,SAAS,WAAW;EAC7B,MAAM;CACR,CAAC;CACD,MAAM,WAAW,QAAQ;CACzB,IAAI,aAAa,KAAA,GAAW,MAAM,IAAI,MAAM,4CAA4C;CAExF,MAAM,OAAO;EAAC;EAAiB,OAAO;EAAM,UAAU,aAAa,YAAY,QAAQ,EAAE;CAAE,CAAC,CAAC,KAC3F,IACF;CAkBA,IAboB,SAClB,uBACA,YACA,gBACA,YACA,IAQI,CAAC,CAACC,QAAWD,MAAS,cAAc,MAAM;AAClD"}
1
+ {"version":3,"file":"jit.js","names":["zodCore","zodConfig"],"sources":["../src/jit.ts"],"sourcesContent":["/**\n * Runtime compilation — the same extract → codegen pipeline the build plugin\n * runs, executed in-process and evaluated through `new Function`.\n *\n * The AOT paths (unplugin, CLI) need a build step to fire. Plenty of everyday\n * code has none: `tsx server.ts`, `node --experimental-strip-types`, a Jest\n * suite, a serverless handler bundled by someone else's toolchain, a library\n * that ships schemas to consumers. There `compile()` is a no-op and every parse\n * runs plain Zod. `jit()` closes that gap — one call, no build integration,\n * measured 3-25x on everyday schemas at ~0.1-0.2 ms of one-time compilation.\n *\n * Nothing here re-implements validation: {@link compileSchemas} and\n * {@link generateIIFE} are the exact modules the plugin and CLI use, so the\n * generated validator, its Zod parity and its performance are identical to what\n * a build would have emitted. The only difference is *when* the code is\n * produced.\n *\n * Compilation is LAZY by default: `jit()` installs accessors that compile on\n * the first read of a parse method and replace themselves with the compiled\n * ones. Importing a module of 500 schemas therefore costs nothing, and a\n * serverless invocation touching three of them pays for three.\n *\n * Zod itself keeps the parse methods on the PROTOTYPE (since 4.4): each is a\n * getter that binds the method on first read and installs the bound copy as an\n * own data property, so a fresh schema carries no own `parse` / `safeParse` at\n * all, while one that has been read already does. `jit()` meets both shapes —\n * it snapshots whatever the slots hold, fronts them with its own accessors, and\n * hands back exactly what it found whenever it has to step aside.\n *\n * Runtime code generation is not always permitted — a strict CSP without\n * `unsafe-eval`, some edge runtimes. Zod v4 has the same constraint (its object\n * fast-pass is itself a `new Function`) and already exposes the two switches\n * for it: the `core.util.allowsEval` probe and `z.config({ jitless: true })`.\n * `jit()` honours both and degrades to plain Zod, so one setting governs both\n * compilers. Those targets are where the build plugin belongs anyway — it emits\n * the same validator with no runtime evaluation at all.\n */\n\nimport { config as zodConfig, core as zodCore, ZodRealError, type output, type ZodType } from \"zod\";\nimport {\n FAIL_CLASS_DECL,\n FAILZ_CLASS_DECL,\n FIN_DECL,\n FIN_DEFERRED_DECL,\n FINZ_DECL,\n generateIIFE,\n MK_VALIDATOR_DECL,\n ZOD_MSG_DECLARATION,\n} from \"./core/iife.js\";\nimport { compileSchemas } from \"./core/pipeline.js\";\nimport type { CompiledSchema } from \"./core/types.js\";\nimport { isZodSchema } from \"./is-zod-schema.js\";\n\n/**\n * The declarations `ZOD_CONFIG_IMPORT` supplies to an emitted module, minus the\n * import itself — `zod`'s three bindings arrive as parameters instead, so the\n * evaluated code has no module scope to resolve. Byte-for-byte the same helper\n * source the CLI emitter writes into a `.compiled.ts`, so a JIT validator and\n * an AOT one share their entire runtime layer.\n */\nconst RUNTIME_PRELUDE = [\n ZOD_MSG_DECLARATION,\n FAIL_CLASS_DECL,\n MK_VALIDATOR_DECL,\n FIN_DECL,\n FIN_DEFERRED_DECL,\n FAILZ_CLASS_DECL,\n FINZ_DECL,\n].join(\"\\n\");\n\n/**\n * Methods `__zcMkv` installs. Each is fronted by a compile-on-read accessor\n * until the schema materializes.\n *\n * `~standard` earns its place: Zod builds it as a closure over `_zod.run`, not\n * over the schema's `safeParse` property, so a Standard Schema consumer (tRPC,\n * Hono, TanStack Form) that never touches `safeParse` would otherwise keep\n * running plain Zod forever behind a \"compiled\" schema.\n */\nconst SLOTS = [\"parse\", \"safeParse\", \"parseAsync\", \"safeParseAsync\", \"is\", \"~standard\"] as const;\n\n/** Schemas already handed to `jit()`, so a second call is a no-op rather than a recompile. */\nconst seen = new WeakSet<object>();\n\nexport interface JitOptions {\n /**\n * Compile immediately instead of on first use. Costs ~0.1-0.2 ms per schema\n * at import time; useful for a long-lived server that would rather pay during\n * startup than on the first request, or to surface a compilation failure\n * eagerly. Default `false`.\n */\n eager?: boolean | undefined;\n /** Use compact codegen and delegate cold error production to Zod. @default \"schema\" */\n output?: \"schema\" | \"compact\" | undefined;\n}\n\n/**\n * Compile `schema` in-process and install the compiled `parse` / `safeParse` /\n * `parseAsync` / `safeParseAsync` / `is` / `~standard` on it.\n *\n * Returns the SAME object — identity-preserving exactly as the build plugin is,\n * so `.shape`, `_zod`, `instanceof`, `z.toJSONSchema()`, `.meta()` and\n * composition into a larger schema all keep working, and every existing\n * reference to the schema picks the compiled methods up.\n *\n * ```ts\n * import { z } from \"zod\";\n * import { jit } from \"zod-compiler/jit\";\n *\n * export const UserSchema = jit(z.object({ name: z.string(), email: z.email() }));\n * UserSchema.safeParse(input); // compiled on this first call\n * ```\n *\n * Schemas the compiler cannot reproduce fall back to Zod per sub-schema, the\n * same way they do at build time; a schema that cannot be compiled at all is\n * left as plain Zod.\n */\nexport function jit<T extends ZodType>(\n schema: T,\n options?: JitOptions,\n): T & CompiledSchema<output<T>> {\n const target = schema as unknown as Record<string, unknown>;\n if (seen.has(target)) return schema as T & CompiledSchema<output<T>>;\n seen.add(target);\n\n if (options?.eager === true) {\n materialize(schema, options);\n return schema as T & CompiledSchema<output<T>>;\n }\n\n // Snapshot what each slot holds before anything is installed: materialize()\n // restores it before handing the object to `__zcMkv`, so the generated code\n // sees a pristine schema — it captures the original `parseAsync` /\n // `safeParseAsync` as its throw paths, and capturing a stub there would loop\n // back into itself. An untouched schema holds NOTHING here: Zod keeps the\n // methods on the prototype and only installs a bound own copy on first read,\n // so `undefined` is the common entry and means \"back to the prototype\". A\n // schema that was read before `jit()` — or that the build plugin's `__zcMkv`\n // already materialized — carries the copies, and those go back verbatim.\n const original = new Map<string, PropertyDescriptor | undefined>();\n try {\n for (const slot of SLOTS) {\n original.set(slot, Object.getOwnPropertyDescriptor(target, slot));\n }\n } catch {\n // The target answers a descriptor query with a throw — an exotic wrapper,\n // not anything Zod built. Without a snapshot there is nothing to roll back\n // to, so install nothing and hand back the schema exactly as it came.\n return schema as T & CompiledSchema<output<T>>;\n }\n\n // Installing the accessors is the step most likely to throw rather than\n // degrade: a slot locked non-configurable (a future Zod, another wrapper) makes\n // defineProperty raise, and `jit()` is called at module scope — so an\n // unhandled throw here takes down the importing app at boot. Roll back to\n // whatever Zod had and leave the schema alone instead.\n let pending = true;\n try {\n installAccessors(\n target,\n original,\n () => {\n if (!pending) return;\n pending = false;\n restore(target, original);\n materialize(schema, options);\n },\n () => {\n if (!pending) return;\n pending = false;\n // Restore EVERY slot, not just the one being written. A left-behind\n // accessor whose trigger has been cancelled would read `target[slot]`\n // and re-enter itself — unbounded recursion, which is what a later read\n // of an untouched slot (`~standard`, from a Standard Schema consumer)\n // would otherwise hit.\n //\n // Reached only when something WRITES a slot before anything reads one: a\n // test double, another wrapper, or an AOT `safeParse` assigned directly.\n // The build plugin's own `__zcMkv` does not land here — its first\n // statement READS `parseAsync`/`safeParseAsync` to capture their\n // originals, so it triggers materialization and then overwrites the\n // compiled-by-jit methods with the compiled-by-plugin ones.\n restore(target, original);\n },\n );\n } catch {\n pending = false;\n restore(target, original);\n }\n\n return schema as T & CompiledSchema<output<T>>;\n}\n\n/**\n * Front every installed method with a compile-on-read accessor. `trigger`\n * materializes the schema, which normally replaces these accessors with the\n * compiled methods (or restores what Zod had). When that replacement does not\n * take, the getter serves Zod's own method rather than re-reading the slot —\n * see the re-entrancy note in the body.\n */\nfunction installAccessors(\n target: Record<string, unknown>,\n original: ReadonlyMap<string, PropertyDescriptor | undefined>,\n trigger: () => void,\n cancel: () => void,\n): void {\n for (const slot of SLOTS) {\n // Re-entrancy is settled structurally rather than by inspection. Reading the\n // slot again is how this getter normally hands over — to the compiled method\n // materialize() installed, or to whatever restore() put back — but the\n // handover can fail to take: a target frozen after `jit()` refuses both, and\n // a second copy of this module in the graph leaves ITS accessor on the slot,\n // so the two bounce reads between them. `trigger()` is spent by then, so\n // either way the read recurses until the stack blows. While a read is already\n // in flight, or once the accessor is known to be stranded, serve Zod's own\n // method instead: a schema that cannot be compiled still parses.\n let reading = false;\n // A stranded accessor is permanent, so what it serves is resolved once.\n let stranded: { value: unknown } | undefined;\n const serveZod = (): unknown => {\n stranded ??= { value: fromZod(target, original, slot) };\n return stranded.value;\n };\n const read = function (): unknown {\n if (reading) return serveZod();\n reading = true;\n try {\n trigger();\n if (stillFrontedBy(target, slot, read)) return serveZod();\n return target[slot];\n } finally {\n reading = false;\n }\n };\n Object.defineProperty(target, slot, {\n configurable: true,\n // Keep the schema's own-key set as it was. A slot Zod already materialized\n // is an enumerable own copy, so the accessor fronting it is enumerable too;\n // an untouched slot has no own key at all, and `is` never exists on a Zod\n // schema, so those stay out of `Object.keys` — the non-enumerable\n // convention `compile()` already uses.\n enumerable: original.get(slot)?.enumerable ?? false,\n get: read,\n set(value: unknown) {\n // Someone overwrote a method before first use (a test double, another\n // wrapper). Their value wins, and compilation is cancelled outright —\n // materializing later would restore the snapshot over it. With the\n // accessor gone the write does what it would have without `jit()`:\n // overwrite the own copy, or run Zod's prototype setter, which installs\n // one. Only a target that refused the rollback still routes here, and a\n // direct define is the one way left to honour the write.\n cancel();\n if (!stillFrontedBy(target, slot, read)) {\n target[slot] = value;\n return;\n }\n Object.defineProperty(target, slot, {\n configurable: true,\n enumerable: original.get(slot)?.enumerable ?? false,\n value,\n writable: true,\n });\n },\n });\n }\n}\n\n/**\n * Is `slot` still fronted by this very accessor — i.e. did the replacement that\n * `trigger()` was supposed to perform not take? A target that will not answer\n * the question is assumed to still hold it, since reading the slot to find out\n * is the recursion being avoided.\n */\nfunction stillFrontedBy(\n target: Record<string, unknown>,\n slot: string,\n getter: () => unknown,\n): boolean {\n try {\n return Object.getOwnPropertyDescriptor(target, slot)?.get === getter;\n } catch {\n return true;\n }\n}\n\n/**\n * Zod's own value for `slot`, bypassing the accessor that fronts it.\n *\n * A slot the snapshot holds is answered from the snapshot. One it does not hold\n * lives on the prototype, where Zod's getter binds the method to its receiver\n * and installs the bound copy as an own property — on a target that accepts\n * the install, that also replaces the stranded accessor with the copy, which is\n * the handover materialize() could not make. A target that refuses the install\n * (frozen, or a wrapper that vetoes `defineProperty`) makes Zod's getter throw\n * instead; there the read goes through a stand-in that inherits from the target,\n * so the copy lands on the stand-in and the method reaches `_zod` through the\n * chain. `undefined` for `is`, which no plain Zod schema carries — the same\n * thing every other degradation path leaves there.\n */\nfunction fromZod(\n target: Record<string, unknown>,\n original: ReadonlyMap<string, PropertyDescriptor | undefined>,\n slot: string,\n): unknown {\n const descriptor = original.get(slot);\n if (descriptor !== undefined) {\n // A snapshot can hold another accessor (a second copy of this module\n // installed first), so invoke it rather than reading a `value` it lacks.\n return descriptor.get === undefined ? descriptor.value : descriptor.get.call(target);\n }\n const proto = Object.getPrototypeOf(target) as object | null;\n if (proto === null) return undefined;\n try {\n return Reflect.get(proto, slot, target);\n } catch {\n return Reflect.get(proto, slot, Object.create(target));\n }\n}\n\n/**\n * Compile every Zod schema found among an object's own values — typically a\n * module namespace, so a whole schema file opts in with one call:\n *\n * ```ts\n * import * as schemas from \"./schemas.js\";\n * jitAll(schemas);\n * ```\n *\n * The namespace object itself is never written to (a module namespace is\n * read-only); `jit()` mutates the schema objects it holds, which is what every\n * importer of that module already references.\n */\nexport function jitAll(schemas: object, options?: JitOptions): void {\n for (const value of Object.values(schemas)) {\n if (isZodSchema(value)) jit(value, options);\n }\n}\n\n/**\n * Put back what the snapshot holds, dropping the compile-on-read accessors: the\n * own copy Zod (or the build plugin) had installed, or nothing at all, so the\n * slot reads through to Zod's prototype getter again.\n */\nfunction restore(\n target: Record<string, unknown>,\n original: ReadonlyMap<string, PropertyDescriptor | undefined>,\n): void {\n for (const slot of SLOTS) {\n // Per slot, because this also runs as the rollback for a failed install: a\n // target that refuses one slot must not cost the others their restoration.\n // A slot left fronted by its accessor still reads correctly — the getter\n // serves Zod's own method — but it keeps a redundant indirection, so\n // restoring what can be restored is worth the try/catch.\n try {\n const descriptor = original.get(slot);\n if (descriptor === undefined) delete target[slot];\n else Object.defineProperty(target, slot, descriptor);\n } catch {\n // Nothing further to try for this slot.\n }\n }\n}\n\n/**\n * Whether runtime code generation is permitted here. Read per call, never\n * snapshotted: `z.config({ jitless: true })` runs in an entry point, after the\n * schema modules it imports have already been evaluated.\n */\nfunction codegenAllowed(): boolean {\n return zodCore.globalConfig.jitless !== true && zodCore.util.allowsEval.value;\n}\n\n/**\n * Run the pipeline and let the generated IIFE install its methods on `schema`.\n * Swallows failure: a schema that cannot be compiled keeps Zod's own methods,\n * which the caller already has, so there is nothing to report and nothing to\n * break.\n */\nfunction materialize(schema: unknown, options?: JitOptions): void {\n if (!codegenAllowed()) return;\n try {\n buildValidator(schema, options);\n } catch {\n // Left as plain Zod. Deliberately silent: `jit()` is an optimization, and a\n // schema using a construct the compiler declines is a supported outcome,\n // not an error.\n }\n}\n\n/**\n * Generate the validator and evaluate it, reproducing the module a\n * `.compiled.ts` would have been: helper preamble, the file-level shared block,\n * then the `__zcMkv` IIFE whose `__rf[]` bases and install target are the live\n * schema object passed in as `__schema`.\n */\nfunction buildValidator(schema: unknown, options?: JitOptions): void {\n const { schemas, shared } = compileSchemas([{ exportName: \"jit\", schema }], {\n compact: options?.output === \"compact\",\n mode: \"inline\",\n });\n const compiled = schemas[0];\n if (compiled === undefined) throw new Error(\"zod-compiler: schema produced no validator\");\n\n const body = [RUNTIME_PRELUDE, shared.code, `return ${generateIIFE(\"__schema\", compiled)};`].join(\n \"\\n\",\n );\n\n // The three bindings ZOD_CONFIG_IMPORT would have imported, passed in so the\n // evaluated code needs no module resolution of its own.\n // oxlint-disable-next-line no-new-func -- generating the validator IS the feature\n const factory = new Function(\n \"__zodCompilerConfig\",\n \"__zcCore\",\n \"__zcZodError\",\n \"__schema\",\n body,\n ) as (\n zodConfigFn: typeof zodConfig,\n zodCoreNs: typeof zodCore,\n zodErrorCtor: typeof ZodRealError,\n target: unknown,\n ) => unknown;\n\n factory(zodConfig, zodCore, ZodRealError, schema);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,MAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;;;;;;;;;;AAWX,MAAM,QAAQ;CAAC;CAAS;CAAa;CAAc;CAAkB;CAAM;AAAW;;AAGtF,MAAM,uBAAO,IAAI,QAAgB;;;;;;;;;;;;;;;;;;;;;;AAmCjC,SAAgB,IACd,QACA,SAC+B;CAC/B,MAAM,SAAS;CACf,IAAI,KAAK,IAAI,MAAM,GAAG,OAAO;CAC7B,KAAK,IAAI,MAAM;CAEf,IAAI,SAAS,UAAU,MAAM;EAC3B,YAAY,QAAQ,OAAO;EAC3B,OAAO;CACT;CAWA,MAAM,2BAAW,IAAI,IAA4C;CACjE,IAAI;EACF,KAAK,MAAM,QAAQ,OACjB,SAAS,IAAI,MAAM,OAAO,yBAAyB,QAAQ,IAAI,CAAC;CAEpE,QAAQ;EAIN,OAAO;CACT;CAOA,IAAI,UAAU;CACd,IAAI;EACF,iBACE,QACA,gBACM;GACJ,IAAI,CAAC,SAAS;GACd,UAAU;GACV,QAAQ,QAAQ,QAAQ;GACxB,YAAY,QAAQ,OAAO;EAC7B,SACM;GACJ,IAAI,CAAC,SAAS;GACd,UAAU;GAa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 +6,7 @@ export declare const __zcFin: any;
6
6
  export declare const __zcFinD: any;
7
7
  export declare const __zcFinZ: any;
8
8
  export declare const __zcTS: any;
9
- export declare const __zcTSn: any;
9
+ export declare const __zcTSt: any;
10
10
  export declare const __zcTSx: any;
11
11
  export declare const __zcTB: any;
12
12
  export declare const __zcTBt: any;
@@ -22,6 +22,8 @@ export declare const __zcFz: any;
22
22
  export declare const __zcHop: any;
23
23
  export declare const __zcLo: any;
24
24
  export declare const __zcSo: any;
25
+ export declare const __zcCpl: any;
26
+ export declare const __zcPs: any;
25
27
  export declare const __zcPlain: any;
26
28
  export declare const __zcPfx: any;
27
29
  export declare const __zcCu: any;