zod-compiler 0.1.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,2536 @@
1
+ import ts, { factory, NodeFlags, EmitHint, TokenFlags, ScriptTarget, ScriptKind, SyntaxKind } from 'typescript';
2
+ import standalone, { ParseStatus } from './standalone.mjs';
3
+ import { _ } from '@swc/helpers/_/_apply_decs_2203_r';
4
+ import z from 'zod';
5
+ import { _ as _$1 } from '@swc/helpers/_/_identity';
6
+
7
+ function uniqueIdentifier(name) {
8
+ return factory.createUniqueName(name, ts.GeneratedIdentifierFlags.ReservedInNestedScopes);
9
+ }
10
+ function local(ident, initializer, modifiable = false) {
11
+ return factory.createVariableStatement([], factory.createVariableDeclarationList([
12
+ factory.createVariableDeclaration(ident, undefined, undefined, initializer)
13
+ ], !modifiable ? NodeFlags.Const : NodeFlags.Let));
14
+ }
15
+ function objectLiteral(obj) {
16
+ const entries = Object.entries(obj).filter(([k, v])=>!!v);
17
+ return factory.createObjectLiteralExpression(entries.map(([name, expr])=>factory.createPropertyAssignment(factory.createStringLiteral(name), expr)), entries.length > 1);
18
+ }
19
+ const IDENT_REGEX = /^[$A-Z_a-z][\w$]*$/;
20
+ function identifierOrStringLiteral(value) {
21
+ if (IDENT_REGEX.test(value)) {
22
+ return factory.createIdentifier(value);
23
+ } else {
24
+ return factory.createStringLiteral(value);
25
+ }
26
+ }
27
+ function propertyChain(start, elements) {
28
+ for (let element of elements){
29
+ if (typeof element === 'string') {
30
+ if (IDENT_REGEX.test(element)) {
31
+ start = factory.createPropertyAccessExpression(start, element);
32
+ continue;
33
+ }
34
+ element = factory.createStringLiteral(element);
35
+ }
36
+ start = factory.createElementAccessExpression(start, element);
37
+ }
38
+ return start;
39
+ }
40
+ function print(node, hint = EmitHint.Unspecified) {
41
+ const file = ts.createSourceFile('print.ts', '', ScriptTarget.ES2022, false, ScriptKind.TS);
42
+ const printer = ts.createPrinter();
43
+ return printer.printNode(hint, node, file);
44
+ }
45
+ function callHelper(verifierContext, helper, ...args) {
46
+ return factory.createCallExpression(propertyChain(verifierContext, [
47
+ 'helpers',
48
+ helper
49
+ ]), undefined, args);
50
+ }
51
+ class Path {
52
+ constructor(parts){
53
+ this.parts = parts;
54
+ }
55
+ static empty() {
56
+ return new Path([]);
57
+ }
58
+ get isEmpty() {
59
+ return this.parts.length === 0;
60
+ }
61
+ clone() {
62
+ return new Path([
63
+ ...this.parts
64
+ ]);
65
+ }
66
+ push(fragment) {
67
+ const parts = [
68
+ ...this.parts
69
+ ];
70
+ if (typeof fragment === 'string') {
71
+ parts.push(factory.createStringLiteral(fragment));
72
+ } else if (typeof fragment === 'number') {
73
+ parts.push(factory.createNumericLiteral(fragment, TokenFlags.None));
74
+ } else {
75
+ parts.push(fragment);
76
+ }
77
+ return new Path(parts);
78
+ }
79
+ serialize() {
80
+ return factory.createArrayLiteralExpression(this.parts, false);
81
+ }
82
+ }
83
+
84
+ /**
85
+ * In JavaScript, there exist two main types of values - primitives like strings, numbers, and booleans; and objects like
86
+ * arrays, `Map`s, `Set`s, and, well, *objects*. Two primitives with equal value are equal to each other: `42 === 42` and
87
+ * `"foo" === "foo"`, however ***two objects will never be equal to each other***: `{} !== {}`, `[] !== []`.
88
+ *
89
+ * Since `zod-compiler` outputs source code which is then {@linkcode eval}uated, it has to get values defined in types
90
+ * like `z.literal()` or `.default()` or `.catch()` from *somewhere*; for primitive types this is fine, and the value can
91
+ * be directly pasted into the source code. However, for objects, this can lead to unexpected behavior if you, for example,
92
+ * expect values returned by `.default()` to be equal to the original value provided in the schema definition.
93
+ *
94
+ * The default inlining mode is {@linkcode Default}, which inlines *primitives*, but not *objects*. This means that
95
+ * any object values are defined as a **dependency**; they are the *exact same values* taken from the schema definition
96
+ * that the compiled parser can use via a reference. This behavior provides the best compatibility for in-source usage of
97
+ * `zod-compiler`.
98
+ *
99
+ * For **standalone** builds, however, that would mean that you'd have to provide these dependency references to the parser.
100
+ * `zc.compile()` returns a dependency array which you could then pass to `standalone()`, though you'd have to figure
101
+ * out where those values come from and extract them out of your source tree. Alternatively, the {@linkcode InliningMode.Aggressive Aggressive}
102
+ * inlining mode *will* attempt to inline objects, arrays, `Map`s, and `Set`s. This does mean that these values would
103
+ * no longer be equivalent to their definition, but there's a good chance you don't depend on that behavior anyway.
104
+ */ var InliningMode = /*#__PURE__*/ function(InliningMode) {
105
+ /** Does not inline any values; they will all be added as dependencies. */ InliningMode[InliningMode["None"] = 0] = "None";
106
+ /** Inlines most primitives: strings, numbers, `BigInt`s, booleans, and `null`/`undefined`. */ InliningMode[InliningMode["Default"] = 1] = "Default";
107
+ /**
108
+ * Like {@linkcode InliningMode.Default Default}, but also inlines objects, arrays, `Map`s and `Set`s, and regular
109
+ * expressions.
110
+ *
111
+ * Symbols and functions cannot be inlined.
112
+ */ InliningMode[InliningMode["Aggressive"] = 2] = "Aggressive";
113
+ return InliningMode;
114
+ }({});
115
+ class Dependencies {
116
+ constructor(verifierContext, inliningMode){
117
+ this.verifierContext = verifierContext;
118
+ this.inliningMode = inliningMode;
119
+ this._dependencies = [];
120
+ }
121
+ add(value) {
122
+ const i = this._dependencies.push(value) - 1;
123
+ return propertyChain(this.verifierContext, [
124
+ 'dependencies',
125
+ i
126
+ ]);
127
+ }
128
+ addOrInline(value) {
129
+ if (this.inliningMode === 0) {
130
+ return this.add(value);
131
+ }
132
+ const expr = toLiteral(value, this.inliningMode);
133
+ if (expr === null) {
134
+ return this.add(value);
135
+ }
136
+ return expr;
137
+ }
138
+ get dependencies() {
139
+ return this._dependencies;
140
+ }
141
+ }
142
+ class AbstractGeneratorContextWithExprs {
143
+ constructor(input, output, verifierContext, dependencies){
144
+ this._input = input;
145
+ this._output = output;
146
+ this._verifierContext = verifierContext;
147
+ this._dependencies = dependencies;
148
+ }
149
+ get input() {
150
+ return this._input;
151
+ }
152
+ get output() {
153
+ return this._output;
154
+ }
155
+ get dependencies() {
156
+ return this._dependencies;
157
+ }
158
+ get verifierContext() {
159
+ return this._verifierContext;
160
+ }
161
+ *prelude() {}
162
+ *postlude() {}
163
+ *outputs(expr) {
164
+ yield factory.createExpressionStatement(factory.createAssignment(this._output, expr));
165
+ }
166
+ *report(issue, input = this.input) {
167
+ yield factory.createExpressionStatement(factory.createCallExpression(propertyChain(this.verifierContext, [
168
+ 'reportIssue'
169
+ ]), undefined, [
170
+ issue,
171
+ input
172
+ ]));
173
+ }
174
+ }
175
+ class AbstractGeneratorContextWithExprsAndStatusVar extends AbstractGeneratorContextWithExprs {
176
+ *prelude() {
177
+ yield factory.createVariableStatement([], factory.createVariableDeclarationList([
178
+ factory.createVariableDeclaration(this.statusVar, undefined, undefined, factory.createNumericLiteral(ParseStatus.VALID))
179
+ ], NodeFlags.Let));
180
+ }
181
+ constructor(...args){
182
+ super(...args), this.statusVar = uniqueIdentifier('status');
183
+ }
184
+ }
185
+ class FunctionalGeneratorContext extends AbstractGeneratorContextWithExprsAndStatusVar {
186
+ *postlude() {
187
+ yield factory.createReturnStatement(this.statusVar);
188
+ }
189
+ *status(status, allowShortCircuiting = true) {
190
+ if (typeof status === 'number') {
191
+ if (status === ParseStatus.INVALID && allowShortCircuiting) {
192
+ yield factory.createReturnStatement(factory.createNumericLiteral(status));
193
+ } else {
194
+ yield factory.createExpressionStatement(factory.createBinaryExpression(this.statusVar, SyntaxKind.BarEqualsToken, factory.createNumericLiteral(status)));
195
+ }
196
+ } else {
197
+ if (allowShortCircuiting) {
198
+ yield factory.createIfStatement(factory.createBitwiseAnd(status, factory.createNumericLiteral(ParseStatus.INVALID)), factory.createReturnStatement(status));
199
+ }
200
+ yield factory.createExpressionStatement(factory.createBinaryExpression(this.statusVar, SyntaxKind.BarEqualsToken, status));
201
+ }
202
+ }
203
+ withInput(expr) {
204
+ const x = new FunctionalGeneratorContext(expr, this.output, this.verifierContext, this.dependencies);
205
+ x.statusVar = this.statusVar;
206
+ return x;
207
+ }
208
+ }
209
+ var LabeledShortCircuitMode = /*#__PURE__*/ function(LabeledShortCircuitMode) {
210
+ LabeledShortCircuitMode[LabeledShortCircuitMode["Continue"] = 0] = "Continue";
211
+ LabeledShortCircuitMode[LabeledShortCircuitMode["Break"] = 1] = "Break";
212
+ return LabeledShortCircuitMode;
213
+ }({});
214
+ class LabeledBlockScopeGeneratorContext extends AbstractGeneratorContextWithExprsAndStatusVar {
215
+ constructor(mode, label, input, output, verifierContext, dependencies){
216
+ super(input, output, verifierContext, dependencies), this.mode = mode, this.label = label;
217
+ }
218
+ *status(status, allowShortCircuiting = true) {
219
+ yield factory.createExpressionStatement(factory.createBinaryExpression(this.statusVar, SyntaxKind.BarEqualsToken, typeof status === 'number' ? factory.createNumericLiteral(status) : status));
220
+ if (allowShortCircuiting) {
221
+ const shortCircuit = ()=>{
222
+ switch(this.mode){
223
+ case 1:
224
+ return factory.createBreakStatement(this.label);
225
+ case 0:
226
+ return factory.createContinueStatement(this.label);
227
+ }
228
+ };
229
+ if (status === ParseStatus.INVALID) {
230
+ yield shortCircuit();
231
+ } else {
232
+ yield factory.createIfStatement(factory.createBitwiseAnd(this.statusVar, factory.createNumericLiteral(ParseStatus.INVALID)), shortCircuit());
233
+ }
234
+ }
235
+ }
236
+ withInput(expr) {
237
+ const x = new LabeledBlockScopeGeneratorContext(this.mode, this.label, expr, this.output, this.verifierContext, this.dependencies);
238
+ x.statusVar = this.statusVar;
239
+ return x;
240
+ }
241
+ }
242
+ function toLiteral(value, mode) {
243
+ switch(typeof value){
244
+ case 'string':
245
+ return factory.createStringLiteral(value);
246
+ case 'number':
247
+ return factory.createNumericLiteral(value);
248
+ case 'bigint':
249
+ return factory.createBigIntLiteral(value.toString());
250
+ case 'undefined':
251
+ return factory.createIdentifier('undefined');
252
+ case 'boolean':
253
+ return value ? factory.createTrue() : factory.createFalse();
254
+ case 'object':
255
+ if (value === null) {
256
+ return factory.createNull();
257
+ }
258
+ if (mode === 2) {
259
+ if (value instanceof RegExp) {
260
+ return factory.createRegularExpressionLiteral(value.toString());
261
+ } else if (value instanceof Map) {
262
+ return factory.createNewExpression(factory.createIdentifier('Map'), undefined, [
263
+ factory.createArrayLiteralExpression([
264
+ ...value.entries()
265
+ ].map(([k, v])=>factory.createArrayLiteralExpression([
266
+ toLiteral(k, mode),
267
+ toLiteral(v, mode)
268
+ ])))
269
+ ]);
270
+ } else if (value instanceof Set) {
271
+ return factory.createNewExpression(factory.createIdentifier('Set'), undefined, [
272
+ factory.createArrayLiteralExpression([
273
+ ...value.values()
274
+ ].map((v)=>toLiteral(v, mode)))
275
+ ]);
276
+ } else if (Array.isArray(value)) {
277
+ return factory.createArrayLiteralExpression(value.map((v)=>toLiteral(v, mode)));
278
+ } else if (value instanceof Date) {
279
+ return factory.createNewExpression(factory.createIdentifier('Date'), undefined, [
280
+ factory.createNumericLiteral(value.getTime())
281
+ ]);
282
+ } else if (value.constructor === Object) {
283
+ return factory.createObjectLiteralExpression(Object.entries(value).map(([k, v])=>factory.createPropertyAssignment(identifierOrStringLiteral(k), toLiteral(v, mode))));
284
+ } else {
285
+ throw new Error(`Value cannot be inlined: ${value}`);
286
+ }
287
+ }
288
+ break;
289
+ case 'function':
290
+ case 'symbol':
291
+ if (mode === 2) {
292
+ throw new Error(`${typeof value === 'function' ? 'Functions' : 'Symbols'} cannot be inlined`);
293
+ }
294
+ break;
295
+ }
296
+ return null;
297
+ }
298
+
299
+ class AbstractCompiledType {
300
+ constructor(type){
301
+ this.type = type;
302
+ }
303
+ }
304
+ const registry = new Map();
305
+ function register(zodType) {
306
+ return function(constructor, _context) {
307
+ registry.set(zodType, constructor);
308
+ };
309
+ }
310
+ function compilable(type) {
311
+ const typeName = type._def.typeName;
312
+ if (typeName === undefined) {
313
+ throw new TypeError('Third-party Zod types are not supported');
314
+ }
315
+ const base = registry.get(typeName);
316
+ if (!base) {
317
+ throw new TypeError(`Unimplemented Zod type \`z.${typeName}\``);
318
+ }
319
+ return new base(type);
320
+ }
321
+
322
+ // Mirrors ZodParsedType from src/helpers/util.ts
323
+ // Mirrors getParsedType from src/helpers/util.ts
324
+ function typeOf(data) {
325
+ switch(typeof data){
326
+ case 'undefined':
327
+ return "undefined";
328
+ case 'string':
329
+ return "string";
330
+ case 'number':
331
+ return isNaN(data) ? "nan" : "number";
332
+ case 'boolean':
333
+ return "boolean";
334
+ case 'function':
335
+ return "function";
336
+ case 'bigint':
337
+ return "bigint";
338
+ case 'symbol':
339
+ return "symbol";
340
+ case 'object':
341
+ if (Array.isArray(data)) {
342
+ return "array";
343
+ }
344
+ if (data === null) {
345
+ return "null";
346
+ }
347
+ if (typeof data.then === 'function' && typeof data.catch === 'function') {
348
+ return "promise";
349
+ }
350
+ if (data instanceof Map) {
351
+ return "map";
352
+ }
353
+ if (data instanceof Set) {
354
+ return "set";
355
+ }
356
+ if (data instanceof Date) {
357
+ return "date";
358
+ }
359
+ return "object";
360
+ default:
361
+ return "unknown";
362
+ }
363
+ }
364
+ function stringify(obj) {
365
+ return JSON.stringify(obj, (_, value)=>{
366
+ if (typeof value === 'bigint') {
367
+ return value.toString();
368
+ }
369
+ return value;
370
+ }, 2 /* ugggghhhhhhhh */ );
371
+ }
372
+ function joinValues(array, separator = ' | ') {
373
+ return array.map((val)=>typeof val === 'string' ? `'${val}'` : val).join(separator);
374
+ }
375
+
376
+ class ZcError extends Error {
377
+ get errors() {
378
+ return this.issues;
379
+ }
380
+ constructor(issues){
381
+ super(), this.issues = issues;
382
+ // TODO: why is this required?
383
+ const actualProto = new.target.prototype;
384
+ Object.setPrototypeOf(this, actualProto);
385
+ this.name = 'ZcError';
386
+ }
387
+ format(_mapper) {
388
+ const mapper = _mapper ?? ((issue)=>issue.message);
389
+ const fieldErrors = {
390
+ _errors: []
391
+ };
392
+ const processError = (error)=>{
393
+ for (const issue of error.issues){
394
+ if (issue.code === "invalid_union") {
395
+ issue.unionErrors.map(processError);
396
+ } else if (issue.code === "invalid_return_type") {
397
+ processError(issue.returnTypeError);
398
+ } else if (issue.code === "invalid_arguments") {
399
+ processError(issue.argumentsError);
400
+ } else if (issue.path.length === 0) {
401
+ fieldErrors._errors.push(mapper(issue));
402
+ } else {
403
+ let curr = fieldErrors;
404
+ let i = 0;
405
+ while(i < issue.path.length){
406
+ const el = issue.path[i];
407
+ curr[el] ||= {
408
+ _errors: []
409
+ };
410
+ const terminal = i === issue.path.length - 1;
411
+ if (terminal) {
412
+ curr[el]._errors.push(mapper(issue));
413
+ }
414
+ curr = curr[el];
415
+ i++;
416
+ }
417
+ }
418
+ }
419
+ };
420
+ processError(this);
421
+ return fieldErrors;
422
+ }
423
+ static create(issues) {
424
+ return new ZcError(issues);
425
+ }
426
+ toString() {
427
+ return this.message;
428
+ }
429
+ get message() {
430
+ return stringify(this.issues);
431
+ }
432
+ get isEmpty() {
433
+ return this.issues.length === 0;
434
+ }
435
+ addIssue(sub) {
436
+ // why not push...?
437
+ this.issues = [
438
+ ...this.issues,
439
+ sub
440
+ ];
441
+ }
442
+ addIssues(subs = []) {
443
+ this.issues = [
444
+ ...this.issues,
445
+ ...subs
446
+ ];
447
+ }
448
+ flatten(mapper = (issue)=>issue.message) {
449
+ const fieldErrors = {};
450
+ const formErrors = [];
451
+ for (const sub of this.issues){
452
+ if (sub.path.length > 0) {
453
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
454
+ fieldErrors[sub.path[0]].push(mapper(sub));
455
+ } else {
456
+ formErrors.push(mapper(sub));
457
+ }
458
+ }
459
+ return {
460
+ formErrors,
461
+ fieldErrors
462
+ };
463
+ }
464
+ get formErrors() {
465
+ return this.flatten(); //.formErrors?;
466
+ }
467
+ }
468
+
469
+ var _dec$u, _initClass$u, _AbstractCompiledType$u;
470
+ let _ZcAny;
471
+ _dec$u = register(z.ZodFirstPartyTypeKind.ZodAny);
472
+ class ZcAny extends (_AbstractCompiledType$u = AbstractCompiledType) {
473
+ static{
474
+ ({ c: [_ZcAny, _initClass$u] } = _(this, [], [
475
+ _dec$u
476
+ ], _AbstractCompiledType$u));
477
+ }
478
+ compileType() {
479
+ return factory.createKeywordTypeNode(SyntaxKind.AnyKeyword);
480
+ }
481
+ *compileParser(ctx, path) {
482
+ yield* ctx.outputs(ctx.input);
483
+ }
484
+ static{
485
+ _initClass$u();
486
+ }
487
+ }
488
+
489
+ var _dec$t, _initClass$t, _AbstractCompiledType$t;
490
+ class ArrayGeneratorContext extends LabeledBlockScopeGeneratorContext {
491
+ constructor(input, output, verifierContext, dependencies, parentStatusSetter){
492
+ super(LabeledShortCircuitMode.Continue, undefined, input, output, verifierContext, dependencies), this.parentStatusSetter = parentStatusSetter;
493
+ }
494
+ *prelude() {}
495
+ *status(status, allowShortCircuiting = true) {
496
+ yield* this.parentStatusSetter(typeof status === 'number' ? factory.createNumericLiteral(status) : status);
497
+ if (allowShortCircuiting) {
498
+ if (status === ParseStatus.INVALID) {
499
+ yield factory.createContinueStatement();
500
+ } else if (typeof status !== 'number') {
501
+ yield factory.createIfStatement(factory.createBitwiseAnd(status, factory.createNumericLiteral(ParseStatus.INVALID)), factory.createContinueStatement());
502
+ }
503
+ }
504
+ }
505
+ withInput(expr) {
506
+ const x = new ArrayGeneratorContext(expr, this.output, this.verifierContext, this.dependencies, this.parentStatusSetter);
507
+ x.statusVar = this.statusVar;
508
+ return x;
509
+ }
510
+ }
511
+ let _ZcArray;
512
+ _dec$t = register(z.ZodFirstPartyTypeKind.ZodArray);
513
+ class ZcArray extends (_AbstractCompiledType$t = AbstractCompiledType) {
514
+ static{
515
+ ({ c: [_ZcArray, _initClass$t] } = _(this, [], [
516
+ _dec$t
517
+ ], _AbstractCompiledType$t));
518
+ }
519
+ compileType() {
520
+ return factory.createArrayTypeNode(compilable(this.type._def.type).compileType());
521
+ }
522
+ *compileParser(ctx, path) {
523
+ yield factory.createIfStatement(factory.createLogicalNot(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier('Array'), 'isArray'), undefined, [
524
+ ctx.input
525
+ ])), factory.createBlock([
526
+ ...ctx.report(objectLiteral({
527
+ path: path.serialize(),
528
+ code: factory.createStringLiteral('invalid_type'),
529
+ expected: factory.createStringLiteral('array'),
530
+ received: callHelper(ctx.verifierContext, 'typeOf', ctx.input)
531
+ })),
532
+ ...ctx.status(ParseStatus.INVALID)
533
+ ], true));
534
+ if (this.type._def.exactLength !== null) {
535
+ const value = factory.createNumericLiteral(this.type._def.exactLength.value);
536
+ const lengthAccessor = factory.createPropertyAccessExpression(ctx.input, 'length');
537
+ const tooBigIdent = uniqueIdentifier('tooBig');
538
+ const tooSmallIdent = uniqueIdentifier('tooSmall');
539
+ yield factory.createIfStatement(factory.createStrictInequality(lengthAccessor, value), factory.createBlock([
540
+ local(tooBigIdent, factory.createGreaterThan(lengthAccessor, value)),
541
+ local(tooSmallIdent, factory.createLessThan(lengthAccessor, value)),
542
+ ...ctx.report(objectLiteral({
543
+ path: path.serialize(),
544
+ code: factory.createConditionalExpression(tooBigIdent, undefined, factory.createStringLiteral('too_big'), undefined, factory.createStringLiteral('too_small')),
545
+ minimum: factory.createConditionalExpression(tooSmallIdent, undefined, value, undefined, factory.createIdentifier('undefined')),
546
+ maximum: factory.createConditionalExpression(tooBigIdent, undefined, value, undefined, factory.createIdentifier('undefined')),
547
+ type: factory.createStringLiteral('array'),
548
+ inclusive: factory.createTrue(),
549
+ exact: factory.createTrue(),
550
+ message: this.type._def.exactLength.message ? factory.createStringLiteral(this.type._def.exactLength.message) : undefined
551
+ })),
552
+ ...ctx.status(ParseStatus.DIRTY)
553
+ ], true));
554
+ }
555
+ if (this.type._def.minLength !== null) {
556
+ yield factory.createIfStatement(factory.createLessThan(factory.createPropertyAccessExpression(ctx.input, 'length'), factory.createNumericLiteral(this.type._def.minLength.value)), factory.createBlock([
557
+ ...ctx.report(objectLiteral({
558
+ path: path.serialize(),
559
+ code: factory.createStringLiteral('too_small'),
560
+ minimum: factory.createNumericLiteral(this.type._def.minLength.value),
561
+ type: factory.createStringLiteral('array'),
562
+ inclusive: factory.createTrue(),
563
+ exact: factory.createFalse(),
564
+ message: this.type._def.minLength.message ? factory.createStringLiteral(this.type._def.minLength.message) : undefined
565
+ })),
566
+ ...ctx.status(ParseStatus.DIRTY)
567
+ ], true));
568
+ }
569
+ if (this.type._def.maxLength !== null) {
570
+ yield factory.createIfStatement(factory.createGreaterThan(factory.createPropertyAccessExpression(ctx.input, 'length'), factory.createNumericLiteral(this.type._def.maxLength.value)), factory.createBlock([
571
+ ...ctx.report(objectLiteral({
572
+ path: path.serialize(),
573
+ code: factory.createStringLiteral('too_big'),
574
+ minimum: factory.createNumericLiteral(this.type._def.maxLength.value),
575
+ type: factory.createStringLiteral('array'),
576
+ inclusive: factory.createTrue(),
577
+ exact: factory.createFalse(),
578
+ message: this.type._def.maxLength.message ? factory.createStringLiteral(this.type._def.maxLength.message) : undefined
579
+ })),
580
+ ...ctx.status(ParseStatus.DIRTY)
581
+ ], true));
582
+ }
583
+ const output = uniqueIdentifier('outputArray');
584
+ yield local(output, factory.createNewExpression(factory.createIdentifier('Array'), undefined, [
585
+ factory.createPropertyAccessExpression(ctx.input, 'length')
586
+ ]));
587
+ const indexInitializer = factory.createLoopVariable(true);
588
+ const elInitializer = uniqueIdentifier('el');
589
+ const elOutput = factory.createElementAccessExpression(output, indexInitializer);
590
+ const childCtx = new ArrayGeneratorContext(elInitializer, elOutput, ctx.verifierContext, ctx.dependencies, (status)=>ctx.status(status, false));
591
+ yield factory.createForOfStatement(undefined, factory.createVariableDeclarationList([
592
+ factory.createVariableDeclaration(factory.createArrayBindingPattern([
593
+ factory.createBindingElement(undefined, undefined, indexInitializer),
594
+ factory.createBindingElement(undefined, undefined, elInitializer)
595
+ ]))
596
+ ], NodeFlags.Const), factory.createCallExpression(factory.createPropertyAccessExpression(ctx.input, 'entries'), undefined, undefined), factory.createBlock([
597
+ ...childCtx.prelude(),
598
+ ...compilable(this.type._def.type).compileParser(childCtx, path.push(indexInitializer)),
599
+ ...childCtx.postlude()
600
+ ]));
601
+ yield* ctx.outputs(output);
602
+ }
603
+ static{
604
+ _initClass$t();
605
+ }
606
+ }
607
+
608
+ var _dec$s, _initClass$s, _AbstractCompiledType$s;
609
+ let _ZcBigInt;
610
+ _dec$s = register(z.ZodFirstPartyTypeKind.ZodBigInt);
611
+ class ZcBigInt extends (_AbstractCompiledType$s = AbstractCompiledType) {
612
+ static{
613
+ ({ c: [_ZcBigInt, _initClass$s] } = _(this, [], [
614
+ _dec$s
615
+ ], _AbstractCompiledType$s));
616
+ }
617
+ compileType() {
618
+ return factory.createKeywordTypeNode(SyntaxKind.BigIntKeyword);
619
+ }
620
+ *compileParser(ctx, path) {
621
+ let input = ctx.input;
622
+ if (this.type._def.coerce) {
623
+ const ident = uniqueIdentifier('coercedInput');
624
+ yield local(ident, undefined, true);
625
+ input = ident;
626
+ yield factory.createTryStatement(factory.createBlock([
627
+ factory.createExpressionStatement(factory.createAssignment(ident, factory.createCallExpression(factory.createIdentifier('BigInt'), undefined, [
628
+ ctx.input
629
+ ])))
630
+ ], true), factory.createCatchClause(uniqueIdentifier('e'), factory.createBlock([
631
+ ...ctx.report(objectLiteral({
632
+ path: path.serialize(),
633
+ code: factory.createStringLiteral('invalid_type'),
634
+ expected: factory.createStringLiteral('bigint'),
635
+ received: callHelper(ctx.verifierContext, 'typeOf', input)
636
+ }), input),
637
+ // hopefully this causes a short circuit and the rest of the body doesn't get executed...
638
+ ...ctx.status(ParseStatus.INVALID)
639
+ ], true)), undefined);
640
+ }
641
+ let stmt = factory.createIfStatement(factory.createStrictInequality(factory.createTypeOfExpression(input), factory.createStringLiteral('bigint')), factory.createBlock([
642
+ ...ctx.report(objectLiteral({
643
+ path: path.serialize(),
644
+ code: factory.createStringLiteral('invalid_type'),
645
+ expected: factory.createStringLiteral('bigint'),
646
+ received: callHelper(ctx.verifierContext, 'typeOf', input)
647
+ }), input),
648
+ ...ctx.status(ParseStatus.INVALID)
649
+ ], true));
650
+ const checkStmts = [];
651
+ for (const check of this.type._def.checks){
652
+ switch(check.kind){
653
+ case 'min':
654
+ checkStmts.push(factory.createIfStatement(factory[check.inclusive ? 'createLessThan' : 'createLessThanEquals'](input, factory.createBigIntLiteral(check.value.toString())), factory.createBlock([
655
+ ...ctx.report(objectLiteral({
656
+ path: path.serialize(),
657
+ code: factory.createStringLiteral('too_small'),
658
+ minimum: factory.createBigIntLiteral(check.value.toString()),
659
+ type: factory.createStringLiteral('bigint'),
660
+ inclusive: check.inclusive ? factory.createTrue() : factory.createFalse(),
661
+ exact: factory.createFalse(),
662
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
663
+ }), input),
664
+ ...ctx.status(ParseStatus.DIRTY)
665
+ ], true)));
666
+ break;
667
+ case 'max':
668
+ checkStmts.push(factory.createIfStatement(factory[check.inclusive ? 'createGreaterThan' : 'createGreaterThanEquals'](input, factory.createBigIntLiteral(check.value.toString())), factory.createBlock([
669
+ ...ctx.report(objectLiteral({
670
+ path: path.serialize(),
671
+ code: factory.createStringLiteral('too_big'),
672
+ minimum: factory.createBigIntLiteral(check.value.toString()),
673
+ type: factory.createStringLiteral('bigint'),
674
+ inclusive: check.inclusive ? factory.createTrue() : factory.createFalse(),
675
+ exact: factory.createFalse(),
676
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
677
+ }), input),
678
+ ...ctx.status(ParseStatus.DIRTY)
679
+ ], true)));
680
+ break;
681
+ case 'multipleOf':
682
+ checkStmts.push(factory.createIfStatement(factory.createStrictInequality(factory.createModulo(input, factory.createBigIntLiteral(check.value.toString())), factory.createBigIntLiteral('0')), factory.createBlock([
683
+ ...ctx.report(objectLiteral({
684
+ path: path.serialize(),
685
+ code: factory.createStringLiteral('not_multiple_of'),
686
+ multipleOf: factory.createBigIntLiteral(check.value.toString()),
687
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
688
+ }), input),
689
+ ...ctx.status(ParseStatus.DIRTY)
690
+ ], true)));
691
+ break;
692
+ default:
693
+ throw new Error(`Unsupported ZcBigInt check: ${check}`);
694
+ }
695
+ }
696
+ if (checkStmts.length === 0) {
697
+ yield stmt;
698
+ } else {
699
+ stmt = factory.updateIfStatement(stmt, stmt.expression, stmt.thenStatement, factory.createBlock([
700
+ ...checkStmts
701
+ ], true));
702
+ yield stmt;
703
+ }
704
+ yield* ctx.outputs(input);
705
+ }
706
+ static{
707
+ _initClass$s();
708
+ }
709
+ }
710
+
711
+ var _dec$r, _initClass$r, _AbstractCompiledType$r;
712
+ let _ZcBoolean;
713
+ _dec$r = register(z.ZodFirstPartyTypeKind.ZodBoolean);
714
+ class ZcBoolean extends (_AbstractCompiledType$r = AbstractCompiledType) {
715
+ static{
716
+ ({ c: [_ZcBoolean, _initClass$r] } = _(this, [], [
717
+ _dec$r
718
+ ], _AbstractCompiledType$r));
719
+ }
720
+ compileType() {
721
+ return factory.createKeywordTypeNode(SyntaxKind.BooleanKeyword);
722
+ }
723
+ *compileParser(ctx, path) {
724
+ let input = ctx.input;
725
+ if (this.type._def.coerce) {
726
+ const ident = uniqueIdentifier('coercedInput');
727
+ yield local(ident, factory.createCallExpression(factory.createIdentifier('Boolean'), [], [
728
+ ctx.input
729
+ ]), false);
730
+ input = ident;
731
+ }
732
+ yield factory.createIfStatement(factory.createStrictInequality(factory.createTypeOfExpression(input), factory.createStringLiteral('boolean')), factory.createBlock([
733
+ ...ctx.report(objectLiteral({
734
+ path: path.serialize(),
735
+ code: factory.createStringLiteral('invalid_type'),
736
+ expected: factory.createStringLiteral('boolean'),
737
+ received: callHelper(ctx.verifierContext, 'typeOf', ctx.input)
738
+ }), input),
739
+ ...ctx.status(ParseStatus.INVALID)
740
+ ], true));
741
+ yield* ctx.outputs(ctx.input);
742
+ }
743
+ static{
744
+ _initClass$r();
745
+ }
746
+ }
747
+
748
+ var _dec$q, _initClass$q, _AbstractCompiledType$q;
749
+ let _ZcBranded;
750
+ _dec$q = register(z.ZodFirstPartyTypeKind.ZodBranded);
751
+ class ZcBranded extends (_AbstractCompiledType$q = AbstractCompiledType) {
752
+ static{
753
+ ({ c: [_ZcBranded, _initClass$q] } = _(this, [], [
754
+ _dec$q
755
+ ], _AbstractCompiledType$q));
756
+ }
757
+ compileType() {
758
+ return compilable(this.type._def.type).compileType();
759
+ }
760
+ *compileParser(ctx, path) {
761
+ yield* compilable(this.type._def.type).compileParser(ctx, path);
762
+ }
763
+ static{
764
+ _initClass$q();
765
+ }
766
+ }
767
+
768
+ var _dec$p, _initClass$p, _AbstractCompiledType$p;
769
+ class CatchGeneratorContext extends LabeledBlockScopeGeneratorContext {
770
+ constructor(label, input, output, verifierContext, dependencies, statusVar){
771
+ super(LabeledShortCircuitMode.Break, label, input, output, verifierContext, dependencies);
772
+ this.statusVar = statusVar;
773
+ }
774
+ *prelude() {}
775
+ withInput(expr) {
776
+ const x = new CatchGeneratorContext(this.label, expr, this.output, this.verifierContext, this.dependencies, this.statusVar);
777
+ x.statusVar = this.statusVar;
778
+ return x;
779
+ }
780
+ }
781
+ let _ZcCatch;
782
+ _dec$p = register(z.ZodFirstPartyTypeKind.ZodCatch);
783
+ class ZcCatch extends (_AbstractCompiledType$p = AbstractCompiledType) {
784
+ static{
785
+ ({ c: [_ZcCatch, _initClass$p] } = _(this, [], [
786
+ _dec$p
787
+ ], _AbstractCompiledType$p));
788
+ }
789
+ compileType() {
790
+ return compilable(this.type._def.innerType).compileType();
791
+ }
792
+ *compileParser(ctx, path) {
793
+ const caughtStatus = uniqueIdentifier('caughtStatus');
794
+ yield local(caughtStatus, factory.createNumericLiteral(ParseStatus.VALID), true);
795
+ const output = uniqueIdentifier('caughtOutput');
796
+ yield local(output, undefined, true);
797
+ const verifierCtxVar = uniqueIdentifier('variantCtx');
798
+ yield local(verifierCtxVar, factory.createObjectLiteralExpression([
799
+ factory.createSpreadAssignment(ctx.verifierContext),
800
+ factory.createPropertyAssignment('issues', factory.createArrayLiteralExpression())
801
+ ], true));
802
+ const label = uniqueIdentifier('catch');
803
+ const childCtx = new CatchGeneratorContext(label, ctx.input, output, verifierCtxVar, ctx.dependencies, caughtStatus);
804
+ const catchValue = ctx.dependencies.addOrInline(this.type._def.catchValue(null));
805
+ yield factory.createLabeledStatement(label, factory.createBlock([
806
+ ...childCtx.prelude(),
807
+ ...compilable(this.type._def.innerType).compileParser(childCtx, path),
808
+ ...childCtx.postlude()
809
+ ]));
810
+ yield factory.createIfStatement(factory.createStrictInequality(caughtStatus, factory.createNumericLiteral(ParseStatus.VALID)), factory.createBlock([
811
+ ...ctx.outputs(catchValue)
812
+ ], true), factory.createBlock([
813
+ ...ctx.outputs(output)
814
+ ], true));
815
+ }
816
+ static{
817
+ _initClass$p();
818
+ }
819
+ }
820
+
821
+ var _dec$o, _initClass$o, _AbstractCompiledType$o;
822
+ let _ZcDate;
823
+ _dec$o = register(z.ZodFirstPartyTypeKind.ZodDate);
824
+ class ZcDate extends (_AbstractCompiledType$o = AbstractCompiledType) {
825
+ static{
826
+ ({ c: [_ZcDate, _initClass$o] } = _(this, [], [
827
+ _dec$o
828
+ ], _AbstractCompiledType$o));
829
+ }
830
+ compileType() {
831
+ return factory.createTypeReferenceNode('Date');
832
+ }
833
+ *compileParser(ctx, path) {
834
+ let input = ctx.input;
835
+ if (this.type._def.coerce) {
836
+ const ident = uniqueIdentifier('coercedInput');
837
+ yield local(ident, factory.createNewExpression(factory.createIdentifier('Date'), [], [
838
+ ctx.input
839
+ ]), false);
840
+ input = ident;
841
+ }
842
+ let stmt = factory.createIfStatement(factory.createLogicalNot(factory.createBinaryExpression(input, SyntaxKind.InstanceOfKeyword, factory.createIdentifier('Date'))), factory.createBlock([
843
+ ...ctx.report(objectLiteral({
844
+ path: path.serialize(),
845
+ code: factory.createStringLiteral('invalid_type'),
846
+ expected: factory.createStringLiteral('date'),
847
+ received: callHelper(ctx.verifierContext, 'typeOf', input)
848
+ }), input),
849
+ ...ctx.status(ParseStatus.INVALID)
850
+ ], true));
851
+ const timeVar = uniqueIdentifier('time');
852
+ const checkStmts = [
853
+ local(timeVar, factory.createCallExpression(factory.createPropertyAccessExpression(input, 'getTime'), undefined, [])),
854
+ factory.createIfStatement(factory.createCallExpression(factory.createIdentifier('isNaN'), undefined, [
855
+ timeVar
856
+ ]), factory.createBlock([
857
+ ...ctx.report(objectLiteral({
858
+ path: path.serialize(),
859
+ code: factory.createStringLiteral('invalid_date')
860
+ }), input),
861
+ ...ctx.status(ParseStatus.INVALID)
862
+ ], true))
863
+ ];
864
+ for (const check of this.type._def.checks){
865
+ switch(check.kind){
866
+ case 'min':
867
+ checkStmts.push(factory.createIfStatement(factory.createLessThan(timeVar, factory.createNumericLiteral(check.value)), factory.createBlock([
868
+ ...ctx.report(objectLiteral({
869
+ path: path.serialize(),
870
+ code: factory.createStringLiteral('too_small'),
871
+ minimum: factory.createNumericLiteral(check.value),
872
+ type: factory.createStringLiteral('date'),
873
+ inclusive: factory.createTrue(),
874
+ exact: factory.createFalse(),
875
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
876
+ }), input),
877
+ ...ctx.status(ParseStatus.DIRTY)
878
+ ], true)));
879
+ break;
880
+ case 'max':
881
+ checkStmts.push(factory.createIfStatement(factory.createGreaterThan(timeVar, factory.createNumericLiteral(check.value)), factory.createBlock([
882
+ ...ctx.report(objectLiteral({
883
+ path: path.serialize(),
884
+ code: factory.createStringLiteral('too_big'),
885
+ minimum: factory.createNumericLiteral(check.value),
886
+ type: factory.createStringLiteral('date'),
887
+ inclusive: factory.createTrue(),
888
+ exact: factory.createFalse(),
889
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
890
+ }), input),
891
+ ...ctx.status(ParseStatus.DIRTY)
892
+ ], true)));
893
+ break;
894
+ default:
895
+ throw new Error(`Unsupported ZcDate check: ${check}`);
896
+ }
897
+ }
898
+ yield factory.updateIfStatement(stmt, stmt.expression, stmt.thenStatement, factory.createBlock([
899
+ ...checkStmts
900
+ ], true));
901
+ yield* ctx.outputs(input);
902
+ }
903
+ static{
904
+ _initClass$o();
905
+ }
906
+ }
907
+
908
+ var _dec$n, _initClass$n, _AbstractCompiledType$n;
909
+ let _ZcDefault;
910
+ _dec$n = register(z.ZodFirstPartyTypeKind.ZodDefault);
911
+ class ZcDefault extends (_AbstractCompiledType$n = AbstractCompiledType) {
912
+ static{
913
+ ({ c: [_ZcDefault, _initClass$n] } = _(this, [], [
914
+ _dec$n
915
+ ], _AbstractCompiledType$n));
916
+ }
917
+ compileType() {
918
+ return compilable(this.type._def.innerType).compileType();
919
+ }
920
+ *compileParser(ctx, path) {
921
+ const newInput = uniqueIdentifier('defaultInput');
922
+ yield local(newInput, ctx.input, true);
923
+ const defaultValue = ctx.dependencies.addOrInline(this.type._def.defaultValue());
924
+ yield factory.createIfStatement(factory.createStrictEquality(factory.createTypeOfExpression(newInput), factory.createStringLiteral('undefined')), factory.createBlock([
925
+ factory.createExpressionStatement(factory.createAssignment(newInput, defaultValue))
926
+ ], true));
927
+ yield* compilable(this.type._def.innerType).compileParser(ctx.withInput(newInput), path);
928
+ }
929
+ static{
930
+ _initClass$n();
931
+ }
932
+ }
933
+
934
+ var _dec$m, _initClass$m, _AbstractCompiledType$m;
935
+ class ObjectGeneratorContext extends LabeledBlockScopeGeneratorContext {
936
+ constructor(label, input, output, verifierContext, dependencies, parentStatusSetter){
937
+ super(LabeledShortCircuitMode.Break, label, input, output, verifierContext, dependencies), this.parentStatusSetter = parentStatusSetter;
938
+ }
939
+ *prelude() {}
940
+ *status(status, allowShortCircuiting = true) {
941
+ yield* this.parentStatusSetter(typeof status === 'number' ? factory.createNumericLiteral(status) : status);
942
+ if (allowShortCircuiting) {
943
+ if (status === ParseStatus.INVALID) {
944
+ yield factory.createBreakStatement(this.label);
945
+ } else if (typeof status !== 'number') {
946
+ yield factory.createIfStatement(factory.createBitwiseAnd(status, factory.createNumericLiteral(ParseStatus.INVALID)), factory.createBreakStatement(this.label));
947
+ }
948
+ }
949
+ }
950
+ withInput(expr) {
951
+ const x = new ObjectGeneratorContext(this.label, expr, this.output, this.verifierContext, this.dependencies, this.parentStatusSetter);
952
+ x.statusVar = this.statusVar;
953
+ return x;
954
+ }
955
+ }
956
+ let _ZcObject;
957
+ _dec$m = register(z.ZodFirstPartyTypeKind.ZodObject);
958
+ class ZcObject extends (_AbstractCompiledType$m = AbstractCompiledType) {
959
+ static{
960
+ ({ c: [_ZcObject, _initClass$m] } = _(this, [], [
961
+ _dec$m
962
+ ], _AbstractCompiledType$m));
963
+ }
964
+ compileType() {
965
+ return factory.createTypeLiteralNode(Object.entries(this.type._def.shape()).map(([key, value])=>{
966
+ const type = compilable(value);
967
+ const isOptional = value._def.typeName === z.ZodFirstPartyTypeKind.ZodOptional || value.isOptional();
968
+ const node = factory.createPropertySignature(undefined, identifierOrStringLiteral(key), isOptional && value._def.typeName !== z.ZodFirstPartyTypeKind.ZodDefault ? factory.createToken(SyntaxKind.QuestionToken) : undefined, type.compileType());
969
+ if (value.description) {
970
+ ts.addSyntheticLeadingComment(node, SyntaxKind.MultiLineCommentTrivia, `* ${value.description} `, true);
971
+ }
972
+ return node;
973
+ }));
974
+ }
975
+ *compileParser(ctx, path) {
976
+ if (!this.canSkipTypeCheck) {
977
+ const typeIdentifier = uniqueIdentifier('type');
978
+ yield local(typeIdentifier, callHelper(ctx.verifierContext, 'typeOf', ctx.input));
979
+ yield factory.createIfStatement(factory.createStrictInequality(typeIdentifier, factory.createStringLiteral('object')), factory.createBlock([
980
+ ...ctx.report(objectLiteral({
981
+ path: path.serialize(),
982
+ code: factory.createStringLiteral('invalid_type'),
983
+ expected: factory.createStringLiteral('object'),
984
+ received: typeIdentifier
985
+ })),
986
+ ...ctx.status(ParseStatus.INVALID)
987
+ ], true));
988
+ }
989
+ const shape = this.type._def.shape();
990
+ // TODO: catchall/passthrough/strict
991
+ // const shapeKeysIdent = uniqueIdentifier('shapeKeys');
992
+ // yield local(
993
+ // shapeKeysIdent,
994
+ // factory.createNewExpression(
995
+ // factory.createIdentifier('Set'),
996
+ // [],
997
+ // [ factory.createArrayLiteralExpression(Object.keys(shape).map(key => factory.createStringLiteral(key))) ]
998
+ // )
999
+ // );
1000
+ const output = uniqueIdentifier('outputObject');
1001
+ yield local(output, factory.createObjectLiteralExpression());
1002
+ for (const [i, [key, value]] of Object.entries(shape).entries()){
1003
+ const label = uniqueIdentifier(`prop${i}`);
1004
+ const inputExpr = propertyChain(ctx.input, [
1005
+ key
1006
+ ]);
1007
+ const outputExpr = propertyChain(output, [
1008
+ key
1009
+ ]);
1010
+ const childCtx = new ObjectGeneratorContext(label, inputExpr, outputExpr, ctx.verifierContext, ctx.dependencies, (status)=>ctx.status(status, false));
1011
+ yield factory.createLabeledStatement(label, factory.createBlock([
1012
+ ...compilable(value).compileParser(childCtx, path.push(key))
1013
+ ]));
1014
+ }
1015
+ yield* ctx.outputs(output);
1016
+ }
1017
+ static{
1018
+ _initClass$m();
1019
+ }
1020
+ constructor(...args){
1021
+ super(...args), // In the case of discriminated unions, we already check that the type is an object before passing off parsing
1022
+ // to a ZcObject.
1023
+ this.canSkipTypeCheck = false;
1024
+ }
1025
+ }
1026
+
1027
+ var _dec$l, _initClass$l, _AbstractCompiledType$l;
1028
+ let _ZcDiscriminatedUnion;
1029
+ _dec$l = register(z.ZodFirstPartyTypeKind.ZodDiscriminatedUnion);
1030
+ class ZcDiscriminatedUnion extends (_AbstractCompiledType$l = AbstractCompiledType) {
1031
+ static{
1032
+ ({ c: [_ZcDiscriminatedUnion, _initClass$l] } = _(this, [], [
1033
+ _dec$l
1034
+ ], _AbstractCompiledType$l));
1035
+ }
1036
+ compileType() {
1037
+ return factory.createUnionTypeNode(this.type._def.options.map((ty)=>compilable(ty).compileType()));
1038
+ }
1039
+ *compileParser(ctx, path) {
1040
+ const typeIdentifier = uniqueIdentifier('type');
1041
+ yield local(typeIdentifier, callHelper(ctx.verifierContext, 'typeOf', ctx.input));
1042
+ yield factory.createIfStatement(factory.createStrictInequality(typeIdentifier, factory.createStringLiteral('object')), factory.createBlock([
1043
+ ...ctx.report(objectLiteral({
1044
+ path: path.serialize(),
1045
+ code: factory.createStringLiteral('invalid_type'),
1046
+ expected: factory.createStringLiteral('object'),
1047
+ received: typeIdentifier
1048
+ })),
1049
+ ...ctx.status(ParseStatus.INVALID)
1050
+ ], true));
1051
+ yield factory.createSwitchStatement(propertyChain(ctx.input, [
1052
+ this.type._def.discriminator
1053
+ ]), factory.createCaseBlock([
1054
+ ...[
1055
+ ...this.type._def.optionsMap.entries()
1056
+ ].map(([discriminator, zodTy])=>{
1057
+ const ty = compilable(zodTy);
1058
+ if (ty instanceof _ZcObject) {
1059
+ // We've already checked that the input is an object.
1060
+ ty.canSkipTypeCheck = true;
1061
+ }
1062
+ return factory.createCaseClause(ctx.dependencies.addOrInline(discriminator), [
1063
+ ...ty.compileParser(ctx, path),
1064
+ factory.createBreakStatement()
1065
+ ]);
1066
+ }),
1067
+ factory.createDefaultClause([
1068
+ ...ctx.report(objectLiteral({
1069
+ path: path.push(this.type._def.discriminator).serialize(),
1070
+ code: factory.createStringLiteral('invalid_union_discriminator'),
1071
+ options: ctx.dependencies.add(Array.from(this.type._def.optionsMap.keys()))
1072
+ })),
1073
+ ...ctx.status(ParseStatus.INVALID)
1074
+ ])
1075
+ ]));
1076
+ }
1077
+ static{
1078
+ _initClass$l();
1079
+ }
1080
+ }
1081
+
1082
+ var _dec$k, _initClass$k, _AbstractCompiledType$k;
1083
+ let _ZcEnum;
1084
+ _dec$k = register(z.ZodFirstPartyTypeKind.ZodEnum);
1085
+ class ZcEnum extends (_AbstractCompiledType$k = AbstractCompiledType) {
1086
+ static{
1087
+ ({ c: [_ZcEnum, _initClass$k] } = _(this, [], [
1088
+ _dec$k
1089
+ ], _AbstractCompiledType$k));
1090
+ }
1091
+ compileType() {
1092
+ return factory.createUnionTypeNode(this.type._def.values.map((ty)=>factory.createLiteralTypeNode(factory.createStringLiteral(ty))));
1093
+ }
1094
+ *compileParser(ctx, path) {
1095
+ const clauses = this.type._def.values.map((value)=>factory.createCaseClause(factory.createStringLiteral(value), []));
1096
+ const lastClause = clauses[clauses.length - 1];
1097
+ clauses[clauses.length - 1] = factory.updateCaseClause(lastClause, lastClause.expression, [
1098
+ ...ctx.outputs(ctx.input),
1099
+ factory.createBreakStatement()
1100
+ ]);
1101
+ yield factory.createIfStatement(factory.createStrictInequality(factory.createTypeOfExpression(ctx.input), factory.createStringLiteral('string')), factory.createBlock([
1102
+ ...ctx.report(objectLiteral({
1103
+ path: path.serialize(),
1104
+ code: factory.createStringLiteral('invalid_type'),
1105
+ expected: factory.createStringLiteral(this.type._def.values.map((value)=>`"${value}"`).join(' | ')),
1106
+ received: callHelper(ctx.verifierContext, 'typeOf', ctx.input)
1107
+ })),
1108
+ ...ctx.status(ParseStatus.INVALID)
1109
+ ], true), factory.createBlock([
1110
+ factory.createSwitchStatement(ctx.input, factory.createCaseBlock([
1111
+ ...clauses,
1112
+ factory.createDefaultClause([
1113
+ ...ctx.report(objectLiteral({
1114
+ path: path.serialize(),
1115
+ code: factory.createStringLiteral('invalid_enum_value'),
1116
+ options: factory.createArrayLiteralExpression(this.type._def.values.map((value)=>factory.createStringLiteral(value))),
1117
+ received: ctx.input
1118
+ })),
1119
+ ...ctx.status(ParseStatus.INVALID)
1120
+ ])
1121
+ ]))
1122
+ ], true));
1123
+ }
1124
+ static{
1125
+ _initClass$k();
1126
+ }
1127
+ }
1128
+
1129
+ var _dec$j, _initClass$j, _AbstractCompiledType$j;
1130
+ class IntersectionGeneratorContext extends LabeledBlockScopeGeneratorContext {
1131
+ constructor(parentLabel, label, input, output, verifierContext, dependencies, parentStatusSetter){
1132
+ super(LabeledShortCircuitMode.Break, label, input, output, verifierContext, dependencies), this.parentLabel = parentLabel, this.parentStatusSetter = parentStatusSetter;
1133
+ }
1134
+ *status(status, allowShortCircuiting = true) {
1135
+ yield* this.parentStatusSetter(typeof status === 'number' ? factory.createNumericLiteral(status) : status);
1136
+ if (allowShortCircuiting) {
1137
+ if (status === ParseStatus.INVALID) {
1138
+ yield factory.createBreakStatement(this.label);
1139
+ } else if (typeof status !== 'number') {
1140
+ yield factory.createIfStatement(factory.createBitwiseAnd(status, factory.createNumericLiteral(ParseStatus.INVALID)), factory.createBreakStatement(this.label));
1141
+ }
1142
+ }
1143
+ }
1144
+ withInput(expr) {
1145
+ const x = new IntersectionGeneratorContext(this.parentLabel, this.label, expr, this.output, this.verifierContext, this.dependencies, this.parentStatusSetter);
1146
+ x.statusVar = this.statusVar;
1147
+ return x;
1148
+ }
1149
+ }
1150
+ let _ZcIntersection;
1151
+ _dec$j = register(z.ZodFirstPartyTypeKind.ZodIntersection);
1152
+ class ZcIntersection extends (_AbstractCompiledType$j = AbstractCompiledType) {
1153
+ static{
1154
+ ({ c: [_ZcIntersection, _initClass$j] } = _(this, [], [
1155
+ _dec$j
1156
+ ], _AbstractCompiledType$j));
1157
+ }
1158
+ compileType() {
1159
+ return factory.createIntersectionTypeNode([
1160
+ compilable(this.type._def.left).compileType(),
1161
+ compilable(this.type._def.right).compileType()
1162
+ ]);
1163
+ }
1164
+ *compileParser(ctx, path) {
1165
+ const mergeOutput = uniqueIdentifier('intersectionOutput');
1166
+ const outputA = uniqueIdentifier('outputA');
1167
+ const outputB = uniqueIdentifier('outputB');
1168
+ const label = uniqueIdentifier('intersection');
1169
+ yield factory.createLabeledStatement(label, factory.createBlock([
1170
+ ...this._generateSide(ctx, path, label, 'left', outputA),
1171
+ ...this._generateSide(ctx, path, label, 'right', outputB),
1172
+ // TODO: We only break one side when parsing fails so that the other can continue to parse; this causes `mergeValues`
1173
+ // (and probably the `invalid_intersection_types` issue) to always be called if either side fails. Zod does not do this.
1174
+ // We need some way to short circuit here if the status is invalid; context should allow inspecting status instead of
1175
+ // being setter-only.
1176
+ local(mergeOutput, callHelper(ctx.verifierContext, 'mergeValues', outputA, outputB)),
1177
+ factory.createIfStatement(factory.createPropertyAccessExpression(mergeOutput, 'valid'), factory.createBlock([
1178
+ ...ctx.outputs(factory.createPropertyAccessExpression(mergeOutput, 'data'))
1179
+ ], true), factory.createBlock([
1180
+ ...ctx.report(objectLiteral({
1181
+ path: path.serialize(),
1182
+ code: factory.createStringLiteral('invalid_intersection_types')
1183
+ })),
1184
+ ...ctx.status(ParseStatus.INVALID)
1185
+ ]))
1186
+ ]));
1187
+ }
1188
+ *_generateSide(ctx, path, parentLabel, side, output) {
1189
+ const name = side === 'left' ? 'A' : 'B';
1190
+ const label = uniqueIdentifier(`type${name}`);
1191
+ yield local(output, undefined, true);
1192
+ const childCtx = new IntersectionGeneratorContext(parentLabel, label, ctx.input, output, ctx.verifierContext, ctx.dependencies, (status)=>ctx.status(status, false));
1193
+ yield factory.createLabeledStatement(label, factory.createBlock([
1194
+ ...compilable(this.type._def[side]).compileParser(childCtx, path)
1195
+ ]));
1196
+ }
1197
+ static{
1198
+ _initClass$j();
1199
+ }
1200
+ }
1201
+
1202
+ var _dec$i, _initClass$i, _AbstractCompiledType$i;
1203
+ let _ZcLiteral;
1204
+ _dec$i = register(z.ZodFirstPartyTypeKind.ZodLiteral);
1205
+ class ZcLiteral extends (_AbstractCompiledType$i = AbstractCompiledType) {
1206
+ static{
1207
+ ({ c: [_ZcLiteral, _initClass$i] } = _(this, [], [
1208
+ _dec$i
1209
+ ], _AbstractCompiledType$i));
1210
+ }
1211
+ compileType() {
1212
+ const value = this.type._def.value;
1213
+ let n;
1214
+ switch(typeof value){
1215
+ case 'string':
1216
+ n = factory.createStringLiteral(value);
1217
+ break;
1218
+ case 'number':
1219
+ n = factory.createNumericLiteral(value);
1220
+ break;
1221
+ case 'bigint':
1222
+ n = factory.createBigIntLiteral(value.toString());
1223
+ break;
1224
+ case 'undefined':
1225
+ return factory.createKeywordTypeNode(SyntaxKind.UndefinedKeyword);
1226
+ case 'boolean':
1227
+ n = value ? factory.createTrue() : factory.createFalse();
1228
+ case 'object':
1229
+ if (value === null) {
1230
+ n = factory.createNull();
1231
+ }
1232
+ // fallthrough
1233
+ default:
1234
+ throw new Error(`\`zc.ZcLiteral\` only supports primitives (string, number, BigInt, boolean, null, or undefined); got '${typeOf(value)}'`);
1235
+ }
1236
+ return factory.createLiteralTypeNode(n);
1237
+ }
1238
+ *compileParser(ctx, path) {
1239
+ const value = ctx.dependencies.addOrInline(this.type._def.value);
1240
+ yield factory.createIfStatement(factory.createStrictInequality(ctx.input, value), factory.createBlock([
1241
+ ...ctx.report(objectLiteral({
1242
+ path: path.serialize(),
1243
+ code: factory.createStringLiteral('invalid_literal'),
1244
+ expected: value,
1245
+ received: ctx.input
1246
+ })),
1247
+ ...ctx.status(ParseStatus.INVALID)
1248
+ ], true));
1249
+ yield* ctx.outputs(ctx.input);
1250
+ }
1251
+ static{
1252
+ _initClass$i();
1253
+ }
1254
+ }
1255
+
1256
+ var _dec$h, _initClass$h, _AbstractCompiledType$h;
1257
+ let _ZcMap;
1258
+ _dec$h = register(z.ZodFirstPartyTypeKind.ZodMap);
1259
+ class ZcMap extends (_AbstractCompiledType$h = AbstractCompiledType) {
1260
+ static{
1261
+ ({ c: [_ZcMap, _initClass$h] } = _(this, [], [
1262
+ _dec$h
1263
+ ], _AbstractCompiledType$h));
1264
+ }
1265
+ compileType() {
1266
+ const [k, v] = [
1267
+ compilable(this.type._def.keyType),
1268
+ compilable(this.type._def.valueType)
1269
+ ];
1270
+ return factory.createTypeReferenceNode(factory.createIdentifier('Map'), [
1271
+ k.compileType(),
1272
+ v.compileType()
1273
+ ]);
1274
+ }
1275
+ *compileParser(ctx, path) {
1276
+ const typeIdentifier = uniqueIdentifier('type');
1277
+ yield local(typeIdentifier, callHelper(ctx.verifierContext, 'typeOf', ctx.input));
1278
+ yield factory.createIfStatement(factory.createStrictInequality(typeIdentifier, factory.createStringLiteral('map')), factory.createBlock([
1279
+ ...ctx.report(objectLiteral({
1280
+ path: path.serialize(),
1281
+ code: factory.createStringLiteral('invalid_type'),
1282
+ expected: factory.createStringLiteral('map'),
1283
+ received: typeIdentifier
1284
+ })),
1285
+ ...ctx.status(ParseStatus.INVALID)
1286
+ ], true));
1287
+ const output = uniqueIdentifier('outputMap');
1288
+ yield local(output, factory.createNewExpression(factory.createIdentifier('Map'), undefined, []));
1289
+ const keyLabel = uniqueIdentifier('parseKey');
1290
+ const keyInput = uniqueIdentifier('key');
1291
+ const keyOutput = uniqueIdentifier('keyOut');
1292
+ const valueLabel = uniqueIdentifier('parseValue');
1293
+ const valueInput = uniqueIdentifier('value');
1294
+ const valueOutput = uniqueIdentifier('valueOut');
1295
+ const keyCtx = new ObjectGeneratorContext(keyLabel, keyInput, keyOutput, ctx.verifierContext, ctx.dependencies, (status)=>ctx.status(status, false));
1296
+ const valueCtx = new ObjectGeneratorContext(valueLabel, valueInput, valueOutput, ctx.verifierContext, ctx.dependencies, (status)=>ctx.status(status, false));
1297
+ yield factory.createForOfStatement(undefined, factory.createVariableDeclarationList([
1298
+ factory.createVariableDeclaration(factory.createArrayBindingPattern([
1299
+ factory.createBindingElement(undefined, undefined, keyInput),
1300
+ factory.createBindingElement(undefined, undefined, valueInput)
1301
+ ]))
1302
+ ], NodeFlags.Const), factory.createCallExpression(factory.createPropertyAccessExpression(ctx.input, 'entries'), undefined, []), factory.createBlock([
1303
+ local(keyOutput, keyInput, true),
1304
+ local(valueOutput, undefined, true),
1305
+ factory.createLabeledStatement(keyLabel, factory.createBlock([
1306
+ ...compilable(this.type._def.keyType).compileParser(keyCtx, path)
1307
+ ])),
1308
+ factory.createLabeledStatement(valueLabel, factory.createBlock([
1309
+ ...compilable(this.type._def.valueType).compileParser(valueCtx, path.push(keyOutput))
1310
+ ])),
1311
+ factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(output, 'set'), undefined, [
1312
+ keyOutput,
1313
+ valueOutput
1314
+ ]))
1315
+ ]));
1316
+ yield* ctx.outputs(output);
1317
+ }
1318
+ static{
1319
+ _initClass$h();
1320
+ }
1321
+ }
1322
+
1323
+ var _dec$g, _initClass$g, _AbstractCompiledType$g;
1324
+ let _ZcNaN;
1325
+ _dec$g = register(z.ZodFirstPartyTypeKind.ZodNaN);
1326
+ class ZcNaN extends (_AbstractCompiledType$g = AbstractCompiledType) {
1327
+ static{
1328
+ ({ c: [_ZcNaN, _initClass$g] } = _(this, [], [
1329
+ _dec$g
1330
+ ], _AbstractCompiledType$g));
1331
+ }
1332
+ compileType() {
1333
+ return factory.createKeywordTypeNode(SyntaxKind.NumberKeyword);
1334
+ }
1335
+ *compileParser(ctx, path) {
1336
+ yield factory.createIfStatement(factory.createLogicalOr(factory.createStrictInequality(factory.createTypeOfExpression(ctx.input), factory.createStringLiteral('number')), factory.createLogicalNot(factory.createCallExpression(factory.createIdentifier('isNaN'), undefined, [
1337
+ ctx.input
1338
+ ]))), factory.createBlock([
1339
+ ...ctx.report(objectLiteral({
1340
+ path: path.serialize(),
1341
+ code: factory.createStringLiteral('invalid_type'),
1342
+ expected: factory.createStringLiteral('nan'),
1343
+ received: callHelper(ctx.verifierContext, 'typeOf', ctx.input)
1344
+ })),
1345
+ ...ctx.status(ParseStatus.INVALID)
1346
+ ], true));
1347
+ yield* ctx.outputs(ctx.input);
1348
+ }
1349
+ static{
1350
+ _initClass$g();
1351
+ }
1352
+ }
1353
+
1354
+ var _dec$f, _initClass$f, _AbstractCompiledType$f;
1355
+ function getValidEnumValues(obj) {
1356
+ const validKeys = Object.keys(obj).filter((k)=>typeof obj[obj[k]] !== 'number');
1357
+ const filtered = {};
1358
+ for (const k of validKeys){
1359
+ filtered[k] = obj[k];
1360
+ }
1361
+ return [
1362
+ ...new Set(Object.values(filtered))
1363
+ ];
1364
+ }
1365
+ let _ZcNativeEnum;
1366
+ _dec$f = register(z.ZodFirstPartyTypeKind.ZodNativeEnum);
1367
+ class ZcNativeEnum extends (_AbstractCompiledType$f = AbstractCompiledType) {
1368
+ static{
1369
+ ({ c: [_ZcNativeEnum, _initClass$f] } = _(this, [], [
1370
+ _dec$f
1371
+ ], _AbstractCompiledType$f));
1372
+ }
1373
+ compileType() {
1374
+ return factory.createUnionTypeNode(getValidEnumValues(this.type._def.values).map((value)=>factory.createLiteralTypeNode(typeof value === 'string' ? factory.createStringLiteral(value) : factory.createNumericLiteral(value))));
1375
+ }
1376
+ *compileParser(ctx, path) {
1377
+ const values = getValidEnumValues(this.type._def.values);
1378
+ const clauses = values.map((value)=>factory.createCaseClause(typeof value === 'string' ? factory.createStringLiteral(value) : factory.createNumericLiteral(value), []));
1379
+ const lastClause = clauses[clauses.length - 1];
1380
+ clauses[clauses.length - 1] = factory.updateCaseClause(lastClause, lastClause.expression, [
1381
+ ...ctx.outputs(ctx.input),
1382
+ factory.createBreakStatement()
1383
+ ]);
1384
+ yield factory.createIfStatement(factory.createLogicalAnd(factory.createStrictInequality(factory.createTypeOfExpression(ctx.input), factory.createStringLiteral('string')), factory.createStrictInequality(factory.createTypeOfExpression(ctx.input), factory.createStringLiteral('number'))), factory.createBlock([
1385
+ ...ctx.report(objectLiteral({
1386
+ path: path.serialize(),
1387
+ code: factory.createStringLiteral('invalid_type'),
1388
+ expected: factory.createStringLiteral(joinValues(values)),
1389
+ received: callHelper(ctx.verifierContext, 'typeOf', ctx.input)
1390
+ })),
1391
+ ...ctx.status(ParseStatus.INVALID)
1392
+ ], true), factory.createBlock([
1393
+ factory.createSwitchStatement(ctx.input, factory.createCaseBlock([
1394
+ ...clauses,
1395
+ factory.createDefaultClause([
1396
+ ...ctx.report(objectLiteral({
1397
+ path: path.serialize(),
1398
+ code: factory.createStringLiteral('invalid_enum_value'),
1399
+ options: factory.createArrayLiteralExpression(values.map((value)=>typeof value === 'string' ? factory.createStringLiteral(value) : factory.createNumericLiteral(value))),
1400
+ received: ctx.input
1401
+ })),
1402
+ ...ctx.status(ParseStatus.INVALID)
1403
+ ])
1404
+ ]))
1405
+ ], true));
1406
+ }
1407
+ static{
1408
+ _initClass$f();
1409
+ }
1410
+ }
1411
+
1412
+ var _dec$e, _initClass$e, _AbstractCompiledType$e;
1413
+ let _ZcNever;
1414
+ _dec$e = register(z.ZodFirstPartyTypeKind.ZodNever);
1415
+ class ZcNever extends (_AbstractCompiledType$e = AbstractCompiledType) {
1416
+ static{
1417
+ ({ c: [_ZcNever, _initClass$e] } = _(this, [], [
1418
+ _dec$e
1419
+ ], _AbstractCompiledType$e));
1420
+ }
1421
+ compileType() {
1422
+ return factory.createKeywordTypeNode(SyntaxKind.NeverKeyword);
1423
+ }
1424
+ *compileParser(ctx, path) {
1425
+ yield* ctx.report(objectLiteral({
1426
+ path: path.serialize(),
1427
+ code: factory.createStringLiteral('invalid_type'),
1428
+ expected: factory.createStringLiteral('never'),
1429
+ received: callHelper(ctx.verifierContext, 'typeOf', ctx.input)
1430
+ }));
1431
+ yield* ctx.status(ParseStatus.INVALID);
1432
+ }
1433
+ static{
1434
+ _initClass$e();
1435
+ }
1436
+ }
1437
+
1438
+ var _dec$d, _initClass$d, _AbstractCompiledType$d;
1439
+ let _ZcNull;
1440
+ _dec$d = register(z.ZodFirstPartyTypeKind.ZodNull);
1441
+ class ZcNull extends (_AbstractCompiledType$d = AbstractCompiledType) {
1442
+ static{
1443
+ ({ c: [_ZcNull, _initClass$d] } = _(this, [], [
1444
+ _dec$d
1445
+ ], _AbstractCompiledType$d));
1446
+ }
1447
+ compileType() {
1448
+ return factory.createLiteralTypeNode(factory.createNull());
1449
+ }
1450
+ *compileParser(ctx, path) {
1451
+ yield factory.createIfStatement(factory.createStrictInequality(ctx.input, factory.createNull()), factory.createBlock([
1452
+ ...ctx.report(objectLiteral({
1453
+ path: path.serialize(),
1454
+ code: factory.createStringLiteral('invalid_type'),
1455
+ expected: factory.createStringLiteral('null'),
1456
+ received: callHelper(ctx.verifierContext, 'typeOf', ctx.input)
1457
+ })),
1458
+ ...ctx.status(ParseStatus.INVALID)
1459
+ ], true));
1460
+ yield* ctx.outputs(ctx.input);
1461
+ }
1462
+ static{
1463
+ _initClass$d();
1464
+ }
1465
+ }
1466
+
1467
+ var _dec$c, _initClass$c, _AbstractCompiledType$c;
1468
+ let _ZcNullable;
1469
+ _dec$c = register(z.ZodFirstPartyTypeKind.ZodNullable);
1470
+ class ZcNullable extends (_AbstractCompiledType$c = AbstractCompiledType) {
1471
+ static{
1472
+ ({ c: [_ZcNullable, _initClass$c] } = _(this, [], [
1473
+ _dec$c
1474
+ ], _AbstractCompiledType$c));
1475
+ }
1476
+ compileType() {
1477
+ return factory.createUnionTypeNode([
1478
+ compilable(this.type._def.innerType).compileType(),
1479
+ factory.createLiteralTypeNode(factory.createNull())
1480
+ ]);
1481
+ }
1482
+ *compileParser(ctx, path) {
1483
+ yield factory.createIfStatement(factory.createStrictEquality(ctx.input, factory.createNull()), factory.createBlock([
1484
+ ...ctx.outputs(factory.createNull())
1485
+ ], true), factory.createBlock([
1486
+ ...compilable(this.type._def.innerType).compileParser(ctx, path)
1487
+ ], true));
1488
+ }
1489
+ static{
1490
+ _initClass$c();
1491
+ }
1492
+ }
1493
+
1494
+ var _dec$b, _initClass$b, _AbstractCompiledType$b;
1495
+ let _ZcNumber;
1496
+ _dec$b = register(z.ZodFirstPartyTypeKind.ZodNumber);
1497
+ class ZcNumber extends (_AbstractCompiledType$b = AbstractCompiledType) {
1498
+ static{
1499
+ ({ c: [_ZcNumber, _initClass$b] } = _(this, [], [
1500
+ _dec$b
1501
+ ], _AbstractCompiledType$b));
1502
+ }
1503
+ compileType() {
1504
+ return factory.createKeywordTypeNode(SyntaxKind.NumberKeyword);
1505
+ }
1506
+ *compileParser(ctx, path) {
1507
+ let input = ctx.input;
1508
+ if (this.type._def.coerce) {
1509
+ const ident = uniqueIdentifier('coercedInput');
1510
+ yield local(ident, factory.createCallExpression(factory.createIdentifier('Number'), [], [
1511
+ ctx.input
1512
+ ]), false);
1513
+ input = ident;
1514
+ }
1515
+ let stmt = factory.createIfStatement(factory.createStrictInequality(factory.createTypeOfExpression(input), factory.createStringLiteral('number')), factory.createBlock([
1516
+ ...ctx.report(objectLiteral({
1517
+ path: path.serialize(),
1518
+ code: factory.createStringLiteral('invalid_type'),
1519
+ expected: factory.createStringLiteral('number'),
1520
+ received: callHelper(ctx.verifierContext, 'typeOf', input)
1521
+ }), input),
1522
+ ...ctx.status(ParseStatus.INVALID)
1523
+ ], true));
1524
+ const checkStmts = [];
1525
+ for (const check of this.type._def.checks){
1526
+ switch(check.kind){
1527
+ case 'min':
1528
+ checkStmts.push(factory.createIfStatement(factory[check.inclusive ? 'createLessThan' : 'createLessThanEquals'](input, factory.createNumericLiteral(check.value)), factory.createBlock([
1529
+ ...ctx.report(objectLiteral({
1530
+ path: path.serialize(),
1531
+ code: factory.createStringLiteral('too_small'),
1532
+ minimum: factory.createNumericLiteral(check.value),
1533
+ type: factory.createStringLiteral('number'),
1534
+ inclusive: check.inclusive ? factory.createTrue() : factory.createFalse(),
1535
+ exact: factory.createFalse(),
1536
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
1537
+ }), input),
1538
+ ...ctx.status(ParseStatus.DIRTY)
1539
+ ], true)));
1540
+ break;
1541
+ case 'max':
1542
+ checkStmts.push(factory.createIfStatement(factory[check.inclusive ? 'createGreaterThan' : 'createGreaterThanEquals'](input, factory.createNumericLiteral(check.value)), factory.createBlock([
1543
+ ...ctx.report(objectLiteral({
1544
+ path: path.serialize(),
1545
+ code: factory.createStringLiteral('too_big'),
1546
+ minimum: factory.createNumericLiteral(check.value),
1547
+ type: factory.createStringLiteral('number'),
1548
+ inclusive: check.inclusive ? factory.createTrue() : factory.createFalse(),
1549
+ exact: factory.createFalse(),
1550
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
1551
+ }), input),
1552
+ ...ctx.status(ParseStatus.DIRTY)
1553
+ ], true)));
1554
+ break;
1555
+ case 'int':
1556
+ checkStmts.push(factory.createIfStatement(factory.createLogicalNot(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier('Number'), 'isInteger'), undefined, [
1557
+ input
1558
+ ])), factory.createBlock([
1559
+ ...ctx.report(objectLiteral({
1560
+ path: path.serialize(),
1561
+ code: factory.createStringLiteral('invalid_type'),
1562
+ expected: factory.createStringLiteral('integer'),
1563
+ received: factory.createStringLiteral('float'),
1564
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
1565
+ }), input),
1566
+ ...ctx.status(ParseStatus.DIRTY)
1567
+ ], true)));
1568
+ break;
1569
+ case 'finite':
1570
+ checkStmts.push(factory.createIfStatement(factory.createLogicalNot(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier('Number'), 'isFinite'), undefined, [
1571
+ input
1572
+ ])), factory.createBlock([
1573
+ ...ctx.report(objectLiteral({
1574
+ path: path.serialize(),
1575
+ code: factory.createStringLiteral('not_finite'),
1576
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
1577
+ }), input),
1578
+ ...ctx.status(ParseStatus.DIRTY)
1579
+ ], true)));
1580
+ break;
1581
+ case 'multipleOf':
1582
+ checkStmts.push(factory.createIfStatement(factory.createStrictInequality(callHelper(ctx.verifierContext, 'floatSafeRemainder', input, factory.createNumericLiteral(check.value)), factory.createNumericLiteral(0)), factory.createBlock([
1583
+ ...ctx.report(objectLiteral({
1584
+ path: path.serialize(),
1585
+ code: factory.createStringLiteral('not_multiple_of'),
1586
+ multipleOf: factory.createNumericLiteral(check.value),
1587
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
1588
+ }), input),
1589
+ ...ctx.status(ParseStatus.DIRTY)
1590
+ ], true)));
1591
+ break;
1592
+ default:
1593
+ throw new Error(`Unsupported ZcNumber check: ${check}`);
1594
+ }
1595
+ }
1596
+ if (checkStmts.length === 0) {
1597
+ yield stmt;
1598
+ } else {
1599
+ stmt = factory.updateIfStatement(stmt, stmt.expression, stmt.thenStatement, factory.createBlock([
1600
+ ...checkStmts
1601
+ ], true));
1602
+ yield stmt;
1603
+ }
1604
+ yield* ctx.outputs(input);
1605
+ }
1606
+ static{
1607
+ _initClass$b();
1608
+ }
1609
+ }
1610
+
1611
+ var _dec$a, _initClass$a, _AbstractCompiledType$a;
1612
+ let _ZcOptional;
1613
+ _dec$a = register(z.ZodFirstPartyTypeKind.ZodOptional);
1614
+ class ZcOptional extends (_AbstractCompiledType$a = AbstractCompiledType) {
1615
+ static{
1616
+ ({ c: [_ZcOptional, _initClass$a] } = _(this, [], [
1617
+ _dec$a
1618
+ ], _AbstractCompiledType$a));
1619
+ }
1620
+ compileType() {
1621
+ return factory.createUnionTypeNode([
1622
+ compilable(this.type._def.innerType).compileType(),
1623
+ factory.createKeywordTypeNode(SyntaxKind.UndefinedKeyword)
1624
+ ]);
1625
+ }
1626
+ *compileParser(ctx, path) {
1627
+ yield factory.createIfStatement(factory.createStrictEquality(factory.createTypeOfExpression(ctx.input), factory.createStringLiteral('undefined')), factory.createBlock([
1628
+ ...ctx.outputs(factory.createIdentifier('undefined'))
1629
+ ], true), factory.createBlock([
1630
+ ...compilable(this.type._def.innerType).compileParser(ctx, path)
1631
+ ], true));
1632
+ }
1633
+ static{
1634
+ _initClass$a();
1635
+ }
1636
+ }
1637
+
1638
+ var _dec$9, _initClass$9, _AbstractCompiledType$9;
1639
+ class ReadonlyGeneratorContext {
1640
+ constructor(ctx){
1641
+ this.ctx = ctx;
1642
+ }
1643
+ get dependencies() {
1644
+ return this.ctx.dependencies;
1645
+ }
1646
+ get input() {
1647
+ return this.ctx.input;
1648
+ }
1649
+ get verifierContext() {
1650
+ return this.ctx.verifierContext;
1651
+ }
1652
+ withInput(expr) {
1653
+ return new ReadonlyGeneratorContext(this.ctx.withInput(expr));
1654
+ }
1655
+ prelude() {
1656
+ return this.ctx.prelude();
1657
+ }
1658
+ postlude() {
1659
+ return this.ctx.postlude();
1660
+ }
1661
+ report(expr) {
1662
+ return this.ctx.report(expr);
1663
+ }
1664
+ status(status, allowShortCircuiting) {
1665
+ return this.ctx.status(status, allowShortCircuiting);
1666
+ }
1667
+ *outputs(expr) {
1668
+ yield* this.ctx.outputs(factory.createCallExpression(propertyChain(factory.createIdentifier('Object'), [
1669
+ 'freeze'
1670
+ ]), undefined, [
1671
+ expr
1672
+ ]));
1673
+ }
1674
+ }
1675
+ let _ZcReadonly;
1676
+ _dec$9 = register(z.ZodFirstPartyTypeKind.ZodReadonly);
1677
+ class ZcReadonly extends (_AbstractCompiledType$9 = AbstractCompiledType) {
1678
+ static{
1679
+ ({ c: [_ZcReadonly, _initClass$9] } = _(this, [], [
1680
+ _dec$9
1681
+ ], _AbstractCompiledType$9));
1682
+ }
1683
+ compileType() {
1684
+ let innerType = compilable(this.type._def.innerType).compileType();
1685
+ if (ts.isArrayTypeNode(innerType)) {
1686
+ return factory.createTypeOperatorNode(ts.SyntaxKind.ReadonlyKeyword, innerType);
1687
+ } else if (ts.isObjectLiteralExpression(innerType) || ts.isUnionTypeNode(innerType) || ts.isIntersectionTypeNode(innerType)) {
1688
+ return factory.createTypeReferenceNode('Readonly', [
1689
+ innerType
1690
+ ]);
1691
+ } else if (ts.isTypeReferenceNode(innerType) && ts.isIdentifier(innerType.typeName)) {
1692
+ switch(innerType.typeName.text){
1693
+ case 'Map':
1694
+ case 'Set':
1695
+ innerType = factory.updateTypeReferenceNode(innerType, factory.createIdentifier(`Readonly${innerType.typeName.text}`), innerType.typeArguments);
1696
+ break;
1697
+ case 'Record':
1698
+ innerType = factory.createTypeReferenceNode('Readonly', [
1699
+ innerType
1700
+ ]);
1701
+ break;
1702
+ }
1703
+ }
1704
+ return innerType;
1705
+ }
1706
+ *compileParser(ctx, path) {
1707
+ yield* compilable(this.type._def.innerType).compileParser(new ReadonlyGeneratorContext(ctx), path);
1708
+ }
1709
+ static{
1710
+ _initClass$9();
1711
+ }
1712
+ }
1713
+
1714
+ var _dec$8, _initClass$8, _AbstractCompiledType$8;
1715
+ let _ZcRecord;
1716
+ _dec$8 = register(z.ZodFirstPartyTypeKind.ZodRecord);
1717
+ class ZcRecord extends (_AbstractCompiledType$8 = AbstractCompiledType) {
1718
+ static{
1719
+ ({ c: [_ZcRecord, _initClass$8] } = _(this, [], [
1720
+ _dec$8
1721
+ ], _AbstractCompiledType$8));
1722
+ }
1723
+ compileType() {
1724
+ const [k, v] = [
1725
+ compilable(this.type._def.keyType),
1726
+ compilable(this.type._def.valueType)
1727
+ ];
1728
+ return factory.createTypeReferenceNode(factory.createIdentifier('Record'), [
1729
+ k.compileType(),
1730
+ v.compileType()
1731
+ ]);
1732
+ }
1733
+ *compileParser(ctx, path) {
1734
+ const typeIdentifier = uniqueIdentifier('type');
1735
+ yield local(typeIdentifier, callHelper(ctx.verifierContext, 'typeOf', ctx.input));
1736
+ yield factory.createIfStatement(factory.createStrictInequality(typeIdentifier, factory.createStringLiteral('object')), factory.createBlock([
1737
+ ...ctx.report(objectLiteral({
1738
+ path: path.serialize(),
1739
+ code: factory.createStringLiteral('invalid_type'),
1740
+ expected: factory.createStringLiteral('object'),
1741
+ received: typeIdentifier
1742
+ })),
1743
+ ...ctx.status(ParseStatus.INVALID)
1744
+ ], true));
1745
+ const output = uniqueIdentifier('outputObject');
1746
+ yield local(output, factory.createObjectLiteralExpression());
1747
+ const keyLabel = uniqueIdentifier('parseKey');
1748
+ const keyInput = uniqueIdentifier('key');
1749
+ const keyOutput = uniqueIdentifier('keyOut');
1750
+ const valueLabel = uniqueIdentifier('parseValue');
1751
+ const valueInput = uniqueIdentifier('value');
1752
+ const valueOutput = uniqueIdentifier('valueOut');
1753
+ const keyCtx = new ObjectGeneratorContext(keyLabel, keyInput, keyOutput, ctx.verifierContext, ctx.dependencies, (status)=>ctx.status(status, false));
1754
+ const valueCtx = new ObjectGeneratorContext(valueLabel, valueInput, valueOutput, ctx.verifierContext, ctx.dependencies, (status)=>ctx.status(status, false));
1755
+ yield factory.createForInStatement(factory.createVariableDeclarationList([
1756
+ factory.createVariableDeclaration(keyInput)
1757
+ ], NodeFlags.Const), ctx.input, factory.createBlock([
1758
+ local(keyOutput, keyInput, true),
1759
+ local(valueInput, factory.createElementAccessExpression(ctx.input, keyInput)),
1760
+ local(valueOutput, undefined, true),
1761
+ factory.createLabeledStatement(keyLabel, factory.createBlock([
1762
+ ...compilable(this.type._def.keyType).compileParser(keyCtx, path.push(keyInput))
1763
+ ])),
1764
+ factory.createLabeledStatement(valueLabel, factory.createBlock([
1765
+ ...compilable(this.type._def.valueType).compileParser(valueCtx, path.push(keyOutput))
1766
+ ])),
1767
+ factory.createExpressionStatement(factory.createAssignment(factory.createElementAccessExpression(output, keyOutput), valueOutput))
1768
+ ]));
1769
+ yield* ctx.outputs(output);
1770
+ }
1771
+ static{
1772
+ _initClass$8();
1773
+ }
1774
+ }
1775
+
1776
+ var _dec$7, _initClass$7, _AbstractCompiledType$7;
1777
+ let _ZcSet;
1778
+ _dec$7 = register(z.ZodFirstPartyTypeKind.ZodSet);
1779
+ class ZcSet extends (_AbstractCompiledType$7 = AbstractCompiledType) {
1780
+ static{
1781
+ ({ c: [_ZcSet, _initClass$7] } = _(this, [], [
1782
+ _dec$7
1783
+ ], _AbstractCompiledType$7));
1784
+ }
1785
+ compileType() {
1786
+ return factory.createTypeReferenceNode('Set', [
1787
+ compilable(this.type._def.valueType).compileType()
1788
+ ]);
1789
+ }
1790
+ *compileParser(ctx, path) {
1791
+ const typeIdentifier = uniqueIdentifier('type');
1792
+ yield local(typeIdentifier, callHelper(ctx.verifierContext, 'typeOf', ctx.input));
1793
+ yield factory.createIfStatement(factory.createStrictInequality(typeIdentifier, factory.createStringLiteral('set')), factory.createBlock([
1794
+ ...ctx.report(objectLiteral({
1795
+ path: path.serialize(),
1796
+ code: factory.createStringLiteral('invalid_type'),
1797
+ expected: factory.createStringLiteral('set'),
1798
+ received: typeIdentifier
1799
+ })),
1800
+ ...ctx.status(ParseStatus.INVALID)
1801
+ ], true));
1802
+ if (this.type._def.minSize !== null) {
1803
+ yield factory.createIfStatement(factory.createLessThan(factory.createPropertyAccessExpression(ctx.input, 'size'), factory.createNumericLiteral(this.type._def.minSize.value)), factory.createBlock([
1804
+ ...ctx.report(objectLiteral({
1805
+ path: path.serialize(),
1806
+ code: factory.createStringLiteral('too_small'),
1807
+ minimum: factory.createNumericLiteral(this.type._def.minSize.value),
1808
+ type: factory.createStringLiteral('set'),
1809
+ inclusive: factory.createTrue(),
1810
+ exact: factory.createFalse(),
1811
+ message: this.type._def.minSize.message ? factory.createStringLiteral(this.type._def.minSize.message) : undefined
1812
+ })),
1813
+ ...ctx.status(ParseStatus.DIRTY)
1814
+ ], true));
1815
+ }
1816
+ if (this.type._def.maxSize !== null) {
1817
+ yield factory.createIfStatement(factory.createGreaterThan(factory.createPropertyAccessExpression(ctx.input, 'size'), factory.createNumericLiteral(this.type._def.maxSize.value)), factory.createBlock([
1818
+ ...ctx.report(objectLiteral({
1819
+ path: path.serialize(),
1820
+ code: factory.createStringLiteral('too_big'),
1821
+ minimum: factory.createNumericLiteral(this.type._def.maxSize.value),
1822
+ type: factory.createStringLiteral('set'),
1823
+ inclusive: factory.createTrue(),
1824
+ exact: factory.createFalse(),
1825
+ message: this.type._def.maxSize.message ? factory.createStringLiteral(this.type._def.maxSize.message) : undefined
1826
+ })),
1827
+ ...ctx.status(ParseStatus.DIRTY)
1828
+ ], true));
1829
+ }
1830
+ const output = uniqueIdentifier('outputSet');
1831
+ yield local(output, factory.createNewExpression(factory.createIdentifier('Set'), undefined, []));
1832
+ const indexInitializer = factory.createLoopVariable(true);
1833
+ const elInitializer = uniqueIdentifier('el');
1834
+ const elOutput = uniqueIdentifier('elOut');
1835
+ const childCtx = new ArrayGeneratorContext(elInitializer, elOutput, ctx.verifierContext, ctx.dependencies, (status)=>ctx.status(status, false));
1836
+ yield factory.createForOfStatement(undefined, factory.createVariableDeclarationList([
1837
+ factory.createVariableDeclaration(factory.createArrayBindingPattern([
1838
+ factory.createBindingElement(undefined, undefined, indexInitializer),
1839
+ factory.createBindingElement(undefined, undefined, elInitializer)
1840
+ ]))
1841
+ ], NodeFlags.Const), factory.createCallExpression(factory.createPropertyAccessExpression(factory.createArrayLiteralExpression([
1842
+ factory.createSpreadElement(factory.createCallExpression(factory.createPropertyAccessExpression(ctx.input, 'values'), undefined, []))
1843
+ ]), 'entries'), undefined, undefined), factory.createBlock([
1844
+ ...childCtx.prelude(),
1845
+ local(elOutput, undefined, true),
1846
+ ...compilable(this.type._def.valueType).compileParser(childCtx, path.push(indexInitializer)),
1847
+ ...childCtx.postlude(),
1848
+ factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(output, 'add'), undefined, [
1849
+ elOutput
1850
+ ]))
1851
+ ]));
1852
+ yield* ctx.outputs(output);
1853
+ }
1854
+ static{
1855
+ _initClass$7();
1856
+ }
1857
+ }
1858
+
1859
+ const DATE = /^((\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\d|3[01])|(0[469]|11)-(0[1-9]|[12]\d|30)|(02)-(0[1-9]|1\d|2[0-8])))$/;
1860
+
1861
+ var _dec$6, _initClass$6, _AbstractCompiledType$6;
1862
+ function timeRegexSource(args) {
1863
+ let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
1864
+ if (args.precision) {
1865
+ regex = `${regex}\\.\\d{${args.precision}}`;
1866
+ } else if (args.precision == null) {
1867
+ regex = `${regex}(\\.\\d+)?`;
1868
+ }
1869
+ return regex;
1870
+ }
1871
+ function createTimeRegex(args) {
1872
+ return `/^${timeRegexSource(args)}$/`;
1873
+ }
1874
+ function createDatetimeRegex(args) {
1875
+ let regex = `${DATE.source.slice(1, -1)}T${timeRegexSource(args)}`;
1876
+ const opts = [];
1877
+ opts.push(args.local ? 'Z?' : 'Z');
1878
+ if (args.offset) {
1879
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
1880
+ }
1881
+ regex = `${regex}(${opts.join('|')})`;
1882
+ return `/^${regex}$/`;
1883
+ }
1884
+ let _ZcString;
1885
+ _dec$6 = register(z.ZodFirstPartyTypeKind.ZodString);
1886
+ new class extends _$1 {
1887
+ constructor(){
1888
+ super(_ZcString), _initClass$6();
1889
+ }
1890
+ static{
1891
+ class ZcString extends (_AbstractCompiledType$6 = AbstractCompiledType) {
1892
+ static{
1893
+ ({ c: [_ZcString, _initClass$6] } = _(this, [], [
1894
+ _dec$6
1895
+ ], _AbstractCompiledType$6));
1896
+ }
1897
+ compileType() {
1898
+ return factory.createKeywordTypeNode(SyntaxKind.StringKeyword);
1899
+ }
1900
+ *compileParser(ctx, path) {
1901
+ let input = ctx.input;
1902
+ const hasModifyingChecks = this.type._def.checks.some((a)=>a.kind === 'toLowerCase' || a.kind === 'toUpperCase' || a.kind === 'trim');
1903
+ if (this.type._def.coerce) {
1904
+ const ident = uniqueIdentifier('coercedInput');
1905
+ yield local(ident, factory.createCallExpression(factory.createIdentifier('String'), [], [
1906
+ ctx.input
1907
+ ]), hasModifyingChecks);
1908
+ input = ident;
1909
+ } else if (hasModifyingChecks) {
1910
+ const ident = uniqueIdentifier('input');
1911
+ yield local(ident, input, true);
1912
+ input = ident;
1913
+ }
1914
+ let stmt = factory.createIfStatement(factory.createStrictInequality(factory.createTypeOfExpression(input), factory.createStringLiteral('string')), factory.createBlock([
1915
+ ...ctx.report(objectLiteral({
1916
+ path: path.serialize(),
1917
+ code: factory.createStringLiteral('invalid_type'),
1918
+ expected: factory.createStringLiteral('string'),
1919
+ received: callHelper(ctx.verifierContext, 'typeOf', input)
1920
+ }), input),
1921
+ ...ctx.status(ParseStatus.INVALID)
1922
+ ], true));
1923
+ const checkStmts = [];
1924
+ for (const check of this.type._def.checks){
1925
+ switch(check.kind){
1926
+ case 'min':
1927
+ checkStmts.push(factory.createIfStatement(factory.createLessThan(propertyChain(input, [
1928
+ 'length'
1929
+ ]), factory.createNumericLiteral(check.value)), factory.createBlock([
1930
+ ...ctx.report(objectLiteral({
1931
+ path: path.serialize(),
1932
+ code: factory.createStringLiteral('too_small'),
1933
+ minimum: factory.createNumericLiteral(check.value),
1934
+ type: factory.createStringLiteral('string'),
1935
+ inclusive: factory.createTrue(),
1936
+ exact: factory.createFalse(),
1937
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
1938
+ }), input),
1939
+ ...ctx.status(ParseStatus.DIRTY)
1940
+ ], true)));
1941
+ break;
1942
+ case 'max':
1943
+ checkStmts.push(factory.createIfStatement(factory.createGreaterThan(propertyChain(input, [
1944
+ 'length'
1945
+ ]), factory.createNumericLiteral(check.value)), factory.createBlock([
1946
+ ...ctx.report(objectLiteral({
1947
+ path: path.serialize(),
1948
+ code: factory.createStringLiteral('too_big'),
1949
+ minimum: factory.createNumericLiteral(check.value),
1950
+ type: factory.createStringLiteral('string'),
1951
+ inclusive: factory.createTrue(),
1952
+ exact: factory.createFalse(),
1953
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
1954
+ }), input),
1955
+ ...ctx.status(ParseStatus.DIRTY)
1956
+ ], true)));
1957
+ break;
1958
+ case 'length':
1959
+ const value = factory.createNumericLiteral(check.value);
1960
+ const lengthAccessor = factory.createPropertyAccessExpression(ctx.input, 'length');
1961
+ const tooBigIdent = uniqueIdentifier('tooBig');
1962
+ const tooSmallIdent = uniqueIdentifier('tooSmall');
1963
+ checkStmts.push(factory.createIfStatement(factory.createStrictInequality(lengthAccessor, value), factory.createBlock([
1964
+ local(tooBigIdent, factory.createGreaterThan(lengthAccessor, value)),
1965
+ local(tooSmallIdent, factory.createLessThan(lengthAccessor, value)),
1966
+ ...ctx.report(objectLiteral({
1967
+ path: path.serialize(),
1968
+ code: factory.createConditionalExpression(tooBigIdent, undefined, factory.createStringLiteral('too_big'), undefined, factory.createStringLiteral('too_small')),
1969
+ minimum: factory.createConditionalExpression(tooSmallIdent, undefined, value, undefined, factory.createIdentifier('undefined')),
1970
+ maximum: factory.createConditionalExpression(tooBigIdent, undefined, value, undefined, factory.createIdentifier('undefined')),
1971
+ type: factory.createStringLiteral('string'),
1972
+ inclusive: factory.createTrue(),
1973
+ exact: factory.createTrue(),
1974
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
1975
+ }), input),
1976
+ ...ctx.status(ParseStatus.DIRTY)
1977
+ ], true)));
1978
+ break;
1979
+ case 'email':
1980
+ case 'emoji':
1981
+ case 'uuid':
1982
+ case 'nanoid':
1983
+ case 'cuid':
1984
+ case 'cuid2':
1985
+ case 'ulid':
1986
+ case 'date':
1987
+ case 'duration':
1988
+ case 'base64':
1989
+ case 'base64url':
1990
+ checkStmts.push(ZcString._basicCheck(ctx, path, input, check.kind.toUpperCase(), check.kind, check.message));
1991
+ break;
1992
+ case 'regex':
1993
+ checkStmts.push(ZcString._basicCheck(ctx, path, input, factory.createRegularExpressionLiteral(check.regex.toString()), check.kind, check.message));
1994
+ break;
1995
+ case 'datetime':
1996
+ {
1997
+ const regex = factory.createRegularExpressionLiteral(createDatetimeRegex(check));
1998
+ checkStmts.push(ZcString._basicCheck(ctx, path, input, regex, check.kind, check.message));
1999
+ break;
2000
+ }
2001
+ case 'time':
2002
+ {
2003
+ const regex = factory.createRegularExpressionLiteral(createTimeRegex(check));
2004
+ checkStmts.push(ZcString._basicCheck(ctx, path, input, regex, check.kind, check.message));
2005
+ break;
2006
+ }
2007
+ case 'ip':
2008
+ case 'cidr':
2009
+ {
2010
+ let cidrSuffix = check.kind === 'cidr' ? '_CIDR' : '';
2011
+ if (!check.version) {
2012
+ checkStmts.push(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalNot(factory.createCallExpression(propertyChain(ctx.verifierContext, [
2013
+ 'regex',
2014
+ `IPV4${cidrSuffix}`,
2015
+ 'test'
2016
+ ]), undefined, [
2017
+ input
2018
+ ])), factory.createLogicalNot(factory.createCallExpression(propertyChain(ctx.verifierContext, [
2019
+ 'regex',
2020
+ `IPV6${cidrSuffix}`,
2021
+ 'test'
2022
+ ]), undefined, [
2023
+ input
2024
+ ]))), factory.createBlock([
2025
+ ...ctx.report(objectLiteral({
2026
+ path: path.serialize(),
2027
+ code: factory.createStringLiteral('invalid_string'),
2028
+ validation: factory.createStringLiteral(check.kind),
2029
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
2030
+ }), input),
2031
+ ...ctx.status(ParseStatus.DIRTY)
2032
+ ], true)));
2033
+ } else {
2034
+ checkStmts.push(ZcString._basicCheck(ctx, path, input, `IP${check.version.toUpperCase()}${cidrSuffix}`, check.kind, check.message));
2035
+ }
2036
+ break;
2037
+ }
2038
+ case 'url':
2039
+ checkStmts.push(factory.createTryStatement(factory.createBlock([
2040
+ factory.createExpressionStatement(factory.createNewExpression(factory.createIdentifier('URL'), undefined, [
2041
+ input
2042
+ ]))
2043
+ ], true), factory.createCatchClause(uniqueIdentifier('e'), factory.createBlock([
2044
+ ...ctx.report(objectLiteral({
2045
+ path: path.serialize(),
2046
+ code: factory.createStringLiteral('invalid_string'),
2047
+ validation: factory.createStringLiteral('url'),
2048
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
2049
+ }), input),
2050
+ ...ctx.status(ParseStatus.DIRTY)
2051
+ ], true)), undefined));
2052
+ break;
2053
+ case 'jwt':
2054
+ checkStmts.push(factory.createIfStatement(factory.createLogicalNot(callHelper(ctx.verifierContext, 'isValidJWT', input, check.alg ? factory.createStringLiteral(check.alg) : factory.createIdentifier('undefined'))), factory.createBlock([
2055
+ ...ctx.report(objectLiteral({
2056
+ path: path.serialize(),
2057
+ code: factory.createStringLiteral('invalid_string'),
2058
+ validation: factory.createStringLiteral('url'),
2059
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
2060
+ }), input),
2061
+ ...ctx.status(ParseStatus.DIRTY)
2062
+ ], true)));
2063
+ break;
2064
+ case 'startsWith':
2065
+ case 'endsWith':
2066
+ checkStmts.push(factory.createIfStatement(factory.createLogicalNot(factory.createCallExpression(factory.createPropertyAccessExpression(input, check.kind), undefined, [
2067
+ factory.createStringLiteral(check.value)
2068
+ ])), factory.createBlock([
2069
+ ...ctx.report(objectLiteral({
2070
+ path: path.serialize(),
2071
+ code: factory.createStringLiteral('invalid_string'),
2072
+ validation: objectLiteral({
2073
+ [check.kind]: factory.createStringLiteral(check.value)
2074
+ }),
2075
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
2076
+ }), input),
2077
+ ...ctx.status(ParseStatus.DIRTY)
2078
+ ], true)));
2079
+ break;
2080
+ case 'includes':
2081
+ checkStmts.push(factory.createIfStatement(factory.createLogicalNot(factory.createCallExpression(factory.createPropertyAccessExpression(input, 'includes'), undefined, [
2082
+ factory.createStringLiteral(check.value),
2083
+ check.position ? factory.createNumericLiteral(check.position) : factory.createIdentifier('undefined')
2084
+ ])), factory.createBlock([
2085
+ ...ctx.report(objectLiteral({
2086
+ path: path.serialize(),
2087
+ code: factory.createStringLiteral('invalid_string'),
2088
+ validation: objectLiteral({
2089
+ includes: factory.createStringLiteral(check.value),
2090
+ position: check.position ? factory.createNumericLiteral(check.position) : undefined
2091
+ }),
2092
+ message: check.message ? factory.createStringLiteral(check.message) : undefined
2093
+ }), input),
2094
+ ...ctx.status(ParseStatus.DIRTY)
2095
+ ], true)));
2096
+ break;
2097
+ case 'trim':
2098
+ case 'toLowerCase':
2099
+ case 'toUpperCase':
2100
+ {
2101
+ checkStmts.push(factory.createExpressionStatement(factory.createAssignment(input, factory.createCallExpression(factory.createPropertyAccessExpression(input, check.kind), undefined, []))));
2102
+ break;
2103
+ }
2104
+ default:
2105
+ throw new Error(`Unsupported ZcString check: ${check}`);
2106
+ }
2107
+ }
2108
+ if (checkStmts.length === 0) {
2109
+ yield stmt;
2110
+ } else {
2111
+ stmt = factory.updateIfStatement(stmt, stmt.expression, stmt.thenStatement, factory.createBlock([
2112
+ ...checkStmts
2113
+ ], true));
2114
+ yield stmt;
2115
+ }
2116
+ yield* ctx.outputs(input);
2117
+ }
2118
+ static _basicCheck(ctx, path, input, regexOrTester, checkKind, message) {
2119
+ const testFunction = typeof regexOrTester === 'string' ? propertyChain(ctx.verifierContext, [
2120
+ 'regex',
2121
+ regexOrTester,
2122
+ 'test'
2123
+ ]) : ts.isRegularExpressionLiteral(regexOrTester) ? factory.createPropertyAccessExpression(regexOrTester, 'test') : regexOrTester;
2124
+ return factory.createIfStatement(factory.createLogicalNot(factory.createCallExpression(testFunction, undefined, [
2125
+ input
2126
+ ])), factory.createBlock([
2127
+ ...ctx.report(objectLiteral({
2128
+ path: path.serialize(),
2129
+ code: factory.createStringLiteral('invalid_string'),
2130
+ validation: factory.createStringLiteral(checkKind),
2131
+ message: message ? factory.createStringLiteral(message) : undefined
2132
+ }), input),
2133
+ ...ctx.status(ParseStatus.DIRTY)
2134
+ ], true));
2135
+ }
2136
+ }
2137
+ }
2138
+ }();
2139
+
2140
+ var _dec$5, _initClass$5, _AbstractCompiledType$5;
2141
+ let _ZcSymbol;
2142
+ _dec$5 = register(z.ZodFirstPartyTypeKind.ZodSymbol);
2143
+ class ZcSymbol extends (_AbstractCompiledType$5 = AbstractCompiledType) {
2144
+ static{
2145
+ ({ c: [_ZcSymbol, _initClass$5] } = _(this, [], [
2146
+ _dec$5
2147
+ ], _AbstractCompiledType$5));
2148
+ }
2149
+ compileType() {
2150
+ return factory.createKeywordTypeNode(SyntaxKind.SymbolKeyword);
2151
+ }
2152
+ *compileParser(ctx, path) {
2153
+ yield factory.createIfStatement(factory.createStrictInequality(factory.createTypeOfExpression(ctx.input), factory.createStringLiteral('symbol')), factory.createBlock([
2154
+ ...ctx.report(objectLiteral({
2155
+ path: path.serialize(),
2156
+ code: factory.createStringLiteral('invalid_type'),
2157
+ expected: factory.createStringLiteral('symbol'),
2158
+ received: callHelper(ctx.verifierContext, 'typeOf', ctx.input)
2159
+ })),
2160
+ ...ctx.status(ParseStatus.INVALID)
2161
+ ], true));
2162
+ yield* ctx.outputs(ctx.input);
2163
+ }
2164
+ static{
2165
+ _initClass$5();
2166
+ }
2167
+ }
2168
+
2169
+ var _dec$4, _initClass$4, _AbstractCompiledType$4;
2170
+ let _ZcTuple;
2171
+ _dec$4 = register(z.ZodFirstPartyTypeKind.ZodTuple);
2172
+ class ZcTuple extends (_AbstractCompiledType$4 = AbstractCompiledType) {
2173
+ static{
2174
+ ({ c: [_ZcTuple, _initClass$4] } = _(this, [], [
2175
+ _dec$4
2176
+ ], _AbstractCompiledType$4));
2177
+ }
2178
+ compileType() {
2179
+ const items = [];
2180
+ for (const item of this.type._def.items){
2181
+ items.push(compilable(item).compileType());
2182
+ }
2183
+ if (this.type._def.rest) {
2184
+ items.push(factory.createRestTypeNode(compilable(this.type._def.rest).compileType()));
2185
+ }
2186
+ return factory.createTupleTypeNode(items);
2187
+ }
2188
+ *compileParser(ctx, path) {
2189
+ yield factory.createIfStatement(factory.createLogicalNot(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier('Array'), 'isArray'), undefined, [
2190
+ ctx.input
2191
+ ])), factory.createBlock([
2192
+ ...ctx.report(objectLiteral({
2193
+ path: path.serialize(),
2194
+ code: factory.createStringLiteral('invalid_type'),
2195
+ expected: factory.createStringLiteral('array'),
2196
+ received: callHelper(ctx.verifierContext, 'typeOf', ctx.input)
2197
+ })),
2198
+ ...ctx.status(ParseStatus.INVALID)
2199
+ ], true));
2200
+ yield factory.createIfStatement(factory.createLessThan(factory.createPropertyAccessExpression(ctx.input, 'length'), factory.createNumericLiteral(this.type._def.items.length)), factory.createBlock([
2201
+ ...ctx.report(objectLiteral({
2202
+ path: path.serialize(),
2203
+ code: factory.createStringLiteral('too_small'),
2204
+ minimum: factory.createNumericLiteral(this.type._def.items.length),
2205
+ type: factory.createStringLiteral('array'),
2206
+ inclusive: factory.createTrue(),
2207
+ exact: factory.createFalse()
2208
+ })),
2209
+ ...ctx.status(ParseStatus.INVALID)
2210
+ ], true));
2211
+ if (!this.type._def.rest) {
2212
+ yield factory.createIfStatement(factory.createGreaterThan(factory.createPropertyAccessExpression(ctx.input, 'length'), factory.createNumericLiteral(this.type._def.items.length)), factory.createBlock([
2213
+ ...ctx.report(objectLiteral({
2214
+ path: path.serialize(),
2215
+ code: factory.createStringLiteral('too_big'),
2216
+ minimum: factory.createNumericLiteral(this.type._def.items.length),
2217
+ type: factory.createStringLiteral('array'),
2218
+ inclusive: factory.createTrue(),
2219
+ exact: factory.createFalse()
2220
+ })),
2221
+ ...ctx.status(ParseStatus.DIRTY)
2222
+ ], true));
2223
+ }
2224
+ const output = uniqueIdentifier('outputTuple');
2225
+ yield local(output, factory.createNewExpression(factory.createIdentifier('Array'), undefined, [
2226
+ factory.createPropertyAccessExpression(ctx.input, 'length')
2227
+ ]));
2228
+ for (const [i, ty] of this.type._def.items.entries()){
2229
+ const label = uniqueIdentifier(`item${i}`);
2230
+ const inputExpr = propertyChain(ctx.input, [
2231
+ i
2232
+ ]);
2233
+ const outputExpr = propertyChain(output, [
2234
+ i
2235
+ ]);
2236
+ const childCtx = new ObjectGeneratorContext(label, inputExpr, outputExpr, ctx.verifierContext, ctx.dependencies, (status)=>ctx.status(status, false));
2237
+ yield factory.createLabeledStatement(label, factory.createBlock([
2238
+ ...compilable(ty).compileParser(childCtx, path.push(i))
2239
+ ]));
2240
+ }
2241
+ if (this.type._def.rest) {
2242
+ const indexInitializer = factory.createLoopVariable(true);
2243
+ const elInitializer = uniqueIdentifier('el');
2244
+ const elOutput = factory.createElementAccessExpression(output, indexInitializer);
2245
+ const childCtx = new ArrayGeneratorContext(elInitializer, elOutput, ctx.verifierContext, ctx.dependencies, (status)=>ctx.status(status, false));
2246
+ yield factory.createForStatement(local(indexInitializer, factory.createNumericLiteral(this.type._def.items.length), true).declarationList, factory.createLessThan(indexInitializer, factory.createPropertyAccessExpression(ctx.input, 'length')), factory.createPostfixIncrement(indexInitializer), factory.createBlock([
2247
+ local(elInitializer, factory.createElementAccessExpression(ctx.input, indexInitializer)),
2248
+ ...childCtx.prelude(),
2249
+ ...compilable(this.type._def.rest).compileParser(childCtx, path.push(indexInitializer)),
2250
+ ...childCtx.postlude()
2251
+ ]));
2252
+ }
2253
+ yield* ctx.outputs(output);
2254
+ }
2255
+ static{
2256
+ _initClass$4();
2257
+ }
2258
+ }
2259
+
2260
+ var _dec$3, _initClass$3, _AbstractCompiledType$3;
2261
+ let _ZcUndefined;
2262
+ _dec$3 = register(z.ZodFirstPartyTypeKind.ZodUndefined);
2263
+ class ZcUndefined extends (_AbstractCompiledType$3 = AbstractCompiledType) {
2264
+ static{
2265
+ ({ c: [_ZcUndefined, _initClass$3] } = _(this, [], [
2266
+ _dec$3
2267
+ ], _AbstractCompiledType$3));
2268
+ }
2269
+ compileType() {
2270
+ return factory.createKeywordTypeNode(SyntaxKind.UndefinedKeyword);
2271
+ }
2272
+ *compileParser(ctx, path) {
2273
+ yield factory.createIfStatement(factory.createStrictInequality(factory.createTypeOfExpression(ctx.input), factory.createStringLiteral('undefined')), factory.createBlock([
2274
+ ...ctx.report(objectLiteral({
2275
+ path: path.serialize(),
2276
+ code: factory.createStringLiteral('invalid_type'),
2277
+ expected: factory.createStringLiteral('undefined'),
2278
+ received: callHelper(ctx.verifierContext, 'typeOf', ctx.input)
2279
+ })),
2280
+ ...ctx.status(ParseStatus.INVALID)
2281
+ ], true));
2282
+ yield* ctx.outputs(ctx.input);
2283
+ }
2284
+ static{
2285
+ _initClass$3();
2286
+ }
2287
+ }
2288
+
2289
+ var _dec$2, _initClass$2, _AbstractCompiledType$2;
2290
+ class UnionGeneratorContext extends LabeledBlockScopeGeneratorContext {
2291
+ constructor(label, input, output, verifierContext, dependencies, parent){
2292
+ super(LabeledShortCircuitMode.Break, label, input, output, verifierContext, dependencies), this.parent = parent;
2293
+ }
2294
+ *postlude() {
2295
+ yield factory.createIfStatement(factory.createStrictEquality(this.statusVar, factory.createNumericLiteral(ParseStatus.VALID)), factory.createBlock([
2296
+ ...this.parent.ctx.outputs(this.output),
2297
+ factory.createBreakStatement(this.parent.label)
2298
+ ], true), factory.createIfStatement(factory.createLogicalAnd(factory.createStrictEquality(this.statusVar, factory.createNumericLiteral(ParseStatus.DIRTY)), factory.createLogicalNot(this.parent.dirtyResultVar)), factory.createBlock([
2299
+ factory.createExpressionStatement(factory.createAssignment(this.parent.dirtyResultVar, this.output)),
2300
+ factory.createExpressionStatement(factory.createAssignment(this.parent.dirtyCtxVar, this.verifierContext))
2301
+ ])));
2302
+ // imho, this shouldn't be behind a condition, but it's how zod does it and I promise parity
2303
+ const childIssues = factory.createPropertyAccessExpression(this.verifierContext, 'issues');
2304
+ yield factory.createIfStatement(factory.createPropertyAccessExpression(childIssues, 'length'), factory.createBlock([
2305
+ factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(this.parent.issues, 'push'), undefined, [
2306
+ childIssues
2307
+ ]))
2308
+ ], true));
2309
+ }
2310
+ withInput(expr) {
2311
+ const x = new UnionGeneratorContext(this.label, expr, this.output, this.verifierContext, this.dependencies, this.parent);
2312
+ x.statusVar = this.statusVar;
2313
+ return x;
2314
+ }
2315
+ }
2316
+ let _ZcUnion;
2317
+ _dec$2 = register(z.ZodFirstPartyTypeKind.ZodUnion);
2318
+ class ZcUnion extends (_AbstractCompiledType$2 = AbstractCompiledType) {
2319
+ static{
2320
+ ({ c: [_ZcUnion, _initClass$2] } = _(this, [], [
2321
+ _dec$2
2322
+ ], _AbstractCompiledType$2));
2323
+ }
2324
+ compileType() {
2325
+ return factory.createUnionTypeNode(this.type._def.options.map((ty)=>compilable(ty).compileType()));
2326
+ }
2327
+ *compileParser(ctx, path) {
2328
+ const dirtyResultVar = uniqueIdentifier('unionDirtyResult');
2329
+ const dirtyCtxVar = uniqueIdentifier('unionDirtyCtx');
2330
+ const issuesVar = uniqueIdentifier('unionIssues');
2331
+ yield local(dirtyResultVar, undefined, true);
2332
+ yield local(dirtyCtxVar, undefined, true);
2333
+ yield local(issuesVar, factory.createArrayLiteralExpression(), false);
2334
+ const mainLabel = uniqueIdentifier('union');
2335
+ yield factory.createLabeledStatement(mainLabel, factory.createBlock([
2336
+ ...this.type._def.options.flatMap((opt, i)=>{
2337
+ function* generateBody() {
2338
+ const ty = compilable(opt);
2339
+ const variantLabel = uniqueIdentifier(`unionVariant_${i}`);
2340
+ const tmpOutput = uniqueIdentifier('variantOutput');
2341
+ const childVerifierCtxVar = uniqueIdentifier('variantCtx');
2342
+ yield local(tmpOutput, undefined, true);
2343
+ yield local(childVerifierCtxVar, factory.createObjectLiteralExpression([
2344
+ factory.createSpreadAssignment(ctx.verifierContext),
2345
+ factory.createPropertyAssignment('issues', factory.createArrayLiteralExpression())
2346
+ ], true));
2347
+ const childCtx = new UnionGeneratorContext(variantLabel, ctx.input, tmpOutput, childVerifierCtxVar, ctx.dependencies, {
2348
+ ctx,
2349
+ label: mainLabel,
2350
+ dirtyCtxVar,
2351
+ dirtyResultVar,
2352
+ issues: issuesVar
2353
+ });
2354
+ yield* childCtx.prelude();
2355
+ yield factory.createLabeledStatement(variantLabel, factory.createBlock([
2356
+ ...ty.compileParser(childCtx, path)
2357
+ ], true));
2358
+ yield* childCtx.postlude();
2359
+ }
2360
+ return [
2361
+ ...generateBody()
2362
+ ];
2363
+ }),
2364
+ factory.createIfStatement(dirtyCtxVar, factory.createBlock([
2365
+ ...ctx.report(factory.createSpreadElement(factory.createPropertyAccessExpression(dirtyCtxVar, 'issues'))),
2366
+ ...ctx.status(ParseStatus.DIRTY)
2367
+ ], true), factory.createBlock([
2368
+ ...ctx.report(objectLiteral({
2369
+ path: path.serialize(),
2370
+ code: factory.createStringLiteral('invalid_union'),
2371
+ unionErrors: factory.createCallExpression(factory.createPropertyAccessExpression(issuesVar, 'map'), undefined, [
2372
+ factory.createArrowFunction(undefined, undefined, [
2373
+ factory.createParameterDeclaration(undefined, undefined, 'issues')
2374
+ ], undefined, undefined, factory.createNewExpression(factory.createPropertyAccessExpression(ctx.verifierContext, 'ZcError'), undefined, [
2375
+ factory.createIdentifier('issues')
2376
+ ]))
2377
+ ])
2378
+ })),
2379
+ ...ctx.status(ParseStatus.INVALID)
2380
+ ], true))
2381
+ ]));
2382
+ }
2383
+ static{
2384
+ _initClass$2();
2385
+ }
2386
+ }
2387
+
2388
+ var _dec$1, _initClass$1, _AbstractCompiledType$1;
2389
+ let _ZcUnknown;
2390
+ _dec$1 = register(z.ZodFirstPartyTypeKind.ZodUnknown);
2391
+ class ZcUnknown extends (_AbstractCompiledType$1 = AbstractCompiledType) {
2392
+ static{
2393
+ ({ c: [_ZcUnknown, _initClass$1] } = _(this, [], [
2394
+ _dec$1
2395
+ ], _AbstractCompiledType$1));
2396
+ }
2397
+ compileType() {
2398
+ return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
2399
+ }
2400
+ *compileParser(ctx, path) {
2401
+ yield* ctx.outputs(ctx.input);
2402
+ }
2403
+ static{
2404
+ _initClass$1();
2405
+ }
2406
+ }
2407
+
2408
+ var _dec, _initClass, _AbstractCompiledType;
2409
+ let _ZcVoid;
2410
+ _dec = register(z.ZodFirstPartyTypeKind.ZodVoid);
2411
+ class ZcVoid extends (_AbstractCompiledType = AbstractCompiledType) {
2412
+ static{
2413
+ ({ c: [_ZcVoid, _initClass] } = _(this, [], [
2414
+ _dec
2415
+ ], _AbstractCompiledType));
2416
+ }
2417
+ compileType() {
2418
+ return factory.createKeywordTypeNode(SyntaxKind.VoidKeyword);
2419
+ }
2420
+ *compileParser(ctx, path) {
2421
+ yield factory.createIfStatement(factory.createStrictInequality(factory.createTypeOfExpression(ctx.input), factory.createStringLiteral('undefined')), factory.createBlock([
2422
+ ...ctx.report(objectLiteral({
2423
+ path: path.serialize(),
2424
+ code: factory.createStringLiteral('invalid_type'),
2425
+ expected: factory.createStringLiteral('undefined'),
2426
+ received: callHelper(ctx.verifierContext, 'typeOf', ctx.input)
2427
+ })),
2428
+ ...ctx.status(ParseStatus.INVALID)
2429
+ ], true));
2430
+ yield* ctx.outputs(ctx.input);
2431
+ }
2432
+ static{
2433
+ _initClass();
2434
+ }
2435
+ }
2436
+
2437
+ function compile(schema, options) {
2438
+ const type = compilable(schema);
2439
+ const verifierContext = factory.createIdentifier('ctx');
2440
+ const dependencies = new Dependencies(verifierContext, options?.inlining ?? InliningMode.Default);
2441
+ const ctx = new FunctionalGeneratorContext(factory.createIdentifier('input'), propertyChain(factory.createIdentifier('ctx'), [
2442
+ 'output'
2443
+ ]), verifierContext, dependencies);
2444
+ const functionBody = [
2445
+ ...ctx.prelude(),
2446
+ ...type.compileParser(ctx, Path.empty()),
2447
+ ...ctx.postlude()
2448
+ ];
2449
+ if (options?.standalone) {
2450
+ return {
2451
+ source: print(factory.createFunctionExpression(undefined, undefined, undefined, undefined, [
2452
+ factory.createParameterDeclaration(undefined, undefined, 'input'),
2453
+ factory.createParameterDeclaration(undefined, undefined, 'ctx')
2454
+ ], undefined, factory.createBlock(functionBody, true))),
2455
+ dependencies: dependencies.dependencies,
2456
+ get hasDependencies () {
2457
+ return dependencies.dependencies.length > 0;
2458
+ }
2459
+ };
2460
+ }
2461
+ const sourceFile = factory.createSourceFile(functionBody, factory.createToken(SyntaxKind.EndOfFileToken), NodeFlags.None);
2462
+ // Usage of `factory.createUniqueName` requires that `identifiers` is defined and a read-only `Map`. This is usually
2463
+ // done after a source file is parsed, but we never do that, so this map doesn't get created and emitting throws errors.
2464
+ // Since this is an internal property, this may break on future/older TypeScript versions.
2465
+ sourceFile.identifiers = new Map();
2466
+ const source = print(sourceFile);
2467
+ const parser = new Function('input', 'ctx', source);
2468
+ return standalone(parser, dependencies.dependencies);
2469
+ }
2470
+ /**
2471
+ * Exports the `schema` to a TypeScript type definition.
2472
+ *
2473
+ * ```ts
2474
+ * import z from 'zod';
2475
+ * import zc from 'zod-compiler';
2476
+ *
2477
+ * const schema = z.string();
2478
+ *
2479
+ * console.log(zc.types(schema));
2480
+ * // export type Schema = string;
2481
+ * ```
2482
+ */ function types(schema, options) {
2483
+ const typeDef = compilable(schema).compileType();
2484
+ if (options?.asExport ?? true) {
2485
+ return print(factory.createSourceFile([
2486
+ factory.createTypeAliasDeclaration([
2487
+ factory.createToken(SyntaxKind.ExportKeyword)
2488
+ ], options?.schemaName ?? 'Schema', undefined, typeDef)
2489
+ ], factory.createToken(SyntaxKind.EndOfFileToken), NodeFlags.None));
2490
+ } else {
2491
+ return print(typeDef);
2492
+ }
2493
+ }
2494
+
2495
+ var zc = {
2496
+ __proto__: null,
2497
+ AbstractCompiledType: AbstractCompiledType,
2498
+ InliningMode: InliningMode,
2499
+ get ZcAny () { return _ZcAny; },
2500
+ get ZcArray () { return _ZcArray; },
2501
+ get ZcBigInt () { return _ZcBigInt; },
2502
+ get ZcBoolean () { return _ZcBoolean; },
2503
+ get ZcBranded () { return _ZcBranded; },
2504
+ get ZcCatch () { return _ZcCatch; },
2505
+ get ZcDate () { return _ZcDate; },
2506
+ get ZcDefault () { return _ZcDefault; },
2507
+ get ZcDiscriminatedUnion () { return _ZcDiscriminatedUnion; },
2508
+ get ZcEnum () { return _ZcEnum; },
2509
+ ZcError: ZcError,
2510
+ get ZcIntersection () { return _ZcIntersection; },
2511
+ get ZcLiteral () { return _ZcLiteral; },
2512
+ get ZcMap () { return _ZcMap; },
2513
+ get ZcNaN () { return _ZcNaN; },
2514
+ get ZcNativeEnum () { return _ZcNativeEnum; },
2515
+ get ZcNever () { return _ZcNever; },
2516
+ get ZcNull () { return _ZcNull; },
2517
+ get ZcNullable () { return _ZcNullable; },
2518
+ get ZcNumber () { return _ZcNumber; },
2519
+ get ZcObject () { return _ZcObject; },
2520
+ get ZcOptional () { return _ZcOptional; },
2521
+ get ZcReadonly () { return _ZcReadonly; },
2522
+ get ZcRecord () { return _ZcRecord; },
2523
+ get ZcSet () { return _ZcSet; },
2524
+ get ZcString () { return _ZcString; },
2525
+ get ZcSymbol () { return _ZcSymbol; },
2526
+ get ZcTuple () { return _ZcTuple; },
2527
+ get ZcUndefined () { return _ZcUndefined; },
2528
+ get ZcUnion () { return _ZcUnion; },
2529
+ get ZcUnknown () { return _ZcUnknown; },
2530
+ get ZcVoid () { return _ZcVoid; },
2531
+ compilable: compilable,
2532
+ compile: compile,
2533
+ types: types
2534
+ };
2535
+
2536
+ export { AbstractCompiledType, InliningMode, _ZcAny as ZcAny, _ZcArray as ZcArray, _ZcBigInt as ZcBigInt, _ZcBoolean as ZcBoolean, _ZcBranded as ZcBranded, _ZcCatch as ZcCatch, _ZcDate as ZcDate, _ZcDefault as ZcDefault, _ZcDiscriminatedUnion as ZcDiscriminatedUnion, _ZcEnum as ZcEnum, ZcError, _ZcIntersection as ZcIntersection, _ZcLiteral as ZcLiteral, _ZcMap as ZcMap, _ZcNaN as ZcNaN, _ZcNativeEnum as ZcNativeEnum, _ZcNever as ZcNever, _ZcNull as ZcNull, _ZcNullable as ZcNullable, _ZcNumber as ZcNumber, _ZcObject as ZcObject, _ZcOptional as ZcOptional, _ZcReadonly as ZcReadonly, _ZcRecord as ZcRecord, _ZcSet as ZcSet, _ZcString as ZcString, _ZcSymbol as ZcSymbol, _ZcTuple as ZcTuple, _ZcUndefined as ZcUndefined, _ZcUnion as ZcUnion, _ZcUnknown as ZcUnknown, _ZcVoid as ZcVoid, compilable, compile, zc as default, types };