nitro-graphql 2.0.0-beta.1 → 2.0.0-beta.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.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { StandardSchemaV1 } from "./types/standard-schema.js";
2
- import { CodegenClientConfig, CodegenServerConfig, ExternalGraphQLService, FederationConfig, GenImport, GenericSdkConfig, NitroGraphQLOptions } from "./types/index.js";
2
+ import { ClientUtilsConfig, CodegenClientConfig, CodegenServerConfig, ExternalGraphQLService, ExternalServicePaths, FederationConfig, FileGenerationConfig, GenImport, GenericSdkConfig, NitroGraphQLOptions, PathsConfig, ScaffoldConfig, SdkConfig, TypesConfig } from "./types/index.js";
3
3
  import * as nitro_types0 from "nitro/types";
4
4
 
5
5
  //#region src/index.d.ts
6
6
  declare const _default: nitro_types0.NitroModule;
7
7
  //#endregion
8
- export { CodegenClientConfig, CodegenServerConfig, ExternalGraphQLService, FederationConfig, GenImport, GenericSdkConfig, NitroGraphQLOptions, StandardSchemaV1, _default as default };
8
+ export { ClientUtilsConfig, CodegenClientConfig, CodegenServerConfig, ExternalGraphQLService, ExternalServicePaths, FederationConfig, FileGenerationConfig, GenImport, GenericSdkConfig, NitroGraphQLOptions, PathsConfig, ScaffoldConfig, SdkConfig, StandardSchemaV1, TypesConfig, _default as default };
package/dist/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { generateDirectiveSchemas } from "./utils/directive-parser.js";
2
2
  import { generateLayerIgnorePatterns, getLayerAppDirectories, getLayerServerDirectories, relativeWithDot, scanDirectives, scanDocs, scanResolvers, scanSchemas, validateExternalServices } from "./utils/index.js";
3
+ import { writeFileIfNotExists } from "./utils/file-generator.js";
4
+ import { getScaffoldConfig, resolveFilePath, shouldGenerateScaffold } from "./utils/path-resolver.js";
3
5
  import { clientTypeGeneration, serverTypeGeneration } from "./utils/type-generation.js";
4
6
  import { rollupConfig } from "./rollup.js";
5
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
7
+ import { existsSync, mkdirSync } from "node:fs";
6
8
  import { fileURLToPath } from "node:url";
7
9
  import { watch } from "chokidar";
8
10
  import consola from "consola";
@@ -23,11 +25,13 @@ var src_default = defineNitroModule({
23
25
  }
24
26
  consola.info(`Configured ${nitro.options.graphql.externalServices.length} external GraphQL services`);
25
27
  }
