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

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 (71) hide show
  1. package/dist/codegen/client-types.mjs +9 -54
  2. package/dist/codegen/external-types.mjs +7 -48
  3. package/dist/codegen/index.d.mts +4 -11
  4. package/dist/codegen/index.mjs +1 -15
  5. package/dist/codegen/server-types.mjs +2 -14
  6. package/dist/constants/scalars.mjs +27 -0
  7. package/dist/constants.mjs +16 -1
  8. package/dist/rollup.d.mts +1 -7
  9. package/dist/rollup.mjs +12 -187
  10. package/dist/routes/apollo-server.d.mts +2 -2
  11. package/dist/routes/apollo-server.mjs +7 -51
  12. package/dist/routes/debug-template.d.mts +15 -0
  13. package/dist/routes/debug-template.mjs +385 -0
  14. package/dist/routes/debug.d.mts +2 -2
  15. package/dist/routes/debug.mjs +1 -344
  16. package/dist/routes/graphql-yoga.d.mts +2 -2
  17. package/dist/routes/graphql-yoga.mjs +7 -51
  18. package/dist/routes/health.d.mts +2 -2
  19. package/dist/setup/file-watcher.mjs +9 -5
  20. package/dist/setup/graphql-scanner.mjs +25 -0
  21. package/dist/setup/scaffold-generator.mjs +1 -1
  22. package/dist/setup/ts-config.mjs +1 -1
  23. package/dist/setup.mjs +38 -47
  24. package/dist/types/index.d.mts +1 -1
  25. package/dist/utils/client-codegen.mjs +4 -30
  26. package/dist/utils/codegen-plugin.d.mts +20 -0
  27. package/dist/utils/codegen-plugin.mjs +30 -0
  28. package/dist/utils/federation.d.mts +29 -0
  29. package/dist/utils/federation.mjs +40 -0
  30. package/dist/utils/file-writer.d.mts +35 -0
  31. package/dist/utils/file-writer.mjs +32 -0
  32. package/dist/utils/imports.d.mts +15 -0
  33. package/dist/utils/imports.mjs +25 -0
  34. package/dist/utils/index.d.mts +11 -38
  35. package/dist/utils/index.mjs +10 -287
  36. package/dist/utils/layers.d.mts +22 -0
  37. package/dist/utils/layers.mjs +28 -0
  38. package/dist/utils/ofetch-templates.d.mts +30 -0
  39. package/dist/utils/ofetch-templates.mjs +135 -0
  40. package/dist/utils/scanning/common.d.mts +23 -0
  41. package/dist/utils/scanning/common.mjs +39 -0
  42. package/dist/utils/scanning/directives.d.mts +11 -0
  43. package/dist/utils/scanning/directives.mjs +43 -0
  44. package/dist/utils/scanning/documents.d.mts +15 -0
  45. package/dist/utils/scanning/documents.mjs +46 -0
  46. package/dist/utils/scanning/index.d.mts +6 -0
  47. package/dist/utils/scanning/index.mjs +7 -0
  48. package/dist/utils/scanning/resolvers.d.mts +11 -0
  49. package/dist/utils/scanning/resolvers.mjs +100 -0
  50. package/dist/utils/scanning/schemas.d.mts +15 -0
  51. package/dist/utils/scanning/schemas.mjs +29 -0
  52. package/dist/utils/schema-builder.d.mts +48 -0
  53. package/dist/utils/schema-builder.mjs +51 -0
  54. package/dist/utils/server-codegen.mjs +3 -29
  55. package/dist/utils/type-generation.d.mts +2 -2
  56. package/dist/utils/type-generation.mjs +2 -2
  57. package/dist/utils/validation.d.mts +11 -0
  58. package/dist/utils/validation.mjs +34 -0
  59. package/dist/virtual/generators/config.d.mts +22 -0
  60. package/dist/virtual/generators/config.mjs +36 -0
  61. package/dist/virtual/generators/debug.d.mts +14 -0
  62. package/dist/virtual/generators/debug.mjs +53 -0
  63. package/dist/virtual/generators/directives.d.mts +14 -0
  64. package/dist/virtual/generators/directives.mjs +52 -0
  65. package/dist/virtual/generators/index.d.mts +6 -0
  66. package/dist/virtual/generators/index.mjs +7 -0
  67. package/dist/virtual/generators/resolvers.d.mts +14 -0
  68. package/dist/virtual/generators/resolvers.mjs +55 -0
  69. package/dist/virtual/generators/schemas.d.mts +14 -0
  70. package/dist/virtual/generators/schemas.mjs +43 -0
  71. package/package.json +22 -18
