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