@pegasusheavy/nestjs-prisma-graphql 1.4.2 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/README.md +18 -7
  2. package/dist/benchmark/analysis.d.ts +7 -0
  3. package/dist/benchmark/analysis.d.ts.map +1 -0
  4. package/dist/benchmark/analysis.js +265 -0
  5. package/dist/benchmark/analysis.js.map +1 -0
  6. package/dist/benchmark/index.d.ts +7 -0
  7. package/dist/benchmark/index.d.ts.map +1 -0
  8. package/dist/benchmark/index.js +272 -0
  9. package/dist/benchmark/index.js.map +1 -0
  10. package/dist/event-names.d.ts +2 -0
  11. package/dist/event-names.d.ts.map +1 -0
  12. package/dist/event-names.js +2 -0
  13. package/dist/event-names.js.map +1 -0
  14. package/dist/generate.d.ts +4 -140
  15. package/dist/generate.d.ts.map +1 -0
  16. package/dist/generate.js +199 -2811
  17. package/dist/generate.js.map +1 -1
  18. package/dist/handlers/args-type.d.ts +7 -0
  19. package/dist/handlers/args-type.d.ts.map +1 -0
  20. package/dist/handlers/args-type.js +68 -0
  21. package/dist/handlers/args-type.js.map +1 -0
  22. package/dist/handlers/combine-scalar-filters.d.ts +6 -0
  23. package/dist/handlers/combine-scalar-filters.d.ts.map +1 -0
  24. package/dist/handlers/combine-scalar-filters.js +110 -0
  25. package/dist/handlers/combine-scalar-filters.js.map +1 -0
  26. package/dist/handlers/create-aggregate-input.d.ts +10 -0
  27. package/dist/handlers/create-aggregate-input.d.ts.map +1 -0
  28. package/dist/handlers/create-aggregate-input.js +33 -0
  29. package/dist/handlers/create-aggregate-input.js.map +1 -0
  30. package/dist/handlers/decimal-helpers.d.ts +10 -0
  31. package/dist/handlers/decimal-helpers.d.ts.map +1 -0
  32. package/dist/handlers/decimal-helpers.js +73 -0
  33. package/dist/handlers/decimal-helpers.js.map +1 -0
  34. package/dist/handlers/emit-single.d.ts +3 -0
  35. package/dist/handlers/emit-single.d.ts.map +1 -0
  36. package/dist/handlers/emit-single.js +14 -0
  37. package/dist/handlers/emit-single.js.map +1 -0
  38. package/dist/handlers/generate-barrel-exports.d.ts +13 -0
  39. package/dist/handlers/generate-barrel-exports.d.ts.map +1 -0
  40. package/dist/handlers/generate-barrel-exports.js +69 -0
  41. package/dist/handlers/generate-barrel-exports.js.map +1 -0
  42. package/dist/handlers/generate-files.d.ts +3 -0
  43. package/dist/handlers/generate-files.d.ts.map +1 -0
  44. package/dist/handlers/generate-files.js +133 -0
  45. package/dist/handlers/generate-files.js.map +1 -0
  46. package/dist/handlers/input-type.d.ts +7 -0
  47. package/dist/handlers/input-type.d.ts.map +1 -0
  48. package/dist/handlers/input-type.js +297 -0
  49. package/dist/handlers/input-type.js.map +1 -0
  50. package/dist/handlers/model-data.d.ts +3 -0
  51. package/dist/handlers/model-data.d.ts.map +1 -0
  52. package/dist/handlers/model-data.js +27 -0
  53. package/dist/handlers/model-data.js.map +1 -0
  54. package/dist/handlers/model-output-type.d.ts +3 -0
  55. package/dist/handlers/model-output-type.d.ts.map +1 -0
  56. package/dist/handlers/model-output-type.js +283 -0
  57. package/dist/handlers/model-output-type.js.map +1 -0
  58. package/dist/handlers/no-atomic-operations.d.ts +3 -0
  59. package/dist/handlers/no-atomic-operations.d.ts.map +1 -0
  60. package/dist/handlers/no-atomic-operations.js +41 -0
  61. package/dist/handlers/no-atomic-operations.js.map +1 -0
  62. package/dist/handlers/output-type.d.ts +3 -0
  63. package/dist/handlers/output-type.d.ts.map +1 -0
  64. package/dist/handlers/output-type.js +179 -0
  65. package/dist/handlers/output-type.js.map +1 -0
  66. package/dist/handlers/patch-type-registry.d.ts +16 -0
  67. package/dist/handlers/patch-type-registry.d.ts.map +1 -0
  68. package/dist/handlers/patch-type-registry.js +47 -0
  69. package/dist/handlers/patch-type-registry.js.map +1 -0
  70. package/dist/handlers/post-process-imports.d.ts +11 -0
  71. package/dist/handlers/post-process-imports.d.ts.map +1 -0
  72. package/dist/handlers/post-process-imports.js +44 -0
  73. package/dist/handlers/post-process-imports.js.map +1 -0
  74. package/dist/handlers/prisma-enum-doc.d.ts +11 -0
  75. package/dist/handlers/prisma-enum-doc.d.ts.map +1 -0
  76. package/dist/handlers/prisma-enum-doc.js +16 -0
  77. package/dist/handlers/prisma-enum-doc.js.map +1 -0
  78. package/dist/handlers/purge-output.d.ts +3 -0
  79. package/dist/handlers/purge-output.d.ts.map +1 -0
  80. package/dist/handlers/purge-output.js +34 -0
  81. package/dist/handlers/purge-output.js.map +1 -0
  82. package/dist/handlers/re-export.d.ts +9 -0
  83. package/dist/handlers/re-export.d.ts.map +1 -0
  84. package/dist/handlers/re-export.js +101 -0
  85. package/dist/handlers/re-export.js.map +1 -0
  86. package/dist/handlers/register-all-types.d.ts +13 -0
  87. package/dist/handlers/register-all-types.d.ts.map +1 -0
  88. package/dist/handlers/register-all-types.js +99 -0
  89. package/dist/handlers/register-all-types.js.map +1 -0
  90. package/dist/handlers/register-enum.d.ts +3 -0
  91. package/dist/handlers/register-enum.d.ts.map +1 -0
  92. package/dist/handlers/register-enum.js +65 -0
  93. package/dist/handlers/register-enum.js.map +1 -0
  94. package/dist/handlers/require-single-fields-in-whereunique-input.d.ts +3 -0
  95. package/dist/handlers/require-single-fields-in-whereunique-input.d.ts.map +1 -0
  96. package/dist/handlers/require-single-fields-in-whereunique-input.js +15 -0
  97. package/dist/handlers/require-single-fields-in-whereunique-input.js.map +1 -0
  98. package/dist/handlers/type-registry.d.ts +14 -0
  99. package/dist/handlers/type-registry.d.ts.map +1 -0
  100. package/dist/handlers/type-registry.js +151 -0
  101. package/dist/handlers/type-registry.js.map +1 -0
  102. package/dist/handlers/warning.d.ts +2 -0
  103. package/dist/handlers/warning.d.ts.map +1 -0
  104. package/dist/handlers/warning.js +14 -0
  105. package/dist/handlers/warning.js.map +1 -0
  106. package/dist/helpers/create-comment.d.ts +3 -0
  107. package/dist/helpers/create-comment.d.ts.map +1 -0
  108. package/dist/helpers/create-comment.js +23 -0
  109. package/dist/helpers/create-comment.js.map +1 -0
  110. package/dist/helpers/create-config.d.ts +51 -0
  111. package/dist/helpers/create-config.d.ts.map +1 -0
  112. package/dist/helpers/create-config.js +165 -0
  113. package/dist/helpers/create-config.js.map +1 -0
  114. package/dist/helpers/create-emit-blocks.d.ts +5 -0
  115. package/dist/helpers/create-emit-blocks.d.ts.map +1 -0
  116. package/dist/helpers/create-emit-blocks.js +37 -0
  117. package/dist/helpers/create-emit-blocks.js.map +1 -0
  118. package/dist/helpers/detect-circular-deps.d.ts +28 -0
  119. package/dist/helpers/detect-circular-deps.d.ts.map +1 -0
  120. package/dist/helpers/detect-circular-deps.js +92 -0
  121. package/dist/helpers/detect-circular-deps.js.map +1 -0
  122. package/dist/helpers/factory-get-source-file.d.ts +13 -0
  123. package/dist/helpers/factory-get-source-file.d.ts.map +1 -0
  124. package/dist/helpers/factory-get-source-file.js +17 -0
  125. package/dist/helpers/factory-get-source-file.js.map +1 -0
  126. package/dist/helpers/file-type-by-location.d.ts +3 -0
  127. package/dist/helpers/file-type-by-location.d.ts.map +1 -0
  128. package/dist/helpers/file-type-by-location.js +19 -0
  129. package/dist/helpers/file-type-by-location.js.map +1 -0
  130. package/dist/helpers/generate-file-name.d.ts +7 -0
  131. package/dist/helpers/generate-file-name.d.ts.map +1 -0
  132. package/dist/helpers/generate-file-name.js +35 -0
  133. package/dist/helpers/generate-file-name.js.map +1 -0
  134. package/dist/helpers/get-enum-name.d.ts +2 -0
  135. package/dist/helpers/get-enum-name.d.ts.map +1 -0
  136. package/dist/helpers/get-enum-name.js +5 -0
  137. package/dist/helpers/get-enum-name.js.map +1 -0
  138. package/dist/helpers/get-graphql-import.d.ts +19 -0
  139. package/dist/helpers/get-graphql-import.d.ts.map +1 -0
  140. package/dist/helpers/get-graphql-import.js +52 -0
  141. package/dist/helpers/get-graphql-import.js.map +1 -0
  142. package/dist/helpers/get-graphql-input-type.d.ts +6 -0
  143. package/dist/helpers/get-graphql-input-type.d.ts.map +1 -0
  144. package/dist/helpers/get-graphql-input-type.js +64 -0
  145. package/dist/helpers/get-graphql-input-type.js.map +1 -0
  146. package/dist/helpers/get-model-name.d.ts +2 -0
  147. package/dist/helpers/get-model-name.d.ts.map +1 -0
  148. package/dist/helpers/get-model-name.js +130 -0
  149. package/dist/helpers/get-model-name.js.map +1 -0
  150. package/dist/helpers/get-output-type-name.d.ts +2 -0
  151. package/dist/helpers/get-output-type-name.d.ts.map +1 -0
  152. package/dist/helpers/get-output-type-name.js +4 -0
  153. package/dist/helpers/get-output-type-name.js.map +1 -0
  154. package/dist/helpers/get-property-type.d.ts +9 -0
  155. package/dist/helpers/get-property-type.d.ts.map +1 -0
  156. package/dist/helpers/get-property-type.js +48 -0
  157. package/dist/helpers/get-property-type.js.map +1 -0
  158. package/dist/helpers/get-where-unique-at-least-keys.d.ts +3 -0
  159. package/dist/helpers/get-where-unique-at-least-keys.d.ts.map +1 -0
  160. package/dist/helpers/get-where-unique-at-least-keys.js +17 -0
  161. package/dist/helpers/get-where-unique-at-least-keys.js.map +1 -0
  162. package/dist/helpers/import-declaration-map.d.ts +19 -0
  163. package/dist/helpers/import-declaration-map.d.ts.map +1 -0
  164. package/dist/helpers/import-declaration-map.js +69 -0
  165. package/dist/helpers/import-declaration-map.js.map +1 -0
  166. package/dist/helpers/is-many-and-return.d.ts +2 -0
  167. package/dist/helpers/is-many-and-return.d.ts.map +1 -0
  168. package/dist/helpers/is-many-and-return.js +9 -0
  169. package/dist/helpers/is-many-and-return.js.map +1 -0
  170. package/dist/helpers/is-where-unique-input-type.d.ts +2 -0
  171. package/dist/helpers/is-where-unique-input-type.d.ts.map +1 -0
  172. package/dist/helpers/is-where-unique-input-type.js +4 -0
  173. package/dist/helpers/is-where-unique-input-type.js.map +1 -0
  174. package/dist/helpers/object-settings.d.ts +39 -0
  175. package/dist/helpers/object-settings.d.ts.map +1 -0
  176. package/dist/helpers/object-settings.js +297 -0
  177. package/dist/helpers/object-settings.js.map +1 -0
  178. package/dist/helpers/pascal-case.d.ts +2 -0
  179. package/dist/helpers/pascal-case.d.ts.map +1 -0
  180. package/dist/helpers/pascal-case.js +5 -0
  181. package/dist/helpers/pascal-case.js.map +1 -0
  182. package/dist/helpers/property-structure.d.ts +13 -0
  183. package/dist/helpers/property-structure.d.ts.map +1 -0
  184. package/dist/helpers/property-structure.js +20 -0
  185. package/dist/helpers/property-structure.js.map +1 -0
  186. package/dist/helpers/relative-path.d.ts +2 -0
  187. package/dist/helpers/relative-path.d.ts.map +1 -0
  188. package/dist/helpers/relative-path.js +20 -0
  189. package/dist/helpers/relative-path.js.map +1 -0
  190. package/dist/helpers/type-safe-assert.d.ts +7 -0
  191. package/dist/helpers/type-safe-assert.d.ts.map +1 -0
  192. package/dist/helpers/type-safe-assert.js +10 -0
  193. package/dist/helpers/type-safe-assert.js.map +1 -0
  194. package/dist/helpers/update-object-property.d.ts +7 -0
  195. package/dist/helpers/update-object-property.d.ts.map +1 -0
  196. package/dist/helpers/update-object-property.js +21 -0
  197. package/dist/helpers/update-object-property.js.map +1 -0
  198. package/dist/index.d.ts +4 -6
  199. package/dist/index.d.ts.map +1 -0
  200. package/dist/index.js +135 -2941
  201. package/dist/index.js.map +1 -1
  202. package/dist/test/test-utils.d.ts +4 -0
  203. package/dist/test/test-utils.d.ts.map +1 -0
  204. package/dist/test/test-utils.js +14 -0
  205. package/dist/test/test-utils.js.map +1 -0
  206. package/dist/types.d.ts +73 -0
  207. package/dist/types.d.ts.map +1 -0
  208. package/dist/types.js +2 -0
  209. package/dist/types.js.map +1 -0
  210. package/package.json +3 -3
