@baeta/plugin-graphql 2.0.0-next.1 → 2.0.0-next.11

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