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

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.
@@ -7,5 +7,5 @@
7
7
  <link rel="prefetch" as="script" crossorigin href="/__nuxt-graphql-middleware/_nuxt/BvMfLM9s.js">
8
8
  <link rel="prefetch" as="style" crossorigin href="/__nuxt-graphql-middleware/_nuxt/error-500.TOCKLquH.css">
9
9
  <link rel="prefetch" as="script" crossorigin href="/__nuxt-graphql-middleware/_nuxt/DkAo05uu.js">
10
- <script type="module" src="/__nuxt-graphql-middleware/_nuxt/BawWjxPx.js" crossorigin></script></head><body><div id="__nuxt"></div><div id="teleports"></div><script type="application/json" data-nuxt-data="nuxt-app" data-ssr="false" id="__NUXT_DATA__">[{"prerenderedAt":1,"serverRendered":2},1742140131009,false]</script>
11
- <script>window.__NUXT__={};window.__NUXT__.config={public:{},app:{baseURL:"/__nuxt-graphql-middleware",buildId:"9b9c571e-ce30-465b-8174-06afbdca446b",buildAssetsDir:"/_nuxt/",cdnURL:""}}</script></body></html>
10
+ <script type="module" src="/__nuxt-graphql-middleware/_nuxt/BawWjxPx.js" crossorigin></script></head><body><div id="__nuxt"></div><div id="teleports"></div><script type="application/json" data-nuxt-data="nuxt-app" data-ssr="false" id="__NUXT_DATA__">[{"prerenderedAt":1,"serverRendered":2},1742651617305,false]</script>
11
+ <script>window.__NUXT__={};window.__NUXT__.config={public:{},app:{baseURL:"/__nuxt-graphql-middleware",buildId:"1d4cde1f-51c0-4bab-b233-3b063cc8ad1c",buildAssetsDir:"/_nuxt/",cdnURL:""}}</script></body></html>
@@ -7,5 +7,5 @@
7
7
  <link rel="prefetch" as="script" crossorigin href="/__nuxt-graphql-middleware/_nuxt/BvMfLM9s.js">
8
8
  <link rel="prefetch" as="style" crossorigin href="/__nuxt-graphql-middleware/_nuxt/error-500.TOCKLquH.css">
9
9
  <link rel="prefetch" as="script" crossorigin href="/__nuxt-graphql-middleware/_nuxt/DkAo05uu.js">
10
- <script type="module" src="/__nuxt-graphql-middleware/_nuxt/BawWjxPx.js" crossorigin></script></head><body><div id="__nuxt"></div><div id="teleports"></div><script type="application/json" data-nuxt-data="nuxt-app" data-ssr="false" id="__NUXT_DATA__">[{"prerenderedAt":1,"serverRendered":2},1742140131009,false]</script>
11
- <script>window.__NUXT__={};window.__NUXT__.config={public:{},app:{baseURL:"/__nuxt-graphql-middleware",buildId:"9b9c571e-ce30-465b-8174-06afbdca446b",buildAssetsDir:"/_nuxt/",cdnURL:""}}</script></body></html>
10
+ <script type="module" src="/__nuxt-graphql-middleware/_nuxt/BawWjxPx.js" crossorigin></script></head><body><div id="__nuxt"></div><div id="teleports"></div><script type="application/json" data-nuxt-data="nuxt-app" data-ssr="false" id="__NUXT_DATA__">[{"prerenderedAt":1,"serverRendered":2},1742651617305,false]</script>
11
+ <script>window.__NUXT__={};window.__NUXT__.config={public:{},app:{baseURL:"/__nuxt-graphql-middleware",buildId:"1d4cde1f-51c0-4bab-b233-3b063cc8ad1c",buildAssetsDir:"/_nuxt/",cdnURL:""}}</script></body></html>
@@ -1 +1 @@
1
- {"id":"9b9c571e-ce30-465b-8174-06afbdca446b","timestamp":1742140121878}
1
+ {"id":"1d4cde1f-51c0-4bab-b233-3b063cc8ad1c","timestamp":1742651608056}
@@ -0,0 +1 @@
1
+ {"id":"1d4cde1f-51c0-4bab-b233-3b063cc8ad1c","timestamp":1742651608056,"matcher":{"static":{},"wildcard":{},"dynamic":{}},"prerendered":[]}
@@ -7,5 +7,5 @@
7
7
  <link rel="prefetch" as="script" crossorigin href="/__nuxt-graphql-middleware/_nuxt/BvMfLM9s.js">
