nuxt-graphql-middleware 5.0.0-alpha.6 → 5.0.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/client/200.html +7 -7
  2. package/dist/client/404.html +7 -7
  3. package/dist/client/_nuxt/{BvMfLM9s.js → BLvMh1Ga.js} +1 -1
  4. package/dist/client/_nuxt/C9pb_2rp.js +2 -0
  5. package/dist/client/_nuxt/{DkAo05uu.js → CBwfSTyQ.js} +1 -1
  6. package/dist/client/_nuxt/{BtHrwWER.js → CPyoLiCY.js} +1 -1
  7. package/dist/client/_nuxt/{BawWjxPx.js → VpkRx2_e.js} +4 -4
  8. package/dist/client/_nuxt/builds/latest.json +1 -1
  9. package/dist/client/_nuxt/builds/meta/c16b1fe3-c3fb-4c15-952d-ba148d4025cb.json +1 -0
  10. package/dist/client/_nuxt/entry.Cn9qfNGa.css +1 -0
  11. package/dist/client/_nuxt/index.DGEN-H8t.css +1 -0
  12. package/dist/client/index.html +7 -7
  13. package/dist/module.d.mts +4 -198
  14. package/dist/module.d.ts +4 -198
  15. package/dist/module.json +2 -2
  16. package/dist/module.mjs +333 -246
  17. package/dist/runtime/composables/useAsyncGraphqlQuery.d.ts +1 -1
  18. package/dist/runtime/composables/useGraphqlMutation.d.ts +1 -1
  19. package/dist/runtime/composables/useGraphqlQuery.d.ts +1 -1
  20. package/dist/runtime/composables/useGraphqlState.js +1 -1
  21. package/dist/runtime/composables/useGraphqlUploadMutation.d.ts +1 -1
  22. package/dist/runtime/helpers/composables.d.ts +1 -1
  23. package/dist/runtime/server/helpers/index.d.ts +3 -3
  24. package/dist/runtime/server/helpers/index.js +1 -1
  25. package/dist/runtime/server/utils/doGraphqlRequest.d.ts +1 -1
  26. package/dist/runtime/server/utils/useGraphqlMutation.d.ts +1 -1
  27. package/dist/runtime/server/utils/useGraphqlQuery.d.ts +1 -1
  28. package/dist/runtime/serverOptions/defineGraphqlServerOptions.d.ts +1 -1
  29. package/dist/runtime/settings/index.d.ts +0 -63
  30. package/dist/runtime/settings/index.js +0 -19
  31. package/dist/runtime/types.d.ts +196 -1
  32. package/dist/types.d.mts +5 -5
  33. package/dist/types.d.ts +5 -5
  34. package/package.json +24 -28
  35. package/dist/client/_nuxt/B4KMzhZo.js +0 -2
  36. package/dist/client/_nuxt/builds/meta/9b9c571e-ce30-465b-8174-06afbdca446b.json +0 -1
  37. package/dist/client/_nuxt/entry.AjgXSF89.css +0 -1
  38. package/dist/client/_nuxt/index.D19Q16VT.css +0 -1
package/dist/module.mjs CHANGED
@@ -1,14 +1,13 @@
1
1
  import { fileURLToPath } from 'url';
2
2
  import { useLogger, addTemplate, addServerTemplate, addTypeTemplate, resolveAlias, createResolver, resolveFiles, addPlugin, addServerHandler, addImports, addServerImports, useNitro, defineNuxtModule } from '@nuxt/kit';
3
- import { Template } from '../dist/runtime/settings/index.js';
4
- import fs from 'node:fs/promises';
5
3
  import { existsSync, promises } from 'node:fs';
6
4
  import { relative } from 'pathe';
7
5
  import { basename } from 'node:path';
8
- import { printSourceLocation, parse, OperationTypeNode, Source } from 'graphql';
6
+ import { printSourceLocation, parse, Source, OperationTypeNode } from 'graphql';
9
7
  import { Generator, FieldNotFoundError, TypeNotFoundError, FragmentNotFoundError } from 'graphql-typescript-deluxe';
10
8
  import color from 'picocolors';
11
9
  import { validateGraphQlDocuments } from '@graphql-tools/utils';
10
+ import fs from 'node:fs/promises';
12
11
  import { generate } from '@graphql-codegen/cli';
13
12
  import * as PluginSchemaAst from '@graphql-codegen/schema-ast';
14
13
  import { loadSchema } from '@graphql-tools/load';
@@ -20,7 +19,7 @@ import { existsSync as existsSync$1 } from 'fs';
20
19
  import { onDevToolsInitialized, extendServerRpc } from '@nuxt/devtools-kit';
