@rexeus/typeweaver-types 0.0.2 → 0.0.4

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.js CHANGED
@@ -1,2109 +1,18 @@
1
- import { Path, BasePlugin } from '@rexeus/typeweaver-gen';
2
1
  import path from 'path';
3
- import { HttpStatusCode } from '@rexeus/typeweaver-core';
4
2
  import { fileURLToPath } from 'url';
5
- import { factory, SyntaxKind, createSourceFile, ScriptTarget, ScriptKind, createPrinter, EmitHint } from 'typescript';
6
-
7
- function getDefaultExportFromCjs (x) {
8
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
9
- }
10
-
11
- var Case$2 = {exports: {}};
12
-
13
- var Case$1 = Case$2.exports;
14
-
15
- var hasRequiredCase;
16
-
17
- function requireCase () {
18
- if (hasRequiredCase) return Case$2.exports;
19
- hasRequiredCase = 1;
20
- (function (module) {
21
- /*! Case - v1.6.2 - 2020-03-24
22
- * Copyright (c) 2020 Nathan Bubna; Licensed MIT, GPL */
23
- (function() {
24
- var unicodes = function(s, prefix) {
25
- prefix = prefix || "";
26
- return s.replace(/(^|-)/g, "$1\\u" + prefix).replace(/,/g, "\\u" + prefix);
27
- }, basicSymbols = unicodes("20-26,28-2F,3A-40,5B-60,7B-7E,A0-BF,D7,F7", "00"), baseLowerCase = "a-z" + unicodes("DF-F6,F8-FF", "00"), baseUpperCase = "A-Z" + unicodes("C0-D6,D8-DE", "00"), improperInTitle = "A|An|And|As|At|But|By|En|For|If|In|Of|On|Or|The|To|Vs?\\.?|Via", regexps = function(symbols, lowers, uppers, impropers) {
28
- symbols = symbols || basicSymbols;
29
- lowers = lowers || baseLowerCase;
30
- uppers = uppers || baseUpperCase;
31
- impropers = impropers || improperInTitle;
32
- return {
33
- capitalize: new RegExp("(^|[" + symbols + "])([" + lowers + "])", "g"),
34
- pascal: new RegExp("(^|[" + symbols + "])+([" + lowers + uppers + "])", "g"),
35
- fill: new RegExp("[" + symbols + "]+(.|$)", "g"),
36
- sentence: new RegExp('(^\\s*|[\\?\\!\\.]+"?\\s+"?|,\\s+")([' + lowers + "])", "g"),
37
- improper: new RegExp("\\b(" + impropers + ")\\b", "g"),
38
- relax: new RegExp("([^" + uppers + "])([" + uppers + "]*)([" + uppers + "])(?=[^" + uppers + "]|$)", "g"),
39
- upper: new RegExp("^[^" + lowers + "]+$"),
40
- hole: /[^\s]\s[^\s]/,
41
- apostrophe: /'/g,
42
- room: new RegExp("[" + symbols + "]")
43
- };
44
- }, re = regexps(), _ = {
45
- re,
46
- unicodes,
47
- regexps,
48
- types: [],
49
- up: String.prototype.toUpperCase,
50
- low: String.prototype.toLowerCase,
51
- cap: function(s) {
52
- return _.up.call(s.charAt(0)) + s.slice(1);
53
- },
54
- decap: function(s) {
55
- return _.low.call(s.charAt(0)) + s.slice(1);
56
- },
57
- deapostrophe: function(s) {
58
- return s.replace(re.apostrophe, "");
59
- },
60
- fill: function(s, fill, deapostrophe) {
61
- if (fill != null) {
62
- s = s.replace(re.fill, function(m, next) {
63
- return next ? fill + next : "";
64
- });
65
- }
66
- if (deapostrophe) {
67
- s = _.deapostrophe(s);
68
- }
69
- return s;
70
- },
71
- prep: function(s, fill, pascal, upper) {
72
- s = s == null ? "" : s + "";
73
- if (!upper && re.upper.test(s)) {
74
- s = _.low.call(s);
75
- }
76
- if (!fill && !re.hole.test(s)) {
77
- var holey = _.fill(s, " ");
78
- if (re.hole.test(holey)) {
79
- s = holey;
80
- }
81
- }
82
- if (!pascal && !re.room.test(s)) {
83
- s = s.replace(re.relax, _.relax);
84
- }
85
- return s;
86
- },
87
- relax: function(m, before, acronym, caps) {
88
- return before + " " + (acronym ? acronym + " " : "") + caps;
89
- }
90
- }, Case = {
91
- _,
92
- of: function(s) {
93
- for (var i = 0, m = _.types.length; i < m; i++) {
94
- if (Case[_.types[i]].apply(Case, arguments) === s) {
95
- return _.types[i];
96
- }
97
- }
98
- },
99
- flip: function(s) {
100
- return s.replace(/\w/g, function(l) {
101
- return (l == _.up.call(l) ? _.low : _.up).call(l);
102
- });
103
- },
104
- random: function(s) {
105
- return s.replace(/\w/g, function(l) {
106
- return (Math.round(Math.random()) ? _.up : _.low).call(l);
107
- });
108
- },
109
- type: function(type2, fn) {
110
- Case[type2] = fn;
111
- _.types.push(type2);
112
- }
113
- }, types = {
114
- lower: function(s, fill, deapostrophe) {
115
- return _.fill(_.low.call(_.prep(s, fill)), fill, deapostrophe);
116
- },
117
- snake: function(s) {
118
- return Case.lower(s, "_", true);
119
- },
120
- constant: function(s) {
121
- return Case.upper(s, "_", true);
122
- },
123
- camel: function(s) {
124
- return _.decap(Case.pascal(s));
125
- },
126
- kebab: function(s) {
127
- return Case.lower(s, "-", true);
128
- },
129
- upper: function(s, fill, deapostrophe) {
130
- return _.fill(_.up.call(_.prep(s, fill, false, true)), fill, deapostrophe);
131
- },
132
- capital: function(s, fill, deapostrophe) {
133
- return _.fill(_.prep(s).replace(re.capitalize, function(m, border, letter) {
134
- return border + _.up.call(letter);
135
- }), fill, deapostrophe);
136
- },
137
- header: function(s) {
138
- return Case.capital(s, "-", true);
139
- },
140
- pascal: function(s) {
141
- return _.fill(_.prep(s, false, true).replace(re.pascal, function(m, border, letter) {
142
- return _.up.call(letter);
143
- }), "", true);
144
- },
145
- title: function(s) {
146
- return Case.capital(s).replace(re.improper, function(small, p, i, s2) {
147
- return i > 0 && i < s2.lastIndexOf(" ") ? _.low.call(small) : small;
148
- });
149
- },
150
- sentence: function(s, names, abbreviations) {
151
- s = Case.lower(s).replace(re.sentence, function(m, prelude, letter) {
152
- return prelude + _.up.call(letter);
153
- });
154
- if (names) {
155
- names.forEach(function(name) {
156
- s = s.replace(new RegExp("\\b" + Case.lower(name) + "\\b", "g"), _.cap);
157
- });
158
- }
159
- if (abbreviations) {
160
- abbreviations.forEach(function(abbr) {
161
- s = s.replace(new RegExp("(\\b" + Case.lower(abbr) + "\\. +)(\\w)"), function(m, abbrAndSpace, letter) {
162
- return abbrAndSpace + _.low.call(letter);
163
- });
164
- });
165
- }
166
- return s;
167
- }
168
- };
169
- types.squish = types.pascal;
170
- Case.default = Case;
171
- for (var type in types) {
172
- Case.type(type, types[type]);
173
- }
174
- var define = typeof define === "function" ? define : function() {
175
- };
176
- define(module.exports ? module.exports = Case : this.Case = Case);
177
- }).call(Case$1);
178
- } (Case$2));
179
- return Case$2.exports;
180
- }
181
-
182
- var CaseExports = requireCase();
183
- var Case = /*@__PURE__*/getDefaultExportFromCjs(CaseExports);
184
-
185
- // @__NO_SIDE_EFFECTS__
186
- function $constructor(name, initializer, params) {
187
- function init(inst, def) {
188
- var _a;
189
- Object.defineProperty(inst, "_zod", {
190
- value: inst._zod ?? {},
191
- enumerable: false
192
- });
193
- (_a = inst._zod).traits ?? (_a.traits = /* @__PURE__ */ new Set());
194
- inst._zod.traits.add(name);
195
- initializer(inst, def);
196
- for (const k in _.prototype) {
197
- if (!(k in inst))
198
- Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
199
- }
200
- inst._zod.constr = _;
201
- inst._zod.def = def;
202
- }
203
- const Parent = params?.Parent ?? Object;
204
- class Definition extends Parent {
205
- }
206
- Object.defineProperty(Definition, "name", { value: name });
207
- function _(def) {
208
- var _a;
209
- const inst = params?.Parent ? new Definition() : this;
210
- init(inst, def);
211
- (_a = inst._zod).deferred ?? (_a.deferred = []);
212
- for (const fn of inst._zod.deferred) {
213
- fn();
214
- }
215
- return inst;
216
- }
217
- Object.defineProperty(_, "init", { value: init });
218
- Object.defineProperty(_, Symbol.hasInstance, {
219
- value: (inst) => {
220
- if (params?.Parent && inst instanceof params.Parent)
221
- return true;
222
- return inst?._zod?.traits?.has(name);
223
- }
224
- });
225
- Object.defineProperty(_, "name", { value: name });
226
- return _;
227
- }
228
- class $ZodAsyncError extends Error {
229
- constructor() {
230
- super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
231
- }
232
- }
233
- const globalConfig = {};
234
- function config(newConfig) {
235
- return globalConfig;
236
- }
237
-
238
- function getEnumValues(entries) {
239
- const numericValues = Object.values(entries).filter((v) => typeof v === "number");
240
- const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
241
- return values;
242
- }
243
- function jsonStringifyReplacer(_, value) {
244
- if (typeof value === "bigint")
245
- return value.toString();
246
- return value;
247
- }
248
- function cached(getter) {
249
- return {
250
- get value() {
251
- {
252
- const value = getter();
253
- Object.defineProperty(this, "value", { value });
254
- return value;
255
- }
256
- }
257
- };
258
- }
259
- function cleanRegex(source) {
260
- const start = source.startsWith("^") ? 1 : 0;
261
- const end = source.endsWith("$") ? source.length - 1 : source.length;
262
- return source.slice(start, end);
263
- }
264
- function defineLazy(object, key, getter) {
265
- Object.defineProperty(object, key, {
266
- get() {
267
- {
268
- const value = getter();
269
- object[key] = value;
270
- return value;
271
- }
272
- },
273
- set(v) {
274
- Object.defineProperty(object, key, {
275
- value: v
276
- // configurable: true,
277
- });
278
- },
279
- configurable: true
280
- });
281
- }
282
- function randomString(length = 10) {
283
- const chars = "abcdefghijklmnopqrstuvwxyz";
284
- let str = "";
285
- for (let i = 0; i < length; i++) {
286
- str += chars[Math.floor(Math.random() * chars.length)];
287
- }
288
- return str;
289
- }
290
- function esc(str) {
291
- return JSON.stringify(str);
292
- }
293
- function isObject(data) {
294
- return typeof data === "object" && data !== null && !Array.isArray(data);
295
- }
296
- const allowsEval = cached(() => {
297
- if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
298
- return false;
299
- }
300
- try {
301
- const F = Function;
302
- new F("");
303
- return true;
304
- } catch (_) {
305
- return false;
306
- }
307
- });
308
- function isPlainObject(o) {
309
- if (isObject(o) === false)
310
- return false;
311
- const ctor = o.constructor;
312
- if (ctor === void 0)
313
- return true;
314
- const prot = ctor.prototype;
315
- if (isObject(prot) === false)
316
- return false;
317
- if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
318
- return false;
319
- }
320
- return true;
321
- }
322
- const propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
323
- const primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
324
- function escapeRegex(str) {
325
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
326
- }
327
- function optionalKeys(shape) {
328
- return Object.keys(shape).filter((k) => {
329
- return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
330
- });
331
- }
332
- function aborted(x, startIndex = 0) {
333
- for (let i = startIndex; i < x.issues.length; i++) {
334
- if (x.issues[i].continue !== true)
335
- return true;
336
- }
337
- return false;
338
- }
339
- function prefixIssues(path, issues) {
340
- return issues.map((iss) => {
341
- var _a;
342
- (_a = iss).path ?? (_a.path = []);
343
- iss.path.unshift(path);
344
- return iss;
345
- });
346
- }
347
- function unwrapMessage(message) {
348
- return typeof message === "string" ? message : message?.message;
349
- }
350
- function finalizeIssue(iss, ctx, config) {
351
- const full = { ...iss, path: iss.path ?? [] };
352
- if (!iss.message) {
353
- const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
354
- full.message = message;
355
- }
356
- delete full.inst;
357
- delete full.continue;
358
- if (!ctx?.reportInput) {
359
- delete full.input;
360
- }
361
- return full;
362
- }
363
- function issue(...args) {
364
- const [iss, input, inst] = args;
365
- if (typeof iss === "string") {
366
- return {
367
- message: iss,
368
- code: "custom",
369
- input,
370
- inst
371
- };
372
- }
373
- return { ...iss };
374
- }
375
-
376
- const initializer = (inst, def) => {
377
- inst.name = "$ZodError";
378
- Object.defineProperty(inst, "_zod", {
379
- value: inst._zod,
380
- enumerable: false
381
- });
382
- Object.defineProperty(inst, "issues", {
383
- value: def,
384
- enumerable: false
385
- });
386
- Object.defineProperty(inst, "message", {
387
- get() {
388
- return JSON.stringify(def, jsonStringifyReplacer, 2);
389
- },
390
- enumerable: true
391
- // configurable: false,
392
- });
393
- };
394
- const $ZodError = $constructor("$ZodError", initializer);
395
- const $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
396
-
397
- const _safeParse = (_Err) => (schema, value, _ctx) => {
398
- const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
399
- const result = schema._zod.run({ value, issues: [] }, ctx);
400
- if (result instanceof Promise) {
401
- throw new $ZodAsyncError();
402
- }
403
- return result.issues.length ? {
404
- success: false,
405
- error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
406
- } : { success: true, data: result.value };
407
- };
408
- const safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
409
- const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
410
- const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
411
- let result = schema._zod.run({ value, issues: [] }, ctx);
412
- if (result instanceof Promise)
413
- result = await result;
414
- return result.issues.length ? {
415
- success: false,
416
- error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
417
- } : { success: true, data: result.value };
418
- };
419
- const safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
420
-
421
- const string = (params) => {
422
- const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
423
- return new RegExp(`^${regex}$`);
424
- };
425
- const bigint = /^\d+n?$/;
426
- const number = /^-?\d+(?:\.\d+)?/i;
427
- const boolean = /true|false/i;
428
- const _null = /null/i;
429
- const _undefined = /undefined/i;
430
-
431
- const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
432
- var _a;
433
- inst._zod ?? (inst._zod = {});
434
- inst._zod.def = def;
435
- (_a = inst._zod).onattach ?? (_a.onattach = []);
436
- });
437
-
438
- class Doc {
439
- constructor(args = []) {
440
- this.content = [];
441
- this.indent = 0;
442
- if (this)
443
- this.args = args;
444
- }
445
- indented(fn) {
446
- this.indent += 1;
447
- fn(this);
448
- this.indent -= 1;
449
- }
450
- write(arg) {
451
- if (typeof arg === "function") {
452
- arg(this, { execution: "sync" });
453
- arg(this, { execution: "async" });
454
- return;
455
- }
456
- const content = arg;
457
- const lines = content.split("\n").filter((x) => x);
458
- const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
459
- const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
460
- for (const line of dedented) {
461
- this.content.push(line);
462
- }
463
- }
464
- compile() {
465
- const F = Function;
466
- const args = this?.args;
467
- const content = this?.content ?? [``];
468
- const lines = [...content.map((x) => ` ${x}`)];
469
- return new F(...args, lines.join("\n"));
470
- }
471
- }
472
-
473
- const version = {
474
- major: 4,
475
- minor: 0,
476
- patch: 0
477
- };
478
-
479
- const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
480
- var _a;
481
- inst ?? (inst = {});
482
- defineLazy(inst._zod, "id", () => def.type + "_" + randomString(10));
483
- inst._zod.def = def;
484
- inst._zod.bag = inst._zod.bag || {};
485
- inst._zod.version = version;
486
- const checks2 = [...inst._zod.def.checks ?? []];
487
- if (inst._zod.traits.has("$ZodCheck")) {
488
- checks2.unshift(inst);
489
- }
490
- for (const ch of checks2) {
491
- for (const fn of ch._zod.onattach) {
492
- fn(inst);
493
- }
494
- }
495
- if (checks2.length === 0) {
496
- (_a = inst._zod).deferred ?? (_a.deferred = []);
497
- inst._zod.deferred?.push(() => {
498
- inst._zod.run = inst._zod.parse;
499
- });
500
- } else {
501
- const runChecks = (payload, checks3, ctx) => {
502
- let isAborted = aborted(payload);
503
- let asyncResult;
504
- for (const ch of checks3) {
505
- if (ch._zod.when) {
506
- const shouldRun = ch._zod.when(payload);
507
- if (!shouldRun)
508
- continue;
509
- } else if (isAborted) {
510
- continue;
511
- }
512
- const currLen = payload.issues.length;
513
- const _ = ch._zod.check(payload);
514
- if (_ instanceof Promise && ctx?.async === false) {
515
- throw new $ZodAsyncError();
516
- }
517
- if (asyncResult || _ instanceof Promise) {
518
- asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
519
- await _;
520
- const nextLen = payload.issues.length;
521
- if (nextLen === currLen)
522
- return;
523
- if (!isAborted)
524
- isAborted = aborted(payload, currLen);
525
- });
526
- } else {
527
- const nextLen = payload.issues.length;
528
- if (nextLen === currLen)
529
- continue;
530
- if (!isAborted)
531
- isAborted = aborted(payload, currLen);
532
- }
533
- }
534
- if (asyncResult) {
535
- return asyncResult.then(() => {
536
- return payload;
537
- });
538
- }
539
- return payload;
540
- };
541
- inst._zod.run = (payload, ctx) => {
542
- const result = inst._zod.parse(payload, ctx);
543
- if (result instanceof Promise) {
544
- if (ctx.async === false)
545
- throw new $ZodAsyncError();
546
- return result.then((result2) => runChecks(result2, checks2, ctx));
547
- }
548
- return runChecks(result, checks2, ctx);
549
- };
550
- }
551
- inst["~standard"] = {
552
- validate: (value) => {
553
- try {
554
- const r = safeParse(inst, value);
555
- return r.success ? { value: r.data } : { issues: r.error?.issues };
556
- } catch (_) {
557
- return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
558
- }
559
- },
560
- vendor: "zod",
561
- version: 1
562
- };
563
- });
564
- const $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
565
- $ZodType.init(inst, def);
566
- inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);
567
- inst._zod.parse = (payload, _) => {
568
- if (def.coerce)
569
- try {
570
- payload.value = String(payload.value);
571
- } catch (_2) {
572
- }
573
- if (typeof payload.value === "string")
574
- return payload;
575
- payload.issues.push({
576
- expected: "string",
577
- code: "invalid_type",
578
- input: payload.value,
579
- inst
580
- });
581
- return payload;
582
- };
583
- });
584
- const $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
585
- $ZodType.init(inst, def);
586
- inst._zod.pattern = inst._zod.bag.pattern ?? number;
587
- inst._zod.parse = (payload, _ctx) => {
588
- if (def.coerce)
589
- try {
590
- payload.value = Number(payload.value);
591
- } catch (_) {
592
- }
593
- const input = payload.value;
594
- if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
595
- return payload;
596
- }
597
- const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
598
- payload.issues.push({
599
- expected: "number",
600
- code: "invalid_type",
601
- input,
602
- inst,
603
- ...received ? { received } : {}
604
- });
605
- return payload;
606
- };
607
- });
608
- const $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
609
- $ZodType.init(inst, def);
610
- inst._zod.pattern = boolean;
611
- inst._zod.parse = (payload, _ctx) => {
612
- if (def.coerce)
613
- try {
614
- payload.value = Boolean(payload.value);
615
- } catch (_) {
616
- }
617
- const input = payload.value;
618
- if (typeof input === "boolean")
619
- return payload;
620
- payload.issues.push({
621
- expected: "boolean",
622
- code: "invalid_type",
623
- input,
624
- inst
625
- });
626
- return payload;
627
- };
628
- });
629
- const $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => {
630
- $ZodType.init(inst, def);
631
- inst._zod.pattern = bigint;
632
- inst._zod.parse = (payload, _ctx) => {
633
- if (def.coerce)
634
- try {
635
- payload.value = BigInt(payload.value);
636
- } catch (_) {
637
- }
638
- const { value: input } = payload;
639
- if (typeof input === "bigint")
640
- return payload;
641
- payload.issues.push({
642
- expected: "bigint",
643
- code: "invalid_type",
644
- input,
645
- inst
646
- });
647
- return payload;
648
- };
649
- });
650
- const $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => {
651
- $ZodType.init(inst, def);
652
- inst._zod.parse = (payload, _ctx) => {
653
- const { value: input } = payload;
654
- if (typeof input === "symbol")
655
- return payload;
656
- payload.issues.push({
657
- expected: "symbol",
658
- code: "invalid_type",
659
- input,
660
- inst
661
- });
662
- return payload;
663
- };
664
- });
665
- const $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => {
666
- $ZodType.init(inst, def);
667
- inst._zod.pattern = _undefined;
668
- inst._zod.values = /* @__PURE__ */ new Set([void 0]);
669
- inst._zod.parse = (payload, _ctx) => {
670
- const { value: input } = payload;
671
- if (typeof input === "undefined")
672
- return payload;
673
- payload.issues.push({
674
- expected: "undefined",
675
- code: "invalid_type",
676
- input,
677
- inst
678
- });
679
- return payload;
680
- };
681
- });
682
- const $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
683
- $ZodType.init(inst, def);
684
- inst._zod.pattern = _null;
685
- inst._zod.values = /* @__PURE__ */ new Set([null]);
686
- inst._zod.parse = (payload, _ctx) => {
687
- const { value: input } = payload;
688
- if (input === null)
689
- return payload;
690
- payload.issues.push({
691
- expected: "null",
692
- code: "invalid_type",
693
- input,
694
- inst
695
- });
696
- return payload;
697
- };
698
- });
699
- const $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => {
700
- $ZodType.init(inst, def);
701
- inst._zod.parse = (payload) => payload;
702
- });
703
- const $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
704
- $ZodType.init(inst, def);
705
- inst._zod.parse = (payload) => payload;
706
- });
707
- const $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
708
- $ZodType.init(inst, def);
709
- inst._zod.parse = (payload, _ctx) => {
710
- payload.issues.push({
711
- expected: "never",
712
- code: "invalid_type",
713
- input: payload.value,
714
- inst
715
- });
716
- return payload;
717
- };
718
- });
719
- const $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => {
720
- $ZodType.init(inst, def);
721
- inst._zod.parse = (payload, _ctx) => {
722
- const { value: input } = payload;
723
- if (typeof input === "undefined")
724
- return payload;
725
- payload.issues.push({
726
- expected: "void",
727
- code: "invalid_type",
728
- input,
729
- inst
730
- });
731
- return payload;
732
- };
733
- });
734
- const $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
735
- $ZodType.init(inst, def);
736
- inst._zod.parse = (payload, _ctx) => {
737
- if (def.coerce) {
738
- try {
739
- payload.value = new Date(payload.value);
740
- } catch (_err) {
741
- }
742
- }
743
- const input = payload.value;
744
- const isDate = input instanceof Date;
745
- const isValidDate = isDate && !Number.isNaN(input.getTime());
746
- if (isValidDate)
747
- return payload;
748
- payload.issues.push({
749
- expected: "date",
750
- code: "invalid_type",
751
- input,
752
- ...isDate ? { received: "Invalid Date" } : {},
753
- inst
754
- });
755
- return payload;
756
- };
757
- });
758
- function handleArrayResult(result, final, index) {
759
- if (result.issues.length) {
760
- final.issues.push(...prefixIssues(index, result.issues));
761
- }
762
- final.value[index] = result.value;
763
- }
764
- const $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
765
- $ZodType.init(inst, def);
766
- inst._zod.parse = (payload, ctx) => {
767
- const input = payload.value;
768
- if (!Array.isArray(input)) {
769
- payload.issues.push({
770
- expected: "array",
771
- code: "invalid_type",
772
- input,
773
- inst
774
- });
775
- return payload;
776
- }
777
- payload.value = Array(input.length);
778
- const proms = [];
779
- for (let i = 0; i < input.length; i++) {
780
- const item = input[i];
781
- const result = def.element._zod.run({
782
- value: item,
783
- issues: []
784
- }, ctx);
785
- if (result instanceof Promise) {
786
- proms.push(result.then((result2) => handleArrayResult(result2, payload, i)));
787
- } else {
788
- handleArrayResult(result, payload, i);
789
- }
790
- }
791
- if (proms.length) {
792
- return Promise.all(proms).then(() => payload);
793
- }
794
- return payload;
795
- };
796
- });
797
- function handleObjectResult(result, final, key) {
798
- if (result.issues.length) {
799
- final.issues.push(...prefixIssues(key, result.issues));
800
- }
801
- final.value[key] = result.value;
802
- }
803
- function handleOptionalObjectResult(result, final, key, input) {
804
- if (result.issues.length) {
805
- if (input[key] === void 0) {
806
- if (key in input) {
807
- final.value[key] = void 0;
808
- } else {
809
- final.value[key] = result.value;
810
- }
811
- } else {
812
- final.issues.push(...prefixIssues(key, result.issues));
813
- }
814
- } else if (result.value === void 0) {
815
- if (key in input)
816
- final.value[key] = void 0;
817
- } else {
818
- final.value[key] = result.value;
819
- }
820
- }
821
- const $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
822
- $ZodType.init(inst, def);
823
- const _normalized = cached(() => {
824
- const keys = Object.keys(def.shape);
825
- for (const k of keys) {
826
- if (!(def.shape[k] instanceof $ZodType)) {
827
- throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
828
- }
829
- }
830
- const okeys = optionalKeys(def.shape);
831
- return {
832
- shape: def.shape,
833
- keys,
834
- keySet: new Set(keys),
835
- numKeys: keys.length,
836
- optionalKeys: new Set(okeys)
837
- };
838
- });
839
- defineLazy(inst._zod, "propValues", () => {
840
- const shape = def.shape;
841
- const propValues = {};
842
- for (const key in shape) {
843
- const field = shape[key]._zod;
844
- if (field.values) {
845
- propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
846
- for (const v of field.values)
847
- propValues[key].add(v);
848
- }
849
- }
850
- return propValues;
851
- });
852
- const generateFastpass = (shape) => {
853
- const doc = new Doc(["shape", "payload", "ctx"]);
854
- const { keys, optionalKeys } = _normalized.value;
855
- const parseStr = (key) => {
856
- const k = esc(key);
857
- return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
858
- };
859
- doc.write(`const input = payload.value;`);
860
- const ids = /* @__PURE__ */ Object.create(null);
861
- for (const key of keys) {
862
- ids[key] = randomString(15);
863
- }
864
- doc.write(`const newResult = {}`);
865
- for (const key of keys) {
866
- if (optionalKeys.has(key)) {
867
- const id = ids[key];
868
- doc.write(`const ${id} = ${parseStr(key)};`);
869
- const k = esc(key);
870
- doc.write(`
871
- if (${id}.issues.length) {
872
- if (input[${k}] === undefined) {
873
- if (${k} in input) {
874
- newResult[${k}] = undefined;
875
- }
876
- } else {
877
- payload.issues = payload.issues.concat(
878
- ${id}.issues.map((iss) => ({
879
- ...iss,
880
- path: iss.path ? [${k}, ...iss.path] : [${k}],
881
- }))
882
- );
883
- }
884
- } else if (${id}.value === undefined) {
885
- if (${k} in input) newResult[${k}] = undefined;
886
- } else {
887
- newResult[${k}] = ${id}.value;
888
- }
889
- `);
890
- } else {
891
- const id = ids[key];
892
- doc.write(`const ${id} = ${parseStr(key)};`);
893
- doc.write(`
894
- if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
895
- ...iss,
896
- path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}]
897
- })));`);
898
- doc.write(`newResult[${esc(key)}] = ${id}.value`);
899
- }
900
- }
901
- doc.write(`payload.value = newResult;`);
902
- doc.write(`return payload;`);
903
- const fn = doc.compile();
904
- return (payload, ctx) => fn(shape, payload, ctx);
905
- };
906
- let fastpass;
907
- const isObject$1 = isObject;
908
- const jit = !globalConfig.jitless;
909
- const allowsEval$1 = allowsEval;
910
- const fastEnabled = jit && allowsEval$1.value;
911
- const { catchall } = def;
912
- let value;
913
- inst._zod.parse = (payload, ctx) => {
914
- value ?? (value = _normalized.value);
915
- const input = payload.value;
916
- if (!isObject$1(input)) {
917
- payload.issues.push({
918
- expected: "object",
919
- code: "invalid_type",
920
- input,
921
- inst
922
- });
923
- return payload;
924
- }
925
- const proms = [];
926
- if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
927
- if (!fastpass)
928
- fastpass = generateFastpass(def.shape);
929
- payload = fastpass(payload, ctx);
930
- } else {
931
- payload.value = {};
932
- const shape = value.shape;
933
- for (const key of value.keys) {
934
- const el = shape[key];
935
- const r = el._zod.run({ value: input[key], issues: [] }, ctx);
936
- const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional";
937
- if (r instanceof Promise) {
938
- proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key)));
939
- } else if (isOptional) {
940
- handleOptionalObjectResult(r, payload, key, input);
941
- } else {
942
- handleObjectResult(r, payload, key);
943
- }
944
- }
945
- }
946
- if (!catchall) {
947
- return proms.length ? Promise.all(proms).then(() => payload) : payload;
948
- }
949
- const unrecognized = [];
950
- const keySet = value.keySet;
951
- const _catchall = catchall._zod;
952
- const t = _catchall.def.type;
953
- for (const key of Object.keys(input)) {
954
- if (keySet.has(key))
955
- continue;
956
- if (t === "never") {
957
- unrecognized.push(key);
958
- continue;
959
- }
960
- const r = _catchall.run({ value: input[key], issues: [] }, ctx);
961
- if (r instanceof Promise) {
962
- proms.push(r.then((r2) => handleObjectResult(r2, payload, key)));
963
- } else {
964
- handleObjectResult(r, payload, key);
965
- }
966
- }
967
- if (unrecognized.length) {
968
- payload.issues.push({
969
- code: "unrecognized_keys",
970
- keys: unrecognized,
971
- input,
972
- inst
973
- });
974
- }
975
- if (!proms.length)
976
- return payload;
977
- return Promise.all(proms).then(() => {
978
- return payload;
979
- });
980
- };
981
- });
982
- function handleUnionResults(results, final, inst, ctx) {
983
- for (const result of results) {
984
- if (result.issues.length === 0) {
985
- final.value = result.value;
986
- return final;
987
- }
988
- }
989
- final.issues.push({
990
- code: "invalid_union",
991
- input: final.value,
992
- inst,
993
- errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
994
- });
995
- return final;
996
- }
997
- const $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
998
- $ZodType.init(inst, def);
999
- defineLazy(inst._zod, "values", () => {
1000
- if (def.options.every((o) => o._zod.values)) {
1001
- return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
1002
- }
1003
- return void 0;
1004
- });
1005
- defineLazy(inst._zod, "pattern", () => {
1006
- if (def.options.every((o) => o._zod.pattern)) {
1007
- const patterns = def.options.map((o) => o._zod.pattern);
1008
- return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
1009
- }
1010
- return void 0;
1011
- });
1012
- inst._zod.parse = (payload, ctx) => {
1013
- let async = false;
1014
- const results = [];
1015
- for (const option of def.options) {
1016
- const result = option._zod.run({
1017
- value: payload.value,
1018
- issues: []
1019
- }, ctx);
1020
- if (result instanceof Promise) {
1021
- results.push(result);
1022
- async = true;
1023
- } else {
1024
- if (result.issues.length === 0)
1025
- return result;
1026
- results.push(result);
1027
- }
1028
- }
1029
- if (!async)
1030
- return handleUnionResults(results, payload, inst, ctx);
1031
- return Promise.all(results).then((results2) => {
1032
- return handleUnionResults(results2, payload, inst, ctx);
1033
- });
1034
- };
1035
- });
1036
- const $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
1037
- $ZodType.init(inst, def);
1038
- inst._zod.parse = (payload, ctx) => {
1039
- const { value: input } = payload;
1040
- const left = def.left._zod.run({ value: input, issues: [] }, ctx);
1041
- const right = def.right._zod.run({ value: input, issues: [] }, ctx);
1042
- const async = left instanceof Promise || right instanceof Promise;
1043
- if (async) {
1044
- return Promise.all([left, right]).then(([left2, right2]) => {
1045
- return handleIntersectionResults(payload, left2, right2);
1046
- });
1047
- }
1048
- return handleIntersectionResults(payload, left, right);
1049
- };
1050
- });
1051
- function mergeValues(a, b) {
1052
- if (a === b) {
1053
- return { valid: true, data: a };
1054
- }
1055
- if (a instanceof Date && b instanceof Date && +a === +b) {
1056
- return { valid: true, data: a };
1057
- }
1058
- if (isPlainObject(a) && isPlainObject(b)) {
1059
- const bKeys = Object.keys(b);
1060
- const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
1061
- const newObj = { ...a, ...b };
1062
- for (const key of sharedKeys) {
1063
- const sharedValue = mergeValues(a[key], b[key]);
1064
- if (!sharedValue.valid) {
1065
- return {
1066
- valid: false,
1067
- mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
1068
- };
1069
- }
1070
- newObj[key] = sharedValue.data;
1071
- }
1072
- return { valid: true, data: newObj };
1073
- }
1074
- if (Array.isArray(a) && Array.isArray(b)) {
1075
- if (a.length !== b.length) {
1076
- return { valid: false, mergeErrorPath: [] };
1077
- }
1078
- const newArray = [];
1079
- for (let index = 0; index < a.length; index++) {
1080
- const itemA = a[index];
1081
- const itemB = b[index];
1082
- const sharedValue = mergeValues(itemA, itemB);
1083
- if (!sharedValue.valid) {
1084
- return {
1085
- valid: false,
1086
- mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
1087
- };
1088
- }
1089
- newArray.push(sharedValue.data);
1090
- }
1091
- return { valid: true, data: newArray };
1092
- }
1093
- return { valid: false, mergeErrorPath: [] };
1094
- }
1095
- function handleIntersectionResults(result, left, right) {
1096
- if (left.issues.length) {
1097
- result.issues.push(...left.issues);
1098
- }
1099
- if (right.issues.length) {
1100
- result.issues.push(...right.issues);
1101
- }
1102
- if (aborted(result))
1103
- return result;
1104
- const merged = mergeValues(left.value, right.value);
1105
- if (!merged.valid) {
1106
- throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
1107
- }
1108
- result.value = merged.data;
1109
- return result;
1110
- }
1111
- const $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
1112
- $ZodType.init(inst, def);
1113
- const items = def.items;
1114
- const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional");
1115
- inst._zod.parse = (payload, ctx) => {
1116
- const input = payload.value;
1117
- if (!Array.isArray(input)) {
1118
- payload.issues.push({
1119
- input,
1120
- inst,
1121
- expected: "tuple",
1122
- code: "invalid_type"
1123
- });
1124
- return payload;
1125
- }
1126
- payload.value = [];
1127
- const proms = [];
1128
- if (!def.rest) {
1129
- const tooBig = input.length > items.length;
1130
- const tooSmall = input.length < optStart - 1;
1131
- if (tooBig || tooSmall) {
1132
- payload.issues.push({
1133
- input,
1134
- inst,
1135
- origin: "array",
1136
- ...tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length }
1137
- });
1138
- return payload;
1139
- }
1140
- }
1141
- let i = -1;
1142
- for (const item of items) {
1143
- i++;
1144
- if (i >= input.length) {
1145
- if (i >= optStart)
1146
- continue;
1147
- }
1148
- const result = item._zod.run({
1149
- value: input[i],
1150
- issues: []
1151
- }, ctx);
1152
- if (result instanceof Promise) {
1153
- proms.push(result.then((result2) => handleTupleResult(result2, payload, i)));
1154
- } else {
1155
- handleTupleResult(result, payload, i);
1156
- }
1157
- }
1158
- if (def.rest) {
1159
- const rest = input.slice(items.length);
1160
- for (const el of rest) {
1161
- i++;
1162
- const result = def.rest._zod.run({
1163
- value: el,
1164
- issues: []
1165
- }, ctx);
1166
- if (result instanceof Promise) {
1167
- proms.push(result.then((result2) => handleTupleResult(result2, payload, i)));
1168
- } else {
1169
- handleTupleResult(result, payload, i);
1170
- }
1171
- }
1172
- }
1173
- if (proms.length)
1174
- return Promise.all(proms).then(() => payload);
1175
- return payload;
1176
- };
1177
- });
1178
- function handleTupleResult(result, final, index) {
1179
- if (result.issues.length) {
1180
- final.issues.push(...prefixIssues(index, result.issues));
1181
- }
1182
- final.value[index] = result.value;
1183
- }
1184
- const $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
1185
- $ZodType.init(inst, def);
1186
- inst._zod.parse = (payload, ctx) => {
1187
- const input = payload.value;
1188
- if (!isPlainObject(input)) {
1189
- payload.issues.push({
1190
- expected: "record",
1191
- code: "invalid_type",
1192
- input,
1193
- inst
1194
- });
1195
- return payload;
1196
- }
1197
- const proms = [];
1198
- if (def.keyType._zod.values) {
1199
- const values = def.keyType._zod.values;
1200
- payload.value = {};
1201
- for (const key of values) {
1202
- if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
1203
- const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
1204
- if (result instanceof Promise) {
1205
- proms.push(result.then((result2) => {
1206
- if (result2.issues.length) {
1207
- payload.issues.push(...prefixIssues(key, result2.issues));
1208
- }
1209
- payload.value[key] = result2.value;
1210
- }));
1211
- } else {
1212
- if (result.issues.length) {
1213
- payload.issues.push(...prefixIssues(key, result.issues));
1214
- }
1215
- payload.value[key] = result.value;
1216
- }
1217
- }
1218
- }
1219
- let unrecognized;
1220
- for (const key in input) {
1221
- if (!values.has(key)) {
1222
- unrecognized = unrecognized ?? [];
1223
- unrecognized.push(key);
1224
- }
1225
- }
1226
- if (unrecognized && unrecognized.length > 0) {
1227
- payload.issues.push({
1228
- code: "unrecognized_keys",
1229
- input,
1230
- inst,
1231
- keys: unrecognized
1232
- });
1233
- }
1234
- } else {
1235
- payload.value = {};
1236
- for (const key of Reflect.ownKeys(input)) {
1237
- if (key === "__proto__")
1238
- continue;
1239
- const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
1240
- if (keyResult instanceof Promise) {
1241
- throw new Error("Async schemas not supported in object keys currently");
1242
- }
1243
- if (keyResult.issues.length) {
1244
- payload.issues.push({
1245
- origin: "record",
1246
- code: "invalid_key",
1247
- issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
1248
- input: key,
1249
- path: [key],
1250
- inst
1251
- });
1252
- payload.value[keyResult.value] = keyResult.value;
1253
- continue;
1254
- }
1255
- const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
1256
- if (result instanceof Promise) {
1257
- proms.push(result.then((result2) => {
1258
- if (result2.issues.length) {
1259
- payload.issues.push(...prefixIssues(key, result2.issues));
1260
- }
1261
- payload.value[keyResult.value] = result2.value;
1262
- }));
1263
- } else {
1264
- if (result.issues.length) {
1265
- payload.issues.push(...prefixIssues(key, result.issues));
1266
- }
1267
- payload.value[keyResult.value] = result.value;
1268
- }
1269
- }
1270
- }
1271
- if (proms.length) {
1272
- return Promise.all(proms).then(() => payload);
1273
- }
1274
- return payload;
1275
- };
1276
- });
1277
- const $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => {
1278
- $ZodType.init(inst, def);
1279
- inst._zod.parse = (payload, ctx) => {
1280
- const input = payload.value;
1281
- if (!(input instanceof Map)) {
1282
- payload.issues.push({
1283
- expected: "map",
1284
- code: "invalid_type",
1285
- input,
1286
- inst
1287
- });
1288
- return payload;
1289
- }
1290
- const proms = [];
1291
- payload.value = /* @__PURE__ */ new Map();
1292
- for (const [key, value] of input) {
1293
- const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
1294
- const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx);
1295
- if (keyResult instanceof Promise || valueResult instanceof Promise) {
1296
- proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => {
1297
- handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx);
1298
- }));
1299
- } else {
1300
- handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
1301
- }
1302
- }
1303
- if (proms.length)
1304
- return Promise.all(proms).then(() => payload);
1305
- return payload;
1306
- };
1307
- });
1308
- function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
1309
- if (keyResult.issues.length) {
1310
- if (propertyKeyTypes.has(typeof key)) {
1311
- final.issues.push(...prefixIssues(key, keyResult.issues));
1312
- } else {
1313
- final.issues.push({
1314
- origin: "map",
1315
- code: "invalid_key",
1316
- input,
1317
- inst,
1318
- issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
1319
- });
1320
- }
1321
- }
1322
- if (valueResult.issues.length) {
1323
- if (propertyKeyTypes.has(typeof key)) {
1324
- final.issues.push(...prefixIssues(key, valueResult.issues));
1325
- } else {
1326
- final.issues.push({
1327
- origin: "map",
1328
- code: "invalid_element",
1329
- input,
1330
- inst,
1331
- key,
1332
- issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
1333
- });
1334
- }
1335
- }
1336
- final.value.set(keyResult.value, valueResult.value);
1337
- }
1338
- const $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => {
1339
- $ZodType.init(inst, def);
1340
- inst._zod.parse = (payload, ctx) => {
1341
- const input = payload.value;
1342
- if (!(input instanceof Set)) {
1343
- payload.issues.push({
1344
- input,
1345
- inst,
1346
- expected: "set",
1347
- code: "invalid_type"
1348
- });
1349
- return payload;
1350
- }
1351
- const proms = [];
1352
- payload.value = /* @__PURE__ */ new Set();
1353
- for (const item of input) {
1354
- const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);
1355
- if (result instanceof Promise) {
1356
- proms.push(result.then((result2) => handleSetResult(result2, payload)));
1357
- } else
1358
- handleSetResult(result, payload);
1359
- }
1360
- if (proms.length)
1361
- return Promise.all(proms).then(() => payload);
1362
- return payload;
1363
- };
1364
- });
1365
- function handleSetResult(result, final) {
1366
- if (result.issues.length) {
1367
- final.issues.push(...result.issues);
1368
- }
1369
- final.value.add(result.value);
1370
- }
1371
- const $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
1372
- $ZodType.init(inst, def);
1373
- const values = getEnumValues(def.entries);
1374
- inst._zod.values = new Set(values);
1375
- inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
1376
- inst._zod.parse = (payload, _ctx) => {
1377
- const input = payload.value;
1378
- if (inst._zod.values.has(input)) {
1379
- return payload;
1380
- }
1381
- payload.issues.push({
1382
- code: "invalid_value",
1383
- values,
1384
- input,
1385
- inst
1386
- });
1387
- return payload;
1388
- };
1389
- });
1390
- const $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
1391
- $ZodType.init(inst, def);
1392
- inst._zod.values = new Set(def.values);
1393
- inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o)).join("|")})$`);
1394
- inst._zod.parse = (payload, _ctx) => {
1395
- const input = payload.value;
1396
- if (inst._zod.values.has(input)) {
1397
- return payload;
1398
- }
1399
- payload.issues.push({
1400
- code: "invalid_value",
1401
- values: def.values,
1402
- input,
1403
- inst
1404
- });
1405
- return payload;
1406
- };
1407
- });
1408
- const $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => {
1409
- $ZodType.init(inst, def);
1410
- inst._zod.parse = (payload, _ctx) => {
1411
- const input = payload.value;
1412
- if (input instanceof File)
1413
- return payload;
1414
- payload.issues.push({
1415
- expected: "file",
1416
- code: "invalid_type",
1417
- input,
1418
- inst
1419
- });
1420
- return payload;
1421
- };
1422
- });
1423
- const $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
1424
- $ZodType.init(inst, def);
1425
- inst._zod.parse = (payload, _ctx) => {
1426
- const _out = def.transform(payload.value, payload);
1427
- if (_ctx.async) {
1428
- const output = _out instanceof Promise ? _out : Promise.resolve(_out);
1429
- return output.then((output2) => {
1430
- payload.value = output2;
1431
- return payload;
1432
- });
1433
- }
1434
- if (_out instanceof Promise) {
1435
- throw new $ZodAsyncError();
1436
- }
1437
- payload.value = _out;
1438
- return payload;
1439
- };
1440
- });
1441
- const $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
1442
- $ZodType.init(inst, def);
1443
- inst._zod.optin = "optional";
1444
- inst._zod.optout = "optional";
1445
- defineLazy(inst._zod, "values", () => {
1446
- return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;
1447
- });
1448
- defineLazy(inst._zod, "pattern", () => {
1449
- const pattern = def.innerType._zod.pattern;
1450
- return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
1451
- });
1452
- inst._zod.parse = (payload, ctx) => {
1453
- if (payload.value === void 0) {
1454
- return payload;
1455
- }
1456
- return def.innerType._zod.run(payload, ctx);
1457
- };
1458
- });
1459
- const $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
1460
- $ZodType.init(inst, def);
1461
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1462
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1463
- defineLazy(inst._zod, "pattern", () => {
1464
- const pattern = def.innerType._zod.pattern;
1465
- return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
1466
- });
1467
- defineLazy(inst._zod, "values", () => {
1468
- return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0;
1469
- });
1470
- inst._zod.parse = (payload, ctx) => {
1471
- if (payload.value === null)
1472
- return payload;
1473
- return def.innerType._zod.run(payload, ctx);
1474
- };
1475
- });
1476
- const $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
1477
- $ZodType.init(inst, def);
1478
- inst._zod.optin = "optional";
1479
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1480
- inst._zod.parse = (payload, ctx) => {
1481
- if (payload.value === void 0) {
1482
- payload.value = def.defaultValue;
1483
- return payload;
1484
- }
1485
- const result = def.innerType._zod.run(payload, ctx);
1486
- if (result instanceof Promise) {
1487
- return result.then((result2) => handleDefaultResult(result2, def));
1488
- }
1489
- return handleDefaultResult(result, def);
1490
- };
1491
- });
1492
- function handleDefaultResult(payload, def) {
1493
- if (payload.value === void 0) {
1494
- payload.value = def.defaultValue;
1495
- }
1496
- return payload;
1497
- }
1498
- const $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
1499
- $ZodType.init(inst, def);
1500
- defineLazy(inst._zod, "values", () => {
1501
- const v = def.innerType._zod.values;
1502
- return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
1503
- });
1504
- inst._zod.parse = (payload, ctx) => {
1505
- const result = def.innerType._zod.run(payload, ctx);
1506
- if (result instanceof Promise) {
1507
- return result.then((result2) => handleNonOptionalResult(result2, inst));
1508
- }
1509
- return handleNonOptionalResult(result, inst);
1510
- };
1511
- });
1512
- function handleNonOptionalResult(payload, inst) {
1513
- if (!payload.issues.length && payload.value === void 0) {
1514
- payload.issues.push({
1515
- code: "invalid_type",
1516
- expected: "nonoptional",
1517
- input: payload.value,
1518
- inst
1519
- });
1520
- }
1521
- return payload;
1522
- }
1523
- const $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => {
1524
- $ZodType.init(inst, def);
1525
- inst._zod.parse = (payload, ctx) => {
1526
- const result = def.innerType._zod.run(payload, ctx);
1527
- if (result instanceof Promise) {
1528
- return result.then((result2) => {
1529
- payload.value = result2.issues.length === 0;
1530
- return payload;
1531
- });
1532
- }
1533
- payload.value = result.issues.length === 0;
1534
- return payload;
1535
- };
1536
- });
1537
- const $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
1538
- $ZodType.init(inst, def);
1539
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1540
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1541
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
1542
- inst._zod.parse = (payload, ctx) => {
1543
- const result = def.innerType._zod.run(payload, ctx);
1544
- if (result instanceof Promise) {
1545
- return result.then((result2) => {
1546
- payload.value = result2.value;
1547
- if (result2.issues.length) {
1548
- payload.value = def.catchValue({
1549
- ...payload,
1550
- error: {
1551
- issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))
1552
- },
1553
- input: payload.value
1554
- });
1555
- payload.issues = [];
1556
- }
1557
- return payload;
1558
- });
1559
- }
1560
- payload.value = result.value;
1561
- if (result.issues.length) {
1562
- payload.value = def.catchValue({
1563
- ...payload,
1564
- error: {
1565
- issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
1566
- },
1567
- input: payload.value
1568
- });
1569
- payload.issues = [];
1570
- }
1571
- return payload;
1572
- };
1573
- });
1574
- const $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => {
1575
- $ZodType.init(inst, def);
1576
- inst._zod.parse = (payload, _ctx) => {
1577
- if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) {
1578
- payload.issues.push({
1579
- input: payload.value,
1580
- inst,
1581
- expected: "nan",
1582
- code: "invalid_type"
1583
- });
1584
- return payload;
1585
- }
1586
- return payload;
1587
- };
1588
- });
1589
- const $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
1590
- $ZodType.init(inst, def);
1591
- defineLazy(inst._zod, "values", () => def.in._zod.values);
1592
- defineLazy(inst._zod, "optin", () => def.in._zod.optin);
1593
- defineLazy(inst._zod, "optout", () => def.out._zod.optout);
1594
- inst._zod.parse = (payload, ctx) => {
1595
- const left = def.in._zod.run(payload, ctx);
1596
- if (left instanceof Promise) {
1597
- return left.then((left2) => handlePipeResult(left2, def, ctx));
1598
- }
1599
- return handlePipeResult(left, def, ctx);
1600
- };
1601
- });
1602
- function handlePipeResult(left, def, ctx) {
1603
- if (aborted(left)) {
1604
- return left;
1605
- }
1606
- return def.out._zod.run({ value: left.value, issues: left.issues }, ctx);
1607
- }
1608
- const $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
1609
- $ZodType.init(inst, def);
1610
- defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
1611
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
1612
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
1613
- inst._zod.parse = (payload, ctx) => {
1614
- const result = def.innerType._zod.run(payload, ctx);
1615
- if (result instanceof Promise) {
1616
- return result.then(handleReadonlyResult);
1617
- }
1618
- return handleReadonlyResult(result);
1619
- };
1620
- });
1621
- function handleReadonlyResult(payload) {
1622
- payload.value = Object.freeze(payload.value);
1623
- return payload;
1624
- }
1625
- const $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => {
1626
- $ZodType.init(inst, def);
1627
- const regexParts = [];
1628
- for (const part of def.parts) {
1629
- if (part instanceof $ZodType) {
1630
- if (!part._zod.pattern) {
1631
- throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);
1632
- }
1633
- const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;
1634
- if (!source)
1635
- throw new Error(`Invalid template literal part: ${part._zod.traits}`);
1636
- const start = source.startsWith("^") ? 1 : 0;
1637
- const end = source.endsWith("$") ? source.length - 1 : source.length;
1638
- regexParts.push(source.slice(start, end));
1639
- } else if (part === null || primitiveTypes.has(typeof part)) {
1640
- regexParts.push(escapeRegex(`${part}`));
1641
- } else {
1642
- throw new Error(`Invalid template literal part: ${part}`);
1643
- }
1644
- }
1645
- inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`);
1646
- inst._zod.parse = (payload, _ctx) => {
1647
- if (typeof payload.value !== "string") {
1648
- payload.issues.push({
1649
- input: payload.value,
1650
- inst,
1651
- expected: "template_literal",
1652
- code: "invalid_type"
1653
- });
1654
- return payload;
1655
- }
1656
- inst._zod.pattern.lastIndex = 0;
1657
- if (!inst._zod.pattern.test(payload.value)) {
1658
- payload.issues.push({
1659
- input: payload.value,
1660
- inst,
1661
- code: "invalid_format",
1662
- format: "template_literal",
1663
- pattern: inst._zod.pattern.source
1664
- });
1665
- return payload;
1666
- }
1667
- return payload;
1668
- };
1669
- });
1670
- const $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => {
1671
- $ZodType.init(inst, def);
1672
- inst._zod.parse = (payload, ctx) => {
1673
- return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));
1674
- };
1675
- });
1676
- const $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => {
1677
- $ZodType.init(inst, def);
1678
- defineLazy(inst._zod, "innerType", () => def.getter());
1679
- defineLazy(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern);
1680
- defineLazy(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues);
1681
- defineLazy(inst._zod, "optin", () => inst._zod.innerType._zod.optin);
1682
- defineLazy(inst._zod, "optout", () => inst._zod.innerType._zod.optout);
1683
- inst._zod.parse = (payload, ctx) => {
1684
- const inner = inst._zod.innerType;
1685
- return inner._zod.run(payload, ctx);
1686
- };
1687
- });
1688
- const $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
1689
- $ZodCheck.init(inst, def);
1690
- $ZodType.init(inst, def);
1691
- inst._zod.parse = (payload, _) => {
1692
- return payload;
1693
- };
1694
- inst._zod.check = (payload) => {
1695
- const input = payload.value;
1696
- const r = def.fn(input);
1697
- if (r instanceof Promise) {
1698
- return r.then((r2) => handleRefineResult(r2, payload, input, inst));
1699
- }
1700
- handleRefineResult(r, payload, input, inst);
1701
- return;
1702
- };
1703
- });
1704
- function handleRefineResult(result, payload, input, inst) {
1705
- if (!result) {
1706
- const _iss = {
1707
- code: "custom",
1708
- input,
1709
- inst,
1710
- // incorporates params.error into issue reporting
1711
- path: [...inst._zod.def.path ?? []],
1712
- // incorporates params.error into issue reporting
1713
- continue: !inst._zod.def.abort
1714
- // params: inst._zod.def.params,
1715
- };
1716
- if (inst._zod.def.params)
1717
- _iss.params = inst._zod.def.params;
1718
- payload.issues.push(issue(_iss));
1719
- }
1720
- }
1721
-
1722
- class TsTypeNode {
1723
- static fromZod(zodType) {
1724
- if (zodType instanceof $ZodString) {
1725
- return TsTypeNode.fromZodString(zodType);
1726
- }
1727
- if (zodType instanceof $ZodNumber) {
1728
- return TsTypeNode.fromZodNumber(zodType);
1729
- }
1730
- if (zodType instanceof $ZodBigInt) {
1731
- return TsTypeNode.fromZodBigInt(zodType);
1732
- }
1733
- if (zodType instanceof $ZodBoolean) {
1734
- return TsTypeNode.fromZodBoolean(zodType);
1735
- }
1736
- if (zodType instanceof $ZodDate) {
1737
- return TsTypeNode.fromZodDate(zodType);
1738
- }
1739
- if (zodType instanceof $ZodSymbol) {
1740
- return TsTypeNode.fromZodSymbol(zodType);
1741
- }
1742
- if (zodType instanceof $ZodUndefined) {
1743
- return TsTypeNode.fromZodUndefined(zodType);
1744
- }
1745
- if (zodType instanceof $ZodNullable) {
1746
- return TsTypeNode.fromZodNullable(zodType);
1747
- }
1748
- if (zodType instanceof $ZodNull) {
1749
- return TsTypeNode.fromZodNull(zodType);
1750
- }
1751
- if (zodType instanceof $ZodAny) {
1752
- return TsTypeNode.fromZodAny(zodType);
1753
- }
1754
- if (zodType instanceof $ZodUnknown) {
1755
- return TsTypeNode.fromZodUnknown(zodType);
1756
- }
1757
- if (zodType instanceof $ZodNever) {
1758
- return TsTypeNode.fromZodNever(zodType);
1759
- }
1760
- if (zodType instanceof $ZodVoid) {
1761
- return TsTypeNode.fromZodVoid(zodType);
1762
- }
1763
- if (zodType instanceof $ZodArray) {
1764
- return TsTypeNode.fromZodArray(zodType);
1765
- }
1766
- if (zodType instanceof $ZodObject) {
1767
- return TsTypeNode.fromZodObject(zodType);
1768
- }
1769
- if (zodType instanceof $ZodUnion) {
1770
- return TsTypeNode.fromZodUnion(zodType);
1771
- }
1772
- if (zodType instanceof $ZodIntersection) {
1773
- return TsTypeNode.fromZodIntersection(zodType);
1774
- }
1775
- if (zodType instanceof $ZodTuple) {
1776
- return TsTypeNode.fromZodTuple(zodType);
1777
- }
1778
- if (zodType instanceof $ZodRecord) {
1779
- return TsTypeNode.fromZodRecord(zodType);
1780
- }
1781
- if (zodType instanceof $ZodMap) {
1782
- return TsTypeNode.fromZodMap(zodType);
1783
- }
1784
- if (zodType instanceof $ZodSet) {
1785
- return TsTypeNode.fromZodSet(zodType);
1786
- }
1787
- if (zodType instanceof $ZodLiteral) {
1788
- if (!TsTypeNode) {
1789
- throw new Error("ZodLiteral has no values");
1790
- }
1791
- return TsTypeNode.fromZodLiteral(zodType);
1792
- }
1793
- if (zodType instanceof $ZodEnum) {
1794
- return TsTypeNode.fromZodEnum(zodType);
1795
- }
1796
- if (zodType instanceof $ZodPromise) {
1797
- return TsTypeNode.fromZodPromise(zodType);
1798
- }
1799
- if (zodType instanceof $ZodLazy) {
1800
- return TsTypeNode.fromZodLazy(zodType);
1801
- }
1802
- if (zodType instanceof $ZodOptional) {
1803
- return TsTypeNode.fromZodOptional(zodType);
1804
- }
1805
- if (zodType instanceof $ZodDefault) {
1806
- return TsTypeNode.fromZodDefault(zodType);
1807
- }
1808
- if (zodType instanceof $ZodTemplateLiteral) {
1809
- return TsTypeNode.fromZodTemplateLiteral(zodType);
1810
- }
1811
- if (zodType instanceof $ZodCustom) {
1812
- return TsTypeNode.fromZodCustom(zodType);
1813
- }
1814
- if (zodType instanceof $ZodTransform) {
1815
- return TsTypeNode.fromZodTransform(zodType);
1816
- }
1817
- if (zodType instanceof $ZodNonOptional) {
1818
- return TsTypeNode.fromZodNonOptional(zodType);
1819
- }
1820
- if (zodType instanceof $ZodReadonly) {
1821
- return TsTypeNode.fromZodReadonly(zodType);
1822
- }
1823
- if (zodType instanceof $ZodNaN) {
1824
- return TsTypeNode.fromZodNaN(zodType);
1825
- }
1826
- if (zodType instanceof $ZodPipe) {
1827
- return TsTypeNode.fromZodPipe(zodType);
1828
- }
1829
- if (zodType instanceof $ZodSuccess) {
1830
- return TsTypeNode.fromZodSuccess(zodType);
1831
- }
1832
- if (zodType instanceof $ZodCatch) {
1833
- return TsTypeNode.fromZodCatch(zodType);
1834
- }
1835
- if (zodType instanceof $ZodFile) {
1836
- return TsTypeNode.fromZodFile(zodType);
1837
- }
1838
- return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
1839
- }
1840
- static fromZodString(zodString) {
1841
- return factory.createKeywordTypeNode(SyntaxKind.StringKeyword);
1842
- }
1843
- static fromZodNumber(zodNumber) {
1844
- return factory.createKeywordTypeNode(SyntaxKind.NumberKeyword);
1845
- }
1846
- static fromZodBigInt(zodBigInt) {
1847
- return factory.createKeywordTypeNode(SyntaxKind.BigIntKeyword);
1848
- }
1849
- static fromZodBoolean(zodBoolean) {
1850
- return factory.createKeywordTypeNode(SyntaxKind.BooleanKeyword);
1851
- }
1852
- static fromZodDate(zodDate) {
1853
- return factory.createTypeReferenceNode(factory.createIdentifier("Date"));
1854
- }
1855
- static fromZodSymbol(zodSymbol) {
1856
- return factory.createKeywordTypeNode(SyntaxKind.SymbolKeyword);
1857
- }
1858
- static fromZodUndefined(zodUndefined) {
1859
- return factory.createKeywordTypeNode(SyntaxKind.UndefinedKeyword);
1860
- }
1861
- static fromZodNullable(zodNullable) {
1862
- const innerType = TsTypeNode.fromZod(zodNullable._zod.def.innerType);
1863
- return factory.createUnionTypeNode([
1864
- innerType,
1865
- factory.createLiteralTypeNode(factory.createNull())
1866
- ]);
1867
- }
1868
- static fromZodNull(zodNull) {
1869
- return factory.createLiteralTypeNode(factory.createNull());
1870
- }
1871
- static fromZodAny(zodAny) {
1872
- return factory.createKeywordTypeNode(SyntaxKind.AnyKeyword);
1873
- }
1874
- static fromZodUnknown(zodUnknown) {
1875
- return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
1876
- }
1877
- static fromZodNever(zodNever) {
1878
- return factory.createKeywordTypeNode(SyntaxKind.NeverKeyword);
1879
- }
1880
- static fromZodVoid(zodVoid) {
1881
- return factory.createKeywordTypeNode(SyntaxKind.VoidKeyword);
1882
- }
1883
- static fromZodArray(zodArray) {
1884
- const innerType = TsTypeNode.fromZod(zodArray._zod.def.element);
1885
- return factory.createArrayTypeNode(innerType);
1886
- }
1887
- static fromZodObject(zodObject) {
1888
- const entries = Object.entries(zodObject._zod.def.shape);
1889
- const members = entries.map(([key, nextZodNode]) => {
1890
- const type = TsTypeNode.fromZod(nextZodNode);
1891
- if (!nextZodNode._zod?.def) {
1892
- console.warn(
1893
- `Zod node for key "${key}" does not have a _zod.def property. This may indicate an issue with the Zod schema.`,
1894
- {
1895
- key
1896
- }
1897
- );
1898
- }
1899
- const { type: nextZodNodeTypeName } = nextZodNode._zod?.def ?? {};
1900
- const isOptional = nextZodNodeTypeName === "optional";
1901
- const propertySignature = factory.createPropertySignature(
1902
- void 0,
1903
- TsTypeNode.createTsAstPropertyKey(key),
1904
- isOptional ? factory.createToken(SyntaxKind.QuestionToken) : void 0,
1905
- type
1906
- );
1907
- return propertySignature;
1908
- });
1909
- return factory.createTypeLiteralNode(members);
1910
- }
1911
- static fromZodUnion(zodUnion) {
1912
- const options = zodUnion._zod.def.options.map(TsTypeNode.fromZod);
1913
- return factory.createUnionTypeNode(options);
1914
- }
1915
- static fromZodIntersection(zodIntersection) {
1916
- const left = TsTypeNode.fromZod(zodIntersection._zod.def.left);
1917
- const right = TsTypeNode.fromZod(zodIntersection._zod.def.right);
1918
- return factory.createIntersectionTypeNode([left, right]);
1919
- }
1920
- static fromZodTuple(zodTuple) {
1921
- const elements = zodTuple._zod.def.items.map(TsTypeNode.fromZod);
1922
- return factory.createTupleTypeNode(elements);
1923
- }
1924
- static fromZodRecord(zodRecord) {
1925
- const keyType = TsTypeNode.fromZod(zodRecord._zod.def.keyType);
1926
- const valueType = TsTypeNode.fromZod(zodRecord._zod.def.valueType);
1927
- return factory.createTypeReferenceNode(factory.createIdentifier("Record"), [
1928
- keyType,
1929
- valueType
1930
- ]);
1931
- }
1932
- static fromZodMap(zodMap) {
1933
- const keyType = TsTypeNode.fromZod(zodMap._zod.def.keyType);
1934
- const valueType = TsTypeNode.fromZod(zodMap._zod.def.valueType);
1935
- return factory.createTypeReferenceNode(factory.createIdentifier("Map"), [
1936
- keyType,
1937
- valueType
1938
- ]);
1939
- }
1940
- static fromZodSet(zodSet) {
1941
- const innerType = TsTypeNode.fromZod(zodSet._zod.def.valueType);
1942
- return factory.createTypeReferenceNode(factory.createIdentifier("Set"), [
1943
- innerType
1944
- ]);
1945
- }
1946
- static fromZodLiteral(zodLiteral) {
1947
- if (zodLiteral._zod.def.values.length === 0) {
1948
- throw new Error("ZodLiteral has no values");
1949
- }
1950
- const value = zodLiteral._zod.def.values[0];
1951
- if (typeof value === "string") {
1952
- return factory.createLiteralTypeNode(factory.createStringLiteral(value));
1953
- }
1954
- if (typeof value === "number") {
1955
- return factory.createLiteralTypeNode(factory.createNumericLiteral(value));
1956
- }
1957
- if (typeof value === "boolean") {
1958
- return factory.createLiteralTypeNode(
1959
- value ? factory.createTrue() : factory.createFalse()
1960
- );
1961
- }
1962
- if (typeof value === "bigint") {
1963
- return factory.createLiteralTypeNode(
1964
- factory.createBigIntLiteral(value.toString())
1965
- );
1966
- }
1967
- if (value === null) {
1968
- return factory.createLiteralTypeNode(factory.createNull());
1969
- }
1970
- if (value === void 0) {
1971
- return factory.createKeywordTypeNode(SyntaxKind.UndefinedKeyword);
1972
- }
1973
- throw new Error(`Unsupported literal type: ${typeof value}`);
1974
- }
1975
- static fromZodEnum(zodEnum) {
1976
- const entries = Object.entries(zodEnum._zod.def.entries);
1977
- const types = entries.map(([key, value]) => {
1978
- return factory.createLiteralTypeNode(factory.createStringLiteral(key));
1979
- });
1980
- return factory.createUnionTypeNode(types);
1981
- }
1982
- static fromZodPromise(zodPromise) {
1983
- const innerType = TsTypeNode.fromZod(zodPromise._zod.def.innerType);
1984
- return factory.createTypeReferenceNode(
1985
- factory.createIdentifier("Promise"),
1986
- [innerType]
1987
- );
1988
- }
1989
- static fromZodLazy(zodLazy) {
1990
- return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
1991
- }
1992
- static fromZodOptional(zodOptional) {
1993
- const innerType = TsTypeNode.fromZod(zodOptional._zod.def.innerType);
1994
- return factory.createUnionTypeNode([
1995
- innerType,
1996
- factory.createKeywordTypeNode(SyntaxKind.UndefinedKeyword)
1997
- ]);
1998
- }
1999
- static fromZodDefault(zodDefault) {
2000
- const innerType = TsTypeNode.fromZod(zodDefault._zod.def.innerType);
2001
- const filteredNodes = [];
2002
- innerType.forEachChild((node) => {
2003
- if (node.kind !== SyntaxKind.UndefinedKeyword) {
2004
- filteredNodes.push(node);
2005
- }
2006
- });
2007
- innerType.types = filteredNodes;
2008
- return innerType;
2009
- }
2010
- static fromZodTemplateLiteral(zodTemplateLiteral) {
2011
- return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
2012
- }
2013
- static fromZodCustom(zodCustom) {
2014
- return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
2015
- }
2016
- static fromZodTransform(zodTransform) {
2017
- return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
2018
- }
2019
- static fromZodNonOptional(zodNonOptional) {
2020
- return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
2021
- }
2022
- static fromZodReadonly(zodReadonly) {
2023
- return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
2024
- }
2025
- static fromZodNaN(zodNaN) {
2026
- return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
2027
- }
2028
- static fromZodPipe(zodPipe) {
2029
- return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
2030
- }
2031
- static fromZodSuccess(zodSuccess) {
2032
- return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
2033
- }
2034
- static fromZodCatch(zodCatch) {
2035
- return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
2036
- }
2037
- static fromZodFile(zodFile) {
2038
- return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
2039
- }
2040
- /**
2041
- * Returns a TypeScript AST node representing the property key.
2042
- * If the key is a valid JavaScript identifier, returns an Identifier node.
2043
- * Otherwise, returns a StringLiteral node.
2044
- *
2045
- * @param {string} key - The property key to convert.
2046
- * @returns {Identifier | StringLiteral} The corresponding AST node for the property key.
2047
- */
2048
- static createTsAstPropertyKey(key) {
2049
- if (/^[$A-Z_a-z][\w$]*$/.test(key)) {
2050
- return factory.createIdentifier(key);
2051
- }
2052
- return factory.createStringLiteral(key);
2053
- }
2054
- }
2055
-
2056
- class TsTypePrinter {
2057
- static print(tsType) {
2058
- const sourceFile = createSourceFile(
2059
- "print.ts",
2060
- "",
2061
- ScriptTarget.Latest,
2062
- false,
2063
- ScriptKind.TS
2064
- );
2065
- const printer = createPrinter();
2066
- return printer.printNode(EmitHint.Unspecified, tsType, sourceFile);
2067
- }
2068
- }
3
+ import { Path, BasePlugin } from '@rexeus/typeweaver-gen';
4
+ import { TsTypePrinter, TsTypeNode } from '@rexeus/typeweaver-zod-to-ts';
5
+ import Case from 'case';
6
+ import { HttpStatusCode } from '@rexeus/typeweaver-core';
2069
7
 