@@ -1,25 +1,17 @@
1
1
  import { FILE_INDEX_TS, LOG_TAG, SERVICE_DEFAULT } from "../constants.mjs";
2
2
  import { generateClientTypes, loadGraphQLDocuments } from "../utils/client-codegen.mjs";
3
+ import { loadFederationSupport } from "../utils/federation.mjs";
3
4
  import { writeFileIfNotExists } from "../utils/file-generator.mjs";
5
+ import { generateOfetchTemplate } from "../utils/ofetch-templates.mjs";
4
6
  import { getClientUtilsConfig, getDefaultPaths, getSdkConfig, getTypesConfig, resolveFilePath, shouldGenerateClientUtils } from "../utils/path-resolver.mjs";
5
7
  import consola from "consola";
6
8
  import { dirname, join, resolve } from "pathe";
7
- import { buildSchema, parse } from "graphql";
8
9
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { buildSchema, parse } from "graphql";
9
11
 
10
12
  //#region src/codegen/client-types.ts
11
13
  const logger = consola.withTag(LOG_TAG);
12
14
  /**
13
- * Load federation support for client-side schema building
14
- */
15
- async function loadFederationSupport() {
16
- try {
17
- return (await import("@apollo/subgraph")).buildSubgraphSchema;
18
- } catch {
19
- return false;
20
- }
21
- }
22
- /**
23
15
  * Check for old structure files and warn user about manual migration
24
16
  */