21
20
 
22
21
  const name = "nuxt-graphql-middleware";
23
- const version = "5.0.0-alpha.6";
22
+ const version = "5.0.0-alpha.8";
24
23
 
25
24
  const logger = useLogger(name);
26
25
  const defaultOptions = {
@@ -139,75 +138,6 @@ class CollectedFile {
139
138
  }
140
139
  }
141
140
 
142
- function ResponseTypes(operations, helper) {
143
- const allTypes = operations.map((v) => v.typeName).sort();
144
- return `import type {
145
- ${allTypes.join(",\n ")}
146
- } from './../graphql-operations'
147
- import type { GraphqlResponseAdditions } from './server-options'
148
- import type { GraphqlServerResponse } from '${helper.paths.runtimeTypes}'
149
-
150
- declare module '#nuxt-graphql-middleware/response' {
151
- export type GraphqlMiddlewareResponseUnion =
152
- | ${allTypes.join("\n | ") || "never"}
153
-
154
- export type GraphqlResponse<T> = GraphqlServerResponse<T> & GraphqlResponseAdditions
155
- export type GraphqlResponseTyped = GraphqlResponse<GraphqlMiddlewareResponseUnion>
156
- }`;
157
- }
158
-
159
- function NitroTypes(operations, serverApiPrefix) {
160
- const endpoints = [];
161
- const imports = [];
162
- for (const operation of operations) {
163
- imports.push(operation.typeName);
164
- const method = operation.operationType === OperationTypeNode.QUERY ? "get" : "post";
165
- endpoints.push(
166
- ` '${serverApiPrefix}/${operation.operationType}/${operation.graphqlName}': {
167
- '${method}': GraphqlResponse<${operation.typeName}>
168
- }`
169
- );
170
- }
171
- return `import type { GraphqlResponse } from './response'
172
- import type {
173
- ${imports.sort().join(",\n ")}
174
- } from './../graphql-operations'
175
-
176
- declare module 'nitropack/types' {
177
- interface InternalApi {
178
- ${endpoints.sort().join("\n")}
179
- }
180
- }`;
181
- }
182
-
183
- function OperationSources(operations, srcDir) {
184
- const lines = [];
185
- for (const operation of operations) {
186
- const filePath = relative(srcDir, operation.filePath);
187
- lines.push(
188
- `${operation.operationType}_${operation.graphqlName}: '${filePath}',`
189
- );
190
- }
191
- return `
192
- export const operationSources = {
193
- ${lines.join("\n ")}
194
- }
195
- `;
196
- }
197
-
198
- function OperationTypes(generatorOutput) {
199
- const typesFile = generatorOutput.getTypes();
200
- let output = "";
201
- const enumImports = typesFile.getTypeScriptEnumDependencies();
202
- if (enumImports.length) {
203
- output += `import type { ${enumImports.join(", ")} } from './enums'
204
-
205
- `;
206
- }
207
- output += typesFile.getSource();
208
- return output;
209
- }
210
-
211
141
  class Collector {
212
142
  constructor(schema, helper) {
213
143
  this.schema = schema;
@@ -240,9 +170,13 @@ class Collector {
240
170
  */
241
171
  rpcItems = /* @__PURE__ */ new Map();
242
172
  /**
243
- * The generated templates.
173
+ * The registered templates.
174
+ */
175
+ templates = [];
176
+ /**
177
+ * The generated template contents.
244
178
  */
245
- templates = /* @__PURE__ */ new Map();
179
+ templateResult = /* @__PURE__ */ new Map();
246
180
  async reset() {
247
181
  this.files.clear();
248
182
  this.generator.reset();
@@ -269,11 +203,8 @@ class Collector {
269
203
  errors
270
204
  };
271
205
  }
272
- updateTemplate(template, content) {
273
- this.templates.set(template, content);
274
- }
275
206
  getTemplate(template) {
276
- const content = this.templates.get(template);
207
+ const content = this.templateResult.get(template);
277
208
  if (content === void 0) {
278
209
  throw new Error(`Missing template content: ${template}`);
279
210
  }
@@ -286,33 +217,22 @@ class Collector {
286
217
  const output = this.generator.build();
287
218
  const operations = output.getCollectedOperations();
288
219
  const generatedCode = output.getGeneratedCode();
289
- this.updateTemplate(
290
- Template.Documents,
291
- output.getOperationsFile({
292
- exportName: "documents",
293
- minify: !this.helper.isDev
294
- }).getSource()
295
- );
296
- this.updateTemplate(
297
- Template.OperationTypesAll,
298
- output.getOperationTypesFile({
299
- importFrom: "./../graphql-operations"
300
- }).getSource()
301
- );
302
- this.updateTemplate(
303
- Template.NitroTypes,
304
- NitroTypes(operations, this.helper.options.serverApiPrefix)
305
- );
306
- this.updateTemplate(Template.OperationTypes, OperationTypes(output));
307
- this.updateTemplate(
308
- Template.ResponseTypes,
309
- ResponseTypes(operations, this.helper)
310
- );
311
- this.updateTemplate(Template.Enums, output.buildFile(["enum"]).getSource());
312
- this.updateTemplate(
313
- Template.OperationSources,
314
- OperationSources(operations, this.helper.paths.root)
315
- );
220
+ this.templates.forEach((template) => {
221
+ if (template.build) {
222
+ const filename = template.options.path + ".js";
223
+ this.templateResult.set(
224
+ filename,
225
+ template.build(output, this.helper).trim()
226
+ );
227
+ }
228
+ if (template.buildTypes) {
229
+ const filename = template.options.path + ".d.ts";
230
+ this.templateResult.set(
231
+ filename,
232
+ template.buildTypes(output, this.helper).trim()
233
+ );
234
+ }
235
+ });
316
236
  const fragmentMap = /* @__PURE__ */ new Map();
317
237
  const operationSourceMap = /* @__PURE__ */ new Map();
318
238
  for (const code of generatedCode) {
@@ -350,21 +270,23 @@ class Collector {
350
270
  if (hasErrors) {
351
271
  throw new Error("GraphQL errors");
352
272
  }
353
- for (const code of generatedCode) {
354
- const id = `${code.identifier}_${code.graphqlName}`;
355
- if (code.identifier === "fragment" || code.identifier === "mutation" || code.identifier === "query") {
356
- if (this.rpcItems.get(id)?.timestamp === code.timestamp) {
357
- continue;
273
+ if (this.helper.isDev) {
274
+ for (const code of generatedCode) {
275
+ const id = `${code.identifier}_${code.graphqlName}`;
276
+ if (code.identifier === "fragment" || code.identifier === "mutation" || code.identifier === "query") {
277
+ if (this.rpcItems.get(id)?.timestamp === code.timestamp) {
278
+ continue;
279
+ }
280
+ const fragmentDepdendencies = code.getGraphQLFragmentDependencies().map((name) => fragmentMap.get(name) || "").join("\n\n");
281
+ this.rpcItems.set(id, {
282
+ id,
283
+ timestamp: code.timestamp,
284
+ source: code.source + "\n\n" + fragmentDepdendencies,
285
+ name: code.graphqlName,
286
+ filePath: code.filePath,
287
+ identifier: code.identifier
288
+ });
358
289
  }
359
- const fragmentDepdendencies = code.getGraphQLFragmentDependencies().map((name) => fragmentMap.get(name) || "").join("\n\n");
360
- this.rpcItems.set(id, {
361
- id,
362
- timestamp: code.timestamp,
363
- source: code.source + "\n\n" + fragmentDepdendencies,
364
- name: code.graphqlName,
365
- filePath: code.filePath,
366
- identifier: code.identifier
367
- });
368
290
  }
369
291
  }
370
292
  }
@@ -403,7 +325,7 @@ class Collector {
403
325
  async init() {
404
326
  try {
405
327
  await this.initDocuments();
406
- } catch (e) {
328
+ } catch {
407
329
  if (this.helper.isDev) {
408
330
  const shouldRevalidate = await this.helper.prompt.confirm(
409
331
  "Do you want to revalidate the GraphQL documents?"
@@ -555,9 +477,10 @@ class Collector {
555
477
  * but a virtual template requires adding two templates.
556
478
  */
557
479
  addVirtualTemplate(template) {
558
- const getContents = () => this.getTemplate(template);
480
+ const filename = template.options.path + ".js";
481
+ const getContents = () => this.getTemplate(filename);
559
482
  addTemplate({
560
- filename: template,
483
+ filename,
561
484
  getContents
562
485
  });
563
486
  addServerTemplate({
@@ -567,7 +490,7 @@ class Collector {
567
490
  //
568
491
  // That way we can reference the same template using the alias in both
569
492
  // Nuxt and Nitro environments.
570
- filename: "#" + template.replace(".mjs", ""),
493
+ filename: "#" + template.options.path,
571
494
  getContents
572
495
  });
573
496
  }
@@ -575,24 +498,32 @@ class Collector {
575
498
  * Adds a template that dependes on Collector state.
576
499
  */
577
500
  addTemplate(template) {
578
- if (template.endsWith(".d.ts")) {
501
+ this.templates.push(template);
502
+ if (template.build) {
503
+ if (template.options.virtual) {
504
+ this.addVirtualTemplate(template);
505
+ } else {
506
+ const filename = template.options.path + ".js";
507
+ addTemplate({
508
+ filename,
509
+ write: true,
510
+ getContents: () => this.getTemplate(filename)
511
+ });
512
+ }
513
+ }
514
+ if (template.buildTypes) {
515
+ const filename = template.options.path + ".d.ts";
579
516
  addTypeTemplate(
580
517
  {
581
- filename: template,
518
+ filename,
582
519
  write: true,
583
- getContents: () => this.getTemplate(template)
520
+ getContents: () => this.getTemplate(filename)
584
521
  },
585
522
  {
586
523
  nuxt: true,
587
524
  nitro: true
588
525
  }
589
526
  );
590
- } else {
591
- addTemplate({
592
- filename: template,
593
- write: true,
594
- getContents: () => this.getTemplate(template)
595
- });
596
527
  }
597
528
  }
598
529
  }
@@ -853,6 +784,7 @@ class ModuleHelper {
853
784
  isDev;
854
785
  options;
855
786
  prompt = new ConsolePrompt();
787
+ nitroExternals = [];
856
788
  /**
857
789
  * Find the path to the graphqlMiddleware.serverOptions.ts file.
858
790
  */
@@ -936,24 +868,44 @@ class ModuleHelper {
936
868
  pathFromName
937
869
  ];
938
870
  this.nuxt.options.nitro.typescript.tsConfig.compilerOptions.paths[name + "/*"] = [pathFromName + "/*"];
871
+ this.nuxt.options.typescript.tsConfig ||= {};
872
+ this.nuxt.options.typescript.tsConfig.compilerOptions ||= {};
873
+ this.nuxt.options.typescript.tsConfig.compilerOptions.paths ||= {};
874
+ this.nuxt.options.typescript.tsConfig.compilerOptions.paths[name] = [
875
+ pathFromName
876
+ ];
877
+ this.nuxt.options.typescript.tsConfig.compilerOptions.paths[name + "/*"] = [
878
+ pathFromName + "/*"
879
+ ];
880
+ this.inlineNitroExternals(name);
939
881
  }
940
882
  inlineNitroExternals(arg) {
941
883
  const path = typeof arg === "string" ? arg : arg.dst;
942
- this.nuxt.options.nitro.externals = this.nuxt.options.nitro.externals || {};
943
- this.nuxt.options.nitro.externals.inline = this.nuxt.options.nitro.externals.inline || [];
944
- this.nuxt.options.nitro.externals.inline.push(path);
884
+ this.nitroExternals.push(path);
885
+ this.transpile(path);
945
886
  }
946
- addTemplate(template, cb) {
947
- const content = cb(this);
948
- if (template.endsWith("d.ts")) {
949
- addTypeTemplate({
950
- filename: template,
887
+ transpile(path) {
888
+ this.nuxt.options.build.transpile.push(path);
889
+ }
890
+ applyBuildConfig() {
891
+ this.nuxt.options.nitro.externals ||= {};
892
+ this.nuxt.options.nitro.externals.inline ||= [];
893
+ this.nuxt.options.nitro.externals.inline.push(...this.nitroExternals);
894
+ }
895
+ addTemplate(template) {
896
+ if (template.build) {
897
+ const content = template.build(this).trim();
898
+ addTemplate({
899
+ filename: template.options.path + ".js",
951
900
  write: true,
952
901
  getContents: () => content
953
902
  });
954
- } else {
955
- addTemplate({
956
- filename: template,
903
+ }
904
+ if (template.buildTypes) {
905
+ const content = template.buildTypes(this).trim();
906
+ const filename = template.options.path + ".d.ts";
907
+ addTypeTemplate({
908
+ filename,
957
909
  write: true,
958
910
  getContents: () => content
959
911
  });
@@ -987,37 +939,68 @@ class ModuleHelper {
987
939
  }
988
940
  }
989
941
 
990
- function GraphqlConfig(helper) {
991
- const patterns = helper.options.autoImportPatterns || [];
992
- const configPath = helper.resolvers.root.resolve(
993
- (helper.options.graphqlConfigFilePath || "").replace(
994
- "/graphql.config.ts",
995
- ""
996
- )
997
- );
998
- const schemaPath = "./" + relative(configPath, helper.paths.schema);
999
- const documents = patterns.filter((v) => !v.includes("!")).map((pattern) => {
1000
- return "./" + relative(configPath, helper.resolvers.root.resolve(pattern));
1001
- });
1002
- return `
1003
- import type { IGraphQLConfig } from 'graphql-config'
942
+ function defineGeneratorTemplate(options, build, buildTypes) {
943
+ return {
944
+ type: "generator",
945
+ options,
946
+ build,
947
+ buildTypes
948
+ };
949
+ }
950
+ function defineStaticTemplate(options, build, buildTypes) {
951
+ return {
952
+ type: "static",
953
+ options,
954
+ build,
955
+ buildTypes
956
+ };
957
+ }
1004
958
 
1005
- const schema = ${JSON.stringify(schemaPath)}
959
+ const ClientOptions = defineStaticTemplate(
960
+ { path: "nuxt-graphql-middleware/client-options" },
961
+ (helper) => {
962
+ if (helper.paths.clientOptions) {
963
+ const pathRelative = helper.toModuleBuildRelative(
964
+ helper.paths.clientOptions
965
+ );
966
+ return `import clientOptions from '${pathRelative}'
967
+ export { clientOptions }
968
+ `;
969
+ }
970
+ return `export const clientOptions = {}`;
971
+ },
972
+ (helper) => {
973
+ if (helper.paths.clientOptions) {
974
+ const pathRelative = helper.toModuleBuildRelative(
975
+ helper.paths.clientOptions
976
+ );
977
+ return `import type { GraphqlClientOptions } from '${helper.paths.runtimeTypes}'
978
+ import { clientOptions } from '${pathRelative}'
1006
979
 
1007
- const documents: string[] = ${JSON.stringify(documents, null, 2)};
980
+ export type GraphqlClientContext = typeof clientOptions extends GraphqlClientOptions<infer R> ? R : {}
1008
981
 
1009
- const config: IGraphQLConfig = {
1010
- schema,
1011
- documents,
1012
- }
982
+ export { clientOptions }`;
983
+ }
984
+ return `
985
+ import type { GraphqlClientOptions } from '${helper.paths.runtimeTypes}'
986
+ export const clientOptions: GraphqlClientOptions
1013
987
 
1014
- export default config
988
+ export type GraphqlClientContext = {}
1015
989
  `;
1016
- }
990
+ }
991
+ );
1017
992
 
1018
- function DocumentTypes() {
1019
- return `
1020
- import type { Query, Mutation } from './operations'
993
+ const Documents = defineGeneratorTemplate(
994
+ { path: "nuxt-graphql-middleware/documents", virtual: true },
995
+ (output, helper) => {
996
+ return output.getOperationsFile({
997
+ exportName: "documents",
998
+ minify: !helper.isDev
999
+ }).getSource();
1000
+ },
1001
+ () => {
1002
+ return `
1003
+ import type { Query, Mutation } from './operation-types'
1021
1004
 
1022
1005
  declare module '#nuxt-graphql-middleware/documents' {
1023
1006
  export type Documents = {
@@ -1026,83 +1009,196 @@ declare module '#nuxt-graphql-middleware/documents' {
1026
1009
  }
1027
1010
  export const documents: Documents
1028
1011
  }`;
1029
- }
1012
+ }
1013
+ );
1030
1014
 
1031
- function Types() {
1032
- return `declare module '#nuxt-graphql-middleware/sources' {
1033
- export const operationSources: Record<string, string>
1034
- }`;
1035
- }
1015
+ const GraphqlConfig = defineStaticTemplate(
1016
+ { path: "nuxt-graphql-middleware/graphql.config" },
1017
+ (helper) => {
1018
+ const patterns = helper.options.autoImportPatterns || [];
1019
+ const configPath = helper.resolvers.root.resolve(
1020
+ (helper.options.graphqlConfigFilePath || "").replace(
1021
+ "/graphql.config.ts",
1022
+ ""
1023
+ )
1024
+ );
1025
+ const schemaPath = "./" + relative(configPath, helper.paths.schema);
1026
+ const documents = patterns.filter((v) => !v.includes("!")).map((pattern) => {
1027
+ return "./" + relative(configPath, helper.resolvers.root.resolve(pattern));
1028
+ });
1029
+ return `const schema = ${JSON.stringify(schemaPath)}
1036
1030
 
1037
- function HelpersTypes() {
1038
- return `export const serverApiPrefix: string;
1039
- export function getEndpoint(operation: string, operationName: string): string`;
1031
+ const documents = ${JSON.stringify(documents, null, 2)};
1032
+
1033
+ const config = {
1034
+ schema,
1035
+ documents,
1040
1036
  }
1041
1037
 
1042
- function Helpers(helper) {
1043
- return `export const serverApiPrefix = '${helper.options.serverApiPrefix}'
1038
+ export default config
1039
+ `;
1040
+ },
1041
+ () => {
1042
+ return `
1043
+ import type { IGraphQLProject } from 'graphql-config'
1044
+
1045
+ type WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };
1046
+
1047
+ const config: WithRequired<IGraphQLProject, 'schema' | 'documents'>;
1048
+
1049
+ export default config;
1050
+ `;
1051
+ }
1052
+ );
1053
+
1054
+ const Helpers = defineStaticTemplate(
1055
+ { path: "nuxt-graphql-middleware/helpers" },
1056
+ (helper) => {
1057
+ return `export const serverApiPrefix = '${helper.options.serverApiPrefix}'
1044
1058
  export function getEndpoint(operation, operationName) {
1045
- return '${helper.options.serverApiPrefix}' + '/' + operation + '/' + operationName
1059
+ return serverApiPrefix + '/' + operation + '/' + operationName
1046
1060
  }
1047
1061
  `;
1048
- }
1062
+ },
1063
+ () => {
1064
+ return `export const serverApiPrefix: string;
1065
+ export function getEndpoint(operation: string, operationName: string): string`;
1066
+ }
1067
+ );
1068
+
1069
+ const NitroTypes = defineGeneratorTemplate(
1070
+ { path: "nuxt-graphql-middleware/nitro" },
1071
+ null,
1072
+ (output, helper) => {
1073
+ const operations = output.getCollectedOperations();
1074
+ const serverApiPrefix = helper.options.serverApiPrefix;
1075
+ const endpoints = [];
1076
+ const imports = [];
1077
+ for (const operation of operations) {
1078
+ imports.push(operation.typeName);
1079
+ const method = operation.operationType === OperationTypeNode.QUERY ? "get" : "post";
1080
+ endpoints.push(
1081
+ ` '${serverApiPrefix}/${operation.operationType}/${operation.graphqlName}': {
1082
+ '${method}': GraphqlResponse<${operation.typeName}>
1083
+ }`
1084
+ );
1085
+ }
1086
+ return `import type { GraphqlResponse } from './response'
1087
+ import type {
1088
+ ${imports.sort().join(",\n ")}
1089
+ } from './../graphql-operations'
1049
1090
 
1050
- function ServerOptions(helper) {
1051
- const resolvedPathRelative = helper.paths.serverOptions ? helper.toModuleBuildRelative(helper.paths.serverOptions) : null;
1052
- const serverOptionsLine = resolvedPathRelative ? `import serverOptions from '${resolvedPathRelative}'` : `const serverOptions = {}`;
1053
- return `
1091
+ declare module 'nitropack/types' {
1092
+ interface InternalApi {
1093
+ ${endpoints.sort().join("\n")}
1094
+ }
1095
+ }`;
1096
+ }
1097
+ );
1098
+
1099
+ const OperationTypesAll = defineGeneratorTemplate(
1100
+ { path: "nuxt-graphql-middleware/operation-types" },
1101
+ () => `export {}`,
1102
+ (output) => {
1103
+ return output.getOperationTypesFile({
1104
+ importFrom: "./../graphql-operations"
1105
+ }).getSource();
1106
+ }
1107
+ );
1108
+
1109
+ const Operations = defineGeneratorTemplate(
1110
+ { path: "graphql-operations/index" },
1111
+ (output) => {
1112
+ const typesFile = output.getOperations("js");
1113
+ return typesFile.getSource();
1114
+ },
1115
+ (output) => {
1116
+ const typesFile = output.getOperations("d.ts");
1117
+ return typesFile.getSource();
1118
+ }
1119
+ );
1120
+
1121
+ const Response = defineGeneratorTemplate(
1122
+ { path: "nuxt-graphql-middleware/response" },
1123
+ null,
1124
+ (output, helper) => {
1125
+ const operations = output.getCollectedOperations();
1126
+ const allTypes = operations.map((v) => v.typeName).sort();
1127
+ return `import type {
1128
+ ${allTypes.join(",\n ")}
1129
+ } from './../graphql-operations'
1130
+ import type { GraphqlResponseAdditions } from './server-options'
1131
+ import type { GraphqlServerResponse } from '${helper.paths.runtimeTypes}'
1132
+
1133
+ declare module '#nuxt-graphql-middleware/response' {
1134
+ export type GraphqlMiddlewareResponseUnion =
1135
+ | ${allTypes.join("\n | ") || "never"}
1136
+
1137
+ export type GraphqlResponse<T> = GraphqlServerResponse<T> & GraphqlResponseAdditions
1138
+ export type GraphqlResponseTyped = GraphqlResponse<GraphqlMiddlewareResponseUnion>
1139
+ }`;
1140
+ }
1141
+ );
1142
+
1143
+ const ServerOptions = defineStaticTemplate(
1144
+ { path: "nuxt-graphql-middleware/server-options" },
1145
+ (helper) => {
1146
+ const resolvedPathRelative = helper.paths.serverOptions ? helper.toModuleBuildRelative(helper.paths.serverOptions) : null;
1147
+ const serverOptionsLine = resolvedPathRelative ? `import serverOptions from '${resolvedPathRelative}'` : `const serverOptions = {}`;
1148
+ return `
1054
1149
  ${serverOptionsLine}
1055
1150
  export { serverOptions }
1056
1151
  `;
1057
- }
1058
-
1059
- function ServerOptionsTypes(helper) {
1060
- const resolvedPathRelative = helper.paths.serverOptions ? helper.toModuleBuildRelative(helper.paths.serverOptions) : null;
1061
- const serverOptionsLineTypes = resolvedPathRelative ? `import serverOptions from '${resolvedPathRelative}'` : `const serverOptions: GraphqlMiddlewareServerOptions = {}`;
1062
- const moduleTypesPath = helper.toModuleBuildRelative(
1063
- helper.resolvers.module.resolve("./types")
1064
- );
1065
- return `
1066
- import type { GraphqlMiddlewareServerOptions } from '${moduleTypesPath}'
1152
+ },
1153
+ (helper) => {
1154
+ const resolvedPathRelative = helper.paths.serverOptions ? helper.toModuleBuildRelative(helper.paths.serverOptions) : null;
1155
+ const serverOptionsLineTypes = resolvedPathRelative ? `import serverOptions from '${resolvedPathRelative}'` : `const serverOptions: GraphqlMiddlewareServerOptions = {}`;
1156
+ return `
1157
+ import type { GraphqlMiddlewareServerOptions } from '${helper.paths.runtimeTypes}'
1067
1158
  ${serverOptionsLineTypes}
1068
1159
 
1069
1160
  export type GraphqlResponseAdditions =
1070
1161
  typeof serverOptions extends GraphqlMiddlewareServerOptions<infer R, any, any> ? R : {}
1071
1162
 
1072
1163
  export { serverOptions }`;
1073
- }
1074
-
1075
- function ClientOptions(helper) {
1076
- if (helper.paths.clientOptions) {
1077
- const pathRelative = helper.toModuleBuildRelative(
1078
- helper.paths.clientOptions
1079
- );
1080
- return `import clientOptions from '${pathRelative}'
1081
- export { clientOptions }
1082
- `;
1083
1164
  }
1084
- return `export const clientOptions = {}`;
1085
- }
1086
-
1087
- function ClientOptionsTypes(helper) {
1088
- if (helper.paths.clientOptions) {
1089
- const pathRelative = helper.toModuleBuildRelative(
1090
- helper.paths.clientOptions
1091
- );
1092
- return `import type { GraphqlClientOptions } from '${helper.paths.runtimeTypes}'
1093
- import { clientOptions } from '${pathRelative}'
1094
-
1095
- export type GraphqlClientContext = typeof clientOptions extends GraphqlClientOptions<infer R> ? R : {}
1165
+ );
1096
1166
 
1097
- export { clientOptions }`;
1167
+ const Sources = defineGeneratorTemplate(
1168
+ { path: "nuxt-graphql-middleware/sources" },
1169
+ (output, helper) => {
1170
+ const operations = output.getCollectedOperations();
1171
+ const srcDir = helper.paths.root;
1172
+ const lines = [];
1173
+ for (const operation of operations) {
1174
+ const filePath = relative(srcDir, operation.filePath);
1175
+ lines.push(
1176
+ `${operation.operationType}_${operation.graphqlName}: '${filePath}',`
1177
+ );
1178
+ }
1179
+ return `
1180
+ export const operationSources = {
1181
+ ${lines.join("\n ")}
1182
+ }
1183
+ `;
1184
+ },
1185
+ () => {
1186
+ return `export const operationSources: Record<string, string>`;
1098
1187
  }
1099
- return `
1100
- import type { GraphqlClientOptions } from '${helper.paths.runtimeTypes}'
1101
- export const clientOptions: GraphqlClientOptions
1188
+ );
1102
1189
 
1103
- export type GraphqlClientContext = {}
1104
- `;
1105
- }
1190
+ const TEMPLATES = [
1191
+ ClientOptions,
1192
+ Documents,
1193
+ GraphqlConfig,
1194
+ Helpers,
1195
+ NitroTypes,
1196
+ OperationTypesAll,
1197
+ Operations,
1198
+ Response,
1199
+ ServerOptions,
1200
+ Sources
1201
+ ];
1106
1202
 
1107
1203
  const DEVTOOLS_UI_ROUTE = "/__nuxt-graphql-middleware";
1108
1204
  const DEVTOOLS_UI_LOCAL_PORT = 3300;
@@ -1272,7 +1368,7 @@ const module = defineNuxtModule({
1272
1368
  configKey: "graphqlMiddleware",
1273
1369
  version,
1274
1370
  compatibility: {
1275
- nuxt: ">=3.16.0"
1371
+ nuxt: ">=3.15.0"
1276
1372
  }
1277
1373
  },
1278
1374
  defaults: defaultOptions,
@@ -1281,7 +1377,6 @@ const module = defineNuxtModule({
1281
1377
  const schemaProvider = new SchemaProvider(helper);
1282
1378
  await schemaProvider.init();
1283
1379
  const collector = new Collector(schemaProvider.getSchema(), helper);
1284
- await collector.init();
1285
1380
  nuxt.options.appConfig.graphqlMiddleware = {
1286
1381
  clientCacheEnabled: !!helper.options.clientCache?.enabled,
1287
1382
  clientCacheMaxSize: helper.options.clientCache?.maxSize ?? 100
@@ -1289,11 +1384,10 @@ const module = defineNuxtModule({
1289
1384
  nuxt.options.runtimeConfig.graphqlMiddleware = {
1290
1385
  graphqlEndpoint: helper.options.graphqlEndpoint || ""
1291
1386
  };
1292
- nuxt.options.build.transpile.push(
1293
- fileURLToPath(new URL("./runtime", import.meta.url))
1294
- );
1387
+ helper.transpile(fileURLToPath(new URL("./runtime", import.meta.url)));
1295
1388
  helper.inlineNitroExternals(helper.resolvers.module.resolve("./runtime"));
1296
1389
  helper.inlineNitroExternals(helper.paths.moduleBuildDir);
1390
+ helper.inlineNitroExternals(helper.paths.moduleTypesDir);
1297
1391
  helper.addAlias("#nuxt-graphql-middleware", helper.paths.moduleBuildDir);
1298
1392
  helper.addAlias("#graphql-operations", helper.paths.moduleTypesDir);
1299
1393
  helper.addPlugin("./runtime/plugins/provideState");
@@ -1320,22 +1414,15 @@ const module = defineNuxtModule({
1320
1414
  helper.addServerUtil("useGraphqlMutation");
1321
1415
  helper.addServerUtil("doGraphqlRequest");
1322
1416
  }
1323
- helper.addTemplate(Template.ClientOptions, ClientOptions);
1324
- helper.addTemplate(Template.ClientOptionsTypes, ClientOptionsTypes);
1325
- helper.addTemplate(Template.DocumentTypes, DocumentTypes);
1326
- helper.addTemplate(Template.GraphqlConfig, GraphqlConfig);
1327
- helper.addTemplate(Template.Helpers, Helpers);
1328
- helper.addTemplate(Template.HelpersTypes, HelpersTypes);
1329
- helper.addTemplate(Template.ServerOptions, ServerOptions);
1330
- helper.addTemplate(Template.ServerOptionsTypes, ServerOptionsTypes);
1331
- helper.addTemplate(Template.Types, Types);
1332
- collector.addTemplate(Template.Enums);
1333
- collector.addTemplate(Template.NitroTypes);
1334
- collector.addTemplate(Template.OperationSources);
1335
- collector.addTemplate(Template.OperationTypes);
1336
- collector.addTemplate(Template.OperationTypesAll);
1337
- collector.addTemplate(Template.ResponseTypes);
1338
- collector.addVirtualTemplate(Template.Documents);
1417
+ TEMPLATES.forEach((template) => {
1418
+ if (template.type === "static") {
1419
+ helper.addTemplate(template);
1420
+ } else {
1421
+ collector.addTemplate(template);
1422
+ }
1423
+ });
1424
+ helper.applyBuildConfig();
1425
+ await collector.init();
1339
1426
  if (!helper.isDev) {
1340
1427
  return;
1341
1428
  }