package/dist/generate.js CHANGED
@@ -1,2824 +1,212 @@
1
- import { memoize, mapKeys, merge, trim, castArray, uniqWith, isEqual, countBy, startCase, camelCase, keyBy, remove, partition, kebabCase, isObject, omit, cloneDeep } from 'lodash-es';
2
- import { createRequire } from 'module';
3
- import { Project, QuoteKind, StructureKind } from 'ts-morph';
4
- import { ok as ok$1 } from 'assert';
5
- import JSON52 from 'json5';
6
- import pupa from 'pupa';
7
- import getRelativePath from 'get-relative-path';
8
- import outmatch2 from 'outmatch';
9
- import { existsSync, rmdirSync as rmdirSync$1 } from 'fs';
10
- import { unflatten } from 'flat';
11
- import filenamify from 'filenamify';
12
- import pluralize from 'pluralize';
13
-
14
- // src/generate.ts
15
- function ok(value, message) {
16
- ok$1(
17
- value,
18
- message
19
- );
20
- }
21
-
22
- // src/helpers/is-many-and-return.ts
23
- function isManyAndReturnOutputType(name) {
24
- const lowerName = name.toLowerCase();
25
- if ((lowerName.startsWith("createmany") || lowerName.startsWith("updatemany")) && (lowerName.endsWith("andreturnoutputtype") || lowerName.endsWith("andreturn"))) {
26
- return true;
27
- }
28
- return false;
29
- }
30
- function pascalCase(string) {
31
- return startCase(camelCase(string)).replaceAll(" ", "");
32
- }
33
-
34
- // src/handlers/args-type.ts
35
- function argsType(field, args) {
36
- if (["queryRaw", "executeRaw"].includes(field.name)) {
37
- return;
38
- }
39
- if (isManyAndReturnOutputType(field.name)) {
40
- return;
41
- }
42
- const { eventEmitter, getModelName: getModelName2, typeNames } = args;
43
- let className = pascalCase(`${field.name}Args`);
44
- const modelName = getModelName2(className) ?? "";
45
- switch (className) {
46
- case `Aggregate${modelName}Args`: {
47
- className = `${modelName}AggregateArgs`;
48
- break;
49
- }
50
- case `GroupBy${modelName}Args`: {
51
- className = `${modelName}GroupByArgs`;
52
- break;
53
- }
54
- }
55
- const inputType2 = {
56
- constraints: { maxNumFields: null, minNumFields: null },
57
- fields: [...field.args],
58
- name: className
59
- };
60
- if (!field.args.some((x) => x.name === "_count") && [`${modelName}AggregateArgs`, `${modelName}GroupByArgs`].includes(className)) {
61
- const names = ["Count", "Avg", "Sum", "Min", "Max"];
62
- if (`${modelName}GroupByArgs` === inputType2.name) {
63
- const byField = inputType2.fields.find((f) => f.name === "by");
64
- if (byField?.inputTypes) {
65
- byField.inputTypes = byField.inputTypes.filter((it) => it.isList);
66
- }
67
- }
68
- for (const name of names) {
69
- if (!typeNames.has(`${modelName}${name}AggregateInput`)) {
70
- continue;
71
- }
72
- inputType2.fields.push({
73
- inputTypes: [
74
- {
75
- isList: false,
76
- location: "inputObjectTypes",
77
- type: `${modelName}${name}AggregateInput`
78
- }
79
- ],
80
- isNullable: true,
81
- isRequired: false,
82
- name: `_${name.toLowerCase()}`
83
- });
84
- }
85
- }
86
- eventEmitter.emitSync("InputType", {
87
- ...args,
88
- classDecoratorName: "ArgsType",
89
- fileType: "args",
90
- inputType: inputType2
91
- });
92
- }
93
-
94
- // src/event-names.ts
95
- var BeforeGenerateField = "BeforeGenerateField";
96
-
97
- // src/handlers/combine-scalar-filters.ts
98
- function combineScalarFilters(eventEmitter) {
99
- eventEmitter.on("BeforeInputType", beforeInputType);
100
- eventEmitter.on(BeforeGenerateField, beforeGenerateField);
101
- eventEmitter.on("PostBegin", postBegin);
102
- }
103
- function beforeInputType(args) {
104
- const { inputType: inputType2, removeTypes } = args;
105
- if (isContainBogus(inputType2.name) && isScalarFilter(inputType2)) {
106
- removeTypes.add(inputType2.name);
107
- inputType2.name = replaceBogus(inputType2.name);
108
- }
109
- }
110
- function beforeGenerateField(field) {
111
- for (const fieldInput of field.inputTypes) {
112
- if (fieldInput.location !== "inputObjectTypes") {
113
- continue;
114
- }
115
- const fieldInputType = fieldInput.type;
116
- if (isContainBogus(fieldInputType)) {
117
- fieldInput.type = replaceBogus(fieldInputType);
118
- }
119
- }
120
- }
121
- function replaceBogus(name) {
122
- return name.replaceAll(/Nullable|Nested/g, "");
123
- }
124
- function isContainBogus(name) {
125
- return name.startsWith("Nested") || name.includes("Nullable") && name.endsWith("Filter") || name.endsWith("NullableFilter");
126
- }
127
- function isScalarFilter(inputType2) {
128
- if (!inputType2.name.endsWith("Filter")) {
129
- return false;
130
- }
131
- let result = false;
132
- const equals = inputType2.fields.find((f) => f.name === "equals");
133
- if (equals) {
134
- result = equals.inputTypes.every((x) => {
135
- return ["enumTypes", "scalar"].includes(x.location);
136
- });
137
- }
138
- return result;
139
- }
140
- function postBegin(args) {
141
- const { modelNames, schema } = args;
142
- const inputTypes = schema.inputObjectTypes.prisma ?? [];
143
- const enumTypes = schema.enumTypes.model ?? [];
144
- const types = [
145
- "Bool",
146
- "Int",
147
- "String",
148
- "DateTime",
149
- "Decimal",
150
- "Float",
151
- "Json",
152
- "Bytes",
153
- "BigInt"
154
- ];
155
- for (const enumType of enumTypes) {
156
- const { name } = enumType;
157
- types.push(`Enum${name}`);
158
- }
159
- const inputTypeByName = keyBy(inputTypes, (it) => it.name);
160
- const replaceBogusFilters = (filterName, filterNameCandidates) => {
161
- for (const filterNameCandidate of filterNameCandidates) {
162
- const candidate = inputTypeByName[filterNameCandidate];
163
- if (candidate) {
164
- const it = cloneDeep({ ...candidate, name: filterName });
165
- inputTypes.push(it);
166
- inputTypeByName[filterName] = it;
167
- break;
168
- }
169
- }
170
- };
171
- for (const type of types) {
172
- replaceBogusFilters(`${type}Filter`, [
173
- `${type}NullableFilter`,
174
- `Nested${type}NullableFilter`
175
- ]);
176
- replaceBogusFilters(`${type}WithAggregatesFilter`, [
177
- `${type}NullableWithAggregatesFilter`,
178
- `Nested${type}NullableWithAggregatesFilter`
179
- ]);
180
- replaceBogusFilters(`${type}ListFilter`, [
181
- `${type}NullableListFilter`,
182
- `Nested${type}NullableListFilter`
183
- ]);
184
- }
185
- for (const modelName of modelNames) {
186
- replaceBogusFilters(`${modelName}RelationFilter`, [
187
- `${modelName}NullableRelationFilter`
188
- ]);
189
- }
190
- for (const modelName of modelNames) {
191
- replaceBogusFilters(`${modelName}ScalarRelationFilter`, [
192
- `${modelName}NullableScalarRelationFilter`
193
- ]);
194
- }
195
- remove(inputTypes, (it) => {
196
- return isContainBogus(it.name);
197
- });
198
- }
199
-
200
- // src/handlers/create-aggregate-input.ts
201
- function createAggregateInput(args) {
202
- const { eventEmitter, outputType: outputType2 } = args;
203
- const className = `${outputType2.name}Input`;
204
- const inputType2 = {
205
- constraints: { maxNumFields: null, minNumFields: null },
206
- fields: outputType2.fields.map((x) => ({
207
- inputTypes: [
208
- {
209
- isList: false,
210
- location: "scalar",
211
- type: "true"
212
- }
213
- ],
214
- isNullable: x.isNullable ?? true,
215
- isRequired: false,
216
- name: x.name
217
- })),
218
- name: className
219
- };
220
- eventEmitter.emitSync("InputType", {
221
- ...args,
222
- classDecoratorName: "InputType",
223
- fileType: "input",
224
- inputType: inputType2
225
- });
226
- }
227
-
228
- // src/handlers/decimal-helpers.ts
229
- function generateDecimalHelpers(args) {
230
- const { output, project } = args;
231
- const rootDirectory = project.getDirectory(output) ?? project.createDirectory(output);
232
- const sourceFile = rootDirectory.createSourceFile("decimal-helpers.ts", void 0, {
233
- overwrite: true
234
- });
235
- const helpersCode = `/**
236
- * Decimal Helpers for Prisma GraphQL
237
- *
238
- * This module provides utilities for transforming Decimal values
239
- * between GraphQL and Prisma, compatible with Prisma 7+.
240
- *
241
- * These functions replace the prisma-graphql-type-decimal package
242
- * which is incompatible with Prisma 7's new client structure.
243
- */
244
-
245
- import Decimal from 'decimal.js';
246
-
247
- /**
248
- * Reconstruct a Decimal from a serialized object.
249
- * Prisma serializes Decimals as objects with d, e, s properties.
250
- */
251
- function createDecimalFromObject(object: { d: number[]; e: number; s: number }): Decimal {
252
- return Object.create(Decimal.prototype, {
253
- d: { value: object.d },
254
- e: { value: object.e },
255
- s: { value: object.s },
256
- });
257
- }
258
-
259
- /**
260
- * Transform input values to Decimal instances.
261
- * Used as a class-transformer Transform decorator argument.
262
- *
263
- * @param params - The transform parameters from class-transformer
264
- * @returns The transformed Decimal or array of Decimals
265
- */
266
- export function transformToDecimal({ value }: { value: unknown }): Decimal | Decimal[] | null | undefined {
267
- if (value == null) return value as null | undefined;
268
-
269
- if (Array.isArray(value)) {
270
- return value.map((v) => {
271
- if (v instanceof Decimal) return v;
272
- if (typeof v === 'object' && v !== null && 'd' in v && 'e' in v && 's' in v) {
273
- return createDecimalFromObject(v as { d: number[]; e: number; s: number });
274
- }
275
- return new Decimal(v as string | number);
276
- });
277
- }
278
-
279
- if (value instanceof Decimal) return value;
280
- if (typeof value === 'object' && value !== null && 'd' in value && 'e' in value && 's' in value) {
281
- return createDecimalFromObject(value as { d: number[]; e: number; s: number });
282
- }
283
- return new Decimal(value as string | number);
284
- }
285
-
286
- /**
287
- * Re-export Decimal class for convenience
288
- */
289
- export { Decimal };
290
- `;
291
- sourceFile.addStatements(helpersCode);
292
- }
293
- function emitSingle(emitter) {
294
- emitter.on("ClassProperty", classProperty);
295
- }
296
- function classProperty(property, eventArguments) {
297
- const { isList, location, propertyType } = eventArguments;
298
- if (["inputObjectTypes", "outputObjectTypes"].includes(location) && !isList) {
299
- const [safeTypes, instanceofTypes] = partition(
300
- propertyType,
301
- (t) => t === "null" || t.startsWith("Prisma.")
302
- );
303
- const mappedInstanceofTypes = instanceofTypes.map((t) => `InstanceType<typeof ${t}>`);
304
- property.type = [...mappedInstanceofTypes, ...safeTypes].join(" | ");
305
- }
306
- }
307
- var ImportDeclarationMap = class extends Map {
308
- add(name, value, isTypeOnly) {
309
- if (!this.has(name)) {
310
- const structure = typeof value === "string" ? { isTypeOnly, moduleSpecifier: value, namedImports: [{ name }] } : value;
311
- this.set(name, structure);
312
- }
313
- }
314
- /**
315
- * Add a type-only import for ESM circular dependency resolution
316
- */
317
- addType(name, moduleSpecifier) {
318
- const typeOnlyKey = `type:${name}`;
319
- if (!this.has(typeOnlyKey) && !this.has(name)) {
320
- this.set(typeOnlyKey, {
321
- isTypeOnly: true,
322
- moduleSpecifier,
323
- namedImports: [{ name }]
324
- });
325
- }
326
- }
327
- create(args) {
328
- const { defaultImport, from, isTypeOnly, namedImport, namespaceImport } = args;
329
- let { name } = args;
330
- const value = {
331
- defaultImport: void 0,
332
- isTypeOnly,
333
- moduleSpecifier: from,
334
- namedImports: [],
335
- namespaceImport: void 0
336
- };
337
- if (namedImport === true && namespaceImport !== void 0) {
338
- value.namedImports = [{ name: namespaceImport }];
339
- name = namespaceImport;
340
- } else if (defaultImport === void 0) {
341
- if (namespaceImport === void 0) {
342
- value.namedImports = [{ name }];
343
- } else {
344
- value.namespaceImport = namespaceImport;
345
- name = namespaceImport;
346
- }
347
- } else {
348
- value.defaultImport = defaultImport === true ? name : defaultImport;
349
- name = value.defaultImport;
350
- }
351
- const key = isTypeOnly === true ? `type:${name}` : name;
352
- if (this.has(key)) {
353
- return;
354
- }
355
- this.set(key, value);
356
- }
357
- *toStatements() {
358
- const iterator = this.values();
359
- let result = iterator.next();
360
- while (result.value !== void 0) {
361
- yield {
362
- ...result.value,
363
- kind: StructureKind.ImportDeclaration
364
- };
365
- result = iterator.next();
366
- }
367
- }
368
- };
369
-
370
- // src/handlers/generate-files.ts
371
- async function generateFiles(args) {
372
- const { config, eventEmitter, output, project } = args;
373
- if (config.emitSingle) {
374
- const rootDirectory = project.getDirectory(output) ?? project.createDirectory(output);
375
- const sourceFile = rootDirectory.getSourceFile("index.ts") ?? rootDirectory.createSourceFile("index.ts", void 0, { overwrite: true });
376
- const statements = project.getSourceFiles().flatMap((s) => {
377
- if (s === sourceFile) {
378
- return [];
379
- }
380
- const classDeclaration = s.getClass(() => true);
381
- const stmts = s.getStructure().statements;
382
- if (Array.isArray(stmts)) {
383
- for (const statement of stmts) {
384
- if (!(typeof statement === "object" && statement.kind === StructureKind.Class)) {
385
- continue;
386
- }
387
- for (const property of statement.properties ?? []) {
388
- for (const decorator of property.decorators ?? []) {
389
- const fullName = classDeclaration?.getProperty(property.name)?.getDecorator(decorator.name)?.getFullName();
390
- ok(
391
- fullName !== void 0,
392
- `Cannot get full name of decorator of class ${String(statement.name)}`
393
- );
394
- decorator.name = fullName;
395
- }
396
- }
397
- }
398
- }
399
- project.removeSourceFile(s);
400
- return stmts;
401
- });
402
- const imports = new ImportDeclarationMap();
403
- const enums = [];
404
- const classes = [];
405
- for (const statement of statements) {
406
- if (typeof statement === "string") {
407
- if (statement.startsWith("registerEnumType")) {
408
- enums.push(statement);
409
- }
410
- continue;
411
- }
412
- switch (statement.kind) {
413
- case StructureKind.ImportDeclaration: {
414
- if (statement.moduleSpecifier.startsWith("./") || statement.moduleSpecifier.startsWith("..")) {
415
- continue;
416
- }
417
- for (const namedImport of statement.namedImports) {
418
- const name = namedImport.alias ?? namedImport.name;
419
- imports.add(name, statement.moduleSpecifier);
420
- }
421
- if (statement.defaultImport) {
422
- imports.create({
423
- defaultImport: statement.defaultImport,
424
- from: statement.moduleSpecifier,
425
- name: statement.defaultImport
426
- });
427
- }
428
- if (statement.namespaceImport) {
429
- imports.create({
430
- from: statement.moduleSpecifier,
431
- name: statement.namespaceImport,
432
- namespaceImport: statement.namespaceImport
433
- });
434
- }
435
- break;
436
- }
437
- case StructureKind.Enum: {
438
- enums.unshift(statement);
439
- break;
440
- }
441
- case StructureKind.Class: {
442
- classes.push(statement);
443
- break;
444
- }
445
- }
446
- }
447
- for (const customImport of config.customImport) {
448
- imports.create(customImport);
449
- }
450
- sourceFile.set({
451
- kind: StructureKind.SourceFile,
452
- statements: [...imports.toStatements(), ...enums, ...classes]
453
- });
454
- }
455
- const sourceFiles = project.getSourceFiles();
456
- const sourceFileCount = sourceFiles.length;
457
- const globalConsole2 = globalThis.console;
458
- const logMessage = (msg) => {
459
- globalConsole2.log(msg);
460
- };
461
- logMessage(
462
- `nestjs-prisma-graphql: saving ${String(sourceFileCount)} source files to ${output}`
463
- );
464
- if (sourceFileCount === 0) {
465
- throw new Error(
466
- "nestjs-prisma-graphql: project has 0 source files \u2014 nothing to write"
467
- );
468
- }
469
- if (config.emitCompiled) {
470
- project.compilerOptions.set({
471
- declaration: true,
472
- declarationDir: output,
473
- emitDecoratorMetadata: false,
474
- outDir: output,
475
- rootDir: output,
476
- skipLibCheck: true
477
- });
478
- const emitResult = await project.emit();
479
- const errors = emitResult.getDiagnostics().map((d) => String(d.getMessageText()));
480
- if (errors.length > 0) {
481
- eventEmitter.emitSync("Warning", errors);
482
- }
483
- } else {
484
- const BATCH_SIZE = 100;
485
- if (sourceFileCount > BATCH_SIZE) {
486
- logMessage(
487
- `nestjs-prisma-graphql: using batched save for large schema (${String(sourceFileCount)} files)`
488
- );
489
- for (let i = 0; i < sourceFileCount; i += BATCH_SIZE) {
490
- const batch = sourceFiles.slice(i, i + BATCH_SIZE);
491
- logMessage(
492
- `nestjs-prisma-graphql: saving batch ${String(Math.floor(i / BATCH_SIZE) + 1)}/${String(Math.ceil(sourceFileCount / BATCH_SIZE))} (${String(batch.length)} files)`
493
- );
494
- await Promise.all(batch.map(async (sf) => await sf.save()));
495
- }
496
- } else {
497
- await project.save();
498
- }
499
- }
500
- }
501
-
502
- // src/helpers/file-type-by-location.ts
503
- function fileTypeByLocation(fieldLocation) {
504
- switch (fieldLocation) {
505
- case "inputObjectTypes": {
506
- return "input";
507
- }
508
- case "outputObjectTypes": {
509
- return "output";
510
- }
511
- case "enumTypes": {
512
- return "enum";
513
- }
514
- case "fieldRefTypes":
515
- case "scalar":
516
- default: {
517
- return "object";
518
- }
519
- }
520
- }
521
- function relativePath(from, to) {
522
- let fromPath = from;
523
- let toPath = to;
524
- if (!fromPath.startsWith("/")) {
525
- fromPath = `/${fromPath}`;
526
- }
527
- if (!toPath.startsWith("/")) {
528
- toPath = `/${toPath}`;
529
- }
530
- let result = getRelativePath(fromPath, toPath);
531
- if (!result.startsWith(".")) {
532
- result = `./${result}`;
533
- }
534
- if (result.endsWith(".ts")) {
535
- result = result.slice(0, -3);
536
- }
537
- return result;
538
- }
539
-
540
- // src/helpers/get-graphql-import.ts
541
- function getGraphqlImport(args) {
542
- const {
543
- config,
544
- fileType,
545
- getSourceFile,
546
- isId,
547
- location,
548
- noTypeId,
549
- sourceFile,
550
- typeName
551
- } = args;
552
- if (location === "scalar") {
553
- if (isId && !noTypeId) {
554
- return { name: "ID", specifier: "@nestjs/graphql" };
555
- }
556
- const graphqlType = config.graphqlScalars[typeName];
557
- if (graphqlType) {
558
- return { name: graphqlType.name, specifier: graphqlType.specifier };
559
- }
560
- switch (typeName) {
561
- case "Float":
562
- case "Int": {
563
- return { name: typeName, specifier: "@nestjs/graphql" };
564
- }
565
- case "DateTime": {
566
- return { name: "Date", specifier: void 0 };
567
- }
568
- case "true":
569
- case "Boolean": {
570
- return { name: "Boolean", specifier: void 0 };
571
- }
572
- case "Decimal": {
573
- return {
574
- name: "GraphQLDecimal",
575
- specifier: "graphql-scalars"
576
- };
577
- }
578
- case "Json": {
579
- return { name: "GraphQLJSON", specifier: "graphql-type-json" };
580
- }
581
- }
582
- return { name: "String", specifier: void 0 };
583
- }
584
- let sourceFileType = fileTypeByLocation(location);
585
- if (sourceFileType === "output" && fileType === "model") {
586
- sourceFileType = "model";
587
- }
588
- const specifier = relativePath(
589
- sourceFile.getFilePath(),
590
- getSourceFile({
591
- name: typeName,
592
- type: sourceFileType
593
- }).getFilePath()
594
- );
595
- return { name: typeName, specifier };
596
- }
597
- function getGraphqlInputType(inputTypes, pattern) {
598
- let result;
599
- inputTypes = inputTypes.filter((t) => !["null", "Null"].includes(t.type));
600
- inputTypes = uniqWith(inputTypes, isEqual);
601
- if (inputTypes.length === 1) {
602
- return inputTypes[0];
603
- }
604
- const countTypes = countBy(inputTypes, (x) => x.location);
605
- const isOneType = Object.keys(countTypes).length === 1;
606
- if (isOneType) {
607
- result = inputTypes.find((x) => x.isList);
608
- if (result) {
609
- return result;
610
- }
611
- }
612
- if (pattern !== null && pattern !== void 0 && pattern.length > 0) {
613
- if (pattern.startsWith("matcher:") || pattern.startsWith("match:")) {
614
- const { 1: patternValue } = pattern.split(":", 2);
615
- const isMatch = outmatch2(patternValue, { separator: false });
616
- result = inputTypes.find((x) => isMatch(x.type));
617
- if (result !== void 0) {
618
- return result;
619
- }
620
- }
621
- result = inputTypes.find((x) => x.type.includes(pattern));
622
- if (result !== void 0) {
623
- return result;
624
- }
625
- }
626
- result = inputTypes.find((x) => x.location === "inputObjectTypes");
627
- if (result !== void 0) {
628
- return result;
629
- }
630
- if ((countTypes.enumTypes ?? 0) > 0 && (countTypes.scalar ?? 0) > 0 && inputTypes.some((x) => x.type === "Json" && x.location === "scalar")) {
631
- result = inputTypes.find((x) => x.type === "Json" && x.location === "scalar");
632
- if (result !== void 0) {
633
- return result;
634
- }
635
- }
636
- if (((countTypes.scalar ?? 0) >= 1 || (countTypes.enumTypes ?? 0) >= 1) && countTypes.fieldRefTypes === 1) {
637
- result = inputTypes.find(
638
- (x) => (x.location === "scalar" || x.location === "enumTypes") && x.isList
639
- );
640
- if (result !== void 0) {
641
- return result;
642
- }
643
- result = inputTypes.find((x) => x.location === "scalar" || x.location === "enumTypes");
644
- if (result !== void 0) {
645
- return result;
646
- }
647
- }
648
- throw new TypeError(
649
- `Cannot get matching input type from ${inputTypes.length > 0 ? inputTypes.map((x) => x.type).join(", ") : "zero length inputTypes"}`
650
- );
651
- }
652
-
653
- // src/helpers/get-property-type.ts
654
- function getPropertyType(args) {
655
- const { location, type } = args;
656
- switch (type) {
657
- case "Float":
658
- case "Int": {
659
- return ["number"];
660
- }
661
- case "String": {
662
- return ["string"];
663
- }
664
- case "Boolean": {
665
- return ["boolean"];
666
- }
667
- case "DateTime": {
668
- return ["Date", "string"];
669
- }
670
- case "Decimal": {
671
- return ["Prisma.Decimal"];
672
- }
673
- case "Json": {
674
- return ["any"];
675
- }
676
- case "Null": {
677
- return ["null"];
678
- }
679
- case "Bytes": {
680
- return ["Uint8Array"];
681
- }
682
- case "BigInt": {
683
- return ["bigint", "number"];
684
- }
685
- }
686
- if (["inputObjectTypes", "outputObjectTypes"].includes(location)) {
687
- return [type];
688
- }
689
- if (location === "enumTypes") {
690
- const enumType = `\`\${${type}}\``;
691
- return [enumType];
692
- }
693
- if (location === "scalar") {
694
- return [type];
695
- }
696
- return ["unknown"];
697
- }
698
-
699
- // src/helpers/get-where-unique-at-least-keys.ts
700
- function getWhereUniqueAtLeastKeys(model) {
701
- const names = model.fields.filter((field) => field.isUnique || field.isId).map((field) => field.name);
702
- if (model.primaryKey) {
703
- names.push(createFieldName(model.primaryKey));
704
- }
705
- for (const uniqueIndex of model.uniqueIndexes) {
706
- names.push(createFieldName(uniqueIndex));
707
- }
708
- return names;
709
- }
710
- function createFieldName(args) {
711
- const { fields, name } = args;
712
- return name !== null && name !== void 0 && name.length > 0 ? name : fields.join("_");
713
- }
714
-
715
- // src/helpers/is-where-unique-input-type.ts
716
- function isWhereUniqueInputType(name) {
717
- return name.endsWith("WhereUniqueInput");
718
- }
719
- function propertyStructure(args) {
720
- const {
721
- hasExclamationToken,
722
- hasQuestionToken,
723
- isList,
724
- isNullable,
725
- name,
726
- propertyType
727
- } = args;
728
- const typeString = propertyType.map((typeItem) => isList ? `Array<${typeItem}>` : typeItem).join(" | ");
729
- return {
730
- decorators: [],
731
- hasExclamationToken: hasExclamationToken ?? !isNullable,
732
- hasQuestionToken: hasQuestionToken ?? isNullable,
733
- kind: StructureKind.Property,
734
- leadingTrivia: "\n",
735
- name,
736
- type: typeString
737
- };
738
- }
739
-
740
- // src/handlers/input-type.ts
741
- function inputType(args) {
742
- const {
743
- classDecoratorName,
744
- classTransformerTypeModels,
745
- config,
746
- eventEmitter,
747
- fieldSettings,
748
- fileType,
749
- getModelName: getModelName2,
750
- getSourceFile,
751
- inputType: inputTypeArg,
752
- models,
753
- output,
754
- removeTypes,
755
- typeNames
756
- } = args;
757
- typeNames.add(inputTypeArg.name);
758
- const importDeclarations = new ImportDeclarationMap();
759
- const sourceFile = getSourceFile({
760
- name: inputTypeArg.name,
761
- type: fileType
762
- });
763
- const classStructure = {
764
- decorators: [
765
- {
766
- arguments: [],
767
- name: classDecoratorName
768
- }
769
- ],
770
- isExported: true,
771
- kind: StructureKind.Class,
772
- name: inputTypeArg.name,
773
- properties: []
774
- };
775
- const modelName = getModelName2(inputTypeArg.name) ?? "";
776
- const model = models.get(modelName);
777
- const modelFieldSettings = model && fieldSettings.get(model.name);
778
- const moduleSpecifier = "@nestjs/graphql";
779
- const lazyTypes = /* @__PURE__ */ new Set();
780
- importDeclarations.set("Field", {
781
- moduleSpecifier,
782
- namedImports: [{ name: "Field" }]
783
- }).set(classDecoratorName, {
784
- moduleSpecifier,
785
- namedImports: [{ name: classDecoratorName }]
786
- });
787
- if (config.esmCompatible) {
788
- const typeRegistryPath = relativePath(
789
- sourceFile.getFilePath(),
790
- `${output}/type-registry.ts`
791
- );
792
- importDeclarations.add("registerType", typeRegistryPath);
793
- importDeclarations.add("getType", typeRegistryPath);
794
- }
795
- const useInputType = config.useInputType.find(
796
- (x) => inputTypeArg.name.includes(x.typeName)
797
- );
798
- const isWhereUnique = isWhereUniqueInputType(inputTypeArg.name);
799
- for (const field of inputTypeArg.fields) {
800
- field.inputTypes = field.inputTypes.filter((t) => !removeTypes.has(t.type));
801
- eventEmitter.emitSync(BeforeGenerateField, field, args);
802
- const { inputTypes, isRequired, name } = field;
803
- if (inputTypes.length === 0) {
804
- continue;
805
- }
806
- const usePattern = useInputType?.ALL ?? useInputType?.[name];
807
- const graphqlInputType = getGraphqlInputType(inputTypes, usePattern);
808
- const { isList, location, type } = graphqlInputType;
809
- const typeName = type;
810
- const settings = modelFieldSettings?.get(name);
811
- const propertySettings = settings?.getPropertyType({
812
- input: true,
813
- name: inputTypeArg.name
814
- });
815
- const modelField = model?.fields.find((f) => f.name === name);
816
- const isCustomsApplicable = typeName === modelField?.type;
817
- const atLeastKeys = model && getWhereUniqueAtLeastKeys(model);
818
- const whereUniqueInputTypeValue = isWhereUniqueInputType(typeName) && atLeastKeys && `Prisma.AtLeast<${typeName}, ${atLeastKeys.map((n) => `'${n}'`).join(" | ")}>`;
819
- const propertyType = castArray(
820
- propertySettings?.name ?? whereUniqueInputTypeValue ?? getPropertyType({
821
- location,
822
- type: typeName
823
- })
824
- );
825
- const hasExclamationToken = Boolean(
826
- isWhereUnique && config.unsafeCompatibleWhereUniqueInput && atLeastKeys?.includes(name)
827
- );
828
- const property = propertyStructure({
829
- hasExclamationToken: hasExclamationToken || void 0,
830
- hasQuestionToken: hasExclamationToken ? false : void 0,
831
- isList,
832
- isNullable: !isRequired,
833
- name,
834
- propertyType
835
- });
836
- if (classStructure.properties) {
837
- classStructure.properties.push(property);
838
- }
839
- if (propertySettings) {
840
- importDeclarations.create({ ...propertySettings });
841
- } else if (propertyType.some(
842
- (p) => typeof p === "string" && p.includes("Prisma.Decimal")
843
- )) {
844
- importDeclarations.add("Prisma", config.prismaClientImport);
845
- } else if (propertyType.some((p) => typeof p === "string" && p.startsWith("Prisma."))) {
846
- importDeclarations.add("Prisma", config.prismaClientImport);
847
- }
848
- let graphqlType;
849
- let useGetType = false;
850
- const shouldHideField = settings?.shouldHideField({
851
- input: true,
852
- name: inputTypeArg.name
853
- }) ?? config.decorate.some(
854
- (d) => d.name === "HideField" && d.from === moduleSpecifier && d.isMatchField(name) && d.isMatchType(inputTypeArg.name)
855
- );
856
- const fieldType = settings?.getFieldType({
857
- input: true,
858
- name: inputTypeArg.name
859
- });
860
- if (fieldType && isCustomsApplicable && !shouldHideField) {
861
- graphqlType = fieldType.name;
862
- importDeclarations.create({ ...fieldType });
863
- } else {
864
- const graphqlImport = getGraphqlImport({
1
+ import { mapKeys } from 'lodash-es';
2
+ import { createRequire } from 'node:module';
3
+ import { Project, QuoteKind } from 'ts-morph';
4
+ import { ok } from './helpers/type-safe-assert.js';
5
+ const createRequireTyped = createRequire;
6
+ // ESLint doesn't understand import.meta.url type - cast to string explicitly
7
+ const requireCjs = createRequireTyped(String(import.meta.url));
8
+ const AwaitEventEmitter = requireCjs('await-event-emitter');
9
+ const AwaitEventEmitterClass = AwaitEventEmitter.default;
10
+ import { argsType } from './handlers/args-type.js';
11
+ import { combineScalarFilters } from './handlers/combine-scalar-filters.js';
12
+ import { createAggregateInput } from './handlers/create-aggregate-input.js';
13
+ import { generateDecimalHelpers } from './handlers/decimal-helpers.js';
14
+ import { emitSingle } from './handlers/emit-single.js';
15
+ import { generateBarrelExports } from './handlers/generate-barrel-exports.js';
16
+ import { generateFiles } from './handlers/generate-files.js';
17
+ import { inputType } from './handlers/input-type.js';
18
+ import { modelData } from './handlers/model-data.js';
19
+ import { modelOutputType } from './handlers/model-output-type.js';
20
+ import { noAtomicOperations } from './handlers/no-atomic-operations.js';
21
+ import { outputType } from './handlers/output-type.js';
22
+ import { patchTypeRegistry } from './handlers/patch-type-registry.js';
23
+ import { postProcessImports } from './handlers/post-process-imports.js';
24
+ import { purgeOutput } from './handlers/purge-output.js';
25
+ import { ReExport, reExport } from './handlers/re-export.js';
26
+ import { generateRegisterAllTypes } from './handlers/register-all-types.js';
27
+ import { registerEnum } from './handlers/register-enum.js';
28
+ import { requireSingleFieldsInWhereUniqueInput } from './handlers/require-single-fields-in-whereunique-input.js';
29
+ import { generateTypeRegistry } from './handlers/type-registry.js';
30
+ import { warning } from './handlers/warning.js';
31
+ import { createConfig } from './helpers/create-config.js';
32
+ import { buildDependencyGraph, detectCircularDependencies, } from './helpers/detect-circular-deps.js';
33
+ import { factoryGetSourceFile } from './helpers/factory-get-source-file.js';
34
+ import { createGetModelName } from './helpers/get-model-name.js';
35
+ export async function generate(args) {
36
+ const { connectCallback, dmmf, generator, skipAddOutputSourceFiles } = args;
37
+ const generatorOutputValue = generator.output?.value ?? '';
38
+ ok(generatorOutputValue !== '', 'Missing generator configuration: output');
39
+ const config = createConfig(generator.config);
40
+ const eventEmitter = new AwaitEventEmitterClass();
41
+ eventEmitter.on('Warning', warning);
42
+ if (config.emitBlocks.models) {
43
+ eventEmitter.on('Model', modelData);
44
+ }
45
+ if (config.emitBlocks.prismaEnums || config.emitBlocks.schemaEnums) {
46
+ eventEmitter.on('EnumType', registerEnum);
47
+ }
48
+ if (config.emitBlocks.outputs ||
49
+ (config.emitBlocks.models && !config.omitModelsCount)) {
50
+ eventEmitter.on('OutputType', outputType);
51
+ }
52
+ if (config.emitBlocks.models) {
53
+ eventEmitter.on('ModelOutputType', modelOutputType);
54
+ }
55
+ if (config.emitBlocks.outputs) {
56
+ eventEmitter.on('AggregateOutput', createAggregateInput);
57
+ }
58
+ if (config.emitBlocks.inputs) {
59
+ eventEmitter.on('InputType', inputType);
60
+ }
61
+ if (config.emitBlocks.args) {
62
+ eventEmitter.on('ArgsType', argsType);
63
+ }
64
+ eventEmitter.on('GenerateFiles', generateFiles);
65
+ for (const message of config.$warnings) {
66
+ eventEmitter.emitSync('Warning', message);
67
+ }
68
+ const project = new Project({
69
+ manipulationSettings: {
70
+ quoteKind: QuoteKind.Single,
71
+ },
72
+ skipAddingFilesFromTsConfig: true,
73
+ skipLoadingLibFiles: !config.emitCompiled,
74
+ tsConfigFilePath: config.tsConfigFilePath,
75
+ });
76
+ if (skipAddOutputSourceFiles !== true) {
77
+ project.addSourceFilesAtPaths([
78
+ `${generatorOutputValue}/**/*.ts`,
79
+ `!${generatorOutputValue}/**/*.d.ts`,
80
+ ]);
81
+ }
82
+ if (config.combineScalarFilters) {
83
+ combineScalarFilters(eventEmitter);
84
+ }
85
+ if (config.noAtomicOperations) {
86
+ noAtomicOperations(eventEmitter);
87
+ }
88
+ if (config.reExport !== ReExport.None) {
89
+ reExport(eventEmitter);
90
+ }
91
+ if (config.emitSingle) {
92
+ emitSingle(eventEmitter);
93
+ }
94
+ if (config.purgeOutput) {
95
+ purgeOutput(eventEmitter);
96
+ }
97
+ if (config.requireSingleFieldsInWhereUniqueInput) {
98
+ requireSingleFieldsInWhereUniqueInput(eventEmitter);
99
+ }
100
+ const models = new Map();
101
+ const modelNames = [];
102
+ const modelFields = new Map();
103
+ const fieldSettings = new Map();
104
+ const getModelName = createGetModelName(modelNames);
105
+ const getSourceFile = factoryGetSourceFile({
106
+ eventEmitter,
107
+ getModelName,
108
+ output: generatorOutputValue,
109
+ outputFilePattern: config.outputFilePattern,
110
+ project,
111
+ });
112
+ const { datamodel, schema } = JSON.parse(JSON.stringify(dmmf));
113
+ const removeTypes = new Set();
114
+ // Build circular dependency detection for ESM compatibility
115
+ const datamodelTypes = datamodel.types ?? [];
116
+ const allModels = [...datamodel.models, ...datamodelTypes];
117
+ const dependencyGraph = buildDependencyGraph(allModels);
118
+ const circularDependencies = detectCircularDependencies(dependencyGraph);
119
+ const eventArguments = {
120
+ circularDependencies,
121
+ classTransformerTypeModels: new Set(),
865
122
  config,
123
+ enums: mapKeys(datamodel.enums, x => x.name),
124
+ eventEmitter,
125
+ fieldSettings,
126
+ getModelName,
866
127
  getSourceFile,
867
- location,
868
- sourceFile,
869
- typeName
870
- });
871
- graphqlType = graphqlImport.name;
872
- if (location === "enumTypes") {
873
- const parts = String(propertyType[0]).split(" ");
874
- parts.at(-1);
875
- }
876
- const shouldUseLazyType = config.esmCompatible && location === "inputObjectTypes";
877
- if (graphqlImport.name === inputTypeArg.name && shouldUseLazyType) {
878
- lazyTypes.add(graphqlImport.name);
879
- useGetType = true;
880
- } else if (graphqlImport.specifier !== null && graphqlImport.specifier !== void 0 && !importDeclarations.has(graphqlImport.name) && graphqlImport.name !== inputTypeArg.name) {
881
- if (shouldUseLazyType) {
882
- importDeclarations.addType(graphqlImport.name, graphqlImport.specifier);
883
- lazyTypes.add(graphqlImport.name);
884
- } else {
885
- importDeclarations.set(graphqlImport.name, {
886
- moduleSpecifier: graphqlImport.specifier,
887
- namedImports: [{ name: graphqlImport.name }]
888
- });
889
- }
890
- }
891
- if (lazyTypes.has(graphqlImport.name)) {
892
- useGetType = true;
893
- }
894
- }
895
- ok(
896
- property.decorators !== void 0 && property.decorators !== null,
897
- "property.decorators is undefined"
898
- );
899
- if (shouldHideField) {
900
- importDeclarations.add("HideField", moduleSpecifier);
901
- property.decorators.push({ arguments: [], name: "HideField" });
902
- } else {
903
- let typeExpression;
904
- if (useGetType) {
905
- typeExpression = isList ? `() => [getType('${graphqlType}')]` : `() => getType('${graphqlType}')`;
906
- } else {
907
- typeExpression = isList ? `() => [${graphqlType}]` : `() => ${graphqlType}`;
908
- }
909
- property.decorators.push({
910
- arguments: [
911
- typeExpression,
912
- JSON52.stringify({
913
- ...settings?.fieldArguments(),
914
- nullable: !isRequired
915
- })
916
- ],
917
- name: "Field"
918
- });
919
- if (graphqlType === "GraphQLDecimal") {
920
- const decimalHelpersPath = relativePath(
921
- sourceFile.getFilePath(),
922
- `${output}/decimal-helpers.ts`
923
- );
924
- importDeclarations.add("transformToDecimal", decimalHelpersPath);
925
- importDeclarations.add("Transform", "class-transformer");
926
- importDeclarations.add("Type", "class-transformer");
927
- property.decorators.push(
928
- {
929
- arguments: ["() => Object"],
930
- name: "Type"
931
- },
932
- {
933
- arguments: ["transformToDecimal"],
934
- name: "Transform"
935
- }
936
- );
937
- } else if (location === "inputObjectTypes" && (modelField?.type === "Decimal" || [
938
- "connect",
939
- "connectOrCreate",
940
- "create",
941
- "createMany",
942
- "data",
943
- "delete",
944
- "deleteMany",
945
- "disconnect",
946
- "set",
947
- "update",
948
- "updateMany",
949
- "upsert",
950
- "where"
951
- ].includes(name) || classTransformerTypeModels.has(getModelName2(graphqlType) ?? "") || modelField?.kind === "object" && models.get(modelField.type)?.fields.some(
952
- (f) => f.kind === "object" && classTransformerTypeModels.has(f.type)
953
- ) === true)) {
954
- importDeclarations.add("Type", "class-transformer");
955
- if (useGetType) {
956
- property.decorators.push({
957
- arguments: [`getType('${graphqlType}')`],
958
- name: "Type"
959
- });
960
- } else {
961
- property.decorators.push({ arguments: [`() => ${graphqlType}`], name: "Type" });
962
- }
963
- }
964
- if (isCustomsApplicable) {
965
- for (const options of settings ?? []) {
966
- if ((options.kind === "Decorator" && options.input && options.match?.(name)) ?? true) {
967
- property.decorators.push({
968
- arguments: options.arguments,
969
- name: options.name
970
- });
971
- ok(
972
- options.from !== void 0 && options.from !== null && options.from !== "",
973
- "Missed 'from' part in configuration or field setting"
974
- );
975
- importDeclarations.create(options);
976
- }
977
- }
978
- }
979
- for (const decorate of config.decorate) {
980
- if (decorate.isMatchField(name) && decorate.isMatchType(inputTypeArg.name)) {
981
- property.decorators.push({
982
- arguments: decorate.arguments?.map((x) => pupa(x, { propertyType })),
983
- name: decorate.name
984
- });
985
- importDeclarations.create(decorate);
986
- }
987
- }
988
- }
989
- eventEmitter.emitSync("ClassProperty", property, {
990
- isList,
991
- location,
992
- propertyType
993
- });
994
- }
995
- const statements = [
996
- ...importDeclarations.toStatements(),
997
- classStructure
998
- ];
999
- if (config.esmCompatible) {
1000
- statements.push(`
1001
- registerType('${inputTypeArg.name}', ${inputTypeArg.name});`);
1002
- }
1003
- sourceFile.set({
1004
- statements
1005
- });
1006
- }
1007
- var ObjectSettings = class extends Array {
1008
- shouldHideField({
1009
- input = false,
1010
- name,
1011
- output = false
1012
- }) {
1013
- const hideField = this.find((s) => s.name === "HideField");
1014
- return Boolean(
1015
- hideField?.input && input || hideField?.output && output || hideField?.match?.(name)
1016
- );
1017
- }
1018
- getFieldType({
1019
- input,
1020
- name,
1021
- output
1022
- }) {
1023
- const fieldType = this.find((s) => s.kind === "FieldType");
1024
- if (!fieldType) {
1025
- return void 0;
1026
- }
1027
- if (fieldType.match) {
1028
- return fieldType.match(name) ? fieldType : void 0;
1029
- }
1030
- if (input && !fieldType.input) {
1031
- return void 0;
1032
- }
1033
- if (output && !fieldType.output) {
1034
- return void 0;
1035
- }
1036
- return fieldType;
1037
- }
1038
- getPropertyType({
1039
- input,
1040
- name,
1041
- output
1042
- }) {
1043
- const propertyType = this.find((s) => s.kind === "PropertyType");
1044
- if (!propertyType) {
1045
- return void 0;
1046
- }
1047
- if (propertyType.match) {
1048
- return propertyType.match(name) ? propertyType : void 0;
1049
- }
1050
- if (input && !propertyType.input) {
1051
- return void 0;
1052
- }
1053
- if (output && !propertyType.output) {
1054
- return void 0;
1055
- }
1056
- return propertyType;
1057
- }
1058
- getObjectTypeArguments(options) {
1059
- const objectTypeOptions = merge({}, options);
1060
- const resultArguments = [objectTypeOptions];
1061
- const objectType = this.find((s) => s.kind === "ObjectType");
1062
- if (objectType && isObject(objectType.arguments)) {
1063
- const { name } = objectType.arguments;
1064
- merge(objectTypeOptions, omit(objectType.arguments, "name"));
1065
- if (name !== null && name !== void 0 && name !== "") {
1066
- resultArguments.unshift(name);
1067
- }
1068
- }
1069
- return resultArguments.map((x) => JSON52.stringify(x));
1070
- }
1071
- fieldArguments() {
1072
- const fieldItem = this.find((item) => item.kind === "Field");
1073
- if (fieldItem) {
1074
- return fieldItem.arguments;
1075
- }
1076
- return void 0;
1077
- }
1078
- };
1079
- function createObjectSettings(args) {
1080
- const { config, text } = args;
1081
- const result = new ObjectSettings();
1082
- const textLines = text.split("\n");
1083
- const documentationLines = [];
1084
- let fieldElement = result.find((item) => item.kind === "Field");
1085
- if (!fieldElement) {
1086
- const newFieldElement = {
1087
- arguments: {},
1088
- from: "",
1089
- input: false,
1090
- kind: "Field",
1091
- model: false,
1092
- name: "",
1093
- output: false
1094
- };
1095
- fieldElement = newFieldElement;
1096
- }
1097
- for (const line of textLines) {
1098
- const match = /^@(?<name>\w+(\.(\w+))?)\((?<args>.*)\)/.exec(line);
1099
- const { documentLine, element } = createSettingElement({
1100
- config,
1101
- fieldElement,
1102
- line,
1103
- match
1104
- });
1105
- if (element) {
1106
- result.push(element);
1107
- }
1108
- if (documentLine) {
1109
- documentationLines.push(line);
1110
- }
1111
- }
1112
- return {
1113
- documentation: documentationLines.filter(Boolean).join("\n") || void 0,
1114
- settings: result
1115
- };
1116
- }
1117
- function createSettingElement({
1118
- config,
1119
- fieldElement,
1120
- line,
1121
- match
1122
- }) {
1123
- const result = {
1124
- documentLine: "",
1125
- element: void 0
1126
- };
1127
- if (line.startsWith("@deprecated")) {
1128
- const DEPRECATED_PREFIX_LENGTH = 11;
1129
- const updatedFieldElement = {
1130
- ...fieldElement,
1131
- arguments: {
1132
- ...fieldElement.arguments,
1133
- deprecationReason: trim(line.slice(DEPRECATED_PREFIX_LENGTH))
1134
- }
1135
- };
1136
- result.element = updatedFieldElement;
1137
- return result;
1138
- }
1139
- if (line.startsWith("@complexity")) {
1140
- const COMPLEXITY_PREFIX_LENGTH = 11;
1141
- const MIN_COMPLEXITY = 1;
1142
- let n = Number.parseInt(trim(line.slice(COMPLEXITY_PREFIX_LENGTH)), 10);
1143
- if (Number.isNaN(n) || n < MIN_COMPLEXITY) {
1144
- n = MIN_COMPLEXITY;
1145
- }
1146
- const updatedFieldElement = {
1147
- ...fieldElement,
1148
- arguments: {
1149
- ...fieldElement.arguments,
1150
- complexity: n
1151
- }
1152
- };
1153
- result.element = updatedFieldElement;
1154
- return result;
1155
- }
1156
- const name = match?.groups?.name;
1157
- if (!(match && name !== void 0 && name !== "")) {
1158
- result.documentLine = line;
1159
- return result;
1160
- }
1161
- const element = {
1162
- arguments: [],
1163
- from: "",
1164
- input: false,
1165
- kind: "Decorator",
1166
- model: false,
1167
- name: "",
1168
- output: false
1169
- };
1170
- result.element = element;
1171
- if (name === "TypeGraphQL.omit" || name === "HideField") {
1172
- Object.assign(element, hideFieldDecorator(match));
1173
- return result;
1174
- }
1175
- if (["FieldType", "PropertyType"].includes(name) && match.groups?.args !== void 0 && match.groups.args !== "") {
1176
- const options2 = customType(match.groups.args);
1177
- const namespaceConfig2 = options2.namespace !== void 0 && options2.namespace !== "" ? config.fields[options2.namespace] : void 0;
1178
- merge(element, namespaceConfig2, options2, {
1179
- kind: name
1180
- });
1181
- return result;
1182
- }
1183
- if (name === "ObjectType" && match.groups?.args !== void 0 && match.groups.args !== "") {
1184
- element.kind = "ObjectType";
1185
- const options2 = customType(match.groups.args);
1186
- if (typeof options2[0] === "string" && options2[0] !== "") {
1187
- options2.name = options2[0];
1188
- }
1189
- if (isObject(options2[1])) {
1190
- merge(options2, options2[1]);
1191
- }
1192
- element.arguments = {
1193
- isAbstract: options2.isAbstract,
1194
- name: options2.name
128
+ modelFields,
129
+ modelNames,
130
+ models,
131
+ output: generatorOutputValue,
132
+ project,
133
+ removeTypes,
134
+ schema,
135
+ typeNames: new Set(),
1195
136
  };
1196
- return result;
1197
- }
1198
- if (name === "Directive" && match.groups?.args !== void 0 && match.groups.args !== "") {
1199
- const options2 = customType(match.groups.args);
1200
- merge(element, { from: "@nestjs/graphql", model: true }, options2, {
1201
- arguments: Array.isArray(options2.arguments) ? options2.arguments.map((s) => JSON52.stringify(s)) : options2.arguments,
1202
- kind: "Decorator",
1203
- name,
1204
- namespace: false
1205
- });
1206
- return result;
1207
- }
1208
- const namespace = getNamespace(name);
1209
- element.namespaceImport = namespace;
1210
- const args = match.groups?.args ?? "";
1211
- const options = {
1212
- arguments: args.split(",").map((s) => trim(s)).filter(Boolean),
1213
- name
1214
- };
1215
- const namespaceConfig = namespace !== void 0 && namespace !== "" ? config.fields[namespace] : void 0;
1216
- merge(element, namespaceConfig, options);
1217
- return result;
1218
- }
1219
- function customType(args) {
1220
- const result = {};
1221
- let options = parseArgs(args);
1222
- if (typeof options === "string") {
1223
- options = { name: options };
1224
- }
1225
- Object.assign(result, options);
1226
- const namespace = getNamespace(options.name);
1227
- result.namespace = namespace;
1228
- const optionsWithName = options;
1229
- if (optionsWithName.name !== void 0 && optionsWithName.name !== "" && optionsWithName.name.includes(".")) {
1230
- result.namespaceImport = namespace;
1231
- }
1232
- if (typeof options.match === "string" || Array.isArray(options.match)) {
1233
- result.match = outmatch2(options.match, { separator: false });
1234
- }
1235
- return result;
1236
- }
1237
- function hideFieldDecorator(match) {
1238
- const result = {
1239
- arguments: [],
1240
- defaultImport: void 0,
1241
- from: "@nestjs/graphql",
1242
- match: void 0,
1243
- name: "HideField",
1244
- namespaceImport: void 0
1245
- };
1246
- const args = match.groups?.args;
1247
- if (args === void 0 || args === "") {
1248
- result.output = true;
1249
- return result;
1250
- }
1251
- if (args.includes("{") && args.includes("}")) {
1252
- const options = parseArgs(args);
1253
- result.output = Boolean(options.output);
1254
- result.input = Boolean(options.input);
1255
- if (typeof options.match === "string" || Array.isArray(options.match)) {
1256
- result.match = outmatch2(options.match, { separator: false });
1257
- }
1258
- } else {
1259
- if (/output:\s*true/.test(args)) {
1260
- result.output = true;
1261
- }
1262
- if (/input:\s*true/.test(args)) {
1263
- result.input = true;
1264
- }
1265
- }
1266
- return result;
1267
- }
1268
- function parseArgs(string) {
1269
- try {
1270
- return JSON52.parse(string);
1271
- } catch {
1272
- try {
1273
- return JSON52.parse(`[${string}]`);
1274
- } catch {
1275
- throw new Error(`Failed to parse: ${string}`);
1276
- }
1277
- }
1278
- }
1279
- function getNamespace(name) {
1280
- if (name === void 0 || name === null) {
1281
- return void 0;
1282
- }
1283
- if (typeof name !== "string") {
1284
- return void 0;
1285
- }
1286
- let result = name;
1287
- if (result === "") {
1288
- return void 0;
1289
- }
1290
- if (result.includes(".")) {
1291
- const parts = result.split(".");
1292
- result = parts[0] ?? "";
1293
- }
1294
- if (result === "") {
1295
- return void 0;
1296
- }
1297
- return result;
1298
- }
1299
-
1300
- // src/handlers/model-data.ts
1301
- function modelData(model, args) {
1302
- const {
1303
- classTransformerTypeModels,
1304
- config,
1305
- fieldSettings,
1306
- modelFields,
1307
- modelNames,
1308
- models
1309
- } = args;
1310
- modelNames.push(model.name);
1311
- models.set(model.name, model);
1312
- const modelFieldsValue = /* @__PURE__ */ new Map();
1313
- modelFields.set(model.name, modelFieldsValue);
1314
- const fieldSettingsValue = /* @__PURE__ */ new Map();
1315
- fieldSettings.set(model.name, fieldSettingsValue);
1316
- for (const field of model.fields) {
1317
- if (field.documentation !== null && field.documentation !== void 0 && field.documentation.length > 0) {
1318
- const { documentation, settings } = createObjectSettings({
1319
- config,
1320
- text: field.documentation
1321
- });
1322
- field.documentation = documentation;
1323
- fieldSettingsValue.set(field.name, settings);
1324
- }
1325
- modelFieldsValue.set(field.name, field);
1326
- }
1327
- if (model.fields.some((field) => field.type === "Decimal")) {
1328
- classTransformerTypeModels.add(model.name);
1329
- }
1330
- }
1331
-
1332
- // src/helpers/create-comment.ts
1333
- function createComment(documentation, settings) {
1334
- const documentationLines = documentation.split("\n");
1335
- const commentLines = ["/**"];
1336
- for (const line of documentationLines) {
1337
- commentLines.push(` * ${line}`);
1338
- }
1339
- const fieldArgs = settings?.fieldArguments();
1340
- let deprecationReason;
1341
- if (fieldArgs === void 0) {
1342
- deprecationReason = void 0;
1343
- } else {
1344
- deprecationReason = fieldArgs.deprecationReason;
1345
- }
1346
- if (deprecationReason !== void 0 && deprecationReason !== null && deprecationReason.length > 0) {
1347
- commentLines.push(` * @deprecated ${deprecationReason}`);
1348
- }
1349
- commentLines.push(" */\n");
1350
- return commentLines.join("\n");
1351
- }
1352
-
1353
- // src/helpers/detect-circular-deps.ts
1354
- function buildDependencyGraph(models) {
1355
- const graph = /* @__PURE__ */ new Map();
1356
- for (const model of models) {
1357
- graph.set(model.name, /* @__PURE__ */ new Set());
1358
- }
1359
- for (const model of models) {
1360
- const dependencies = graph.get(model.name);
1361
- if (!dependencies) {
1362
- continue;
1363
- }
1364
- for (const field of model.fields) {
1365
- if (field.kind === "object" && field.type !== model.name) {
1366
- if (graph.has(field.type)) {
1367
- dependencies.add(field.type);
1368
- }
1369
- }
1370
- }
1371
- }
1372
- return graph;
1373
- }
1374
- function detectCircularDependencies(graph) {
1375
- const circularPairs = /* @__PURE__ */ new Set();
1376
- const visited = /* @__PURE__ */ new Set();
1377
- const recursionStack = /* @__PURE__ */ new Set();
1378
- const path = [];
1379
- function dfs(node) {
1380
- visited.add(node);
1381
- recursionStack.add(node);
1382
- path.push(node);
1383
- const dependencies = graph.get(node) ?? /* @__PURE__ */ new Set();
1384
- for (const dep of dependencies) {
1385
- if (!visited.has(dep)) {
1386
- dfs(dep);
1387
- } else if (recursionStack.has(dep)) {
1388
- const cycleStartIndex = path.indexOf(dep);
1389
- if (cycleStartIndex !== -1) {
1390
- const cyclePath = path.slice(cycleStartIndex);
1391
- for (let i = 0; i < cyclePath.length; i++) {
1392
- const a = cyclePath[i];
1393
- const b = cyclePath[(i + 1) % cyclePath.length];
1394
- const pair = a < b ? `${a}:${b}` : `${b}:${a}`;
1395
- circularPairs.add(pair);
1396
- }
1397
- }
1398
- }
1399
- }
1400
- path.pop();
1401
- recursionStack.delete(node);
1402
- }
1403
- for (const node of graph.keys()) {
1404
- if (!visited.has(node)) {
1405
- dfs(node);
1406
- }
1407
- }
1408
- return circularPairs;
1409
- }
1410
- function hasCircularDependency(circularDeps, modelA, modelB) {
1411
- const pair = modelA < modelB ? `${modelA}:${modelB}` : `${modelB}:${modelA}`;
1412
- return circularDeps.has(pair);
1413
- }
1414
-
1415
- // src/helpers/get-output-type-name.ts
1416
- function getOutputTypeName(name) {
1417
- return name.replace(/(?:OutputType|Output)$/, "");
1418
- }
1419
-
1420
- // src/handlers/model-output-type.ts
1421
- var nestjsGraphql = "@nestjs/graphql";
1422
- function modelOutputType(outputType2, args) {
1423
- const {
1424
- circularDependencies,
1425
- config,
1426
- eventEmitter,
1427
- fieldSettings,
1428
- getSourceFile,
1429
- modelFields,
1430
- models,
1431
- output
1432
- } = args;
1433
- if (isManyAndReturnOutputType(outputType2.name)) {
1434
- return;
1435
- }
1436
- const model = models.get(outputType2.name);
1437
- ok(model, `Cannot find model by name ${outputType2.name}`);
1438
- const sourceFile = getSourceFile({
1439
- name: outputType2.name,
1440
- type: "model"
1441
- });
1442
- const sourceFileStructure = sourceFile.getStructure();
1443
- const exportDeclaration = getExportDeclaration(
1444
- model.name,
1445
- sourceFileStructure.statements
1446
- );
1447
- const importDeclarations = new ImportDeclarationMap();
1448
- const classStructure = {
1449
- decorators: [
1450
- {
1451
- arguments: [],
1452
- name: "ObjectType"
1453
- }
1454
- ],
1455
- isExported: true,
1456
- kind: StructureKind.Class,
1457
- name: outputType2.name,
1458
- properties: []
1459
- };
1460
- sourceFileStructure.statements.push(classStructure);
1461
- ok(classStructure.decorators, "classStructure.decorators is undefined");
1462
- const decorator = classStructure.decorators.find((d) => d.name === "ObjectType");
1463
- ok(decorator, "ObjectType decorator not found");
1464
- let modelSettings;
1465
- if (model.documentation !== null && model.documentation !== void 0 && model.documentation.length > 0) {
1466
- const objectTypeOptions = {};
1467
- const { documentation, settings } = createObjectSettings({
1468
- config,
1469
- text: model.documentation
1470
- });
1471
- if (documentation !== void 0 && documentation.length > 0) {
1472
- classStructure.leadingTrivia ??= createComment(documentation);
1473
- objectTypeOptions.description = documentation;
1474
- }
1475
- decorator.arguments = settings.getObjectTypeArguments(objectTypeOptions);
1476
- modelSettings = settings;
1477
- }
1478
- importDeclarations.add("Field", nestjsGraphql);
1479
- importDeclarations.add("ObjectType", nestjsGraphql);
1480
- const lazyTypes = /* @__PURE__ */ new Set();
1481
- if (config.esmCompatible) {
1482
- const typeRegistryPath = relativePath(
1483
- sourceFile.getFilePath(),
1484
- `${output}/type-registry.ts`
1485
- );
1486
- importDeclarations.add("registerType", typeRegistryPath);
1487
- importDeclarations.add("getType", typeRegistryPath);
1488
- }
1489
- for (const field of outputType2.fields) {
1490
- if (config.omitModelsCount && field.name === "_count") {
1491
- continue;
1492
- }
1493
- let fileType = "model";
1494
- const { isList, location, namespace, type } = field.outputType;
1495
- let outputTypeName = type;
1496
- if (namespace !== "model") {
1497
- fileType = "output";
1498
- outputTypeName = getOutputTypeName(outputTypeName);
1499
- }
1500
- const modelField = modelFields.get(model.name)?.get(field.name);
1501
- const settings = fieldSettings.get(model.name)?.get(field.name);
1502
- const fieldType = settings?.getFieldType({
1503
- name: outputType2.name,
1504
- output: true
1505
- });
1506
- const propertySettings = settings?.getPropertyType({
1507
- name: outputType2.name,
1508
- output: true
1509
- });
1510
- const propertyType = castArray(
1511
- propertySettings?.name ?? getPropertyType({
1512
- location,
1513
- type: outputTypeName
1514
- })
1515
- );
1516
- propertyType.splice(1, propertyType.length);
1517
- if (field.isNullable === true && !isList) {
1518
- propertyType.push("null");
1519
- }
1520
- let graphqlType;
1521
- let useGetType = false;
1522
- if (fieldType === void 0) {
1523
- const graphqlImport = getGraphqlImport({
1524
- config,
1525
- fileType,
1526
- getSourceFile,
1527
- isId: modelField?.isId,
1528
- location,
1529
- noTypeId: config.noTypeId,
1530
- sourceFile,
1531
- typeName: outputTypeName
1532
- });
1533
- graphqlType = graphqlImport.name;
1534
- if (graphqlImport.name !== outputType2.name && graphqlImport.specifier !== null && graphqlImport.specifier !== void 0 && graphqlImport.specifier.length > 0) {
1535
- const isCircular = config.esmCompatible && location === "outputObjectTypes" && namespace === "model" && hasCircularDependency(circularDependencies, outputType2.name, outputTypeName);
1536
- if (isCircular) {
1537
- importDeclarations.add(graphqlImport.name, graphqlImport.specifier);
1538
- lazyTypes.add(graphqlImport.name);
1539
- useGetType = true;
1540
- } else {
1541
- importDeclarations.add(graphqlImport.name, graphqlImport.specifier);
1542
- }
1543
- }
1544
- } else {
1545
- graphqlType = fieldType.name;
1546
- importDeclarations.create({ ...fieldType });
1547
- }
1548
- const property = propertyStructure({
1549
- hasExclamationToken: true,
1550
- hasQuestionToken: location === "outputObjectTypes",
1551
- isList,
1552
- isNullable: field.isNullable,
1553
- name: field.name,
1554
- propertyType
1555
- });
1556
- if (typeof property.leadingTrivia === "string" && modelField?.documentation !== null && modelField?.documentation !== void 0 && modelField.documentation.length > 0) {
1557
- property.leadingTrivia += createComment(modelField.documentation, settings);
1558
- }
1559
- if (classStructure.properties !== void 0) {
1560
- classStructure.properties.push(property);
1561
- }
1562
- if (propertySettings !== void 0) {
1563
- importDeclarations.create({ ...propertySettings });
1564
- } else if (propertyType.some((p) => p.includes("Prisma.Decimal"))) {
1565
- importDeclarations.add("Prisma", config.prismaClientImport);
1566
- }
1567
- ok(property.decorators !== void 0, "property.decorators is undefined");
1568
- const shouldHideField = settings?.shouldHideField({ name: outputType2.name, output: true }) === true || config.decorate.some(
1569
- (d) => d.name === "HideField" && d.from === "@nestjs/graphql" && d.isMatchField(field.name) && d.isMatchType(outputTypeName)
1570
- );
1571
- if (shouldHideField) {
1572
- importDeclarations.add("HideField", nestjsGraphql);
1573
- property.decorators.push({ arguments: [], name: "HideField" });
1574
- } else {
1575
- let typeExpression;
1576
- if (useGetType) {
1577
- typeExpression = isList ? `() => [getType('${graphqlType}')]` : `() => getType('${graphqlType}')`;
1578
- } else {
1579
- typeExpression = isList ? `() => [${graphqlType}]` : `() => ${graphqlType}`;
1580
- }
1581
- property.decorators.push({
1582
- arguments: [
1583
- typeExpression,
1584
- JSON52.stringify({
1585
- ...settings?.fieldArguments(),
1586
- defaultValue: ["number", "string", "boolean"].includes(
1587
- typeof modelField?.default
1588
- ) ? modelField?.default : void 0,
1589
- description: modelField?.documentation !== null && modelField?.documentation !== void 0 && modelField.documentation !== "" ? modelField.documentation : void 0,
1590
- nullable: Boolean(field.isNullable)
1591
- })
1592
- ],
1593
- name: "Field"
1594
- });
1595
- for (const setting of settings ?? []) {
1596
- if (shouldBeDecorated(setting) && (setting.match?.(field.name) ?? true)) {
1597
- property.decorators.push({
1598
- arguments: setting.arguments,
1599
- name: setting.name
1600
- });
1601
- ok(
1602
- setting.from && setting.from.length > 0,
1603
- "Missed 'from' part in configuration or field setting"
1604
- );
1605
- importDeclarations.create(setting);
1606
- }
1607
- }
1608
- for (const decorate of config.decorate) {
1609
- if (decorate.isMatchField(field.name) && decorate.isMatchType(outputTypeName)) {
1610
- property.decorators.push({
1611
- arguments: decorate.arguments?.map((x) => pupa(x, { propertyType })),
1612
- name: decorate.name
1613
- });
1614
- importDeclarations.create(decorate);
1615
- }
1616
- }
1617
- }
1618
- eventEmitter.emitSync("ClassProperty", property, {
1619
- isList,
1620
- location,
1621
- propertyType
1622
- });
1623
- }
1624
- for (const setting of modelSettings ?? []) {
1625
- if (shouldBeDecorated(setting)) {
1626
- classStructure.decorators.push({
1627
- arguments: setting.arguments,
1628
- name: setting.name
1629
- });
1630
- importDeclarations.create(setting);
1631
- }
1632
- }
1633
- const statements = [
1634
- ...importDeclarations.toStatements(),
1635
- classStructure
1636
- ];
1637
- if (config.esmCompatible) {
1638
- statements.push(`
1639
- registerType('${outputType2.name}', ${outputType2.name});`);
1640
- }
1641
- if (exportDeclaration) {
1642
- sourceFile.set({
1643
- statements: [exportDeclaration, "\n", classStructure]
1644
- });
1645
- const classDeclaration = sourceFile.getClassOrThrow(model.name);
1646
- const commentedText = classDeclaration.getText().split("\n").map((x) => `// ${x}`);
1647
- classDeclaration.remove();
1648
- sourceFile.addStatements(["\n", ...commentedText]);
1649
- } else {
1650
- sourceFile.set({
1651
- statements
1652
- });
1653
- }
1654
- }
1655
- function shouldBeDecorated(setting) {
1656
- return setting.kind === "Decorator" && (setting.output || setting.model) && !(setting.output && setting.model);
1657
- }
1658
- function getExportDeclaration(name, statements) {
1659
- return statements.find((structure) => {
1660
- return structure.kind === StructureKind.ExportDeclaration && structure.namedExports.some(
1661
- (o) => (o.alias ?? o.name) === name
1662
- );
1663
- });
1664
- }
1665
-
1666
- // src/handlers/no-atomic-operations.ts
1667
- function noAtomicOperations(eventEmitter) {
1668
- eventEmitter.on("BeforeInputType", beforeInputType2);
1669
- eventEmitter.on("BeforeGenerateFiles", beforeGenerateFiles);
1670
- }
1671
- function beforeInputType2(args) {
1672
- const { getModelName: getModelName2, inputType: inputType2 } = args;
1673
- for (const field of inputType2.fields) {
1674
- const fieldName = field.name;
1675
- field.inputTypes = field.inputTypes.filter((it) => {
1676
- const inputTypeName = it.type;
1677
- const modelName = getModelName2(inputTypeName);
1678
- const isModelNameValid = modelName !== null && modelName !== void 0 && modelName.length > 0;
1679
- if (isAtomicOperation(inputTypeName) || isModelNameValid && isListInput(inputTypeName, modelName, fieldName)) {
1680
- return false;
1681
- }
1682
- return true;
1683
- });
1684
- }
1685
- }
1686
- function beforeGenerateFiles(args) {
1687
- const { project } = args;
1688
- for (const sourceFile of project.getSourceFiles()) {
1689
- const className = sourceFile.getClass(() => true)?.getName();
1690
- const isClassNameValid = className !== void 0 && className !== null && className.length > 0;
1691
- if (isClassNameValid && isAtomicOperation(className)) {
1692
- project.removeSourceFile(sourceFile);
1693
- }
1694
- }
1695
- }
1696
- function isAtomicOperation(typeName) {
1697
- if (typeName.endsWith("FieldUpdateOperationsInput")) {
1698
- return true;
1699
- }
1700
- return false;
1701
- }
1702
- function isListInput(typeName, model, field) {
1703
- return typeName === `${model}Create${field}Input` || typeName === `${model}Update${field}Input`;
1704
- }
1705
-
1706
- // src/helpers/get-enum-name.ts
1707
- function getEnumName(referenceName) {
1708
- return referenceName.slice(3, -2);
1709
- }
1710
-
1711
- // src/handlers/output-type.ts
1712
- var nestjsGraphql2 = "@nestjs/graphql";
1713
- function outputType(outputTypeArg, args) {
1714
- const { config, eventEmitter, fieldSettings, getModelName: getModelName2, getSourceFile, models } = args;
1715
- const importDeclarations = new ImportDeclarationMap();
1716
- const fileType = "output";
1717
- const modelName = getModelName2(outputTypeArg.name);
1718
- const model = modelName === void 0 ? void 0 : models.get(modelName);
1719
- const isAggregateOutput = model !== void 0 && /(?:Count|Avg|Sum|Min|Max)AggregateOutputType$/.test(outputTypeArg.name) && outputTypeArg.name.startsWith(model.name);
1720
- const isCountOutput = model?.name !== void 0 && model.name !== "" && outputTypeArg.name === `${model.name}CountOutputType`;
1721
- if (config.emitBlocks.outputs || isCountOutput) ; else {
1722
- return;
1723
- }
1724
- outputTypeArg.name = getOutputTypeName(outputTypeArg.name);
1725
- if (isAggregateOutput) {
1726
- eventEmitter.emitSync("AggregateOutput", { ...args, outputType: outputTypeArg });
1727
- }
1728
- const sourceFile = getSourceFile({
1729
- name: outputTypeArg.name,
1730
- type: fileType
1731
- });
1732
- const classStructure = {
1733
- decorators: [
1734
- {
1735
- arguments: [],
1736
- name: "ObjectType"
1737
- }
1738
- ],
1739
- isExported: true,
1740
- kind: StructureKind.Class,
1741
- name: outputTypeArg.name,
1742
- properties: []
1743
- };
1744
- importDeclarations.add("Field", nestjsGraphql2);
1745
- importDeclarations.add("ObjectType", nestjsGraphql2);
1746
- for (const field of outputTypeArg.fields) {
1747
- const { isList, location, type } = field.outputType;
1748
- const outputTypeName = getOutputTypeName(type);
1749
- let settings;
1750
- if (isCountOutput) {
1751
- settings = void 0;
1752
- } else if (model === void 0) {
1753
- settings = void 0;
1754
- } else {
1755
- settings = fieldSettings.get(model.name)?.get(field.name);
1756
- }
1757
- const propertySettings = settings?.getPropertyType({
1758
- name: outputTypeArg.name,
1759
- output: true
1760
- });
1761
- const isCustomsApplicable = outputTypeName === model?.fields.find((f) => f.name === field.name)?.type;
1762
- field.outputType.type = outputTypeName;
1763
- const propertyType = castArray(
1764
- propertySettings?.name ?? getPropertyType({
1765
- location,
1766
- type: outputTypeName
1767
- })
1768
- );
1769
- const property = propertyStructure({
1770
- hasQuestionToken: isCountOutput ? true : void 0,
1771
- isList,
1772
- isNullable: field.isNullable,
1773
- name: field.name,
1774
- propertyType
1775
- });
1776
- classStructure.properties?.push(property);
1777
- if (propertySettings !== void 0) {
1778
- importDeclarations.create({ ...propertySettings });
1779
- } else if (propertyType.some((p) => p.includes("Prisma.Decimal"))) {
1780
- importDeclarations.add("Prisma", config.prismaClientImport);
1781
- }
1782
- let graphqlType;
1783
- const shouldHideField = settings?.shouldHideField({
1784
- name: outputTypeArg.name,
1785
- output: true
1786
- }) === true || config.decorate.some(
1787
- (d) => d.name === "HideField" && d.from === "@nestjs/graphql" && d.isMatchField(field.name) && d.isMatchType(outputTypeName)
1788
- );
1789
- const fieldType = settings?.getFieldType({
1790
- name: outputTypeArg.name,
1791
- output: true
1792
- });
1793
- if (fieldType !== void 0 && isCustomsApplicable && !shouldHideField) {
1794
- graphqlType = fieldType.name;
1795
- importDeclarations.create({ ...fieldType });
1796
- } else {
1797
- const graphqlImport = getGraphqlImport({
1798
- config,
1799
- fileType,
1800
- getSourceFile,
1801
- isId: false,
1802
- location,
1803
- sourceFile,
1804
- typeName: outputTypeName
1805
- });
1806
- const referenceName = location === "enumTypes" ? getEnumName(propertyType[0]) : propertyType[0];
1807
- graphqlType = graphqlImport.name;
1808
- if (graphqlImport.specifier !== null && graphqlImport.specifier !== void 0 && graphqlImport.specifier.length > 0 && !importDeclarations.has(graphqlImport.name) && (graphqlImport.name !== outputTypeArg.name && !shouldHideField || shouldHideField && referenceName === graphqlImport.name)) {
1809
- importDeclarations.set(graphqlImport.name, {
1810
- moduleSpecifier: graphqlImport.specifier,
1811
- namedImports: [{ name: graphqlImport.name }]
1812
- });
1813
- }
1814
- }
1815
- ok(property.decorators !== void 0, "property.decorators is undefined");
1816
- if (shouldHideField) {
1817
- importDeclarations.add("HideField", nestjsGraphql2);
1818
- property.decorators.push({ arguments: [], name: "HideField" });
1819
- } else {
1820
- property.decorators.push({
1821
- arguments: [
1822
- isList ? `() => [${graphqlType}]` : `() => ${graphqlType}`,
1823
- JSON52.stringify({
1824
- ...settings?.fieldArguments(),
1825
- nullable: Boolean(field.isNullable)
1826
- })
1827
- ],
1828
- name: "Field"
1829
- });
1830
- if (isCustomsApplicable) {
1831
- for (const options of settings ?? []) {
1832
- const shouldApplyDecorator = options.kind === "Decorator" && options.output && (options.match?.(field.name) ?? true);
1833
- if (shouldApplyDecorator) {
1834
- property.decorators.push({
1835
- arguments: options.arguments,
1836
- name: options.name
1837
- });
1838
- ok(
1839
- options.from !== null && options.from !== void 0 && options.from.length > 0,
1840
- "Missed 'from' part in configuration or field setting"
1841
- );
1842
- importDeclarations.create(options);
1843
- }
137
+ if (connectCallback) {
138
+ await connectCallback(eventEmitter, eventArguments);
139
+ }
140
+ await eventEmitter.emit('Begin', eventArguments);
141
+ // Generate type registry file for ESM compatibility
142
+ // Must be after 'Begin' event since purgeOutput deletes all files on Begin
143
+ if (config.esmCompatible) {
144
+ generateTypeRegistry(eventArguments);
145
+ }
146
+ // Generate decimal helpers for Prisma 7+ compatibility
147
+ // This replaces the dependency on prisma-graphql-type-decimal
148
+ generateDecimalHelpers(eventArguments);
149
+ for (const model of datamodel.models) {
150
+ await eventEmitter.emit('Model', model, eventArguments);
151
+ }
152
+ // Types behaves like model
153
+ for (const model of datamodelTypes) {
154
+ await eventEmitter.emit('Model', model, eventArguments);
155
+ }
156
+ const { enumTypes, inputObjectTypes, outputObjectTypes } = schema;
157
+ await eventEmitter.emit('PostBegin', eventArguments);
158
+ for (const enumType of enumTypes.prisma.concat(enumTypes.model ?? [])) {
159
+ await eventEmitter.emit('EnumType', enumType, eventArguments);
160
+ }
161
+ for (const outputTypeItem of outputObjectTypes.model) {
162
+ await eventEmitter.emit('ModelOutputType', outputTypeItem, eventArguments);
163
+ }
164
+ const queryOutputTypes = [];
165
+ for (const outputTypeItem of outputObjectTypes.prisma) {
166
+ if (['Query', 'Mutation'].includes(outputTypeItem.name)) {
167
+ queryOutputTypes.push(outputTypeItem);
168
+ continue;
1844
169
  }
1845
- }
170
+ await eventEmitter.emit('OutputType', outputTypeItem, eventArguments);
1846
171
  }
1847
- eventEmitter.emitSync("ClassProperty", property, {
1848
- isList,
1849
- location,
1850
- propertyType
1851
- });
1852
- }
1853
- sourceFile.set({
1854
- statements: [...importDeclarations.toStatements(), classStructure]
1855
- });
1856
- }
1857
- var rmdirTyped = rmdirSync$1;
1858
- var rmdirSync = (path) => {
1859
- rmdirTyped(path);
1860
- };
1861
- function purgeOutput(emitter) {
1862
- emitter.on("Begin", begin);
1863
- emitter.on("End", end);
1864
- }
1865
- function begin({ output, project }) {
1866
- const sourceFiles = project.getDirectory(output)?.getDescendantSourceFiles();
1867
- if (sourceFiles) {
1868
- for (const sourceFile of sourceFiles) {
1869
- sourceFile.delete();
1870
- }
1871
- }
1872
- }
1873
- function end({ output, project }) {
1874
- const directories = project.getDirectory(output)?.getDescendantDirectories().filter((directory) => directory.getSourceFiles().length === 0).map((directory) => directory.getPath());
1875
- const directoryList = directories ?? [];
1876
- for (const directory of directoryList) {
1877
- try {
1878
- rmdirSync(directory);
1879
- } catch {
1880
- }
1881
- }
1882
- }
1883
- var ReExport = /* @__PURE__ */ ((ReExport2) => {
1884
- ReExport2["None"] = "None";
1885
- ReExport2["Directories"] = "Directories";
1886
- ReExport2["Single"] = "Single";
1887
- ReExport2["All"] = "All";
1888
- return ReExport2;
1889
- })(ReExport || {});
1890
- function reExport(emitter) {
1891
- emitter.on("BeforeGenerateFiles", beforeGenerateFiles2);
1892
- }
1893
- function beforeGenerateFiles2(args) {
1894
- const { config, output, project } = args;
1895
- const rootDirectory = project.getDirectoryOrThrow(output);
1896
- if (["Directories" /* Directories */, "All" /* All */].includes(config.reExport)) {
1897
- const directories = [...rootDirectory.getDescendantDirectories()];
1898
- const indexFiles = [];
1899
- for (const directory of directories) {
1900
- const sourceFiles = directory.getSourceFiles().filter((sourceFile) => sourceFile.getBaseName() !== "index.ts");
1901
- if (sourceFiles.length > 0) {
1902
- const exportDeclarations = sourceFiles.map(
1903
- (sourceFile) => getExportDeclaration2(directory, sourceFile)
1904
- );
1905
- indexFiles.push({
1906
- path: `${directory.getPath()}/index.ts`,
1907
- statements: exportDeclarations
1908
- });
1909
- } else {
1910
- const subdirs = directory.getDirectories();
1911
- if (subdirs.length > 0) {
1912
- const namespaceExportDeclarations = subdirs.map(
1913
- (sourceDirectory) => getNamespaceExportDeclaration(directory, sourceDirectory)
1914
- );
1915
- indexFiles.push({
1916
- path: `${directory.getPath()}/index.ts`,
1917
- statements: namespaceExportDeclarations
1918
- });
172
+ const inputTypes = (inputObjectTypes.prisma ?? []).concat(inputObjectTypes.model ?? []);
173
+ for (const inputTypeItem of inputTypes) {
174
+ const event = {
175
+ ...eventArguments,
176
+ classDecoratorName: 'InputType',
177
+ fileType: 'input',
178
+ inputType: inputTypeItem,
179
+ };
180
+ if (inputTypeItem.fields.length === 0) {
181
+ removeTypes.add(inputTypeItem.name);
182
+ continue;
1919
183
  }
1920
- }
1921
- }
1922
- for (const { path, statements } of indexFiles) {
1923
- project.createSourceFile(path, { statements }, { overwrite: true });
1924
- }
1925
- }
1926
- if (config.reExport === "Single" /* Single */) {
1927
- const sourceFiles = project.getSourceFiles().filter((sourceFile) => sourceFile.getBaseName() !== "index.ts");
1928
- const exportDeclarations = sourceFiles.map(
1929
- (sourceFile) => getExportDeclaration2(rootDirectory, sourceFile)
1930
- );
1931
- rootDirectory.createSourceFile(
1932
- "index.ts",
1933
- { statements: exportDeclarations },
1934
- { overwrite: true }
1935
- );
1936
- }
1937
- if (config.reExport === "All" /* All */) {
1938
- const exportDeclarations = [];
1939
- const directories = rootDirectory.getDirectories();
1940
- for (const directory of directories) {
1941
- if (directory.getBaseName() === "node_modules") {
1942
- continue;
1943
- }
1944
- const indexFile = directory.getSourceFile("index.ts");
1945
- if (indexFile) {
1946
- const dirName = directory.getBaseName();
1947
- exportDeclarations.push({
1948
- kind: StructureKind.ExportDeclaration,
1949
- moduleSpecifier: `./${dirName}/index.js`
1950
- });
1951
- }
1952
- }
1953
- if (exportDeclarations.length > 0) {
1954
- rootDirectory.createSourceFile(
1955
- "index.ts",
1956
- { statements: exportDeclarations },
1957
- { overwrite: true }
1958
- );
1959
- }
1960
- }
1961
- }
1962
- function getExportDeclaration2(directory, sourceFile) {
1963
- let moduleSpecifier = directory.getRelativePathAsModuleSpecifierTo(sourceFile);
1964
- if (!moduleSpecifier.endsWith(".js") && !moduleSpecifier.endsWith(".ts")) {
1965
- moduleSpecifier += ".js";
1966
- } else if (moduleSpecifier.endsWith(".ts")) {
1967
- moduleSpecifier = `${moduleSpecifier.slice(0, -3)}.js`;
1968
- }
1969
- return {
1970
- kind: StructureKind.ExportDeclaration,
1971
- moduleSpecifier
1972
- };
1973
- }
1974
- function getNamespaceExportDeclaration(directory, sourceDirectory) {
1975
- let moduleSpecifier = directory.getRelativePathAsModuleSpecifierTo(sourceDirectory);
1976
- if (!moduleSpecifier.endsWith("/index.js")) {
1977
- moduleSpecifier += "/index.js";
1978
- }
1979
- return {
1980
- kind: StructureKind.ExportDeclaration,
1981
- moduleSpecifier
1982
- };
1983
- }
1984
-
1985
- // src/handlers/register-all-types.ts
1986
- function generateRegisterAllTypes(args) {
1987
- const { config, output, project } = args;
1988
- if (!config.esmCompatible) {
1989
- return;
1990
- }
1991
- const rootDirectory = project.getDirectory(output) ?? project.createDirectory(output);
1992
- const sourceFile = rootDirectory.createSourceFile("register-all-types.ts", void 0, {
1993
- overwrite: true
1994
- });
1995
- const importPaths = [];
1996
- const typeNames = [];
1997
- const allSourceFiles = project.getSourceFiles(`${output}/**/*.ts`);
1998
- for (const file of allSourceFiles) {
1999
- const filePath = file.getFilePath();
2000
- if (filePath.endsWith("type-registry.ts") || filePath.endsWith("register-all-types.ts") || filePath.endsWith("index.ts")) {
2001
- continue;
2002
- }
2003
- const fileText = file.getText();
2004
- const registerMatch = /registerType\(['"]([^'"]+)['"]/.exec(fileText);
2005
- if (registerMatch) {
2006
- const relPath = relativePath(sourceFile.getFilePath(), filePath);
2007
- importPaths.push(relPath);
2008
- typeNames.push(registerMatch[1]);
2009
- }
2010
- }
2011
- importPaths.sort();
2012
- typeNames.sort();
2013
- const fileContent = `/**
2014
- * ESM Type Registration Module
2015
- *
2016
- * This file registers all generated types with the type registry to solve
2017
- * ESM circular dependency issues. In ESM, unlike CommonJS, circular imports
2018
- * can result in undefined values because modules are evaluated in a different order.
2019
- *
2020
- * IMPORTANT: Import this file at the very top of your application entry point,
2021
- * BEFORE any other code that uses the generated types.
2022
- *
2023
- * Example usage in main.ts:
2024
- *
2025
- * // This MUST be the first import
2026
- * import './@generated/register-all-types.js';
2027
- *
2028
- * // Now you can safely import and use generated types
2029
- * import { NestFactory } from '@nestjs/core';
2030
- * import { AppModule } from './app.module.js';
2031
- *
2032
- * Why this is needed:
2033
- * - ESM uses "live bindings" where imports reference the actual export
2034
- * - With circular deps (User -> Post -> User), one module isn't ready when imported
2035
- * - CJS would give a partial object that fills in later; ESM gives undefined
2036
- * - This registry pattern defers type resolution until runtime when all modules are loaded
2037
- */
2038
-
2039
- import { markRegistrationComplete } from './type-registry.js';
2040
-
2041
- // Import all generated type files to trigger their registerType() calls
2042
- // These are side-effect imports that populate the type registry
2043
- ${importPaths.map((p) => `import '${p}';`).join("\n")}
2044
-
2045
- // Mark registration as complete to enable warning messages
2046
- markRegistrationComplete();
2047
-
2048
- // Export type names for validation (optional)
2049
- export const registeredTypes = [
2050
- ${typeNames.map((n) => ` '${n}',`).join("\n")}
2051
- ] as const;
2052
-
2053
- export type RegisteredTypeName = typeof registeredTypes[number];
2054
- `;
2055
- sourceFile.addStatements(fileContent);
2056
- }
2057
-
2058
- // src/handlers/prisma-enum-doc.ts
2059
- function extractEnumValueDocs(values) {
2060
- return Object.fromEntries(
2061
- values.map((value) => {
2062
- const { name } = value;
2063
- const { documentation } = value;
2064
- if (typeof documentation !== "string") {
2065
- return null;
2066
- }
2067
- if (documentation.startsWith("@deprecated")) {
2068
- return [name, { deprecationReason: documentation.slice(11).trim() }];
2069
- }
2070
- return [name, { description: documentation }];
2071
- }).filter((entry) => entry !== null)
2072
- );
2073
- }
2074
-
2075
- // src/handlers/register-enum.ts
2076
- function registerEnum(enumType, args) {
2077
- const { config, enums, getSourceFile } = args;
2078
- const enumTypeAsRecord = enumType;
2079
- const rawName = enumTypeAsRecord.name;
2080
- const enumName = typeof rawName === "string" ? rawName : String(rawName);
2081
- const enumValue = enums[enumName];
2082
- if (!config.emitBlocks.prismaEnums && enumValue === void 0) {
2083
- return;
2084
- }
2085
- const dataModelEnum = enumValue;
2086
- const enumTypesData = dataModelEnum?.values ?? [];
2087
- const sourceFile = getSourceFile({
2088
- name: enumName,
2089
- type: "enum"
2090
- });
2091
- const importDeclarations = new ImportDeclarationMap();
2092
- importDeclarations.set("registerEnumType", {
2093
- moduleSpecifier: "@nestjs/graphql",
2094
- namedImports: [{ name: "registerEnumType" }]
2095
- });
2096
- const valuesMap = extractEnumValueDocs(enumTypesData);
2097
- const filteredValuesMap = Object.fromEntries(
2098
- Object.entries(valuesMap).filter(([, v]) => Object.keys(v).length > 0)
2099
- );
2100
- const hasValuesMap = Object.keys(filteredValuesMap).length > 0;
2101
- const formattedValuesMap = hasValuesMap ? JSON.stringify(filteredValuesMap, null, 2).replace(/"([^"]+)":/g, "$1:") : "";
2102
- const valuesMapEntry = hasValuesMap ? `, valuesMap: ${formattedValuesMap}` : "";
2103
- const enumTypeRecord = enumType;
2104
- const rawValues = enumTypeRecord.values;
2105
- const enumValues = Array.isArray(rawValues) ? rawValues.map((v) => String(v)) : [];
2106
- const enumStructure = {
2107
- isExported: true,
2108
- kind: StructureKind.Enum,
2109
- members: enumValues.map((v) => ({
2110
- initializer: JSON.stringify(v),
2111
- name: v
2112
- })),
2113
- name: enumName
2114
- };
2115
- const enumTypeName = enumName;
2116
- sourceFile.set({
2117
- statements: [
2118
- ...importDeclarations.toStatements(),
2119
- enumStructure,
2120
- "\n",
2121
- `registerEnumType(${enumTypeName}, { name: '${enumTypeName}', description: ${JSON.stringify(
2122
- dataModelEnum?.documentation
2123
- )}${valuesMapEntry} })`
2124
- ]
2125
- });
2126
- }
2127
-
2128
- // src/handlers/require-single-fields-in-whereunique-input.ts
2129
- function requireSingleFieldsInWhereUniqueInput(eventEmitter) {
2130
- eventEmitter.on("BeforeInputType", beforeInputType3);
2131
- }
2132
- function beforeInputType3(args) {
2133
- const { inputType: inputType2 } = args;
2134
- if (!isWhereUniqueInputType(inputType2.name) || inputType2.fields.length !== 1) {
2135
- return;
2136
- }
2137
- for (const field of inputType2.fields) {
2138
- field.isRequired = true;
2139
- field.isNullable = false;
2140
- }
2141
- }
2142
-
2143
- // src/handlers/type-registry.ts
2144
- function generateTypeRegistry(args) {
2145
- const { config, output, project } = args;
2146
- if (!config.esmCompatible) {
2147
- return;
2148
- }
2149
- const rootDirectory = project.getDirectory(output) ?? project.createDirectory(output);
2150
- const sourceFile = rootDirectory.createSourceFile("type-registry.ts", void 0, {
2151
- overwrite: true
2152
- });
2153
- const registryCode = `/**
2154
- * Type Registry for ESM Circular Dependency Resolution
2155
- *
2156
- * In ESM, circular dependencies behave differently than CommonJS:
2157
- * - CJS: Modules get a partial/incomplete export object that gets filled in
2158
- * - ESM: Imports are "live bindings" but can be undefined if not yet initialized
2159
- *
2160
- * This registry solves this by:
2161
- * 1. Deferring type resolution until runtime (after all modules are loaded)
2162
- * 2. Providing a forwardRef pattern for GraphQL field type declarations
2163
- * 3. Validating all types are registered before they're needed
2164
- */
2165
-
2166
- const registry = new Map<string, unknown>();
2167
- const pendingResolutions = new Map<string, Array<(type: unknown) => void>>();
2168
- let registrationComplete = false;
2169
-
2170
- /**
2171
- * Register a type with the registry.
2172
- * This should be called at module load time after the class is defined.
2173
- */
2174
- export function registerType(name: string, type: unknown): void {
2175
- if (type === undefined) {
2176
- console.warn(\`[nestjs-prisma-graphql] Warning: Registering undefined type for "\${name}". This may indicate a circular dependency issue.\`);
2177
- }
2178
- registry.set(name, type);
2179
-
2180
- // Resolve any pending forwardRef callbacks
2181
- const pending = pendingResolutions.get(name);
2182
- if (pending) {
2183
- for (const callback of pending) {
2184
- callback(type);
2185
- }
2186
- pendingResolutions.delete(name);
2187
- }
2188
- }
2189
-
2190
- /**
2191
- * Get a type from the registry.
2192
- * Returns the type if registered, undefined otherwise.
2193
- *
2194
- * For use in \\@Field(() => getType('TypeName')) decorators.
2195
- */
2196
- export function getType<T = unknown>(name: string): T {
2197
- const type = registry.get(name);
2198
- if (type === undefined && registrationComplete) {
2199
- console.warn(\`[nestjs-prisma-graphql] Warning: Type "\${name}" not found in registry. Ensure register-all-types is imported before using generated types.\`);
2200
- }
2201
- return type as T;
2202
- }
2203
-
2204
- /**
2205
- * Create a forward reference to a type that may not be registered yet.
2206
- * This is useful for handling circular dependencies where type A references type B
2207
- * and type B references type A.
2208
- *
2209
- * Usage: \\@Field(() => forwardRef('Post'))
2210
- */
2211
- export function forwardRef<T = unknown>(name: string): () => T {
2212
- return () => {
2213
- const type = registry.get(name);
2214
- if (type === undefined) {
2215
- throw new Error(
2216
- \`[nestjs-prisma-graphql] Type "\${name}" not registered. \\n\` +
2217
- \`This usually means:\\n\` +
2218
- \` 1. The register-all-types.ts file was not imported early enough\\n\` +
2219
- \` 2. There's a circular dependency that couldn't be resolved\\n\` +
2220
- \` 3. The type file failed to load\\n\\n\` +
2221
- \`Make sure to import 'register-all-types' at the top of your main.ts or app.module.ts\`
2222
- );
2223
- }
2224
- return type as T;
2225
- };
2226
- }
2227
-
2228
- /**
2229
- * Lazily resolve a type, returning a thunk that can be called later.
2230
- * This is the safest pattern for circular references in ESM.
2231
- *
2232
- * Usage: \\@Field(lazyType('Post'))
2233
- */
2234
- export function lazyType<T = unknown>(name: string): () => T {
2235
- return () => getType<T>(name);
2236
- }
2237
-
2238
- /**
2239
- * Mark registration as complete. Called after all types are imported.
2240
- * This enables warning messages for missing types.
2241
- */
2242
- export function markRegistrationComplete(): void {
2243
- registrationComplete = true;
2244
-
2245
- // Warn about any unresolved forward refs
2246
- if (pendingResolutions.size > 0) {
2247
- const missing = Array.from(pendingResolutions.keys()).join(', ');
2248
- console.warn(\`[nestjs-prisma-graphql] Warning: Unresolved forward references: \${missing}\`);
2249
- }
2250
- }
2251
-
2252
- /**
2253
- * Get all registered type names (useful for debugging)
2254
- */
2255
- export function getRegisteredTypes(): string[] {
2256
- return Array.from(registry.keys());
2257
- }
2258
-
2259
- /**
2260
- * Check if a type is registered
2261
- */
2262
- export function isTypeRegistered(name: string): boolean {
2263
- return registry.has(name);
2264
- }
2265
-
2266
- /**
2267
- * Validate that all expected types are registered.
2268
- * Throws an error if any types are missing.
2269
- */
2270
- export function validateRegistry(expectedTypes: string[]): void {
2271
- const missing = expectedTypes.filter(name => !registry.has(name));
2272
- if (missing.length > 0) {
2273
- throw new Error(
2274
- \`[nestjs-prisma-graphql] Missing type registrations: \${missing.join(', ')}\\n\` +
2275
- \`Ensure register-all-types.ts is imported before using these types.\`
2276
- );
2277
- }
2278
- }
2279
- `;
2280
- sourceFile.addStatements(registryCode);
2281
- }
2282
-
2283
- // src/handlers/warning.ts
2284
- var globalConsole = globalThis.console;
2285
- var log = (msg) => {
2286
- globalConsole.log(msg);
2287
- };
2288
- function warning(message) {
2289
- if (Array.isArray(message)) {
2290
- log("nestjs-prisma-graphql:");
2291
- log(message.join("\n"));
2292
- } else {
2293
- log(`nestjs-prisma-graphql: ${message}`);
2294
- }
2295
- }
2296
-
2297
- // src/helpers/create-emit-blocks.ts
2298
- var allEmmittedBlocks = [
2299
- "prismaEnums",
2300
- "schemaEnums",
2301
- "models",
2302
- "inputs",
2303
- "args",
2304
- "outputs"
2305
- ];
2306
- var blocksDependencyMap = {
2307
- args: ["args", "inputs", "prismaEnums"],
2308
- enums: ["schemaEnums", "prismaEnums"],
2309
- inputs: ["inputs", "prismaEnums"],
2310
- models: ["models", "schemaEnums"],
2311
- outputs: ["outputs"]
2312
- };
2313
- function createEmitBlocks(data) {
2314
- if (!data) {
2315
- const entries = allEmmittedBlocks.map((block) => [block, true]);
2316
- const allBlocks = Object.fromEntries(entries);
2317
- return allBlocks;
2318
- }
2319
- const initialBlocks = {};
2320
- let currentBlocks = initialBlocks;
2321
- for (const block of data) {
2322
- if (!Object.keys(blocksDependencyMap).includes(block)) {
2323
- continue;
2324
- }
2325
- const blockEntries = blocksDependencyMap[block].map(
2326
- (emittedBlock) => [emittedBlock, true]
2327
- );
2328
- const newBlocks = Object.fromEntries(blockEntries);
2329
- currentBlocks = {
2330
- ...currentBlocks,
2331
- ...newBlocks
2332
- };
2333
- }
2334
- return currentBlocks;
2335
- }
2336
-
2337
- // src/helpers/create-config.ts
2338
- function createConfig(data) {
2339
- const config = merge({}, unflatten(data, { delimiter: "_" }));
2340
- const $warnings = [];
2341
- const defaultPattern = `{model}/{name}.{type}.ts`;
2342
- const outputFilePatternValue = config.outputFilePattern;
2343
- const configOutputFilePattern = typeof outputFilePatternValue === "string" ? outputFilePatternValue : defaultPattern;
2344
- const sanitizedStep1 = configOutputFilePattern.replaceAll("..", "/").replaceAll(/\/+/g, "/");
2345
- const outputFilePattern = trim(sanitizedStep1, "/");
2346
- if (outputFilePattern !== configOutputFilePattern) {
2347
- $warnings.push(
2348
- `Due to invalid filepath 'outputFilePattern' changed to '${outputFilePattern}'`
2349
- );
2350
- }
2351
- if (config.reExportAll !== void 0 && config.reExportAll !== null && config.reExportAll !== false) {
2352
- $warnings.push(`Option 'reExportAll' is deprecated, use 'reExport' instead`);
2353
- if (toBoolean(config.reExportAll)) {
2354
- config.reExport = "All";
2355
- }
2356
- }
2357
- const fields = Object.fromEntries(
2358
- Object.entries(
2359
- config.fields ?? {}
2360
- ).filter(({ 1: value }) => typeof value === "object").map(([name, value]) => {
2361
- const fieldSetting = {
2362
- arguments: [],
2363
- defaultImport: toBoolean(value.defaultImport) ? true : value.defaultImport,
2364
- from: value.from,
2365
- input: toBoolean(value.input),
2366
- model: toBoolean(value.model),
2367
- namespaceImport: value.namespaceImport,
2368
- output: toBoolean(value.output)
2369
- };
2370
- return [name, fieldSetting];
2371
- })
2372
- );
2373
- const decorate = [];
2374
- const decorateConfig = config.decorate !== void 0 && config.decorate !== null ? config.decorate : {};
2375
- const configDecorate = Object.values(decorateConfig);
2376
- for (const element of configDecorate) {
2377
- if (element === void 0 || element === null) {
2378
- continue;
2379
- }
2380
- ok(
2381
- element.from !== void 0 && element.from !== "" && element.name !== void 0 && element.name !== "",
2382
- `Missed 'from' or 'name' part in configuration for decorate`
2383
- );
2384
- decorate.push({
2385
- arguments: element.arguments !== void 0 && element.arguments !== "" ? JSON52.parse(element.arguments) : void 0,
2386
- defaultImport: toBoolean(element.defaultImport) ? true : element.defaultImport,
2387
- from: element.from,
2388
- isMatchField: outmatch2(element.field, { separator: false }),
2389
- isMatchType: outmatch2(element.type, { separator: false }),
2390
- name: element.name,
2391
- namedImport: toBoolean(element.namedImport),
2392
- namespaceImport: element.namespaceImport
2393
- });
2394
- }
2395
- const customImport = [];
2396
- const customImportConfig = config.customImport !== void 0 && config.customImport !== null ? config.customImport : {};
2397
- const configCustomImport = Object.values(customImportConfig);
2398
- for (const element of configCustomImport) {
2399
- if (element === void 0 || element === null) {
2400
- continue;
2401
- }
2402
- ok(
2403
- element.from !== void 0 && element.from !== "" && element.name !== void 0 && element.name !== "",
2404
- `Missed 'from' or 'name' part in configuration for customImport`
2405
- );
2406
- customImport.push({
2407
- defaultImport: toBoolean(element.defaultImport) ? true : element.defaultImport,
2408
- from: element.from,
2409
- name: element.name,
2410
- namedImport: toBoolean(element.namedImport),
2411
- namespaceImport: element.namespaceImport
2412
- });
2413
- }
2414
- return {
2415
- $warnings,
2416
- combineScalarFilters: toBoolean(config.combineScalarFilters),
2417
- customImport,
2418
- decorate,
2419
- emitBlocks: createEmitBlocks(config.emitBlocks),
2420
- emitCompiled: toBoolean(config.emitCompiled),
2421
- emitSingle: toBoolean(config.emitSingle),
2422
- esmCompatible: toBoolean(config.esmCompatible),
2423
- fields,
2424
- graphqlScalars: config.graphqlScalars ?? {},
2425
- noAtomicOperations: toBoolean(config.noAtomicOperations),
2426
- noTypeId: toBoolean(config.noTypeId),
2427
- omitModelsCount: toBoolean(config.omitModelsCount),
2428
- outputFilePattern,
2429
- prismaClientImport: createPrismaImport(config.prismaClientImport),
2430
- purgeOutput: toBoolean(config.purgeOutput),
2431
- reExport: ReExport[String(config.reExport)] ?? "None" /* None */,
2432
- requireSingleFieldsInWhereUniqueInput: toBoolean(
2433
- config.requireSingleFieldsInWhereUniqueInput
2434
- ),
2435
- tsConfigFilePath: createTsConfigFilePathValue(config.tsConfigFilePath),
2436
- unsafeCompatibleWhereUniqueInput: toBoolean(config.unsafeCompatibleWhereUniqueInput),
2437
- useInputType: createUseInputType(
2438
- config.useInputType
2439
- )
2440
- };
2441
- }
2442
- var existsSyncTyped = existsSync;
2443
- var tsConfigFileExistsRaw = memoize((filePath) => {
2444
- const exists = existsSyncTyped(filePath);
2445
- return exists;
2446
- });
2447
- var tsConfigFileExists = tsConfigFileExistsRaw;
2448
- function createTsConfigFilePathValue(value) {
2449
- if (typeof value === "string" && value !== "") {
2450
- return value;
2451
- }
2452
- const fileExists = tsConfigFileExists("tsconfig.json");
2453
- if (fileExists) {
2454
- return "tsconfig.json";
2455
- }
2456
- return void 0;
2457
- }
2458
- function createPrismaImport(value) {
2459
- if (typeof value === "string" && value !== "") {
2460
- return value;
2461
- }
2462
- return "@prisma/client";
2463
- }
2464
- function createUseInputType(data) {
2465
- if (data === void 0 || data === null) {
2466
- return [];
2467
- }
2468
- const result = [];
2469
- for (const [typeName, useInputs] of Object.entries(data)) {
2470
- const entry = {
2471
- ALL: void 0,
2472
- typeName
2473
- };
2474
- if (useInputs.ALL !== void 0 && useInputs.ALL !== "") {
2475
- entry.ALL = useInputs.ALL;
2476
- delete useInputs.ALL;
2477
- }
2478
- for (const [propertyName, pattern] of Object.entries(useInputs)) {
2479
- entry[propertyName] = pattern;
184
+ await eventEmitter.emit('BeforeInputType', event);
185
+ await eventEmitter.emit('InputType', event);
2480
186
  }
2481
- result.push(entry);
2482
- }
2483
- return result;
2484
- }
2485
- function toBoolean(value) {
2486
- return ["true", "1", "on"].includes(String(value));
2487
- }
2488
- function generateFileName(args) {
2489
- const { getModelName: getModelName2, name, template, type } = args;
2490
- const rawPath = pupa(template, {
2491
- get model() {
2492
- const result = getModelName2(name) ?? "prisma";
2493
- return kebabCase(result);
2494
- },
2495
- get name() {
2496
- let result = kebabCase(name);
2497
- for (const suffix of ["input", "args", "enum"]) {
2498
- const ending = `-${suffix}`;
2499
- if (type === suffix && result.endsWith(ending)) {
2500
- result = result.slice(0, -ending.length);
187
+ for (const outputTypeItem of queryOutputTypes) {
188
+ for (const field of outputTypeItem.fields) {
189
+ await eventEmitter.emit('ArgsType', field, eventArguments);
2501
190
  }
2502
- }
2503
- return result;
2504
- },
2505
- plural: {
2506
- get type() {
2507
- return pluralize(type);
2508
- }
2509
- },
2510
- type
2511
- });
2512
- return rawPath.split("/").map((segment) => filenamify(segment, { replacement: "-" })).join("/");
2513
- }
2514
-
2515
- // src/helpers/factory-get-source-file.ts
2516
- function factoryGetSourceFile(args) {
2517
- const { getModelName: getModelName2, output, outputFilePattern, project } = args;
2518
- return function getSourceFile(getSourceFileArgs) {
2519
- const { name, type } = getSourceFileArgs;
2520
- let filePath = generateFileName({
2521
- getModelName: getModelName2,
2522
- name,
2523
- template: outputFilePattern,
2524
- type
2525
- });
2526
- filePath = `${output}/${filePath}`;
2527
- return project.getSourceFile(filePath) ?? project.createSourceFile(filePath, void 0, { overwrite: true });
2528
- };
2529
- }
2530
- var splitKeywords = [
2531
- "CreateInput",
2532
- "CreateMany",
2533
- "CreateNested",
2534
- "CreateOneWithout",
2535
- "CreateOrConnect",
2536
- "CreateWithout",
2537
- "DistinctField",
2538
- "Filter",
2539
- "ManyWithout",
2540
- "OrderByInput",
2541
- "RelationFilter",
2542
- "NullableRelationFilter",
2543
- "ListRelationFilter",
2544
- "ScalarWhereInput",
2545
- "UpdateInput",
2546
- "UpdateMany",
2547
- "UpdateOneRequiredWithout",
2548
- "UpdateOneWithout",
2549
- "UpdateWith",
2550
- "UpsertWith",
2551
- "UpsertWithout",
2552
- "WhereInput",
2553
- "WhereUniqueInput",
2554
- "AvgAggregate",
2555
- "SumAggregate",
2556
- "MinAggregate",
2557
- "MaxAggregate",
2558
- "CountAggregate",
2559
- "ScalarField",
2560
- "GroupBy",
2561
- "OrderBy",
2562
- "UncheckedUpdate",
2563
- "UncheckedCreate",
2564
- "ScalarWhere",
2565
- "CountOutputType",
2566
- "CountOrderBy",
2567
- "SumOrderBy",
2568
- "MinOrderBy",
2569
- "MaxOrderBy",
2570
- "AvgOrderBy",
2571
- "Create",
2572
- "Update",
2573
- "ScalarRelationFilter",
2574
- "NullableScalarRelationFilter"
2575
- ].sort((a, b) => b.length - a.length);
2576
- var endsWithKeywords = [
2577
- "Aggregate",
2578
- "GroupBy",
2579
- "CreateOne",
2580
- "CreateMany",
2581
- "DeleteMany",
2582
- "DeleteOne",
2583
- "FindMany",
2584
- "FindOne",
2585
- "FindUnique",
2586
- "UpdateMany",
2587
- "UpdateOne",
2588
- "UpsertOne"
2589
- ];
2590
- var middleKeywords = [
2591
- ["FindFirst", "OrThrowArgs"],
2592
- ["FindUnique", "OrThrowArgs"],
2593
- ["Aggregate", "Args"],
2594
- ["CreateOne", "Args"],
2595
- ["CreateMany", "Args"],
2596
- ["DeleteMany", "Args"],
2597
- ["DeleteOne", "Args"],
2598
- ["FindMany", "Args"],
2599
- ["FindFirst", "Args"],
2600
- ["FindOne", "Args"],
2601
- ["FindUnique", "Args"],
2602
- ["UpdateMany", "Args"],
2603
- ["UpdateMany", "AndReturnOutputType"],
2604
- ["UpdateOne", "Args"],
2605
- ["UpsertOne", "Args"],
2606
- ["GroupBy", "Args"],
2607
- ["OrderBy", "Args"]
2608
- ];
2609
- function createGetModelName(modelNames) {
2610
- return memoize(tryGetName);
2611
- function tryGetName(name) {
2612
- return getModelName({ modelNames, name });
2613
- }
2614
- }
2615
- function getModelName(args) {
2616
- const { modelNames, name } = args;
2617
- for (const keyword of splitKeywords) {
2618
- const [test] = name.split(keyword, 1);
2619
- if (test !== void 0 && modelNames.includes(test)) {
2620
- return test;
2621
191
  }
2622
- }
2623
- for (const keyword of endsWithKeywords) {
2624
- const test = name.split(keyword).at(-1);
2625
- if (test !== void 0 && modelNames.includes(test)) {
2626
- return test;
2627
- }
2628
- }
2629
- for (const [start, end2] of middleKeywords) {
2630
- let test = name.slice(start.length).slice(0, -end2.length);
2631
- if (modelNames.includes(test) && name.startsWith(start) && name.endsWith(end2)) {
2632
- return test;
2633
- }
2634
- test = name.slice(0, -(start + end2).length);
2635
- if (modelNames.includes(test) && name.endsWith(start + end2)) {
2636
- return test;
2637
- }
2638
- }
2639
- if (name.endsWith("CompoundUniqueInput")) {
2640
- const test = name.slice(0, -19);
2641
- const models = modelNames.filter((x) => test.startsWith(x)).sort((a, b) => b.length - a.length);
2642
- return models[0];
2643
- }
2644
- if (name.endsWith("Count")) {
2645
- const test = name.slice(0, -5);
2646
- if (modelNames.includes(test)) {
2647
- return test;
2648
- }
2649
- }
2650
- return void 0;
2651
- }
2652
-
2653
- // src/generate.ts
2654
- var createRequireTyped = createRequire;
2655
- var requireCjs = createRequireTyped(String(import.meta.url));
2656
- var AwaitEventEmitter = requireCjs(
2657
- "await-event-emitter"
2658
- );
2659
- var AwaitEventEmitterClass = AwaitEventEmitter.default;
2660
- async function generate(args) {
2661
- const { connectCallback, dmmf, generator, skipAddOutputSourceFiles } = args;
2662
- const generatorOutputValue = generator.output?.value ?? "";
2663
- ok(generatorOutputValue !== "", "Missing generator configuration: output");
2664
- const config = createConfig(generator.config);
2665
- const eventEmitter = new AwaitEventEmitterClass();
2666
- eventEmitter.on("Warning", warning);
2667
- if (config.emitBlocks.models) {
2668
- eventEmitter.on("Model", modelData);
2669
- }
2670
- if (config.emitBlocks.prismaEnums || config.emitBlocks.schemaEnums) {
2671
- eventEmitter.on("EnumType", registerEnum);
2672
- }
2673
- if (config.emitBlocks.outputs || config.emitBlocks.models && !config.omitModelsCount) {
2674
- eventEmitter.on("OutputType", outputType);
2675
- }
2676
- if (config.emitBlocks.models) {
2677
- eventEmitter.on("ModelOutputType", modelOutputType);
2678
- }
2679
- if (config.emitBlocks.outputs) {
2680
- eventEmitter.on("AggregateOutput", createAggregateInput);
2681
- }
2682
- if (config.emitBlocks.inputs) {
2683
- eventEmitter.on("InputType", inputType);
2684
- }
2685
- if (config.emitBlocks.args) {
2686
- eventEmitter.on("ArgsType", argsType);
2687
- }
2688
- eventEmitter.on("GenerateFiles", generateFiles);
2689
- for (const message of config.$warnings) {
2690
- eventEmitter.emitSync("Warning", message);
2691
- }
2692
- const project = new Project({
2693
- manipulationSettings: {
2694
- quoteKind: QuoteKind.Single
2695
- },
2696
- skipAddingFilesFromTsConfig: true,
2697
- skipLoadingLibFiles: !config.emitCompiled,
2698
- tsConfigFilePath: config.tsConfigFilePath
2699
- });
2700
- if (skipAddOutputSourceFiles !== true) {
2701
- project.addSourceFilesAtPaths([
2702
- `${generatorOutputValue}/**/*.ts`,
2703
- `!${generatorOutputValue}/**/*.d.ts`
2704
- ]);
2705
- }
2706
- if (config.combineScalarFilters) {
2707
- combineScalarFilters(eventEmitter);
2708
- }
2709
- if (config.noAtomicOperations) {
2710
- noAtomicOperations(eventEmitter);
2711
- }
2712
- if (config.reExport !== "None" /* None */) {
2713
- reExport(eventEmitter);
2714
- }
2715
- if (config.emitSingle) {
2716
- emitSingle(eventEmitter);
2717
- }
2718
- if (config.purgeOutput) {
2719
- purgeOutput(eventEmitter);
2720
- }
2721
- if (config.requireSingleFieldsInWhereUniqueInput) {
2722
- requireSingleFieldsInWhereUniqueInput(eventEmitter);
2723
- }
2724
- const models = /* @__PURE__ */ new Map();
2725
- const modelNames = [];
2726
- const modelFields = /* @__PURE__ */ new Map();
2727
- const fieldSettings = /* @__PURE__ */ new Map();
2728
- const getModelName2 = createGetModelName(modelNames);
2729
- const getSourceFile = factoryGetSourceFile({
2730
- getModelName: getModelName2,
2731
- output: generatorOutputValue,
2732
- outputFilePattern: config.outputFilePattern,
2733
- project
2734
- });
2735
- const { datamodel, schema } = JSON.parse(JSON.stringify(dmmf));
2736
- const removeTypes = /* @__PURE__ */ new Set();
2737
- const datamodelTypes = datamodel.types ?? [];
2738
- const allModels = [...datamodel.models, ...datamodelTypes];
2739
- const dependencyGraph = buildDependencyGraph(allModels);
2740
- const circularDependencies = detectCircularDependencies(dependencyGraph);
2741
- const eventArguments = {
2742
- circularDependencies,
2743
- classTransformerTypeModels: /* @__PURE__ */ new Set(),
2744
- config,
2745
- enums: mapKeys(datamodel.enums, (x) => x.name),
2746
- eventEmitter,
2747
- fieldSettings,
2748
- getModelName: getModelName2,
2749
- getSourceFile,
2750
- modelFields,
2751
- modelNames,
2752
- models,
2753
- output: generatorOutputValue,
2754
- project,
2755
- removeTypes,
2756
- schema,
2757
- typeNames: /* @__PURE__ */ new Set()
2758
- };
2759
- if (connectCallback) {
2760
- await connectCallback(eventEmitter, eventArguments);
2761
- }
2762
- await eventEmitter.emit("Begin", eventArguments);
2763
- if (config.esmCompatible) {
2764
- generateTypeRegistry(eventArguments);
2765
- }
2766
- generateDecimalHelpers(eventArguments);
2767
- for (const model of datamodel.models) {
2768
- await eventEmitter.emit("Model", model, eventArguments);
2769
- }
2770
- for (const model of datamodelTypes) {
2771
- await eventEmitter.emit("Model", model, eventArguments);
2772
- }
2773
- const { enumTypes, inputObjectTypes, outputObjectTypes } = schema;
2774
- await eventEmitter.emit("PostBegin", eventArguments);
2775
- for (const enumType of enumTypes.prisma.concat(enumTypes.model ?? [])) {
2776
- await eventEmitter.emit("EnumType", enumType, eventArguments);
2777
- }
2778
- for (const outputTypeItem of outputObjectTypes.model) {
2779
- await eventEmitter.emit("ModelOutputType", outputTypeItem, eventArguments);
2780
- }
2781
- const queryOutputTypes = [];
2782
- for (const outputTypeItem of outputObjectTypes.prisma) {
2783
- if (["Query", "Mutation"].includes(outputTypeItem.name)) {
2784
- queryOutputTypes.push(outputTypeItem);
2785
- continue;
2786
- }
2787
- await eventEmitter.emit("OutputType", outputTypeItem, eventArguments);
2788
- }
2789
- const inputTypes = (inputObjectTypes.prisma ?? []).concat(inputObjectTypes.model ?? []);
2790
- for (const inputTypeItem of inputTypes) {
2791
- const event = {
2792
- ...eventArguments,
2793
- classDecoratorName: "InputType",
2794
- fileType: "input",
2795
- inputType: inputTypeItem
2796
- };
2797
- if (inputTypeItem.fields.length === 0) {
2798
- removeTypes.add(inputTypeItem.name);
2799
- continue;
192
+ // Pre-save processing steps for ESM compatibility
193
+ // Must run BEFORE GenerateFiles so created files are included in the save
194
+ if (config.esmCompatible) {
195
+ // 1. Generate barrel exports (index.ts files) if reExport="None"
196
+ generateBarrelExports(eventArguments);
197
+ // 2. Add .js extensions and convert type imports for ESM
198
+ postProcessImports(eventArguments);
199
+ // 3. Patch type-registry and add @ts-nocheck
200
+ patchTypeRegistry(eventArguments);
201
+ // 4. Generate register-all-types file
202
+ // Must be last so it can scan all final files with registerType()
203
+ generateRegisterAllTypes(eventArguments);
2800
204
  }
2801
- await eventEmitter.emit("BeforeInputType", event);
2802
- await eventEmitter.emit("InputType", event);
2803
- }
2804
- for (const outputTypeItem of queryOutputTypes) {
2805
- for (const field of outputTypeItem.fields) {
2806
- await eventEmitter.emit("ArgsType", field, eventArguments);
205
+ await eventEmitter.emit('BeforeGenerateFiles', eventArguments);
206
+ await eventEmitter.emit('GenerateFiles', eventArguments);
207
+ await eventEmitter.emit('End', eventArguments);
208
+ for (const name of Object.keys(eventEmitter._events)) {
209
+ eventEmitter.off(name);
2807
210
  }
2808
- }
2809
- if (config.esmCompatible) {
2810
- generateRegisterAllTypes(eventArguments);
2811
- }
2812
- await eventEmitter.emit("BeforeGenerateFiles", eventArguments);
2813
- await eventEmitter.emit("GenerateFiles", eventArguments);
2814
- await eventEmitter.emit("End", eventArguments);
2815
- for (const name of Object.keys(
2816
- eventEmitter._events
2817
- )) {
2818
- eventEmitter.off(name);
2819
- }
2820
211
  }
2821
-
2822
- export { generate };
2823
- //# sourceMappingURL=generate.js.map
2824
212
  //# sourceMappingURL=generate.js.map