@stryke/prisma-trpc-generator 0.13.26 → 0.13.34

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/generator.js DELETED
@@ -1,4211 +0,0 @@
1
- #! /usr/bin/env node
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
10
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
11
- }) : x)(function(x) {
12
- if (typeof require !== "undefined") return require.apply(this, arguments);
13
- throw Error('Dynamic require of "' + x + '" is not supported');
14
- });
15
- var __esm = (fn, res) => function __init() {
16
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
17
- };
18
- var __commonJS = (cb, mod) => function __require2() {
19
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
20
- };
21
- var __copyProps = (to, from, except, desc) => {
22
- if (from && typeof from === "object" || typeof from === "function") {
23
- for (let key of __getOwnPropNames(from))
24
- if (!__hasOwnProp.call(to, key) && key !== except)
25
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
26
- }
27
- return to;
28
- };
29
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
30
- // If the importer is in node compatibility mode or this is not an ESM
31
- // file that has been converted to a CommonJS file using a Babel-
32
- // compatible transform (i.e. "__esModule" has not been set), then set
33
- // "default" to the CommonJS "module.exports" for node compatibility.
34
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
35
- mod
36
- ));
37
-
38
- // ../../node_modules/.pnpm/tsup@8.5.1_@microsoft+api-extractor@7.55.1_@types+node@24.10.1__@swc+core@1.15.3_@swc+h_88727a58a5077acdeb714aa851988eef/node_modules/tsup/assets/esm_shims.js
39
- var init_esm_shims = __esm({
40
- "../../node_modules/.pnpm/tsup@8.5.1_@microsoft+api-extractor@7.55.1_@types+node@24.10.1__@swc+core@1.15.3_@swc+h_88727a58a5077acdeb714aa851988eef/node_modules/tsup/assets/esm_shims.js"() {
41
- "use strict";
42
- }
43
- });
44
-
45
- // ../../node_modules/.pnpm/pluralize@8.0.0/node_modules/pluralize/pluralize.js
46
- var require_pluralize = __commonJS({
47
- "../../node_modules/.pnpm/pluralize@8.0.0/node_modules/pluralize/pluralize.js"(exports, module) {
48
- "use strict";
49
- init_esm_shims();
50
- (function(root, pluralize2) {
51
- if (typeof __require === "function" && typeof exports === "object" && typeof module === "object") {
52
- module.exports = pluralize2();
53
- } else if (typeof define === "function" && define.amd) {
54
- define(function() {
55
- return pluralize2();
56
- });
57
- } else {
58
- root.pluralize = pluralize2();
59
- }
60
- })(exports, function() {
61
- var pluralRules = [];
62
- var singularRules = [];
63
- var uncountables = {};
64
- var irregularPlurals = {};
65
- var irregularSingles = {};
66
- function sanitizeRule(rule) {
67
- if (typeof rule === "string") {
68
- return new RegExp("^" + rule + "$", "i");
69
- }
70
- return rule;
71
- }
72
- __name(sanitizeRule, "sanitizeRule");
73
- function restoreCase(word, token) {
74
- if (word === token) return token;
75
- if (word === word.toLowerCase()) return token.toLowerCase();
76
- if (word === word.toUpperCase()) return token.toUpperCase();
77
- if (word[0] === word[0].toUpperCase()) {
78
- return token.charAt(0).toUpperCase() + token.substr(1).toLowerCase();
79
- }
80
- return token.toLowerCase();
81
- }
82
- __name(restoreCase, "restoreCase");
83
- function interpolate(str, args) {
84
- return str.replace(/\$(\d{1,2})/g, function(match, index) {
85
- return args[index] || "";
86
- });
87
- }
88
- __name(interpolate, "interpolate");
89
- function replace(word, rule) {
90
- return word.replace(rule[0], function(match, index) {
91
- var result = interpolate(rule[1], arguments);
92
- if (match === "") {
93
- return restoreCase(word[index - 1], result);
94
- }
95
- return restoreCase(match, result);
96
- });
97
- }
98
- __name(replace, "replace");
99
- function sanitizeWord(token, word, rules) {
100
- if (!token.length || uncountables.hasOwnProperty(token)) {
101
- return word;
102
- }
103
- var len = rules.length;
104
- while (len--) {
105
- var rule = rules[len];
106
- if (rule[0].test(word)) return replace(word, rule);
107
- }
108
- return word;
109
- }
110
- __name(sanitizeWord, "sanitizeWord");
111
- function replaceWord(replaceMap, keepMap, rules) {
112
- return function(word) {
113
- var token = word.toLowerCase();
114
- if (keepMap.hasOwnProperty(token)) {
115
- return restoreCase(word, token);
116
- }
117
- if (replaceMap.hasOwnProperty(token)) {
118
- return restoreCase(word, replaceMap[token]);
119
- }
120
- return sanitizeWord(token, word, rules);
121
- };
122
- }
123
- __name(replaceWord, "replaceWord");
124
- function checkWord(replaceMap, keepMap, rules, bool) {
125
- return function(word) {
126
- var token = word.toLowerCase();
127
- if (keepMap.hasOwnProperty(token)) return true;
128
- if (replaceMap.hasOwnProperty(token)) return false;
129
- return sanitizeWord(token, token, rules) === token;
130
- };
131
- }
132
- __name(checkWord, "checkWord");
133
- function pluralize2(word, count, inclusive) {
134
- var pluralized = count === 1 ? pluralize2.singular(word) : pluralize2.plural(word);
135
- return (inclusive ? count + " " : "") + pluralized;
136
- }
137
- __name(pluralize2, "pluralize");
138
- pluralize2.plural = replaceWord(irregularSingles, irregularPlurals, pluralRules);
139
- pluralize2.isPlural = checkWord(irregularSingles, irregularPlurals, pluralRules);
140
- pluralize2.singular = replaceWord(irregularPlurals, irregularSingles, singularRules);
141
- pluralize2.isSingular = checkWord(irregularPlurals, irregularSingles, singularRules);
142
- pluralize2.addPluralRule = function(rule, replacement) {
143
- pluralRules.push([
144
- sanitizeRule(rule),
145
- replacement
146
- ]);
147
- };
148
- pluralize2.addSingularRule = function(rule, replacement) {
149
- singularRules.push([
150
- sanitizeRule(rule),
151
- replacement
152
- ]);
153
- };
154
- pluralize2.addUncountableRule = function(word) {
155
- if (typeof word === "string") {
156
- uncountables[word.toLowerCase()] = true;
157
- return;
158
- }
159
- pluralize2.addPluralRule(word, "$0");
160
- pluralize2.addSingularRule(word, "$0");
161
- };
162
- pluralize2.addIrregularRule = function(single, plural) {
163
- plural = plural.toLowerCase();
164
- single = single.toLowerCase();
165
- irregularSingles[single] = plural;
166
- irregularPlurals[plural] = single;
167
- };
168
- [
169
- // Pronouns.
170
- [
171
- "I",
172
- "we"
173
- ],
174
- [
175
- "me",
176
- "us"
177
- ],
178
- [
179
- "he",
180
- "they"
181
- ],
182
- [
183
- "she",
184
- "they"
185
- ],
186
- [
187
- "them",
188
- "them"
189
- ],
190
- [
191
- "myself",
192
- "ourselves"
193
- ],
194
- [
195
- "yourself",
196
- "yourselves"
197
- ],
198
- [
199
- "itself",
200
- "themselves"
201
- ],
202
- [
203
- "herself",
204
- "themselves"
205
- ],
206
- [
207
- "himself",
208
- "themselves"
209
- ],
210
- [
211
- "themself",
212
- "themselves"
213
- ],
214
- [
215
- "is",
216
- "are"
217
- ],
218
- [
219
- "was",
220
- "were"
221
- ],
222
- [
223
- "has",
224
- "have"
225
- ],
226
- [
227
- "this",
228
- "these"
229
- ],
230
- [
231
- "that",
232
- "those"
233
- ],
234
- // Words ending in with a consonant and `o`.
235
- [
236
- "echo",
237
- "echoes"
238
- ],
239
- [
240
- "dingo",
241
- "dingoes"
242
- ],
243
- [
244
- "volcano",
245
- "volcanoes"
246
- ],
247
- [
248
- "tornado",
249
- "tornadoes"
250
- ],
251
- [
252
- "torpedo",
253
- "torpedoes"
254
- ],
255
- // Ends with `us`.
256
- [
257
- "genus",
258
- "genera"
259
- ],
260
- [
261
- "viscus",
262
- "viscera"
263
- ],
264
- // Ends with `ma`.
265
- [
266
- "stigma",
267
- "stigmata"
268
- ],
269
- [
270
- "stoma",
271
- "stomata"
272
- ],
273
- [
274
- "dogma",
275
- "dogmata"
276
- ],
277
- [
278
- "lemma",
279
- "lemmata"
280
- ],
281
- [
282
- "schema",
283
- "schemata"
284
- ],
285
- [
286
- "anathema",
287
- "anathemata"
288
- ],
289
- // Other irregular rules.
290
- [
291
- "ox",
292
- "oxen"
293
- ],
294
- [
295
- "axe",
296
- "axes"
297
- ],
298
- [
299
- "die",
300
- "dice"
301
- ],
302
- [
303
- "yes",
304
- "yeses"
305
- ],
306
- [
307
- "foot",
308
- "feet"
309
- ],
310
- [
311
- "eave",
312
- "eaves"
313
- ],
314
- [
315
- "goose",
316
- "geese"
317
- ],
318
- [
319
- "tooth",
320
- "teeth"
321
- ],
322
- [
323
- "quiz",
324
- "quizzes"
325
- ],
326
- [
327
- "human",
328
- "humans"
329
- ],
330
- [
331
- "proof",
332
- "proofs"
333
- ],
334
- [
335
- "carve",
336
- "carves"
337
- ],
338
- [
339
- "valve",
340
- "valves"
341
- ],
342
- [
343
- "looey",
344
- "looies"
345
- ],
346
- [
347
- "thief",
348
- "thieves"
349
- ],
350
- [
351
- "groove",
352
- "grooves"
353
- ],
354
- [
355
- "pickaxe",
356
- "pickaxes"
357
- ],
358
- [
359
- "passerby",
360
- "passersby"
361
- ]
362
- ].forEach(function(rule) {
363
- return pluralize2.addIrregularRule(rule[0], rule[1]);
364
- });
365
- [
366
- [
367
- /s?$/i,
368
- "s"
369
- ],
370
- [
371
- /[^\u0000-\u007F]$/i,
372
- "$0"
373
- ],
374
- [
375
- /([^aeiou]ese)$/i,
376
- "$1"
377
- ],
378
- [
379
- /(ax|test)is$/i,
380
- "$1es"
381
- ],
382
- [
383
- /(alias|[^aou]us|t[lm]as|gas|ris)$/i,
384
- "$1es"
385
- ],
386
- [
387
- /(e[mn]u)s?$/i,
388
- "$1s"
389
- ],
390
- [
391
- /([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i,
392
- "$1"
393
- ],
394
- [
395
- /(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i,
396
- "$1i"
397
- ],
398
- [
399
- /(alumn|alg|vertebr)(?:a|ae)$/i,
400
- "$1ae"
401
- ],
402
- [
403
- /(seraph|cherub)(?:im)?$/i,
404
- "$1im"
405
- ],
406
- [
407
- /(her|at|gr)o$/i,
408
- "$1oes"
409
- ],
410
- [
411
- /(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i,
412
- "$1a"
413
- ],
414
- [
415
- /(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i,
416
- "$1a"
417
- ],
418
- [
419
- /sis$/i,
420
- "ses"
421
- ],
422
- [
423
- /(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i,
424
- "$1$2ves"
425
- ],
426
- [
427
- /([^aeiouy]|qu)y$/i,
428
- "$1ies"
429
- ],
430
- [
431
- /([^ch][ieo][ln])ey$/i,
432
- "$1ies"
433
- ],
434
- [
435
- /(x|ch|ss|sh|zz)$/i,
436
- "$1es"
437
- ],
438
- [
439
- /(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i,
440
- "$1ices"
441
- ],
442
- [
443
- /\b((?:tit)?m|l)(?:ice|ouse)$/i,
444
- "$1ice"
445
- ],
446
- [
447
- /(pe)(?:rson|ople)$/i,
448
- "$1ople"
449
- ],
450
- [
451
- /(child)(?:ren)?$/i,
452
- "$1ren"
453
- ],
454
- [
455
- /eaux$/i,
456
- "$0"
457
- ],
458
- [
459
- /m[ae]n$/i,
460
- "men"
461
- ],
462
- [
463
- "thou",
464
- "you"
465
- ]
466
- ].forEach(function(rule) {
467
- return pluralize2.addPluralRule(rule[0], rule[1]);
468
- });
469
- [
470
- [
471
- /s$/i,
472
- ""
473
- ],
474
- [
475
- /(ss)$/i,
476
- "$1"
477
- ],
478
- [
479
- /(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i,
480
- "$1fe"
481
- ],
482
- [
483
- /(ar|(?:wo|[ae])l|[eo][ao])ves$/i,
484
- "$1f"
485
- ],
486
- [
487
- /ies$/i,
488
- "y"
489
- ],
490
- [
491
- /\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i,
492
- "$1ie"
493
- ],
494
- [
495
- /\b(mon|smil)ies$/i,
496
- "$1ey"
497
- ],
498
- [
499
- /\b((?:tit)?m|l)ice$/i,
500
- "$1ouse"
501
- ],
502
- [
503
- /(seraph|cherub)im$/i,
504
- "$1"
505
- ],
506
- [
507
- /(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i,
508
- "$1"
509
- ],
510
- [
511
- /(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i,
512
- "$1sis"
513
- ],
514
- [
515
- /(movie|twelve|abuse|e[mn]u)s$/i,
516
- "$1"
517
- ],
518
- [
519
- /(test)(?:is|es)$/i,
520
- "$1is"
521
- ],
522
- [
523
- /(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i,
524
- "$1us"
525
- ],
526
- [
527
- /(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i,
528
- "$1um"
529
- ],
530
- [
531
- /(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i,
532
- "$1on"
533
- ],
534
- [
535
- /(alumn|alg|vertebr)ae$/i,
536
- "$1a"
537
- ],
538
- [
539
- /(cod|mur|sil|vert|ind)ices$/i,
540
- "$1ex"
541
- ],
542
- [
543
- /(matr|append)ices$/i,
544
- "$1ix"
545
- ],
546
- [
547
- /(pe)(rson|ople)$/i,
548
- "$1rson"
549
- ],
550
- [
551
- /(child)ren$/i,
552
- "$1"
553
- ],
554
- [
555
- /(eau)x?$/i,
556
- "$1"
557
- ],
558
- [
559
- /men$/i,
560
- "man"
561
- ]
562
- ].forEach(function(rule) {
563
- return pluralize2.addSingularRule(rule[0], rule[1]);
564
- });
565
- [
566
- // Singular words with no plurals.
567
- "adulthood",
568
- "advice",
569
- "agenda",
570
- "aid",
571
- "aircraft",
572
- "alcohol",
573
- "ammo",
574
- "analytics",
575
- "anime",
576
- "athletics",
577
- "audio",
578
- "bison",
579
- "blood",
580
- "bream",
581
- "buffalo",
582
- "butter",
583
- "carp",
584
- "cash",
585
- "chassis",
586
- "chess",
587
- "clothing",
588
- "cod",
589
- "commerce",
590
- "cooperation",
591
- "corps",
592
- "debris",
593
- "diabetes",
594
- "digestion",
595
- "elk",
596
- "energy",
597
- "equipment",
598
- "excretion",
599
- "expertise",
600
- "firmware",
601
- "flounder",
602
- "fun",
603
- "gallows",
604
- "garbage",
605
- "graffiti",
606
- "hardware",
607
- "headquarters",
608
- "health",
609
- "herpes",
610
- "highjinks",
611
- "homework",
612
- "housework",
613
- "information",
614
- "jeans",
615
- "justice",
616
- "kudos",
617
- "labour",
618
- "literature",
619
- "machinery",
620
- "mackerel",
621
- "mail",
622
- "media",
623
- "mews",
624
- "moose",
625
- "music",
626
- "mud",
627
- "manga",
628
- "news",
629
- "only",
630
- "personnel",
631
- "pike",
632
- "plankton",
633
- "pliers",
634
- "police",
635
- "pollution",
636
- "premises",
637
- "rain",
638
- "research",
639
- "rice",
640
- "salmon",
641
- "scissors",
642
- "series",
643
- "sewage",
644
- "shambles",
645
- "shrimp",
646
- "software",
647
- "species",
648
- "staff",
649
- "swine",
650
- "tennis",
651
- "traffic",
652
- "transportation",
653
- "trout",
654
- "tuna",
655
- "wealth",
656
- "welfare",
657
- "whiting",
658
- "wildebeest",
659
- "wildlife",
660
- "you",
661
- /pok[eé]mon$/i,
662
- // Regexes.
663
- /[^aeiou]ese$/i,
664
- /deer$/i,
665
- /fish$/i,
666
- /measles$/i,
667
- /o[iu]s$/i,
668
- /pox$/i,
669
- /sheep$/i
670
- ].forEach(pluralize2.addUncountableRule);
671
- return pluralize2;
672
- });
673
- }
674
- });
675
-
676
- // src/generator.ts
677
- init_esm_shims();
678
-
679
- // src/index.ts
680
- init_esm_shims();
681
-
682
- // src/prisma-generator.ts
683
- init_esm_shims();
684
- import { existsSync } from "@stryke/fs/exists";
685
- import { createDirectory as createDirectory2, removeDirectory } from "@stryke/fs/helpers";
686
- import { joinPaths as joinPaths4 } from "@stryke/path/join-paths";
687
-
688
- // ../string-format/src/lower-case-first.ts
689
- init_esm_shims();
690
- function lowerCaseFirst(input) {
691
- return input ? input.charAt(0).toLowerCase() + input.slice(1) : input;
692
- }
693
- __name(lowerCaseFirst, "lowerCaseFirst");
694
-
695
- // src/prisma-generator.ts
696
- var import_pluralize = __toESM(require_pluralize(), 1);
697
- import path5 from "node:path";
698
-
699
- // src/config.ts
700
- init_esm_shims();
701
- import { z } from "zod";
702
- var ModelAction = /* @__PURE__ */ (function(ModelAction2) {
703
- ModelAction2["findUnique"] = "findUnique";
704
- ModelAction2["findUniqueOrThrow"] = "findUniqueOrThrow";
705
- ModelAction2["findFirst"] = "findFirst";
706
- ModelAction2["findFirstOrThrow"] = "findFirstOrThrow";
707
- ModelAction2["findMany"] = "findMany";
708
- ModelAction2["create"] = "create";
709
- ModelAction2["createMany"] = "createMany";
710
- ModelAction2["createManyAndReturn"] = "createManyAndReturn";
711
- ModelAction2["update"] = "update";
712
- ModelAction2["updateMany"] = "updateMany";
713
- ModelAction2["updateManyAndReturn"] = "updateManyAndReturn";
714
- ModelAction2["upsert"] = "upsert";
715
- ModelAction2["delete"] = "delete";
716
- ModelAction2["deleteMany"] = "deleteMany";
717
- ModelAction2["groupBy"] = "groupBy";
718
- ModelAction2["count"] = "count";
719
- ModelAction2["aggregate"] = "aggregate";
720
- ModelAction2["findRaw"] = "findRaw";
721
- ModelAction2["aggregateRaw"] = "aggregateRaw";
722
- return ModelAction2;
723
- })({});
724
- var modelActionEnum = z.nativeEnum(ModelAction);
725
- var configBoolean = z.string().trim().transform((value) => !value || value.toLowerCase() === "false" || value.toLowerCase() === "n" || value.toLowerCase() === "no" || value === "0" ? false : value.toLowerCase() === "true" || value.toLowerCase() === "y" || value.toLowerCase() === "yes" || value === "1" ? true : value);
726
- var configSchema = z.object({
727
- debug: configBoolean.default("false"),
728
- withNext: configBoolean.default("true"),
729
- withMiddleware: configBoolean.default("false"),
730
- withShield: configBoolean.default("false"),
731
- contextPath: z.string().trim().default("../context"),
732
- trpcOptions: configBoolean.default("true"),
733
- showModelNameInProcedure: configBoolean.default("false"),
734
- generateModelActions: z.string().default(Object.values(ModelAction).join(",")).transform((arg) => {
735
- return arg.split(",").map((action) => modelActionEnum.parse(action.trim()));
736
- }),
737
- // Zod configuration
738
- withZod: configBoolean.default("true"),
739
- relationModel: configBoolean.default("true").or(z.literal("default")),
740
- modelSuffix: z.string().default("Schema"),
741
- modelCase: z.enum([
742
- "PascalCase",
743
- "camelCase"
744
- ]).default("camelCase"),
745
- useDecimalJs: configBoolean.default("true"),
746
- imports: z.string().optional(),
747
- prismaJsonNullability: configBoolean.default("true")
748
- });
749
-
750
- // src/helpers.ts
751
- init_esm_shims();
752
- import { relativePath } from "@stryke/path/file-path-fns";
753
- import { joinPaths as joinPaths3 } from "@stryke/path/join-paths";
754
-
755
- // src/project.ts
756
- init_esm_shims();
757
- import { ModuleKind, Project, ScriptTarget } from "ts-morph";
758
- var compilerOptions = {
759
- target: ScriptTarget.ESNext,
760
- module: ModuleKind.ESNext,
761
- emitDecoratorMetadata: true,
762
- experimentalDecorators: true,
763
- esModuleInterop: true
764
- };
765
- var project = new Project({
766
- compilerOptions: {
767
- ...compilerOptions
768
- }
769
- });
770
-
771
- // src/utils/get-prisma-internals.ts
772
- init_esm_shims();
773
-
774
- // src/utils/get-jiti.ts
775
- init_esm_shims();
776
-
777
- // ../env/src/get-env-paths.ts
778
- init_esm_shims();
779
- import { joinPaths } from "@stryke/path/join-paths";
780
-
781
- // ../string-format/src/title-case.ts
782
- init_esm_shims();
783
-
784
- // ../string-format/src/combine.ts
785
- init_esm_shims();
786
- function combine(acc, str) {
787
- return `${acc} ${str}`;
788
- }
789
- __name(combine, "combine");
790
-
791
- // ../string-format/src/decamelize.ts
792
- init_esm_shims();
793
- function decamelize(value) {
794
- return value.replace(/([a-z\d])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g, "$1_$2").toLowerCase();
795
- }
796
- __name(decamelize, "decamelize");
797
-
798
- // ../string-format/src/format-special-cases.ts
799
- init_esm_shims();
800
-
801
- // ../string-format/src/acronyms.ts
802
- init_esm_shims();
803
- var ACRONYMS = {
804
- "2D": {
805
- description: "Two-Dimensional",
806
- display: "2d"
807
- },
808
- "3D": {
809
- description: "Three-Dimensional",
810
- display: "3d"
811
- },
812
- "4D": {
813
- description: "Four-Dimensional",
814
- display: "4d"
815
- },
816
- "5G": {
817
- description: "Fifth Generation (mobile networks)"
818
- },
819
- "6G": {
820
- description: "Sixth Generation (mobile networks)"
821
- },
822
- "7G": {
823
- description: "Seventh Generation (mobile networks)"
824
- },
825
- "8G": {
826
- description: "Eighth Generation (mobile networks)"
827
- },
828
- "ACID": {
829
- description: "Atomicity, Consistency, Isolation, Durability"
830
- },
831
- "AITA": {
832
- description: "Am I The Asshole"
833
- },
834
- "AES": {
835
- description: "Advanced Encryption Standard"
836
- },
837
- "AI": {
838
- description: "Artificial Intelligence"
839
- },
840
- "AJAX": {
841
- description: "Asynchronous JavaScript and XML"
842
- },
843
- "API": {
844
- description: "Application Programming Interface"
845
- },
846
- "AR": {
847
- description: "Augmented Reality"
848
- },
849
- "ASCII": {
850
- description: "American Standard Code for Information Interchange"
851
- },
852
- "ATF": {
853
- description: "Bureau of Alcohol, Tobacco, Firearms and Explosives"
854
- },
855
- "ATM": {
856
- description: "Automated Teller Machine"
857
- },
858
- "B2B": {
859
- description: "Business to Business"
860
- },
861
- "B2C": {
862
- description: "Business to Consumer"
863
- },
864
- "BATFE": {
865
- description: "Bureau of Alcohol, Tobacco, Firearms and Explosives"
866
- },
867
- "BFF": {
868
- description: "Best Friends Forever"
869
- },
870
- "BFFS": {
871
- description: "Best Friends Forever (plural)"
872
- },
873
- "BI": {
874
- description: "Business Intelligence"
875
- },
876
- "BIOS": {
877
- description: "Basic Input/Output System"
878
- },
879
- "BGP": {
880
- description: "Border Gateway Protocol"
881
- },
882
- "BOM": {
883
- description: "Bill of Materials / Byte Order Mark"
884
- },
885
- "BSON": {
886
- description: "Binary JSON"
887
- },
888
- "BYOD": {
889
- description: "Bring Your Own Device"
890
- },
891
- "C2C": {
892
- description: "Consumer to Consumer"
893
- },
894
- "CAGR": {
895
- description: "Compound Annual Growth Rate"
896
- },
897
- "CAPTCHA": {
898
- description: "Completely Automated Public Turing test to tell Computers and Humans Apart"
899
- },
900
- "CCTV": {
901
- description: "Closed-Circuit Television"
902
- },
903
- "CD": {
904
- description: "Continuous Delivery / Compact Disc"
905
- },
906
- "CDN": {
907
- description: "Content Delivery Network"
908
- },
909
- "CDP": {
910
- description: "Customer Data Platform"
911
- },
912
- "CDT": {
913
- description: "Central Daylight Time"
914
- },
915
- "CIA": {
916
- description: "Central Intelligence Agency"
917
- },
918
- "CI": {
919
- description: "Continuous Integration"
920
- },
921
- "CI/CD": {
922
- description: "Continuous Integration/Continuous Delivery"
923
- },
924
- "CIAM": {
925
- description: "Customer Identity and Access Management"
926
- },
927
- "CICD": {
928
- description: "Continuous Integration Continuous Delivery",
929
- display: "CI/CD"
930
- },
931
- "CLI": {
932
- description: "Command Line Interface"
933
- },
934
- "CMDB": {
935
- description: "Configuration Management Database"
936
- },
937
- "CORS": {
938
- description: "Cross-Origin Resource Sharing"
939
- },
940
- "CPA": {
941
- description: "Certified Public Accountant"
942
- },
943
- "CPU": {
944
- description: "Central Processing Unit"
945
- },
946
- "CRUD": {
947
- description: "Create, Read, Update, Delete"
948
- },
949
- "CSR": {
950
- description: "Certificate Signing Request / Corporate Social Responsibility"
951
- },
952
- "CSS": {
953
- description: "Cascading Style Sheets"
954
- },
955
- "CST": {
956
- description: "Central Standard Time"
957
- },
958
- "CTA": {
959
- description: "Call To Action"
960
- },
961
- "CWD": {
962
- description: "Current Working Directory"
963
- },
964
- "CX": {
965
- description: "Customer Experience"
966
- },
967
- "DAG": {
968
- description: "Directed Acyclic Graph"
969
- },
970
- "DBMS": {
971
- description: "Database Management System"
972
- },
973
- "DDOS": {
974
- description: "Distributed Denial of Service",
975
- display: "DDoS"
976
- },
977
- "DEA": {
978
- description: "Drug Enforcement Administration"
979
- },
980
- "DEVENV": {
981
- description: "Devenv",
982
- display: "Devenv"
983
- },
984
- "DEVOPS": {
985
- description: "Development Operations",
986
- display: "DevOps"
987
- },
988
- "DHS": {
989
- description: "Department of Homeland Security"
990
- },
991
- "DIRENV": {
992
- description: "DirEnv",
993
- display: "DirEnv"
994
- },
995
- "DNC": {
996
- description: "Democratic National Committee / Do Not Call"
997
- },
998
- "DNS": {
999
- description: "Domain Name System"
1000
- },
1001
- "DNSSEC": {
1002
- description: "Domain Name System Security Extensions"
1003
- },
1004
- "DOD": {
1005
- description: "Department of Defense",
1006
- display: "DoD"
1007
- },
1008
- "DOJ": {
1009
- description: "Department of Justice",
1010
- display: "DoJ"
1011
- },
1012
- "DOM": {
1013
- description: "Document Object Model"
1014
- },
1015
- "DOT": {
1016
- description: "Department of Transportation",
1017
- display: "DoT"
1018
- },
1019
- "DOTENV": {
1020
- description: "Dotenv (.env)",
1021
- display: "Dotenv"
1022
- },
1023
- "DR": {
1024
- description: "Disaster Recovery"
1025
- },
1026
- "DRM": {
1027
- description: "Digital Rights Management"
1028
- },
1029
- "DSN": {
1030
- description: "Data Source Name"
1031
- },
1032
- "DWH": {
1033
- description: "Data Warehouse"
1034
- },
1035
- "E2E": {
1036
- description: "End to End"
1037
- },
1038
- "EAI": {
1039
- description: "Enterprise Application Integration"
1040
- },
1041
- "EDT": {
1042
- description: "Eastern Daylight Time"
1043
- },
1044
- "EEA": {
1045
- description: "European Economic Area"
1046
- },
1047
- "EKS": {
1048
- description: "Elastic Kubernetes Service"
1049
- },
1050
- "EOF": {
1051
- description: "End Of File"
1052
- },
1053
- "EOD": {
1054
- description: "End Of Day / Explosive Ordnance Disposal"
1055
- },
1056
- "EPA": {
1057
- description: "Environmental Protection Agency"
1058
- },
1059
- "ER": {
1060
- description: "Emergency Room / Entity Relationship"
1061
- },
1062
- "EST": {
1063
- description: "Eastern Standard Time"
1064
- },
1065
- "ETC": {
1066
- description: "Et Cetera"
1067
- },
1068
- "ETL": {
1069
- description: "Extract, Transform, Load"
1070
- },
1071
- "EULA": {
1072
- description: "End User License Agreement"
1073
- },
1074
- "FAAS": {
1075
- description: "Function as a Service",
1076
- display: "FaaS"
1077
- },
1078
- "FAQ": {
1079
- description: "Frequently Asked Questions",
1080
- display: "FAQs"
1081
- },
1082
- "FAQS": {
1083
- description: "Frequently Asked Questions"
1084
- },
1085
- "FBI": {
1086
- description: "Federal Bureau of Investigation"
1087
- },
1088
- "FCC": {
1089
- description: "Federal Communications Commission"
1090
- },
1091
- "FDA": {
1092
- description: "Food and Drug Administration"
1093
- },
1094
- "FIDO": {
1095
- description: "Fast IDentity Online"
1096
- },
1097
- "FLOTUS": {
1098
- description: "First Lady of the United States"
1099
- },
1100
- "FQDN": {
1101
- description: "Fully Qualified Domain Name"
1102
- },
1103
- "FTC": {
1104
- description: "Federal Trade Commission"
1105
- },
1106
- "FTP": {
1107
- description: "File Transfer Protocol"
1108
- },
1109
- "GC": {
1110
- description: "Garbage Collection"
1111
- },
1112
- "GCP": {
1113
- description: "Google Cloud Platform"
1114
- },
1115
- "GDPR": {
1116
- description: "General Data Protection Regulation"
1117
- },
1118
- "GMT": {
1119
- description: "Greenwich Mean Time"
1120
- },
1121
- "GOP": {
1122
- description: "Grand Old Party"
1123
- },
1124
- "GPU": {
1125
- description: "Graphics Processing Unit"
1126
- },
1127
- "GUID": {
1128
- description: "Globally Unique Identifier"
1129
- },
1130
- "GUI": {
1131
- description: "Graphical User Interface"
1132
- },
1133
- "GZIP": {
1134
- description: "GNU Zip"
1135
- },
1136
- "HCI": {
1137
- description: "Human Computer Interaction / Hyper-Converged Infrastructure"
1138
- },
1139
- "HDD": {
1140
- description: "Hard Disk Drive"
1141
- },
1142
- "HDFS": {
1143
- description: "Hadoop Distributed File System"
1144
- },
1145
- "HHS": {
1146
- description: "Health and Human Services"
1147
- },
1148
- "HIPAA": {
1149
- description: "Health Insurance Portability and Accountability Act"
1150
- },
1151
- "HMAC": {
1152
- description: "Hash-based Message Authentication Code"
1153
- },
1154
- "HOTP": {
1155
- description: "HMAC-based One-Time Password"
1156
- },
1157
- "HSM": {
1158
- description: "Hardware Security Module"
1159
- },
1160
- "HTML": {
1161
- description: "HyperText Markup Language"
1162
- },
1163
- "HTTP": {
1164
- description: "HyperText Transfer Protocol (HTTP)"
1165
- },
1166
- "HTTP/2": {
1167
- description: "HyperText Transfer Protocol Version 2 (HTTP/2)"
1168
- },
1169
- "HTTP/2.0": {
1170
- description: "HyperText Transfer Protocol Version 2 (HTTP/2)",
1171
- display: "HTTP2"
1172
- },
1173
- "HTTP/3": {
1174
- description: "HyperText Transfer Protocol Version 3 (HTTP/3)"
1175
- },
1176
- "HTTP/3.0": {
1177
- description: "HyperText Transfer Protocol Version 3 (HTTP/3)",
1178
- display: "HTTP3"
1179
- },
1180
- "HTTP2": {
1181
- description: "HyperText Transfer Protocol Version 2 (HTTP/2)",
1182
- display: "HTTP2"
1183
- },
1184
- "HTTP2.0": {
1185
- description: "HyperText Transfer Protocol Version 2 (HTTP/2)",
1186
- display: "HTTP2"
1187
- },
1188
- "HTTP3": {
1189
- description: "HyperText Transfer Protocol Version 3 (HTTP/3)",
1190
- display: "HTTP3"
1191
- },
1192
- "HTTP3.0": {
1193
- description: "HyperText Transfer Protocol Version 3 (HTTP/3)",
1194
- display: "HTTP3"
1195
- },
1196
- "HTTPS": {
1197
- description: "HyperText Transfer Protocol Secure (HTTPS)"
1198
- },
1199
- "HTTPS/2": {
1200
- description: "HyperText Transfer Protocol Secure Version 2 (HTTPS/2)"
1201
- },
1202
- "HTTPS/2.0": {
1203
- description: "HyperText Transfer Protocol Secure Version 2 (HTTPS/2)",
1204
- display: "HTTPS2"
1205
- },
1206
- "HTTPS/3": {
1207
- description: "HyperText Transfer Protocol Secure Version 3 (HTTPS/3)"
1208
- },
1209
- "HTTPS/3.0": {
1210
- description: "HyperText Transfer Protocol Secure Version 3 (HTTPS/3)",
1211
- display: "HTTPS3"
1212
- },
1213
- "HTTPS2": {
1214
- description: "HyperText Transfer Protocol Secure Version 2 (HTTPS/2)",
1215
- display: "HTTPS2"
1216
- },
1217
- "HTTPS2.0": {
1218
- description: "HyperText Transfer Protocol Secure Version 2 (HTTPS/2)",
1219
- display: "HTTPS2"
1220
- },
1221
- "HTTPS3": {
1222
- description: "HyperText Transfer Protocol Secure Version 3 (HTTPS/3)",
1223
- display: "HTTPS3"
1224
- },
1225
- "HTTPS3.0": {
1226
- description: "HyperText Transfer Protocol Secure Version 3 (HTTPS/3)",
1227
- display: "HTTPS3"
1228
- },
1229
- "IAAS": {
1230
- description: "Infrastructure as a Service",
1231
- display: "IaaS"
1232
- },
1233
- "IAM": {
1234
- description: "Identity and Access Management"
1235
- },
1236
- "IAMM": {
1237
- description: "Identity and Access Management and Monitoring"
1238
- },
1239
- "IAMT": {
1240
- description: "Identity and Access Management Tool"
1241
- },
1242
- "ID": {
1243
- description: "Identifier",
1244
- display: "Id"
1245
- },
1246
- "IFTTT": {
1247
- description: "If This Then That"
1248
- },
1249
- "IMAP": {
1250
- description: "Internet Message Access Protocol"
1251
- },
1252
- "IO": {
1253
- description: "Input/Output"
1254
- },
1255
- "IP": {
1256
- description: "Internet Protocol"
1257
- },
1258
- "IPFS": {
1259
- description: "InterPlanetary File System"
1260
- },
1261
- "IPS": {
1262
- description: "Intrusion Prevention System"
1263
- },
1264
- "ISO": {
1265
- description: "International Organization for Standardization"
1266
- },
1267
- "IQ": {
1268
- description: "Intelligence Quotient",
1269
- display: "IQ"
1270
- },
1271
- "IOT": {
1272
- description: "Internet of Things",
1273
- display: "IoT"
1274
- },
1275
- "JSON": {
1276
- description: "JavaScript Object Notation"
1277
- },
1278
- "JSONP": {
1279
- description: "JSON with Padding"
1280
- },
1281
- "JWT": {
1282
- description: "JSON Web Token"
1283
- },
1284
- "K8S": {
1285
- description: "Kubernetes",
1286
- display: "K8s"
1287
- },
1288
- "KMS": {
1289
- description: "Key Management Service"
1290
- },
1291
- "KPI": {
1292
- description: "Key Performance Indicator"
1293
- },
1294
- "KV": {
1295
- description: "Key Value"
1296
- },
1297
- "LAN": {
1298
- description: "Local Area Network"
1299
- },
1300
- "LHS": {
1301
- description: "Left Hand Side"
1302
- },
1303
- "LPGA": {
1304
- description: "Ladies Professional Golf Association"
1305
- },
1306
- "LXC": {
1307
- description: "Linux Containers"
1308
- },
1309
- "MDT": {
1310
- description: "Mountain Daylight Time"
1311
- },
1312
- "MFA": {
1313
- description: "Multi-Factor Authentication"
1314
- },
1315
- "ML": {
1316
- description: "Machine Learning"
1317
- },
1318
- "MLB": {
1319
- description: "Major League Baseball"
1320
- },
1321
- "MLOps": {
1322
- description: "Machine Learning Operations"
1323
- },
1324
- "MPA": {
1325
- description: "Multi-Page Application"
1326
- },
1327
- "MST": {
1328
- description: "Mountain Standard Time"
1329
- },
1330
- "MVC": {
1331
- description: "Model View Controller"
1332
- },
1333
- "MVP": {
1334
- description: "Minimum Viable Product / Most Valuable Player"
1335
- },
1336
- "NAIA": {
1337
- description: "National Association of Intercollegiate Athletics"
1338
- },
1339
- "NAS": {
1340
- description: "Network Attached Storage"
1341
- },
1342
- "NASA": {
1343
- description: "National Aeronautics and Space Administration"
1344
- },
1345
- "NASCAR": {
1346
- description: "National Association for Stock Car Auto Racing"
1347
- },
1348
- "NAT": {
1349
- description: "Network Address Translation"
1350
- },
1351
- "NBA": {
1352
- description: "National Basketball Association"
1353
- },
1354
- "NCAA": {
1355
- description: "National Collegiate Athletic Association"
1356
- },
1357
- "NDA": {
1358
- description: "Non-Disclosure Agreement"
1359
- },
1360
- "NFS": {
1361
- description: "Network File System"
1362
- },
1363
- "NHL": {
1364
- description: "National Hockey League"
1365
- },
1366
- "NIST": {
1367
- description: "National Institute of Standards and Technology"
1368
- },
1369
- "NLP": {
1370
- description: "Natural Language Processing"
1371
- },
1372
- "NPS": {
1373
- description: "Net Promoter Score"
1374
- },
1375
- "NRA": {
1376
- description: "National Rifle Association"
1377
- },
1378
- "NSFW": {
1379
- description: "Not Safe For Work"
1380
- },
1381
- "NX": {
1382
- description: "Nx",
1383
- display: "Nx"
1384
- },
1385
- "OCR": {
1386
- description: "Optical Character Recognition"
1387
- },
1388
- "OEM": {
1389
- description: "Original Equipment Manufacturer"
1390
- },
1391
- "OKR": {
1392
- description: "Objectives and Key Results"
1393
- },
1394
- "OLAP": {
1395
- description: "Online Analytical Processing"
1396
- },
1397
- "OLTP": {
1398
- description: "Online Transaction Processing"
1399
- },
1400
- "OOP": {
1401
- description: "Object Oriented Programming"
1402
- },
1403
- "ORM": {
1404
- description: "Object Relational Mapping"
1405
- },
1406
- "OS": {
1407
- description: "Operating System"
1408
- },
1409
- "OSINT": {
1410
- description: "Open Source Intelligence"
1411
- },
1412
- "OSS": {
1413
- description: "Open Source Software"
1414
- },
1415
- "OTP": {
1416
- description: "One-Time Password"
1417
- },
1418
- "P2P": {
1419
- description: "Peer to Peer"
1420
- },
1421
- "PAAS": {
1422
- description: "Platform as a Service",
1423
- display: "PaaS"
1424
- },
1425
- "PCI": {
1426
- description: "Payment Card Industry"
1427
- },
1428
- "PDP": {
1429
- description: "Policy Decision Point / Product Detail Page"
1430
- },
1431
- "PDT": {
1432
- description: "Pacific Daylight Time"
1433
- },
1434
- "PGA": {
1435
- description: "Professional Golfers' Association"
1436
- },
1437
- "POTUS": {
1438
- description: "President of the United States"
1439
- },
1440
- "PP": {
1441
- description: "Pages / PayPal / Percentage Points"
1442
- },
1443
- "PST": {
1444
- description: "Pacific Standard Time"
1445
- },
1446
- "PTO": {
1447
- description: "Paid Time Off / Power Take-Off"
1448
- },
1449
- "PKI": {
1450
- description: "Public Key Infrastructure"
1451
- },
1452
- "PWA": {
1453
- description: "Progressive Web App"
1454
- },
1455
- "PX": {
1456
- description: "Pixel"
1457
- },
1458
- "QA": {
1459
- description: "Quality Assurance"
1460
- },
1461
- "R2": {
1462
- description: "R2"
1463
- },
1464
- "RAID": {
1465
- description: "Redundant Array of Independent Disks"
1466
- },
1467
- "RAM": {
1468
- description: "Random Access Memory"
1469
- },
1470
- "RDS": {
1471
- description: "Relational Database Service"
1472
- },
1473
- "REST": {
1474
- description: "Representational State Transfer"
1475
- },
1476
- "RHS": {
1477
- description: "Right Hand Side"
1478
- },
1479
- "ROI": {
1480
- description: "Return on Investment"
1481
- },
1482
- "RPC": {
1483
- description: "Remote Procedure Call"
1484
- },
1485
- "RPA": {
1486
- description: "Robotic Process Automation"
1487
- },
1488
- "RSC": {
1489
- description: "React Server Components"
1490
- },
1491
- "RSS": {
1492
- description: "Really Simple Syndication"
1493
- },
1494
- "RUM": {
1495
- description: "Real User Monitoring"
1496
- },
1497
- "S3": {
1498
- description: "Simple Storage Service (S3)"
1499
- },
1500
- "SAN": {
1501
- description: "Storage Area Network"
1502
- },
1503
- "SASE": {
1504
- description: "Secure Access Service Edge"
1505
- },
1506
- "SCOTUS": {
1507
- description: "Supreme Court of the United States"
1508
- },
1509
- "SDLC": {
1510
- description: "Software Development Life Cycle"
1511
- },
1512
- "SDK": {
1513
- description: "Software Development Kit"
1514
- },
1515
- "SEC": {
1516
- description: "Securities and Exchange Commission"
1517
- },
1518
- "SEO": {
1519
- description: "Search Engine Optimization"
1520
- },
1521
- "SFTP": {
1522
- description: "SSH File Transfer Protocol / Secure File Transfer Protocol"
1523
- },
1524
- "SIEM": {
1525
- description: "Security Information and Event Management"
1526
- },
1527
- "SLA": {
1528
- description: "Service Level Agreement"
1529
- },
1530
- "SMB": {
1531
- description: "Server Message Block / Small and Medium Business"
1532
- },
1533
- "SMTP": {
1534
- description: "Simple Mail Transfer Protocol"
1535
- },
1536
- "SOAP": {
1537
- description: "Simple Object Access Protocol"
1538
- },
1539
- "SOA": {
1540
- description: "Service Oriented Architecture"
1541
- },
1542
- "SOC": {
1543
- description: "Security Operations Center / System on Chip"
1544
- },
1545
- "SPA": {
1546
- description: "Single Page Application"
1547
- },
1548
- "SPDY": {
1549
- description: 'Speedy (pronounced "SPeeDY")'
1550
- },
1551
- "SPF": {
1552
- description: "Sender Policy Framework"
1553
- },
1554
- "SQL": {
1555
- description: "Structured Query Language"
1556
- },
1557
- "SRV": {
1558
- description: "Service"
1559
- },
1560
- "SRE": {
1561
- description: "Site Reliability Engineering"
1562
- },
1563
- "SSH": {
1564
- description: "Secure Shell"
1565
- },
1566
- "SSDL": {
1567
- description: "Secure Software Development Lifecycle"
1568
- },
1569
- "SSG": {
1570
- description: "Static Site Generation"
1571
- },
1572
- "SSR": {
1573
- description: "Server Side Rendering"
1574
- },
1575
- "SSO": {
1576
- description: "Single Sign-On"
1577
- },
1578
- "SSL": {
1579
- description: "Secure Sockets Layer"
1580
- },
1581
- "TDD": {
1582
- description: "Test Driven Development"
1583
- },
1584
- "TLD": {
1585
- description: "Top Level Domain"
1586
- },
1587
- "TLS": {
1588
- description: "Transport Layer Security"
1589
- },
1590
- "TLS1.3": {
1591
- description: "Transport Layer Security 1.3"
1592
- },
1593
- "TOR": {
1594
- description: "The Onion Router"
1595
- },
1596
- "TOTP": {
1597
- description: "Time-based One-Time Password"
1598
- },
1599
- "TRPC": {
1600
- description: "TypeScript Remote Procedure Call"
1601
- },
1602
- "TSA": {
1603
- description: "Transportation Security Administration"
1604
- },
1605
- "TTL": {
1606
- description: "Time To Live"
1607
- },
1608
- "UDP": {
1609
- description: "User Datagram Protocol"
1610
- },
1611
- "UI": {
1612
- description: "User Interface"
1613
- },
1614
- "UID": {
1615
- description: "Unique Identifier"
1616
- },
1617
- "URI": {
1618
- description: "Uniform Resource Identifier"
1619
- },
1620
- "URL": {
1621
- description: "Uniform Resource Locator"
1622
- },
1623
- "USOPC": {
1624
- description: "United States Olympic & Paralympic Committee"
1625
- },
1626
- "USPS": {
1627
- description: "United States Postal Service"
1628
- },
1629
- "USTA": {
1630
- description: "United States Tennis Association"
1631
- },
1632
- "UTF": {
1633
- description: "Unicode Transformation Format"
1634
- },
1635
- "UTC": {
1636
- description: "Coordinated Universal Time"
1637
- },
1638
- "UUID": {
1639
- description: "Universally Unique Identifier"
1640
- },
1641
- "UX": {
1642
- description: "User Experience"
1643
- },
1644
- "VM": {
1645
- description: "Virtual Machine"
1646
- },
1647
- "VLAN": {
1648
- description: "Virtual Local Area Network"
1649
- },
1650
- "VPN": {
1651
- description: "Virtual Private Network"
1652
- },
1653
- "VPPA": {
1654
- description: "Video Privacy Protection Act"
1655
- },
1656
- "VR": {
1657
- description: "Virtual Reality"
1658
- },
1659
- "WAF": {
1660
- description: "Web Application Firewall"
1661
- },
1662
- "WAN": {
1663
- description: "Wide Area Network"
1664
- },
1665
- "WNBA": {
1666
- description: "Women's National Basketball Association"
1667
- },
1668
- "WLAN": {
1669
- description: "Wireless Local Area Network"
1670
- },
1671
- "WPA": {
1672
- description: "Wi-Fi Protected Access"
1673
- },
1674
- "WPA2": {
1675
- description: "Wi-Fi Protected Access II"
1676
- },
1677
- "WPA3": {
1678
- description: "Wi-Fi Protected Access III"
1679
- },
1680
- "WWW": {
1681
- description: "World Wide Web"
1682
- },
1683
- "WYSIWYG": {
1684
- description: "What You See Is What You Get"
1685
- },
1686
- "XACML": {
1687
- description: "eXtensible Access Control Markup Language"
1688
- },
1689
- "XDG": {
1690
- description: "Cross-Desktop Group"
1691
- },
1692
- "XML": {
1693
- description: "eXtensible Markup Language"
1694
- },
1695
- "XSRF": {
1696
- description: "Cross-Site Request Forgery"
1697
- },
1698
- "XSS": {
1699
- description: "Cross-Site Scripting"
1700
- },
1701
- "XR": {
1702
- description: "Extended Reality"
1703
- },
1704
- "YAML": {
1705
- description: "YAML Ain't Markup Language"
1706
- },
1707
- "YMCA": {
1708
- description: "Young Men's Christian Association"
1709
- },
1710
- "YWCA": {
1711
- description: "Young Women's Christian Association"
1712
- },
1713
- "ZTA": {
1714
- description: "Zero Trust Architecture"
1715
- }
1716
- };
1717
- var ACRONYM_DISPLAY = Object.fromEntries(Object.entries(ACRONYMS).map(([key, value]) => [
1718
- key,
1719
- value.display ?? key
1720
- ]));
1721
- var ACRONYM_DESCRIPTION = Object.fromEntries(Object.entries(ACRONYMS).map(([key, value]) => [
1722
- key,
1723
- value.description
1724
- ]));
1725
- var ACRONYM_LIST = Object.keys(ACRONYMS);
1726
-
1727
- // ../string-format/src/articles.ts
1728
- init_esm_shims();
1729
- var ARTICLES = [
1730
- "a",
1731
- "an",
1732
- "the"
1733
- ];
1734
-
1735
- // ../string-format/src/conjunctions.ts
1736
- init_esm_shims();
1737
- var CONJUNCTIONS = [
1738
- "and",
1739
- "that",
1740
- "but",
1741
- "or",
1742
- "as",
1743
- "if",
1744
- "when",
1745
- "than",
1746
- "because",
1747
- "while",
1748
- "where",
1749
- "after",
1750
- "so",
1751
- "though",
1752
- "since",
1753
- "until",
1754
- "whether",
1755
- "before",
1756
- "although",
1757
- "nor",
1758
- "like",
1759
- "once",
1760
- "unless",
1761
- "now",
1762
- "except"
1763
- ];
1764
-
1765
- // ../string-format/src/prepositions.ts
1766
- init_esm_shims();
1767
- var PREPOSITIONS = [
1768
- "about",
1769
- "above",
1770
- "across",
1771
- "after",
1772
- "against",
1773
- "along",
1774
- "among",
1775
- "around",
1776
- "at",
1777
- "because of",
1778
- "before",
1779
- "behind",
1780
- "below",
1781
- "beneath",
1782
- "beside",
1783
- "besides",
1784
- "between",
1785
- "beyond",
1786
- "but",
1787
- "by",
1788
- "concerning",
1789
- "despite",
1790
- "down",
1791
- "during",
1792
- "except",
1793
- "excepting",
1794
- "for",
1795
- "from",
1796
- "in",
1797
- "in front of",
1798
- "inside",
1799
- "in spite of",
1800
- "instead of",
1801
- "into",
1802
- "like",
1803
- "near",
1804
- "of",
1805
- "off",
1806
- "on",
1807
- "onto",
1808
- "out",
1809
- "outside",
1810
- "over",
1811
- "past",
1812
- "regarding",
1813
- "since",
1814
- "through",
1815
- "throughout",
1816
- "to",
1817
- "toward",
1818
- "under",
1819
- "underneath",
1820
- "until",
1821
- "up",
1822
- "upon",
1823
- "up to",
1824
- "with",
1825
- "within",
1826
- "without",
1827
- "with regard to",
1828
- "with respect to"
1829
- ];
1830
-
1831
- // ../string-format/src/special-cases.ts
1832
- init_esm_shims();
1833
- var SPECIAL_CASES = [
1834
- "2FA",
1835
- "4K",
1836
- "5K",
1837
- "8K",
1838
- "AGI",
1839
- "BI",
1840
- "ChatGPT",
1841
- "CTA",
1842
- "DateTime",
1843
- "FMS",
1844
- "GitHub",
1845
- "GPT",
1846
- "HD",
1847
- "IBMid",
1848
- "IDs",
1849
- "iMac",
1850
- "IMAX",
1851
- "iOS",
1852
- "iPad",
1853
- "iPhone",
1854
- "iPod",
1855
- "LDAP",
1856
- "LinkedIn",
1857
- "LLM",
1858
- "macOS",
1859
- "McDonalds",
1860
- "MCP",
1861
- "ML",
1862
- "MySQL",
1863
- "NLG",
1864
- "NLP",
1865
- "NLU",
1866
- "OpenAI",
1867
- "PDFs",
1868
- "PIM",
1869
- "PEFT",
1870
- "pH",
1871
- "PostgreSQL",
1872
- "SEO",
1873
- "TTS",
1874
- "UHD",
1875
- "UUID",
1876
- "XSS",
1877
- "YouTube",
1878
- "CSpell",
1879
- "ESLint"
1880
- ];
1881
-
1882
- // ../string-format/src/format-special-cases.ts
1883
- function formatSpecialCases(value, index, words, options) {
1884
- const lowercaseStr = value.toLowerCase();
1885
- const uppercaseStr = value.toUpperCase();
1886
- for (const special of SPECIAL_CASES) {
1887
- if (special.toLowerCase() === lowercaseStr) {
1888
- return special;
1889
- }
1890
- }
1891
- if (ACRONYMS[uppercaseStr]) {
1892
- return options?.useDescriptions !== false ? ACRONYMS[uppercaseStr].description : ACRONYMS[uppercaseStr].display || uppercaseStr;
1893
- }
1894
- if (index === 0) {
1895
- return value;
1896
- }
1897
- if (index === words.length - 1) {
1898
- return value;
1899
- }
1900
- if (value.length >= 4) {
1901
- return value;
1902
- }
1903
- if (PREPOSITIONS.includes(lowercaseStr)) {
1904
- return lowercaseStr;
1905
- }
1906
- if (CONJUNCTIONS.includes(lowercaseStr)) {
1907
- return lowercaseStr;
1908
- }
1909
- if (ARTICLES.includes(lowercaseStr)) {
1910
- return lowercaseStr;
1911
- }
1912
- return value;
1913
- }
1914
- __name(formatSpecialCases, "formatSpecialCases");
1915
-
1916
- // ../string-format/src/upper-case-first.ts
1917
- init_esm_shims();
1918
- function upperCaseFirst(input) {
1919
- return input ? input.charAt(0).toUpperCase() + input.slice(1) : input;
1920
- }
1921
- __name(upperCaseFirst, "upperCaseFirst");
1922
-
1923
- // ../string-format/src/title-case.ts
1924
- function titleCase(input, options) {
1925
- return input?.split(/\s+-\s+/).map((segment) => decamelize(segment).split(/[\s\-_]/).map(upperCaseFirst).map((value, index, array) => formatSpecialCases(value, index, array, options)).reduce(combine)).join(" - ");
1926
- }
1927
- __name(titleCase, "titleCase");
1928
-
1929
- // ../env/src/get-env-paths.ts
1930
- import os from "node:os";
1931
- import path from "node:path";
1932
- var homedir = os.homedir();
1933
- var tmpdir = os.tmpdir();
1934
- var macos = /* @__PURE__ */ __name((orgId) => {
1935
- const library = joinPaths(homedir, "Library");
1936
- return {
1937
- data: joinPaths(library, "Application Support", orgId),
1938
- config: joinPaths(library, "Preferences", orgId),
1939
- cache: joinPaths(library, "Caches", orgId),
1940
- log: joinPaths(library, "Logs", orgId),
1941
- temp: joinPaths(tmpdir, orgId)
1942
- };
1943
- }, "macos");
1944
- var windows = /* @__PURE__ */ __name((orgId) => {
1945
- const appData = process.env.APPDATA || joinPaths(homedir, "AppData", "Roaming");
1946
- const localAppData = process.env.LOCALAPPDATA || joinPaths(homedir, "AppData", "Local");
1947
- const windowsFormattedOrgId = titleCase(orgId).trim().replace(/\s+/g, "");
1948
- return {
1949
- // Data/config/cache/log are invented by me as Windows isn't opinionated about this
1950
- data: joinPaths(localAppData, windowsFormattedOrgId, "Data"),
1951
- config: joinPaths(appData, windowsFormattedOrgId, "Config"),
1952
- cache: joinPaths(localAppData, "Cache", orgId),
1953
- log: joinPaths(localAppData, windowsFormattedOrgId, "Log"),
1954
- temp: joinPaths(tmpdir, orgId)
1955
- };
1956
- }, "windows");
1957
- var linux = /* @__PURE__ */ __name((orgId) => {
1958
- const username = path.basename(homedir);
1959
- return {
1960
- data: joinPaths(process.env.XDG_DATA_HOME || joinPaths(homedir, ".local", "share"), orgId),
1961
- config: joinPaths(process.env.XDG_CONFIG_HOME || joinPaths(homedir, ".config"), orgId),
1962
- cache: joinPaths(process.env.XDG_CACHE_HOME || joinPaths(homedir, ".cache"), orgId),
1963
- // https://wiki.debian.org/XDGBaseDirectorySpecification#state
1964
- log: joinPaths(process.env.XDG_STATE_HOME || joinPaths(homedir, ".local", "state"), orgId),
1965
- // https://devenv.sh/files-and-variables/#devenv_root
1966
- temp: process.env.DEVENV_RUNTIME || process.env.XDG_RUNTIME_DIR ? joinPaths(process.env.DEVENV_RUNTIME || process.env.XDG_RUNTIME_DIR, orgId) : joinPaths(tmpdir, username, orgId)
1967
- };
1968
- }, "linux");
1969
- function getEnvPaths(options = {}) {
1970
- let orgId = options.orgId || "storm-software";
1971
- if (!orgId) {
1972
- throw new Error("You need to provide an orgId to the `getEnvPaths` function");
1973
- }
1974
- if (options.suffix) {
1975
- orgId += `-${typeof options.suffix === "string" ? options.suffix : "nodejs"}`;
1976
- }
1977
- let result = {};
1978
- if (process.platform === "darwin") {
1979
- result = macos(orgId);
1980
- } else if (process.platform === "win32") {
1981
- result = windows(orgId);
1982
- } else {
1983
- result = linux(orgId);
1984
- }
1985
- if (process.env.STORM_DATA_DIR) {
1986
- result.data = process.env.STORM_DATA_DIR;
1987
- } else if (process.env.STORM_CONFIG_DIR) {
1988
- result.config = process.env.STORM_CONFIG_DIR;
1989
- } else if (process.env.STORM_CACHE_DIR) {
1990
- result.cache = process.env.STORM_CACHE_DIR;
1991
- } else if (process.env.STORM_LOG_DIR) {
1992
- result.log = process.env.STORM_LOG_DIR;
1993
- } else if (process.env.STORM_TEMP_DIR) {
1994
- result.temp = process.env.STORM_TEMP_DIR;
1995
- }
1996
- if (options.workspaceRoot) {
1997
- result.cache ??= joinPaths(options.workspaceRoot, "node_modules", ".cache", orgId);
1998
- result.temp ??= joinPaths(options.workspaceRoot, "tmp", orgId);
1999
- result.log ??= joinPaths(result.temp, "logs");
2000
- result.config ??= joinPaths(options.workspaceRoot, ".config", orgId);
2001
- }
2002
- return Object.keys(result).reduce((ret, key) => {
2003
- if (result[key]) {
2004
- const filePath = result[key];
2005
- ret[key] = options.appId && options.appId !== options.orgId && options.appId !== options.nestedDir ? joinPaths(filePath, options.appId) : filePath;
2006
- if (options.nestedDir && options.nestedDir !== options.orgId && options.nestedDir !== options.appId) {
2007
- ret[key] = joinPaths(ret[key], options.nestedDir);
2008
- }
2009
- }
2010
- return ret;
2011
- }, {});
2012
- }
2013
- __name(getEnvPaths, "getEnvPaths");
2014
-
2015
- // src/utils/get-jiti.ts
2016
- import { getWorkspaceRoot } from "@stryke/fs/get-workspace-root";
2017
- import { joinPaths as joinPaths2 } from "@stryke/path/join-paths";
2018
- import { createJiti } from "jiti";
2019
- var jiti;
2020
- function getJiti() {
2021
- if (!jiti) {
2022
- const envPaths = getEnvPaths();
2023
- jiti = createJiti(getWorkspaceRoot(), {
2024
- fsCache: joinPaths2(envPaths.cache, "jiti"),
2025
- interopDefault: true
2026
- });
2027
- }
2028
- return jiti;
2029
- }
2030
- __name(getJiti, "getJiti");
2031
-
2032
- // src/utils/get-prisma-internals.ts
2033
- async function getPrismaInternals() {
2034
- return getJiti().import(getJiti().esmResolve("@prisma/internals"));
2035
- }
2036
- __name(getPrismaInternals, "getPrismaInternals");
2037
- async function getPrismaGeneratorHelper() {
2038
- return getJiti().import(getJiti().esmResolve("@prisma/generator-helper"));
2039
- }
2040
- __name(getPrismaGeneratorHelper, "getPrismaGeneratorHelper");
2041
-
2042
- // src/zod/model-helpers.ts
2043
- init_esm_shims();
2044
- import path2 from "node:path";
2045
- import { StructureKind, VariableDeclarationKind } from "ts-morph";
2046
-
2047
- // src/zod/docs-helpers.ts
2048
- init_esm_shims();
2049
- import parenthesis from "parenthesis";
2050
- var getJSDocs = /* @__PURE__ */ __name((docString) => {
2051
- const lines = [];
2052
- if (docString) {
2053
- const docLines = docString.split("\n").filter((dL) => !dL.trimStart().startsWith("@zod"));
2054
- if (docLines.length) {
2055
- lines.push("/**");
2056
- docLines.forEach((dL) => lines.push(` * ${dL}`));
2057
- lines.push(" */");
2058
- }
2059
- }
2060
- return lines;
2061
- }, "getJSDocs");
2062
- var getZodDocElements = /* @__PURE__ */ __name((docString) => docString.split("\n").filter((line) => line.trimStart().startsWith("@zod")).map((line) => line.trimStart().slice(4)).flatMap((line) => (
2063
- // Array.from(line.matchAll(/\.([^().]+\(.*?\))/g), (m) => m.slice(1)).flat()
2064
- chunk(parenthesis.parse(line), 2).slice(0, -1).map(([each, contents]) => `${each.replace(/\)?\./, "")}${parenthesis.stringify(contents)})`)
2065
- )), "getZodDocElements");
2066
-
2067
- // src/zod/model-helpers.ts
2068
- function checkModelHasModelRelation(model) {
2069
- const { fields: modelFields } = model;
2070
- for (const modelField of modelFields) {
2071
- const isRelationField = checkIsModelRelationField(modelField);
2072
- if (isRelationField) {
2073
- return true;
2074
- }
2075
- }
2076
- return false;
2077
- }
2078
- __name(checkModelHasModelRelation, "checkModelHasModelRelation");
2079
- function checkModelHasManyModelRelation(model) {
2080
- const { fields: modelFields } = model;
2081
- for (const modelField of modelFields) {
2082
- const isManyRelationField = checkIsManyModelRelationField(modelField);
2083
- if (isManyRelationField) {
2084
- return true;
2085
- }
2086
- }
2087
- return false;
2088
- }
2089
- __name(checkModelHasManyModelRelation, "checkModelHasManyModelRelation");
2090
- function checkIsModelRelationField(modelField) {
2091
- const { kind, relationName } = modelField;
2092
- return kind === "object" && !!relationName;
2093
- }
2094
- __name(checkIsModelRelationField, "checkIsModelRelationField");
2095
- function checkIsManyModelRelationField(modelField) {
2096
- return checkIsModelRelationField(modelField) && modelField.isList;
2097
- }
2098
- __name(checkIsManyModelRelationField, "checkIsManyModelRelationField");
2099
- function findModelByName(models, modelName) {
2100
- return models.find(({ name }) => name === modelName);
2101
- }
2102
- __name(findModelByName, "findModelByName");
2103
- var writeArray = /* @__PURE__ */ __name((writer, array, newLine = true) => array.forEach((line) => writer.write(line).conditionalNewLine(newLine)), "writeArray");
2104
- var useModelNames = /* @__PURE__ */ __name(({ modelCase, modelSuffix, relationModel }) => {
2105
- const formatModelName = /* @__PURE__ */ __name((name, prefix = "") => {
2106
- if (modelCase === "camelCase") {
2107
- name = name.slice(0, 1).toLowerCase() + name.slice(1);
2108
- }
2109
- return `${prefix}${name}${modelSuffix}`;
2110
- }, "formatModelName");
2111
- return {
2112
- modelName: /* @__PURE__ */ __name((name) => formatModelName(name, relationModel === "default" ? "_" : ""), "modelName"),
2113
- relatedModelName: /* @__PURE__ */ __name((name) => formatModelName(relationModel === "default" ? name.toString() : `Related${name.toString()}`), "relatedModelName")
2114
- };
2115
- }, "useModelNames");
2116
- var dotSlash = /* @__PURE__ */ __name((input) => {
2117
- const converted = input.replace(/^\\\\\?\\/, "").replace(/\\/g, "/").replace(/\/{2,}/g, "/");
2118
- if (converted.includes(`/node_modules/`)) return converted.split(`/node_modules/`).slice(-1)[0];
2119
- if (converted.startsWith(`../`)) return converted;
2120
- return `./${converted}`;
2121
- }, "dotSlash");
2122
- var chunk = /* @__PURE__ */ __name((input, size) => {
2123
- return input.reduce((arr, item, idx) => {
2124
- return idx % size === 0 ? [
2125
- ...arr,
2126
- [
2127
- item
2128
- ]
2129
- ] : [
2130
- ...arr.slice(0, -1),
2131
- [
2132
- ...arr.slice(-1)[0],
2133
- item
2134
- ]
2135
- ];
2136
- }, []);
2137
- }, "chunk");
2138
- var needsRelatedModel = /* @__PURE__ */ __name((model, config) => model.fields.some((field) => field.kind === "object") && config.relationModel !== false, "needsRelatedModel");
2139
- var writeImportsForModel = /* @__PURE__ */ __name(async (model, sourceFile, config, options) => {
2140
- const internals = await getPrismaInternals();
2141
- const outputPath = internals.parseEnvValue(options.generator.output);
2142
- const { relatedModelName } = useModelNames(config);
2143
- const importList = [
2144
- {
2145
- kind: StructureKind.ImportDeclaration,
2146
- namespaceImport: "z",
2147
- moduleSpecifier: "zod"
2148
- }
2149
- ];
2150
- if (config.imports) {
2151
- importList.push({
2152
- kind: StructureKind.ImportDeclaration,
2153
- namespaceImport: "imports",
2154
- moduleSpecifier: dotSlash(path2.relative(outputPath, path2.resolve(path2.dirname(options.schemaPath), config.imports)))
2155
- });
2156
- }
2157
- if (config.useDecimalJs && model.fields.some((f) => f.type === "Decimal")) {
2158
- importList.push({
2159
- kind: StructureKind.ImportDeclaration,
2160
- namedImports: [
2161
- "Decimal"
2162
- ],
2163
- moduleSpecifier: "decimal.js"
2164
- });
2165
- }
2166
- const enumFields = model.fields.filter((f) => f.kind === "enum");
2167
- const relationFields = model.fields.filter((f) => f.kind === "object");
2168
- const clientPath = options.otherGenerators.find((each) => each.provider.value === "prisma-client-js").output.value;
2169
- const relativePath2 = path2.relative(outputPath, clientPath);
2170
- if (enumFields.length > 0) {
2171
- importList.push({
2172
- kind: StructureKind.ImportDeclaration,
2173
- isTypeOnly: enumFields.length === 0,
2174
- moduleSpecifier: dotSlash(relativePath2),
2175
- namedImports: enumFields.map((f) => f.type)
2176
- });
2177
- }
2178
- if (config.relationModel !== false && relationFields.length > 0) {
2179
- const filteredFields = relationFields.filter((f) => f.type !== model.name);
2180
- if (filteredFields.length > 0) {
2181
- importList.push({
2182
- kind: StructureKind.ImportDeclaration,
2183
- moduleSpecifier: "./index",
2184
- namedImports: Array.from(new Set(filteredFields.flatMap((f) => [
2185
- `${f.type}`,
2186
- relatedModelName(f.type)
2187
- ])))
2188
- });
2189
- }
2190
- }
2191
- sourceFile.addImportDeclarations(importList);
2192
- }, "writeImportsForModel");
2193
- var computeCustomSchema = /* @__PURE__ */ __name((docString) => {
2194
- return getZodDocElements(docString).find((modifier) => modifier.startsWith("custom("))?.slice(7).slice(0, -1);
2195
- }, "computeCustomSchema");
2196
- var computeModifiers = /* @__PURE__ */ __name((docString) => {
2197
- return getZodDocElements(docString).filter((each) => !each.startsWith("custom("));
2198
- }, "computeModifiers");
2199
- var getZodConstructor = /* @__PURE__ */ __name((field, getRelatedModelName = (name) => name.toString()) => {
2200
- let zodType = "z.unknown()";
2201
- const extraModifiers = [
2202
- ""
2203
- ];
2204
- if (field.kind === "scalar") {
2205
- switch (field.type) {
2206
- case "String":
2207
- zodType = "z.string()";
2208
- break;
2209
- case "Int":
2210
- zodType = "z.number()";
2211
- extraModifiers.push("int()");
2212
- break;
2213
- case "BigInt":
2214
- zodType = "z.bigint()";
2215
- break;
2216
- case "DateTime":
2217
- zodType = "z.date()";
2218
- break;
2219
- case "Float":
2220
- zodType = "z.number()";
2221
- break;
2222
- case "Decimal":
2223
- zodType = "z.number()";
2224
- break;
2225
- case "Json":
2226
- zodType = "jsonSchema";
2227
- break;
2228
- case "Boolean":
2229
- zodType = "z.boolean()";
2230
- break;
2231
- // TODO: Proper type for bytes fields
2232
- case "Bytes":
2233
- zodType = "z.unknown()";
2234
- break;
2235
- }
2236
- } else if (field.kind === "enum") {
2237
- zodType = `z.nativeEnum(${field.type})`;
2238
- } else if (field.kind === "object") {
2239
- zodType = getRelatedModelName(field.type);
2240
- }
2241
- if (field.isList) extraModifiers.push("array()");
2242
- if (field.documentation) {
2243
- zodType = computeCustomSchema(field.documentation) ?? zodType;
2244
- extraModifiers.push(...computeModifiers(field.documentation));
2245
- }
2246
- if (!field.isRequired && field.type !== "Json") extraModifiers.push("nullish()");
2247
- return `${zodType}${extraModifiers.join(".")}`;
2248
- }, "getZodConstructor");
2249
- var writeTypeSpecificSchemas = /* @__PURE__ */ __name((model, sourceFile, config) => {
2250
- if (model.fields.some((f) => f.type === "Json")) {
2251
- sourceFile.addStatements((writer) => {
2252
- writer.newLine();
2253
- writeArray(writer, [
2254
- "// Helper schema for JSON fields",
2255
- `type Literal = boolean | number | string${config.prismaJsonNullability ? "" : "| null"}`,
2256
- "type Json = Literal | { [key: string]: Json } | Json[]",
2257
- `const literalSchema = z.union([z.string(), z.number(), z.boolean()${config.prismaJsonNullability ? "" : ", z.null()"}])`,
2258
- "const jsonSchema: z.ZodSchema<Json> = z.lazy(() => z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)]))"
2259
- ]);
2260
- });
2261
- }
2262
- if (config.useDecimalJs && model.fields.some((f) => f.type === "Decimal")) {
2263
- sourceFile.addStatements((writer) => {
2264
- writer.newLine();
2265
- writeArray(writer, [
2266
- "// Helper schema for Decimal fields",
2267
- "z",
2268
- ".instanceof(Decimal)",
2269
- ".or(z.string())",
2270
- ".or(z.number())",
2271
- ".refine((value) => {",
2272
- " try {",
2273
- " return new Decimal(value);",
2274
- " } catch (error) {",
2275
- " return false;",
2276
- " }",
2277
- "})",
2278
- ".transform((value) => new Decimal(value));"
2279
- ]);
2280
- });
2281
- }
2282
- }, "writeTypeSpecificSchemas");
2283
- var generateSchemaForModel = /* @__PURE__ */ __name((model, sourceFile, config) => {
2284
- const { modelName } = useModelNames(config);
2285
- sourceFile.addVariableStatement({
2286
- declarationKind: VariableDeclarationKind.Const,
2287
- isExported: true,
2288
- leadingTrivia: /* @__PURE__ */ __name((writer) => writer.blankLineIfLastNot(), "leadingTrivia"),
2289
- declarations: [
2290
- {
2291
- name: modelName(model.name),
2292
- initializer(writer) {
2293
- writer.write("z.object(").inlineBlock(() => {
2294
- model.fields.filter((f) => f.kind !== "object").forEach((field) => {
2295
- writeArray(writer, getJSDocs(field.documentation));
2296
- writer.write(`${field.name}: ${getZodConstructor(field)}`).write(",").newLine();
2297
- });
2298
- }).write(")");
2299
- }
2300
- }
2301
- ]
2302
- });
2303
- }, "generateSchemaForModel");
2304
- var generateRelatedSchemaForModel = /* @__PURE__ */ __name((model, sourceFile, config) => {
2305
- const { modelName, relatedModelName } = useModelNames(config);
2306
- const relationFields = model.fields.filter((f) => f.kind === "object");
2307
- sourceFile.addInterface({
2308
- name: `${model.name}`,
2309
- isExported: true,
2310
- extends: [
2311
- `z.infer<typeof ${modelName(model.name)}>`
2312
- ],
2313
- properties: relationFields.map((f) => ({
2314
- hasQuestionToken: !f.isRequired,
2315
- name: f.name,
2316
- type: `${f.type}${f.isList ? "[]" : ""}${!f.isRequired ? " | null" : ""}`
2317
- }))
2318
- });
2319
- sourceFile.addStatements((writer) => writeArray(writer, [
2320
- "",
2321
- "/**",
2322
- ` * ${relatedModelName(model.name)} contains all relations on your model in addition to the scalars`,
2323
- " *",
2324
- " * NOTE: Lazy required in case of potential circular dependencies within schema",
2325
- " */"
2326
- ]));
2327
- sourceFile.addVariableStatement({
2328
- declarationKind: VariableDeclarationKind.Const,
2329
- isExported: true,
2330
- declarations: [
2331
- {
2332
- name: relatedModelName(model.name),
2333
- type: `z.ZodSchema<${model.name}>`,
2334
- initializer(writer) {
2335
- writer.write(`z.lazy(() => ${modelName(model.name)}.extend(`).inlineBlock(() => {
2336
- relationFields.forEach((field) => {
2337
- writeArray(writer, getJSDocs(field.documentation));
2338
- writer.write(`${field.name}: ${getZodConstructor(field, relatedModelName)}`).write(",").newLine();
2339
- });
2340
- }).write("))");
2341
- }
2342
- }
2343
- ]
2344
- });
2345
- }, "generateRelatedSchemaForModel");
2346
- var populateModelFile = /* @__PURE__ */ __name(async (model, sourceFile, config, options) => {
2347
- await writeImportsForModel(model, sourceFile, config, options);
2348
- writeTypeSpecificSchemas(model, sourceFile, config);
2349
- generateSchemaForModel(model, sourceFile, config);
2350
- if (needsRelatedModel(model, config)) generateRelatedSchemaForModel(model, sourceFile, config);
2351
- }, "populateModelFile");
2352
- var generateBarrelFile = /* @__PURE__ */ __name((models, indexFile) => {
2353
- models.forEach((model) => indexFile.addExportDeclaration({
2354
- moduleSpecifier: `./${lowerCaseFirst(model.name)}.schema`
2355
- }));
2356
- }, "generateBarrelFile");
2357
-
2358
- // src/helpers.ts
2359
- var getProcedureName = /* @__PURE__ */ __name((config) => {
2360
- return config.withShield ? "shieldedProcedure" : config.withMiddleware ? "protectedProcedure" : "publicProcedure";
2361
- }, "getProcedureName");
2362
- var generateCreateRouterImport = /* @__PURE__ */ __name(({ sourceFile, config }) => {
2363
- const imports = [
2364
- "t"
2365
- ];
2366
- if (config) {
2367
- imports.push(getProcedureName(config));
2368
- }
2369
- sourceFile.addImportDeclaration({
2370
- moduleSpecifier: "../trpc",
2371
- namedImports: imports
2372
- });
2373
- }, "generateCreateRouterImport");
2374
- var generateRouterImport = /* @__PURE__ */ __name((sourceFile, modelNamePlural, modelNameCamelCase) => {
2375
- sourceFile.addImportDeclaration({
2376
- moduleSpecifier: `./${lowerCaseFirst(modelNameCamelCase)}.router`,
2377
- namedImports: [
2378
- `${modelNamePlural}Router`
2379
- ]
2380
- });
2381
- }, "generateRouterImport");
2382
- async function generateTRPCExports(sourceFile, config, options, outputDir) {
2383
- if (config.withShield) {
2384
- sourceFile.addImportDeclaration({
2385
- moduleSpecifier: relativePath(outputDir, joinPaths3(outputDir, typeof config.withShield === "string" ? config.withShield : "shield")),
2386
- namedImports: [
2387
- "permissions"
2388
- ]
2389
- });
2390
- }
2391
- sourceFile.addStatements(
2392
- /* ts */
2393
- `import type { Context } from '${relativePath(outputDir, joinPaths3(outputDir, config.contextPath))}';`
2394
- );
2395
- if (config.trpcOptions) {
2396
- sourceFile.addStatements(
2397
- /* ts */
2398
- `import trpcOptions from '${typeof config.trpcOptions === "string" ? relativePath(outputDir, joinPaths3(outputDir, config.trpcOptions)) : "./options"}';`
2399
- );
2400
- }
2401
- if (config.withNext) {
2402
- sourceFile.addStatements(
2403
- /* ts */
2404
- `import { createContext } from '${relativePath(outputDir, joinPaths3(outputDir, config.contextPath))}';
2405
- import { initTRPC } from '@trpc/server';
2406
- import { createTRPCServerActionHandler } from '@stryke/trpc-next/action-handler';
2407
- import { cookies } from "next/headers";`
2408
- );
2409
- }
2410
- sourceFile.addStatements(
2411
- /* ts */
2412
- `
2413
- export const t = initTRPC.context<Context>().create(${config.trpcOptions ? "trpcOptions" : ""});`
2414
- );
2415
- const middlewares = [];
2416
- if (config.withMiddleware && typeof config.withMiddleware === "boolean") {
2417
- sourceFile.addStatements(
2418
- /* ts */
2419
- `
2420
- export const globalMiddleware = t.middleware(async ({ ctx, next }) => {
2421
- console.log('inside middleware!')
2422
- return next()
2423
- });`
2424
- );
2425
- middlewares.push({
2426
- type: "global",
2427
- value: (
2428
- /* ts */
2429
- `.use(globalMiddleware)`
2430
- )
2431
- });
2432
- }
2433
- if (config.withMiddleware && typeof config.withMiddleware === "string") {
2434
- sourceFile.addStatements(
2435
- /* ts */
2436
- `
2437
- import middleware from '${relativePath(outputDir, joinPaths3(outputDir, typeof config.withMiddleware === "string" ? config.withMiddleware : "middleware"))}';
2438
- `
2439
- );
2440
- sourceFile.addStatements(
2441
- /* ts */
2442
- `
2443
- export const globalMiddleware = t.middleware(middleware);`
2444
- );
2445
- middlewares.push({
2446
- type: "global",
2447
- value: (
2448
- /* ts */
2449
- `.use(globalMiddleware)`
2450
- )
2451
- });
2452
- }
2453
- if (config.withShield) {
2454
- sourceFile.addStatements(
2455
- /* ts */
2456
- `
2457
- export const permissionsMiddleware = t.middleware(permissions);
2458
- `
2459
- );
2460
- middlewares.push({
2461
- type: "shield",
2462
- value: (
2463
- /* ts */
2464
- `
2465
- .use(permissions)`
2466
- )
2467
- });
2468
- }
2469
- sourceFile.addStatements(
2470
- /* ts */
2471
- `
2472
- /**
2473
- * Create a server-side caller
2474
- * @see https://trpc.io/docs/server/server-side-calls
2475
- */
2476
- export const createCallerFactory = t.createCallerFactory;`
2477
- );
2478
- sourceFile.addStatements(
2479
- /* ts */
2480
- `
2481
- export const publicProcedure = t.procedure; `
2482
- );
2483
- if (middlewares.length > 0) {
2484
- const procName = getProcedureName(config);
2485
- middlewares.forEach((middleware, i) => {
2486
- if (i === 0) {
2487
- sourceFile.addStatements(
2488
- /* ts */
2489
- `
2490
- export const ${procName} = t.procedure`
2491
- );
2492
- }
2493
- sourceFile.addStatements(
2494
- /* ts */
2495
- `.use(${middleware.type === "shield" ? "permissionsMiddleware" : "globalMiddleware"})`
2496
- );
2497
- });
2498
- }
2499
- if (config.withNext) {
2500
- sourceFile.addStatements(
2501
- /* ts */
2502
- `
2503
- export const createAction: ReturnType<typeof createTRPCServerActionHandler> =
2504
- createTRPCServerActionHandler(cookies, t, createContext);
2505
- `
2506
- );
2507
- }
2508
- sourceFile.formatText({
2509
- indentSize: 2
2510
- });
2511
- }
2512
- __name(generateTRPCExports, "generateTRPCExports");
2513
- function generateProcedure(sourceFile, name, typeName, modelName, opType, baseOpType, config) {
2514
- let input = `input${!config.withZod ? " as any" : ""}`;
2515
- const nameWithoutModel = name.replace(modelName, "");
2516
- if (nameWithoutModel === "groupBy" && config.withZod) {
2517
- input = "{ where: input.where, orderBy: input.orderBy, by: input.by, having: input.having, take: input.take, skip: input.skip }";
2518
- }
2519
- sourceFile.addStatements(
2520
- /* ts */
2521
- `${config.showModelNameInProcedure ? name : nameWithoutModel}: ${getProcedureName(config)}
2522
- ${config.withZod ? `.input(${lowerCaseFirst(typeName)})` : ""}.${getProcedureTypeByOpName(baseOpType)}(async ({ ctx, input }) => {
2523
- const ${name} = await ctx.prisma.${lowerCaseFirst(modelName)}.${opType.replace("One", "")}(${input});
2524
- return ${name};
2525
- }),`
2526
- );
2527
- }
2528
- __name(generateProcedure, "generateProcedure");
2529
- function generateRouterSchemaImports(sourceFile, modelName, modelActions) {
2530
- sourceFile.addStatements(
2531
- /* ts */
2532
- [
2533
- // remove any duplicate import statements
2534
- ...new Set(modelActions.map((opName) => getRouterSchemaImportByOpName(opName, modelName)))
2535
- ].join("\n")
2536
- );
2537
- }
2538
- __name(generateRouterSchemaImports, "generateRouterSchemaImports");
2539
- var getRouterSchemaImportByOpName = /* @__PURE__ */ __name((opName, modelName) => {
2540
- const opType = opName.replace("OrThrow", "").replace("ManyAndReturn", "");
2541
- const inputType = getInputTypeByOpName(opType, modelName);
2542
- return inputType ? `import { ${lowerCaseFirst(inputType)} } from "../schemas/${lowerCaseFirst(opType)}${modelName}.schema"; ` : "";
2543
- }, "getRouterSchemaImportByOpName");
2544
- var getInputTypeByOpName = /* @__PURE__ */ __name((opName, modelName) => {
2545
- let inputType;
2546
- switch (opName) {
2547
- case "findUnique":
2548
- inputType = `${modelName}FindUniqueSchema`;
2549
- break;
2550
- case "findFirst":
2551
- inputType = `${modelName}FindFirstSchema`;
2552
- break;
2553
- case "findMany":
2554
- inputType = `${modelName}FindManySchema`;
2555
- break;
2556
- case "findRaw":
2557
- inputType = `${modelName}FindRawObjectSchema`;
2558
- break;
2559
- case "createOne":
2560
- inputType = `${modelName}CreateOneSchema`;
2561
- break;
2562
- case "createMany":
2563
- inputType = `${modelName}CreateManySchema`;
2564
- break;
2565
- case "createManyAndReturn":
2566
- inputType = `${modelName}CreateManySchema`;
2567
- break;
2568
- case "deleteOne":
2569
- inputType = `${modelName}DeleteOneSchema`;
2570
- break;
2571
- case "deleteMany":
2572
- inputType = `${modelName}DeleteManySchema`;
2573
- break;
2574
- case "updateOne":
2575
- inputType = `${modelName}UpdateOneSchema`;
2576
- break;
2577
- case "updateMany":
2578
- inputType = `${modelName}UpdateManySchema`;
2579
- break;
2580
- case "updateManyAndReturn":
2581
- inputType = `${modelName}UpdateManySchema`;
2582
- break;
2583
- case "upsertOne":
2584
- inputType = `${modelName}UpsertSchema`;
2585
- break;
2586
- case "aggregate":
2587
- inputType = `${modelName}AggregateSchema`;
2588
- break;
2589
- case "aggregateRaw":
2590
- inputType = `${modelName}AggregateRawObjectSchema`;
2591
- break;
2592
- case "groupBy":
2593
- inputType = `${modelName}GroupBySchema`;
2594
- break;
2595
- default:
2596
- console.log("getInputTypeByOpName: ", {
2597
- opName,
2598
- modelName
2599
- });
2600
- }
2601
- return inputType;
2602
- }, "getInputTypeByOpName");
2603
- var getProcedureTypeByOpName = /* @__PURE__ */ __name((opName) => {
2604
- let procType;
2605
- switch (opName) {
2606
- case "findUnique":
2607
- case "findFirst":
2608
- case "findMany":
2609
- case "findRaw":
2610
- case "aggregate":
2611
- case "aggregateRaw":
2612
- case "groupBy":
2613
- procType = "query";
2614
- break;
2615
- case "createOne":
2616
- case "createMany":
2617
- case "createManyAndReturn":
2618
- case "deleteOne":
2619
- case "updateOne":
2620
- case "deleteMany":
2621
- case "updateMany":
2622
- case "updateManyAndReturn":
2623
- case "upsertOne":
2624
- procType = "mutation";
2625
- break;
2626
- default:
2627
- console.log("getProcedureTypeByOpName: ", {
2628
- opName
2629
- });
2630
- }
2631
- return procType;
2632
- }, "getProcedureTypeByOpName");
2633
- function resolveModelsComments(models, hiddenModels) {
2634
- const modelAttributeRegex2 = /(?:@@Gen\.)+[A-z]+\(.+\)/;
2635
- const attributeNameRegex2 = /\.+[A-Z]+\(+/i;
2636
- const attributeArgsRegex2 = /\(+[A-Z]+:.+\)/i;
2637
- for (const model of models) {
2638
- if (model.documentation) {
2639
- const attribute = model.documentation?.match(modelAttributeRegex2)?.[0];
2640
- const attributeName = attribute?.match(attributeNameRegex2)?.[0]?.slice(1, -1);
2641
- if (attributeName !== "model") continue;
2642
- const rawAttributeArgs = attribute?.match(attributeArgsRegex2)?.[0]?.slice(1, -1);
2643
- const parsedAttributeArgs = {};
2644
- if (rawAttributeArgs) {
2645
- const rawAttributeArgsParts = rawAttributeArgs.split(":").map((it) => it.trim()).map((part) => part.startsWith("[") ? part : part.split(",")).flat().map((it) => it.trim());
2646
- for (let i = 0; i < rawAttributeArgsParts.length; i += 2) {
2647
- const key = rawAttributeArgsParts[i];
2648
- const value = rawAttributeArgsParts[i + 1];
2649
- parsedAttributeArgs[key] = JSON.parse(value);
2650
- }
2651
- }
2652
- if (parsedAttributeArgs.hide) {
2653
- hiddenModels.push(model.name);
2654
- }
2655
- }
2656
- }
2657
- }
2658
- __name(resolveModelsComments, "resolveModelsComments");
2659
- var getImports = /* @__PURE__ */ __name((type, newPath) => {
2660
- let statement = "";
2661
- if (type === "trpc") {
2662
- statement = "import * as trpc from '@trpc/server';\n";
2663
- } else if (type === "trpc-shield") {
2664
- statement = "import { shield, allow } from '@stryke/trpc-next/shield';\n";
2665
- } else if (type === "context") {
2666
- statement = `import type { Context } from '${newPath}';
2667
- `;
2668
- }
2669
- return statement;
2670
- }, "getImports");
2671
- var wrapWithObject = /* @__PURE__ */ __name(({ shieldItemLines }) => {
2672
- let wrapped = "{";
2673
- wrapped += "\n";
2674
- wrapped += Array.isArray(shieldItemLines) ? ` ${shieldItemLines.join(",\r\n")}` : ` ${shieldItemLines}`;
2675
- wrapped += "\n";
2676
- wrapped += "}";
2677
- return wrapped;
2678
- }, "wrapWithObject");
2679
- var wrapWithTrpcShieldCall = /* @__PURE__ */ __name(({ shieldObjectTextWrapped }) => {
2680
- let wrapped = "shield<Context>(";
2681
- wrapped += "\n";
2682
- wrapped += ` ${shieldObjectTextWrapped}`;
2683
- wrapped += "\n";
2684
- wrapped += ")";
2685
- return wrapped;
2686
- }, "wrapWithTrpcShieldCall");
2687
- var wrapWithExport = /* @__PURE__ */ __name(({ shieldObjectText }) => {
2688
- return `export const permissions: ReturnType<typeof shield<Context>> = ${shieldObjectText};`;
2689
- }, "wrapWithExport");
2690
- var constructShield = /* @__PURE__ */ __name(async ({ queries, mutations, subscriptions }, config, options, outputDir) => {
2691
- if (queries.length === 0 && mutations.length === 0 && subscriptions.length === 0) {
2692
- return "";
2693
- }
2694
- let rootItems = "";
2695
- if (queries.length > 0) {
2696
- const queryLinesWrapped = `query: ${wrapWithObject({
2697
- shieldItemLines: queries.map((query) => `${query}: allow`)
2698
- })},`;
2699
- rootItems += queryLinesWrapped;
2700
- }
2701
- if (mutations.length > 0) {
2702
- const mutationLinesWrapped = `mutation: ${wrapWithObject({
2703
- shieldItemLines: mutations.map((mutation) => `${mutation}: allow`)
2704
- })},`;
2705
- rootItems += mutationLinesWrapped;
2706
- }
2707
- if (subscriptions.length > 0) {
2708
- const subscriptionLinesWrapped = `subscription: ${wrapWithObject({
2709
- shieldItemLines: subscriptions.map((subscription) => `${subscription}: allow`)
2710
- })},`;
2711
- rootItems += subscriptionLinesWrapped;
2712
- }
2713
- if (rootItems.length === 0) {
2714
- return "";
2715
- }
2716
- let shieldText = getImports("trpc-shield");
2717
- shieldText += getImports("context", relativePath(outputDir, joinPaths3(outputDir, config.contextPath)));
2718
- shieldText += "\n\n";
2719
- shieldText += wrapWithExport({
2720
- shieldObjectText: wrapWithTrpcShieldCall({
2721
- shieldObjectTextWrapped: wrapWithObject({
2722
- shieldItemLines: rootItems
2723
- })
2724
- })
2725
- });
2726
- return shieldText;
2727
- }, "constructShield");
2728
- var constructDefaultOptions = /* @__PURE__ */ __name((config, options, outputDir) => {
2729
- return `import { ZodError } from 'zod';${config.withNext ? '\nimport { transformer } from "@stryke/trpc-next/shared";' : ""}
2730
- import type {
2731
- DataTransformerOptions,
2732
- RootConfig
2733
- } from "@trpc/server/unstable-core-do-not-import";
2734
- import type { Context } from "${relativePath(outputDir, joinPaths3(outputDir, config.contextPath))}";
2735
-
2736
- interface RuntimeConfigOptions<
2737
- TContext extends object,
2738
- TMeta extends object = object
2739
- > extends Partial<
2740
- Omit<
2741
- RootConfig<{
2742
- ctx: TContext;
2743
- meta: TMeta;
2744
- errorShape: any;
2745
- transformer: any;
2746
- }>,
2747
- "$types" | "transformer"
2748
- >
2749
- > {
2750
- /**
2751
- * Use a data transformer
2752
- * @see https://trpc.io/docs/v11/data-transformers
2753
- */
2754
- transformer?: DataTransformerOptions;
2755
- }
2756
-
2757
- const options: RuntimeConfigOptions<Context> = {${config.withNext ? "\n transformer," : ""}
2758
- errorFormatter({ shape, error }) {
2759
- return {
2760
- ...shape,
2761
- data: {
2762
- ...shape.data,
2763
- zodError:
2764
- error.code === "BAD_REQUEST" && error.cause instanceof ZodError
2765
- ? error.cause.flatten()
2766
- : null
2767
- }
2768
- };
2769
- }
2770
- };
2771
-
2772
- export default options;
2773
- `;
2774
- }, "constructDefaultOptions");
2775
- var constructZodModels = /* @__PURE__ */ __name(async (models, outputPath, config, options) => {
2776
- const indexFile = project.createSourceFile(`${outputPath}/index.ts`, {}, {
2777
- overwrite: true
2778
- });
2779
- generateBarrelFile(models, indexFile);
2780
- indexFile.formatText({
2781
- indentSize: 2
2782
- });
2783
- await Promise.all(models.map(async (model) => {
2784
- const sourceFile = project.createSourceFile(`${outputPath}/${lowerCaseFirst(model.name)}.schema.ts`, {}, {
2785
- overwrite: true
2786
- });
2787
- await populateModelFile(model, sourceFile, config, options);
2788
- sourceFile.formatText({
2789
- indentSize: 2
2790
- });
2791
- }));
2792
- }, "constructZodModels");
2793
-
2794
- // src/utils/write-file-safely.ts
2795
- init_esm_shims();
2796
- import { createDirectory } from "@stryke/fs/helpers";
2797
- import { writeFile } from "@stryke/fs/write-file";
2798
- import { correctPath } from "@stryke/path/correct-path";
2799
- import { findFilePath } from "@stryke/path/file-path-fns";
2800
- import path3 from "node:path";
2801
-
2802
- // src/utils/format-file.ts
2803
- init_esm_shims();
2804
- import prettier from "prettier";
2805
- async function formatFile(content) {
2806
- const options = await prettier.resolveConfig(process.cwd());
2807
- let formatOptions = options;
2808
- if (!options) {
2809
- formatOptions = {
2810
- trailingComma: "all",
2811
- tabWidth: 2,
2812
- printWidth: 80,
2813
- bracketSpacing: true,
2814
- semi: true,
2815
- singleQuote: true,
2816
- useTabs: false
2817
- };
2818
- }
2819
- const formatted = await prettier.format(content, {
2820
- ...formatOptions,
2821
- parser: "typescript"
2822
- });
2823
- return formatted;
2824
- }
2825
- __name(formatFile, "formatFile");
2826
-
2827
- // src/utils/write-file-safely.ts
2828
- var indexExports = /* @__PURE__ */ new Set();
2829
- var addIndexExport = /* @__PURE__ */ __name((filePath) => {
2830
- indexExports.add(filePath);
2831
- }, "addIndexExport");
2832
- var writeFileSafely = /* @__PURE__ */ __name(async (writeLocation, content, addToIndex = true) => {
2833
- const [fileContent] = await Promise.all([
2834
- formatFile(content),
2835
- createDirectory(findFilePath(writeLocation))
2836
- ]);
2837
- await writeFile(writeLocation, fileContent);
2838
- if (addToIndex) {
2839
- addIndexExport(writeLocation);
2840
- }
2841
- }, "writeFileSafely");
2842
- var writeIndexFile = /* @__PURE__ */ __name(async (indexPath) => {
2843
- const rows = Array.from(indexExports).map((filePath) => {
2844
- let relativePath2 = path3.relative(path3.dirname(indexPath), filePath);
2845
- if (relativePath2.endsWith(".ts")) {
2846
- relativePath2 = relativePath2.slice(0, relativePath2.lastIndexOf(".ts"));
2847
- }
2848
- const normalized = correctPath(relativePath2);
2849
- return `export * from './${normalized}';`;
2850
- });
2851
- rows.push("export * from './models';");
2852
- await writeFileSafely(indexPath, rows.join("\n"), false);
2853
- }, "writeIndexFile");
2854
-
2855
- // src/zod/aggregate-helpers.ts
2856
- init_esm_shims();
2857
- var isAggregateOutputType = /* @__PURE__ */ __name((name) => /(?:Count|Avg|Sum|Min|Max)AggregateOutputType$/.test(name), "isAggregateOutputType");
2858
- var isAggregateInputType = /* @__PURE__ */ __name((name) => name.endsWith("CountAggregateInput") || name.endsWith("SumAggregateInput") || name.endsWith("AvgAggregateInput") || name.endsWith("MinAggregateInput") || name.endsWith("MaxAggregateInput"), "isAggregateInputType");
2859
- function addMissingInputObjectTypesForAggregate(inputObjectTypes, outputObjectTypes) {
2860
- const aggregateOutputTypes = outputObjectTypes.filter(({ name }) => isAggregateOutputType(name));
2861
- for (const aggregateOutputType of aggregateOutputTypes) {
2862
- const name = aggregateOutputType.name.replace(/(?:OutputType|Output)$/, "");
2863
- inputObjectTypes.push({
2864
- constraints: {
2865
- maxNumFields: null,
2866
- minNumFields: null
2867
- },
2868
- name: `${name}Input`,
2869
- fields: aggregateOutputType.fields.map((field) => ({
2870
- name: field.name,
2871
- isNullable: false,
2872
- isRequired: false,
2873
- inputTypes: [
2874
- {
2875
- isList: false,
2876
- type: "True",
2877
- location: "scalar"
2878
- }
2879
- ]
2880
- }))
2881
- });
2882
- }
2883
- }
2884
- __name(addMissingInputObjectTypesForAggregate, "addMissingInputObjectTypesForAggregate");
2885
- function resolveZodAggregateOperationSupport(inputObjectTypes) {
2886
- const aggregateOperationSupport = {};
2887
- for (const inputType of inputObjectTypes) {
2888
- if (isAggregateInputType(inputType.name)) {
2889
- const name = inputType.name.replace("AggregateInput", "");
2890
- if (name.endsWith("Count")) {
2891
- const model = name.replace("Count", "");
2892
- aggregateOperationSupport[model] = {
2893
- ...aggregateOperationSupport[model],
2894
- count: true
2895
- };
2896
- } else if (name.endsWith("Min")) {
2897
- const model = name.replace("Min", "");
2898
- aggregateOperationSupport[model] = {
2899
- ...aggregateOperationSupport[model],
2900
- min: true
2901
- };
2902
- } else if (name.endsWith("Max")) {
2903
- const model = name.replace("Max", "");
2904
- aggregateOperationSupport[model] = {
2905
- ...aggregateOperationSupport[model],
2906
- max: true
2907
- };
2908
- } else if (name.endsWith("Sum")) {
2909
- const model = name.replace("Sum", "");
2910
- aggregateOperationSupport[model] = {
2911
- ...aggregateOperationSupport[model],
2912
- sum: true
2913
- };
2914
- } else if (name.endsWith("Avg")) {
2915
- const model = name.replace("Avg", "");
2916
- aggregateOperationSupport[model] = {
2917
- ...aggregateOperationSupport[model],
2918
- avg: true
2919
- };
2920
- }
2921
- }
2922
- }
2923
- return aggregateOperationSupport;
2924
- }
2925
- __name(resolveZodAggregateOperationSupport, "resolveZodAggregateOperationSupport");
2926
-
2927
- // src/zod/comments-helpers.ts
2928
- init_esm_shims();
2929
- var modelAttributeRegex = /(?:@@Gen\.)+[A-z]+\(.+\)/;
2930
- var attributeNameRegex = /\.+[A-Z]+\(+/i;
2931
- var attributeArgsRegex = /\(+[A-Z]+:.+\)/i;
2932
- function resolveZodModelsComments(models, modelOperations, enumTypes, hiddenModels, hiddenFields) {
2933
- models = collectHiddenModels(models, hiddenModels);
2934
- collectHiddenFields(models, hiddenModels, hiddenFields);
2935
- hideModelOperations(models, modelOperations);
2936
- hideEnums(enumTypes, hiddenModels);
2937
- }
2938
- __name(resolveZodModelsComments, "resolveZodModelsComments");
2939
- function collectHiddenModels(models, hiddenModels) {
2940
- return models.map((model) => {
2941
- if (model.documentation) {
2942
- const attribute = model.documentation?.match(modelAttributeRegex)?.[0];
2943
- const attributeName = attribute?.match(attributeNameRegex)?.[0]?.slice(1, -1);
2944
- if (attributeName !== "model") {
2945
- return model;
2946
- }
2947
- const rawAttributeArgs = attribute?.match(attributeArgsRegex)?.[0]?.slice(1, -1);
2948
- const parsedAttributeArgs = {};
2949
- if (rawAttributeArgs) {
2950
- const rawAttributeArgsParts = rawAttributeArgs.split(":").map((it) => it.trim()).map((part) => part.startsWith("[") ? part : part.split(",")).flat().map((it) => it.trim());
2951
- for (let i = 0; i < rawAttributeArgsParts.length; i += 2) {
2952
- const key = rawAttributeArgsParts[i];
2953
- const value = rawAttributeArgsParts[i + 1];
2954
- parsedAttributeArgs[key] = JSON.parse(value);
2955
- }
2956
- }
2957
- if (parsedAttributeArgs.hide) {
2958
- hiddenModels.push(model.name);
2959
- return null;
2960
- }
2961
- }
2962
- return model;
2963
- }).filter(Boolean);
2964
- }
2965
- __name(collectHiddenModels, "collectHiddenModels");
2966
- function collectHiddenFields(models, hiddenModels, hiddenFields) {
2967
- models.forEach((model) => {
2968
- model.fields.forEach((field) => {
2969
- if (hiddenModels.includes(field.type)) {
2970
- hiddenFields.push(field.name);
2971
- if (field.relationFromFields) {
2972
- field.relationFromFields.forEach((item) => hiddenFields.push(item));
2973
- }
2974
- }
2975
- });
2976
- });
2977
- }
2978
- __name(collectHiddenFields, "collectHiddenFields");
2979
- function hideEnums(enumTypes, hiddenModels) {
2980
- enumTypes.prisma = enumTypes.prisma.filter((item) => !hiddenModels.find((model) => item.name.startsWith(model)));
2981
- }
2982
- __name(hideEnums, "hideEnums");
2983
- function hideModelOperations(models, modelOperations) {
2984
- let i = modelOperations.length;
2985
- while (i >= 0) {
2986
- --i;
2987
- const modelOperation = modelOperations[i];
2988
- if (modelOperation && !models.find((model) => {
2989
- return model.name === modelOperation.model;
2990
- })) {
2991
- modelOperations.splice(i, 1);
2992
- }
2993
- }
2994
- }
2995
- __name(hideModelOperations, "hideModelOperations");
2996
- function hideZodInputObjectTypesAndRelatedFields(inputObjectTypes, hiddenModels, hiddenFields) {
2997
- let j = inputObjectTypes.length;
2998
- while (j >= 0) {
2999
- --j;
3000
- const inputType = inputObjectTypes[j];
3001
- if (inputType && (hiddenModels.includes(inputType?.meta?.source) || hiddenModels.find((model) => inputType.name.startsWith(model)))) {
3002
- inputObjectTypes.splice(j, 1);
3003
- } else {
3004
- let k = inputType?.fields?.length ?? 0;
3005
- while (k >= 0) {
3006
- --k;
3007
- const field = inputType?.fields?.[k];
3008
- if (field && hiddenFields.includes(field.name)) {
3009
- inputObjectTypes[j].fields.slice(k, 1);
3010
- }
3011
- }
3012
- }
3013
- }
3014
- }
3015
- __name(hideZodInputObjectTypesAndRelatedFields, "hideZodInputObjectTypesAndRelatedFields");
3016
-
3017
- // src/zod/generator-helpers.ts
3018
- init_esm_shims();
3019
-
3020
- // src/zod/transformer.ts
3021
- init_esm_shims();
3022
- import path4 from "node:path";
3023
-
3024
- // src/zod/mongodb-helpers.ts
3025
- init_esm_shims();
3026
- function addMissingInputObjectTypesForMongoDbRawOpsAndQueries(modelOperations, outputObjectTypes, inputObjectTypes) {
3027
- const rawOpsMap = resolveMongoDbRawOperations(modelOperations);
3028
- Transformer.rawOpsMap = rawOpsMap ?? {};
3029
- const mongoDbRawQueryInputObjectTypes = resolveMongoDbRawQueryInputObjectTypes(outputObjectTypes);
3030
- for (const mongoDbRawQueryInputType of mongoDbRawQueryInputObjectTypes) {
3031
- inputObjectTypes.push(mongoDbRawQueryInputType);
3032
- }
3033
- }
3034
- __name(addMissingInputObjectTypesForMongoDbRawOpsAndQueries, "addMissingInputObjectTypesForMongoDbRawOpsAndQueries");
3035
- function resolveMongoDbRawOperations(modelOperations) {
3036
- const rawOpsMap = {};
3037
- const rawOpsNames = [
3038
- ...new Set(modelOperations.reduce((result, current) => {
3039
- const keys = Object.keys(current);
3040
- keys?.forEach((key) => {
3041
- if (key.includes("Raw")) {
3042
- result.push(key);
3043
- }
3044
- });
3045
- return result;
3046
- }, []))
3047
- ];
3048
- const modelNames = modelOperations.map((item) => item.model);
3049
- rawOpsNames.forEach((opName) => {
3050
- modelNames.forEach((modelName) => {
3051
- const isFind = opName === "findRaw";
3052
- const opWithModel = `${opName.replace("Raw", "")}${modelName}Raw`;
3053
- rawOpsMap[opWithModel] = isFind ? `${modelName}FindRawArgs` : `${modelName}AggregateRawArgs`;
3054
- });
3055
- });
3056
- return rawOpsMap;
3057
- }
3058
- __name(resolveMongoDbRawOperations, "resolveMongoDbRawOperations");
3059
- function resolveMongoDbRawQueryInputObjectTypes(outputObjectTypes) {
3060
- const mongoDbRawQueries = getMongoDbRawQueries(outputObjectTypes);
3061
- const mongoDbRawQueryInputObjectTypes = mongoDbRawQueries.map((item) => ({
3062
- name: item.name,
3063
- constraints: {
3064
- maxNumFields: null,
3065
- minNumFields: null
3066
- },
3067
- fields: item.args.map((arg) => ({
3068
- name: arg.name,
3069
- isRequired: arg.isRequired,
3070
- isNullable: arg.isNullable,
3071
- inputTypes: arg.inputTypes
3072
- }))
3073
- }));
3074
- return mongoDbRawQueryInputObjectTypes;
3075
- }
3076
- __name(resolveMongoDbRawQueryInputObjectTypes, "resolveMongoDbRawQueryInputObjectTypes");
3077
- function getMongoDbRawQueries(outputObjectTypes) {
3078
- const queryOutputTypes = outputObjectTypes.filter((item) => item.name === "Query");
3079
- const mongodbRawQueries = queryOutputTypes?.[0].fields.filter((field) => field.name.includes("Raw")) ?? [];
3080
- return mongodbRawQueries;
3081
- }
3082
- __name(getMongoDbRawQueries, "getMongoDbRawQueries");
3083
- var isMongodbRawOp = /* @__PURE__ */ __name((name) => /find[\s\S]*?Raw/.test(name) || /aggregate[\s\S]*?Raw/.test(name), "isMongodbRawOp");
3084
-
3085
- // src/zod/transformer.ts
3086
- var Transformer = class _Transformer {
3087
- static {
3088
- __name(this, "Transformer");
3089
- }
3090
- name;
3091
- fields;
3092
- schemaImports = /* @__PURE__ */ new Set();
3093
- models;
3094
- modelOperations;
3095
- aggregateOperationSupport;
3096
- enumTypes;
3097
- static enumNames = [];
3098
- static rawOpsMap = {};
3099
- static provider;
3100
- static previewFeatures;
3101
- static outputPath = "./generated";
3102
- hasJson = false;
3103
- static prismaClientOutputPath = "@prisma/client";
3104
- static isCustomPrismaClientOutputPath = false;
3105
- static isGenerateSelect = true;
3106
- static isGenerateInclude = true;
3107
- constructor(params) {
3108
- this.name = params.name ?? "";
3109
- this.fields = params.fields ?? [];
3110
- this.models = params.models ?? [];
3111
- this.modelOperations = params.modelOperations ?? [];
3112
- this.aggregateOperationSupport = params.aggregateOperationSupport ?? {};
3113
- this.enumTypes = params.enumTypes ?? [];
3114
- }
3115
- static setOutputPath(outPath) {
3116
- this.outputPath = outPath;
3117
- }
3118
- static setIsGenerateSelect(isGenerateSelect) {
3119
- this.isGenerateSelect = isGenerateSelect;
3120
- }
3121
- static setIsGenerateInclude(isGenerateInclude) {
3122
- this.isGenerateInclude = isGenerateInclude;
3123
- }
3124
- static getOutputPath() {
3125
- return this.outputPath;
3126
- }
3127
- static setPrismaClientOutputPath(prismaClientCustomPath) {
3128
- this.prismaClientOutputPath = prismaClientCustomPath;
3129
- this.isCustomPrismaClientOutputPath = prismaClientCustomPath !== "@prisma/client";
3130
- }
3131
- static async generateIndex() {
3132
- const indexPath = path4.join(_Transformer.outputPath, "schemas/index.ts");
3133
- await writeIndexFile(indexPath);
3134
- }
3135
- async generateEnumSchemas() {
3136
- for (const enumType of this.enumTypes) {
3137
- const { name, values } = enumType;
3138
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/enums/${lowerCaseFirst(name)}.schema.ts`), `${this.generateImportZodStatement()}
3139
- ${this.generateExportSchemaStatement(`${lowerCaseFirst(name)}`, `z.enum(${JSON.stringify(values)})`)}`);
3140
- }
3141
- }
3142
- generateImportZodStatement() {
3143
- return "import { z } from 'zod';\n";
3144
- }
3145
- generateExportSchemaStatement(name, schema) {
3146
- return `export const ${lowerCaseFirst(name)}Schema = ${schema}`;
3147
- }
3148
- async generateObjectSchema() {
3149
- const zodObjectSchemaFields = this.generateObjectSchemaFields();
3150
- const objectSchema = this.prepareObjectSchema(zodObjectSchemaFields);
3151
- const objectSchemaName = this.resolveObjectSchemaName();
3152
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/objects/${lowerCaseFirst(objectSchemaName)}.schema.ts`), objectSchema);
3153
- }
3154
- generateObjectSchemaFields() {
3155
- const zodObjectSchemaFields = this.fields.map((field) => this.generateObjectSchemaField(field)).flatMap((item) => item).map((item) => {
3156
- const [zodStringWithMainType, field, skipValidators] = item;
3157
- const value = skipValidators ? zodStringWithMainType : this.generateFieldValidators(zodStringWithMainType, field);
3158
- return value.trim();
3159
- });
3160
- return zodObjectSchemaFields;
3161
- }
3162
- generateObjectSchemaField(field) {
3163
- const lines = field.inputTypes;
3164
- if (lines.length === 0) {
3165
- return [];
3166
- }
3167
- let alternatives = lines.reduce((result, inputType) => {
3168
- if (inputType.type === "String") {
3169
- result.push(this.wrapWithZodValidators("z.string()", field));
3170
- } else if (inputType.type === "Int" || inputType.type === "Float" || inputType.type === "Decimal") {
3171
- result.push(this.wrapWithZodValidators("z.number()", field));
3172
- } else if (inputType.type === "BigInt") {
3173
- result.push(this.wrapWithZodValidators("z.bigint()", field));
3174
- } else if (inputType.type === "Boolean") {
3175
- result.push(this.wrapWithZodValidators("z.boolean()", field));
3176
- } else if (inputType.type === "DateTime") {
3177
- result.push(this.wrapWithZodValidators("z.coerce.date()", field));
3178
- } else if (inputType.type === "Json") {
3179
- this.hasJson = true;
3180
- result.push(this.wrapWithZodValidators("jsonSchema", field));
3181
- } else if (inputType.type === "True") {
3182
- result.push(this.wrapWithZodValidators("z.literal(true)", field));
3183
- } else if (inputType.type === "Bytes") {
3184
- result.push(this.wrapWithZodValidators("z.instanceof(Buffer)", field));
3185
- } else if (!inputType.type.endsWith("FieldRefInput")) {
3186
- const isEnum = inputType.location === "enumTypes";
3187
- if (inputType.namespace === "prisma" || isEnum) {
3188
- if (inputType.type !== this.name && typeof inputType.type === "string") {
3189
- this.addSchemaImport(inputType.type);
3190
- }
3191
- result.push(this.generatePrismaStringLine(field, inputType, lines.length));
3192
- }
3193
- }
3194
- return result;
3195
- }, []);
3196
- if (alternatives.length === 0) {
3197
- return [];
3198
- }
3199
- if (alternatives.length > 1) {
3200
- alternatives = alternatives.map((alter) => alter.replace(".optional()", ""));
3201
- }
3202
- const fieldName = alternatives.some((alt) => alt.includes(":")) ? "" : ` ${field.name}:`;
3203
- const opt = !field.isRequired ? ".optional()" : "";
3204
- let resString = alternatives.length === 1 ? alternatives.join(",\r\n") : `z.union([${alternatives.join(",\r\n")}])${opt}`;
3205
- if (field.isNullable) {
3206
- resString += ".nullable()";
3207
- }
3208
- return [
3209
- [
3210
- ` ${fieldName} ${resString} `,
3211
- field,
3212
- true
3213
- ]
3214
- ];
3215
- }
3216
- wrapWithZodValidators(mainValidator, field) {
3217
- let line = "";
3218
- line = mainValidator;
3219
- if (field.inputTypes.some((inputType) => inputType.isList)) {
3220
- line += ".array()";
3221
- }
3222
- if (!field.isRequired) {
3223
- line += ".optional()";
3224
- }
3225
- return line;
3226
- }
3227
- addSchemaImport(name) {
3228
- this.schemaImports.add(name);
3229
- }
3230
- generatePrismaStringLine(field, inputType, inputsLength) {
3231
- const isEnum = inputType.location === "enumTypes";
3232
- const inputTypeString = inputType.type;
3233
- const { isModelQueryType, modelName, queryName } = this.checkIsModelQueryType(inputTypeString);
3234
- const objectSchemaLine = isModelQueryType ? this.resolveModelQuerySchemaName(modelName, queryName) : `${inputTypeString}ObjectSchema`;
3235
- const enumSchemaLine = `${inputTypeString}Schema`;
3236
- const schema = inputType.type === this.name ? objectSchemaLine : isEnum ? enumSchemaLine : objectSchemaLine;
3237
- const arr = inputType.isList ? ".array()" : "";
3238
- const opt = !field.isRequired ? ".optional()" : "";
3239
- return inputsLength === 1 ? ` ${field.name}: z.lazy(() => ${lowerCaseFirst(schema)})${arr}${opt}` : `z.lazy(() => ${lowerCaseFirst(schema)})${arr}${opt}`;
3240
- }
3241
- generateFieldValidators(zodStringWithMainType, field) {
3242
- const { isRequired, isNullable } = field;
3243
- if (!isRequired) {
3244
- zodStringWithMainType += ".optional()";
3245
- }
3246
- if (isNullable) {
3247
- zodStringWithMainType += ".nullable()";
3248
- }
3249
- return zodStringWithMainType;
3250
- }
3251
- prepareObjectSchema(zodObjectSchemaFields) {
3252
- const objectSchema = `${this.generateExportObjectSchemaStatement(this.addFinalWrappers({
3253
- zodStringFields: zodObjectSchemaFields
3254
- }))}
3255
- `;
3256
- const prismaImportStatement = this.generateImportPrismaStatement();
3257
- const json = this.generateJsonSchemaImplementation();
3258
- return `${this.generateObjectSchemaImportStatements()}${prismaImportStatement}${json}${objectSchema}`;
3259
- }
3260
- generateExportObjectSchemaStatement(schema) {
3261
- let name = this.name;
3262
- let exportName = this.name;
3263
- if (_Transformer.provider === "mongodb") {
3264
- if (isMongodbRawOp(name)) {
3265
- name = _Transformer.rawOpsMap[name];
3266
- exportName = name.replace("Args", "");
3267
- }
3268
- }
3269
- if (isAggregateInputType(name)) {
3270
- name = `${name}Type`;
3271
- }
3272
- const end = `export const ${lowerCaseFirst(exportName)}ObjectSchema = schema`;
3273
- return `const schema: z.ZodType<Prisma.${name}> = ${schema};
3274
-
3275
- ${end}`;
3276
- }
3277
- addFinalWrappers({ zodStringFields }) {
3278
- const fields = [
3279
- ...zodStringFields
3280
- ];
3281
- return `${this.wrapWithZodObject(fields)}.strict()`;
3282
- }
3283
- generateImportPrismaStatement() {
3284
- let prismaClientImportPath;
3285
- if (_Transformer.isCustomPrismaClientOutputPath) {
3286
- const fromPath = path4.join(_Transformer.outputPath, "schemas", "objects");
3287
- const toPath = _Transformer.prismaClientOutputPath;
3288
- const relativePathFromOutputToPrismaClient = path4.relative(fromPath, toPath).split(path4.sep).join(path4.posix.sep);
3289
- prismaClientImportPath = relativePathFromOutputToPrismaClient;
3290
- } else {
3291
- prismaClientImportPath = _Transformer.prismaClientOutputPath;
3292
- }
3293
- return `import type { Prisma } from '${prismaClientImportPath}';
3294
-
3295
- `;
3296
- }
3297
- generateJsonSchemaImplementation() {
3298
- let jsonSchemaImplementation = "";
3299
- if (this.hasJson) {
3300
- jsonSchemaImplementation += `
3301
- `;
3302
- jsonSchemaImplementation += `const literalSchema = z.union([z.string(), z.number(), z.boolean()]);
3303
- `;
3304
- jsonSchemaImplementation += `const jsonSchema: z.ZodType<Prisma.InputJsonValue> = z.lazy(() =>
3305
- `;
3306
- jsonSchemaImplementation += ` z.union([literalSchema, z.array(jsonSchema.nullable()), z.record(jsonSchema.nullable())])
3307
- `;
3308
- jsonSchemaImplementation += `);
3309
-
3310
- `;
3311
- }
3312
- return jsonSchemaImplementation;
3313
- }
3314
- generateObjectSchemaImportStatements() {
3315
- let generatedImports = this.generateImportZodStatement();
3316
- generatedImports += this.generateSchemaImports();
3317
- generatedImports += "\n\n";
3318
- return generatedImports;
3319
- }
3320
- generateSchemaImports() {
3321
- return [
3322
- ...this.schemaImports
3323
- ].map((name) => {
3324
- const { isModelQueryType, modelName, queryName } = this.checkIsModelQueryType(name);
3325
- if (isModelQueryType) {
3326
- return `import { ${this.resolveModelQuerySchemaName(modelName, queryName)} } from '../${queryName}${modelName}.schema'`;
3327
- } else if (_Transformer.enumNames.includes(name)) {
3328
- return `import { ${lowerCaseFirst(name)}Schema } from '../enums/${lowerCaseFirst(name)}.schema'`;
3329
- } else {
3330
- return `import { ${lowerCaseFirst(name)}ObjectSchema } from './${lowerCaseFirst(name)}.schema'`;
3331
- }
3332
- }).join(";\r\n");
3333
- }
3334
- checkIsModelQueryType(type) {
3335
- const modelQueryTypeSuffixToQueryName = {
3336
- FindManyArgs: "findMany"
3337
- };
3338
- for (const modelQueryType of [
3339
- "FindManyArgs"
3340
- ]) {
3341
- if (type.includes(modelQueryType)) {
3342
- const modelQueryTypeSuffixIndex = type.indexOf(modelQueryType);
3343
- return {
3344
- isModelQueryType: true,
3345
- modelName: type.substring(0, modelQueryTypeSuffixIndex),
3346
- queryName: modelQueryTypeSuffixToQueryName[modelQueryType]
3347
- };
3348
- }
3349
- }
3350
- return {
3351
- isModelQueryType: false
3352
- };
3353
- }
3354
- resolveModelQuerySchemaName(modelName, queryName) {
3355
- const modelNameUncapitalized = lowerCaseFirst(modelName);
3356
- const queryNameCapitalized = upperCaseFirst(queryName);
3357
- return `${modelNameUncapitalized}${queryNameCapitalized}Schema`;
3358
- }
3359
- wrapWithZodUnion(zodStringFields) {
3360
- let wrapped = "";
3361
- wrapped += "z.union([";
3362
- wrapped += "\n";
3363
- wrapped += ` ${zodStringFields.join(",")}`;
3364
- wrapped += "\n";
3365
- wrapped += "])";
3366
- return wrapped;
3367
- }
3368
- wrapWithZodObject(zodStringFields) {
3369
- let wrapped = "";
3370
- wrapped += "z.object({";
3371
- wrapped += "\n";
3372
- wrapped += ` ${typeof zodStringFields === "string" ? zodStringFields : zodStringFields.join(",\n ")}`;
3373
- wrapped += "\n";
3374
- wrapped += "})";
3375
- return wrapped;
3376
- }
3377
- resolveObjectSchemaName() {
3378
- let name = this.name;
3379
- let exportName = this.name;
3380
- if (isMongodbRawOp(name)) {
3381
- name = _Transformer.rawOpsMap[name];
3382
- exportName = name.replace("Args", "");
3383
- }
3384
- return lowerCaseFirst(exportName);
3385
- }
3386
- async generateModelSchemas() {
3387
- for (const modelOperation of this.modelOperations) {
3388
- const {
3389
- findUnique,
3390
- findFirst,
3391
- findMany,
3392
- // @ts-ignore
3393
- createOne,
3394
- createMany,
3395
- createManyAndReturn,
3396
- // @ts-ignore
3397
- deleteOne,
3398
- // @ts-ignore
3399
- updateOne,
3400
- deleteMany,
3401
- updateMany,
3402
- updateManyAndReturn,
3403
- // @ts-ignore
3404
- upsertOne,
3405
- aggregate,
3406
- groupBy
3407
- } = modelOperation;
3408
- const model = findModelByName(this.models, modelOperation.model);
3409
- const modelName = lowerCaseFirst(modelOperation.model);
3410
- const { selectImport, includeImport, selectZodSchemaLine, includeZodSchemaLine, selectZodSchemaLineLazy, includeZodSchemaLineLazy } = this.resolveSelectIncludeImportAndZodSchemaLine(model);
3411
- const { orderByImport, orderByZodSchemaLine } = this.resolveOrderByWithRelationImportAndZodSchemaLine(model);
3412
- if (findUnique) {
3413
- const imports = [
3414
- selectImport,
3415
- includeImport,
3416
- `import { ${modelName}WhereUniqueInputObjectSchema } from './objects/${modelName}WhereUniqueInput.schema'`
3417
- ];
3418
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/${findUnique}.schema.ts`), `${this.generateImportStatements(imports)}${this.generateExportSchemaStatement(`${modelName}FindUnique`, `z.object({ ${selectZodSchemaLine} ${includeZodSchemaLine} where: ${modelName}WhereUniqueInputObjectSchema })`)}`);
3419
- }
3420
- if (findFirst) {
3421
- const imports = [
3422
- selectImport,
3423
- includeImport,
3424
- orderByImport,
3425
- `import { ${modelName}WhereInputObjectSchema } from './objects/${modelName}WhereInput.schema'`,
3426
- `import { ${modelName}WhereUniqueInputObjectSchema } from './objects/${modelName}WhereUniqueInput.schema'`,
3427
- `import { ${modelName}ScalarFieldEnumSchema } from './enums/${modelName}ScalarFieldEnum.schema'`
3428
- ];
3429
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/${findFirst}.schema.ts`), `${this.generateImportStatements(imports)}${this.generateExportSchemaStatement(`${modelName}FindFirst`, `z.object({ ${selectZodSchemaLine} ${includeZodSchemaLine} ${orderByZodSchemaLine} where: ${modelName}WhereInputObjectSchema.optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${modelName}ScalarFieldEnumSchema).optional() })`)}`);
3430
- }
3431
- if (findMany) {
3432
- const imports = [
3433
- selectImport,
3434
- includeImport,
3435
- orderByImport,
3436
- `import { ${modelName}WhereInputObjectSchema } from './objects/${modelName}WhereInput.schema'`,
3437
- `import { ${modelName}WhereUniqueInputObjectSchema } from './objects/${modelName}WhereUniqueInput.schema'`,
3438
- `import { ${modelName}ScalarFieldEnumSchema } from './enums/${modelName}ScalarFieldEnum.schema'`
3439
- ];
3440
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/${findMany}.schema.ts`), `${this.generateImportStatements(imports)}${this.generateExportSchemaStatement(`${modelName}FindMany`, `z.object({ ${selectZodSchemaLineLazy} ${includeZodSchemaLineLazy} ${orderByZodSchemaLine} where: ${modelName}WhereInputObjectSchema.optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), distinct: z.array(${modelName}ScalarFieldEnumSchema).optional() })`)}`);
3441
- }
3442
- if (createOne) {
3443
- const imports = [
3444
- selectImport,
3445
- includeImport,
3446
- `import { ${modelName}CreateInputObjectSchema } from './objects/${modelName}CreateInput.schema'`,
3447
- `import { ${modelName}UncheckedCreateInputObjectSchema } from './objects/${modelName}UncheckedCreateInput.schema'`
3448
- ];
3449
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/${createOne}.schema.ts`), `${this.generateImportStatements(imports)}${this.generateExportSchemaStatement(`${modelName}CreateOne`, `z.object({ ${selectZodSchemaLine} ${includeZodSchemaLine} data: z.union([${modelName}CreateInputObjectSchema, ${modelName}UncheckedCreateInputObjectSchema]) })`)}`);
3450
- }
3451
- if (createMany) {
3452
- const imports = [
3453
- `import { ${modelName}CreateManyInputObjectSchema } from './objects/${modelName}CreateManyInput.schema'`
3454
- ];
3455
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/${createMany}.schema.ts`), `${this.generateImportStatements(imports)}${this.generateExportSchemaStatement(`${modelName}CreateMany`, `z.object({ data: z.union([ ${modelName}CreateManyInputObjectSchema, z.array(${modelName}CreateManyInputObjectSchema) ]), ${_Transformer.provider === "mongodb" || _Transformer.provider === "sqlserver" ? "" : "skipDuplicates: z.boolean().optional()"} })`)}`);
3456
- }
3457
- if (createManyAndReturn) {
3458
- const imports = [
3459
- `import { ${modelName}CreateManyAndReturnInputObjectSchema } from './objects/${modelName}CreateManyAndReturnInput.schema'`
3460
- ];
3461
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/${createManyAndReturn}.schema.ts`), `${this.generateImportStatements(imports)}${this.generateExportSchemaStatement(`${modelName}CreateManyAndReturn`, `z.object({ data: z.union([ ${modelName}CreateManyAndReturnInputObjectSchema, z.array(${modelName}CreateManyAndReturnInputObjectSchema) ]), ${_Transformer.provider === "mongodb" || _Transformer.provider === "sqlserver" ? "" : "skipDuplicates: z.boolean().optional()"} })`)}`);
3462
- }
3463
- if (deleteOne) {
3464
- const imports = [
3465
- selectImport,
3466
- includeImport,
3467
- `import { ${modelName}WhereUniqueInputObjectSchema } from './objects/${modelName}WhereUniqueInput.schema'`
3468
- ];
3469
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/${deleteOne}.schema.ts`), `${this.generateImportStatements(imports)}${this.generateExportSchemaStatement(`${modelName}DeleteOne`, `z.object({ ${selectZodSchemaLine} ${includeZodSchemaLine} where: ${modelName}WhereUniqueInputObjectSchema })`)}`);
3470
- }
3471
- if (deleteMany) {
3472
- const imports = [
3473
- `import { ${modelName}WhereInputObjectSchema } from './objects/${modelName}WhereInput.schema'`
3474
- ];
3475
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/${deleteMany}.schema.ts`), `${this.generateImportStatements(imports)}${this.generateExportSchemaStatement(`${modelName}DeleteMany`, `z.object({ where: ${modelName}WhereInputObjectSchema.optional() })`)}`);
3476
- }
3477
- if (updateOne) {
3478
- const imports = [
3479
- selectImport,
3480
- includeImport,
3481
- `import { ${modelName}UpdateInputObjectSchema } from './objects/${modelName}UpdateInput.schema'`,
3482
- `import { ${modelName}UncheckedUpdateInputObjectSchema } from './objects/${modelName}UncheckedUpdateInput.schema'`,
3483
- `import { ${modelName}WhereUniqueInputObjectSchema } from './objects/${modelName}WhereUniqueInput.schema'`
3484
- ];
3485
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/${updateOne}.schema.ts`), `${this.generateImportStatements(imports)}${this.generateExportSchemaStatement(`${modelName}UpdateOne`, `z.object({ ${selectZodSchemaLine} ${includeZodSchemaLine} data: z.union([${modelName}UpdateInputObjectSchema, ${modelName}UncheckedUpdateInputObjectSchema]), where: ${modelName}WhereUniqueInputObjectSchema })`)}`);
3486
- }
3487
- if (updateMany) {
3488
- const imports = [
3489
- `import { ${modelName}UpdateManyMutationInputObjectSchema } from './objects/${modelName}UpdateManyMutationInput.schema'`,
3490
- `import { ${modelName}WhereInputObjectSchema } from './objects/${modelName}WhereInput.schema'`
3491
- ];
3492
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/${updateMany}.schema.ts`), `${this.generateImportStatements(imports)}${this.generateExportSchemaStatement(`${modelName}UpdateMany`, `z.object({ data: ${modelName}UpdateManyMutationInputObjectSchema, where: ${modelName}WhereInputObjectSchema.optional() })`)}`);
3493
- }
3494
- if (updateManyAndReturn) {
3495
- const imports = [
3496
- `import { ${modelName}UpdateManyAndReturnInputObjectSchema } from './objects/${modelName}UpdateManyAndReturnInput.schema'`
3497
- ];
3498
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/${updateManyAndReturn}.schema.ts`), `${this.generateImportStatements(imports)}${this.generateExportSchemaStatement(`${modelName}UpdateManyAndReturn`, `z.object({ data: z.union([ ${modelName}UpdateManyAndReturnInputObjectSchema, z.array(${modelName}UpdateManyAndReturnInputObjectSchema) ]), ${_Transformer.provider === "mongodb" || _Transformer.provider === "sqlserver" ? "" : "skipDuplicates: z.boolean().optional()"} })`)}`);
3499
- }
3500
- if (upsertOne) {
3501
- const imports = [
3502
- selectImport,
3503
- includeImport,
3504
- `import { ${modelName}WhereUniqueInputObjectSchema } from './objects/${modelName}WhereUniqueInput.schema'`,
3505
- `import { ${modelName}CreateInputObjectSchema } from './objects/${modelName}CreateInput.schema'`,
3506
- `import { ${modelName}UncheckedCreateInputObjectSchema } from './objects/${modelName}UncheckedCreateInput.schema'`,
3507
- `import { ${modelName}UpdateInputObjectSchema } from './objects/${modelName}UpdateInput.schema'`,
3508
- `import { ${modelName}UncheckedUpdateInputObjectSchema } from './objects/${modelName}UncheckedUpdateInput.schema'`
3509
- ];
3510
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/${upsertOne}.schema.ts`), `${this.generateImportStatements(imports)}${this.generateExportSchemaStatement(`${modelName}Upsert`, `z.object({ ${selectZodSchemaLine} ${includeZodSchemaLine} where: ${modelName}WhereUniqueInputObjectSchema, create: z.union([ ${modelName}CreateInputObjectSchema, ${modelName}UncheckedCreateInputObjectSchema ]), update: z.union([ ${modelName}UpdateInputObjectSchema, ${modelName}UncheckedUpdateInputObjectSchema ]) })`)}`);
3511
- }
3512
- if (aggregate) {
3513
- const imports = [
3514
- orderByImport,
3515
- `import { ${modelName}WhereInputObjectSchema } from './objects/${modelName}WhereInput.schema'`,
3516
- `import { ${modelName}WhereUniqueInputObjectSchema } from './objects/${modelName}WhereUniqueInput.schema'`
3517
- ];
3518
- const aggregateOperations = [];
3519
- if (this.aggregateOperationSupport[modelName]) {
3520
- if (this.aggregateOperationSupport[modelName].count) {
3521
- imports.push(`import { ${modelName}CountAggregateInputObjectSchema } from './objects/${modelName}CountAggregateInput.schema'`);
3522
- aggregateOperations.push(`_count: z.union([ z.literal(true), ${modelName}CountAggregateInputObjectSchema ]).optional()`);
3523
- }
3524
- if (this.aggregateOperationSupport[modelName].min) {
3525
- imports.push(`import { ${modelName}MinAggregateInputObjectSchema } from './objects/${modelName}MinAggregateInput.schema'`);
3526
- aggregateOperations.push(`_min: ${modelName}MinAggregateInputObjectSchema.optional()`);
3527
- }
3528
- if (this.aggregateOperationSupport[modelName].max) {
3529
- imports.push(`import { ${modelName}MaxAggregateInputObjectSchema } from './objects/${modelName}MaxAggregateInput.schema'`);
3530
- aggregateOperations.push(`_max: ${modelName}MaxAggregateInputObjectSchema.optional()`);
3531
- }
3532
- if (this.aggregateOperationSupport[modelName].avg) {
3533
- imports.push(`import { ${modelName}AvgAggregateInputObjectSchema } from './objects/${modelName}AvgAggregateInput.schema'`);
3534
- aggregateOperations.push(`_avg: ${modelName}AvgAggregateInputObjectSchema.optional()`);
3535
- }
3536
- if (this.aggregateOperationSupport[modelName].sum) {
3537
- imports.push(`import { ${modelName}SumAggregateInputObjectSchema } from './objects/${modelName}SumAggregateInput.schema'`);
3538
- aggregateOperations.push(`_sum: ${modelName}SumAggregateInputObjectSchema.optional()`);
3539
- }
3540
- }
3541
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/${aggregate}.schema.ts`), `${this.generateImportStatements(imports)}${this.generateExportSchemaStatement(`${modelName}Aggregate`, `z.object({ ${orderByZodSchemaLine} where: ${modelName}WhereInputObjectSchema.optional(), cursor: ${modelName}WhereUniqueInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), ${aggregateOperations.join(", ")} })`)}`);
3542
- }
3543
- if (groupBy) {
3544
- const imports = [
3545
- `import { ${modelName}WhereInputObjectSchema } from './objects/${modelName}WhereInput.schema'`,
3546
- `import { ${modelName}OrderByWithAggregationInputObjectSchema } from './objects/${modelName}OrderByWithAggregationInput.schema'`,
3547
- `import { ${modelName}ScalarWhereWithAggregatesInputObjectSchema } from './objects/${modelName}ScalarWhereWithAggregatesInput.schema'`,
3548
- `import { ${modelName}ScalarFieldEnumSchema } from './enums/${modelName}ScalarFieldEnum.schema'`
3549
- ];
3550
- await writeFileSafely(path4.join(_Transformer.outputPath, `schemas/${groupBy}.schema.ts`), `${this.generateImportStatements(imports)}${this.generateExportSchemaStatement(`${modelName}GroupBy`, `z.object({ where: ${modelName}WhereInputObjectSchema.optional(), orderBy: z.union([${modelName}OrderByWithAggregationInputObjectSchema, ${modelName}OrderByWithAggregationInputObjectSchema.array()]).optional(), having: ${modelName}ScalarWhereWithAggregatesInputObjectSchema.optional(), take: z.number().optional(), skip: z.number().optional(), by: z.array(${modelName}ScalarFieldEnumSchema) })`)}`);
3551
- }
3552
- }
3553
- }
3554
- generateImportStatements(imports) {
3555
- let generatedImports = this.generateImportZodStatement();
3556
- generatedImports += imports?.filter((importItem) => !!importItem).join(";\r\n") ?? "";
3557
- generatedImports += "\n\n";
3558
- return generatedImports;
3559
- }
3560
- resolveSelectIncludeImportAndZodSchemaLine(model) {
3561
- const { name: modelName } = model;
3562
- const hasRelationToAnotherModel = checkModelHasModelRelation(model);
3563
- const selectImport = _Transformer.isGenerateSelect ? `import { ${lowerCaseFirst(modelName)}SelectObjectSchema } from './objects/${lowerCaseFirst(modelName)}Select.schema'` : "";
3564
- const includeImport = _Transformer.isGenerateInclude && hasRelationToAnotherModel ? `import { ${lowerCaseFirst(modelName)}IncludeObjectSchema } from './objects/${lowerCaseFirst(modelName)}Include.schema'` : "";
3565
- let selectZodSchemaLine = "";
3566
- let includeZodSchemaLine = "";
3567
- let selectZodSchemaLineLazy = "";
3568
- let includeZodSchemaLineLazy = "";
3569
- if (_Transformer.isGenerateSelect) {
3570
- const zodSelectObjectSchema = `${lowerCaseFirst(modelName)}SelectObjectSchema.optional()`;
3571
- selectZodSchemaLine = `select: ${zodSelectObjectSchema},`;
3572
- selectZodSchemaLineLazy = `select: z.lazy(() => ${zodSelectObjectSchema}),`;
3573
- }
3574
- if (_Transformer.isGenerateInclude && hasRelationToAnotherModel) {
3575
- const zodIncludeObjectSchema = `${lowerCaseFirst(modelName)}IncludeObjectSchema.optional()`;
3576
- includeZodSchemaLine = `include: ${zodIncludeObjectSchema},`;
3577
- includeZodSchemaLineLazy = `include: z.lazy(() => ${zodIncludeObjectSchema}),`;
3578
- }
3579
- return {
3580
- selectImport,
3581
- includeImport,
3582
- selectZodSchemaLine,
3583
- includeZodSchemaLine,
3584
- selectZodSchemaLineLazy,
3585
- includeZodSchemaLineLazy
3586
- };
3587
- }
3588
- resolveOrderByWithRelationImportAndZodSchemaLine(model) {
3589
- const { name: modelName } = model;
3590
- let modelOrderBy = "";
3591
- if ([
3592
- "postgresql",
3593
- "mysql"
3594
- ].includes(_Transformer.provider) && _Transformer.previewFeatures?.includes("fullTextSearch")) {
3595
- modelOrderBy = `${lowerCaseFirst(modelName)}OrderByWithRelationAndSearchRelevanceInput`;
3596
- } else {
3597
- modelOrderBy = `${lowerCaseFirst(modelName)}OrderByWithRelationInput`;
3598
- }
3599
- const orderByImport = `import { ${modelOrderBy}ObjectSchema } from './objects/${modelOrderBy}.schema'`;
3600
- const orderByZodSchemaLine = `orderBy: z.union([${modelOrderBy}ObjectSchema, ${modelOrderBy}ObjectSchema.array()]).optional(),`;
3601
- return {
3602
- orderByImport,
3603
- orderByZodSchemaLine
3604
- };
3605
- }
3606
- };
3607
-
3608
- // src/zod/generator-helpers.ts
3609
- async function generateZodEnumSchemas(prismaSchemaEnum, modelSchemaEnum) {
3610
- const enumTypes = [
3611
- ...prismaSchemaEnum,
3612
- ...modelSchemaEnum
3613
- ];
3614
- const enumNames = enumTypes.map((enumItem) => enumItem.name);
3615
- Transformer.enumNames = enumNames ?? [];
3616
- const transformer = new Transformer({
3617
- enumTypes
3618
- });
3619
- await transformer.generateEnumSchemas();
3620
- }
3621
- __name(generateZodEnumSchemas, "generateZodEnumSchemas");
3622
- async function generateZodObjectSchemas(inputObjectTypes) {
3623
- for (let i = 0; i < inputObjectTypes.length; i += 1) {
3624
- const fields = inputObjectTypes[i]?.fields;
3625
- const name = inputObjectTypes[i]?.name;
3626
- const transformer = new Transformer({
3627
- name,
3628
- fields
3629
- });
3630
- await transformer.generateObjectSchema();
3631
- }
3632
- }
3633
- __name(generateZodObjectSchemas, "generateZodObjectSchemas");
3634
- async function generateZodModelSchemas(models, modelOperations, aggregateOperationSupport) {
3635
- const transformer = new Transformer({
3636
- models,
3637
- modelOperations,
3638
- aggregateOperationSupport
3639
- });
3640
- await transformer.generateModelSchemas();
3641
- }
3642
- __name(generateZodModelSchemas, "generateZodModelSchemas");
3643
- async function generateZodIndex() {
3644
- await Transformer.generateIndex();
3645
- }
3646
- __name(generateZodIndex, "generateZodIndex");
3647
-
3648
- // src/zod/helpers.ts
3649
- init_esm_shims();
3650
-
3651
- // src/zod/include-helpers.ts
3652
- init_esm_shims();
3653
- function addMissingInputObjectTypesForInclude(inputObjectTypes, models, isGenerateSelect) {
3654
- const generatedIncludeInputObjectTypes = generateModelIncludeInputObjectTypes(models, isGenerateSelect);
3655
- for (const includeInputObjectType of generatedIncludeInputObjectTypes) {
3656
- inputObjectTypes.push(includeInputObjectType);
3657
- }
3658
- }
3659
- __name(addMissingInputObjectTypesForInclude, "addMissingInputObjectTypesForInclude");
3660
- function generateModelIncludeInputObjectTypes(models, isGenerateSelect) {
3661
- const modelIncludeInputObjectTypes = [];
3662
- for (const model of models) {
3663
- const { name: modelName, fields: modelFields } = model;
3664
- const fields = [];
3665
- for (const modelField of modelFields) {
3666
- const { name: modelFieldName, isList, type } = modelField;
3667
- const isRelationField = checkIsModelRelationField(modelField);
3668
- if (isRelationField) {
3669
- const field = {
3670
- name: modelFieldName,
3671
- isRequired: false,
3672
- isNullable: false,
3673
- inputTypes: [
3674
- {
3675
- isList: false,
3676
- type: "Boolean",
3677
- location: "scalar"
3678
- },
3679
- {
3680
- isList: false,
3681
- type: isList ? `${type}FindManyArgs` : `${type}DefaultArgs`,
3682
- location: "inputObjectTypes",
3683
- namespace: "prisma"
3684
- }
3685
- ]
3686
- };
3687
- fields.push(field);
3688
- }
3689
- }
3690
- const hasRelationToAnotherModel = checkModelHasModelRelation(model);
3691
- if (!hasRelationToAnotherModel) {
3692
- continue;
3693
- }
3694
- const hasManyRelationToAnotherModel = checkModelHasManyModelRelation(model);
3695
- const shouldAddCountField = hasManyRelationToAnotherModel;
3696
- if (shouldAddCountField) {
3697
- const inputTypes = [
3698
- {
3699
- isList: false,
3700
- type: "Boolean",
3701
- location: "scalar"
3702
- }
3703
- ];
3704
- if (isGenerateSelect) {
3705
- inputTypes.push({
3706
- isList: false,
3707
- type: `${modelName}CountOutputTypeDefaultArgs`,
3708
- location: "inputObjectTypes",
3709
- namespace: "prisma"
3710
- });
3711
- }
3712
- const _countField = {
3713
- name: "_count",
3714
- isRequired: false,
3715
- isNullable: false,
3716
- inputTypes
3717
- };
3718
- fields.push(_countField);
3719
- }
3720
- const modelIncludeInputObjectType = {
3721
- name: `${modelName}Include`,
3722
- constraints: {
3723
- maxNumFields: null,
3724
- minNumFields: null
3725
- },
3726
- fields
3727
- };
3728
- modelIncludeInputObjectTypes.push(modelIncludeInputObjectType);
3729
- }
3730
- return modelIncludeInputObjectTypes;
3731
- }
3732
- __name(generateModelIncludeInputObjectTypes, "generateModelIncludeInputObjectTypes");
3733
-
3734
- // src/zod/modelArgs-helpers.ts
3735
- init_esm_shims();
3736
- function addMissingInputObjectTypesForModelArgs(inputObjectTypes, models, isGenerateSelect, isGenerateInclude) {
3737
- const modelArgsInputObjectTypes = generateModelArgsInputObjectTypes(models, isGenerateSelect, isGenerateInclude);
3738
- for (const modelArgsInputObjectType of modelArgsInputObjectTypes) {
3739
- inputObjectTypes.push(modelArgsInputObjectType);
3740
- }
3741
- }
3742
- __name(addMissingInputObjectTypesForModelArgs, "addMissingInputObjectTypesForModelArgs");
3743
- function generateModelArgsInputObjectTypes(models, isGenerateSelect, isGenerateInclude) {
3744
- const modelArgsInputObjectTypes = [];
3745
- for (const model of models) {
3746
- const { name: modelName } = model;
3747
- const fields = [];
3748
- if (isGenerateSelect) {
3749
- const selectField = {
3750
- name: "select",
3751
- isRequired: false,
3752
- isNullable: false,
3753
- inputTypes: [
3754
- {
3755
- isList: false,
3756
- type: `${modelName}Select`,
3757
- location: "inputObjectTypes",
3758
- namespace: "prisma"
3759
- }
3760
- ]
3761
- };
3762
- fields.push(selectField);
3763
- }
3764
- const hasRelationToAnotherModel = checkModelHasModelRelation(model);
3765
- if (isGenerateInclude && hasRelationToAnotherModel) {
3766
- const includeField = {
3767
- name: "include",
3768
- isRequired: false,
3769
- isNullable: false,
3770
- inputTypes: [
3771
- {
3772
- isList: false,
3773
- type: `${modelName}Include`,
3774
- location: "inputObjectTypes",
3775
- namespace: "prisma"
3776
- }
3777
- ]
3778
- };
3779
- fields.push(includeField);
3780
- }
3781
- const modelArgsInputObjectType = {
3782
- name: `${modelName}DefaultArgs`,
3783
- constraints: {
3784
- maxNumFields: null,
3785
- minNumFields: null
3786
- },
3787
- fields
3788
- };
3789
- modelArgsInputObjectTypes.push(modelArgsInputObjectType);
3790
- }
3791
- return modelArgsInputObjectTypes;
3792
- }
3793
- __name(generateModelArgsInputObjectTypes, "generateModelArgsInputObjectTypes");
3794
-
3795
- // src/zod/select-helpers.ts
3796
- init_esm_shims();
3797
- function addMissingInputObjectTypesForSelect(inputObjectTypes, outputObjectTypes, models) {
3798
- const modelCountOutputTypes = getModelCountOutputTypes(outputObjectTypes);
3799
- const modelCountOutputTypeSelectInputObjectTypes = generateModelCountOutputTypeSelectInputObjectTypes(modelCountOutputTypes);
3800
- const modelCountOutputTypeArgsInputObjectTypes = generateModelCountOutputTypeArgsInputObjectTypes(modelCountOutputTypes);
3801
- const modelSelectInputObjectTypes = generateModelSelectInputObjectTypes(models);
3802
- const generatedInputObjectTypes = [
3803
- modelCountOutputTypeSelectInputObjectTypes,
3804
- modelCountOutputTypeArgsInputObjectTypes,
3805
- modelSelectInputObjectTypes
3806
- ].flat();
3807
- for (const inputObjectType of generatedInputObjectTypes) {
3808
- inputObjectTypes.push(inputObjectType);
3809
- }
3810
- }
3811
- __name(addMissingInputObjectTypesForSelect, "addMissingInputObjectTypesForSelect");
3812
- function getModelCountOutputTypes(outputObjectTypes) {
3813
- return outputObjectTypes.filter(({ name }) => name.includes("CountOutputType"));
3814
- }
3815
- __name(getModelCountOutputTypes, "getModelCountOutputTypes");
3816
- function generateModelCountOutputTypeSelectInputObjectTypes(modelCountOutputTypes) {
3817
- const modelCountOutputTypeSelectInputObjectTypes = [];
3818
- for (const modelCountOutputType of modelCountOutputTypes) {
3819
- const { name: modelCountOutputTypeName, fields: modelCountOutputTypeFields } = modelCountOutputType;
3820
- const modelCountOutputTypeSelectInputObjectType = {
3821
- name: `${modelCountOutputTypeName}Select`,
3822
- constraints: {
3823
- maxNumFields: null,
3824
- minNumFields: null
3825
- },
3826
- fields: modelCountOutputTypeFields.map(({ name }) => ({
3827
- name,
3828
- isRequired: false,
3829
- isNullable: false,
3830
- inputTypes: [
3831
- {
3832
- isList: false,
3833
- type: `Boolean`,
3834
- location: "scalar"
3835
- }
3836
- ]
3837
- }))
3838
- };
3839
- modelCountOutputTypeSelectInputObjectTypes.push(modelCountOutputTypeSelectInputObjectType);
3840
- }
3841
- return modelCountOutputTypeSelectInputObjectTypes;
3842
- }
3843
- __name(generateModelCountOutputTypeSelectInputObjectTypes, "generateModelCountOutputTypeSelectInputObjectTypes");
3844
- function generateModelCountOutputTypeArgsInputObjectTypes(modelCountOutputTypes) {
3845
- const modelCountOutputTypeArgsInputObjectTypes = [];
3846
- for (const modelCountOutputType of modelCountOutputTypes) {
3847
- const { name: modelCountOutputTypeName } = modelCountOutputType;
3848
- const modelCountOutputTypeArgsInputObjectType = {
3849
- name: `${modelCountOutputTypeName}DefaultArgs`,
3850
- constraints: {
3851
- maxNumFields: null,
3852
- minNumFields: null
3853
- },
3854
- fields: [
3855
- {
3856
- name: "select",
3857
- isRequired: false,
3858
- isNullable: false,
3859
- inputTypes: [
3860
- {
3861
- isList: false,
3862
- type: `${modelCountOutputTypeName}Select`,
3863
- location: "inputObjectTypes",
3864
- namespace: "prisma"
3865
- }
3866
- ]
3867
- }
3868
- ]
3869
- };
3870
- modelCountOutputTypeArgsInputObjectTypes.push(modelCountOutputTypeArgsInputObjectType);
3871
- }
3872
- return modelCountOutputTypeArgsInputObjectTypes;
3873
- }
3874
- __name(generateModelCountOutputTypeArgsInputObjectTypes, "generateModelCountOutputTypeArgsInputObjectTypes");
3875
- function generateModelSelectInputObjectTypes(models) {
3876
- const modelSelectInputObjectTypes = [];
3877
- for (const model of models) {
3878
- const { name: modelName, fields: modelFields } = model;
3879
- const fields = [];
3880
- for (const modelField of modelFields) {
3881
- const { name: modelFieldName, isList, type } = modelField;
3882
- const isRelationField = checkIsModelRelationField(modelField);
3883
- const field = {
3884
- name: modelFieldName,
3885
- isRequired: false,
3886
- isNullable: false,
3887
- inputTypes: [
3888
- {
3889
- isList: false,
3890
- type: "Boolean",
3891
- location: "scalar"
3892
- }
3893
- ]
3894
- };
3895
- if (isRelationField) {
3896
- const schemaArgInputType = {
3897
- isList: false,
3898
- type: isList ? `${type}FindManyArgs` : `${type}DefaultArgs`,
3899
- location: "inputObjectTypes",
3900
- namespace: "prisma"
3901
- };
3902
- field.inputTypes.push(schemaArgInputType);
3903
- }
3904
- fields.push(field);
3905
- }
3906
- const hasManyRelationToAnotherModel = checkModelHasManyModelRelation(model);
3907
- const shouldAddCountField = hasManyRelationToAnotherModel;
3908
- if (shouldAddCountField) {
3909
- const _countField = {
3910
- name: "_count",
3911
- isRequired: false,
3912
- isNullable: false,
3913
- inputTypes: [
3914
- {
3915
- isList: false,
3916
- type: "Boolean",
3917
- location: "scalar"
3918
- },
3919
- {
3920
- isList: false,
3921
- type: `${modelName}CountOutputTypeDefaultArgs`,
3922
- location: "inputObjectTypes",
3923
- namespace: "prisma"
3924
- }
3925
- ]
3926
- };
3927
- fields.push(_countField);
3928
- }
3929
- const modelSelectInputObjectType = {
3930
- name: `${modelName}Select`,
3931
- constraints: {
3932
- maxNumFields: null,
3933
- minNumFields: null
3934
- },
3935
- fields
3936
- };
3937
- modelSelectInputObjectTypes.push(modelSelectInputObjectType);
3938
- }
3939
- return modelSelectInputObjectTypes;
3940
- }
3941
- __name(generateModelSelectInputObjectTypes, "generateModelSelectInputObjectTypes");
3942
-
3943
- // src/zod/whereUniqueInput-helpers.ts
3944
- init_esm_shims();
3945
- function changeOptionalToRequiredFields(inputObjectTypes) {
3946
- inputObjectTypes.map((item) => {
3947
- if (item.name.includes("WhereUniqueInput") && // eslint-disable-next-line ts/no-non-null-asserted-optional-chain
3948
- item.constraints.fields?.length > 0) {
3949
- item.fields = item.fields.map((subItem) => {
3950
- if (item.constraints.fields?.includes(subItem.name)) {
3951
- subItem.isRequired = true;
3952
- return subItem;
3953
- }
3954
- return subItem;
3955
- });
3956
- }
3957
- return item;
3958
- });
3959
- }
3960
- __name(changeOptionalToRequiredFields, "changeOptionalToRequiredFields");
3961
-
3962
- // src/zod/helpers.ts
3963
- function addMissingZodInputObjectTypes(inputObjectTypes, outputObjectTypes, models, modelOperations, dataSourceProvider, options) {
3964
- if (dataSourceProvider === "mongodb") {
3965
- addMissingInputObjectTypesForMongoDbRawOpsAndQueries(modelOperations, outputObjectTypes, inputObjectTypes);
3966
- }
3967
- addMissingInputObjectTypesForAggregate(inputObjectTypes, outputObjectTypes);
3968
- if (options.isGenerateSelect) {
3969
- addMissingInputObjectTypesForSelect(inputObjectTypes, outputObjectTypes, models);
3970
- Transformer.setIsGenerateSelect(true);
3971
- }
3972
- if (options.isGenerateSelect || options.isGenerateInclude) {
3973
- addMissingInputObjectTypesForModelArgs(inputObjectTypes, models, options.isGenerateSelect, options.isGenerateInclude);
3974
- }
3975
- if (options.isGenerateInclude) {
3976
- addMissingInputObjectTypesForInclude(inputObjectTypes, models, options.isGenerateSelect);
3977
- Transformer.setIsGenerateInclude(true);
3978
- }
3979
- changeOptionalToRequiredFields(inputObjectTypes);
3980
- }
3981
- __name(addMissingZodInputObjectTypes, "addMissingZodInputObjectTypes");
3982
-
3983
- // src/prisma-generator.ts
3984
- async function generate(options) {
3985
- console.log("[STORM]: Running the Storm Software - Prisma tRPC generator \n");
3986
- const internals = await getPrismaInternals();
3987
- console.log(`[STORM]: Validating configuration options
3988
- `);
3989
- const outputDir = internals.parseEnvValue(options.generator.output);
3990
- const results = await configSchema.safeParseAsync(options.generator.config);
3991
- if (!results.success) {
3992
- throw new Error("Invalid options passed");
3993
- }
3994
- const config = results.data;
3995
- const consoleLog = /* @__PURE__ */ __name((message) => {
3996
- if (config.debug) {
3997
- console.log(`[STORM]: ${message}
3998
- `);
3999
- }
4000
- }, "consoleLog");
4001
- consoleLog(`Using configuration parameters:
4002
- ${JSON.stringify(config)}`);
4003
- consoleLog(`Preparing output directory: ${outputDir}`);
4004
- await removeDirectory(outputDir);
4005
- await createDirectory2(outputDir);
4006
- consoleLog("Finding Prisma Client generator");
4007
- const prismaClientProvider = options.otherGenerators.find((it) => internals.parseEnvValue(it.provider) === "prisma-client-js");
4008
- if (!prismaClientProvider) {
4009
- throw new Error("No Prisma Client generator found. Please add `prisma-client-js` to your generator list.");
4010
- }
4011
- consoleLog("Generating Prisma Client DMMF");
4012
- const prismaClientDmmf = await internals.getDMMF({
4013
- datamodel: options.datamodel,
4014
- previewFeatures: prismaClientProvider?.previewFeatures
4015
- });
4016
- const modelOperations = prismaClientDmmf.mappings.modelOperations;
4017
- const inputObjectTypes = prismaClientDmmf.schema.inputObjectTypes.prisma;
4018
- const outputObjectTypes = prismaClientDmmf.schema.outputObjectTypes.prisma;
4019
- const enumTypes = prismaClientDmmf.schema.enumTypes;
4020
- const models = prismaClientDmmf.datamodel.models;
4021
- const hiddenModels = [];
4022
- const hiddenFields = [];
4023
- if (config.withZod !== false) {
4024
- consoleLog("Generating Zod schemas");
4025
- const zodOutputPath = internals.parseEnvValue(options.generator.output);
4026
- await createDirectory2(zodOutputPath);
4027
- Transformer.setOutputPath(zodOutputPath);
4028
- if (prismaClientProvider?.isCustomOutput) {
4029
- Transformer.setPrismaClientOutputPath(prismaClientProvider.output?.value);
4030
- }
4031
- await constructZodModels(models, joinPaths4(zodOutputPath, "schemas", "models"), config, options);
4032
- resolveZodModelsComments(models, modelOperations, enumTypes, hiddenModels, hiddenFields);
4033
- await generateZodEnumSchemas(enumTypes.prisma, enumTypes.model);
4034
- const dataSource = options.datasources?.[0];
4035
- if (!dataSource) {
4036
- throw new Error("No datasource found");
4037
- }
4038
- const previewFeatures = prismaClientProvider?.previewFeatures;
4039
- Transformer.provider = dataSource.provider;
4040
- Transformer.previewFeatures = previewFeatures;
4041
- addMissingZodInputObjectTypes(inputObjectTypes, outputObjectTypes, models, modelOperations, dataSource.provider, {
4042
- isGenerateSelect: true,
4043
- isGenerateInclude: true
4044
- });
4045
- const aggregateOperationSupport = resolveZodAggregateOperationSupport(inputObjectTypes);
4046
- hideZodInputObjectTypesAndRelatedFields(inputObjectTypes, hiddenModels, hiddenFields);
4047
- await generateZodObjectSchemas(inputObjectTypes);
4048
- await generateZodModelSchemas(models, modelOperations, aggregateOperationSupport);
4049
- await generateZodIndex();
4050
- } else {
4051
- consoleLog("Skipping Zod schemas generation");
4052
- }
4053
- const queries = [];
4054
- const mutations = [];
4055
- const subscriptions = [];
4056
- prismaClientDmmf.mappings.modelOperations.forEach((modelOperation) => {
4057
- const { model: _model, plural: _plural, ...operations } = modelOperation;
4058
- for (const [opType, opNameWithModel] of Object.entries(operations)) {
4059
- if ([
4060
- "findUnique",
4061
- "findUniqueOrThrow",
4062
- "findFirst",
4063
- "findFirstOrThrow",
4064
- "findRaw",
4065
- "findMany",
4066
- "aggregateRaw",
4067
- "count",
4068
- "aggregate",
4069
- "groupBy"
4070
- ].includes(opType)) {
4071
- queries.push(opNameWithModel);
4072
- }
4073
- if ([
4074
- "createOne",
4075
- "createMany",
4076
- "createManyAndReturn",
4077
- "deleteOne",
4078
- "deleteMany",
4079
- "updateOne",
4080
- "updateMany",
4081
- "updateManyAndReturn",
4082
- "upsertOne"
4083
- ].includes(opType)) {
4084
- mutations.push(opNameWithModel);
4085
- }
4086
- }
4087
- });
4088
- queries.sort();
4089
- mutations.sort();
4090
- subscriptions.sort();
4091
- if (config.withShield && !(typeof config.withShield === "string" && (existsSync(joinPaths4(outputDir, config.withShield)) || existsSync(joinPaths4(outputDir, `./${config.withShield}.ts`)) || existsSync(joinPaths4(outputDir, config.withShield, "./shield.ts"))))) {
4092
- consoleLog(`Generating tRPC Shield source file to ${outputDir}`);
4093
- await writeFileSafely(joinPaths4(outputDir, "./shield.ts"), await constructShield({
4094
- queries,
4095
- mutations,
4096
- subscriptions
4097
- }, config, options, outputDir));
4098
- } else {
4099
- consoleLog("Skipping tRPC Shield generation");
4100
- }
4101
- consoleLog(`Generating tRPC source code for ${models.length} models`);
4102
- if (config.trpcOptions && typeof config.trpcOptions === "boolean") {
4103
- consoleLog(`Generating tRPC options source file to ${outputDir}`);
4104
- await writeFileSafely(joinPaths4(outputDir, "./options.ts"), constructDefaultOptions(config, options, outputDir));
4105
- }
4106
- resolveModelsComments(models, hiddenModels);
4107
- consoleLog("Generating tRPC export file");
4108
- const trpcExports = project.createSourceFile(path5.resolve(outputDir, "trpc.ts"), void 0, {
4109
- overwrite: true
4110
- });
4111
- await generateTRPCExports(trpcExports, config, options, outputDir);
4112
- consoleLog("Generating tRPC app router");
4113
- const appRouter = project.createSourceFile(path5.resolve(outputDir, "routers", `index.ts`), void 0, {
4114
- overwrite: true
4115
- });
4116
- consoleLog("Generating tRPC router imports");
4117
- generateCreateRouterImport({
4118
- sourceFile: appRouter
4119
- });
4120
- const routerStatements = [];
4121
- for (const modelOperation of modelOperations) {
4122
- const { model, ...operations } = modelOperation;
4123
- if (hiddenModels.includes(model)) {
4124
- consoleLog(`Skipping model ${model} as it is hidden`);
4125
- continue;
4126
- }
4127
- if (!model) {
4128
- consoleLog(`Skipping model ${model} as it is not defined`);
4129
- continue;
4130
- }
4131
- const modelActions = Object.keys(operations).filter((opType) => (
4132
- // eslint-disable-next-line unicorn/prefer-includes
4133
- config.generateModelActions.some((generateModelAction) => generateModelAction === opType.replace("One", ""))
4134
- ));
4135
- if (!modelActions.length) {
4136
- consoleLog(`Skipping model ${model} as it has no actions to generate`);
4137
- continue;
4138
- }
4139
- const plural = (0, import_pluralize.default)(lowerCaseFirst(model));
4140
- consoleLog(`Generating tRPC router for model ${model}`);
4141
- generateRouterImport(appRouter, plural, model);
4142
- const modelRouter = project.createSourceFile(path5.resolve(outputDir, "routers", `${lowerCaseFirst(model)}.router.ts`), void 0, {
4143
- overwrite: true
4144
- });
4145
- generateCreateRouterImport({
4146
- sourceFile: modelRouter,
4147
- config
4148
- });
4149
- if (config.withZod) {
4150
- consoleLog("Generating Zod schemas imports");
4151
- generateRouterSchemaImports(modelRouter, model, modelActions);
4152
- }
4153
- modelRouter.addStatements(
4154
- /* ts */
4155
- `
4156
- export const ${plural}Router = t.router({`
4157
- );
4158
- for (const opType of modelActions) {
4159
- const opNameWithModel = operations[opType];
4160
- if (opNameWithModel) {
4161
- const baseOpType = opType.replace("OrThrow", "");
4162
- generateProcedure(modelRouter, opNameWithModel, getInputTypeByOpName(baseOpType, model), model, opType, baseOpType, config);
4163
- }
4164
- }
4165
- modelRouter.addStatements(
4166
- /* ts */
4167
- `
4168
- })`
4169
- );
4170
- modelRouter.formatText({
4171
- indentSize: 2
4172
- });
4173
- routerStatements.push(
4174
- /* ts */
4175
- `
4176
- ${lowerCaseFirst(model)}: ${plural}Router`
4177
- );
4178
- consoleLog(`Generated tRPC router for model ${model} with ${modelActions.length} actions`);
4179
- }
4180
- consoleLog("Generating tRPC app router");
4181
- appRouter.addStatements(
4182
- /* ts */
4183
- `
4184
- export const appRouter = t.router({${routerStatements.join()}});
4185
-
4186
- export type AppRouter = typeof appRouter;`
4187
- );
4188
- appRouter.formatText({
4189
- indentSize: 2
4190
- });
4191
- consoleLog("Saving tRPC router source files to disk");
4192
- await project.save();
4193
- consoleLog("Storm Software - Prisma tRPC generator completed successfully");
4194
- }
4195
- __name(generate, "generate");
4196
-
4197
- // src/index.ts
4198
- getPrismaGeneratorHelper().then((helpers) => {
4199
- helpers.generatorHandler({
4200
- onManifest: /* @__PURE__ */ __name(() => ({
4201
- defaultOutput: "./generated",
4202
- prettyName: "Storm Software - Prisma tRPC Generator",
4203
- requiresGenerators: [
4204
- "prisma-client-js"
4205
- ]
4206
- }), "onManifest"),
4207
- onGenerate: generate
4208
- });
4209
- }).catch((reason) => {
4210
- console.error(`An error occured while generating prisma tRPC source code: ${reason}`);
4211
- });