nitro-graphql 2.0.0-beta.30 → 2.0.0-beta.32

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 (42) hide show
  1. package/README.md +3 -3
  2. package/dist/codegen/client-types.d.mts +13 -0
  3. package/dist/codegen/client-types.mjs +176 -0
  4. package/dist/codegen/external-types.d.mts +12 -0
  5. package/dist/codegen/external-types.mjs +129 -0
  6. package/dist/codegen/index.d.mts +25 -0
  7. package/dist/codegen/index.mjs +38 -0
  8. package/dist/codegen/server-types.d.mts +13 -0
  9. package/dist/codegen/server-types.mjs +76 -0
  10. package/dist/codegen/validation.d.mts +13 -0
  11. package/dist/codegen/validation.mjs +96 -0
  12. package/dist/config/defaults.mjs +36 -0
  13. package/dist/constants.mjs +91 -0
  14. package/dist/define.d.mts +3 -3
  15. package/dist/define.mjs +3 -3
  16. package/dist/ecosystem/nuxt.mjs +3 -3
  17. package/dist/rollup.d.mts +7 -7
  18. package/dist/rollup.mjs +73 -73
  19. package/dist/routes/apollo-server.d.mts +2 -2
  20. package/dist/routes/debug.d.mts +2 -2
  21. package/dist/routes/graphql-yoga.d.mts +2 -2
  22. package/dist/routes/health.d.mts +2 -2
  23. package/dist/setup/file-watcher.mjs +80 -0
  24. package/dist/setup/rollup-integration.mjs +90 -0
  25. package/dist/setup/scaffold-generator.mjs +109 -0
  26. package/dist/setup/ts-config.mjs +69 -0
  27. package/dist/setup.d.mts +2 -2
  28. package/dist/setup.mjs +127 -290
  29. package/dist/types/index.d.mts +1 -1
  30. package/dist/utils/client-codegen.d.mts +1 -1
  31. package/dist/utils/client-codegen.mjs +5 -2
  32. package/dist/utils/directive-parser.d.mts +2 -1
  33. package/dist/utils/directive-parser.mjs +4 -2
  34. package/dist/utils/file-generator.mjs +1 -1
  35. package/dist/utils/index.d.mts +2 -2
  36. package/dist/utils/index.mjs +12 -11
  37. package/dist/utils/path-resolver.d.mts +2 -2
  38. package/dist/utils/path-resolver.mjs +2 -2
  39. package/dist/utils/server-codegen.mjs +4 -1
  40. package/dist/utils/type-generation.d.mts +6 -12
  41. package/dist/utils/type-generation.mjs +6 -419
  42. package/package.json +10 -4
package/dist/setup.mjs CHANGED
@@ -1,40 +1,50 @@
1
+ import { ENDPOINT_DEBUG, FRAMEWORK_NITRO, FRAMEWORK_NUXT, GRAPHQL_HTTP_METHODS, LOG_TAG } from "./constants.mjs";
2
+ import { DEFAULT_RUNTIME_CONFIG, DEFAULT_TYPESCRIPT_STRICT, DEFAULT_TYPES_CONFIG } from "./config/defaults.mjs";
1
3
  import { generateDirectiveSchemas } from "./utils/directive-parser.mjs";
2
- import { generateLayerIgnorePatterns, getLayerAppDirectories, getLayerServerDirectories, relativeWithDot, scanDirectives, scanDocs, scanResolvers, scanSchemas, validateExternalServices } from "./utils/index.mjs";
3
- import { writeFileIfNotExists } from "./utils/file-generator.mjs";
4
- import { getScaffoldConfig, getTypesConfig, resolveFilePath, shouldGenerateScaffold } from "./utils/path-resolver.mjs";
5
- import { clientTypeGeneration, serverTypeGeneration } from "./utils/type-generation.mjs";
4
+ import { scanDirectives, scanDocuments, scanResolvers, scanSchemas, validateExternalServices } from "./utils/index.mjs";
5
+ import { getDefaultPaths } from "./utils/path-resolver.mjs";
6
+ import { clientTypeGeneration, serverTypeGeneration } from "./codegen/index.mjs";
6
7
  import { rollupConfig } from "./rollup.mjs";
8
+ import { getWatchDirectories, setupFileWatcher } from "./setup/file-watcher.mjs";
9
+ import { setupRollupChunking, setupRollupExternals } from "./setup/rollup-integration.mjs";
10
+ import { generateScaffoldFiles } from "./setup/scaffold-generator.mjs";
11
+ import { setupTypeScriptPaths } from "./setup/ts-config.mjs";
7
12
  import defu from "defu";
8
- import { existsSync, mkdirSync } from "node:fs";
9
13
  import { fileURLToPath } from "node:url";
