@baeta/plugin-graphql 0.0.2 → 0.0.3

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 (44) hide show
  1. package/dist/index.cjs +1282 -0
  2. package/dist/index.d.ts +10 -3
  3. package/dist/index.js +1260 -21
  4. package/package.json +13 -12
  5. package/dist/codegen.d.ts +0 -6
  6. package/dist/codegen.js +0 -116
  7. package/dist/codegen.mjs +0 -89
  8. package/dist/config.d.ts +0 -10
  9. package/dist/config.js +0 -16
  10. package/dist/config.mjs +0 -0
  11. package/dist/index.mjs +0 -19
  12. package/dist/modules/builder.d.ts +0 -17
  13. package/dist/modules/builder.js +0 -439
  14. package/dist/modules/builder.mjs +0 -429
  15. package/dist/modules/config.d.ts +0 -11
  16. package/dist/modules/config.js +0 -16
  17. package/dist/modules/config.mjs +0 -0
  18. package/dist/modules/index.d.ts +0 -6
  19. package/dist/modules/index.js +0 -148
  20. package/dist/modules/index.mjs +0 -132
  21. package/dist/modules/utils.d.ts +0 -28
  22. package/dist/modules/utils.js +0 -209
  23. package/dist/modules/utils.mjs +0 -168
  24. package/dist/resolvers/config.d.ts +0 -16
  25. package/dist/resolvers/config.js +0 -16
  26. package/dist/resolvers/config.mjs +0 -0
  27. package/dist/resolvers/index.d.ts +0 -10
  28. package/dist/resolvers/index.js +0 -309
  29. package/dist/resolvers/index.mjs +0 -289
  30. package/dist/resolvers/visitor.d.ts +0 -29
  31. package/dist/resolvers/visitor.js +0 -139
  32. package/dist/resolvers/visitor.mjs +0 -111
  33. package/dist/utils/cache.d.ts +0 -3
  34. package/dist/utils/cache.js +0 -40
  35. package/dist/utils/cache.mjs +0 -16
  36. package/dist/utils/hash.d.ts +0 -6
  37. package/dist/utils/hash.js +0 -38
  38. package/dist/utils/hash.mjs +0 -13
  39. package/dist/utils/load.d.ts +0 -9
  40. package/dist/utils/load.js +0 -62
  41. package/dist/utils/load.mjs +0 -40
  42. package/dist/utils/path.d.ts +0 -3
  43. package/dist/utils/path.js +0 -37
  44. package/dist/utils/path.mjs +0 -7