2070
8
  const __dirname$5 = path.dirname(fileURLToPath(import.meta.url));
2071
- class SharedResponseGenerator {
2072
- static generate(context) {
2073
- const templateFile = path.join(
2074
- __dirname$5,
2075
- "templates",
2076
- "SharedResponse.ejs"
2077
- );
2078
- for (const sharedResponse of context.resources.sharedResponseResources) {
2079
- this.writeSharedResponse(templateFile, sharedResponse, context);
2080
- }
2081
- }
2082
- static writeSharedResponse(templateFile, sharedResponse, context) {
2083
- const headerTsType = sharedResponse.header ? TsTypePrinter.print(TsTypeNode.fromZod(sharedResponse.header)) : void 0;
2084
- const bodyTsType = sharedResponse.body ? TsTypePrinter.print(TsTypeNode.fromZod(sharedResponse.body)) : void 0;
2085
- const pascalCaseName = Case.pascal(sharedResponse.name);
2086
- const content = context.renderTemplate(templateFile, {
2087
- coreDir: context.coreDir,
2088
- httpStatusCode: HttpStatusCode,
2089
- headerTsType,
2090
- bodyTsType,
2091
- pascalCaseName,
2092
- sharedResponse
2093
- });
2094
- const relativePath = path.relative(context.outputDir, sharedResponse.outputFile);
2095
- context.writeFile(relativePath, content);
2096
- }
2097
- }
2098
-
2099
- const __dirname$4 = path.dirname(fileURLToPath(import.meta.url));
2100
9
  class RequestGenerator {
2101
10
  static generate(context) {
2102
- const templateFilePath = path.join(__dirname$4, "templates", "Request.ejs");
2103
- for (const [, operationResources] of Object.entries(
11
+ const templateFilePath = path.join(__dirname$5, "templates", "Request.ejs");
12
+ for (const [, entityResource] of Object.entries(
2104
13
  context.resources.entityResources
2105
14
  )) {
2106
- for (const definition of operationResources) {
15
+ for (const definition of entityResource.operations) {
2107
16
  this.writeRequestType(templateFilePath, definition, context);
2108
17
  }
2109
18
  }
@@ -2124,31 +33,41 @@ class RequestGenerator {
2124
33
  const pascalCaseOperationId = Case.pascal(operationId);
2125
34
  const sourcePath = Path.relative(
2126
35
  outputDir,
2127
- `${operationResource.sourceDir}/${path.basename(operationResource.sourceFile, ".ts")}`
36
+ `${operationResource.sourceDir}/${path.relative(operationResource.sourceDir, operationResource.sourceFile).replace(/\.ts$/, "")}`
2128
37
  );
2129
38
  const ownSuccessResponses = [];
2130
39
  const ownErrorResponses = [];
2131
40
  const sharedSuccessResponses = [];
2132
41
  const sharedErrorResponses = [];
2133
42
  for (const response of responses) {
2134
- const { statusCode, name, isShared } = response;
2135
- if (isShared) {
43
+ const { statusCode, name, isReference } = response;
44
+ if (isReference) {
2136
45
  const sharedResponse = context.resources.sharedResponseResources.find(
2137
- (resource) => {
2138
- return resource.name === name;
2139
- }
46
+ (resource) => resource.name === name
2140
47
  );
48
+ let responsePath;
2141
49
  if (!sharedResponse) {
2142
- throw new Error(
2143
- `Shared response '${response.name}' not found in shared resources`
50
+ const entityResponses = context.resources.entityResources[operationResource.entityName]?.responses;
51
+ const entityResponse = entityResponses?.find((r) => r.name === name);
52
+ if (entityResponse) {
53
+ responsePath = Path.relative(
54
+ outputDir,
55
+ `${entityResponse.outputDir}/${path.basename(entityResponse.outputFileName, ".ts")}`
56
+ );
57
+ } else {
58
+ throw new Error(
59
+ `Shared response '${response.name}' not found in shared or entity resources`
60
+ );
61
+ }
62
+ } else {
63
+ responsePath = Path.relative(
64
+ outputDir,
65
+ `${sharedResponse.outputDir}/${path.basename(sharedResponse.outputFileName, ".ts")}`
2144
66
  );
2145
67
  }
2146
68
  const assembledResponse2 = {
2147
69
  name,
2148
- path: Path.relative(
2149
- outputDir,
2150
- `${sharedResponse.outputDir}/${path.basename(sharedResponse.outputFileName, ".ts")}`
2151
- )
70
+ path: responsePath
2152
71
  };
2153
72
  if (statusCode >= 200 && statusCode < 300) {
2154
73
  sharedSuccessResponses.push(assembledResponse2);
@@ -2191,23 +110,26 @@ class RequestGenerator {
2191
110
  hasErrorResponses: ownErrorResponses.length > 0 || sharedErrorResponses.length > 0,
2192
111
  hasSuccessResponses: ownSuccessResponses.length > 0 || sharedSuccessResponses.length > 0
2193
112
  });
2194
- const relativePath = path.relative(context.outputDir, operationResource.outputRequestFile);
113
+ const relativePath = path.relative(
114
+ context.outputDir,
115
+ operationResource.outputRequestFile
116
+ );
2195
117
  context.writeFile(relativePath, content);
2196
118
  }
2197
119
  }
2198
120
 
2199
- const __dirname$3 = path.dirname(fileURLToPath(import.meta.url));
121
+ const __dirname$4 = path.dirname(fileURLToPath(import.meta.url));
2200
122
  class RequestValidationGenerator {
2201
123
  static generate(context) {
2202
124
  const templateFilePath = path.join(
2203
- __dirname$3,
125
+ __dirname$4,
2204
126
  "templates",
2205
127
  "RequestValidator.ejs"
2206
128
  );
2207
- for (const [, operationResources] of Object.entries(
129
+ for (const [, entityResource] of Object.entries(
2208
130
  context.resources.entityResources
2209
131
  )) {
2210
- for (const definition of operationResources) {
132
+ for (const definition of entityResource.operations) {
2211
133
  this.writeRequestValidator(templateFilePath, definition, context);
2212
134
  }
2213
135
  }
@@ -2222,7 +144,7 @@ class RequestValidationGenerator {
2222
144
  operationId,
2223
145
  sourcePath: Path.relative(
2224
146
  outputDir,
2225
- `${operationResource.sourceDir}/${path.basename(operationResource.sourceFile, ".ts")}`
147
+ `${operationResource.sourceDir}/${path.relative(operationResource.sourceDir, operationResource.sourceFile).replace(/\.ts$/, "")}`
2226
148
  ),
2227
149
  corePath: context.coreDir,
2228
150
  requestFile: Path.relative(
@@ -2234,21 +156,36 @@ class RequestValidationGenerator {
2234
156
  param,
2235
157
  header
2236
158
  });
2237
- const relativePath = path.relative(context.outputDir, operationResource.outputRequestValidationFile);
159
+ const relativePath = path.relative(
160
+ context.outputDir,
161
+ operationResource.outputRequestValidationFile
162
+ );
2238
163
  context.writeFile(relativePath, content);
2239
164
  }
2240
165
  }
2241
166
 
2242
- const __dirname$2 = path.dirname(fileURLToPath(import.meta.url));
167
+ const __dirname$3 = path.dirname(fileURLToPath(import.meta.url));
2243
168
  class ResponseGenerator {
2244
169
  static generate(context) {
2245
- const templateFile = path.join(__dirname$2, "templates", "Response.ejs");
2246
- for (const [, operationResources] of Object.entries(
170
+ const templateFile = path.join(__dirname$3, "templates", "Response.ejs");
171
+ const sharedResponseTemplateFile = path.join(
172
+ __dirname$3,
173
+ "templates",
174
+ "SharedResponse.ejs"
175
+ );
176
+ for (const [, entityResource] of Object.entries(
2247
177
  context.resources.entityResources
2248
178
  )) {
2249
- for (const definition of operationResources) {
179
+ for (const definition of entityResource.operations) {
2250
180
  this.writeResponseType(templateFile, definition, context);
2251
181
  }
182
+ for (const responseResource of entityResource.responses) {
183
+ this.writeEntityResponseType(
184
+ sharedResponseTemplateFile,
185
+ responseResource,
186
+ context
187
+ );
188
+ }
2252
189
  }
2253
190
  }
2254
191
  static writeResponseType(templateFile, resource, context) {
@@ -2265,25 +202,35 @@ class ResponseGenerator {
2265
202
  const ownResponses = [];
2266
203
  const sharedResponses = [];
2267
204
  for (const response of responses) {
2268
- const { statusCode, name, isShared, body, header } = response;
2269
- if (isShared) {
205
+ const { statusCode, name, body, header, isReference } = response;
206
+ if (isReference) {
2270
207
  const sharedResponse = context.resources.sharedResponseResources.find(
2271
- (resource2) => {
2272
- return resource2.name === name;
2273
- }
208
+ (resource2) => resource2.name === name
2274
209
  );
2275
- if (!sharedResponse) {
2276
- throw new Error(
2277
- `Shared response '${response.name}' not found in shared resources`
2278
- );
210
+ if (sharedResponse) {
211
+ sharedResponses.push({
212
+ name,
213
+ path: Path.relative(
214
+ outputDir,
215
+ `${sharedResponse.outputDir}/${path.basename(sharedResponse.outputFileName, ".ts")}`
216
+ )
217
+ });
218
+ } else {
219
+ const entityResponses = context.resources.entityResources[resource.entityName]?.responses;
220
+ const entityResponse = entityResponses?.find((r) => r.name === name);
221
+ if (!entityResponse) {
222
+ throw new Error(
223
+ `Response ${name} not found in shared or entity-specific responses`
224
+ );
225
+ }
226
+ sharedResponses.push({
227
+ name,
228
+ path: Path.relative(
229
+ outputDir,
230
+ `${entityResponse.outputDir}/${path.basename(entityResponse.outputFileName, ".ts")}`
231
+ )
232
+ });
2279
233
  }
2280
- sharedResponses.push({
2281
- name,
2282
- path: Path.relative(
2283
- outputDir,
2284
- `${sharedResponse.outputDir}/${path.basename(sharedResponse.outputFileName, ".ts")}`
2285
- )
2286
- });
2287
234
  continue;
2288
235
  }
2289
236
  ownResponses.push({
@@ -2306,27 +253,48 @@ class ResponseGenerator {
2306
253
  ),
2307
254
  sourcePath: Path.relative(
2308
255
  outputDir,
2309
- `${sourceDir}/${path.basename(sourceFile, ".ts")}`
256
+ `${sourceDir}/${path.relative(sourceDir, sourceFile).replace(/\.ts$/, "")}`
2310
257
  )
2311
258
  });
2312
259
  const relativePath = path.relative(context.outputDir, outputResponseFile);
2313
260
  context.writeFile(relativePath, content);
2314
261
  }
262
+ static writeEntityResponseType(templateFile, resource, context) {
263
+ const { name, body, header, outputFile } = resource;
264
+ const pascalCaseName = Case.pascal(name);
265
+ const headerTsType = header ? TsTypePrinter.print(TsTypeNode.fromZod(header)) : void 0;
266
+ const bodyTsType = body ? TsTypePrinter.print(TsTypeNode.fromZod(body)) : void 0;
267
+ const content = context.renderTemplate(templateFile, {
268
+ coreDir: context.coreDir,
269
+ httpStatusCode: HttpStatusCode,
270
+ headerTsType,
271
+ bodyTsType,
272
+ pascalCaseName,
273
+ sharedResponse: resource
274
+ // The template expects this property name
275
+ });
276
+ const relativePath = path.relative(context.outputDir, outputFile);
277
+ context.writeFile(relativePath, content);
278
+ }
2315
279
  }
2316
280
 
2317
- const __dirname$1 = path.dirname(fileURLToPath(import.meta.url));
281
+ const __dirname$2 = path.dirname(fileURLToPath(import.meta.url));
2318
282
  class ResponseValidationGenerator {
2319
283
  static generate(context) {
2320
284
  const templateFilePath = path.join(
2321
- __dirname$1,
285
+ __dirname$2,
2322
286
  "templates",
2323
287
  "ResponseValidator.ejs"
2324
288
  );
2325
- for (const [, operationResources] of Object.entries(
289
+ for (const [, entityResource] of Object.entries(
2326
290
  context.resources.entityResources
2327
291
  )) {
2328
- for (const operationResource of operationResources) {
2329
- this.writeResponseValidator(templateFilePath, operationResource, context);
292
+ for (const operationResource of entityResource.operations) {
293
+ this.writeResponseValidator(
294
+ templateFilePath,
295
+ operationResource,
296
+ context
297
+ );
2330
298
  }
2331
299
  }
2332
300
  }
@@ -2345,7 +313,7 @@ class ResponseValidationGenerator {
2345
313
  const sharedResponses = [];
2346
314
  const allStatusCodes = [];
2347
315
  for (const response of responses) {
2348
- const { statusCode, name, isShared, body, header, statusCodeName } = response;
316
+ const { statusCode, name, isReference, body, header, statusCodeName } = response;
2349
317
  const index = responses.indexOf(response);
2350
318
  const isStatusCodeIncluded = allStatusCodes.some((status) => {
2351
319
  return status.statusCode === statusCode;
@@ -2356,23 +324,33 @@ class ResponseValidationGenerator {
2356
324
  name: statusCodeName
2357
325
  });
2358
326
  }
2359
- if (isShared) {
327
+ if (isReference) {
2360
328
  const sharedResponse = context.resources.sharedResponseResources.find(
2361
- (resource2) => {
2362
- return resource2.name === name;
2363
- }
329
+ (resource2) => resource2.name === name
2364
330
  );
331
+ let importPath;
2365
332
  if (!sharedResponse) {
2366
- throw new Error(
2367
- `Shared response '${response.name}' not found in shared resources`
333
+ const entityResponses = context.resources.entityResources[resource.entityName]?.responses;
334
+ const entityResponse = entityResponses?.find((r) => r.name === name);
335
+ if (entityResponse) {
336
+ importPath = Path.relative(
337
+ outputDir,
338
+ `${entityResponse.outputDir}/${path.basename(entityResponse.outputFileName, ".ts")}`
339
+ );
340
+ } else {
341
+ throw new Error(
342
+ `Shared response '${response.name}' not found in shared or entity resources`
343
+ );
344
+ }
345
+ } else {
346
+ importPath = Path.relative(
347
+ outputDir,
348
+ `${sharedResponse.outputDir}/${path.basename(sharedResponse.outputFileName, ".ts")}`
2368
349
  );
2369
350
  }
2370
351
  sharedResponses.push({
2371
352
  name,
2372
- importPath: Path.relative(
2373
- outputDir,
2374
- `${sharedResponse.outputDir}/${path.basename(sharedResponse.outputFileName, ".ts")}`
2375
- ),
353
+ importPath,
2376
354
  hasBody: !!body,
2377
355
  hasHeader: !!header,
2378
356
  statusCode,
@@ -2396,13 +374,48 @@ class ResponseValidationGenerator {
2396
374
  responseFile: `./${path.basename(outputResponseFileName, ".ts")}`,
2397
375
  sourcePath: Path.relative(
2398
376
  outputDir,
2399
- `${sourceDir}/${path.basename(sourceFile, ".ts")}`
377
+ `${sourceDir}/${path.relative(sourceDir, sourceFile).replace(/\.ts$/, "")}`
2400
378
  ),
2401
379
  sharedResponses,
2402
380
  ownResponses,
2403
381
  allStatusCodes
2404
382
  });
2405
- const relativePath = path.relative(context.outputDir, outputResponseValidationFile);
383
+ const relativePath = path.relative(
384
+ context.outputDir,
385
+ outputResponseValidationFile
386
+ );
387
+ context.writeFile(relativePath, content);
388
+ }
389
+ }
390
+
391
+ const __dirname$1 = path.dirname(fileURLToPath(import.meta.url));
392
+ class SharedResponseGenerator {
393
+ static generate(context) {
394
+ const templateFile = path.join(
395
+ __dirname$1,
396
+ "templates",
397
+ "SharedResponse.ejs"
398
+ );
399
+ for (const sharedResponse of context.resources.sharedResponseResources) {
400
+ this.writeSharedResponse(templateFile, sharedResponse, context);
401
+ }
402
+ }
403
+ static writeSharedResponse(templateFile, sharedResponse, context) {
404
+ const headerTsType = sharedResponse.header ? TsTypePrinter.print(TsTypeNode.fromZod(sharedResponse.header)) : void 0;
405
+ const bodyTsType = sharedResponse.body ? TsTypePrinter.print(TsTypeNode.fromZod(sharedResponse.body)) : void 0;
406
+ const pascalCaseName = Case.pascal(sharedResponse.name);
407
+ const content = context.renderTemplate(templateFile, {
408
+ coreDir: context.coreDir,
409
+ httpStatusCode: HttpStatusCode,
410
+ headerTsType,
411
+ bodyTsType,
412
+ pascalCaseName,
413
+ sharedResponse
414
+ });
415
+ const relativePath = path.relative(
416
+ context.outputDir,
417
+ sharedResponse.outputFile
418
+ );
2406
419
  context.writeFile(relativePath, content);
2407
420
  }
2408
421
  }