25
17
  function warnLegacyGraphQLStructure(clientDir) {
@@ -127,49 +119,12 @@ function generateNuxtOfetchClient(nitro, clientDir, serviceName = SERVICE_DEFAUL
127
119
  const serviceDir = dirname(ofetchPath);
128
120
  if (!existsSync(serviceDir)) mkdirSync(serviceDir, { recursive: true });
129
121
  if (existsSync(ofetchPath)) return;
130
- writeFileIfNotExists(ofetchPath, nitro.options.framework?.name === "nuxt" ? `// This file is auto-generated once by nitro-graphql for quick start
131
- // You can modify this file according to your needs
132
- import type { Requester } from './sdk'
133
- import { getSdk } from './sdk'
134
-
135
- export function createGraphQLClient(endpoint: string): Requester {
136
- return async <R>(doc: string, vars?: any): Promise<R> => {
137
- const headers = import.meta.server ? useRequestHeaders() : undefined
138
-
139
- const result = await $fetch(endpoint, {
140
- method: 'POST',
141
- body: { query: doc, variables: vars },
142
- headers: {
143
- 'Content-Type': 'application/json',
144
- ...headers,
145
- },
146
- })
147
-
148
- return result as R
149
- }
150
- }
151
-
152
- export const $sdk = getSdk(createGraphQLClient('/api/graphql'))` : `// This file is auto-generated once by nitro-graphql for quick start
153
- // You can modify this file according to your needs
154
- import type { Requester } from './sdk'
155
- import { ofetch } from 'ofetch'
156
- import { getSdk } from './sdk'
157
-
158
- export function createGraphQLClient(endpoint: string): Requester {
159
- return async <R>(doc: string, vars?: any): Promise<R> => {
160
- const result = await ofetch(endpoint, {
161
- method: 'POST',
162
- body: { query: doc, variables: vars },
163
- headers: {
164
- 'Content-Type': 'application/json',
165
- },
166
- })
167
-
168
- return result as R
169
- }
170
- }
171
-
172
- export const $sdk = getSdk(createGraphQLClient('/api/graphql'))`, `${serviceName} ofetch.ts`);
122
+ writeFileIfNotExists(ofetchPath, generateOfetchTemplate({
123
+ serviceName,
124
+ isNuxt: nitro.options.framework?.name === "nuxt",
125
+ endpoint: "/api/graphql",
126
+ isExternal: false
127
+ }), `${serviceName} ofetch.ts`);
173
128
  }
174
129
 
175
130
  //#endregion
@@ -1,13 +1,12 @@
1
- import { LOG_TAG } from "../constants.mjs";
2
1
  import { downloadAndSaveSchema, generateExternalClientTypes, loadExternalSchema, loadGraphQLDocuments } from "../utils/client-codegen.mjs";
3
2
  import { writeFileIfNotExists } from "../utils/file-generator.mjs";
3
+ import { generateOfetchTemplate } from "../utils/ofetch-templates.mjs";
4
4
  import { getClientUtilsConfig, getDefaultPaths, getSdkConfig, getTypesConfig, resolveFilePath, shouldGenerateClientUtils } from "../utils/path-resolver.mjs";
5
5
  import consola from "consola";
6
6
  import { dirname } from "pathe";
7
7
  import { existsSync, mkdirSync, writeFileSync } from "node:fs";
8
8
 
9
9
  //#region src/codegen/external-types.ts
10
- consola.withTag(LOG_TAG);
11
10
  /**
12
11
  * Generate types for all external GraphQL services
13
12
  */
@@ -77,52 +76,12 @@ function generateExternalOfetchClient(nitro, service, endpoint) {
77
76
  if (!ofetchPath) return;
78
77
  const serviceDir = dirname(ofetchPath);
79
78
  if (!existsSync(serviceDir)) mkdirSync(serviceDir, { recursive: true });
80
- if (!existsSync(ofetchPath)) {
81
- const capitalizedServiceName = serviceName.charAt(0).toUpperCase() + serviceName.slice(1);
82
- writeFileIfNotExists(ofetchPath, nitro.options.framework?.name === "nuxt" ? `// This file is auto-generated once by nitro-graphql for quick start
83
- // You can modify this file according to your needs
84
- import type { Sdk, Requester } from './sdk'
85
- import { getSdk } from './sdk'
86
-
87
- export function create${capitalizedServiceName}GraphQLClient(endpoint: string = '${endpoint}'): Requester {
88
- return async <R>(doc: string, vars?: any): Promise<R> => {
89
- const headers = import.meta.server ? useRequestHeaders() : undefined
90
-
91
- const result = await $fetch(endpoint, {
92
- method: 'POST',
93
- body: { query: doc, variables: vars },
94
- headers: {
95
- 'Content-Type': 'application/json',
96
- ...headers,
97
- },
98
- })
99
-
100
- return result as R
101
- }
102
- }
103
-
104
- export const $${serviceName}Sdk: Sdk = getSdk(create${capitalizedServiceName}GraphQLClient())` : `// This file is auto-generated once by nitro-graphql for quick start
105
- // You can modify this file according to your needs
106
- import type { Sdk, Requester } from './sdk'
107
- import { ofetch } from 'ofetch'
108
- import { getSdk } from './sdk'
109
-
110
- export function create${capitalizedServiceName}GraphQLClient(endpoint: string = '${endpoint}'): Requester {
111
- return async <R>(doc: string, vars?: any): Promise<R> => {
112
- const result = await ofetch(endpoint, {
113
- method: 'POST',
114
- body: { query: doc, variables: vars },
115
- headers: {
116
- 'Content-Type': 'application/json',
117
- },
118
- })
119
-
120
- return result as R
121
- }
122
- }
123
-
124
- export const $${serviceName}Sdk: Sdk = getSdk(create${capitalizedServiceName}GraphQLClient())`, `${serviceName} external ofetch.ts`);
125
- }
79
+ if (!existsSync(ofetchPath)) writeFileIfNotExists(ofetchPath, generateOfetchTemplate({
80
+ serviceName,
81
+ isNuxt: nitro.options.framework?.name === "nuxt",
82
+ endpoint,
83
+ isExternal: true
84
+ }), `${serviceName} external ofetch.ts`);
126
85
  }
127
86
 
128
87
  //#endregion
@@ -7,19 +7,12 @@ import { Nitro } from "nitro/types";
7
7
  //#region src/codegen/index.d.ts
8
8
 
9
9
  /**
10
- * Generate server-side GraphQL resolver types
11
- * @deprecated Use generateServerTypes instead
10
+ * Generate client-side GraphQL types
11
+ * Generates types for both main service and external services
12
12
  */
13
- declare function serverTypeGeneration(nitro: Nitro, options?: {
14
- silent?: boolean;
15
- }): Promise<void>;
16
- /**
17
- * Generate client-side GraphQL types (main service + external services)
18
- * @deprecated Use generateClientTypes instead
19
- */
20
- declare function clientTypeGeneration(nitro: Nitro, options?: {
13
+ declare function generateClientTypes(nitro: Nitro, options?: {
21
14
  silent?: boolean;
22
15
  isInitial?: boolean;
23
16
  }): Promise<void>;
24
17
  //#endregion
25
- export { clientTypeGeneration, serverTypeGeneration };
18
+ export { generateClientTypes };
@@ -8,20 +8,6 @@ import consola from "consola";
8
8
  //#region src/codegen/index.ts
9
9
  const logger = consola.withTag(LOG_TAG);
10
10
  /**
11
- * Generate server-side GraphQL resolver types
12
- * @deprecated Use generateServerTypes instead
13
- */
14
- async function serverTypeGeneration(nitro, options = {}) {
15
- return generateServerTypes(nitro, options);
16
- }
17
- /**
18
- * Generate client-side GraphQL types (main service + external services)
19
- * @deprecated Use generateClientTypes instead
20
- */
21
- async function clientTypeGeneration(nitro, options = {}) {
22
- return generateClientTypes(nitro, options);
23
- }
24
- /**
25
11
  * Generate client-side GraphQL types
26
12
  * Generates types for both main service and external services
27
13
  */
@@ -35,4 +21,4 @@ async function generateClientTypes(nitro, options = {}) {
35
21
  }
36
22
 
37
23
  //#endregion
38
- export { clientTypeGeneration, serverTypeGeneration };
24
+ export { generateClientTypes };
@@ -1,30 +1,18 @@
1
1
  import { LOG_TAG } from "../constants.mjs";
2
+ import { loadFederationSupport } from "../utils/federation.mjs";
2
3
  import { getDefaultPaths, getTypesConfig, resolveFilePath, shouldGenerateTypes } from "../utils/path-resolver.mjs";
3
4
  import { generateTypes } from "../utils/server-codegen.mjs";
4
5
  import { validateNoDuplicateTypes } from "./validation.mjs";
5
6
  import consola from "consola";
6
7
  import { dirname, resolve } from "pathe";
7
- import { buildSchema, parse } from "graphql";
8
8
  import { mkdirSync, writeFileSync } from "node:fs";
9
+ import { buildSchema, parse } from "graphql";
9
10
  import { printSchemaWithDirectives } from "@graphql-tools/utils";
10
11
  import { loadFilesSync } from "@graphql-tools/load-files";
11
12
  import { mergeTypeDefs } from "@graphql-tools/merge";
12
13
 
13
14
  //#region src/codegen/server-types.ts
14
15
  const logger = consola.withTag(LOG_TAG);
15
- let buildSubgraphSchema = null;
16
- /**
17
- * Load Apollo Federation support if enabled
18
- */
19
- async function loadFederationSupport() {
20
- if (buildSubgraphSchema !== null) return buildSubgraphSchema;
21
- try {
22
- buildSubgraphSchema = (await import("@apollo/subgraph")).buildSubgraphSchema;
23
- } catch {
24
- buildSubgraphSchema = false;
25
- }
26
- return buildSubgraphSchema;
27
- }
28
16
  /**
29
17
  * Generate server-side GraphQL types
30
18
  * Creates resolver types from GraphQL schemas
@@ -0,0 +1,27 @@
1
+ import { CurrencyResolver, DateTimeISOResolver, DateTimeResolver, JSONObjectResolver, JSONResolver, NonEmptyStringResolver, UUIDResolver } from "graphql-scalars";
2
+
3
+ //#region src/constants/scalars.ts
4
+ /**
5
+ * Default GraphQL scalar type definitions
6
+ * Used by both server and client codegen
7
+ */
8
+ /**
9
+ * Default scalar type mappings for GraphQL codegen
10
+ * These scalars are commonly used and have proper TypeScript type mappings
11
+ */
12
+ const DEFAULT_GRAPHQL_SCALARS = {
13
+ DateTime: DateTimeResolver.extensions.codegenScalarType,
14
+ DateTimeISO: DateTimeISOResolver.extensions.codegenScalarType,
15
+ UUID: UUIDResolver.extensions.codegenScalarType,
16
+ JSON: JSONResolver.extensions.codegenScalarType,
17
+ JSONObject: JSONObjectResolver.extensions.codegenScalarType,
18
+ NonEmptyString: NonEmptyStringResolver.extensions.codegenScalarType,
19
+ Currency: CurrencyResolver.extensions.codegenScalarType,
20
+ File: {
21
+ input: "File",
22
+ output: "File"
23
+ }
24
+ };
25
+
26
+ //#endregion
27
+ export { DEFAULT_GRAPHQL_SCALARS };
@@ -16,6 +16,10 @@ const RESOLVER_EXTENSIONS = [".resolver.ts", ".resolver.js"];
16
16
  */
17
17
  const DIRECTIVE_EXTENSIONS = [".directive.ts", ".directive.js"];
18
18
  /**
19
+ * Combined pattern for glob scanning
20
+ */
21
+ const GLOB_SCAN_PATTERN = "**/*.{graphql,gql,js,mjs,cjs,ts,mts,cts,tsx,jsx}";
22
+ /**
19
23
  * Framework names
20
24
  */
21
25
  const FRAMEWORK_NUXT = "nuxt";
@@ -54,6 +58,17 @@ const CHUNK_PATH_UNKNOWN = "chunks/_/[name].mjs";
54
58
  const CHUNK_NAME_SCHEMAS = "schemas";
55
59
  const CHUNK_NAME_RESOLVERS = "resolvers";
56
60
  /**
61
+ * Valid define function names for resolver exports
62
+ */
63
+ const DEFINE_FUNCTIONS = [
64
+ "defineResolver",
65
+ "defineQuery",
66
+ "defineMutation",
67
+ "defineField",
68
+ "defineSubscription",
69
+ "defineDirective"
70
+ ];
71
+ /**
57
72
  * Built-in GraphQL scalar types (should not be flagged as duplicates)
58
73
  */
59
74
  const BUILTIN_SCALARS = [
@@ -88,4 +103,4 @@ const LOG_TAG = "nitro-graphql";
88
103
  const SERVICE_DEFAULT = "default";
89
104
 
90
105
  //#endregion
91
- export { BUILTIN_SCALARS, CHUNK_NAME_RESOLVERS, CHUNK_NAME_SCHEMAS, CHUNK_PATH_GRAPHQL, CHUNK_PATH_UNKNOWN, DEFAULT_CLIENT_TYPES_PATH, DEFAULT_SERVER_TYPES_PATH, DIRECTIVE_EXTENSIONS, DIR_SERVER_GRAPHQL, DIR_SERVER_GRAPHQL_WIN, ENDPOINT_DEBUG, ENDPOINT_GRAPHQL, ENDPOINT_HEALTH, FILE_CONFIG_TS, FILE_CONTEXT_DTS, FILE_CONTEXT_TS, FILE_GRAPHQL_CONFIG, FILE_INDEX_TS, FILE_SCHEMA_TS, FRAMEWORK_NITRO, FRAMEWORK_NUXT, GRAPHQL_EXTENSIONS, GRAPHQL_HTTP_METHODS, LOG_TAG, RESOLVER_EXTENSIONS, SERVICE_DEFAULT };
106
+ export { BUILTIN_SCALARS, CHUNK_NAME_RESOLVERS, CHUNK_NAME_SCHEMAS, CHUNK_PATH_GRAPHQL, CHUNK_PATH_UNKNOWN, DEFAULT_CLIENT_TYPES_PATH, DEFAULT_SERVER_TYPES_PATH, DEFINE_FUNCTIONS, DIRECTIVE_EXTENSIONS, DIR_SERVER_GRAPHQL, DIR_SERVER_GRAPHQL_WIN, ENDPOINT_DEBUG, ENDPOINT_GRAPHQL, ENDPOINT_HEALTH, FILE_CONFIG_TS, FILE_CONTEXT_DTS, FILE_CONTEXT_TS, FILE_GRAPHQL_CONFIG, FILE_INDEX_TS, FILE_SCHEMA_TS, FRAMEWORK_NITRO, FRAMEWORK_NUXT, GLOB_SCAN_PATTERN, GRAPHQL_EXTENSIONS, GRAPHQL_HTTP_METHODS, LOG_TAG, RESOLVER_EXTENSIONS, SERVICE_DEFAULT };
package/dist/rollup.d.mts CHANGED
@@ -2,11 +2,5 @@ import { Nitro } from "nitro/types";
2
2
 
3
3
  //#region src/rollup.d.ts
4
4
  declare function rollupConfig(nitro: Nitro): Promise<void>;
5
- declare function virtualSchemas(nitro: Nitro): void;
6
- declare function virtualResolvers(nitro: Nitro): void;
7
- declare function virtualDirectives(nitro: Nitro): void;
8
- declare function getGraphQLConfig(nitro: Nitro): void;
9
- declare function virtualModuleConfig(nitro: Nitro): void;
10
- declare function virtualDebugInfo(nitro: Nitro): void;
11
5
  //#endregion
12
- export { getGraphQLConfig, rollupConfig, virtualDebugInfo, virtualDirectives, virtualModuleConfig, virtualResolvers, virtualSchemas };
6
+ export { rollupConfig };
package/dist/rollup.mjs CHANGED
@@ -1,17 +1,21 @@
1
- import { getImportId, scanGraphql } from "./utils/index.mjs";
2
- import { clientTypeGeneration, serverTypeGeneration } from "./codegen/index.mjs";
1
+ import { generateServerTypes } from "./codegen/server-types.mjs";
2
+ import { generateClientTypes } from "./codegen/index.mjs";
3
+ import { scanGraphql } from "./utils/scanning/schemas.mjs";
4
+ import { virtualGraphQLConfig, virtualModuleConfig } from "./virtual/generators/config.mjs";
5
+ import { virtualDebugInfo } from "./virtual/generators/debug.mjs";
6
+ import { virtualDirectives } from "./virtual/generators/directives.mjs";
7
+ import { virtualResolvers } from "./virtual/generators/resolvers.mjs";
8
+ import { virtualSchemas } from "./virtual/generators/schemas.mjs";
3
9
  import { readFile } from "node:fs/promises";
4
10
  import { fileURLToPath } from "node:url";
5
- import { resolve } from "pathe";
6
11
  import { parse } from "graphql";
7
- import { genImport } from "knitwork";
8
12
 
9
13
  //#region src/rollup.ts
10
14
  async function rollupConfig(nitro) {
11
15
  virtualSchemas(nitro);
12
16
  virtualResolvers(nitro);
13
17
  virtualDirectives(nitro);
14
- getGraphQLConfig(nitro);
18
+ virtualGraphQLConfig(nitro);
15
19
  virtualModuleConfig(nitro);
16
20
  virtualDebugInfo(nitro);
17
21
  nitro.hooks.hook("rollup:before", (_, rollupConfig$1) => {
@@ -94,189 +98,10 @@ async function rollupConfig(nitro) {
94
98
  }
95
99
  });
96
100
  nitro.hooks.hook("dev:reload", async () => {
97
- await serverTypeGeneration(nitro, { silent: true });
98
- await clientTypeGeneration(nitro, { silent: true });
101
+ await generateServerTypes(nitro, { silent: true });
102
+ await generateClientTypes(nitro, { silent: true });
99
103
  });
100
104
  }
101
- function virtualSchemas(nitro) {
102
- const getSchemas = () => [...nitro.scanSchemas, ...nitro.options.graphql?.typedefs ?? []];
103
- nitro.options.virtual ??= {};
104
- nitro.options.virtual["#nitro-graphql/server-schemas"] = () => {
105
- try {
106
- const imports = getSchemas();
107
- if (imports.length === 0) {
108
- if (nitro.options.dev) nitro.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")}
115
-
116
- export const schemas = [
117
- ${schemaArray.join(",\n")}
118
- ];
119
- `;
120
- } catch (error) {
121
- nitro.logger.error("[nitro-graphql] Failed to generate virtual schema module:", error);
122
- return "export const schemas = []";
123
- }
124
- };
125
- }
126
- function virtualResolvers(nitro) {
127
- const getResolvers = () => [...nitro.scanResolvers];
128
- nitro.options.virtual ??= {};
129
- nitro.options.virtual["#nitro-graphql/server-resolvers"] = () => {
130
- try {
131
- const imports = getResolvers();
132
- if (imports.length === 0) {
133
- if (nitro.options.dev) nitro.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: options$1 } 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$1);
144
- importsContent.push(importCode);
145
- } catch (error) {
146
- const message = error instanceof Error ? error.message : String(error);
147
- invalidImports.push(`${specifier}: ${message}`);
148
- if (nitro.options.dev) nitro.logger.error(`[nitro-graphql] Failed to generate import for ${specifier}:`, error);
149
- }
150
- if (invalidImports.length > 0 && nitro.options.dev) {
151
- nitro.logger.warn("[nitro-graphql] Some resolver imports could not be generated:");
152
- for (const msg of invalidImports) nitro.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
- nitro.logger.error("[nitro-graphql] Failed to generate virtual resolver module:", error);
165
- return "export const resolvers = []";
166
- }
167
- };
168
- }
169
- function virtualDirectives(nitro) {
170
- const getDirectives = () => nitro.scanDirectives || [];
171
- nitro.options.virtual ??= {};
172
- nitro.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: options$1 } 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$1);
184
- importsContent.push(importCode);
185
- } catch (error) {
186
- const message = error instanceof Error ? error.message : String(error);
187
- invalidImports.push(`${specifier}: ${message}`);
188
- if (nitro.options.dev) nitro.logger.error(`[nitro-graphql] Failed to generate import for directive ${specifier}:`, error);
189
- }
190
- if (invalidImports.length > 0 && nitro.options.dev) {
191
- nitro.logger.warn("[nitro-graphql] Some directive imports could not be generated:");
192
- for (const msg of invalidImports) nitro.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
- nitro.logger.error("[nitro-graphql] Failed to generate virtual directive module:", error);
205
- return "export const directives = []";
206
- }
207
- };
208
- }
209
- function getGraphQLConfig(nitro) {
210
- const configPath = resolve(nitro.graphql.serverDir, "config.ts");
211
- nitro.options.virtual ??= {};
212
- nitro.options.virtual["#nitro-graphql/graphql-config"] = () => {
213
- return `import config from '${configPath}'
214
- const importedConfig = config
215
- export { importedConfig }
216
- `;
217
- };
218
- }
219
- function virtualModuleConfig(nitro) {
220
- nitro.options.virtual ??= {};
221
- nitro.options.virtual["#nitro-graphql/module-config"] = () => {
222
- const moduleConfig = nitro.options.graphql || {};
223
- return `export const moduleConfig = ${JSON.stringify(moduleConfig, null, 2)};`;
224
- };
225
- }
226
- function virtualDebugInfo(nitro) {
227
- nitro.options.virtual ??= {};
228
- nitro.options.virtual["#nitro-graphql/debug-info"] = () => {
229
- const virtualModuleCodes = {};
230
- try {
231
- const schemasGenerator = nitro.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 = nitro.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 = nitro.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 = nitro.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 = nitro.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: nitro.options.dev,
262
- framework: nitro.options.framework.name,
263
- graphqlFramework: nitro.options.graphql?.framework,
264
- federation: nitro.options.graphql?.federation,
265
- scanned: {
266
- schemas: nitro.scanSchemas?.length || 0,
267
- schemaFiles: nitro.scanSchemas || [],
268
- resolvers: nitro.scanResolvers?.length || 0,
269
- resolverFiles: nitro.scanResolvers || [],
270
- directives: nitro.scanDirectives?.length || 0,
271
- directiveFiles: nitro.scanDirectives || [],
272
- documents: nitro.scanDocuments?.length || 0,
273
- documentFiles: nitro.scanDocuments || []
274
- },
275
- virtualModules: virtualModuleCodes
276
- };
277
- return `export const debugInfo = ${JSON.stringify(debugInfo, null, 2)};`;
278
- };
279
- }
280
105
 
281
106
  //#endregion
282
- export { getGraphQLConfig, rollupConfig, virtualDebugInfo, virtualDirectives, virtualModuleConfig, virtualResolvers, virtualSchemas };
107
+ export { rollupConfig };
@@ -1,6 +1,6 @@
1
- import * as nitro_deps_h35 from "nitro/deps/h3";
1
+ import * as nitro_deps_h31 from "nitro/deps/h3";
2
2
 
3
3
  //#region src/routes/apollo-server.d.ts
4
- declare const _default: nitro_deps_h35.EventHandlerWithFetch<nitro_deps_h35.EventHandlerRequest, Promise<any>>;
4
+ declare const _default: nitro_deps_h31.EventHandlerWithFetch<nitro_deps_h31.EventHandlerRequest, Promise<any>>;
5
5
  //#endregion
6
6
  export { _default as default };
@@ -1,7 +1,5 @@
1
+ import { createMergedSchema } from "../utils/schema-builder.mjs";
1
2
  import defu from "defu";
2
- import { consola as consola$1 } from "consola";
3
- import { parse } from "graphql";
4
- import { mergeResolvers, mergeTypeDefs } from "@graphql-tools/merge";
5
3
  import { importedConfig } from "#nitro-graphql/graphql-config";
6
4
  import { moduleConfig } from "#nitro-graphql/module-config";
7
5
  import { directives } from "#nitro-graphql/server-directives";
@@ -9,63 +7,21 @@ import { resolvers } from "#nitro-graphql/server-resolvers";
9
7
  import { schemas } from "#nitro-graphql/server-schemas";
10
8
  import { ApolloServer } from "@apollo/server";
11
9
  import { ApolloServerPluginLandingPageLocalDefault } from "@apollo/server/plugin/landingPage/default";
12
- import { makeExecutableSchema } from "@graphql-tools/schema";
13
10
  import { startServerAndCreateH3Handler } from "nitro-graphql/utils/apollo";
14
11
  import { defineEventHandler } from "nitro/h3";
15
12
 
16
13
  //#region src/routes/apollo-server.ts
17
- let buildSubgraphSchema = null;
18
- async function loadFederationSupport() {
19
- if (buildSubgraphSchema !== null) return buildSubgraphSchema;
20
- try {
21
- buildSubgraphSchema = (await import("@apollo/subgraph")).buildSubgraphSchema;
22
- } catch {
23
- buildSubgraphSchema = false;
24
- }
25
- return buildSubgraphSchema;
26
- }
27
- async function createMergedSchema() {
28
- try {
29
- const typeDefs = mergeTypeDefs([schemas.map((schema$1) => schema$1.def).join("\n\n")], {
30
- throwOnConflict: true,
31
- commentDescriptions: true,
32
- sort: true
33
- });
34
- const mergedResolvers = mergeResolvers(resolvers.map((r) => r.resolver));
35
- const federationEnabled = moduleConfig.federation?.enabled;
36
- let schema;
37
- if (federationEnabled) {
38
- const buildSubgraph = await loadFederationSupport();
39
- if (buildSubgraph) schema = buildSubgraph({
40
- typeDefs: typeof typeDefs === "string" ? parse(typeDefs) : typeDefs,
41
- resolvers: mergedResolvers
42
- });
43
- else {
44
- console.warn("Federation enabled but @apollo/subgraph not available, falling back to regular schema");
45
- schema = makeExecutableSchema({
46
- typeDefs,
47
- resolvers: mergedResolvers
48
- });
49
- }
50
- } else schema = makeExecutableSchema({
51
- typeDefs,
52
- resolvers: mergedResolvers
53
- });
54
- if (directives && directives.length > 0) {
55
- for (const { directive } of directives) if (directive.transformer) schema = directive.transformer(schema);
56
- }
57
- return schema;
58
- } catch (error) {
59
- consola$1.error("Schema merge error:", error);
60
- throw error;
61
- }
62
- }
63
14
  let apolloServer = null;
64
15
  let serverStarted = false;
65
16
  async function createApolloServer() {
66
17
  if (!apolloServer) {
67
18
  apolloServer = new ApolloServer(defu({
68
- schema: await createMergedSchema(),
19
+ schema: await createMergedSchema({
20
+ schemas,
21
+ resolvers,
22
+ directives,
23
+ moduleConfig
24
+ }),
69
25
  introspection: true,
70
26
  plugins: [ApolloServerPluginLandingPageLocalDefault({ embed: true })]
71
27
  }, importedConfig));
@@ -0,0 +1,15 @@
1
+ //#region src/routes/debug-template.d.ts
2
+ /**
3
+ * Debug dashboard HTML template
4
+ * Extracted from debug.ts to reduce file complexity
5
+ */
6
+ /**
7
+ * Escape HTML special characters
8
+ */
9
+ declare function escapeHtml(text: string): string;
10
+ /**
11
+ * Generate the HTML dashboard for the debug endpoint
12
+ */
13
+ declare function generateHtmlDashboard(debugInfo: any): string;
14
+ //#endregion
15
+ export { escapeHtml, generateHtmlDashboard };