8
8
  <link rel="prefetch" as="style" crossorigin href="/__nuxt-graphql-middleware/_nuxt/error-500.TOCKLquH.css">
9
9
  <link rel="prefetch" as="script" crossorigin href="/__nuxt-graphql-middleware/_nuxt/DkAo05uu.js">
10
- <script type="module" src="/__nuxt-graphql-middleware/_nuxt/BawWjxPx.js" crossorigin></script></head><body><div id="__nuxt"></div><div id="teleports"></div><script type="application/json" data-nuxt-data="nuxt-app" data-ssr="false" id="__NUXT_DATA__">[{"prerenderedAt":1,"serverRendered":2},1742140131009,false]</script>
11
- <script>window.__NUXT__={};window.__NUXT__.config={public:{},app:{baseURL:"/__nuxt-graphql-middleware",buildId:"9b9c571e-ce30-465b-8174-06afbdca446b",buildAssetsDir:"/_nuxt/",cdnURL:""}}</script></body></html>
10
+ <script type="module" src="/__nuxt-graphql-middleware/_nuxt/BawWjxPx.js" crossorigin></script></head><body><div id="__nuxt"></div><div id="teleports"></div><script type="application/json" data-nuxt-data="nuxt-app" data-ssr="false" id="__NUXT_DATA__">[{"prerenderedAt":1,"serverRendered":2},1742651617305,false]</script>
11
+ <script>window.__NUXT__={};window.__NUXT__.config={public:{},app:{baseURL:"/__nuxt-graphql-middleware",buildId:"1d4cde1f-51c0-4bab-b233-3b063cc8ad1c",buildAssetsDir:"/_nuxt/",cdnURL:""}}</script></body></html>
package/dist/module.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "nuxt-graphql-middleware",
3
3
  "configKey": "graphqlMiddleware",
4
- "version": "5.0.0-alpha.6",
4
+ "version": "5.0.0-alpha.7",
5
5
  "compatibility": {
6
- "nuxt": ">=3.16.0"
6
+ "nuxt": ">=3.15.0"
7
7
  },
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "0.8.4",
package/dist/module.mjs CHANGED
@@ -1,11 +1,10 @@
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
3
  import fs from 'node:fs/promises';
5
4
  import { existsSync, promises } from 'node:fs';
6
5
  import { relative } from 'pathe';
7
6
  import { basename } from 'node:path';
8
- import { printSourceLocation, parse, OperationTypeNode, Source } from 'graphql';
7
+ import { printSourceLocation, parse, Source, OperationTypeNode } from 'graphql';
9
8
  import { Generator, FieldNotFoundError, TypeNotFoundError, FragmentNotFoundError } from 'graphql-typescript-deluxe';
10
9
  import color from 'picocolors';
11
10
  import { validateGraphQlDocuments } from '@graphql-tools/utils';
@@ -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.7";
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
  }
@@ -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,35 @@ class ModuleHelper {
936
868
  pathFromName
937
869
  ];
938
870
  this.nuxt.options.nitro.typescript.tsConfig.compilerOptions.paths[name + "/*"] = [pathFromName + "/*"];
871
+ this.inlineNitroExternals(name);
939
872
  }
940
873
  inlineNitroExternals(arg) {
941
874
  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);
875
+ this.nitroExternals.push(path);
876
+ this.transpile(path);
945
877
  }