package/dist/index.cjs ADDED
@@ -0,0 +1,1282 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+
26
+ // index.ts
27
+ var graphql_exports = {};
28
+ __export(graphql_exports, {
29
+ default: () => graphql_default
30
+ });
31
+ module.exports = __toCommonJS(graphql_exports);
32
+ var import_plugin2 = require("@baeta/plugin");
33
+
34
+ // codegen.ts
35
+ var import_core = require("@graphql-codegen/core");
36
+ var import_plugin_helpers4 = require("@graphql-codegen/plugin-helpers");
37
+
38
+ // modules/index.ts
39
+ var import_graphql3 = require("graphql");
40
+ var import_path = require("path");
41
+
42
+ // modules/utils.ts
43
+ var import_graphql = require("graphql");
44
+ var import_parse_filepath = __toESM(require("parse-filepath"), 1);
45
+ var sep = "/";
46
+ function collectUsedTypes(doc) {
47
+ const used = [];
48
+ doc.definitions.forEach(findRelated);
49
+ function markAsUsed(type) {
50
+ pushUnique(used, type);
51
+ }
52
+ function findRelated(node) {
53
+ if (node.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION || node.kind === import_graphql.Kind.OBJECT_TYPE_EXTENSION) {
54
+ markAsUsed(node.name.value);
55
+ if (node.fields) {
56
+ node.fields.forEach(findRelated);
57
+ }
58
+ if (node.interfaces) {
59
+ node.interfaces.forEach(findRelated);
60
+ }
61
+ } else if (node.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION || node.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION) {
62
+ markAsUsed(node.name.value);
63
+ if (node.fields) {
64
+ node.fields.forEach(findRelated);
65
+ }
66
+ } else if (node.kind === import_graphql.Kind.INTERFACE_TYPE_DEFINITION || node.kind === import_graphql.Kind.INTERFACE_TYPE_EXTENSION) {
67
+ markAsUsed(node.name.value);
68
+ if (node.fields) {
69
+ node.fields.forEach(findRelated);
70
+ }
71
+ if (node.interfaces) {
72
+ node.interfaces.forEach(findRelated);
73
+ }
74
+ } else if (node.kind === import_graphql.Kind.UNION_TYPE_DEFINITION || node.kind === import_graphql.Kind.UNION_TYPE_EXTENSION) {
75
+ markAsUsed(node.name.value);
76
+ if (node.types) {
77
+ node.types.forEach(findRelated);
78
+ }
79
+ } else if (node.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION || node.kind === import_graphql.Kind.ENUM_TYPE_EXTENSION) {
80
+ markAsUsed(node.name.value);
81
+ } else if (node.kind === import_graphql.Kind.SCALAR_TYPE_DEFINITION || node.kind === import_graphql.Kind.SCALAR_TYPE_EXTENSION) {
82
+ if (!isGraphQLPrimitive(node.name.value)) {
83
+ markAsUsed(node.name.value);
84
+ }
85
+ } else if (node.kind === import_graphql.Kind.INPUT_VALUE_DEFINITION) {
86
+ findRelated(resolveTypeNode(node.type));
87
+ } else if (node.kind === import_graphql.Kind.FIELD_DEFINITION) {
88
+ findRelated(resolveTypeNode(node.type));
89
+ if (node.arguments) {
90
+ node.arguments.forEach(findRelated);
91
+ }
92
+ } else if (node.kind === import_graphql.Kind.NAMED_TYPE && !isGraphQLPrimitive(node.name.value)) {
93
+ markAsUsed(node.name.value);
94
+ }
95
+ }
96
+ return used;
97
+ }
98
+ function resolveTypeNode(node) {
99
+ if (node.kind === import_graphql.Kind.LIST_TYPE) {
100
+ return resolveTypeNode(node.type);
101
+ }
102
+ if (node.kind === import_graphql.Kind.NON_NULL_TYPE) {
103
+ return resolveTypeNode(node.type);
104
+ }
105
+ return node;
106
+ }
107
+ function isGraphQLPrimitive(name) {
108
+ return ["String", "Boolean", "ID", "Float", "Int"].includes(name);
109
+ }
110
+ function unique(val, i, all) {
111
+ return i === all.indexOf(val);
112
+ }
113
+ function withQuotes(val) {
114
+ return `'${val}'`;
115
+ }
116
+ function indent(size) {
117
+ const space = new Array(size).fill(" ").join("");
118
+ function indentInner(val) {
119
+ return val.split("\n").map((line) => `${space}${line}`).join("\n");
120
+ }
121
+ return indentInner;
122
+ }
123
+ function buildBlock({
124
+ name,
125
+ lines
126
+ }) {
127
+ if (!lines.length) {
128
+ return "";
129
+ }
130
+ return [`${name} {`, ...lines.map(indent(2)), "};"].join("\n");
131
+ }
132
+ var getRelativePath = function(filepath, basePath) {
133
+ const normalizedFilepath = normalize(filepath);
134
+ const normalizedBasePath = ensureStartsWithSeparator(
135
+ normalize(ensureEndsWithSeparator(basePath))
136
+ );
137
+ const [, relativePath] = normalizedFilepath.split(normalizedBasePath);
138
+ return relativePath;
139
+ };
140
+ function groupSourcesByModule(sources, basePath) {
141
+ const grouped = {};
142
+ sources.forEach((source) => {
143
+ if (!source.location) {
144
+ return;
145
+ }
146
+ const relativePath = getRelativePath(source.location, basePath);
147
+ if (relativePath) {
148
+ const mod = extractModuleDirectory(source.location, basePath);
149
+ if (!grouped[mod]) {
150
+ grouped[mod] = [];
151
+ }
152
+ grouped[mod].push(source);
153
+ }
154
+ });
155
+ return grouped;
156
+ }
157
+ function extractModuleDirectory(filepath, basePath) {
158
+ const relativePath = getRelativePath(filepath, basePath);
159
+ const [moduleDirectory] = relativePath.split(sep);
160
+ return moduleDirectory;
161
+ }
162
+ function stripFilename(path2) {
163
+ const parsedPath = (0, import_parse_filepath.default)(path2);
164
+ return normalize(parsedPath.dir);
165
+ }
166
+ function normalize(path2) {
167
+ return path2.replace(/\\/g, "/");
168
+ }
169
+ function ensureEndsWithSeparator(path2) {
170
+ return path2.endsWith(sep) ? path2 : path2 + sep;
171
+ }
172
+ function ensureStartsWithSeparator(path2) {
173
+ return path2.startsWith(".") ? path2.replace(/^(..\/)|(.\/)/, "/") : path2.startsWith("/") ? path2 : "/" + path2;
174
+ }
175
+ function pushUnique(list, item) {
176
+ if (!list.includes(item)) {
177
+ list.push(item);
178
+ }
179
+ }
180
+ function concatByKey(left, right, key) {
181
+ return [.../* @__PURE__ */ new Set([...left[key], ...right[key]])];
182
+ }
183
+ function uniqueByKey(left, right, key) {
184
+ return left[key].filter((item) => !right[key].includes(item));
185
+ }
186
+ function createObject(keys, valueFn) {
187
+ const obj = {};
188
+ keys.forEach((key) => {
189
+ obj[key] = valueFn(key);
190
+ });
191
+ return obj;
192
+ }
193
+
194
+ // modules/builder.ts
195
+ var import_graphql2 = require("graphql");
196
+ var import_change_case_all = require("change-case-all");
197
+ var registryKeys = [
198
+ "objects",
199
+ "inputs",
200
+ "interfaces",
201
+ "scalars",
202
+ "unions",
203
+ "enums"
204
+ ];
205
+ var resolverKeys = ["scalars", "objects", "enums"];
206
+ function buildModule(name, doc, {
207
+ importNamespace,
208
+ importPath,
209
+ encapsulate,
210
+ requireRootResolvers,
211
+ shouldDeclare,
212
+ rootTypes,
213
+ schema,
214
+ baseVisitor
215
+ }) {
216
+ const picks = createObject(
217
+ registryKeys,
218
+ () => ({})
219
+ );
220
+ const defined = createObject(registryKeys, () => []);
221
+ const extended = createObject(registryKeys, () => []);
222
+ const usedTypes = collectUsedTypes(doc);
223
+ (0, import_graphql2.visit)(doc, {
224
+ ObjectTypeDefinition(node) {
225
+ collectTypeDefinition(node);
226
+ },
227
+ ObjectTypeExtension(node) {
228
+ collectTypeExtension(node);
229
+ },
230
+ InputObjectTypeDefinition(node) {
231
+ collectTypeDefinition(node);
232
+ },
233
+ InputObjectTypeExtension(node) {
234
+ collectTypeExtension(node);
235
+ },
236
+ InterfaceTypeDefinition(node) {
237
+ collectTypeDefinition(node);
238
+ },
239
+ InterfaceTypeExtension(node) {
240
+ collectTypeExtension(node);
241
+ },
242
+ ScalarTypeDefinition(node) {
243
+ collectTypeDefinition(node);
244
+ },
245
+ UnionTypeDefinition(node) {
246
+ collectTypeDefinition(node);
247
+ },
248
+ UnionTypeExtension(node) {
249
+ collectTypeExtension(node);
250
+ },
251
+ EnumTypeDefinition(node) {
252
+ collectTypeDefinition(node);
253
+ },
254
+ EnumTypeExtension(node) {
255
+ collectTypeExtension(node);
256
+ }
257
+ });
258
+ const visited = createObject(
259
+ registryKeys,
260
+ (key) => concatByKey(defined, extended, key)
261
+ );
262
+ const external = createObject(
263
+ registryKeys,
264
+ (key) => uniqueByKey(extended, defined, key)
265
+ );
266
+ const imports = [
267
+ `import * as ${importNamespace} from "${importPath}";`,
268
+ 'import { DocumentNode } from "graphql";',
269
+ 'import * as Baeta from "@baeta/core/sdk";'
270
+ ];
271
+ let content = [
272
+ printDefinedFields(),
273
+ printDefinedEnumValues(),
274
+ printDefinedInputFields(),
275
+ printSchemaTypes(usedTypes),
276
+ printScalars(visited),
277
+ printResolveSignaturesPerType(visited),
278
+ printResolversType(visited),
279
+ printMetadata()
280
+ ].filter(Boolean).join("\n\n");
281
+ const moduleNamespace = baseVisitor.convertName(name, {
282
+ suffix: "Module",
283
+ useTypesPrefix: false,
284
+ useTypesSuffix: false
285
+ });
286
+ if (encapsulate === "namespace") {
287
+ content = `${shouldDeclare ? "declare" : "export"} namespace ${baseVisitor.convertName(name, {
288
+ suffix: "Module",
289
+ useTypesPrefix: false,
290
+ useTypesSuffix: false
291
+ })} {
292
+ ` + (shouldDeclare ? `${indent(2)(imports.join("\n"))}
293
+ ` : "") + indent(2)(content) + "\n}";
294
+ }
295
+ return [...!shouldDeclare ? imports : [], content, printFactoryMethod()].filter(Boolean).join("\n");
296
+ function printMetadata() {
297
+ return `export namespace ModuleMetadata {
298
+ export const id = '${name}';
299
+ export const dirname = __dirname;
300
+ export const typedef = ${JSON.stringify(doc)} as unknown as DocumentNode;
301
+ ${printBaetaManager()}
302
+ }`;
303
+ }
304
+ function printDefinedFields() {
305
+ return buildBlock({
306
+ name: `interface DefinedFields`,
307
+ lines: [...visited.objects, ...visited.interfaces].map(
308
+ (typeName) => `${typeName}: ${printPicks(typeName, {
309
+ ...picks.objects,
310
+ ...picks.interfaces
311
+ })};`
312
+ )
313
+ });
314
+ }
315
+ function printFactoryMethod() {
316
+ const name2 = moduleNamespace.slice(0, moduleNamespace.length - 6);
317
+ const createModuleFn = `create${name2}Module`;
318
+ const getModuleFn = `get${name2}Module`;
319
+ return `
320
+ export const ${createModuleFn} = () => Baeta.createModule(ModuleMetadata);
321
+ export const ${getModuleFn} = Baeta.createSingletonModule(${createModuleFn});
322
+ `;
323
+ }
324
+ function printObjectFieldResolverBuilder(typeName, field) {
325
+ const resolverType = `${typeName}Resolvers["${field}"]`;
326
+ return `${field}: Baeta.createResolverBuilder<NonNullable<${resolverType}>>("${typeName}", "${field}", options),`;
327
+ }
328
+ function printObjectResolverBuilder(typeName, objects) {
329
+ var _a;
330
+ const fields = ((_a = objects[typeName]) == null ? void 0 : _a.filter(unique).map((field) => printObjectFieldResolverBuilder(typeName, field))) ?? [];
331
+ if (fields.length === 0) {
332
+ return "";
333
+ }
334
+ const resolversType = `${typeName}Resolvers`;
335
+ const content2 = `{
336
+ ${fields.map(indent(2)).join("\n")}
337
+ }`;
338
+ return `${typeName}: Baeta.createResolversBuilder("${typeName}", options, {} as ${resolversType}, ${content2}),`;
339
+ }
340
+ function printSubscriptionFieldBuilder(field) {
341
+ const resolverType = `SubscriptionResolvers["${field}"]`;
342
+ return `${field}: Baeta.createSubscriptionBuilder<${resolverType}>("${field}", options),`;
343
+ }
344
+ function printSubscriptionObjectBuilder() {
345
+ var _a;
346
+ const subscriptions = ((_a = picks.objects["Subscription"]) == null ? void 0 : _a.filter(unique)) ?? [];
347
+ if (subscriptions.length === 0) {
348
+ return "";
349
+ }
350
+ const fields = subscriptions.map(
351
+ (subscription) => printSubscriptionFieldBuilder(subscription)
352
+ );
353
+ const resolversType = `SubscriptionResolvers`;
354
+ const content2 = `{
355
+ ${fields.map(indent(2)).join("\n")}
356
+ }`;
357
+ return `Subscription: Baeta.createSubscriptionsBuilder(options, {} as ${resolversType}, ${content2}),`;
358
+ }
359
+ function printScalarBuilder() {
360
+ const scalars = visited.scalars;
361
+ if (scalars.length === 0) {
362
+ return "";
363
+ }
364
+ const fields = scalars.map(
365
+ (scalar) => `${scalar}: Baeta.createScalarBuilder("${scalar}", options),`
366
+ );
367
+ const content2 = fields.map(indent(2)).join("\n");
368
+ return `Scalar: {
369
+ ${content2}
370
+ },`;
371
+ }
372
+ function printBaetaManager() {
373
+ const objects = visited.objects.filter((type) => type !== "Subscription").map((typeName) => printObjectResolverBuilder(typeName, picks.objects)).filter(Boolean);
374
+ const bodyFields = [
375
+ ...objects,
376
+ printScalarBuilder(),
377
+ printSubscriptionObjectBuilder()
378
+ ];
379
+ const body = bodyFields.filter(Boolean).map(indent(6)).join("\n");
380
+ const content2 = `{
381
+ ${body}
382
+ }`;
383
+ return `
384
+ export function createManager(options: Baeta.ManagerOptions) {
385
+ return Baeta.createManager(options, {}, ${content2});
386
+ }`;
387
+ }
388
+ function printDefinedEnumValues() {
389
+ return buildBlock({
390
+ name: `interface DefinedEnumValues`,
391
+ lines: visited.enums.map(
392
+ (typeName) => `${typeName}: ${printPicks(typeName, picks.enums)};`
393
+ )
394
+ });
395
+ }
396
+ function encapsulateTypeName(typeName) {
397
+ if (encapsulate === "prefix") {
398
+ return `${(0, import_change_case_all.pascalCase)(name)}_${typeName}`;
399
+ }
400
+ return typeName;
401
+ }
402
+ function printDefinedInputFields() {
403
+ return buildBlock({
404
+ name: `interface DefinedInputFields`,
405
+ lines: visited.inputs.map(
406
+ (typeName) => `${typeName}: ${printPicks(typeName, picks.inputs)};`
407
+ )
408
+ });
409
+ }
410
+ function printSchemaTypes(types) {
411
+ return types.filter((type) => !visited.scalars.includes(type)).map(printExportType).join("\n");
412
+ }
413
+ function printResolveSignaturesPerType(registry) {
414
+ return [
415
+ [...registry.objects, ...registry.interfaces].map(
416
+ (name2) => printResolverType(
417
+ name2,
418
+ "DefinedFields",
419
+ requireRootResolvers && rootTypes.includes(name2),
420
+ !rootTypes.includes(name2) && defined.objects.includes(name2) ? ` | '__isTypeOf'` : ""
421
+ )
422
+ ).join("\n")
423
+ ].join("\n");
424
+ }
425
+ function printScalars(registry) {
426
+ if (!registry.scalars.length) {
427
+ return "";
428
+ }
429
+ return [
430
+ `export type ${encapsulateTypeName(
431
+ "Scalars"
432
+ )} = Pick<${importNamespace}.Scalars, ${registry.scalars.map(withQuotes).join(" | ")}>;`,
433
+ ...registry.scalars.map((scalar) => {
434
+ const convertedName = baseVisitor.convertName(scalar, {
435
+ suffix: "ScalarConfig"
436
+ });
437
+ return `export type ${encapsulateTypeName(
438
+ convertedName
439
+ )} = ${importNamespace}.${convertedName};`;
440
+ })
441
+ ].join("\n");
442
+ }
443
+ function printResolversType(registry) {
444
+ const lines = [];
445
+ for (const kind in registry) {
446
+ const k = kind;
447
+ if (registry.hasOwnProperty(k) && resolverKeys.includes(k)) {
448
+ const types = registry[k];
449
+ types.forEach((typeName) => {
450
+ if (k === "enums") {
451
+ return;
452
+ }
453
+ if (k === "scalars") {
454
+ lines.push(
455
+ `${typeName}?: ${encapsulateTypeName(
456
+ importNamespace
457
+ )}.Resolvers['${typeName}'];`
458
+ );
459
+ } else {
460
+ const fieldModifier = requireRootResolvers && rootTypes.includes(typeName) ? "" : "?";
461
+ lines.push(
462
+ `${typeName}${fieldModifier}: ${encapsulateTypeName(
463
+ typeName
464
+ )}Resolvers;`
465
+ );
466
+ }
467
+ });
468
+ }
469
+ }
470
+ return buildBlock({
471
+ name: `export interface ${encapsulateTypeName("Resolvers")}`,
472
+ lines
473
+ });
474
+ }
475
+ function printResolverType(typeName, picksTypeName, requireFieldsResolvers = false, extraKeys = "") {
476
+ const typeSignature = `Pick<${importNamespace}.${baseVisitor.convertName(
477
+ typeName,
478
+ {
479
+ suffix: "Resolvers"
480
+ }
481
+ )}, ${picksTypeName}['${typeName}']${extraKeys}>`;
482
+ return `export type ${encapsulateTypeName(`${typeName}Resolvers`)} = ${requireFieldsResolvers ? `Required<${typeSignature}>` : typeSignature};`;
483
+ }
484
+ function printPicks(typeName, records) {
485
+ return records[typeName].filter(unique).map(withQuotes).join(" | ");
486
+ }
487
+ function printTypeBody(typeName) {
488
+ const coreType = `${importNamespace}.${baseVisitor.convertName(typeName, {
489
+ useTypesSuffix: true,
490
+ useTypesPrefix: true
491
+ })}`;
492
+ if (external.enums.includes(typeName) || external.objects.includes(typeName)) {
493
+ if (schema && (0, import_graphql2.isScalarType)(schema.getType(typeName))) {
494
+ return `${importNamespace}.Scalars['${typeName}']`;
495
+ }
496
+ return coreType;
497
+ }
498
+ if (defined.enums.includes(typeName) && picks.enums[typeName]) {
499
+ return `DefinedEnumValues['${typeName}']`;
500
+ }
501
+ if (defined.objects.includes(typeName) && picks.objects[typeName]) {
502
+ return `Pick<${coreType}, DefinedFields['${typeName}']>`;
503
+ }
504
+ if (defined.interfaces.includes(typeName) && picks.interfaces[typeName]) {
505
+ return `Pick<${coreType}, DefinedFields['${typeName}']>`;
506
+ }
507
+ if (defined.inputs.includes(typeName) && picks.inputs[typeName]) {
508
+ return `Pick<${coreType}, DefinedInputFields['${typeName}']>`;
509
+ }
510
+ return coreType;
511
+ }
512
+ function printExportType(typeName) {
513
+ return `export type ${encapsulateTypeName(typeName)} = ${printTypeBody(
514
+ typeName
515
+ )};`;
516
+ }
517
+ function collectFields(node, picksObj) {
518
+ const name2 = node.name.value;
519
+ if (node.fields) {
520
+ if (!picksObj[name2]) {
521
+ picksObj[name2] = [];
522
+ }
523
+ node.fields.forEach((field) => {
524
+ picksObj[name2].push(field.name.value);
525
+ });
526
+ }
527
+ }
528
+ function collectValuesFromEnum(node) {
529
+ const name2 = node.name.value;
530
+ if (node.values) {
531
+ if (!picks.enums[name2]) {
532
+ picks.enums[name2] = [];
533
+ }
534
+ node.values.forEach((field) => {
535
+ picks.enums[name2].push(field.name.value);
536
+ });
537
+ }
538
+ }
539
+ function collectTypeDefinition(node) {
540
+ const name2 = node.name.value;
541
+ switch (node.kind) {
542
+ case import_graphql2.Kind.OBJECT_TYPE_DEFINITION: {
543
+ defined.objects.push(name2);
544
+ collectFields(node, picks.objects);
545
+ break;
546
+ }
547
+ case import_graphql2.Kind.ENUM_TYPE_DEFINITION: {
548
+ defined.enums.push(name2);
549
+ collectValuesFromEnum(node);
550
+ break;
551
+ }
552
+ case import_graphql2.Kind.INPUT_OBJECT_TYPE_DEFINITION: {
553
+ defined.inputs.push(name2);
554
+ collectFields(node, picks.inputs);
555
+ break;
556
+ }
557
+ case import_graphql2.Kind.SCALAR_TYPE_DEFINITION: {
558
+ defined.scalars.push(name2);
559
+ break;
560
+ }
561
+ case import_graphql2.Kind.INTERFACE_TYPE_DEFINITION: {
562
+ defined.interfaces.push(name2);
563
+ collectFields(node, picks.interfaces);
564
+ break;
565
+ }
566
+ case import_graphql2.Kind.UNION_TYPE_DEFINITION: {
567
+ defined.unions.push(name2);
568
+ break;
569
+ }
570
+ }
571
+ }
572
+ function collectTypeExtension(node) {
573
+ const name2 = node.name.value;
574
+ switch (node.kind) {
575
+ case import_graphql2.Kind.OBJECT_TYPE_EXTENSION: {
576
+ collectFields(node, picks.objects);
577
+ if (rootTypes.includes(name2)) {
578
+ pushUnique(defined.objects, name2);
579
+ return;
580
+ }
581
+ pushUnique(extended.objects, name2);
582
+ break;
583
+ }
584
+ case import_graphql2.Kind.ENUM_TYPE_EXTENSION: {
585
+ collectValuesFromEnum(node);
586
+ pushUnique(extended.enums, name2);
587
+ break;
588
+ }
589
+ case import_graphql2.Kind.INPUT_OBJECT_TYPE_EXTENSION: {
590
+ collectFields(node, picks.inputs);
591
+ pushUnique(extended.inputs, name2);
592
+ break;
593
+ }
594
+ case import_graphql2.Kind.INTERFACE_TYPE_EXTENSION: {
595
+ collectFields(node, picks.interfaces);
596
+ pushUnique(extended.interfaces, name2);
597
+ break;
598
+ }
599
+ case import_graphql2.Kind.UNION_TYPE_EXTENSION: {
600
+ pushUnique(extended.unions, name2);
601
+ break;
602
+ }
603
+ }
604
+ }
605
+ }
606
+
607
+ // modules/index.ts
608
+ var import_visitor_plugin_common = require("@graphql-codegen/visitor-plugin-common");
609
+ var preset = {
610
+ buildGeneratesSection: (options) => {
611
+ const { baseOutputDir } = options;
612
+ const { baseTypesPath, encapsulateModuleTypes } = options.presetConfig;
613
+ const requireRootResolvers = (0, import_visitor_plugin_common.getConfigValue)(
614
+ options == null ? void 0 : options.presetConfig.requireRootResolvers,
615
+ false
616
+ );
617
+ const cwd = (0, import_path.resolve)(options.presetConfig.cwd || process.cwd());
618
+ const importTypesNamespace = options.presetConfig.importTypesNamespace || "Types";
619
+ if (!baseTypesPath) {
620
+ throw new Error(
621
+ `Preset "graphql-modules" requires you to specify "baseTypesPath" configuration and point it to your base types file (generated by "typescript" plugin)!`
622
+ );
623
+ }
624
+ if (!options.schemaAst || !options.schemaAst.extensions.sources) {
625
+ throw new Error(`Preset "graphql-modules" requires to use GraphQL SDL`);
626
+ }
627
+ const extensions = options.schemaAst.extensions;
628
+ const sourcesByModuleMap = groupSourcesByModule(
629
+ extensions.extendedSources,
630
+ baseOutputDir
631
+ );
632
+ const modules = Object.keys(sourcesByModuleMap);
633
+ const baseVisitor = new import_visitor_plugin_common.BaseVisitor(options.config, {});
634
+ const baseOutput = {
635
+ filename: (0, import_path.resolve)(cwd, baseOutputDir, baseTypesPath),
636
+ schema: options.schema,
637
+ documents: options.documents,
638
+ plugins: [
639
+ ...options.plugins,
640
+ {
641
+ "modules-exported-scalars": {}
642
+ }
643
+ ],
644
+ pluginMap: {
645
+ ...options.pluginMap,
646
+ "modules-exported-scalars": {
647
+ plugin: (schema) => {
648
+ const typeMap = schema.getTypeMap();
649
+ return Object.keys(typeMap).map((t) => {
650
+ if (t && typeMap[t] && (0, import_graphql3.isScalarType)(typeMap[t]) && !isGraphQLPrimitive(t)) {
651
+ const convertedName = baseVisitor.convertName(t);
652
+ return `export type ${convertedName} = Scalars["${t}"];`;
653
+ }
654
+ return null;
655
+ }).filter(Boolean).join("\n");
656
+ }
657
+ }
658
+ },
659
+ config: {
660
+ ...options.config,
661
+ enumsAsTypes: true
662
+ },
663
+ schemaAst: options.schemaAst
664
+ };
665
+ const baseTypesFilename = baseTypesPath.replace(/\.(js|ts|d.ts)$/, "");
666
+ const baseTypesDir = stripFilename(baseOutput.filename);
667
+ const outputs = modules.map((moduleName) => {
668
+ const filename = (0, import_path.resolve)(
669
+ cwd,
670
+ baseOutputDir,
671
+ moduleName,
672
+ options.presetConfig.filename
673
+ );
674
+ const dirpath = stripFilename(filename);
675
+ const relativePath = (0, import_path.relative)(dirpath, baseTypesDir);
676
+ const importPath = options.presetConfig.importBaseTypesFrom || normalize((0, import_path.join)(relativePath, baseTypesFilename));
677
+ const sources = sourcesByModuleMap[moduleName];
678
+ const documents = sources.map(
679
+ (source) => source.document
680
+ );
681
+ const moduleDocument = (0, import_graphql3.concatAST)(documents);
682
+ const shouldDeclare = filename.endsWith(".d.ts");
683
+ return {
684
+ filename,
685
+ schema: options.schema,
686
+ documents: [],
687
+ plugins: [
688
+ ...options.plugins.filter((p) => typeof p === "object" && !!p.add),
689
+ {
690
+ "graphql-modules-plugin": {}
691
+ }
692
+ ],
693
+ pluginMap: {
694
+ ...options.pluginMap,
695
+ "graphql-modules-plugin": {
696
+ plugin: (schema) => {
697
+ var _a, _b, _c;
698
+ return buildModule(moduleName, moduleDocument, {
699
+ importNamespace: importTypesNamespace,
700
+ importPath,
701
+ encapsulate: encapsulateModuleTypes || "namespace",
702
+ requireRootResolvers,
703
+ shouldDeclare,
704
+ schema,
705
+ baseVisitor,
706
+ useGraphQLModules: false,
707
+ rootTypes: [
708
+ ((_a = schema.getQueryType()) == null ? void 0 : _a.name) || "",
709
+ ((_b = schema.getMutationType()) == null ? void 0 : _b.name) || "",
710
+ ((_c = schema.getSubscriptionType()) == null ? void 0 : _c.name) || ""
711
+ ].filter(Boolean)
712
+ });
713
+ }
714
+ }
715
+ },
716
+ config: options.config,
717
+ schemaAst: options.schemaAst
718
+ };
719
+ });
720
+ return [baseOutput].concat(outputs);
721
+ }
722
+ };
723
+
724
+ // codegen.ts
725
+ var typescriptPlugin = __toESM(require("@graphql-codegen/typescript"), 1);
726
+
727
+ // resolvers/index.ts
728
+ var resolvers_exports = {};
729
+ __export(resolvers_exports, {
730
+ plugin: () => plugin
731
+ });
732
+ var import_visitor_plugin_common3 = require("@graphql-codegen/visitor-plugin-common");
733
+ var import_plugin_helpers = require("@graphql-codegen/plugin-helpers");
734
+
735
+ // resolvers/visitor.ts
736
+ var import_auto_bind = __toESM(require("auto-bind"), 1);
737
+ var import_visitor_plugin_common2 = require("@graphql-codegen/visitor-plugin-common");
738
+ var import_typescript = require("@graphql-codegen/typescript");
739
+ var ENUM_RESOLVERS_SIGNATURE = "export type EnumResolverSignature<T, AllowedValues = any> = { [key in keyof T]?: AllowedValues };";
740
+ var TypeScriptResolversVisitor = class extends import_visitor_plugin_common2.BaseResolversVisitor {
741
+ constructor(pluginConfig, schema) {
742
+ super(
743
+ pluginConfig,
744
+ {
745
+ avoidOptionals: (0, import_visitor_plugin_common2.getConfigValue)(pluginConfig.avoidOptionals, false),
746
+ useIndexSignature: (0, import_visitor_plugin_common2.getConfigValue)(
747
+ pluginConfig.useIndexSignature,
748
+ false
749
+ ),
750
+ wrapFieldDefinitions: (0, import_visitor_plugin_common2.getConfigValue)(
751
+ pluginConfig.wrapFieldDefinitions,
752
+ false
753
+ ),
754
+ allowParentTypeOverride: (0, import_visitor_plugin_common2.getConfigValue)(
755
+ pluginConfig.allowParentTypeOverride,
756
+ false
757
+ ),
758
+ optionalInfoArgument: (0, import_visitor_plugin_common2.getConfigValue)(
759
+ pluginConfig.optionalInfoArgument,
760
+ false
761
+ )
762
+ },
763
+ schema
764
+ );
765
+ (0, import_auto_bind.default)(this);
766
+ this.setVariablesTransformer(
767
+ new import_typescript.TypeScriptOperationVariablesToObject(
768
+ this.scalars,
769
+ this.convertName,
770
+ this.config.avoidOptionals,
771
+ this.config.immutableTypes,
772
+ this.config.namespacedImportName,
773
+ [],
774
+ this.config.enumPrefix,
775
+ this.config.enumValues
776
+ )
777
+ );
778
+ if (this.config.useIndexSignature) {
779
+ this._declarationBlockConfig = {
780
+ blockTransformer(block) {
781
+ return `ResolversObject<${block}>`;
782
+ }
783
+ };
784
+ }
785
+ }
786
+ transformParentGenericType(parentType) {
787
+ if (this.config.allowParentTypeOverride) {
788
+ return `ParentType = ${parentType}`;
789
+ }
790
+ return `ParentType extends ${parentType} = ${parentType}`;
791
+ }
792
+ formatRootResolver(schemaTypeName, resolverType, declarationKind) {
793
+ var _a;
794
+ const avoidOptionals = ((_a = this.config.avoidOptionals) == null ? void 0 : _a.resolvers) ?? this.config.avoidOptionals === true;
795
+ return `${schemaTypeName}${avoidOptionals ? "" : "?"}: ${resolverType}${this.getPunctuation(declarationKind)}`;
796
+ }
797
+ clearOptional(str) {
798
+ if (str.startsWith("Maybe")) {
799
+ return str.replace(/Maybe<(.*?)>$/, "$1");
800
+ }
801
+ return str;
802
+ }
803
+ ListType(node) {
804
+ return `Maybe<${super.ListType(node)}>`;
805
+ }
806
+ wrapWithListType(str) {
807
+ return `${this.config.immutableTypes ? "ReadonlyArray" : "Array"}<${str}>`;
808
+ }
809
+ getParentTypeForSignature(node) {
810
+ if (this._federation.isResolveReferenceField(node) && this.config.wrapFieldDefinitions) {
811
+ return "UnwrappedObject<ParentType>";
812
+ }
813
+ return "ParentType";
814
+ }
815
+ NamedType(node) {
816
+ return `Maybe<${super.NamedType(node)}>`;
817
+ }
818
+ NonNullType(node) {
819
+ const baseValue = super.NonNullType(node);
820
+ return this.clearOptional(baseValue);
821
+ }
822
+ getPunctuation(_declarationKind) {
823
+ return ";";
824
+ }
825
+ buildEnumResolverContentBlock(node, mappedEnumType) {
826
+ const valuesMap = `{ ${(node.values || []).map(
827
+ (v) => `${v.name}${this.config.avoidOptionals ? "" : "?"}: any`
828
+ ).join(", ")} }`;
829
+ this._globalDeclarations.add(ENUM_RESOLVERS_SIGNATURE);
830
+ return `EnumResolverSignature<${valuesMap}, ${mappedEnumType}>`;
831
+ }
832
+ buildEnumResolversExplicitMappedValues(node, valuesMapping) {
833
+ return `{ ${(node.values || []).map((v) => {
834
+ const valueName = v.name;
835
+ const mappedValue = valuesMapping[valueName];
836
+ return `${valueName}: ${typeof mappedValue === "number" ? mappedValue : `'${mappedValue}'`}`;
837
+ }).join(", ")} }`;
838
+ }
839
+ };
840
+
841
+ // resolvers/index.ts
842
+ var capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
843
+ var plugin = (schema, documents, config) => {
844
+ const imports = [];
845
+ if (!config.customResolveInfo) {
846
+ imports.push("GraphQLResolveInfo");
847
+ }
848
+ const showUnusedMappers = typeof config.showUnusedMappers === "boolean" ? config.showUnusedMappers : true;
849
+ const noSchemaStitching = typeof config.noSchemaStitching === "boolean" ? config.noSchemaStitching : true;
850
+ const indexSignature = config.useIndexSignature ? [
851
+ "export type WithIndex<TObject> = TObject & Record<string, any>;",
852
+ "export type ResolversObject<TObject> = WithIndex<TObject>;"
853
+ ].join("\n") : "";
854
+ const importType = config.useTypeImports ? "import type" : "import";
855
+ const prepend = [];
856
+ const defsToInclude = [];
857
+ const directiveResolverMappings = {};
858
+ if (config.directiveResolverMappings) {
859
+ for (const [directiveName, mapper] of Object.entries(
860
+ config.directiveResolverMappings
861
+ )) {
862
+ const parsedMapper = (0, import_visitor_plugin_common3.parseMapper)(mapper);
863
+ const capitalizedDirectiveName = capitalize(directiveName);
864
+ const resolverFnName = `ResolverFn${capitalizedDirectiveName}`;
865
+ const resolverFnUsage2 = `${resolverFnName}<TResult, TParent, TContext, TArgs>`;
866
+ const resolverWithResolveUsage2 = `Resolver${capitalizedDirectiveName}WithResolve<TResult, TParent, TContext, TArgs>`;
867
+ const resolverWithResolve2 = `
868
+ export type Resolver${capitalizedDirectiveName}WithResolve<TResult, TParent, TContext, TArgs> = {
869
+ resolve: ${resolverFnName}<TResult, TParent, TContext, TArgs>;
870
+ };`;
871
+ const resolverTypeName = `Resolver${capitalizedDirectiveName}`;
872
+ const resolverType2 = `export type ${resolverTypeName}<TResult, TParent = {}, TContext = {}, TArgs = {}> =`;
873
+ if (parsedMapper.isExternal) {
874
+ if (parsedMapper.default) {
875
+ prepend.push(
876
+ `${importType} ${resolverFnName} from '${parsedMapper.source}';`
877
+ );
878
+ } else {
879
+ prepend.push(
880
+ `${importType} { ${parsedMapper.import} ${parsedMapper.import !== resolverFnName ? `as ${resolverFnName} ` : ""}} from '${parsedMapper.source}';`
881
+ );
882
+ }
883
+ prepend.push(
884
+ `export${config.useTypeImports ? " type" : ""} { ${resolverFnName} };`
885
+ );
886
+ } else {
887
+ defsToInclude.push(
888
+ `export type ${resolverFnName}<TResult, TParent, TContext, TArgs> = ${parsedMapper.type}`
889
+ );
890
+ }
891
+ if (config.makeResolverTypeCallable) {
892
+ defsToInclude.push(`${resolverType2} ${resolverFnUsage2};`);
893
+ } else {
894
+ defsToInclude.push(resolverWithResolve2);
895
+ defsToInclude.push(
896
+ `${resolverType2} ${resolverFnUsage2} | ${resolverWithResolveUsage2};`
897
+ );
898
+ }
899
+ directiveResolverMappings[directiveName] = resolverTypeName;
900
+ }
901
+ }
902
+ const transformedSchema = config.federation ? (0, import_plugin_helpers.addFederationReferencesToSchema)(schema) : schema;
903
+ const visitor = new TypeScriptResolversVisitor(
904
+ { ...config, directiveResolverMappings },
905
+ transformedSchema
906
+ );
907
+ const namespacedImportPrefix = visitor.config.namespacedImportName ? `${visitor.config.namespacedImportName}.` : "";
908
+ const astNode = (0, import_plugin_helpers.getCachedDocumentNodeFromSchema)(transformedSchema);
909
+ const visitorResult = (0, import_plugin_helpers.oldVisit)(astNode, { leave: visitor });
910
+ const optionalSignForInfoArg = visitor.config.optionalInfoArgument ? "?" : "";
911
+ const legacyStitchingResolverType = `
912
+ export type LegacyStitchingResolver<TResult, TParent, TContext, TArgs> = {
913
+ fragment: string;
914
+ resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
915
+ };`;
916
+ const newStitchingResolverType = `
917
+ export type NewStitchingResolver<TResult, TParent, TContext, TArgs> = {
918
+ selectionSet: string | ((fieldNode: FieldNode) => SelectionSetNode);
919
+ resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
920
+ };`;
921
+ const stitchingResolverType = `export type StitchingResolver<TResult, TParent, TContext, TArgs> = LegacyStitchingResolver<TResult, TParent, TContext, TArgs> | NewStitchingResolver<TResult, TParent, TContext, TArgs>;`;
922
+ const resolverWithResolve = `
923
+ export type ResolverWithResolve<TResult, TParent, TContext, TArgs> = {
924
+ resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
925
+ };`;
926
+ const resolverType = `export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> =`;
927
+ const resolverFnUsage = `ResolverFn<TResult, TParent, TContext, TArgs>`;
928
+ const resolverWithResolveUsage = `ResolverWithResolve<TResult, TParent, TContext, TArgs>`;
929
+ const stitchingResolverUsage = `StitchingResolver<TResult, TParent, TContext, TArgs>`;
930
+ if (visitor.hasFederation()) {
931
+ if (visitor.config.wrapFieldDefinitions) {
932
+ defsToInclude.push(`export type UnwrappedObject<T> = {
933
+ [P in keyof T]: T[P] extends infer R | Promise<infer R> | (() => infer R2 | Promise<infer R2>)
934
+ ? R & R2 : T[P]
935
+ };`);
936
+ }
937
+ defsToInclude.push(`export type ReferenceResolver<TResult, TReference, TContext> = (
938
+ reference: TReference,
939
+ context: TContext,
940
+ info${optionalSignForInfoArg}: GraphQLResolveInfo
941
+ ) => Promise<TResult> | TResult;`);
942
+ defsToInclude.push(`
943
+ type ScalarCheck<T, S> = S extends true ? T : NullableCheck<T, S>;
944
+ type NullableCheck<T, S> = ${namespacedImportPrefix}Maybe<T> extends T ? ${namespacedImportPrefix}Maybe<ListCheck<NonNullable<T>, S>> : ListCheck<T, S>;
945
+ type ListCheck<T, S> = T extends (infer U)[] ? NullableCheck<U, S>[] : GraphQLRecursivePick<T, S>;
946
+ export type GraphQLRecursivePick<T, S> = { [K in keyof T & keyof S]: ScalarCheck<T[K], S[K]> };
947
+ `);
948
+ }
949
+ if (!config.makeResolverTypeCallable) {
950
+ defsToInclude.push(resolverWithResolve);
951
+ }
952
+ if (noSchemaStitching) {
953
+ const defs = config.makeResolverTypeCallable ? `${resolverType} ${resolverFnUsage};` : `${resolverType} ${resolverFnUsage} | ${resolverWithResolveUsage};`;
954
+ defsToInclude.push(defs);
955
+ } else {
956
+ defsToInclude.push(
957
+ [
958
+ legacyStitchingResolverType,
959
+ newStitchingResolverType,
960
+ stitchingResolverType,
961
+ resolverType,
962
+ ` | ${resolverFnUsage}`,
963
+ config.makeResolverTypeCallable ? `` : ` | ${resolverWithResolveUsage}`,
964
+ ` | ${stitchingResolverUsage};`
965
+ ].join("\n")
966
+ );
967
+ imports.push("SelectionSetNode", "FieldNode");
968
+ }
969
+ if (config.customResolverFn) {
970
+ const parsedMapper = (0, import_visitor_plugin_common3.parseMapper)(config.customResolverFn);
971
+ if (parsedMapper.isExternal) {
972
+ if (parsedMapper.default) {
973
+ prepend.push(`${importType} ResolverFn from '${parsedMapper.source}';`);
974
+ } else {
975
+ prepend.push(
976
+ `${importType} { ${parsedMapper.import} ${parsedMapper.import !== "ResolverFn" ? "as ResolverFn " : ""}} from '${parsedMapper.source}';`
977
+ );
978
+ }
979
+ prepend.push(
980
+ `export${config.useTypeImports ? " type" : ""} { ResolverFn };`
981
+ );
982
+ } else {
983
+ prepend.push(
984
+ `export type ResolverFn<TResult, TParent, TContext, TArgs> = ${parsedMapper.type}`
985
+ );
986
+ }
987
+ } else {
988
+ const defaultResolverFn = `
989
+ export type ResolverFn<TResult, TParent, TContext, TArgs> = (
990
+ parent: TParent,
991
+ args: TArgs,
992
+ context: TContext,
993
+ info${optionalSignForInfoArg}: GraphQLResolveInfo
994
+ ) => Promise<TResult> | TResult;`;
995
+ defsToInclude.push(defaultResolverFn);
996
+ }
997
+ if (config.customSubscriptionResolver) {
998
+ const parsedMapper = (0, import_visitor_plugin_common3.parseMapper)(config.customSubscriptionResolver);
999
+ if (parsedMapper.isExternal) {
1000
+ if (parsedMapper.default) {
1001
+ prepend.push(
1002
+ `${importType} SubscriptionResolver from '${parsedMapper.source}';`
1003
+ );
1004
+ } else {
1005
+ prepend.push(
1006
+ `${importType} { ${parsedMapper.import} ${parsedMapper.import !== "SubscriptionResolver" ? "as SubscriptionResolver " : ""}} from '${parsedMapper.source}';`
1007
+ );
1008
+ }
1009
+ prepend.push(
1010
+ `export${config.useTypeImports ? " type" : ""} { SubscriptionResolver };`
1011
+ );
1012
+ } else {
1013
+ prepend.push(
1014
+ `export type SubscriptionResolver<TResult, TKey extends string, TParent = {}, TContext = {}, TArgs = {}> = ${parsedMapper.type}`
1015
+ );
1016
+ }
1017
+ } else {
1018
+ const defaultSubscriptionDef = `
1019
+ export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
1020
+ parent: TParent,
1021
+ args: TArgs,
1022
+ context: TContext,
1023
+ info${optionalSignForInfoArg}: GraphQLResolveInfo
1024
+ ) => AsyncIterable<TResult> | Promise<AsyncIterable<TResult>>;
1025
+
1026
+ export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
1027
+ parent: TParent,
1028
+ args: TArgs,
1029
+ context: TContext,
1030
+ info${optionalSignForInfoArg}: GraphQLResolveInfo
1031
+ ) => TResult | Promise<TResult>;
1032
+
1033
+ export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> {
1034
+ subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>;
1035
+ resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>;
1036
+ }
1037
+
1038
+ export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
1039
+ subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>;
1040
+ resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>;
1041
+ }
1042
+
1043
+ export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> =
1044
+ | SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
1045
+ | SubscriptionResolverObject<TResult, TParent, TContext, TArgs>;
1046
+
1047
+ export type SubscriptionResolver<TResult, TKey extends string, TParent = {}, TContext = {}, TArgs = {}> =
1048
+ | ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
1049
+ | SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;
1050
+ `;
1051
+ defsToInclude.push(defaultSubscriptionDef);
1052
+ }
1053
+ const header = `${indexSignature}
1054
+
1055
+ ${visitor.getResolverTypeWrapperSignature()}
1056
+
1057
+ ${defsToInclude.join("\n")}
1058
+
1059
+ export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = (
1060
+ parent: TParent,
1061
+ context: TContext,
1062
+ info${optionalSignForInfoArg}: GraphQLResolveInfo
1063
+ ) => ${namespacedImportPrefix}Maybe<TTypes> | Promise<${namespacedImportPrefix}Maybe<TTypes>>;
1064
+
1065
+ export type IsTypeOfResolverFn<T = {}, TContext = {}> = (obj: T, context: TContext, info${optionalSignForInfoArg}: GraphQLResolveInfo) => boolean | Promise<boolean>;
1066
+
1067
+ export type NextResolverFn<T> = () => Promise<T>;
1068
+
1069
+ export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs = {}> = (
1070
+ next: NextResolverFn<TResult>,
1071
+ parent: TParent,
1072
+ args: TArgs,
1073
+ context: TContext,
1074
+ info${optionalSignForInfoArg}: GraphQLResolveInfo
1075
+ ) => TResult | Promise<TResult>;
1076
+ `;
1077
+ const resolversTypeMapping = visitor.buildResolversTypes();
1078
+ const resolversParentTypeMapping = visitor.buildResolversParentTypes();
1079
+ const {
1080
+ getRootResolver,
1081
+ getAllDirectiveResolvers,
1082
+ mappersImports,
1083
+ unusedMappers,
1084
+ hasScalars
1085
+ } = visitor;
1086
+ if (hasScalars()) {
1087
+ imports.push("GraphQLScalarType", "GraphQLScalarTypeConfig");
1088
+ }
1089
+ if (showUnusedMappers && unusedMappers.length) {
1090
+ console.warn(`Unused mappers: ${unusedMappers.join(",")}`);
1091
+ }
1092
+ if (imports.length) {
1093
+ prepend.push(`${importType} { ${imports.join(", ")} } from 'graphql';`);
1094
+ }
1095
+ if (config.customResolveInfo) {
1096
+ const parsedMapper = (0, import_visitor_plugin_common3.parseMapper)(config.customResolveInfo);
1097
+ if (parsedMapper.isExternal) {
1098
+ if (parsedMapper.default) {
1099
+ prepend.push(`import GraphQLResolveInfo from '${parsedMapper.source}'`);
1100
+ }
1101
+ prepend.push(
1102
+ `import { ${parsedMapper.import} ${parsedMapper.import !== "GraphQLResolveInfo" ? "as GraphQLResolveInfo" : ""} } from '${parsedMapper.source}';`
1103
+ );
1104
+ } else {
1105
+ prepend.push(`type GraphQLResolveInfo = ${parsedMapper.type}`);
1106
+ }
1107
+ }
1108
+ prepend.push(...mappersImports, ...visitor.globalDeclarations);
1109
+ return {
1110
+ prepend,
1111
+ content: [
1112
+ header,
1113
+ resolversTypeMapping,
1114
+ resolversParentTypeMapping,
1115
+ ...visitorResult.definitions.filter((d) => typeof d === "string"),
1116
+ getRootResolver(),
1117
+ getAllDirectiveResolvers()
1118
+ ].join("\n")
1119
+ };
1120
+ };
1121
+
1122
+ // codegen.ts
1123
+ var import_path2 = __toESM(require("path"), 1);
1124
+
1125
+ // utils/cache.ts
1126
+ function createCache() {
1127
+ const cache = /* @__PURE__ */ new Map();
1128
+ return function ensure(namespace, key, factory) {
1129
+ const cacheKey = `${namespace}:${key}`;
1130
+ const cachedValue = cache.get(cacheKey);
1131
+ if (cachedValue) {
1132
+ return cachedValue;
1133
+ }
1134
+ const value = factory();
1135
+ cache.set(cacheKey, value);
1136
+ return value;
1137
+ };
1138
+ }
1139
+
1140
+ // utils/load.ts
1141
+ var import_plugin_helpers3 = require("@graphql-codegen/plugin-helpers");
1142
+ var import_load = require("@graphql-tools/load");
1143
+ var import_code_file_loader = require("@graphql-tools/code-file-loader");
1144
+ var import_git_loader = require("@graphql-tools/git-loader");
1145
+ var import_github_loader = require("@graphql-tools/github-loader");
1146
+ var import_graphql_file_loader = require("@graphql-tools/graphql-file-loader");
1147
+ var import_json_file_loader = require("@graphql-tools/json-file-loader");
1148
+ var import_url_loader = require("@graphql-tools/url-loader");
1149
+ var import_apollo_engine_loader = require("@graphql-tools/apollo-engine-loader");
1150
+ var import_prisma_loader = require("@graphql-tools/prisma-loader");
1151
+
1152
+ // utils/hash.ts
1153
+ var import_plugin_helpers2 = require("@graphql-codegen/plugin-helpers");
1154
+ var import_graphql4 = require("graphql");
1155
+ var import_node_crypto = require("crypto");
1156
+ function hashContent(content) {
1157
+ return (0, import_node_crypto.createHash)("sha256").update(content).digest("hex");
1158
+ }
1159
+ function hashSchema(schema) {
1160
+ return hashContent((0, import_graphql4.print)((0, import_plugin_helpers2.getCachedDocumentNodeFromSchema)(schema)));
1161
+ }
1162
+
1163
+ // utils/load.ts
1164
+ async function loadSchema(schemaPointerMap, cwd) {
1165
+ const outputSchemaAst = await (0, import_load.loadSchema)(schemaPointerMap, {
1166
+ loaders: [
1167
+ new import_code_file_loader.CodeFileLoader(),
1168
+ new import_git_loader.GitLoader(),
1169
+ new import_github_loader.GithubLoader(),
1170
+ new import_graphql_file_loader.GraphQLFileLoader(),
1171
+ new import_json_file_loader.JsonFileLoader(),
1172
+ new import_url_loader.UrlLoader(),
1173
+ new import_apollo_engine_loader.ApolloEngineLoader(),
1174
+ new import_prisma_loader.PrismaLoader()
1175
+ ],
1176
+ cwd,
1177
+ includeSources: true
1178
+ });
1179
+ if (!outputSchemaAst.extensions) {
1180
+ outputSchemaAst.extensions = {};
1181
+ }
1182
+ outputSchemaAst.extensions["hash"] = hashSchema(outputSchemaAst);
1183
+ return {
1184
+ outputSchemaAst,
1185
+ outputSchema: (0, import_plugin_helpers3.getCachedDocumentNodeFromSchema)(outputSchemaAst)
1186
+ };
1187
+ }
1188
+
1189
+ // codegen.ts
1190
+ var import_plugin = require("@baeta/plugin");
1191
+ async function generate(options) {
1192
+ const root = process.cwd();
1193
+ const modulesDir = import_path2.default.relative(root, options.modulesDir || "modules");
1194
+ const rootConfig = {
1195
+ schemas: (0, import_plugin_helpers4.normalizeInstanceOrArray)(options.schemas),
1196
+ modulesDir,
1197
+ baseTypesPath: import_path2.default.relative(
1198
+ modulesDir,
1199
+ options.baseTypesPath || "./__generated__/types.ts"
1200
+ ),
1201
+ contextType: options.contextType,
1202
+ moduleDefinitionName: options.moduleDefinitionName || "typedef.ts",
1203
+ scalars: options.scalars,
1204
+ plugins: (0, import_plugin_helpers4.normalizeConfig)(["typescript", "typescript-resolvers"]),
1205
+ pluginMap: {
1206
+ typescript: typescriptPlugin,
1207
+ "typescript-resolvers": resolvers_exports
1208
+ }
1209
+ };
1210
+ const cache = createCache();
1211
+ const schemaPointerMap = {};
1212
+ for (const ptr of rootConfig.schemas) {
1213
+ if (typeof ptr === "string") {
1214
+ schemaPointerMap[ptr] = {};
1215
+ } else if (typeof ptr === "object") {
1216
+ Object.assign(schemaPointerMap, ptr);
1217
+ }
1218
+ }
1219
+ const hash = JSON.stringify(schemaPointerMap);
1220
+ const result = await cache("schema", hash, async () => {
1221
+ return loadSchema(schemaPointerMap, root);
1222
+ });
1223
+ const outputs = await preset.buildGeneratesSection({
1224
+ baseOutputDir: modulesDir,
1225
+ presetConfig: {
1226
+ baseTypesPath: rootConfig.baseTypesPath,
1227
+ filename: rootConfig.moduleDefinitionName,
1228
+ encapsulateModuleTypes: "none"
1229
+ },
1230
+ schema: result.outputSchema,
1231
+ schemaAst: result.outputSchemaAst,
1232
+ documents: [],
1233
+ pluginMap: rootConfig.pluginMap,
1234
+ plugins: rootConfig.plugins,
1235
+ config: {
1236
+ useIndexSignature: true,
1237
+ inputMaybeValue: "T | undefined",
1238
+ mapperTypeSuffix: "Prisma",
1239
+ contextType: rootConfig.contextType,
1240
+ customResolverFn: "@baeta/core#Resolver",
1241
+ customSubscriptionResolver: "@baeta/core#SubscriptionResolver",
1242
+ useTypeImports: true,
1243
+ makeResolverTypeCallable: true,
1244
+ includeDirectives: true,
1245
+ resolverTypeWrapperSignature: "T",
1246
+ scalars: {
1247
+ BigInt: "number",
1248
+ Bytes: "Buffer",
1249
+ DateTime: "Date",
1250
+ Decimal: "number",
1251
+ Json: "{}",
1252
+ ...rootConfig.scalars
1253
+ }
1254
+ }
1255
+ });
1256
+ const promises = outputs.map(async (output) => {
1257
+ const result2 = await (0, import_core.codegen)({
1258
+ ...output,
1259
+ cache
1260
+ });
1261
+ return new import_plugin.File(output.filename, result2, "graphql");
1262
+ });
1263
+ return Promise.all(promises);
1264
+ }
1265
+
1266
+ // index.ts
1267
+ var graphql_default = (0, import_plugin2.createPluginFactoryV1)({
1268
+ name: "graphql",
1269
+ watch: (baetaConfig, pluginConfig) => {
1270
+ return {
1271
+ include: pluginConfig.schemas,
1272
+ ignore: []
1273
+ };
1274
+ },
1275
+ generate: async (params) => {
1276
+ const files = await generate(params.config);
1277
+ params.ctx.fileManager.add(...files);
1278
+ return params.next();
1279
+ }
1280
+ });
1281
+ // Annotate the CommonJS export names for ESM import in node:
1282
+ 0 && (module.exports = {});