28
+ const { getDefaultPaths: getDefaultPaths$1 } = await import("./utils/path-resolver.js");
29
+ const defaultPaths = getDefaultPaths$1(nitro);
26
30
  nitro.graphql ||= {
27
31
  buildDir: "",
28
32
  watchDirs: [],
29
- clientDir: "",
30
- serverDir: resolve(nitro.options.srcDir, "graphql"),
33
+ clientDir: defaultPaths.clientGraphql,
34
+ serverDir: defaultPaths.serverGraphql,
31
35
  dir: {
32
36
  build: relative(nitro.options.rootDir, nitro.options.buildDir),
33
37
  client: "graphql",
@@ -59,11 +63,8 @@ var src_default = defineNitroModule({
59
63
  const watchDirs = [];
60
64
  switch (nitro.options.framework.name) {
61
65
  case "nuxt": {
62
- if (!nitro.graphql.clientDir) {
63
- nitro.graphql.clientDir = resolve(nitro.options.rootDir, "app", "graphql");
64
- nitro.graphql.dir.client = "app/graphql";
65
- }
66
- if (!nitro.options.graphql?.serverDir) nitro.graphql.serverDir = resolve(nitro.options.rootDir, "server", "graphql");
66
+ nitro.graphql.dir.client = relative(nitro.options.rootDir, nitro.graphql.clientDir);
67
+ nitro.graphql.dir.server = relative(nitro.options.rootDir, nitro.graphql.serverDir);
67
68
  watchDirs.push(nitro.graphql.clientDir);
68
69
  const layerServerDirs = getLayerServerDirectories(nitro);
69
70
  const layerAppDirs = getLayerAppDirectories(nitro);
@@ -72,8 +73,10 @@ var src_default = defineNitroModule({
72
73
  break;
73
74
  }
74
75
  case "nitro":
75
- nitro.graphql.clientDir = resolve(nitro.options.rootDir, "graphql");
76
- nitro.graphql.dir.client = "graphql";
76
+ nitro.graphql.dir.client = relative(nitro.options.rootDir, nitro.graphql.clientDir);
77
+ nitro.graphql.dir.server = relative(nitro.options.rootDir, nitro.graphql.serverDir);
78
+ watchDirs.push(nitro.graphql.clientDir);
79
+ watchDirs.push(nitro.graphql.serverDir);
77
80
  break;
78
81
  default:
79
82
  }
@@ -90,7 +93,11 @@ var src_default = defineNitroModule({
90
93
  ignoreInitial: true,
91
94
  ignored: [...nitro.options.ignore, ...generateLayerIgnorePatterns(nitro)]
92
95
  }).on("all", async (_, path) => {
93
- if (path.endsWith(".graphql") || path.endsWith(".gql")) await clientTypeGeneration(nitro);
96
+ if (path.endsWith(".graphql") || path.endsWith(".gql")) if (path.includes(nitro.graphql.serverDir) || path.includes("server/graphql") || path.includes("server\\graphql")) {
97
+ await serverTypeGeneration(nitro);
98
+ await clientTypeGeneration(nitro);
99
+ await nitro.hooks.callHook("dev:reload");
100
+ } else await clientTypeGeneration(nitro);
94
101
  });
95
102
  nitro.hooks.hook("close", () => {
96
103
  watcher.close();
@@ -104,12 +111,53 @@ var src_default = defineNitroModule({
104
111
  nitro.scanDirectives = directives;
105
112
  await generateDirectiveSchemas(nitro, directives);
106
113
  nitro.hooks.hook("dev:start", async () => {
107
- nitro.scanSchemas = await scanSchemas(nitro);
108
- nitro.scanResolvers = await scanResolvers(nitro);
114
+ const schemas = await scanSchemas(nitro);
115
+ nitro.scanSchemas = schemas;
116
+ const resolvers = await scanResolvers(nitro);
117
+ nitro.scanResolvers = resolvers;
109
118
  const directives$1 = await scanDirectives(nitro);
110
119
  nitro.scanDirectives = directives$1;
111
120
  await generateDirectiveSchemas(nitro, directives$1);
112
- nitro.scanDocuments = await scanDocs(nitro);
121
+ const docs = await scanDocs(nitro);
122
+ nitro.scanDocuments = docs;
123
+ if (nitro.options.dev) {
124
+ consola.box({
125
+ title: "Nitro GraphQL",
126
+ message: [
127
+ `Framework: ${nitro.options.graphql?.framework || "Not configured"}`,
128
+ `Schemas: ${schemas.length}`,
129
+ `Resolvers: ${resolvers.length}`,
130
+ `Directives: ${directives$1.length}`,
131
+ `Documents: ${docs.length}`,
132
+ "",
133
+ "Debug Dashboard: /_nitro/graphql/debug"
134
+ ].join("\n"),
135
+ style: {
136
+ borderColor: "cyan",
137
+ borderStyle: "rounded"
138
+ }
139
+ });
140
+ if (resolvers.length > 0) {
141
+ const totalExports = resolvers.reduce((sum, r) => sum + r.imports.length, 0);
142
+ const typeCount = {
143
+ query: 0,
144
+ mutation: 0,
145
+ resolver: 0,
146
+ type: 0,
147
+ subscription: 0,
148
+ directive: 0
149
+ };
150
+ for (const resolver of resolvers) for (const imp of resolver.imports) if (imp.type in typeCount) typeCount[imp.type]++;
151
+ const breakdown = [];
152
+ if (typeCount.query > 0) breakdown.push(`${typeCount.query} query`);
153
+ if (typeCount.mutation > 0) breakdown.push(`${typeCount.mutation} mutation`);
154
+ if (typeCount.resolver > 0) breakdown.push(`${typeCount.resolver} resolver`);
155
+ if (typeCount.type > 0) breakdown.push(`${typeCount.type} type`);
156
+ if (typeCount.subscription > 0) breakdown.push(`${typeCount.subscription} subscription`);
157
+ if (typeCount.directive > 0) breakdown.push(`${typeCount.directive} directive`);
158
+ if (breakdown.length > 0) consola.success(`[nitro-graphql] ${totalExports} resolver export(s): ${breakdown.join(", ")}`);
159
+ } else consola.warn("[nitro-graphql] No resolvers found. Check /_nitro/graphql/debug for details.");
160
+ }
113
161
  });
114
162
  await rollupConfig(nitro);
115
163
  await serverTypeGeneration(nitro);
@@ -139,6 +187,14 @@ var src_default = defineNitroModule({
139
187
  handler: join(runtime, "health"),
140
188
  method: "GET"
141
189
  });
190
+ if (nitro.options.dev) {
191
+ nitro.options.handlers.push({
192
+ route: "/_nitro/graphql/debug",
193
+ handler: join(runtime, "debug"),
194
+ method: "GET"
195
+ });
196
+ consola.info("[nitro-graphql] Debug dashboard available at: /_nitro/graphql/debug");
197
+ }
142
198
  if (nitro.options.imports) {
143
199
  nitro.options.imports.presets ??= [];
144
200
  nitro.options.imports.presets.push({
@@ -158,11 +214,20 @@ var src_default = defineNitroModule({
158
214
  nitro.hooks.hook("rollup:before", (_, rollupConfig$1) => {
159
215
  const manualChunks = rollupConfig$1.output?.manualChunks;
160
216
  const chunkFiles = rollupConfig$1.output?.chunkFileNames;
161
- if (!rollupConfig$1.output.inlineDynamicImports) rollupConfig$1.output.manualChunks = (id, meta) => {
162
- if (id.endsWith(".graphql") || id.endsWith(".gql")) return "schemas";
163
- if (id.endsWith(".resolver.ts")) return "resolvers";
164
- if (typeof manualChunks === "function") return manualChunks(id, meta);
165
- };
217
+ if (!rollupConfig$1.output.inlineDynamicImports) {
218
+ rollupConfig$1.output.manualChunks = (id, meta) => {
219
+ if (id.endsWith(".graphql") || id.endsWith(".gql")) return "schemas";
220
+ if (id.endsWith(".resolver.ts")) return "resolvers";
221
+ if (typeof manualChunks === "function") return manualChunks(id, meta);
222
+ };
223
+ rollupConfig$1.output.advancedChunks = { groups: [{
224
+ name: "schemas",
225
+ test: /\.(?:graphql|gql)$/
226
+ }, {
227
+ name: "resolvers",
228
+ test: /\.resolver\.ts$/
229
+ }] };
230
+ }
166
231
  rollupConfig$1.output.chunkFileNames = (chunkInfo) => {
167
232
  if (chunkInfo.moduleIds && chunkInfo.moduleIds.some((id) => id.endsWith(".graphql") || id.endsWith(".resolver.ts") || id.endsWith(".gql"))) return `chunks/graphql/[name].mjs`;
168
233
  if (typeof chunkFiles === "function") return chunkFiles(chunkInfo);
@@ -186,33 +251,39 @@ var src_default = defineNitroModule({
186
251
  const nuxtOptions = nitro._nuxt?.options;
187
252
  if (nuxtOptions) nuxtOptions.nitroGraphqlExternalServices = nitro.options.graphql?.externalServices || [];
188
253
  });
189
- if (!existsSync(join(nitro.options.rootDir, "graphql.config.ts"))) {
190
- const schemaPath = relativeWithDot(nitro.options.rootDir, resolve(nitro.graphql.buildDir, "schema.graphql"));
191
- const documentsPath = relativeWithDot(nitro.options.rootDir, resolve(nitro.graphql.clientDir, "**/*.{graphql,js,ts,jsx,tsx}"));
192
- writeFileSync(join(nitro.options.rootDir, "graphql.config.ts"), `
254
+ if (shouldGenerateScaffold(nitro)) {
255
+ const placeholders = getDefaultPaths$1(nitro);
256
+ const scaffoldConfig = getScaffoldConfig(nitro);
257
+ const graphqlConfigPath = resolveFilePath(scaffoldConfig.graphqlConfig, scaffoldConfig.enabled, true, "graphql.config.ts", placeholders);
258
+ if (graphqlConfigPath) writeFileIfNotExists(graphqlConfigPath, `
193
259
  import type { IGraphQLConfig } from 'graphql-config'
194
260
 
195
261
  export default <IGraphQLConfig> {
196
262
  projects: {
197
263
  default: {
198
264
  schema: [
199
- '${schemaPath}',
265
+ '${relativeWithDot(nitro.options.rootDir, resolve(nitro.graphql.buildDir, "schema.graphql"))}',
200
266
  ],
201
267
  documents: [
202
- '${documentsPath}',
268
+ '${relativeWithDot(nitro.options.rootDir, resolve(nitro.graphql.clientDir, "**/*.{graphql,js,ts,jsx,tsx}"))}',
203
269
  ],
204
270
  },
205
271
  },
206
- }`, "utf-8");
207
- }
208
- if (!existsSync(nitro.graphql.serverDir)) mkdirSync(nitro.graphql.serverDir, { recursive: true });
209
- if (!existsSync(join(nitro.graphql.serverDir, "schema.ts"))) writeFileSync(join(nitro.graphql.serverDir, "schema.ts"), `export default defineSchema({
272
+ }`, "graphql.config.ts");
273
+ const serverSchemaPath = resolveFilePath(scaffoldConfig.serverSchema, scaffoldConfig.enabled, true, "{serverGraphql}/schema.ts", placeholders);
274
+ const serverConfigPath = resolveFilePath(scaffoldConfig.serverConfig, scaffoldConfig.enabled, true, "{serverGraphql}/config.ts", placeholders);
275
+ const serverContextPath = resolveFilePath(scaffoldConfig.serverContext, scaffoldConfig.enabled, true, "{serverGraphql}/context.ts", placeholders);
276
+ if (serverSchemaPath || serverConfigPath || serverContextPath) {
277
+ if (!existsSync(nitro.graphql.serverDir)) mkdirSync(nitro.graphql.serverDir, { recursive: true });
278
+ }
279
+ if (serverSchemaPath) writeFileIfNotExists(serverSchemaPath, `export default defineSchema({
210
280
 
211
281
  })
212
- `, "utf-8");
213
- if (!existsSync(join(nitro.graphql.serverDir, "config.ts"))) writeFileSync(join(nitro.graphql.serverDir, "config.ts"), `// Example GraphQL config file please change it to your needs
282
+ `, "server schema.ts");
283
+ if (serverConfigPath) writeFileIfNotExists(serverConfigPath, `// Example GraphQL config file please change it to your needs
214
284
  // import * as tables from '../drizzle/schema/index'
215
285
  // import { useDatabase } from '../utils/useDb'
286
+ import { defineGraphQLConfig } from 'nitro-graphql/utils/define'
216
287
 
217
288
  export default defineGraphQLConfig({
218
289
  // graphql-yoga example config
@@ -225,8 +296,8 @@ export default defineGraphQLConfig({
225
296
  // }
226
297
  // },
227
298
  })
228
- `, "utf-8");
229
- if (!existsSync(join(nitro.graphql.serverDir, "context.ts"))) writeFileSync(join(nitro.graphql.serverDir, "context.ts"), `// Example context definition - please change it to your needs
299
+ `, "server config.ts");
300
+ if (serverContextPath) writeFileIfNotExists(serverContextPath, `// Example context definition - please change it to your needs
230
301
  // import type { Database } from '../utils/useDb'
231
302
 
232
303
  declare module 'h3' {
@@ -241,11 +312,12 @@ declare module 'h3' {
241
312
  // }
242
313
  // }
243
314
  }
244
- }`, "utf-8");
245
- if (existsSync(join(nitro.graphql.serverDir, "context.d.ts"))) {
246
- consola.warn("nitro-graphql: Found context.d.ts file. Please rename it to context.ts for the new structure.");
247
- consola.info("The context file should now be context.ts instead of context.d.ts");
248
- }
315
+ }`, "server context.ts");
316
+ if (existsSync(join(nitro.graphql.serverDir, "context.d.ts"))) {
317
+ consola.warn("nitro-graphql: Found context.d.ts file. Please rename it to context.ts for the new structure.");
318
+ consola.info("The context file should now be context.ts instead of context.d.ts");
319
+ }
320
+ } else consola.info("[nitro-graphql] Scaffold file generation is disabled (library mode)");
249
321
  }
250
322
  });
251
323
 
package/dist/rollup.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { getImportId, scanGraphql } from "./utils/index.js";
2
2
  import { clientTypeGeneration, serverTypeGeneration } from "./utils/type-generation.js";
3
+ import { fileURLToPath } from "node:url";
3
4
  import { resolve } from "pathe";
4
5
  import { readFile } from "node:fs/promises";
5
6
  import { parse } from "graphql";
@@ -12,32 +13,82 @@ async function rollupConfig(app) {
12
13
  virtualDirectives(app);
13
14
  getGraphQLConfig(app);
14
15
  virtualModuleConfig(app);
16
+ virtualDebugInfo(app);
15
17
  app.hooks.hook("rollup:before", (nitro, rollupConfig$1) => {
16
18
  rollupConfig$1.plugins = rollupConfig$1.plugins || [];
17
- const { include = /\.(graphql|gql)$/i, exclude, validate = false } = app.options.graphql?.loader || {};
19
+ const { include = /\.(?:graphql|gql)$/i, exclude, validate = false } = app.options.graphql?.loader || {};
18
20
  if (Array.isArray(rollupConfig$1.plugins)) {
19
21
  rollupConfig$1.plugins.push({
20
- name: "nitro-graphql",
21
- async load(id) {
22
- if (exclude?.test?.(id)) return null;
23
- if (!include.test(id)) return null;
24
- try {
25
- const content = await readFile(id, "utf-8");
26
- if (validate) parse(content);
27
- return `export default ${JSON.stringify(content)}`;
28
- } catch (error) {
29
- if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return null;
30
- const message = error instanceof Error ? error.message : String(error);
31
- this.error(`Failed to read GraphQL file ${id}: ${message}`);
22
+ name: "nitro-graphql:virtual",
23
+ resolveId: {
24
+ order: "pre",
25
+ filter: { id: /^#nitro-graphql\// },
26
+ async handler(id, parent, options) {
27
+ if (id.startsWith("#nitro-graphql/")) return `\0virtual:${id}`;
28
+ if (parent?.startsWith("\0virtual:#nitro-graphql")) {
29
+ const runtimeDir = fileURLToPath(new URL("routes", import.meta.url));
30
+ const internalRes = await this.resolve(id, runtimeDir, {
31
+ skipSelf: true,
32
+ ...options
33
+ });
34
+ if (internalRes) return internalRes;
35
+ }
36
+ }
37
+ },
38
+ load: {
39
+ order: "pre",
40
+ filter: { id: /^\0virtual:#nitro-graphql\// },
41
+ handler(id) {
42
+ if (id.startsWith("\0virtual:#nitro-graphql/")) {
43
+ const moduleName = id.slice(9);
44
+ const generator = app.options.virtual?.[moduleName];
45
+ if (typeof generator === "function") try {
46
+ return {
47
+ code: generator(),
48
+ moduleType: "js"
49
+ };
50
+ } catch (error) {
51
+ const message = error instanceof Error ? error.message : String(error);
52
+ this.error(`Failed to generate virtual module ${moduleName}: ${message}`);
53
+ }
54
+ else this.error(`No generator function found for virtual module ${moduleName}`);
55
+ }
32
56
  }
33
57
  }
34
58
  });
35
59
  rollupConfig$1.plugins.push({
60
+ name: "nitro-graphql",
61
+ resolveId: {
62
+ order: "pre",
63
+ handler(id) {
64
+ if (/\.(?:graphql|gql)$/i.test(id)) return null;
65
+ }
66
+ },
67
+ load: {
68
+ order: "pre",
69
+ async handler(id) {
70
+ if (exclude?.test?.(id)) return null;
71
+ if (!include.test(id)) return null;
72
+ try {
73
+ const content = await readFile(id, "utf-8");
74
+ if (validate) parse(content);
75
+ return `export default ${JSON.stringify(content)}`;
76
+ } catch (error) {
77
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return null;
78
+ const message = error instanceof Error ? error.message : String(error);
79
+ this.error(`Failed to read GraphQL file ${id}: ${message}`);
80
+ }
81
+ }
82
+ }
83
+ });
84
+ if (app.options.dev) rollupConfig$1.plugins.push({
36
85
  name: "nitro-graphql-watcher",
37
- async buildStart() {
38
- const graphqlFiles = await scanGraphql(nitro);
39
- for (const file of graphqlFiles) this.addWatchFile(file);
40
- this.addWatchFile(app.graphql.serverDir);
86
+ buildStart: {
87
+ order: "pre",
88
+ async handler() {
89
+ const graphqlFiles = await scanGraphql(nitro);
90
+ for (const file of graphqlFiles) this.addWatchFile(file);
91
+ }
41
92
  }
42
93
  });
43
94
  }
@@ -48,65 +99,117 @@ async function rollupConfig(app) {
48
99
  });
49
100
  }
50
101
  function virtualSchemas(app) {
51
- const getSchemas = () => {
52
- return [...app.scanSchemas, ...app.options.graphql?.typedefs ?? []];
53
- };
102
+ const getSchemas = () => [...app.scanSchemas, ...app.options.graphql?.typedefs ?? []];
54
103
  app.options.virtual ??= {};
55
- app.options.virtual["#nitro-internal-virtual/server-schemas"] = () => {
56
- const imports = getSchemas();
57
- return `
58
- ${imports.map((handler) => `import ${getImportId(handler)} from '${handler}';`).join("\n")}
104
+ app.options.virtual["#nitro-graphql/server-schemas"] = () => {
105
+ try {
106
+ const imports = getSchemas();
107
+ if (imports.length === 0) {
108
+ if (app.options.dev) app.logger.warn("[nitro-graphql] No schemas found. Virtual module will export empty array.");
109
+ return "export const schemas = []";
110
+ }
111
+ const importStatements = imports.map((handler) => `import ${getImportId(handler)} from '${handler}';`);
112
+ const schemaArray = imports.map((h) => `{ def: ${getImportId(h)} }`);
113
+ return `
114
+ ${importStatements.join("\n")}
59
115
 
60
116
  export const schemas = [
61
- ${imports.map((h) => `{ def: ${getImportId(h)} }`).join(",\n")}
117
+ ${schemaArray.join(",\n")}
62
118
  ];
63
119
  `;
120
+ } catch (error) {
121
+ app.logger.error("[nitro-graphql] Failed to generate virtual schema module:", error);
122
+ return "export const schemas = []";
123
+ }
64
124
  };
65
125
  }
66
126
  function virtualResolvers(app) {
67
- const getResolvers = () => {
68
- return [...app.scanResolvers];
69
- };
127
+ const getResolvers = () => [...app.scanResolvers];
70
128
  app.options.virtual ??= {};
71
- app.options.virtual["#nitro-internal-virtual/server-resolvers"] = () => {
72
- const imports = getResolvers();
73
- const importsContent = [...imports.map(({ specifier, imports: imports$1, options }) => {
74
- return genImport(specifier, imports$1, options);
75
- })];
76
- const content = [
77
- "export const resolvers = [",
78
- imports.map(({ imports: imports$1 }) => imports$1.map((i) => `{ resolver: ${i.as} }`).join(",\n")).filter(Boolean).join(",\n"),
79
- "]",
80
- ""
81
- ];
82
- content.unshift(...importsContent);
83
- return content.join("\n");
129
+ app.options.virtual["#nitro-graphql/server-resolvers"] = () => {
130
+ try {
131
+ const imports = getResolvers();
132
+ if (imports.length === 0) {
133
+ if (app.options.dev) app.logger.warn("[nitro-graphql] No resolvers found. Virtual module will export empty array.");
134
+ return "export const resolvers = []";
135
+ }
136
+ const importsContent = [];
137
+ const invalidImports = [];
138
+ for (const { specifier, imports: importList, options } of imports) try {
139
+ if (!importList || importList.length === 0) {
140
+ invalidImports.push(`${specifier}: No exports found`);
141
+ continue;
142
+ }
143
+ const importCode = genImport(specifier, importList, options);
144
+ importsContent.push(importCode);
145
+ } catch (error) {
146
+ const message = error instanceof Error ? error.message : String(error);
147
+ invalidImports.push(`${specifier}: ${message}`);
148
+ if (app.options.dev) app.logger.error(`[nitro-graphql] Failed to generate import for ${specifier}:`, error);
149
+ }
150
+ if (invalidImports.length > 0 && app.options.dev) {
151
+ app.logger.warn("[nitro-graphql] Some resolver imports could not be generated:");
152
+ for (const msg of invalidImports) app.logger.warn(` - ${msg}`);
153
+ }
154
+ const data = imports.map(({ imports: importList }) => importList.map((i) => `{ resolver: ${i.as} }`).join(",\n")).filter(Boolean).join(",\n");
155
+ return [
156
+ ...importsContent,
157
+ "",
158
+ "export const resolvers = [",
159
+ data,
160
+ "]",
161
+ ""
162
+ ].join("\n");
163
+ } catch (error) {
164
+ app.logger.error("[nitro-graphql] Failed to generate virtual resolver module:", error);
165
+ return "export const resolvers = []";
166
+ }
84
167
  };
85
168
  }
86
169
  function virtualDirectives(app) {
87
- const getDirectives = () => {
88
- return [...app.scanDirectives || []];
89
- };
170
+ const getDirectives = () => app.scanDirectives || [];
90
171
  app.options.virtual ??= {};
91
- app.options.virtual["#nitro-internal-virtual/server-directives"] = () => {
92
- const imports = getDirectives();
93
- const importsContent = [...imports.map(({ specifier, imports: imports$1, options }) => {
94
- return genImport(specifier, imports$1, options);
95
- })];
96
- const content = [
97
- "export const directives = [",
98
- imports.map(({ imports: imports$1 }) => imports$1.map((i) => `{ directive: ${i.as} }`).join(",\n")).filter(Boolean).join(",\n"),
99
- "]",
100
- ""
101
- ];
102
- content.unshift(...importsContent);
103
- return content.join("\n");
172
+ app.options.virtual["#nitro-graphql/server-directives"] = () => {
173
+ try {
174
+ const imports = getDirectives();
175
+ if (imports.length === 0) return "export const directives = []";
176
+ const importsContent = [];
177
+ const invalidImports = [];
178
+ for (const { specifier, imports: importList, options } of imports) try {
179
+ if (!importList || importList.length === 0) {
180
+ invalidImports.push(`${specifier}: No exports found`);
181
+ continue;
182
+ }
183
+ const importCode = genImport(specifier, importList, options);
184
+ importsContent.push(importCode);
185
+ } catch (error) {
186
+ const message = error instanceof Error ? error.message : String(error);
187
+ invalidImports.push(`${specifier}: ${message}`);
188
+ if (app.options.dev) app.logger.error(`[nitro-graphql] Failed to generate import for directive ${specifier}:`, error);
189
+ }
190
+ if (invalidImports.length > 0 && app.options.dev) {
191
+ app.logger.warn("[nitro-graphql] Some directive imports could not be generated:");
192
+ for (const msg of invalidImports) app.logger.warn(` - ${msg}`);
193
+ }
194
+ const data = imports.map(({ imports: importList }) => importList.map((i) => `{ directive: ${i.as} }`).join(",\n")).filter(Boolean).join(",\n");
195
+ return [
196
+ ...importsContent,
197
+ "",
198
+ "export const directives = [",
199
+ data,
200
+ "]",
201
+ ""
202
+ ].join("\n");
203
+ } catch (error) {
204
+ app.logger.error("[nitro-graphql] Failed to generate virtual directive module:", error);
205
+ return "export const directives = []";
206
+ }
104
207
  };
105
208
  }
106
209
  function getGraphQLConfig(app) {
107
210
  const configPath = resolve(app.graphql.serverDir, "config.ts");
108
211
  app.options.virtual ??= {};
109
- app.options.virtual["#nitro-internal-virtual/graphql-config"] = () => {
212
+ app.options.virtual["#nitro-graphql/graphql-config"] = () => {
110
213
  return `import config from '${configPath}'
111
214
  const importedConfig = config
112
215
  export { importedConfig }
@@ -115,11 +218,65 @@ export { importedConfig }
115
218
  }
116
219
  function virtualModuleConfig(app) {
117
220
  app.options.virtual ??= {};
118
- app.options.virtual["#nitro-internal-virtual/module-config"] = () => {
221
+ app.options.virtual["#nitro-graphql/module-config"] = () => {
119
222
  const moduleConfig = app.options.graphql || {};
120
223
  return `export const moduleConfig = ${JSON.stringify(moduleConfig, null, 2)};`;
121
224
  };
122
225
  }
226
+ function virtualDebugInfo(app) {
227
+ app.options.virtual ??= {};
228
+ app.options.virtual["#nitro-graphql/debug-info"] = () => {
229
+ const virtualModuleCodes = {};
230
+ try {
231
+ const schemasGenerator = app.options.virtual["#nitro-graphql/server-schemas"];
232
+ if (schemasGenerator && typeof schemasGenerator === "function") virtualModuleCodes["server-schemas"] = schemasGenerator();
233
+ } catch (error) {
234
+ virtualModuleCodes["server-schemas"] = `// Error generating: ${error instanceof Error ? error.message : String(error)}`;
235
+ }
236
+ try {
237
+ const resolversGenerator = app.options.virtual["#nitro-graphql/server-resolvers"];
238
+ if (resolversGenerator && typeof resolversGenerator === "function") virtualModuleCodes["server-resolvers"] = resolversGenerator();
239
+ } catch (error) {
240
+ virtualModuleCodes["server-resolvers"] = `// Error generating: ${error instanceof Error ? error.message : String(error)}`;
241
+ }
242
+ try {
243
+ const directivesGenerator = app.options.virtual["#nitro-graphql/server-directives"];
244
+ if (directivesGenerator && typeof directivesGenerator === "function") virtualModuleCodes["server-directives"] = directivesGenerator();
245
+ } catch (error) {
246
+ virtualModuleCodes["server-directives"] = `// Error generating: ${error instanceof Error ? error.message : String(error)}`;
247
+ }
248
+ try {
249
+ const moduleConfigGenerator = app.options.virtual["#nitro-graphql/module-config"];
250
+ if (moduleConfigGenerator && typeof moduleConfigGenerator === "function") virtualModuleCodes["module-config"] = moduleConfigGenerator();
251
+ } catch (error) {
252
+ virtualModuleCodes["module-config"] = `// Error generating: ${error instanceof Error ? error.message : String(error)}`;
253
+ }
254
+ try {
255
+ const graphqlConfigGenerator = app.options.virtual["#nitro-graphql/graphql-config"];
256
+ if (graphqlConfigGenerator && typeof graphqlConfigGenerator === "function") virtualModuleCodes["graphql-config"] = graphqlConfigGenerator();
257
+ } catch (error) {
258
+ virtualModuleCodes["graphql-config"] = `// Error generating: ${error instanceof Error ? error.message : String(error)}`;
259
+ }
260
+ const debugInfo = {
261
+ isDev: app.options.dev,
262
+ framework: app.options.framework.name,
263
+ graphqlFramework: app.options.graphql?.framework,
264
+ federation: app.options.graphql?.federation,
265
+ scanned: {
266
+ schemas: app.scanSchemas?.length || 0,
267
+ schemaFiles: app.scanSchemas || [],
268
+ resolvers: app.scanResolvers?.length || 0,
269
+ resolverFiles: app.scanResolvers || [],
270
+ directives: app.scanDirectives?.length || 0,
271
+ directiveFiles: app.scanDirectives || [],
272
+ documents: app.scanDocuments?.length || 0,
273
+ documentFiles: app.scanDocuments || []
274
+ },
275
+ virtualModules: virtualModuleCodes
276
+ };
277
+ return `export const debugInfo = ${JSON.stringify(debugInfo, null, 2)};`;
278
+ };
279
+ }
123
280
 
124
281
  //#endregion
125
282
  export { rollupConfig };
@@ -1,6 +1,6 @@
1
- import * as h33 from "h3";
1
+ import * as h31 from "h3";
2
2
 
3
3
  //#region src/routes/apollo-server.d.ts
4
- declare const _default: h33.EventHandler<h33.EventHandlerRequest, unknown>;
4
+ declare const _default: h31.EventHandlerWithFetch<h31.EventHandlerRequest, Promise<any>>;
5
5
  //#endregion
6
6
  export { _default as default };
@@ -2,11 +2,11 @@ import { consola as consola$1 } from "consola";
2
2
  import defu from "defu";
3
3
  import { parse } from "graphql";
4
4
  import { mergeResolvers, mergeTypeDefs } from "@graphql-tools/merge";
5
- import { importedConfig } from "#nitro-internal-virtual/graphql-config";
6
- import { moduleConfig } from "#nitro-internal-virtual/module-config";
7
- import { directives } from "#nitro-internal-virtual/server-directives";
8
- import { resolvers } from "#nitro-internal-virtual/server-resolvers";
9
- import { schemas } from "#nitro-internal-virtual/server-schemas";
5
+ import { importedConfig } from "#nitro-graphql/graphql-config";
6
+ import { moduleConfig } from "#nitro-graphql/module-config";
7
+ import { directives } from "#nitro-graphql/server-directives";
8
+ import { resolvers } from "#nitro-graphql/server-resolvers";
9
+ import { schemas } from "#nitro-graphql/server-schemas";
10
10
  import { ApolloServer } from "@apollo/server";
11
11
  import { ApolloServerPluginLandingPageLocalDefault } from "@apollo/server/plugin/landingPage/default";
12
12
  import { makeExecutableSchema } from "@graphql-tools/schema";