946
- addTemplate(template, cb) {
947
- const content = cb(this);
948
- if (template.endsWith("d.ts")) {
949
- addTypeTemplate({
950
- filename: template,
878
+ transpile(path) {
879
+ this.nuxt.options.build.transpile.push(path);
880
+ }
881
+ applyBuildConfig() {
882
+ this.nuxt.options.nitro.externals ||= {};
883
+ this.nuxt.options.nitro.externals.inline ||= [];
884
+ this.nuxt.options.nitro.externals.inline.push(...this.nitroExternals);
885
+ }
886
+ addTemplate(template) {
887
+ if (template.build) {
888
+ const content = template.build(this).trim();
889
+ addTemplate({
890
+ filename: template.options.path + ".js",
951
891
  write: true,
952
892
  getContents: () => content
953
893
  });
954
- } else {
955
- addTemplate({
956
- filename: template,
894
+ }
895
+ if (template.buildTypes) {
896
+ const content = template.buildTypes(this).trim();
897
+ const filename = template.options.path + ".d.ts";
898
+ addTypeTemplate({
899
+ filename,
957
900
  write: true,
958
901
  getContents: () => content
959
902
  });
@@ -987,37 +930,68 @@ class ModuleHelper {
987
930
  }
988
931
  }
989
932
 
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'
933
+ function defineGeneratorTemplate(options, build, buildTypes) {
934
+ return {
935
+ type: "generator",
936
+ options,
937
+ build,
938
+ buildTypes
939
+ };
940
+ }
941
+ function defineStaticTemplate(options, build, buildTypes) {
942
+ return {
943
+ type: "static",
944
+ options,
945
+ build,
946
+ buildTypes
947
+ };
948
+ }
1004
949
 
1005
- const schema = ${JSON.stringify(schemaPath)}
950
+ const ClientOptions = defineStaticTemplate(
951
+ { path: "nuxt-graphql-middleware/client-options" },
952
+ (helper) => {
953
+ if (helper.paths.clientOptions) {
954
+ const pathRelative = helper.toModuleBuildRelative(
955
+ helper.paths.clientOptions
956
+ );
957
+ return `import clientOptions from '${pathRelative}'
958
+ export { clientOptions }
959
+ `;
960
+ }
961
+ return `export const clientOptions = {}`;
962
+ },
963
+ (helper) => {
964
+ if (helper.paths.clientOptions) {
965
+ const pathRelative = helper.toModuleBuildRelative(
966
+ helper.paths.clientOptions
967
+ );
968
+ return `import type { GraphqlClientOptions } from '${helper.paths.runtimeTypes}'
969
+ import { clientOptions } from '${pathRelative}'
1006
970
 
1007
- const documents: string[] = ${JSON.stringify(documents, null, 2)};
971
+ export type GraphqlClientContext = typeof clientOptions extends GraphqlClientOptions<infer R> ? R : {}
1008
972
 
1009
- const config: IGraphQLConfig = {
1010
- schema,
1011
- documents,
1012
- }
973
+ export { clientOptions }`;
974
+ }
975
+ return `
976
+ import type { GraphqlClientOptions } from '${helper.paths.runtimeTypes}'
977
+ export const clientOptions: GraphqlClientOptions
1013
978
 
1014
- export default config
979
+ export type GraphqlClientContext = {}
1015
980
  `;
1016
- }
981
+ }
982
+ );
1017
983
 
1018
- function DocumentTypes() {
1019
- return `
1020
- import type { Query, Mutation } from './operations'
984
+ const Documents = defineGeneratorTemplate(
985
+ { path: "nuxt-graphql-middleware/documents", virtual: true },
986
+ (output, helper) => {
987
+ return output.getOperationsFile({
988
+ exportName: "documents",
989
+ minify: !helper.isDev
990
+ }).getSource();
991
+ },
992
+ () => {
993
+ return `
994
+ import type { Query, Mutation } from './operation-types'
1021
995
 
1022
996
  declare module '#nuxt-graphql-middleware/documents' {
1023
997
  export type Documents = {
@@ -1026,43 +1000,154 @@ declare module '#nuxt-graphql-middleware/documents' {
1026
1000
  }
1027
1001
  export const documents: Documents
1028
1002
  }`;
1029
- }
1003
+ }
1004
+ );
1030
1005
 
1031
- function Types() {
1032
- return `declare module '#nuxt-graphql-middleware/sources' {
1033
- export const operationSources: Record<string, string>
1034
- }`;
1035
- }
1006
+ const GraphqlConfig = defineStaticTemplate(
1007
+ { path: "nuxt-graphql-middleware/graphql.config" },
1008
+ (helper) => {
1009
+ const patterns = helper.options.autoImportPatterns || [];
1010
+ const configPath = helper.resolvers.root.resolve(
1011
+ (helper.options.graphqlConfigFilePath || "").replace(
1012
+ "/graphql.config.ts",
1013
+ ""
1014
+ )
1015
+ );
1016
+ const schemaPath = "./" + relative(configPath, helper.paths.schema);
1017
+ const documents = patterns.filter((v) => !v.includes("!")).map((pattern) => {
1018
+ return "./" + relative(configPath, helper.resolvers.root.resolve(pattern));
1019
+ });
1020
+ return `const schema = ${JSON.stringify(schemaPath)}
1036
1021
 
1037
- function HelpersTypes() {
1038
- return `export const serverApiPrefix: string;
1039
- export function getEndpoint(operation: string, operationName: string): string`;
1022
+ const documents = ${JSON.stringify(documents, null, 2)};
1023
+
1024
+ const config = {
1025
+ schema,
1026
+ documents,
1040
1027
  }
1041
1028
 
1042
- function Helpers(helper) {
1043
- return `export const serverApiPrefix = '${helper.options.serverApiPrefix}'
1029
+ export default config
1030
+ `;
1031
+ },
1032
+ () => {
1033
+ return `
1034
+ import type { IGraphQLProject } from 'graphql-config'
1035
+
1036
+ type WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };
1037
+
1038
+ const config: WithRequired<IGraphQLProject, 'schema' | 'documents'>;
1039
+
1040
+ export default config;
1041
+ `;
1042
+ }
1043
+ );
1044
+
1045
+ const Helpers = defineStaticTemplate(
1046
+ { path: "nuxt-graphql-middleware/helpers" },
1047
+ (helper) => {
1048
+ return `export const serverApiPrefix = '${helper.options.serverApiPrefix}'
1044
1049
  export function getEndpoint(operation, operationName) {
1045
- return '${helper.options.serverApiPrefix}' + '/' + operation + '/' + operationName
1050
+ return serverApiPrefix + '/' + operation + '/' + operationName
1046
1051
  }
1047
1052
  `;
1048
- }
1053
+ },
1054
+ () => {
1055
+ return `export const serverApiPrefix: string;
1056
+ export function getEndpoint(operation: string, operationName: string): string`;
1057
+ }
1058
+ );
1059
+
1060
+ const NitroTypes = defineGeneratorTemplate(
1061
+ { path: "nuxt-graphql-middleware/nitro" },
1062
+ null,
1063
+ (output, helper) => {
1064
+ const operations = output.getCollectedOperations();
1065
+ const serverApiPrefix = helper.options.serverApiPrefix;
1066
+ const endpoints = [];
1067
+ const imports = [];
1068
+ for (const operation of operations) {
1069
+ imports.push(operation.typeName);
1070
+ const method = operation.operationType === OperationTypeNode.QUERY ? "get" : "post";
1071
+ endpoints.push(
1072
+ ` '${serverApiPrefix}/${operation.operationType}/${operation.graphqlName}': {
1073
+ '${method}': GraphqlResponse<${operation.typeName}>
1074
+ }`
1075
+ );
1076
+ }
1077
+ return `import type { GraphqlResponse } from './response'
1078
+ import type {
1079
+ ${imports.sort().join(",\n ")}
1080
+ } from './../graphql-operations'
1081
+
1082
+ declare module 'nitropack/types' {
1083
+ interface InternalApi {
1084
+ ${endpoints.sort().join("\n")}
1085
+ }
1086
+ }`;
1087
+ }
1088
+ );
1089
+
1090
+ const OperationTypesAll = defineGeneratorTemplate(
1091
+ { path: "nuxt-graphql-middleware/operation-types" },
1092
+ () => `export {}`,
1093
+ (output) => {
1094
+ return output.getOperationTypesFile({
1095
+ importFrom: "./../graphql-operations"
1096
+ }).getSource();
1097
+ }
1098
+ );
1099
+
1100
+ const Operations = defineGeneratorTemplate(
1101
+ { path: "graphql-operations/index" },
1102
+ (output) => {
1103
+ const typesFile = output.getOperations("js");
1104
+ return typesFile.getSource();
1105
+ },
1106
+ (output) => {
1107
+ const typesFile = output.getOperations("d.ts");
1108
+ return typesFile.getSource();
1109
+ }
1110
+ );
1111
+
1112
+ const Response = defineGeneratorTemplate(
1113
+ { path: "nuxt-graphql-middleware/response" },
1114
+ null,
1115
+ (output, helper) => {
1116
+ const operations = output.getCollectedOperations();
1117
+ const allTypes = operations.map((v) => v.typeName).sort();
1118
+ return `import type {
1119
+ ${allTypes.join(",\n ")}
1120
+ } from './../graphql-operations'
1121
+ import type { GraphqlResponseAdditions } from './server-options'
1122
+ import type { GraphqlServerResponse } from '${helper.paths.runtimeTypes}'
1123
+
1124
+ declare module '#nuxt-graphql-middleware/response' {
1125
+ export type GraphqlMiddlewareResponseUnion =
1126
+ | ${allTypes.join("\n | ") || "never"}
1049
1127
 
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 `
1128
+ export type GraphqlResponse<T> = GraphqlServerResponse<T> & GraphqlResponseAdditions
1129
+ export type GraphqlResponseTyped = GraphqlResponse<GraphqlMiddlewareResponseUnion>
1130
+ }`;
1131
+ }
1132
+ );
1133
+
1134
+ const ServerOptions = defineStaticTemplate(
1135
+ { path: "nuxt-graphql-middleware/server-options" },
1136
+ (helper) => {
1137
+ const resolvedPathRelative = helper.paths.serverOptions ? helper.toModuleBuildRelative(helper.paths.serverOptions) : null;
1138
+ const serverOptionsLine = resolvedPathRelative ? `import serverOptions from '${resolvedPathRelative}'` : `const serverOptions = {}`;
1139
+ return `
1054
1140
  ${serverOptionsLine}
1055
1141
  export { serverOptions }
1056
1142
  `;
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 `
1143
+ },
1144
+ (helper) => {
1145
+ const resolvedPathRelative = helper.paths.serverOptions ? helper.toModuleBuildRelative(helper.paths.serverOptions) : null;
1146
+ const serverOptionsLineTypes = resolvedPathRelative ? `import serverOptions from '${resolvedPathRelative}'` : `const serverOptions: GraphqlMiddlewareServerOptions = {}`;
1147
+ const moduleTypesPath = helper.toModuleBuildRelative(
1148
+ helper.resolvers.module.resolve("./types")
1149
+ );
1150
+ return `
1066
1151
  import type { GraphqlMiddlewareServerOptions } from '${moduleTypesPath}'
1067
1152
  ${serverOptionsLineTypes}
1068
1153
 
@@ -1070,39 +1155,44 @@ export type GraphqlResponseAdditions =
1070
1155
  typeof serverOptions extends GraphqlMiddlewareServerOptions<infer R, any, any> ? R : {}
1071
1156
 
1072
1157
  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
1158
  }
1084
- return `export const clientOptions = {}`;
1085
- }
1159
+ );
1086
1160
 
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 : {}
1096
-
1097
- export { clientOptions }`;
1161
+ const Sources = defineGeneratorTemplate(
1162
+ { path: "nuxt-graphql-middleware/sources" },
1163
+ (output, helper) => {
1164
+ const operations = output.getCollectedOperations();
1165
+ const srcDir = helper.paths.root;
1166
+ const lines = [];
1167
+ for (const operation of operations) {
1168
+ const filePath = relative(srcDir, operation.filePath);
1169
+ lines.push(
1170
+ `${operation.operationType}_${operation.graphqlName}: '${filePath}',`
1171
+ );
1172
+ }
1173
+ return `
1174
+ export const operationSources = {
1175
+ ${lines.join("\n ")}
1176
+ }
1177
+ `;
1178
+ },
1179
+ () => {
1180
+ return `export const operationSources: Record<string, string>`;
1098
1181
  }
1099
- return `
1100
- import type { GraphqlClientOptions } from '${helper.paths.runtimeTypes}'
1101
- export const clientOptions: GraphqlClientOptions
1182
+ );
1102
1183
 
1103
- export type GraphqlClientContext = {}
1104
- `;
1105
- }
1184
+ const TEMPLATES = [
1185
+ ClientOptions,
1186
+ Documents,
1187
+ GraphqlConfig,
1188
+ Helpers,
1189
+ NitroTypes,
1190
+ OperationTypesAll,
1191
+ Operations,
1192
+ Response,
1193
+ ServerOptions,
1194
+ Sources
1195
+ ];
1106
1196
 
1107
1197
  const DEVTOOLS_UI_ROUTE = "/__nuxt-graphql-middleware";
1108
1198
  const DEVTOOLS_UI_LOCAL_PORT = 3300;
@@ -1272,7 +1362,7 @@ const module = defineNuxtModule({
1272
1362
  configKey: "graphqlMiddleware",
1273
1363
  version,
1274
1364
  compatibility: {
1275
- nuxt: ">=3.16.0"
1365
+ nuxt: ">=3.15.0"
1276
1366
  }
1277
1367
  },
1278
1368
  defaults: defaultOptions,
@@ -1281,7 +1371,6 @@ const module = defineNuxtModule({
1281
1371
  const schemaProvider = new SchemaProvider(helper);
1282
1372
  await schemaProvider.init();
1283
1373
  const collector = new Collector(schemaProvider.getSchema(), helper);
1284
- await collector.init();
1285
1374
  nuxt.options.appConfig.graphqlMiddleware = {
1286
1375
  clientCacheEnabled: !!helper.options.clientCache?.enabled,
1287
1376
  clientCacheMaxSize: helper.options.clientCache?.maxSize ?? 100
@@ -1289,11 +1378,10 @@ const module = defineNuxtModule({
1289
1378
  nuxt.options.runtimeConfig.graphqlMiddleware = {
1290
1379
  graphqlEndpoint: helper.options.graphqlEndpoint || ""
1291
1380
  };
1292
- nuxt.options.build.transpile.push(
1293
- fileURLToPath(new URL("./runtime", import.meta.url))
1294
- );
1381
+ helper.transpile(fileURLToPath(new URL("./runtime", import.meta.url)));
1295
1382
  helper.inlineNitroExternals(helper.resolvers.module.resolve("./runtime"));
1296
1383
  helper.inlineNitroExternals(helper.paths.moduleBuildDir);
1384
+ helper.inlineNitroExternals(helper.paths.moduleTypesDir);
1297
1385
  helper.addAlias("#nuxt-graphql-middleware", helper.paths.moduleBuildDir);
1298
1386
  helper.addAlias("#graphql-operations", helper.paths.moduleTypesDir);
1299
1387
  helper.addPlugin("./runtime/plugins/provideState");
@@ -1320,22 +1408,15 @@ const module = defineNuxtModule({
1320
1408
  helper.addServerUtil("useGraphqlMutation");
1321
1409
  helper.addServerUtil("doGraphqlRequest");
1322
1410
  }
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);
1411
+ TEMPLATES.forEach((template) => {
1412
+ if (template.type === "static") {
1413
+ helper.addTemplate(template);
1414
+ } else {
1415
+ collector.addTemplate(template);
1416
+ }
1417
+ });
1418
+ helper.applyBuildConfig();
1419
+ await collector.init();
1339
1420
  if (!helper.isDev) {
1340
1421
  return;
1341
1422
  }
@@ -6,7 +6,7 @@ import type { GraphqlResponse } from '#nuxt-graphql-middleware/response';
6
6
  import type { RequestCacheOptions } from './../types.js';
7
7
  import type { AsyncData, AsyncDataOptions, NuxtError } from '#app';
8
8
  import type { DefaultAsyncDataValue } from 'nuxt/app/defaults';
9
- import type { Query } from '#nuxt-graphql-middleware/operations';
9
+ import type { Query } from '#nuxt-graphql-middleware/operation-types';
10
10
  type AsyncGraphqlQueryOptions<FetchOptions, ResT, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = DefaultAsyncDataValue> = AsyncDataOptions<ResT, DataT, PickKeys, DefaultT> & {
11
11
  /**
12
12
  * Control how the GraphQL response can be cached.
@@ -1,6 +1,6 @@
1
1
  import { type GetMutationArgs, type MutationObjectArgs, type GetMutationResult } from './../helpers/composables.js';
2
2
  import type { GraphqlResponse } from '#nuxt-graphql-middleware/response';
3
- import type { Mutation } from '#nuxt-graphql-middleware/operations';
3
+ import type { Mutation } from '#nuxt-graphql-middleware/operation-types';
4
4
  /**
5
5
  * Performs a GraphQL mutation.
6
6
  */
@@ -1,6 +1,6 @@
1
1
  import { type GetQueryArgs, type QueryObjectArgs, type GetQueryResult } from './../helpers/composables.js';
2
2
  import type { GraphqlResponse } from '#nuxt-graphql-middleware/response';
3
- import type { Query } from '#nuxt-graphql-middleware/operations';
3
+ import type { Query } from '#nuxt-graphql-middleware/operation-types';
4
4
  /**
5
5
  * Performs a GraphQL query.
6
6
  */
@@ -1,6 +1,6 @@
1
1
  import { type GetMutationArgs, type MutationObjectArgs, type GetMutationResult } from './../helpers/composables.js';
2
2
  import type { GraphqlResponse } from '#nuxt-graphql-middleware/response';
3
- import type { Mutation } from '#nuxt-graphql-middleware/operations';
3
+ import type { Mutation } from '#nuxt-graphql-middleware/operation-types';
4
4
  /**
5
5
  * Performs a GraphQL upload mutation.
6
6
  */
@@ -1,7 +1,7 @@
1
1
  import type { FetchOptions } from 'ofetch';
2
2
  import type { RequestCacheOptions } from './../types.js';
3
3
  import type { GraphqlClientContext } from '#nuxt-graphql-middleware/client-options';
4
- import type { Query, Mutation } from '#nuxt-graphql-middleware/operations';
4
+ import type { Query, Mutation } from '#nuxt-graphql-middleware/operation-types';
5
5
  export type GraphqlComposableOptions = {
6
6
  fetchOptions?: FetchOptions;
7
7
  graphqlCaching?: RequestCacheOptions;
@@ -3,7 +3,7 @@ import type { H3Event } from 'h3';
3
3
  import type { FetchOptions, FetchResponse, FetchError } from 'ofetch';
4
4
  import type { GraphqlMiddlewareRequestContext, GraphqlMiddlewareRuntimeConfig, GraphqlMiddlewareServerOptions } from './../../../types.js';
5
5
  import { type GraphqlMiddlewareOperation } from './../../settings/index.js';
6
- import type { Mutation, Query } from '#nuxt-graphql-middleware/operations';
6
+ import type { Mutation, Query } from '#nuxt-graphql-middleware/operation-types';
7
7
  export declare function isValidMutation(v?: string): v is keyof Mutation;
8
8
  export declare function isValidQuery(v?: string): v is keyof Query;
9
9
  export declare function queryParamToVariables(query: QueryObject): any;
@@ -1,6 +1,6 @@
1
1
  import type { GraphqlResponse } from '#nuxt-graphql-middleware/response';
2
2
  import { type GetMutationArgs, type MutationObjectArgs, type GetMutationResult } from './../../helpers/composables.js';
3
- import type { Mutation } from '#nuxt-graphql-middleware/operations';
3
+ import type { Mutation } from '#nuxt-graphql-middleware/operation-types';
4
4
  /**
5
5
  * Performs a GraphQL mutation.
6
6
  */
@@ -1,6 +1,6 @@
1
1
  import type { GraphqlResponse } from '#nuxt-graphql-middleware/response';
2
2
  import { type GetQueryArgs, type QueryObjectArgs, type GetQueryResult } from './../../helpers/composables.js';
3
- import type { Query } from '#nuxt-graphql-middleware/operations';
3
+ import type { Query } from '#nuxt-graphql-middleware/operation-types';
4
4
  /**
5
5
  * Performs a GraphQL query.
6
6
  */
@@ -1,66 +1,3 @@
1
- export declare enum Template {
2
- /**
3
- * Contains the TS definitions for all GraphQL queries, mutations and fragments.
4
- */
5
- OperationTypes = "graphql-operations/index.d.ts",
6
- /**
7
- * Contains the TS definitions for all GraphQL queries, mutations and fragments.
8
- */
9
- OperationTypesAll = "nuxt-graphql-middleware/operations.d.ts",
10
- /**
11
- * Contains the TS definitions for all GraphQL queries, mutations and fragments.
12
- */
13
- Enums = "graphql-operations/enums.ts",
14
- /**
15
- * Template for the middleware response types.
16
- */
17
- ResponseTypes = "nuxt-graphql-middleware/response.d.ts",
18
- /**
19
- * Types for the generated endpoints.
20
- */
21
- NitroTypes = "nuxt-graphql-middleware/nitro.d.ts",
22
- /**
23
- * Configuration template.
24
- */
25
- Helpers = "nuxt-graphql-middleware/helpers.mjs",
26
- /**
27
- * Configuration template types.
28
- */
29
- HelpersTypes = "nuxt-graphql-middleware/helpers.d.ts",
30
- /**
31
- * Exports a single opject containing the compiled queries and mutations.
32
- */
33
- Documents = "nuxt-graphql-middleware/documents.mjs",
34
- /**
35
- * Exports a single opject containing the compiled queries and mutations.
36
- */
37
- DocumentTypes = "nuxt-graphql-middleware/documents.d.ts",
38
- /**
39
- * Contains the source file paths for every operation.
40
- */
41
- OperationSources = "nuxt-graphql-middleware/sources.mjs",
42
- Types = "nuxt-graphql-middleware/types.d.ts",
43
- /**
44
- * The graphql-config file.
45
- */
46
- GraphqlConfig = "nuxt-graphql-middleware/graphql.config.ts",
47
- /**
48
- * Imports and exports the user's server options file.
49
- */
50
- ServerOptions = "nuxt-graphql-middleware/server-options.mjs",
51
- /**
52
- * Exports the server options types.
53
- */
54
- ServerOptionsTypes = "nuxt-graphql-middleware/server-options.d.ts",
55
- /**
56
- * Imports and exports the user's client options file.
57
- */
58
- ClientOptions = "nuxt-graphql-middleware/client-options.mjs",
59
- /**
60
- * Exports the client option specific types.
61
- */
62
- ClientOptionsTypes = "nuxt-graphql-middleware/client-options.d.ts"
63
- }
64
1
  export declare enum GraphqlMiddlewareOperation {
65
2
  Query = "query",
66
3
  Mutation = "mutation"
@@ -1,22 +1,3 @@
1
- export var Template = /* @__PURE__ */ ((Template2) => {
2
- Template2["OperationTypes"] = "graphql-operations/index.d.ts";
3
- Template2["OperationTypesAll"] = "nuxt-graphql-middleware/operations.d.ts";
4
- Template2["Enums"] = "graphql-operations/enums.ts";
5
- Template2["ResponseTypes"] = "nuxt-graphql-middleware/response.d.ts";
6
- Template2["NitroTypes"] = "nuxt-graphql-middleware/nitro.d.ts";
7
- Template2["Helpers"] = "nuxt-graphql-middleware/helpers.mjs";
8
- Template2["HelpersTypes"] = "nuxt-graphql-middleware/helpers.d.ts";
9
- Template2["Documents"] = "nuxt-graphql-middleware/documents.mjs";
10
- Template2["DocumentTypes"] = "nuxt-graphql-middleware/documents.d.ts";
11
- Template2["OperationSources"] = "nuxt-graphql-middleware/sources.mjs";
12
- Template2["Types"] = "nuxt-graphql-middleware/types.d.ts";
13
- Template2["GraphqlConfig"] = "nuxt-graphql-middleware/graphql.config.ts";
14
- Template2["ServerOptions"] = "nuxt-graphql-middleware/server-options.mjs";
15
- Template2["ServerOptionsTypes"] = "nuxt-graphql-middleware/server-options.d.ts";
16
- Template2["ClientOptions"] = "nuxt-graphql-middleware/client-options.mjs";
17
- Template2["ClientOptionsTypes"] = "nuxt-graphql-middleware/client-options.d.ts";
18
- return Template2;
19
- })(Template || {});
20
1
  export var GraphqlMiddlewareOperation = /* @__PURE__ */ ((GraphqlMiddlewareOperation2) => {
21
2
  GraphqlMiddlewareOperation2["Query"] = "query";
22
3
  GraphqlMiddlewareOperation2["Mutation"] = "mutation";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nuxt-graphql-middleware",
3
- "version": "5.0.0-alpha.6",
3
+ "version": "5.0.0-alpha.7",
4
4
  "description": "Module to perform GraphQL requests as a server middleware.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -69,7 +69,7 @@
69
69
  "@graphql-codegen/schema-ast": "^4.1.0",
70
70
  "@graphql-tools/utils": "^10.2.2",
71
71
  "@nuxt/devtools-kit": "1.3.7",
72
- "graphql-typescript-deluxe": "^0.0.6",
72
+ "graphql-typescript-deluxe": "^0.0.7",
73
73
  "inquirer": "^9.3.2",
74
74
  "minisearch": "^6.3.0",
75
75
  "picocolors": "^1.0.1"
@@ -1 +0,0 @@
1
- {"id":"9b9c571e-ce30-465b-8174-06afbdca446b","timestamp":1742140121878,"matcher":{"static":{},"wildcard":{},"dynamic":{}},"prerendered":[]}