@baeta/plugin-graphql 2.0.0-next.2 → 2.0.0-next.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.
package/dist/index.js CHANGED
@@ -1,314 +1,266 @@
1
- // index.ts
2
1
  import { createPluginV1, isMatch } from "@baeta/generator-sdk";
3
-
4
- // lib/codegen.ts
5
- import { join as join2 } from "@baeta/util-path";
6
- import { concatAST } from "graphql";
7
-
8
- // utils/load.ts
2
+ import { join, normalize, posixPath, relative } from "@baeta/util-path";
3
+ import { Kind, concatAST, validateSchema, visit } from "graphql";
9
4
  import { GraphQLFileLoader } from "@graphql-tools/graphql-file-loader";
10
- import {
11
- loadSchema as loadSchemaToolkit
12
- } from "@graphql-tools/load";
13
- import {
14
- getDocumentNodeFromSchema
15
- } from "@graphql-tools/utils";
16
- import { validateSchema } from "graphql";
17
- async function loadSchema(schemas, cwd, extraLoaders = []) {
18
- const schemaPointerMap = {};
19
- for (const ptr of Array.isArray(schemas) ? schemas : [schemas]) {
20
- schemaPointerMap[ptr] = {};
21
- }
22
- const outputSchemaAst = await loadSchemaToolkit(schemaPointerMap, {
23
- loaders: [new GraphQLFileLoader(), ...extraLoaders],
24
- cwd,
25
- includeSources: true
26
- });
27
- const errors = validateSchema(outputSchemaAst);
28
- if (errors.length > 0) {
29
- const messages = errors.map((e) => e.toString()).join("\n\n--------------------\n\n");
30
- const subject = errors.length === 1 ? "error" : "errors";
31
- throw new Error(`Invalid schema. Found ${errors.length} ${subject}:
5
+ import { loadSchema } from "@graphql-tools/load";
6
+ import { getDocumentNodeFromSchema } from "@graphql-tools/utils";
7
+ import { camelCase, pascalCase } from "change-case-all";
32
8
 
33
- ${messages}`);
34
- }
35
- if (!outputSchemaAst.extensions) {
36
- outputSchemaAst.extensions = {};
37
- }
38
- return {
39
- outputSchemaAst,
40
- outputSchema: getDocumentNodeFromSchema(outputSchemaAst)
41
- };
9
+ //#region utils/load.ts
10
+ async function loadSchema$1(schemas, cwd, extraLoaders = []) {
11
+ const schemaPointerMap = {};
12
+ for (const ptr of Array.isArray(schemas) ? schemas : [schemas]) schemaPointerMap[ptr] = {};
13
+ const outputSchemaAst = await loadSchema(schemaPointerMap, {
14
+ loaders: [new GraphQLFileLoader(), ...extraLoaders],
15
+ cwd,
16
+ includeSources: true
17
+ });
18
+ const errors = validateSchema(outputSchemaAst);
19
+ if (errors.length > 0) {
20
+ const messages = errors.map((e) => e.toString()).join("\n\n--------------------\n\n");
21
+ const subject = errors.length === 1 ? "error" : "errors";
22
+ throw new Error(`Invalid schema. Found ${errors.length} ${subject}:\n\n${messages}`);
23
+ }
24
+ if (!outputSchemaAst.extensions) outputSchemaAst.extensions = {};
25
+ return {
26
+ outputSchemaAst,
27
+ outputSchema: getDocumentNodeFromSchema(outputSchemaAst)
28
+ };
42
29
  }
43
30
 
44
- // utils/path.ts
45
- import path, { normalize } from "@baeta/util-path";
46
- var sep = "/";
31
+ //#endregion
32
+ //#region utils/path.ts
33
+ const sep = "/";
47
34
  function getRelativePath(filepath, basePath) {
48
- const normalizedFilepath = normalize(filepath);
49
- const normalizedBasePath = ensureStartsWithSeparator(
50
- ensureEndsWithSeparator(normalize(basePath))
51
- );
52
- const [, relativePath] = normalizedFilepath.split(normalizedBasePath);
53
- return relativePath;
35
+ const normalizedFilepath = normalize(filepath);
36
+ const normalizedBasePath = ensureStartsWithSeparator(ensureEndsWithSeparator(normalize(basePath)));
37
+ const [, relativePath] = normalizedFilepath.split(normalizedBasePath);
38
+ return relativePath;
54
39
  }
55
40
  function extractModuleDirectory(relativePath) {
56
- const [moduleDirectory] = relativePath.split(sep);
57
- return moduleDirectory;
41
+ const [moduleDirectory] = relativePath.split(sep);
42
+ return moduleDirectory;
58
43
  }
59
- function ensureStartsWithSeparator(path2) {
60
- return path2.startsWith(sep) ? path2 : sep + path2;
44
+ function ensureStartsWithSeparator(path$1) {
45
+ return path$1.startsWith(sep) ? path$1 : sep + path$1;
61
46
  }
62
- function ensureEndsWithSeparator(path2) {
63
- return path2.endsWith(sep) ? path2 : path2 + sep;
47
+ function ensureEndsWithSeparator(path$1) {
48
+ return path$1.endsWith(sep) ? path$1 : path$1 + sep;
64
49
  }
65
50
 
66
- // utils/source.ts
51
+ //#endregion
52
+ //#region utils/source.ts
67
53
  function groupSourcesByModule(sources, basePath) {
68
- const map = /* @__PURE__ */ new Map();
69
- for (const source of sources) {
70
- if (!source.location) {
71
- continue;
72
- }
73
- const relativePath = getRelativePath(source.location, basePath);
74
- if (!relativePath) {
75
- continue;
76
- }
77
- const mod = extractModuleDirectory(relativePath);
78
- const existing = map.get(mod) ?? [];
79
- existing.push(source);
80
- map.set(mod, existing);
81
- }
82
- return map;
54
+ const map = /* @__PURE__ */ new Map();
55
+ for (const source of sources) {
56
+ if (!source.location) continue;
57
+ const relativePath = getRelativePath(source.location, basePath);
58
+ if (!relativePath) continue;
59
+ const mod = extractModuleDirectory(relativePath);
60
+ const existing = map.get(mod) ?? [];
61
+ existing.push(source);
62
+ map.set(mod, existing);
63
+ }
64
+ return map;
83
65
  }
84
66
  function getSourcesFromSchema(schema) {
85
- const extensions = schema.extensions;
86
- return extensions?.extendedSources ?? [];
67
+ return schema.extensions?.extendedSources ?? [];
87
68
  }
88
69
 
89
- // lib/printer/printer-autoload.ts
90
- import { camelCase } from "change-case-all";
70
+ //#endregion
71
+ //#region lib/printer/printer-autoload.ts
91
72
  function printAutoload(config, modules) {
92
- return [printImports(config, modules), printExport(modules)].join("\n\n");
73
+ return [printImports(config, modules), printExport(modules)].join("\n\n");
93
74
  }
94
75
  function printImports(config, modules) {
95
- return modules.map(
96
- (module) => `import ${camelCase(module)} from "./${module}/index${config.importExtension}"`
97
- ).join("\n");
76
+ return modules.map((module) => `import ${camelCase(module)} from "./${module}/index${config.importExtension}"`).join("\n");
98
77
  }
99
78
  function printExport(modules) {
100
- return `export default [${modules.map((m) => camelCase(m)).join(", ")}];`;
79
+ return `export default [${modules.map((m) => camelCase(m)).join(", ")}];`;
101
80
  }
102
81
 
103
- // lib/printer/printer-module.ts
104
- import { join, relative } from "@baeta/util-path";
105
- import { pascalCase } from "change-case-all";
106
-
107
- // lib/printer/printer-utils.ts
82
+ //#endregion
83
+ //#region lib/printer/printer-utils.ts
108
84
  function buildBlock({ name, lines }) {
109
- return [`${name} {`, ...lines.filter(Boolean).map(indent(2)), "};"].join("\n");
85
+ return [
86
+ `${name} {`,
87
+ ...lines.filter(Boolean).map(indent(2)),
88
+ "};"
89
+ ].join("\n");
110
90
  }
111
91
  function buildCodeBlock({ name, lines }) {
112
- const linesWithSep = lines.filter(Boolean).map(indent(2)).join(",\n");
113
- return [`${name} {`, linesWithSep, "}"].join("\n");
92
+ const linesWithSep = lines.filter(Boolean).map(indent(2)).join(",\n");
93
+ return [
94
+ `${name} {`,
95
+ linesWithSep,
96
+ "}"
97
+ ].join("\n");
114
98
  }
115
99
  function indent(size) {
116
- const space = new Array(size).fill(" ").join("");
117
- function indentInner(val) {
118
- return val.split("\n").map((line) => `${space}${line}`).join("\n");
119
- }
120
- return indentInner;
100
+ const space = new Array(size).fill(" ").join("");
101
+ function indentInner(val) {
102
+ return val.split("\n").map((line) => `${space}${line}`).join("\n");
103
+ }
104
+ return indentInner;
105
+ }
106
+ function makeRelativePathForImport(from, to) {
107
+ const res = posixPath(relative(from, to));
108
+ if (res.startsWith(".") || res.startsWith("/")) return res;
109
+ return `./${res}`;
121
110
  }
122
111
 
123
- // lib/printer/printer-module.ts
112
+ //#endregion
113
+ //#region lib/printer/printer-module.ts
124
114
  function printModuleImports(config, moduleName) {
125
- const typesDir = relative(join(config.modulesDir, moduleName), config.typesDir);
126
- return [
127
- 'import type { DocumentNode, GraphQLScalarType } from "graphql";',
128
- 'import * as Baeta from "@baeta/core/sdk";',
129
- `import extensions from "../extensions${config.importExtension}";`,
130
- `import type {Ctx, Info} from "../types${config.importExtension}";`,
131
- `import * as Types from "${typesDir}/types${config.importExtension}";`
132
- ].join("\n");
115
+ const typesDir = makeRelativePathForImport(join(config.modulesDir, moduleName), config.typesDir);
116
+ return [
117
+ "import type { DocumentNode, GraphQLScalarType } from \"graphql\";",
118
+ "import * as Baeta from \"@baeta/core/sdk\";",
119
+ `import extensions from "../extensions${config.importExtension}";`,
120
+ `import type {Ctx, Info} from "../types${config.importExtension}";`,
121
+ `import type * as Types from "${typesDir}/types${config.importExtension}";`
122
+ ].join("\n");
133
123
  }
134
124
  function printModuleMetadata(name, doc) {
135
- return buildCodeBlock({
136
- name: "const moduleMetadata =",
137
- lines: [
138
- `id: '${name}'`,
139
- `dirname: './${name}'`,
140
- `typedef: ${JSON.stringify(doc)} as unknown as DocumentNode`
141
- ]
142
- });
125
+ return buildCodeBlock({
126
+ name: "const moduleMetadata =",
127
+ lines: [
128
+ `id: '${name}'`,
129
+ `dirname: './${name}'`,
130
+ `typedef: ${JSON.stringify(doc)} as unknown as DocumentNode`
131
+ ]
132
+ });
143
133
  }
144
134
  function printBaetaModuleTypes(config) {
145
- return buildBlock({
146
- name: "interface BaetaModuleTypes",
147
- lines: [
148
- buildBlock({
149
- name: "Builders:",
150
- lines: printBaetaModuleTypesForFields(config, false)
151
- }),
152
- buildBlock({
153
- name: "Factories:",
154
- lines: [
155
- ...printBaetaModuleTypesForFields(config, true),
156
- ...printBaetaModuleTypesScalars(config)
157
- ]
158
- })
159
- ]
160
- });
135
+ return buildBlock({
136
+ name: "interface BaetaModuleTypes",
137
+ lines: [buildBlock({
138
+ name: "Builders:",
139
+ lines: printBaetaModuleTypesForFields(config, false)
140
+ }), buildBlock({
141
+ name: "Factories:",
142
+ lines: [...printBaetaModuleTypesForFields(config, true), ...printBaetaModuleTypesScalars(config)]
143
+ })]
144
+ });
161
145
  }
162
146
  function printBaetaModuleTypesForFields(config, isFactory) {
163
- return config.registry.defined.objects.map(
164
- (typeName) => printObjectTypeModuleType(typeName, config.registry.picks.objects, isFactory)
165
- ).filter(Boolean);
147
+ return config.registry.defined.objects.map((typeName) => printObjectTypeModuleType(typeName, config.registry.picks.objects, isFactory)).filter(Boolean);
166
148
  }
167
149
  function printObjectTypeModuleType(typeName, objects, isFactory) {
168
- const object = objects[typeName];
169
- if (!object) {
170
- return "";
171
- }
172
- const parentType = getParentType(typeName);
173
- const contextType = getContextType();
174
- const infoType = getInfoType();
175
- if (isFactory) {
176
- return `${typeName}: Baeta.TypeCompilerFactory<${parentType}, ${contextType}, ${infoType}, BaetaModuleObjectTypeFields['${typeName}']['Factory']>`;
177
- }
178
- return `${typeName}: Baeta.TypeMethods<${parentType}, ${contextType}, ${infoType}, BaetaModuleObjectTypeFields['${typeName}']['Builder'], BaetaModuleObjectTypeFields['${typeName}']['Factory']>`;
150
+ if (!objects[typeName]) return "";
151
+ const parentType = getParentType(typeName);
152
+ const contextType = getContextType();
153
+ const infoType = getInfoType();
154
+ if (isFactory) return `${typeName}: Baeta.TypeCompilerFactory<${parentType}, ${contextType}, ${infoType}, BaetaModuleObjectTypeFields['${typeName}']['Factory']>`;
155
+ return `${typeName}: Baeta.TypeMethods<${parentType}, ${contextType}, ${infoType}, BaetaModuleObjectTypeFields['${typeName}']['Builder'], BaetaModuleObjectTypeFields['${typeName}']['Factory']>`;
179
156
  }
180
157
  function printBaetaModuleTypesScalars(config) {
181
- return config.registry.defined.scalars.map((scalar) => `${scalar}: GraphQLScalarType`);
158
+ return config.registry.defined.scalars.map((scalar) => `${scalar}: GraphQLScalarType`);
182
159
  }
183
160
  function printModuleObjectTypeFields(config) {
184
- const objects = config.registry.defined.objects.map((typeName) => printObjectTypeFields(config, typeName, config.registry.picks.objects)).filter(Boolean);
185
- return buildBlock({
186
- name: "interface BaetaModuleObjectTypeFields",
187
- lines: objects
188
- });
161
+ return buildBlock({
162
+ name: "interface BaetaModuleObjectTypeFields",
163
+ lines: config.registry.defined.objects.map((typeName) => printObjectTypeFields(config, typeName, config.registry.picks.objects)).filter(Boolean)
164
+ });
189
165
  }
190
166
  function printObjectTypeFields(config, typeName, objects) {
191
- const fields = objects[typeName];
192
- if (!fields || fields.length === 0) {
193
- return "";
194
- }
195
- const fieldsBuilders = fields.map(
196
- (field) => printObjectTypeFieldBuilders(config, typeName, field)
197
- );
198
- const fieldsFactories = fields.map(
199
- (field) => printObjectTypeFieldFactories(config, typeName, field)
200
- );
201
- return buildBlock({
202
- name: `${typeName}:`,
203
- lines: [
204
- buildBlock({
205
- name: "Builder:",
206
- lines: fieldsBuilders
207
- }),
208
- buildBlock({
209
- name: "Factory:",
210
- lines: fieldsFactories
211
- })
212
- ]
213
- });
167
+ const fields = objects[typeName];
168
+ if (!fields || fields.length === 0) return "";
169
+ const fieldsBuilders = fields.map((field) => printObjectTypeFieldBuilders(config, typeName, field));
170
+ const fieldsFactories = fields.map((field) => printObjectTypeFieldFactories(config, typeName, field));
171
+ return buildBlock({
172
+ name: `${typeName}:`,
173
+ lines: [buildBlock({
174
+ name: "Builder:",
175
+ lines: fieldsBuilders
176
+ }), buildBlock({
177
+ name: "Factory:",
178
+ lines: fieldsFactories
179
+ })]
180
+ });
214
181
  }
215
182
  function printObjectTypeFieldBuilders(config, typeName, field) {
216
- const parentType = getParentType(typeName);
217
- const resultType = getResultType(config, typeName, field);
218
- const argumentsType = getArgsType(config, typeName, field);
219
- const contextType = getContextType();
220
- const infoType = getInfoType();
221
- const namespace = typeName === "Subscription" ? "SubscriptionMethods" : "FieldMethods";
222
- return `${field}: Baeta.${namespace}<${resultType}, ${parentType}, ${contextType}, ${argumentsType}, ${infoType}>`;
183
+ const parentType = getParentType(typeName);
184
+ const resultType = getResultType(config, typeName, field);
185
+ const argumentsType = getArgsType(config, typeName, field);
186
+ const contextType = getContextType();
187
+ const infoType = getInfoType();
188
+ return `${field}: Baeta.${typeName === "Subscription" ? "SubscriptionMethods" : "FieldMethods"}<${resultType}, ${parentType}, ${contextType}, ${argumentsType}, ${infoType}>`;
223
189
  }
224
190
  function printObjectTypeFieldFactories(config, typeName, field) {
225
- const parentType = getParentType(typeName);
226
- const resultType = getResultType(config, typeName, field);
227
- const argumentsType = getArgsType(config, typeName, field);
228
- const contextType = getContextType();
229
- const infoType = getInfoType();
230
- const namespace = typeName === "Subscription" ? "SubscriptionField" : "Field";
231
- return `${field}: Baeta.${namespace}<${resultType}, ${resultType}, ${parentType}, ${contextType}, ${argumentsType}, ${infoType}>`;
191
+ const parentType = getParentType(typeName);
192
+ const resultType = getResultType(config, typeName, field);
193
+ const argumentsType = getArgsType(config, typeName, field);
194
+ const contextType = getContextType();
195
+ const infoType = getInfoType();
196
+ return `${field}: Baeta.${typeName === "Subscription" ? "SubscriptionField" : "Field"}<${resultType}, ${resultType}, ${parentType}, ${contextType}, ${argumentsType}, ${infoType}>`;
232
197
  }
233
198
  function printModuleBuilder(config, moduleName) {
234
- const objectTypes = config.registry.defined.objects.map((typeName) => printObjectTypeBuilder(typeName, config.registry.picks.objects)).filter(Boolean);
235
- const builders = buildCodeBlock({
236
- name: "",
237
- lines: objectTypes
238
- });
239
- const typeNameResolvers = buildCodeBlock({
240
- name: "",
241
- lines: [...config.registry.defined.unions, ...config.registry.defined.interfaces].map(
242
- (name) => `${name}: ${printTypeNameResolver()}`
243
- )
244
- });
245
- const infoType = getInfoType();
246
- const contextType = getContextType();
247
- return [
248
- `export const ${pascalCase(moduleName)}Module = Baeta.createModuleBuilder<${contextType}, ${infoType}, BaetaModuleTypes['Builders'], BaetaModuleTypes['Factories']>(moduleMetadata.id, moduleMetadata.typedef,`,
249
- builders,
250
- ",",
251
- typeNameResolvers,
252
- `, ${getExtensionsVar()});`
253
- ].join("");
199
+ const builders = buildCodeBlock({
200
+ name: "",
201
+ lines: config.registry.defined.objects.map((typeName) => printObjectTypeBuilder(typeName, config.registry.picks.objects)).filter(Boolean)
202
+ });
203
+ const typeNameResolvers = buildCodeBlock({
204
+ name: "",
205
+ lines: [...config.registry.defined.unions, ...config.registry.defined.interfaces].map((name) => `${name}: ${printTypeNameResolver()}`)
206
+ });
207
+ const infoType = getInfoType();
208
+ const contextType = getContextType();
209
+ return [
210
+ `export const ${pascalCase(moduleName)}Module = Baeta.createModuleBuilder<${contextType}, ${infoType}, BaetaModuleTypes['Builders'], BaetaModuleTypes['Factories']>(moduleMetadata.id, moduleMetadata.typedef,`,
211
+ builders,
212
+ ",",
213
+ typeNameResolvers,
214
+ `, ${getExtensionsVar()});`
215
+ ].join("");
254
216
  }
255
217
  function printObjectTypeBuilder(typeName, objects) {
256
- const fields = objects[typeName]?.map((field) => printObjectTypeFieldBuilder(typeName, field));
257
- if (fields == null || fields.length === 0) {
258
- return "";
259
- }
260
- const content = buildCodeBlock({
261
- name: "",
262
- lines: fields
263
- });
264
- return `${typeName}: Baeta.createTypeBuilder("${typeName}",${content}, ${getExtensionsVar()})`;
218
+ const fields = objects[typeName]?.map((field) => printObjectTypeFieldBuilder(typeName, field));
219
+ if (fields == null || fields.length === 0) return "";
220
+ return `${typeName}: Baeta.createTypeBuilder("${typeName}",${buildCodeBlock({
221
+ name: "",
222
+ lines: fields
223
+ })}, ${getExtensionsVar()})`;
265
224
  }
266
225
  function printTypeNameResolver() {
267
- return "{ __resolveType: (source: {__typename: string}) => { return source.__typename; }}";
226
+ return "{ __resolveType: (source: {__typename: string}) => { return source.__typename; }}";
268
227
  }
269
228
  function getParentType(type) {
270
- if (["Query", "Mutation", "Subscription"].includes(type)) {
271
- return "{}";
272
- }
273
- return `Types.${type}`;
229
+ if ([
230
+ "Query",
231
+ "Mutation",
232
+ "Subscription"
233
+ ].includes(type)) return "{}";
234
+ return `Types.${type}`;
274
235
  }
275
236
  function getResultType(config, type, field) {
276
- const fieldType = config.fieldInfo.get(type)?.get(field)?.type;
277
- if (fieldType == null) {
278
- return "{}";
279
- }
280
- return fieldType;
237
+ const fieldType = config.fieldInfo.get(type)?.get(field)?.type;
238
+ if (fieldType == null) return "{}";
239
+ return fieldType;
281
240
  }
282
241
  function getArgsType(config, type, field) {
283
- const hasArgs = config.fieldInfo.get(type)?.get(field)?.hasArguments ?? false;
284
- if (!hasArgs) {
285
- return "{}";
286
- }
287
- const fieldUpper = field[0].toUpperCase() + field.slice(1);
288
- return `Types.${type}${fieldUpper}Args`;
242
+ if (!(config.fieldInfo.get(type)?.get(field)?.hasArguments ?? false)) return "{}";
243
+ return `Types.${type}${field[0].toUpperCase() + field.slice(1)}Args`;
289
244
  }
290
245
  function printObjectTypeFieldBuilder(typeName, field) {
291
- if (typeName === "Subscription") {
292
- return `${field}: Baeta.createSubscriptionBuilder("${field}", ${getExtensionsVar()})`;
293
- }
294
- return `${field}: Baeta.createFieldBuilder("${typeName}", "${field}", ${getExtensionsVar()})`;
246
+ if (typeName === "Subscription") return `${field}: Baeta.createSubscriptionBuilder("${field}", ${getExtensionsVar()})`;
247
+ return `${field}: Baeta.createFieldBuilder("${typeName}", "${field}", ${getExtensionsVar()})`;
295
248
  }
296
249
  function getContextType() {
297
- return "Ctx";
250
+ return "Ctx";
298
251
  }
299
252
  function getInfoType() {
300
- return "Info";
253
+ return "Info";
301
254
  }
302
255
  function getExtensionsVar() {
303
- return "extensions";
256
+ return "extensions";
304
257
  }
305
258
 
306
- // lib/printer/printer-templates.ts
307
- import { relative as relative2 } from "@baeta/util-path";
259
+ //#endregion
260
+ //#region lib/printer/printer-templates.ts
308
261
  function printTypesTemplate(options) {
309
- const importDir = relative2(options.modulesDir, options.typesDir);
310
- return `import type { GraphQLResolveInfo } from 'graphql';
311
- import type { BaseObjectTypes, BaseScalars } from '${importDir}/utility${options.importExtension}';
262
+ return `import type { GraphQLResolveInfo } from 'graphql';
263
+ import type { BaseObjectTypes, BaseScalars } from '${makeRelativePathForImport(options.modulesDir, options.typesDir)}/utility${options.importExtension}';
312
264
 
313
265
  export interface Scalars extends BaseScalars {}
314
266
 
@@ -320,491 +272,437 @@ export type Info = GraphQLResolveInfo;
320
272
  `;
321
273
  }
322
274
  function printExtensionsTemplate() {
323
- return `import { createExtensions } from '@baeta/core';
275
+ return `import { createExtensions } from '@baeta/core';
324
276
 
325
277
  export default createExtensions({});
326
278
  `;
327
279
  }
328
280
 
329
- // lib/printer/printer-types.ts
330
- import { pascalCase as pascalCase2 } from "change-case-all";
331
- import {
332
- Kind
333
- } from "graphql";
334
-
335
- // utils/scalar.ts
281
+ //#endregion
282
+ //#region utils/scalar.ts
336
283
  function isScalarType(definitionsMap, defaultScalars, type) {
337
- return definitionsMap.scalarTypeMap.has(type.name.value) || defaultScalars.includes(type.name.value);
284
+ return definitionsMap.scalarTypeMap.has(type.name.value) || defaultScalars.includes(type.name.value);
338
285
  }
339
286
 
340
- // lib/printer/printer-types.ts
287
+ //#endregion
288
+ //#region lib/printer/printer-types.ts
341
289
  function printUtilityTypes() {
342
- return [
343
- "export type Or<A, B> = void extends A ? B : A;",
344
- "export type Maybe<T> = T | null;"
345
- ].join("\n\n");
346
- }
347
- var defaultScalarTypes = {
348
- ID: "string",
349
- String: "string",
350
- Boolean: "boolean",
351
- Int: "number",
352
- Float: "number"
290
+ return ["export type Or<A, B> = void extends A ? B : A;", "export type Maybe<T> = T | null;"].join("\n\n");
291
+ }
292
+ const defaultScalarTypes = {
293
+ ID: "string",
294
+ String: "string",
295
+ Boolean: "boolean",
296
+ Int: "number",
297
+ Float: "number"
353
298
  };
354
299
  function printBaseScalars(config) {
355
- const defaultScalars = config.defaultScalars.map((scalar) => {
356
- const type = defaultScalarTypes[scalar];
357
- if (type == null) return null;
358
- return `${scalar}: ${type};`;
359
- }).filter((el) => el != null);
360
- const customScalars = [...config.globalDefinitions.scalarTypeMap.values()].map(
361
- (scalar) => `${scalar.name.value}: unknown;`
362
- );
363
- return buildBlock({
364
- name: "export type BaseScalars =",
365
- lines: [...defaultScalars, ...customScalars]
366
- });
300
+ const defaultScalars = config.defaultScalars.map((scalar) => {
301
+ const type = defaultScalarTypes[scalar];
302
+ if (type == null) return null;
303
+ return `${scalar}: ${type};`;
304
+ }).filter((el) => el != null);
305
+ const customScalars = [...config.globalDefinitions.scalarTypeMap.values()].map((scalar) => `${scalar.name.value}: unknown;`);
306
+ return buildBlock({
307
+ name: "export type BaseScalars =",
308
+ lines: [...defaultScalars, ...customScalars]
309
+ });
367
310
  }
368
311
  function printBaseObjectTypes(config) {
369
- const objectTypes = [...config.globalDefinitions.objectTypeMap.values()].map((t) => t.name.value);
370
- return buildBlock({
371
- name: "export interface BaseObjectTypes",
372
- lines: objectTypes.map((t) => `${t}: unknown;`)
373
- });
374
- }
375
- function printTypesHeaders() {
376
- return [
377
- 'import * as BaetaUtility from "./utility.ts";',
378
- 'import * as BaetaOverrides from "../modules/types.ts";',
379
- "",
380
- "export type Scalars = BaetaOverrides.Scalars;"
381
- ].join("\n");
312
+ return buildBlock({
313
+ name: "export interface BaseObjectTypes",
314
+ lines: [...config.globalDefinitions.objectTypeMap.values()].map((t) => t.name.value).map((t) => `${t}: unknown;`)
315
+ });
316
+ }
317
+ function printTypesHeaders(config) {
318
+ const overridesDir = makeRelativePathForImport(config.typesDir, config.modulesDir);
319
+ return [
320
+ `import type * as BaetaUtility from "./utility${config.importExtension}";`,
321
+ `import type * as BaetaOverrides from "${overridesDir}/types${config.importExtension}";`,
322
+ "",
323
+ "export type Scalars = BaetaOverrides.Scalars;"
324
+ ].join("\n");
382
325
  }
383
326
  function printRootTypesFromMap(config, rootTypes, map) {
384
- return [...map.values()].filter((type) => rootTypes.includes(type.name.value)).map((type) => printObjectType(config, type)).join("\n\n");
327
+ return [...map.values()].filter((type) => rootTypes.includes(type.name.value)).map((type) => printObjectType(config, type)).join("\n\n");
385
328
  }
386
329
  function printObjectTypeTypesFromMap(config, map) {
387
- return [...map.values()].map((type) => printObjectType(config, type));
330
+ return [...map.values()].map((type) => printObjectType(config, type));
388
331
  }
389
332
  function printObjectType(config, type) {
390
- const fields = type.fields?.map((field) => printObjectTypeField(config, field));
391
- return `export type ${type.name.value} = ${printOrObjectType(type, fields)}`;
333
+ const fields = type.fields?.map((field) => printObjectTypeField(config, field));
334
+ return `export type ${type.name.value} = ${printOrObjectType(type, fields)}`;
392
335
  }
393
336
  function printObjectTypeField(config, field) {
394
- const optionalMarker = printOptionalMarker(config, field.type);
395
- return `${field.name.value}${optionalMarker}: ${printType(config, field.type)}`;
337
+ const optionalMarker = printOptionalMarker(config, field.type);
338
+ return `${field.name.value}${optionalMarker}: ${printType(config, field.type)}`;
396
339
  }
397
340
  function printEnumTypesFromMap(map) {
398
- return [...map.values()].map(printEnumType);
341
+ return [...map.values()].map(printEnumType);
399
342
  }
400
343
  function printEnumType(type) {
401
- const values = type.values?.map((value) => `'${value.name.value}'`);
402
- return `export type ${type.name.value} = ${values?.join(" | ") || "never"}`;
344
+ const values = type.values?.map((value) => `'${value.name.value}'`);
345
+ return `export type ${type.name.value} = ${values?.join(" | ") || "never"}`;
403
346
  }
404
347
  function printInterfaceTypesFromMap(config, map) {
405
- return [...map.values()].map((type) => printInterfaceType(config, type));
348
+ return [...map.values()].map((type) => printInterfaceType(config, type));
406
349
  }
407
350
  function printInterfaceType(config, type) {
408
- const objectTypes = Array.from(config.globalDefinitions.objectTypeMap.values());
409
- const implementingTypes = objectTypes.filter(
410
- (t) => t.interfaces?.some((i) => i.name.value === type.name.value)
411
- );
412
- const types = implementingTypes.map((t) => printNamedTypeForInterface(t.name.value));
413
- return `export type ${type.name.value} = ${types.join(" | ") || "never"}`;
351
+ const types = Array.from(config.globalDefinitions.objectTypeMap.values()).filter((t) => t.interfaces?.some((i) => i.name.value === type.name.value)).map((t) => printNamedTypeForInterface(t.name.value));
352
+ return `export type ${type.name.value} = ${types.join(" | ") || "never"}`;
414
353
  }
415
354
  function printNamedTypeForInterface(name) {
416
- return `${name} & {__typename: "${name}"}`;
355
+ return `${name} & {__typename: "${name}"}`;
417
356
  }
418
357
  function printUnionTypesFromMap(config, map) {
419
- return [...map.values()].map((type) => printUnionType(config, type));
358
+ return [...map.values()].map((type) => printUnionType(config, type));
420
359
  }
421
360
  function printUnionType(config, type) {
422
- const types = type.types?.map((type2) => printNamedTypeForUnion(config, type2));
423
- return `export type ${type.name.value} = ${types?.join(" | ") || "never"}`;
361
+ const types = type.types?.map((type$1) => printNamedTypeForUnion(config, type$1));
362
+ return `export type ${type.name.value} = ${types?.join(" | ") || "never"}`;
424
363
  }
425
364
  function printNamedTypeForUnion(config, type) {
426
- return `${printNamedType(config, type, false)} & {__typename: "${type.name.value}"}`;
365
+ return `${printNamedType$1(config, type, false)} & {__typename: "${type.name.value}"}`;
427
366
  }
428
367
  function printInputObjectTypeTypesFromMap(config, map) {
429
- return [...map.values()].map((type) => printInputObjectType(config, type));
368
+ return [...map.values()].map((type) => printInputObjectType(config, type));
430
369
  }
431
370
  function printInputObjectType(config, type) {
432
- const fields = type.fields?.map((field) => printInputObjectTypeField(config, field));
433
- return buildBlock({
434
- name: `export type ${type.name.value} =`,
435
- lines: fields ?? []
436
- });
371
+ const fields = type.fields?.map((field) => printInputObjectTypeField(config, field));
372
+ return buildBlock({
373
+ name: `export type ${type.name.value} =`,
374
+ lines: fields ?? []
375
+ });
437
376
  }
438
377
  function printInputObjectTypeField(config, field) {
439
- const optionalMarker = printOptionalMarker(config, field.type);
440
- return `${field.name.value}${optionalMarker}: ${printType(config, field.type)}`;
378
+ const optionalMarker = printOptionalMarker(config, field.type);
379
+ return `${field.name.value}${optionalMarker}: ${printType(config, field.type)}`;
441
380
  }
442
381
  function printObjectTypeFieldsArgsFromMap(config, map) {
443
- return [...map.values()].flatMap((type) => printObjectTypeArgs(config, type));
382
+ return [...map.values()].flatMap((type) => printObjectTypeArgs(config, type));
444
383
  }
445
384
  function printObjectTypeArgs(config, type) {
446
- if (type.fields == null) {
447
- return [];
448
- }
449
- return type.fields.map((field) => printObjectTypeFieldArgs(config, type.name.value, field)).filter(Boolean);
385
+ if (type.fields == null) return [];
386
+ return type.fields.map((field) => printObjectTypeFieldArgs(config, type.name.value, field)).filter(Boolean);
450
387
  }
451
388
  function printObjectTypeFieldArgs(config, typeName, field) {
452
- const name = `${typeName + pascalCase2(field.name.value)}Args`;
453
- return buildBlock({
454
- name: `export type ${name} =`,
455
- lines: field.arguments?.map((arg) => printObjectTypeFieldArg(config, arg)) ?? []
456
- });
389
+ return buildBlock({
390
+ name: `export type ${`${typeName + pascalCase(field.name.value)}Args`} =`,
391
+ lines: field.arguments?.map((arg) => printObjectTypeFieldArg(config, arg)) ?? []
392
+ });
457
393
  }
458
394
  function printObjectTypeFieldArg(config, arg) {
459
- return `${arg.name.value}: ${printType(config, arg.type)}`;
395
+ return `${arg.name.value}: ${printType(config, arg.type)}`;
460
396
  }
461
397
  function printType(config, type, nullable = true) {
462
- switch (type.kind) {
463
- case Kind.NAMED_TYPE:
464
- return printNamedType(config, type, nullable);
465
- case Kind.LIST_TYPE:
466
- return printListType(config, type, nullable);
467
- case Kind.NON_NULL_TYPE:
468
- return printType(config, type.type, false);
469
- default:
470
- return type;
471
- }
398
+ switch (type.kind) {
399
+ case Kind.NAMED_TYPE: return printNamedType$1(config, type, nullable);
400
+ case Kind.LIST_TYPE: return printListType(config, type, nullable);
401
+ case Kind.NON_NULL_TYPE: return printType(config, type.type, false);
402
+ default: return type;
403
+ }
472
404
  }
473
405
  function printListType(config, type, nullable = true) {
474
- return printValue(config, `Array<${printType(config, type.type)}>`, nullable);
406
+ return printValue(config, `Array<${printType(config, type.type)}>`, nullable);
475
407
  }
476
- function printNamedType(config, type, nullable = true) {
477
- if (isScalarType(config.globalDefinitions, config.defaultScalars, type)) {
478
- return printScalarType(config, type, nullable);
479
- }
480
- return printValue(config, type.name.value, nullable);
408
+ function printNamedType$1(config, type, nullable = true) {
409
+ if (isScalarType(config.globalDefinitions, config.defaultScalars, type)) return printScalarType(config, type, nullable);
410
+ return printValue(config, type.name.value, nullable);
481
411
  }
482
412
  function printScalarType(config, type, nullable = true) {
483
- return printValue(config, `Scalars["${type.name.value}"]`, nullable);
413
+ return printValue(config, `Scalars["${type.name.value}"]`, nullable);
484
414
  }
485
415
  function printValue(config, value, nullable) {
486
- if (!nullable) {
487
- return value;
488
- }
489
- if (config.withMaybe) {
490
- return `BaetaUtility.Maybe<${value}>`;
491
- }
492
- return `${value} | null`;
416
+ if (!nullable) return value;
417
+ if (config.withMaybe) return `BaetaUtility.Maybe<${value}>`;
418
+ return `${value} | null`;
493
419
  }
494
420
  function printOptionalMarker(config, type) {
495
- return config.withOptional && type.kind !== Kind.NON_NULL_TYPE ? "?" : "";
421
+ return config.withOptional && type.kind !== Kind.NON_NULL_TYPE ? "?" : "";
496
422
  }
497
423
  function printOrObjectType(type, fields) {
498
- return `BaetaUtility.Or<BaetaOverrides.ObjectTypes["${type.name.value}"], {
499
- ${fields?.map(indent(2)).join("\n") ?? ""}
500
- }>`;
424
+ return `BaetaUtility.Or<BaetaOverrides.ObjectTypes["${type.name.value}"], {\n${fields?.map(indent(2)).join("\n") ?? ""}\n}>`;
501
425
  }
502
426
 
503
- // lib/visitors/definitions-map.ts
504
- import {
505
- visit
506
- } from "graphql";
427
+ //#endregion
428
+ //#region lib/visitors/definitions-map.ts
507
429
  function createRegistry() {
508
- return {
509
- scalarTypeMap: /* @__PURE__ */ new Map(),
510
- enumTypeMap: /* @__PURE__ */ new Map(),
511
- objectTypeMap: /* @__PURE__ */ new Map(),
512
- inputObjectTypeMap: /* @__PURE__ */ new Map(),
513
- unionTypeMap: /* @__PURE__ */ new Map(),
514
- interfaceTypeMap: /* @__PURE__ */ new Map()
515
- };
430
+ return {
431
+ scalarTypeMap: /* @__PURE__ */ new Map(),
432
+ enumTypeMap: /* @__PURE__ */ new Map(),
433
+ objectTypeMap: /* @__PURE__ */ new Map(),
434
+ inputObjectTypeMap: /* @__PURE__ */ new Map(),
435
+ unionTypeMap: /* @__PURE__ */ new Map(),
436
+ interfaceTypeMap: /* @__PURE__ */ new Map()
437
+ };
516
438
  }
517
439
  function createDefinitionsMapFromSources(sources) {
518
- const registry = createRegistry();
519
- for (const source of sources) {
520
- if (source.document) {
521
- collectTypesFromDocument(source.document, registry, ["Query", "Mutation", "Subscription"]);
522
- }
523
- }
524
- return registry;
440
+ const registry = createRegistry();
441
+ for (const source of sources) if (source.document) collectTypesFromDocument(source.document, registry, [
442
+ "Query",
443
+ "Mutation",
444
+ "Subscription"
445
+ ]);
446
+ return registry;
525
447
  }
526
448
  function createDefinitionsMapFromDocument(document) {
527
- const registry = createRegistry();
528
- collectTypesFromDocument(document, registry);
529
- return registry;
449
+ const registry = createRegistry();
450
+ collectTypesFromDocument(document, registry);
451
+ return registry;
530
452
  }
531
453
  function collectTypesFromDocument(document, registry, filterObjectTypes = []) {
532
- visit(document, {
533
- ScalarTypeDefinition(node) {
534
- if (registry.scalarTypeMap.has(node.name.value)) {
535
- throw new Error(`Scalar type ${node.name.value} already exists`);
536
- }
537
- registry.scalarTypeMap.set(node.name.value, node);
538
- },
539
- EnumTypeDefinition(node) {
540
- if (registry.enumTypeMap.has(node.name.value)) {
541
- throw new Error(`Enum type ${node.name.value} already exists, use 'extend' instead!`);
542
- }
543
- registry.enumTypeMap.set(node.name.value, node);
544
- },
545
- ObjectTypeDefinition(node) {
546
- if (filterObjectTypes.includes(node.name.value)) {
547
- return;
548
- }
549
- if (registry.objectTypeMap.has(node.name.value)) {
550
- throw new Error(`Object type ${node.name.value} already exists, use 'extend' instead!`);
551
- }
552
- registry.objectTypeMap.set(node.name.value, node);
553
- },
554
- InputObjectTypeDefinition(node) {
555
- if (registry.inputObjectTypeMap.has(node.name.value)) {
556
- throw new Error(`Input type ${node.name.value} already exists. Use 'extend' instead!`);
557
- }
558
- registry.inputObjectTypeMap.set(node.name.value, node);
559
- },
560
- UnionTypeDefinition(node) {
561
- if (registry.unionTypeMap.has(node.name.value)) {
562
- throw new Error(`Union type ${node.name.value} already exists, use 'extend' instead!`);
563
- }
564
- registry.unionTypeMap.set(node.name.value, node);
565
- },
566
- InterfaceTypeDefinition(node) {
567
- if (registry.interfaceTypeMap.has(node.name.value)) {
568
- throw new Error(`Interface type ${node.name.value} already exists. Use 'extend' instead!`);
569
- }
570
- registry.interfaceTypeMap.set(node.name.value, node);
571
- }
572
- });
454
+ visit(document, {
455
+ ScalarTypeDefinition(node) {
456
+ if (registry.scalarTypeMap.has(node.name.value)) throw new Error(`Scalar type ${node.name.value} already exists`);
457
+ registry.scalarTypeMap.set(node.name.value, node);
458
+ },
459
+ EnumTypeDefinition(node) {
460
+ if (registry.enumTypeMap.has(node.name.value)) throw new Error(`Enum type ${node.name.value} already exists, use 'extend' instead!`);
461
+ registry.enumTypeMap.set(node.name.value, node);
462
+ },
463
+ ObjectTypeDefinition(node) {
464
+ if (filterObjectTypes.includes(node.name.value)) return;
465
+ if (registry.objectTypeMap.has(node.name.value)) throw new Error(`Object type ${node.name.value} already exists, use 'extend' instead!`);
466
+ registry.objectTypeMap.set(node.name.value, node);
467
+ },
468
+ InputObjectTypeDefinition(node) {
469
+ if (registry.inputObjectTypeMap.has(node.name.value)) throw new Error(`Input type ${node.name.value} already exists. Use 'extend' instead!`);
470
+ registry.inputObjectTypeMap.set(node.name.value, node);
471
+ },
472
+ UnionTypeDefinition(node) {
473
+ if (registry.unionTypeMap.has(node.name.value)) throw new Error(`Union type ${node.name.value} already exists, use 'extend' instead!`);
474
+ registry.unionTypeMap.set(node.name.value, node);
475
+ },
476
+ InterfaceTypeDefinition(node) {
477
+ if (registry.interfaceTypeMap.has(node.name.value)) throw new Error(`Interface type ${node.name.value} already exists. Use 'extend' instead!`);
478
+ registry.interfaceTypeMap.set(node.name.value, node);
479
+ }
480
+ });
573
481
  }
574
482
 
575
- // lib/visitors/field-info.ts
576
- import { Kind as Kind2 } from "graphql";
483
+ //#endregion
484
+ //#region lib/visitors/field-info.ts
577
485
  function createFieldInfoMap(definitionsMap, defaultScalars) {
578
- const map = /* @__PURE__ */ new Map();
579
- for (const objectType of definitionsMap.objectTypeMap.values()) {
580
- const objectName = objectType.name.value;
581
- for (const field of objectType.fields ?? []) {
582
- const fieldName = field.name.value;
583
- const type = printNamedType2(definitionsMap, defaultScalars, field.type, true);
584
- const hasArguments = field.arguments != null && field.arguments.length > 0;
585
- const fieldMap = map.get(objectName) ?? /* @__PURE__ */ new Map();
586
- fieldMap.set(fieldName, { type, hasArguments });
587
- map.set(objectName, fieldMap);
588
- }
589
- }
590
- return map;
591
- }
592
- function printNamedType2(definitionsMap, defaultScalars, type, nullable = true) {
593
- const withNullable = nullable ? " | null" : "";
594
- switch (type.kind) {
595
- case Kind2.NAMED_TYPE:
596
- if (isScalarType(definitionsMap, defaultScalars, type)) {
597
- return `Types.Scalars["${type.name.value}"]${withNullable}`;
598
- }
599
- return `Types.${type.name.value}${withNullable}`;
600
- case Kind2.LIST_TYPE:
601
- return `Array<${printNamedType2(definitionsMap, defaultScalars, type.type, nullable)}>${withNullable}`;
602
- case Kind2.NON_NULL_TYPE:
603
- return printNamedType2(definitionsMap, defaultScalars, type.type, false);
604
- default:
605
- return type;
606
- }
486
+ const map = /* @__PURE__ */ new Map();
487
+ for (const objectType of definitionsMap.objectTypeMap.values()) {
488
+ const objectName = objectType.name.value;
489
+ for (const field of objectType.fields ?? []) {
490
+ const fieldName = field.name.value;
491
+ const type = printNamedType(definitionsMap, defaultScalars, field.type, true);
492
+ const hasArguments = field.arguments != null && field.arguments.length > 0;
493
+ const fieldMap = map.get(objectName) ?? /* @__PURE__ */ new Map();
494
+ fieldMap.set(fieldName, {
495
+ type,
496
+ hasArguments
497
+ });
498
+ map.set(objectName, fieldMap);
499
+ }
500
+ }
501
+ return map;
502
+ }
503
+ function printNamedType(definitionsMap, defaultScalars, type, nullable = true) {
504
+ const withNullable = nullable ? " | null" : "";
505
+ switch (type.kind) {
506
+ case Kind.NAMED_TYPE:
507
+ if (isScalarType(definitionsMap, defaultScalars, type)) return `Types.Scalars["${type.name.value}"]${withNullable}`;
508
+ return `Types.${type.name.value}${withNullable}`;
509
+ case Kind.LIST_TYPE: return `Array<${printNamedType(definitionsMap, defaultScalars, type.type, nullable)}>${withNullable}`;
510
+ case Kind.NON_NULL_TYPE: return printNamedType(definitionsMap, defaultScalars, type.type, false);
511
+ default: return type;
512
+ }
607
513
  }
608
514
 
609
- // lib/visitors/module-registry.ts
610
- import {
611
- visit as visit2
612
- } from "graphql";
613
- var registryKeys = ["objects", "interfaces", "unions", "scalars"];
515
+ //#endregion
516
+ //#region lib/visitors/module-registry.ts
517
+ const registryKeys = [
518
+ "objects",
519
+ "interfaces",
520
+ "unions",
521
+ "scalars"
522
+ ];
614
523
  function createModuleRegistry(document) {
615
- const picks = createObject(
616
- registryKeys,
617
- () => ({})
618
- );
619
- const defined = createObject(registryKeys, () => []);
620
- visit2(document, {
621
- ObjectTypeDefinition(node) {
622
- defined.objects.push(node.name.value);
623
- collectFields(node, picks.objects);
624
- },
625
- ObjectTypeExtension(node) {
626
- pushUnique(defined.objects, node.name.value);
627
- collectFields(node, picks.objects);
628
- },
629
- InterfaceTypeDefinition(node) {
630
- defined.interfaces.push(node.name.value);
631
- collectFields(node, picks.interfaces);
632
- },
633
- UnionTypeDefinition(node) {
634
- defined.unions.push(node.name.value);
635
- collectUnionTypes(node, picks);
636
- },
637
- ScalarTypeDefinition(node) {
638
- defined.scalars.push(node.name.value);
639
- }
640
- });
641
- return {
642
- defined,
643
- picks
644
- };
524
+ const picks = createObject(registryKeys, () => ({}));
525
+ const defined = createObject(registryKeys, () => []);
526
+ visit(document, {
527
+ ObjectTypeDefinition(node) {
528
+ defined.objects.push(node.name.value);
529
+ collectFields(node, picks.objects);
530
+ },
531
+ ObjectTypeExtension(node) {
532
+ pushUnique(defined.objects, node.name.value);
533
+ collectFields(node, picks.objects);
534
+ },
535
+ InterfaceTypeDefinition(node) {
536
+ defined.interfaces.push(node.name.value);
537
+ collectFields(node, picks.interfaces);
538
+ },
539
+ UnionTypeDefinition(node) {
540
+ defined.unions.push(node.name.value);
541
+ collectUnionTypes(node, picks);
542
+ },
543
+ ScalarTypeDefinition(node) {
544
+ defined.scalars.push(node.name.value);
545
+ }
546
+ });
547
+ return {
548
+ defined,
549
+ picks
550
+ };
645
551
  }
646
552
  function collectFields(node, picksObj) {
647
- const name = node.name.value;
648
- if (node.fields) {
649
- if (!picksObj[name]) {
650
- picksObj[name] = [];
651
- }
652
- for (const field of node.fields) {
653
- picksObj[name].push(field.name.value);
654
- }
655
- }
553
+ const name = node.name.value;
554
+ if (node.fields) {
555
+ if (!picksObj[name]) picksObj[name] = [];
556
+ for (const field of node.fields) picksObj[name].push(field.name.value);
557
+ }
656
558
  }
657
559
  function collectUnionTypes(node, picks) {
658
- const name = node.name.value;
659
- if (node.types) {
660
- if (!picks.unions[name]) {
661
- picks.unions[name] = [];
662
- }
663
- for (const type of node.types) {
664
- picks.unions[name].push(type.name.value);
665
- }
666
- }
560
+ const name = node.name.value;
561
+ if (node.types) {
562
+ if (!picks.unions[name]) picks.unions[name] = [];
563
+ for (const type of node.types) picks.unions[name].push(type.name.value);
564
+ }
667
565
  }
668
566
  function pushUnique(list, item) {
669
- if (!list.includes(item)) {
670
- list.push(item);
671
- }
567
+ if (!list.includes(item)) list.push(item);
672
568
  }
673
569
  function createObject(keys, valueFn) {
674
- const obj = {};
675
- for (const key of keys) {
676
- obj[key] = valueFn(key);
677
- }
678
- return obj;
570
+ const obj = {};
571
+ for (const key of keys) obj[key] = valueFn(key);
572
+ return obj;
679
573
  }
680
574
 
681
- // lib/codegen.ts
575
+ //#endregion
576
+ //#region lib/codegen.ts
682
577
  async function generate(options) {
683
- const { outputSchema, outputSchemaAst } = await loadSchema(
684
- options.schemas,
685
- options.cwd,
686
- options.loaders
687
- );
688
- const sources = getSourcesFromSchema(outputSchemaAst);
689
- const sourcesByModule = groupSourcesByModule(sources, options.modulesDir);
690
- const modules = Array.from(sourcesByModule.keys());
691
- const globalDefinitions = createDefinitionsMapFromDocument(outputSchema);
692
- const modulesDefinitions = createDefinitionsMapFromSources(sources);
693
- const defaultScalars = ["ID", "Int", "Float", "String", "Boolean"];
694
- const config = {
695
- globalDefinitions,
696
- withMaybe: false,
697
- withOptional: false,
698
- defaultScalars
699
- };
700
- const fieldInfo = createFieldInfoMap(globalDefinitions, defaultScalars);
701
- const typesContent = [
702
- printTypesHeaders(),
703
- printRootTypesFromMap(
704
- config,
705
- ["Query", "Mutation", "Subscription"],
706
- globalDefinitions.objectTypeMap
707
- ),
708
- ...printEnumTypesFromMap(globalDefinitions.enumTypeMap),
709
- ...printObjectTypeTypesFromMap(config, modulesDefinitions.objectTypeMap),
710
- ...printObjectTypeFieldsArgsFromMap(config, globalDefinitions.objectTypeMap),
711
- ...printInputObjectTypeTypesFromMap(config, globalDefinitions.inputObjectTypeMap),
712
- ...printInterfaceTypesFromMap(config, globalDefinitions.interfaceTypeMap),
713
- ...printUnionTypesFromMap(config, globalDefinitions.unionTypeMap)
714
- ].join("\n\n");
715
- const utilityContent = [
716
- printUtilityTypes(),
717
- printBaseScalars(config),
718
- printBaseObjectTypes(config)
719
- ].join("\n\n");
720
- const files = [
721
- {
722
- filename: join2(options.typesDir, "types.ts"),
723
- content: typesContent
724
- },
725
- {
726
- filename: join2(options.typesDir, "utility.ts"),
727
- content: utilityContent
728
- },
729
- {
730
- filename: join2(options.modulesDir, "index.ts"),
731
- content: printAutoload({ importExtension: options.importExtension }, modules)
732
- },
733
- {
734
- filename: join2(options.modulesDir, "types.ts"),
735
- content: printTypesTemplate({
736
- importExtension: options.importExtension,
737
- typesDir: options.typesDir,
738
- modulesDir: options.modulesDir
739
- }),
740
- options: {
741
- allowOverwrite: false,
742
- disableBiomeHeader: true,
743
- disableEslintHeader: true,
744
- disableGenerationNoticeHeader: true
745
- }
746
- },
747
- {
748
- filename: join2(options.modulesDir, "extensions.ts"),
749
- content: printExtensionsTemplate(),
750
- options: {
751
- allowOverwrite: false,
752
- disableBiomeHeader: true,
753
- disableEslintHeader: true,
754
- disableGenerationNoticeHeader: true
755
- }
756
- }
757
- ];
758
- for (const module of modules) {
759
- const sources2 = sourcesByModule.get(module);
760
- const documents = sources2?.map((s) => s.document).filter((el) => el != null) ?? [];
761
- if (documents.length === 0) continue;
762
- const document = concatAST(documents);
763
- const config2 = {
764
- typesDir: options.typesDir,
765
- fieldInfo,
766
- importExtension: options.importExtension,
767
- modulesDir: options.modulesDir,
768
- registry: createModuleRegistry(document)
769
- };
770
- files.push({
771
- filename: `src/modules/${module}/${options.moduleDefinitionName}`,
772
- content: [
773
- printModuleImports(config2, module),
774
- printModuleMetadata(module, document),
775
- printBaetaModuleTypes(config2),
776
- printModuleObjectTypeFields(config2),
777
- printModuleBuilder(config2, module)
778
- ].join("\n\n")
779
- });
780
- }
781
- return files;
578
+ const { outputSchema, outputSchemaAst } = await loadSchema$1(options.schemas, options.cwd, options.loaders);
579
+ const sources = getSourcesFromSchema(outputSchemaAst);
580
+ const sourcesByModule = groupSourcesByModule(sources, options.modulesDir);
581
+ const modules = Array.from(sourcesByModule.keys());
582
+ const globalDefinitions = createDefinitionsMapFromDocument(outputSchema);
583
+ const modulesDefinitions = createDefinitionsMapFromSources(sources);
584
+ const defaultScalars = [
585
+ "ID",
586
+ "Int",
587
+ "Float",
588
+ "String",
589
+ "Boolean"
590
+ ];
591
+ const config = {
592
+ globalDefinitions,
593
+ withMaybe: false,
594
+ withOptional: false,
595
+ defaultScalars,
596
+ importExtension: options.importExtension,
597
+ typesDir: options.typesDir,
598
+ modulesDir: options.modulesDir
599
+ };
600
+ const fieldInfo = createFieldInfoMap(globalDefinitions, defaultScalars);
601
+ const typesContent = [
602
+ printTypesHeaders(config),
603
+ printRootTypesFromMap(config, [
604
+ "Query",
605
+ "Mutation",
606
+ "Subscription"
607
+ ], globalDefinitions.objectTypeMap),
608
+ ...printEnumTypesFromMap(globalDefinitions.enumTypeMap),
609
+ ...printObjectTypeTypesFromMap(config, modulesDefinitions.objectTypeMap),
610
+ ...printObjectTypeFieldsArgsFromMap(config, globalDefinitions.objectTypeMap),
611
+ ...printInputObjectTypeTypesFromMap(config, globalDefinitions.inputObjectTypeMap),
612
+ ...printInterfaceTypesFromMap(config, globalDefinitions.interfaceTypeMap),
613
+ ...printUnionTypesFromMap(config, globalDefinitions.unionTypeMap)
614
+ ].join("\n\n");
615
+ const utilityContent = [
616
+ printUtilityTypes(),
617
+ printBaseScalars(config),
618
+ printBaseObjectTypes(config)
619
+ ].join("\n\n");
620
+ const files = [
621
+ {
622
+ filename: join(options.typesDir, "types.ts"),
623
+ content: typesContent
624
+ },
625
+ {
626
+ filename: join(options.typesDir, "utility.ts"),
627
+ content: utilityContent
628
+ },
629
+ {
630
+ filename: join(options.modulesDir, "index.ts"),
631
+ content: printAutoload({ importExtension: options.importExtension }, modules)
632
+ },
633
+ {
634
+ filename: join(options.modulesDir, "types.ts"),
635
+ content: printTypesTemplate({
636
+ importExtension: options.importExtension,
637
+ typesDir: options.typesDir,
638
+ modulesDir: options.modulesDir
639
+ }),
640
+ options: {
641
+ allowOverwrite: false,
642
+ disableBiomeV1Header: true,
643
+ disableBiomeV2Header: true,
644
+ disableEslintHeader: true,
645
+ disableGenerationNoticeHeader: true
646
+ }
647
+ },
648
+ {
649
+ filename: join(options.modulesDir, "extensions.ts"),
650
+ content: printExtensionsTemplate(),
651
+ options: {
652
+ allowOverwrite: false,
653
+ disableBiomeV1Header: true,
654
+ disableBiomeV2Header: true,
655
+ disableEslintHeader: true,
656
+ disableGenerationNoticeHeader: true
657
+ }
658
+ }
659
+ ];
660
+ for (const module of modules) {
661
+ const documents = sourcesByModule.get(module)?.map((s) => s.document).filter((el) => el != null) ?? [];
662
+ if (documents.length === 0) continue;
663
+ const document = concatAST(documents);
664
+ const config$1 = {
665
+ typesDir: options.typesDir,
666
+ fieldInfo,
667
+ importExtension: options.importExtension,
668
+ modulesDir: options.modulesDir,
669
+ registry: createModuleRegistry(document)
670
+ };
671
+ files.push({
672
+ filename: join(options.modulesDir, `/${module}/${options.moduleDefinitionName}`),
673
+ content: [
674
+ printModuleImports(config$1, module),
675
+ printModuleMetadata(module, document),
676
+ printBaetaModuleTypes(config$1),
677
+ printModuleObjectTypeFields(config$1),
678
+ printModuleBuilder(config$1, module)
679
+ ].join("\n\n")
680
+ });
681
+ }
682
+ return files;
782
683
  }
783
684
 
784
- // index.ts
685
+ //#endregion
686
+ //#region index.ts
785
687
  function graphqlPlugin() {
786
- return createPluginV1({
787
- name: "graphql",
788
- actionName: "GraphQL modules",
789
- watch: (options, watcher, reload) => {
790
- const handleChange = (file) => {
791
- if (isMatch(file.relativePath, options.schemas)) {
792
- reload(file);
793
- }
794
- };
795
- watcher.on("update", handleChange);
796
- watcher.on("delete", handleChange);
797
- },
798
- generate: async (ctx, next) => {
799
- const items = await generate(ctx.generatorOptions);
800
- for (const item of items) {
801
- ctx.fileManager.createAndAdd(item.filename, item.content, "graphql", item.options);
802
- }
803
- return next();
804
- }
805
- });
806
- }
807
- export {
808
- graphqlPlugin
809
- };
688
+ return createPluginV1({
689
+ name: "graphql",
690
+ actionName: "GraphQL modules",
691
+ watch: (options, watcher, reload) => {
692
+ const handleChange = (file) => {
693
+ if (isMatch(file.relativePath, options.schemas)) reload(file);
694
+ };
695
+ watcher.on("update", handleChange);
696
+ watcher.on("delete", handleChange);
697
+ },
698
+ generate: async (ctx, next) => {
699
+ const items = await generate(ctx.generatorOptions);
700
+ for (const item of items) ctx.fileManager.createAndAdd(item.filename, item.content, "graphql", item.options);
701
+ return next();
702
+ }
703
+ });
704
+ }
705
+
706
+ //#endregion
707
+ export { graphqlPlugin };
810
708
  //# sourceMappingURL=index.js.map