10
- import { watch } from "chokidar";
11
14
  import consola from "consola";
12
- import { dirname, join, relative, resolve } from "pathe";
15
+ import { join, relative, resolve } from "pathe";
13
16
 
14
17
  //#region src/setup.ts
15
- const logger = consola.withTag("nitro-graphql");
18
+ const logger = consola.withTag(LOG_TAG);
16
19
  /**
17
- * Shared setup logic for nitro-graphql module
18
- * Used by both the direct Nitro module export and the Vite plugin's nitro: hook
20
+ * Main setup function for nitro-graphql
21
+ * Coordinates all initialization steps for the module
19
22
  */
20
23
  async function setupNitroGraphQL(nitro) {
24
+ initializeConfiguration(nitro);
25
+ validateConfiguration(nitro);
26
+ setupBuildDirectories(nitro);
27
+ setupRollupExternals(nitro);
28
+ setupRollupChunking(nitro);
29
+ initializeRuntimeConfig(nitro);
30
+ setupFileWatching(nitro);
31
+ await scanGraphQLFiles(nitro);
32
+ setupDevHooks(nitro);
33
+ await rollupConfig(nitro);
34
+ await generateTypes(nitro);
35
+ setupCloseHooks(nitro);
36
+ registerRouteHandlers(nitro);
37
+ setupTypeScriptConfiguration(nitro);
38
+ setupNuxtIntegration(nitro);
39
+ generateScaffoldFiles(nitro);
40
+ }
41
+ /**
42
+ * Initialize default configuration values
43
+ */
44
+ function initializeConfiguration(nitro) {
21
45
  nitro.options.graphql ||= {};
22
- nitro.options.graphql.types = defu(nitro.options.graphql.types, {
23
- server: ".graphql/nitro-graphql-server.d.ts",
24
- client: ".graphql/nitro-graphql-client.d.ts",
25
- enabled: true
26
- });
46
+ nitro.options.graphql.types = defu(nitro.options.graphql.types, DEFAULT_TYPES_CONFIG);
27
47
  if (!nitro.options.graphql?.framework) logger.warn("No GraphQL framework specified. Please set graphql.framework to \"graphql-yoga\" or \"apollo-server\".");
28
- if (nitro.options.graphql?.externalServices?.length) {
29
- const validationErrors = validateExternalServices(nitro.options.graphql.externalServices);
30
- if (validationErrors.length > 0) {
31
- logger.error("External services configuration errors:");
32
- for (const error of validationErrors) logger.error(` - ${error}`);
33
- throw new Error("Invalid external services configuration");
34
- }
35
- logger.info(`Configured ${nitro.options.graphql.externalServices.length} external GraphQL services`);
36
- }
37
- const { getDefaultPaths } = await import("./utils/path-resolver.mjs");
38
48
  const defaultPaths = getDefaultPaths(nitro);
39
49
  nitro.graphql ||= {
40
50
  buildDir: "",
@@ -47,100 +57,87 @@ async function setupNitroGraphQL(nitro) {
47
57
  server: "server"
48
58
  }
49
59
  };
50
- nitro.hooks.hook("rollup:before", (_, rollupConfig$1) => {
51
- rollupConfig$1.external = rollupConfig$1.external || [];
52
- const allExternals = [...["oxc-parser", "@oxc-parser"]];
53
- if (!nitro.options.graphql?.federation?.enabled) allExternals.push(...[
54
- "@apollo/subgraph",
55
- "@apollo/federation-internals",
56
- "@apollo/cache-control-types"
57
- ]);
58
- if (Array.isArray(rollupConfig$1.external)) rollupConfig$1.external.push(...allExternals);
59
- else if (typeof rollupConfig$1.external === "function") {
60
- const originalExternal = rollupConfig$1.external;
61
- rollupConfig$1.external = (id, parent, isResolved) => {
62
- if (allExternals.some((external) => id.includes(external))) return true;
63
- return originalExternal(id, parent, isResolved);
64
- };
60
+ }
61
+ /**
62
+ * Validate external services configuration
63
+ */
64
+ function validateConfiguration(nitro) {
65
+ if (nitro.options.graphql?.externalServices?.length) {
66
+ const validationErrors = validateExternalServices(nitro.options.graphql.externalServices);
67
+ if (validationErrors.length > 0) {
68
+ logger.error("External services configuration errors:");
69
+ for (const error of validationErrors) logger.error(` - ${error}`);
70
+ throw new Error("Invalid external services configuration");
65
71
  }
66
- });
67
- nitro.options.runtimeConfig.graphql = defu(nitro.options.runtimeConfig.graphql || {}, {
68
- endpoint: {
69
- graphql: "/api/graphql",
70
- healthCheck: "/api/graphql/health"
71
- },
72
- playground: true
73
- });
72
+ logger.info(`Configured ${nitro.options.graphql.externalServices.length} external GraphQL services`);
73
+ }
74
74
  if (nitro.options.graphql?.federation?.enabled) logger.info(`Apollo Federation enabled for service: ${nitro.options.graphql.federation.serviceName || "unnamed"}`);
75
+ }
76
+ /**
77
+ * Setup build directories
78
+ */
79
+ function setupBuildDirectories(nitro) {
75
80
  const graphqlBuildDir = resolve(nitro.options.buildDir, "graphql");
76
81
  nitro.graphql.buildDir = graphqlBuildDir;
77
- const watchDirs = [];
78
82
  switch (nitro.options.framework.name) {
79
- case "nuxt": {
83
+ case FRAMEWORK_NUXT:
80
84
  nitro.graphql.dir.client = relative(nitro.options.rootDir, nitro.graphql.clientDir);
81
85
  nitro.graphql.dir.server = relative(nitro.options.rootDir, nitro.graphql.serverDir);
82
- watchDirs.push(nitro.graphql.clientDir);
83
- const layerServerDirs = getLayerServerDirectories(nitro);
84
- const layerAppDirs = getLayerAppDirectories(nitro);
85
- for (const layerServerDir of layerServerDirs) watchDirs.push(join(layerServerDir, "graphql"));
86
- for (const layerAppDir of layerAppDirs) watchDirs.push(join(layerAppDir, "graphql"));
87
86
  break;
88
- }
89
- case "nitro":
87
+ case FRAMEWORK_NITRO:
90
88
  nitro.graphql.dir.client = relative(nitro.options.rootDir, nitro.graphql.clientDir);
91
89
  nitro.graphql.dir.server = relative(nitro.options.rootDir, nitro.graphql.serverDir);
92
- watchDirs.push(nitro.graphql.clientDir);
93
- watchDirs.push(nitro.graphql.serverDir);
94
90
  break;
95
- default:
91
+ default: break;
96
92
  }
97
- if (nitro.options.graphql?.externalServices?.length) {
98
- for (const service of nitro.options.graphql.externalServices) if (service.documents?.length) for (const pattern of service.documents) {
99
- if (!pattern) continue;
100
- const baseDir = pattern.split("**")[0]?.replace(/\/$/, "") || ".";
101
- const resolvedDir = resolve(nitro.options.rootDir, baseDir);
102
- if (!watchDirs.includes(resolvedDir)) watchDirs.push(resolvedDir);
103
- }
104
- }
105
- const watcher = watch(watchDirs, {
106
- persistent: true,
107
- ignoreInitial: true,
108
- ignored: [...nitro.options.ignore, ...generateLayerIgnorePatterns()]
109
- }).on("all", async (_, path) => {
110
- const isGraphQLFile = path.endsWith(".graphql") || path.endsWith(".gql");
111
- const isResolverFile = path.endsWith(".resolver.ts") || path.endsWith(".resolver.js");
112
- const isDirectiveFile = path.endsWith(".directive.ts") || path.endsWith(".directive.js");
113
- if (isGraphQLFile || isResolverFile || isDirectiveFile) if (path.includes(nitro.graphql.serverDir) || path.includes("server/graphql") || path.includes("server\\graphql") || isResolverFile || isDirectiveFile) {
114
- await scanResolvers(nitro).then((r) => nitro.scanResolvers = r);
115
- await scanDirectives(nitro).then((d) => nitro.scanDirectives = d);
116
- logger.success("Types regenerated");
117
- await serverTypeGeneration(nitro, { silent: true });
118
- await clientTypeGeneration(nitro, { silent: true });
119
- await nitro.hooks.callHook("dev:reload");
120
- } else {
121
- logger.success("Types regenerated");
122
- await clientTypeGeneration(nitro, { silent: true });
123
- }
124
- });
93
+ }
94
+ /**
95
+ * Initialize runtime configuration
96
+ */
97
+ function initializeRuntimeConfig(nitro) {
98
+ nitro.options.runtimeConfig.graphql = defu(nitro.options.runtimeConfig.graphql || {}, DEFAULT_RUNTIME_CONFIG);
99
+ }
100
+ /**
101
+ * Setup file watching for development mode
102
+ */
103
+ function setupFileWatching(nitro) {
104
+ const watchDirs = getWatchDirectories(nitro);
105
+ nitro.graphql.watchDirs = watchDirs;
106
+ const watcher = setupFileWatcher(nitro, watchDirs);
125
107
  nitro.hooks.hook("close", () => {
126
108
  watcher.close();
127
109
  });
128
- const tsconfigDir = dirname(resolve(nitro.options.buildDir, nitro.options.typescript.tsconfigPath));
129
- nitro.scanSchemas = await scanSchemas(nitro);
130
- nitro.scanDocuments = await scanDocs(nitro);
131
- nitro.scanResolvers = await scanResolvers(nitro);
110
+ }
111
+ /**
112
+ * Scan all GraphQL files (schemas, resolvers, directives, documents)
113
+ */
114
+ async function scanGraphQLFiles(nitro) {
132
115
  const directives = await scanDirectives(nitro);
133
116
  nitro.scanDirectives = directives;
134
- await generateDirectiveSchemas(nitro, directives);
117
+ nitro.scanSchemas = [];
118
+ const directivesPath = await generateDirectiveSchemas(nitro, directives);
119
+ const schemas = await scanSchemas(nitro);
120
+ if (directivesPath && !schemas.includes(directivesPath)) schemas.push(directivesPath);
121
+ nitro.scanSchemas = schemas;
122
+ nitro.scanDocuments = await scanDocuments(nitro);
123
+ nitro.scanResolvers = await scanResolvers(nitro);
124
+ }
125
+ /**
126
+ * Setup dev mode hooks for rescanning files
127
+ */
128
+ function setupDevHooks(nitro) {
135
129
  let hasShownInitialLogs = false;
136
130
  nitro.hooks.hook("dev:start", async () => {
137
- nitro.scanSchemas = await scanSchemas(nitro);
131
+ const directives = await scanDirectives(nitro);
132
+ nitro.scanDirectives = directives;
133
+ if (!nitro.scanSchemas) nitro.scanSchemas = [];
134
+ const directivesPath = await generateDirectiveSchemas(nitro, directives);
135
+ const schemas = await scanSchemas(nitro);
136
+ if (directivesPath && !schemas.includes(directivesPath)) schemas.push(directivesPath);
137
+ nitro.scanSchemas = schemas;
138
+ nitro.scanDocuments = await scanDocuments(nitro);
138
139
  const resolvers = await scanResolvers(nitro);
139
140
  nitro.scanResolvers = resolvers;
140
- const directives$1 = await scanDirectives(nitro);
141
- nitro.scanDirectives = directives$1;
142
- await generateDirectiveSchemas(nitro, directives$1);
143
- nitro.scanDocuments = await scanDocs(nitro);
144
141
  if (nitro.options.dev && !hasShownInitialLogs) {
145
142
  hasShownInitialLogs = true;
146
143
  if (resolvers.length > 0) {
@@ -165,25 +162,35 @@ async function setupNitroGraphQL(nitro) {
165
162
  } else logger.warn("No resolvers found. Check /_nitro/graphql/debug for details.");
166
163
  }
167
164
  });
168
- await rollupConfig(nitro);
165
+ }
166
+ /**
167
+ * Generate server and client types
168
+ */
169
+ async function generateTypes(nitro) {
169
170
  await serverTypeGeneration(nitro);
170
171
  await clientTypeGeneration(nitro, { isInitial: true });
172
+ }
173
+ /**
174
+ * Setup close hooks for final type generation
175
+ */
176
+ function setupCloseHooks(nitro) {
171
177
  nitro.hooks.hook("close", async () => {
172
178
  await serverTypeGeneration(nitro, { silent: true });
173
179
  await clientTypeGeneration(nitro, { silent: true });
174
180
  });
181
+ }
182
+ /**
183
+ * Register GraphQL route handlers
184
+ */
185
+ function registerRouteHandlers(nitro) {
175
186
  const runtime = fileURLToPath(new URL("routes", import.meta.url));
176
- const methods = [
177
- "GET",
178
- "POST",
179
- "OPTIONS"
180
- ];
181
- if (nitro.options.graphql?.framework === "graphql-yoga") for (const method of methods) nitro.options.handlers.push({
187
+ const framework = nitro.options.graphql?.framework;
188
+ if (framework === "graphql-yoga") for (const method of GRAPHQL_HTTP_METHODS) nitro.options.handlers.push({
182
189
  route: nitro.options.runtimeConfig.graphql?.endpoint?.graphql || "/api/graphql",
183
190
  handler: join(runtime, "graphql-yoga"),
184
191
  method
185
192
  });
186
- if (nitro.options.graphql?.framework === "apollo-server") for (const method of methods) nitro.options.handlers.push({
193
+ if (framework === "apollo-server") for (const method of GRAPHQL_HTTP_METHODS) nitro.options.handlers.push({
187
194
  route: nitro.options.runtimeConfig.graphql?.endpoint?.graphql || "/api/graphql",
188
195
  handler: join(runtime, "apollo-server"),
189
196
  method
@@ -194,198 +201,28 @@ async function setupNitroGraphQL(nitro) {
194
201
  method: "GET"
195
202
  });
196
203
  if (nitro.options.dev) nitro.options.handlers.push({
197
- route: "/_nitro/graphql/debug",
204
+ route: ENDPOINT_DEBUG,
198
205
  handler: join(runtime, "debug"),
199
206
  method: "GET"
200
207
  });
201
- if (nitro.options.imports) {
202
- nitro.options.imports.presets ??= [];
203
- nitro.options.imports.presets.push({
204
- from: fileURLToPath(new URL("define", import.meta.url)),
205
- imports: [
206
- "defineResolver",
207
- "defineMutation",
208
- "defineQuery",
209
- "defineSubscription",
210
- "defineType",
211
- "defineGraphQLConfig",
212
- "defineSchema",
213
- "defineDirective"
214
- ]
215
- });
216
- }
217
- nitro.hooks.hook("rollup:before", (_, rollupConfig$1) => {
218
- const manualChunks = rollupConfig$1.output?.manualChunks;
219
- const chunkFiles = rollupConfig$1.output?.chunkFileNames;
220
- if (!rollupConfig$1.output.inlineDynamicImports) {
221
- rollupConfig$1.output.manualChunks = (id, meta) => {
222
- if (id.endsWith(".graphql") || id.endsWith(".gql")) {
223
- let graphqlIndex = id.indexOf("server/graphql/");
224
- let baseLength = 15;
225
- if (graphqlIndex === -1) {
226
- graphqlIndex = id.indexOf("routes/graphql/");
227
- baseLength = 15;
228
- }
229
- if (graphqlIndex !== -1) return id.slice(graphqlIndex + baseLength).replace(/\.(?:graphql|gql)$/, "-schema");
230
- return "schemas";
231
- }
232
- if (id.endsWith(".resolver.ts")) {
233
- let graphqlIndex = id.indexOf("server/graphql/");
234
- let baseLength = 15;
235
- if (graphqlIndex === -1) {
236
- graphqlIndex = id.indexOf("routes/graphql/");
237
- baseLength = 15;
238
- }
239
- if (graphqlIndex !== -1) return id.slice(graphqlIndex + baseLength).replace(/\.resolver\.ts$/, "");
240
- return "resolvers";
241
- }
242
- if (typeof manualChunks === "function") return manualChunks(id, meta);
243
- };
244
- rollupConfig$1.output.advancedChunks = {
245
- groups: [{
246
- name: (moduleId) => {
247
- if (!moduleId.endsWith(".graphql") && !moduleId.endsWith(".gql")) return;
248
- let graphqlIndex = moduleId.indexOf("server/graphql/");
249
- let baseLength = 15;
250
- if (graphqlIndex === -1) {
251
- graphqlIndex = moduleId.indexOf("routes/graphql/");
252
- baseLength = 15;
253
- }
254
- if (graphqlIndex !== -1) return moduleId.slice(graphqlIndex + baseLength).replace(/\.(?:graphql|gql)$/, "-schema");
255
- return "schemas";
256
- },
257
- test: /\.(?:graphql|gql)$/
258
- }, {
259
- name: (moduleId) => {
260
- if (!moduleId.endsWith(".resolver.ts")) return;
261
- let graphqlIndex = moduleId.indexOf("server/graphql/");
262
- let baseLength = 15;
263
- if (graphqlIndex === -1) {
264
- graphqlIndex = moduleId.indexOf("routes/graphql/");
265
- baseLength = 15;
266
- }
267
- if (graphqlIndex !== -1) return moduleId.slice(graphqlIndex + baseLength).replace(/\.resolver\.ts$/, "");
268
- return "resolvers";
269
- },
270
- test: /\.resolver\.(?:ts|js)$/
271
- }],
272
- minSize: 0,
273
- minShareCount: 1
274
- };
275
- }
276
- rollupConfig$1.output.chunkFileNames = (chunkInfo) => {
277
- if (chunkInfo.moduleIds && chunkInfo.moduleIds.some((id) => id.endsWith(".graphql") || id.endsWith(".resolver.ts") || id.endsWith(".gql"))) return `chunks/graphql/[name].mjs`;
278
- if (typeof chunkFiles === "function") return chunkFiles(chunkInfo);
279
- return `chunks/_/[name].mjs`;
280
- };
281
- });
282
- nitro.options.typescript.strict = true;
208
+ }
209
+ /**
210
+ * Setup TypeScript configuration and path aliases
211
+ */
212
+ function setupTypeScriptConfiguration(nitro) {
213
+ nitro.options.typescript.strict = DEFAULT_TYPESCRIPT_STRICT;
283
214
  nitro.hooks.hook("types:extend", (types) => {
284
- types.tsConfig ||= {};
285
- types.tsConfig.compilerOptions ??= {};
286
- types.tsConfig.compilerOptions.paths ??= {};
287
- const placeholders = getDefaultPaths(nitro);
288
- const typesConfig = getTypesConfig(nitro);
289
- const serverTypesPath = resolveFilePath(typesConfig.server, typesConfig.enabled, true, "{typesDir}/nitro-graphql-server.d.ts", placeholders);
290
- if (serverTypesPath) types.tsConfig.compilerOptions.paths["#graphql/server"] = [relativeWithDot(tsconfigDir, serverTypesPath)];
291
- const clientTypesPath = resolveFilePath(typesConfig.client, typesConfig.enabled, true, "{typesDir}/nitro-graphql-client.d.ts", placeholders);
292
- if (clientTypesPath) types.tsConfig.compilerOptions.paths["#graphql/client"] = [relativeWithDot(tsconfigDir, clientTypesPath)];
293
- types.tsConfig.compilerOptions.paths["#graphql/schema"] = [relativeWithDot(tsconfigDir, join(nitro.graphql.serverDir, "schema.ts"))];
294
- if (nitro.options.graphql?.externalServices?.length) for (const service of nitro.options.graphql.externalServices) {
295
- const servicePlaceholders = {
296
- ...placeholders,
297
- serviceName: service.name
298
- };
299
- const externalTypesPath = resolveFilePath(service.paths?.types ?? typesConfig.external, typesConfig.enabled, true, "{typesDir}/nitro-graphql-client-{serviceName}.d.ts", servicePlaceholders);
300
- if (externalTypesPath) types.tsConfig.compilerOptions.paths[`#graphql/client/${service.name}`] = [relativeWithDot(tsconfigDir, externalTypesPath)];
301
- }
302
- types.tsConfig.include = types.tsConfig.include || [];
303
- if (serverTypesPath) types.tsConfig.include.push(relativeWithDot(tsconfigDir, serverTypesPath));
304
- if (clientTypesPath) types.tsConfig.include.push(relativeWithDot(tsconfigDir, clientTypesPath));
305
- types.tsConfig.include.push(relativeWithDot(tsconfigDir, join(placeholders.typesDir, "graphql.d.ts")));
306
- if (nitro.options.graphql?.externalServices?.length) for (const service of nitro.options.graphql.externalServices) {
307
- const servicePlaceholders = {
308
- ...placeholders,
309
- serviceName: service.name
310
- };
311
- const externalTypesPath = resolveFilePath(service.paths?.types ?? typesConfig.external, typesConfig.enabled, true, "{typesDir}/nitro-graphql-client-{serviceName}.d.ts", servicePlaceholders);
312
- if (externalTypesPath) types.tsConfig.include.push(relativeWithDot(tsconfigDir, externalTypesPath));
313
- }
215
+ setupTypeScriptPaths(nitro, types);
314
216
  });
315
- if (nitro.options.framework?.name === "nuxt" && nitro.options.graphql?.externalServices?.length) nitro.hooks.hook("build:before", () => {
217
+ }
218
+ /**
219
+ * Setup Nuxt-specific integration
220
+ */
221
+ function setupNuxtIntegration(nitro) {
222
+ if (nitro.options.framework?.name === FRAMEWORK_NUXT && nitro.options.graphql?.externalServices?.length) nitro.hooks.hook("build:before", () => {
316
223
  const nuxtOptions = nitro._nuxt?.options;
317
224
  if (nuxtOptions) nuxtOptions.nitroGraphqlExternalServices = nitro.options.graphql?.externalServices || [];
318
225
  });
319
- if (shouldGenerateScaffold(nitro)) {
320
- const placeholders = getDefaultPaths(nitro);
321
- const scaffoldConfig = getScaffoldConfig(nitro);
322
- const graphqlConfigPath = resolveFilePath(scaffoldConfig.graphqlConfig, scaffoldConfig.enabled, true, "graphql.config.ts", placeholders);
323
- if (graphqlConfigPath) writeFileIfNotExists(graphqlConfigPath, `
324
- import type { IGraphQLConfig } from 'graphql-config'
325
-
326
- export default <IGraphQLConfig> {
327
- projects: {
328
- default: {
329
- schema: [
330
- '${relativeWithDot(nitro.options.rootDir, resolve(nitro.graphql.buildDir, "schema.graphql"))}',
331
- ],
332
- documents: [
333
- '${relativeWithDot(nitro.options.rootDir, resolve(nitro.graphql.clientDir, "**/*.{graphql,js,ts,jsx,tsx}"))}',
334
- ],
335
- },
336
- },
337
- }`, "graphql.config.ts");
338
- const serverSchemaPath = resolveFilePath(scaffoldConfig.serverSchema, scaffoldConfig.enabled, true, "{serverGraphql}/schema.ts", placeholders);
339
- const serverConfigPath = resolveFilePath(scaffoldConfig.serverConfig, scaffoldConfig.enabled, true, "{serverGraphql}/config.ts", placeholders);
340
- const serverContextPath = resolveFilePath(scaffoldConfig.serverContext, scaffoldConfig.enabled, true, "{serverGraphql}/context.d.ts", placeholders);
341
- if (serverSchemaPath || serverConfigPath || serverContextPath) {
342
- if (!existsSync(nitro.graphql.serverDir)) mkdirSync(nitro.graphql.serverDir, { recursive: true });
343
- }
344
- if (serverSchemaPath) writeFileIfNotExists(serverSchemaPath, `export default defineSchema({
345
-
346
- })
347
- `, "server schema.ts");
348
- if (serverConfigPath) writeFileIfNotExists(serverConfigPath, `// Example GraphQL config file please change it to your needs
349
- // import * as tables from '../drizzle/schema/index'
350
- // import { useDatabase } from '../utils/useDb'
351
- import { defineGraphQLConfig } from 'nitro-graphql/define'
352
-
353
- export default defineGraphQLConfig({
354
- // graphql-yoga example config
355
- // context: () => {
356
- // return {
357
- // context: {
358
- // useDatabase,
359
- // tables,
360
- // },
361
- // }
362
- // },
363
- })
364
- `, "server config.ts");
365
- if (serverContextPath) writeFileIfNotExists(serverContextPath, `// Example context definition - please change it to your needs
366
- // import type { Database } from '../utils/useDb'
367
-
368
- declare module 'nitro/h3' {
369
- interface H3EventContext {
370
- // Add your custom context properties here
371
- // useDatabase: () => Database
372
- // tables: typeof import('../drizzle/schema')
373
- // auth?: {
374
- // user?: {
375
- // id: string
376
- // role: 'admin' | 'user'
377
- // }
378
- // }
379
- }
380
- }
381
-
382
- export {}
383
- `, "server context.d.ts");
384
- if (existsSync(join(nitro.graphql.serverDir, "context.ts"))) {
385
- logger.warn("Found context.ts file. Please rename it to context.d.ts for type-only definitions.");
386
- logger.info("The context file should now be context.d.ts instead of context.ts");
387
- }
388
- } else logger.info("Scaffold file generation is disabled (library mode)");
389
226
  }
390
227
 
391
228
  //#endregion
@@ -1,9 +1,9 @@
1
1
  import { StandardSchemaV1 } from "./standard-schema.mjs";
2
2
  import { ESMCodeGenOptions } from "knitwork";
3
- import { IResolvers } from "@graphql-tools/utils";
4
3
  import { TypeScriptPluginConfig } from "@graphql-codegen/typescript";
5
4
  import { plugin as plugin$1 } from "@graphql-codegen/typescript-generic-sdk";
6
5
  import { TypeScriptDocumentsPluginConfig } from "@graphql-codegen/typescript-operations";
6
+ import { IResolvers } from "@graphql-tools/utils";
7
7
  import { TypeScriptResolversPluginConfig } from "@graphql-codegen/typescript-resolvers";
8
8
 
9
9
  //#region src/types/index.d.ts
@@ -1,7 +1,7 @@
1
1
  import { CodegenClientConfig, ExternalGraphQLService, GenericSdkConfig } from "../types/index.mjs";
2
2
  import { GraphQLSchema } from "graphql";
3
- import { Source } from "@graphql-tools/utils";
4
3
  import { LoadSchemaOptions, UnnormalizedTypeDefPointer } from "@graphql-tools/load";
4
+ import { Source } from "@graphql-tools/utils";
5
5
 
6
6
  //#region src/utils/client-codegen.d.ts
7
7
 
@@ -1,9 +1,8 @@
1
1
  import { defu as defu$1 } from "defu";
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
2
  import { consola as consola$1 } from "consola";
4
3
  import { dirname, resolve } from "pathe";
5
4
  import { parse } from "graphql";
6
- import { printSchemaWithDirectives } from "@graphql-tools/utils";
5
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
6
  import { createHash } from "node:crypto";
8
7
  import { codegen } from "@graphql-codegen/core";
9
8
  import { preset } from "@graphql-codegen/import-types-preset";
@@ -13,9 +12,13 @@ import { plugin as plugin$2 } from "@graphql-codegen/typescript-operations";
13
12
  import { GraphQLFileLoader } from "@graphql-tools/graphql-file-loader";
14
13
  import { loadDocuments, loadSchemaSync } from "@graphql-tools/load";
15
14
  import { UrlLoader } from "@graphql-tools/url-loader";
15
+ import { printSchemaWithDirectives } from "@graphql-tools/utils";
16
16
  import { CurrencyResolver, DateTimeISOResolver, DateTimeResolver, JSONObjectResolver, JSONResolver, NonEmptyStringResolver, UUIDResolver } from "graphql-scalars";
17
17
 
18
18
  //#region src/utils/client-codegen.ts
19
+ /**
20
+ * Plugin to add prepend comments to generated files
21
+ */
19
22
  function pluginContent(_schema, _documents, _config, _info) {
20
23
  return {
21
24
  prepend: [
@@ -70,8 +70,9 @@ declare class DirectiveParser {
70
70
  declare function generateDirectiveSchema(directive: ParsedDirective): string;
71
71
  /**
72
72
  * Generate directive schemas file from scanned directives
73
+ * @returns The path to the generated _directives.graphql file, or null if no directives
73
74
  */
74
- declare function generateDirectiveSchemas(nitro: any, directives: any[]): Promise<void>;
75
+ declare function generateDirectiveSchemas(nitro: any, directives: any[]): Promise<string | null>;
75
76
  /**
76
77
  * Singleton instance for reuse
77
78
  */
@@ -181,9 +181,10 @@ function generateDirectiveSchema(directive) {
181
181
  }
182
182
  /**
183
183
  * Generate directive schemas file from scanned directives
184
+ * @returns The path to the generated _directives.graphql file, or null if no directives
184
185
  */
185
186
  async function generateDirectiveSchemas(nitro, directives) {
186
- if (directives.length === 0) return;
187
+ if (directives.length === 0) return null;
187
188
  const { existsSync, readFileSync, writeFileSync, mkdirSync } = await import("node:fs");
188
189
  const { readFile } = await import("node:fs/promises");
189
190
  const { resolve, dirname } = await import("pathe");
@@ -212,8 +213,9 @@ ${directiveSchemas.join("\n\n")}`;
212
213
  let shouldWrite = true;
213
214
  if (existsSync(directivesPath)) shouldWrite = readFileSync(directivesPath, "utf-8") !== content;
214
215
  if (shouldWrite) writeFileSync(directivesPath, content, "utf-8");
215
- if (!nitro.scanSchemas.includes(directivesPath)) nitro.scanSchemas.push(directivesPath);
216
+ return directivesPath;
216
217
  }
218
+ return null;
217
219
  }
218
220
  /**
219
221
  * Singleton instance for reuse
@@ -1,6 +1,6 @@
1
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
1
  import consola from "consola";
3
2
  import { dirname } from "pathe";
3
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
4
4
 
5
5
  //#region src/utils/file-generator.ts
6
6
  /**
@@ -27,7 +27,7 @@ declare function scanGraphql(nitro: Nitro): Promise<string[]>;
27
27
  declare function scanResolvers(nitro: Nitro): Promise<GenImport[]>;
28
28
  declare function scanDirectives(nitro: Nitro): Promise<GenImport[]>;
29
29
  declare function scanSchemas(nitro: Nitro): Promise<string[]>;
30
- declare function scanDocs(nitro: Nitro): Promise<string[]>;
30
+ declare function scanDocuments(nitro: Nitro): Promise<string[]>;
31
31
  /**
32
32
  * Scan documents for a specific external service
33
33
  */
@@ -37,4 +37,4 @@ declare function scanExternalServiceDocs(nitro: Nitro, serviceName: string, patt
37
37
  */
38
38
  declare function validateExternalServices(services: unknown[]): string[];
39
39
  //#endregion
40
- export { GLOB_SCAN_PATTERN, createDefaultMaskError, directiveParser, generateDirectiveSchema, generateDirectiveSchemas, generateLayerIgnorePatterns, getImportId, getLayerAppDirectories, getLayerDirectories, getLayerServerDirectories, relativeWithDot, scanDirectives, scanDocs, scanExternalServiceDocs, scanGraphql, scanResolvers, scanSchemas, validateExternalServices };
40
+ export { GLOB_SCAN_PATTERN, createDefaultMaskError, directiveParser, generateDirectiveSchema, generateDirectiveSchemas, generateLayerIgnorePatterns, getImportId, getLayerAppDirectories, getLayerDirectories, getLayerServerDirectories, relativeWithDot, scanDirectives, scanDocuments, scanExternalServiceDocs, scanGraphql, scanResolvers, scanSchemas, validateExternalServices };