nitro-graphql 2.0.0-beta.37 → 2.0.0-beta.39

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 (204) hide show
  1. package/README.md +2 -2
  2. package/dist/cli/commands/generate.d.mts +26 -0
  3. package/dist/cli/commands/generate.mjs +196 -0
  4. package/dist/cli/commands/index.d.mts +4 -0
  5. package/dist/cli/commands/index.mjs +5 -0
  6. package/dist/cli/commands/init.d.mts +43 -0
  7. package/dist/cli/commands/init.mjs +191 -0
  8. package/dist/cli/commands/validate.d.mts +10 -0
  9. package/dist/cli/commands/validate.mjs +69 -0
  10. package/dist/cli/completions.d.mts +7 -0
  11. package/dist/cli/completions.mjs +34 -0
  12. package/dist/cli/config.d.mts +75 -0
  13. package/dist/cli/config.mjs +20 -0
  14. package/dist/cli/index.d.mts +24 -0
  15. package/dist/cli/index.mjs +253 -0
  16. package/dist/core/codegen/client.d.mts +23 -0
  17. package/dist/core/codegen/client.mjs +150 -0
  18. package/dist/core/codegen/document-loader.d.mts +10 -0
  19. package/dist/core/codegen/document-loader.mjs +18 -0
  20. package/dist/core/codegen/index.d.mts +8 -0
  21. package/dist/core/codegen/index.mjs +9 -0
  22. package/dist/{utils/codegen-plugin.d.mts → core/codegen/plugin.d.mts} +2 -2
  23. package/dist/{utils/codegen-plugin.mjs → core/codegen/plugin.mjs} +1 -1
  24. package/dist/core/codegen/runtime.d.mts +20 -0
  25. package/dist/core/codegen/runtime.mjs +60 -0
  26. package/dist/core/codegen/schema-loader.d.mts +28 -0
  27. package/dist/core/codegen/schema-loader.mjs +128 -0
  28. package/dist/core/codegen/server.d.mts +28 -0
  29. package/dist/core/codegen/server.mjs +143 -0
  30. package/dist/{codegen → core/codegen}/validation.d.mts +1 -1
  31. package/dist/{codegen → core/codegen}/validation.mjs +1 -1
  32. package/dist/core/config.d.mts +50 -0
  33. package/dist/core/config.mjs +82 -0
  34. package/dist/core/constants.d.mts +188 -0
  35. package/dist/core/constants.mjs +210 -0
  36. package/dist/core/index.d.mts +32 -0
  37. package/dist/core/index.mjs +26 -0
  38. package/dist/core/scanning/ast-scanner.d.mts +23 -0
  39. package/dist/core/scanning/ast-scanner.mjs +103 -0
  40. package/dist/core/scanning/common.d.mts +37 -0
  41. package/dist/core/scanning/common.mjs +60 -0
  42. package/dist/core/scanning/directives.d.mts +10 -0
  43. package/dist/core/scanning/directives.mjs +29 -0
  44. package/dist/core/scanning/documents.d.mts +21 -0
  45. package/dist/core/scanning/documents.mjs +43 -0
  46. package/dist/core/scanning/index.d.mts +7 -0
  47. package/dist/core/scanning/index.mjs +8 -0
  48. package/dist/core/scanning/resolvers.d.mts +10 -0
  49. package/dist/core/scanning/resolvers.mjs +58 -0
  50. package/dist/core/scanning/schemas.d.mts +14 -0
  51. package/dist/core/scanning/schemas.mjs +64 -0
  52. package/dist/{utils/schema-builder.d.mts → core/schema/builder.d.mts} +7 -2
  53. package/dist/{utils/schema-builder.mjs → core/schema/builder.mjs} +22 -3
  54. package/dist/{utils → core/schema}/federation.d.mts +10 -5
  55. package/dist/{utils → core/schema}/federation.mjs +1 -1
  56. package/dist/core/schema/index.d.mts +3 -0
  57. package/dist/core/schema/index.mjs +4 -0
  58. package/dist/core/types/adapter.d.mts +58 -0
  59. package/dist/core/types/codegen.d.mts +133 -0
  60. package/dist/core/types/config.d.mts +212 -0
  61. package/dist/{types → core/types}/define.d.mts +3 -7
  62. package/dist/core/types/index.d.mts +5 -0
  63. package/dist/core/types/scanning.d.mts +69 -0
  64. package/dist/core/types/scanning.mjs +1 -0
  65. package/dist/{utils → core/utils}/directive-parser.d.mts +21 -5
  66. package/dist/{utils → core/utils}/directive-parser.mjs +25 -36
  67. package/dist/{utils → core/utils}/errors.d.mts +8 -4
  68. package/dist/{utils → core/utils}/errors.mjs +8 -4
  69. package/dist/core/utils/file-io.d.mts +24 -0
  70. package/dist/core/utils/file-io.mjs +47 -0
  71. package/dist/{utils → core/utils}/imports.d.mts +1 -1
  72. package/dist/{utils → core/utils}/imports.mjs +1 -1
  73. package/dist/core/utils/index.d.mts +7 -0
  74. package/dist/core/utils/index.mjs +8 -0
  75. package/dist/core/utils/logger.d.mts +19 -0
  76. package/dist/core/utils/logger.mjs +38 -0
  77. package/dist/{utils → core/utils}/ofetch-templates.d.mts +1 -1
  78. package/dist/{utils → core/utils}/ofetch-templates.mjs +1 -1
  79. package/dist/core/validation/external-services.d.mts +11 -0
  80. package/dist/{utils/validation.mjs → core/validation/external-services.mjs} +3 -3
  81. package/dist/core/validation/index.d.mts +2 -0
  82. package/dist/core/validation/index.mjs +3 -0
  83. package/dist/define.d.mts +2 -4
  84. package/dist/define.mjs +1 -1
  85. package/dist/index.d.mts +6 -44
  86. package/dist/index.mjs +5 -62
  87. package/dist/nitro/adapter.d.mts +30 -0
  88. package/dist/nitro/adapter.mjs +97 -0
  89. package/dist/{utils → nitro}/apollo.d.mts +1 -1
  90. package/dist/{utils → nitro}/apollo.mjs +1 -1
  91. package/dist/nitro/codegen.d.mts +19 -0
  92. package/dist/nitro/codegen.mjs +141 -0
  93. package/dist/nitro/config.d.mts +52 -0
  94. package/dist/nitro/config.mjs +58 -0
  95. package/dist/nitro/index.d.mts +46 -0
  96. package/dist/nitro/index.mjs +65 -0
  97. package/dist/{utils/path-resolver.d.mts → nitro/paths.d.mts} +3 -19
  98. package/dist/{utils/path-resolver.mjs → nitro/paths.mjs} +2 -36
  99. package/dist/{rollup.d.mts → nitro/rollup.d.mts} +1 -1
  100. package/dist/{rollup.mjs → nitro/rollup.mjs} +11 -23
  101. package/dist/{routes → nitro/routes}/apollo-server.d.mts +1 -1
  102. package/dist/{routes → nitro/routes}/apollo-server.mjs +5 -5
  103. package/dist/{routes → nitro/routes}/debug-template.d.mts +1 -1
  104. package/dist/{routes → nitro/routes}/debug-template.mjs +1 -1
  105. package/dist/{routes → nitro/routes}/debug.d.mts +10 -16
  106. package/dist/{routes → nitro/routes}/debug.mjs +2 -2
  107. package/dist/{routes → nitro/routes}/graphql-yoga.d.mts +1 -1
  108. package/dist/{routes → nitro/routes}/graphql-yoga.mjs +3 -3
  109. package/dist/{routes → nitro/routes}/health.d.mts +1 -1
  110. package/dist/{routes → nitro/routes}/health.mjs +1 -1
  111. package/dist/nitro/setup/file-watcher.d.mts +16 -0
  112. package/dist/{setup → nitro/setup}/file-watcher.mjs +14 -18
  113. package/dist/{setup.d.mts → nitro/setup/logging.d.mts} +5 -6
  114. package/dist/nitro/setup/logging.mjs +66 -0
  115. package/dist/nitro/setup/rollup-integration.d.mts +16 -0
  116. package/dist/{setup → nitro/setup}/rollup-integration.mjs +2 -2
  117. package/dist/nitro/setup/routes.d.mts +10 -0
  118. package/dist/nitro/setup/routes.mjs +35 -0
  119. package/dist/nitro/setup/ts-config.d.mts +11 -0
  120. package/dist/{setup → nitro/setup}/ts-config.mjs +3 -3
  121. package/dist/nitro/setup.d.mts +12 -0
  122. package/dist/{setup.mjs → nitro/setup.mjs} +33 -100
  123. package/dist/{types/index.d.mts → nitro/types.d.mts} +125 -43
  124. package/dist/nitro/types.mjs +1 -0
  125. package/dist/nitro/virtual/generators.d.mts +31 -0
  126. package/dist/nitro/virtual/generators.mjs +193 -0
  127. package/dist/nitro/virtual/stubs.d.mts +20 -0
  128. package/dist/nitro/virtual/stubs.mjs +31 -0
  129. package/dist/{ecosystem/nuxt.d.mts → nuxt.d.mts} +1 -1
  130. package/dist/{ecosystem/nuxt.mjs → nuxt.mjs} +2 -2
  131. package/dist/{graphql/server.d.mts → stubs/index.d.mts} +5 -1
  132. package/dist/stubs/index.mjs +1 -0
  133. package/package.json +45 -42
  134. package/dist/codegen/client-types.d.mts +0 -13
  135. package/dist/codegen/client-types.mjs +0 -131
  136. package/dist/codegen/external-types.d.mts +0 -12
  137. package/dist/codegen/external-types.mjs +0 -88
  138. package/dist/codegen/index.d.mts +0 -18
  139. package/dist/codegen/index.mjs +0 -24
  140. package/dist/codegen/server-types.d.mts +0 -13
  141. package/dist/codegen/server-types.mjs +0 -64
  142. package/dist/config/defaults.mjs +0 -36
  143. package/dist/constants/scalars.mjs +0 -27
  144. package/dist/constants.mjs +0 -106
  145. package/dist/graphql/index.d.mts +0 -5
  146. package/dist/setup/graphql-scanner.mjs +0 -25
  147. package/dist/setup/scaffold-generator.mjs +0 -109
  148. package/dist/types/standard-schema.d.mts +0 -59
  149. package/dist/utils/client-codegen.d.mts +0 -41
  150. package/dist/utils/client-codegen.mjs +0 -277
  151. package/dist/utils/file-generator.d.mts +0 -37
  152. package/dist/utils/file-generator.mjs +0 -72
  153. package/dist/utils/file-writer.d.mts +0 -35
  154. package/dist/utils/file-writer.mjs +0 -32
  155. package/dist/utils/index.d.mts +0 -13
  156. package/dist/utils/index.mjs +0 -13
  157. package/dist/utils/layers.d.mts +0 -22
  158. package/dist/utils/layers.mjs +0 -28
  159. package/dist/utils/scanning/common.d.mts +0 -23
  160. package/dist/utils/scanning/common.mjs +0 -39
  161. package/dist/utils/scanning/directives.d.mts +0 -11
  162. package/dist/utils/scanning/directives.mjs +0 -43
  163. package/dist/utils/scanning/documents.d.mts +0 -15
  164. package/dist/utils/scanning/documents.mjs +0 -46
  165. package/dist/utils/scanning/index.d.mts +0 -6
  166. package/dist/utils/scanning/index.mjs +0 -7
  167. package/dist/utils/scanning/resolvers.d.mts +0 -11
  168. package/dist/utils/scanning/resolvers.mjs +0 -100
  169. package/dist/utils/scanning/schemas.d.mts +0 -15
  170. package/dist/utils/scanning/schemas.mjs +0 -29
  171. package/dist/utils/server-codegen.d.mts +0 -7
  172. package/dist/utils/server-codegen.mjs +0 -113
  173. package/dist/utils/type-generation.d.mts +0 -6
  174. package/dist/utils/type-generation.mjs +0 -7
  175. package/dist/utils/validation.d.mts +0 -11
  176. package/dist/virtual/debug-info.d.mts +0 -9
  177. package/dist/virtual/debug-info.mjs +0 -26
  178. package/dist/virtual/generators/config.d.mts +0 -22
  179. package/dist/virtual/generators/config.mjs +0 -36
  180. package/dist/virtual/generators/debug.d.mts +0 -14
  181. package/dist/virtual/generators/debug.mjs +0 -53
  182. package/dist/virtual/generators/directives.d.mts +0 -14
  183. package/dist/virtual/generators/directives.mjs +0 -52
  184. package/dist/virtual/generators/index.d.mts +0 -6
  185. package/dist/virtual/generators/index.mjs +0 -7
  186. package/dist/virtual/generators/resolvers.d.mts +0 -14
  187. package/dist/virtual/generators/resolvers.mjs +0 -55
  188. package/dist/virtual/generators/schemas.d.mts +0 -14
  189. package/dist/virtual/generators/schemas.mjs +0 -43
  190. package/dist/virtual/graphql-config.d.mts +0 -9
  191. package/dist/virtual/graphql-config.mjs +0 -10
  192. package/dist/virtual/module-config.d.mts +0 -9
  193. package/dist/virtual/module-config.mjs +0 -10
  194. package/dist/virtual/server-directives.d.mts +0 -11
  195. package/dist/virtual/server-directives.mjs +0 -10
  196. package/dist/virtual/server-resolvers.d.mts +0 -11
  197. package/dist/virtual/server-resolvers.mjs +0 -10
  198. package/dist/virtual/server-schemas.d.mts +0 -11
  199. package/dist/virtual/server-schemas.mjs +0 -10
  200. /package/dist/{graphql/index.mjs → core/types/adapter.mjs} +0 -0
  201. /package/dist/{graphql/server.mjs → core/types/codegen.mjs} +0 -0
  202. /package/dist/{types/define.mjs → core/types/config.mjs} +0 -0
  203. /package/dist/{types/index.mjs → core/types/define.mjs} +0 -0
  204. /package/dist/{types/standard-schema.mjs → core/types/index.mjs} +0 -0
@@ -1,27 +0,0 @@
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 };
@@ -1,106 +0,0 @@
1
- //#region src/constants.ts
2
- /**
3
- * Constants and magic strings used throughout nitro-graphql
4
- * Centralizing these values prevents typos and makes refactoring easier
5
- */
6
- /**
7
- * GraphQL schema file extensions
8
- */
9
- const GRAPHQL_EXTENSIONS = [".graphql", ".gql"];
10
- /**
11
- * Resolver file extensions
12
- */
13
- const RESOLVER_EXTENSIONS = [".resolver.ts", ".resolver.js"];
14
- /**
15
- * Directive file extensions
16
- */
17
- const DIRECTIVE_EXTENSIONS = [".directive.ts", ".directive.js"];
18
- /**
19
- * Combined pattern for glob scanning
20
- */
21
- const GLOB_SCAN_PATTERN = "**/*.{graphql,gql,js,mjs,cjs,ts,mts,cts,tsx,jsx}";
22
- /**
23
- * Framework names
24
- */
25
- const FRAMEWORK_NUXT = "nuxt";
26
- const FRAMEWORK_NITRO = "nitro";
27
- /**
28
- * Default directory names for GraphQL files
29
- */
30
- const DIR_SERVER_GRAPHQL = "server/graphql";
31
- /**
32
- * Windows-compatible server GraphQL directory
33
- */
34
- const DIR_SERVER_GRAPHQL_WIN = "server\\graphql";
35
- /**
36
- * Default GraphQL endpoint paths
37
- */
38
- const ENDPOINT_GRAPHQL = "/api/graphql";
39
- const ENDPOINT_HEALTH = "/api/graphql/health";
40
- const ENDPOINT_DEBUG = "/_nitro/graphql/debug";
41
- /**
42
- * Configuration and scaffold file names
43
- */
44
- const FILE_GRAPHQL_CONFIG = "graphql.config.ts";
45
- const FILE_SCHEMA_TS = "schema.ts";
46
- const FILE_CONFIG_TS = "config.ts";
47
- const FILE_CONTEXT_DTS = "context.d.ts";
48
- const FILE_CONTEXT_TS = "context.ts";
49
- const FILE_INDEX_TS = "index.ts";
50
- /**
51
- * Rollup/Rolldown chunk output paths
52
- */
53
- const CHUNK_PATH_GRAPHQL = "chunks/graphql/[name].mjs";
54
- const CHUNK_PATH_UNKNOWN = "chunks/_/[name].mjs";
55
- /**
56
- * Default chunk names
57
- */
58
- const CHUNK_NAME_SCHEMAS = "schemas";
59
- const CHUNK_NAME_RESOLVERS = "resolvers";
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
- /**
72
- * Built-in GraphQL scalar types (should not be flagged as duplicates)
73
- */
74
- const BUILTIN_SCALARS = [
75
- "String",
76
- "Int",
77
- "Float",
78
- "Boolean",
79
- "ID",
80
- "DateTime",
81
- "JSON"
82
- ];
83
- /**
84
- * Supported HTTP methods for GraphQL endpoints
85
- */
86
- const GRAPHQL_HTTP_METHODS = [
87
- "GET",
88
- "POST",
89
- "OPTIONS"
90
- ];
91
- /**
92
- * Default paths for type generation (relative to buildDir)
93
- */
94
- const DEFAULT_SERVER_TYPES_PATH = ".graphql/nitro-graphql-server.d.ts";
95
- const DEFAULT_CLIENT_TYPES_PATH = ".graphql/nitro-graphql-client.d.ts";
96
- /**
97
- * Logger tag for nitro-graphql module
98
- */
99
- const LOG_TAG = "nitro-graphql";
100
- /**
101
- * Default service directory name for main service
102
- */
103
- const SERVICE_DEFAULT = "default";
104
-
105
- //#endregion
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 };
@@ -1,5 +0,0 @@
1
- //#region src/graphql/index.d.ts
2
- interface StandardSchemaV1 extends Record<string, any> {}
3
- interface ResolversTypes extends Record<string, any> {}
4
- //#endregion
5
- export { ResolversTypes, StandardSchemaV1 };
@@ -1,25 +0,0 @@
1
- import { generateDirectiveSchemas } from "../utils/directive-parser.mjs";
2
- import { scanDirectives } from "../utils/scanning/directives.mjs";
3
- import { scanDocuments } from "../utils/scanning/documents.mjs";
4
- import { scanResolvers } from "../utils/scanning/resolvers.mjs";
5
- import { scanSchemas } from "../utils/scanning/schemas.mjs";
6
-
7
- //#region src/setup/graphql-scanner.ts
8
- /**
9
- * Scan all GraphQL files and update Nitro state
10
- * Used by both initial setup and dev:start hook
11
- */
12
- async function scanAllGraphQLFiles(nitro) {
13
- const directives = await scanDirectives(nitro);
14
- nitro.scanDirectives = directives;
15
- if (!nitro.scanSchemas) nitro.scanSchemas = [];
16
- const directivesPath = await generateDirectiveSchemas(nitro, directives);
17
- const schemas = await scanSchemas(nitro);
18
- if (directivesPath && !schemas.includes(directivesPath)) schemas.push(directivesPath);
19
- nitro.scanSchemas = schemas;
20
- nitro.scanDocuments = await scanDocuments(nitro);
21
- nitro.scanResolvers = await scanResolvers(nitro);
22
- }
23
-
24
- //#endregion
25
- export { scanAllGraphQLFiles };
@@ -1,109 +0,0 @@
1
- import { FILE_CONFIG_TS, FILE_CONTEXT_DTS, FILE_CONTEXT_TS, FILE_GRAPHQL_CONFIG, FILE_SCHEMA_TS, LOG_TAG } from "../constants.mjs";
2
- import { writeFileIfNotExists } from "../utils/file-generator.mjs";
3
- import { getDefaultPaths, getScaffoldConfig, resolveFilePath, shouldGenerateScaffold } from "../utils/path-resolver.mjs";
4
- import { relativeWithDot } from "../utils/imports.mjs";
5
- import consola from "consola";
6
- import { join, resolve } from "pathe";
7
- import { existsSync, mkdirSync } from "node:fs";
8
-
9
- //#region src/setup/scaffold-generator.ts
10
- const logger = consola.withTag(LOG_TAG);
11
- /**
12
- * Generate all scaffold files based on configuration
13
- * Can be disabled via: scaffold: false or scaffold.enabled: false
14
- */
15
- function generateScaffoldFiles(nitro) {
16
- if (!shouldGenerateScaffold(nitro)) {
17
- logger.info("Scaffold file generation is disabled (library mode)");
18
- return;
19
- }
20
- const placeholders = getDefaultPaths(nitro);
21
- const scaffoldConfig = getScaffoldConfig(nitro);
22
- generateGraphQLConfig(nitro, scaffoldConfig, placeholders);
23
- generateServerScaffoldFiles(nitro, scaffoldConfig, placeholders);
24
- checkOldContextFile(nitro);
25
- }
26
- /**
27
- * Generate graphql.config.ts for IDE tooling support
28
- */
29
- function generateGraphQLConfig(nitro, scaffoldConfig, placeholders) {
30
- const graphqlConfigPath = resolveFilePath(scaffoldConfig.graphqlConfig, scaffoldConfig.enabled, true, FILE_GRAPHQL_CONFIG, placeholders);
31
- if (!graphqlConfigPath) return;
32
- writeFileIfNotExists(graphqlConfigPath, `import type { IGraphQLConfig } from 'graphql-config'
33
-
34
- export default <IGraphQLConfig> {
35
- projects: {
36
- default: {
37
- schema: [
38
- '${relativeWithDot(nitro.options.rootDir, resolve(nitro.graphql.buildDir, "schema.graphql"))}',
39
- ],
40
- documents: [
41
- '${relativeWithDot(nitro.options.rootDir, resolve(nitro.graphql.clientDir, "**/*.{graphql,js,ts,jsx,tsx}"))}',
42
- ],
43
- },
44
- },
45
- }`, FILE_GRAPHQL_CONFIG);
46
- }
47
- /**
48
- * Generate server-side scaffold files (schema.ts, config.ts, context.d.ts)
49
- */
50
- function generateServerScaffoldFiles(nitro, scaffoldConfig, placeholders) {
51
- const serverSchemaPath = resolveFilePath(scaffoldConfig.serverSchema, scaffoldConfig.enabled, true, "{serverGraphql}/schema.ts", placeholders);
52
- const serverConfigPath = resolveFilePath(scaffoldConfig.serverConfig, scaffoldConfig.enabled, true, "{serverGraphql}/config.ts", placeholders);
53
- const serverContextPath = resolveFilePath(scaffoldConfig.serverContext, scaffoldConfig.enabled, true, "{serverGraphql}/context.d.ts", placeholders);
54
- if (serverSchemaPath || serverConfigPath || serverContextPath) {
55
- if (!existsSync(nitro.graphql.serverDir)) mkdirSync(nitro.graphql.serverDir, { recursive: true });
56
- }
57
- if (serverSchemaPath) writeFileIfNotExists(serverSchemaPath, `export default defineSchema({
58
-
59
- })
60
- `, `server ${FILE_SCHEMA_TS}`);
61
- if (serverConfigPath) writeFileIfNotExists(serverConfigPath, `// Example GraphQL config file please change it to your needs
62
- // import * as tables from '../drizzle/schema/index'
63
- // import { useDatabase } from '../utils/useDb'
64
- import { defineGraphQLConfig } from 'nitro-graphql/define'
65
-
66
- export default defineGraphQLConfig({
67
- // graphql-yoga example config
68
- // context: () => {
69
- // return {
70
- // context: {
71
- // useDatabase,
72
- // tables,
73
- // },
74
- // }
75
- // },
76
- })
77
- `, `server ${FILE_CONFIG_TS}`);
78
- if (serverContextPath) writeFileIfNotExists(serverContextPath, `// Example context definition - please change it to your needs
79
- // import type { Database } from '../utils/useDb'
80
-
81
- declare module 'nitro/h3' {
82
- interface H3EventContext {
83
- // Add your custom context properties here
84
- // useDatabase: () => Database
85
- // tables: typeof import('../drizzle/schema')
86
- // auth?: {
87
- // user?: {
88
- // id: string
89
- // role: 'admin' | 'user'
90
- // }
91
- // }
92
- }
93
- }
94
-
95
- export {}
96
- `, `server ${FILE_CONTEXT_DTS}`);
97
- }
98
- /**
99
- * Check for old context.ts file and warn users to migrate to context.d.ts
100
- */
101
- function checkOldContextFile(nitro) {
102
- if (existsSync(join(nitro.graphql.serverDir, FILE_CONTEXT_TS))) {
103
- logger.warn(`Found ${FILE_CONTEXT_TS} file. Please rename it to ${FILE_CONTEXT_DTS} for type-only definitions.`);
104
- logger.info(`The context file should now be ${FILE_CONTEXT_DTS} instead of ${FILE_CONTEXT_TS}`);
105
- }
106
- }
107
-
108
- //#endregion
109
- export { generateScaffoldFiles };
@@ -1,59 +0,0 @@
1
- //#region src/types/standard-schema.d.ts
2
- /** The Standard Schema interface. */
3
- interface StandardSchemaV1<Input = unknown, Output = Input> {
4
- /** The Standard Schema properties. */
5
- readonly '~standard': StandardSchemaV1.Props<Input, Output>;
6
- }
7
- declare namespace StandardSchemaV1 {
8
- /** The Standard Schema properties interface. */
9
- export interface Props<Input = unknown, Output = Input> {
10
- /** The version number of the standard. */
11
- readonly version: 1;
12
- /** The vendor name of the schema library. */
13
- readonly vendor: string;
14
- /** Validates unknown input values. */
15
- readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
16
- /** Inferred types associated with the schema. */
17
- readonly types?: Types<Input, Output> | undefined;
18
- }
19
- /** The result interface of the validate function. */
20
- export type Result<Output> = SuccessResult<Output> | FailureResult;
21
- /** The result interface if validation succeeds. */
22
- export interface SuccessResult<Output> {
23
- /** The typed output value. */
24
- readonly value: Output;
25
- /** The non-existent issues. */
26
- readonly issues?: undefined;
27
- }
28
- /** The result interface if validation fails. */
29
- export interface FailureResult {
30
- /** The issues of failed validation. */
31
- readonly issues: ReadonlyArray<Issue>;
32
- }
33
- /** The issue interface of the failure output. */
34
- export interface Issue {
35
- /** The error message of the issue. */
36
- readonly message: string;
37
- /** The path of the issue, if any. */
38
- readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
39
- }
40
- /** The path segment interface of the issue. */
41
- export interface PathSegment {
42
- /** The key representing a path segment. */
43
- readonly key: PropertyKey;
44
- }
45
- /** The Standard Schema types interface. */
46
- export interface Types<Input = unknown, Output = Input> {
47
- /** The input type of the schema. */
48
- readonly input: Input;
49
- /** The output type of the schema. */
50
- readonly output: Output;
51
- }
52
- /** Infers the input type of a Standard Schema. */
53
- export type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
54
- /** Infers the output type of a Standard Schema. */
55
- export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
56
- export {};
57
- }
58
- //#endregion
59
- export { StandardSchemaV1 };
@@ -1,41 +0,0 @@
1
- import { CodegenClientConfig, ExternalGraphQLService, GenericSdkConfig } from "../types/index.mjs";
2
- import { GraphQLSchema } from "graphql";
3
- import { LoadSchemaOptions, UnnormalizedTypeDefPointer } from "@graphql-tools/load";
4
- import { Source } from "@graphql-tools/utils";
5
-
6
- //#region src/utils/client-codegen.d.ts
7
-
8
- /**
9
- * Type definition pointer for GraphQL schemas
10
- */
11
- type GraphQLTypeDefPointer = UnnormalizedTypeDefPointer | UnnormalizedTypeDefPointer[];
12
- /**
13
- * Options for loading GraphQL schemas
14
- */
15
- type GraphQLLoadSchemaOptions = Partial<LoadSchemaOptions>;
16
- declare function graphQLLoadSchemaSync(schemaPointers: GraphQLTypeDefPointer, data?: GraphQLLoadSchemaOptions): Promise<GraphQLSchema | undefined>;
17
- /**
18
- * Load schema from external GraphQL service
19
- */
20
- declare function loadExternalSchema(service: ExternalGraphQLService, buildDir?: string): Promise<GraphQLSchema | undefined>;
21
- /**
22
- * Download and save schema from external service
23
- */
24
- declare function downloadAndSaveSchema(service: ExternalGraphQLService, buildDir: string): Promise<string | undefined>;
25
- declare function loadGraphQLDocuments(patterns: string | string[]): Promise<Source[]>;
26
- declare function generateClientTypes(schema: GraphQLSchema, docs: Source[], config?: CodegenClientConfig, sdkConfig?: GenericSdkConfig, outputPath?: string, serviceName?: string, virtualTypesPath?: string, options?: {
27
- silent?: boolean;
28
- isInitial?: boolean;
29
- }): Promise<false | {
30
- types: string;
31
- sdk: string;
32
- }>;
33
- /**
34
- * Generate client types for external GraphQL service
35
- */
36
- declare function generateExternalClientTypes(service: ExternalGraphQLService, schema: GraphQLSchema, docs: Source[], virtualTypesPath?: string): Promise<{
37
- types: string;
38
- sdk: string;
39
- } | false>;
40
- //#endregion
41
- export { GraphQLLoadSchemaOptions, GraphQLTypeDefPointer, downloadAndSaveSchema, generateClientTypes, generateExternalClientTypes, graphQLLoadSchemaSync, loadExternalSchema, loadGraphQLDocuments };
@@ -1,277 +0,0 @@
1
- import { DEFAULT_GRAPHQL_SCALARS } from "../constants/scalars.mjs";
2
- import { pluginContent } from "./codegen-plugin.mjs";
3
- import { defu as defu$1 } from "defu";
4
- import { consola as consola$1 } from "consola";
5
- import { dirname, resolve } from "pathe";
6
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
- import { parse } from "graphql";
8
- import { createHash } from "node:crypto";
9
- import { codegen } from "@graphql-codegen/core";
10
- import { preset } from "@graphql-codegen/import-types-preset";
11
- import { plugin } from "@graphql-codegen/typed-document-node";
12
- import { plugin as plugin$1 } from "@graphql-codegen/typescript";
13
- import { plugin as plugin$2 } from "@graphql-codegen/typescript-generic-sdk";
14
- import { plugin as plugin$3 } from "@graphql-codegen/typescript-operations";
15
- import { GraphQLFileLoader } from "@graphql-tools/graphql-file-loader";
16
- import { loadDocuments, loadSchemaSync } from "@graphql-tools/load";
17
- import { UrlLoader } from "@graphql-tools/url-loader";
18
- import { printSchemaWithDirectives } from "@graphql-tools/utils";
19
-
20
- //#region src/utils/client-codegen.ts
21
- async function graphQLLoadSchemaSync(schemaPointers, data = {}) {
22
- const filteredPointers = [...Array.isArray(schemaPointers) ? schemaPointers : [schemaPointers], "!**/vfs/**"];
23
- let result;
24
- try {
25
- result = loadSchemaSync(filteredPointers, {
26
- ...data,
27
- loaders: [
28
- new GraphQLFileLoader(),
29
- new UrlLoader(),
30
- ...data.loaders || []
31
- ]
32
- });
33
- } catch (e) {
34
- if ((e.message || "").includes("Unable to find any GraphQL type definitions for the following pointers:")) consola$1.info("No server GraphQL files found. If you need server-side GraphQL, add .graphql files to your server directory.");
35
- else throw e;
36
- }
37
- return result;
38
- }
39
- /**
40
- * Load schema from external GraphQL service
41
- */
42
- async function loadExternalSchema(service, buildDir) {
43
- try {
44
- const headers = typeof service.headers === "function" ? service.headers() : service.headers || {};
45
- const schemaSource = service.schema ?? service.endpoint;
46
- const schemas = Array.isArray(schemaSource) ? schemaSource : [schemaSource];
47
- if (service.downloadSchema && buildDir) {
48
- const defaultPath = resolve(buildDir, "graphql", "schemas", `${service.name}.graphql`);
49
- const schemaFilePath = service.downloadPath ? resolve(service.downloadPath) : defaultPath;
50
- if (existsSync(schemaFilePath)) try {
51
- return loadSchemaSync([schemaFilePath], { loaders: [new GraphQLFileLoader()] });
52
- } catch {
53
- consola$1.warn(`[graphql:${service.name}] Cached schema invalid, loading from source`);
54
- }
55
- }
56
- const hasUrls = schemas.some((schema) => isUrl(schema));
57
- const hasLocalFiles = schemas.some((schema) => !isUrl(schema));
58
- const loaders = [];
59
- if (hasLocalFiles) loaders.push(new GraphQLFileLoader());
60
- if (hasUrls) loaders.push(new UrlLoader());
61
- if (loaders.length === 0) throw new Error("No appropriate loaders found for schema sources");
62
- return loadSchemaSync(schemas, {
63
- loaders,
64
- ...Object.keys(headers).length > 0 && { headers }
65
- });
66
- } catch (error) {
67
- consola$1.error(`[graphql:${service.name}] Failed to load external schema:`, error);
68
- return;
69
- }
70
- }
71
- /**
72
- * Check if a path is a URL (http/https)
73
- */
74
- function isUrl(path) {
75
- return path.startsWith("http://") || path.startsWith("https://");
76
- }
77
- /**
78
- * Download and save schema from external service
79
- */
80
- async function downloadAndSaveSchema(service, buildDir) {
81
- const downloadMode = service.downloadSchema;
82
- if (!downloadMode || downloadMode === "manual") return;
83
- const defaultPath = resolve(buildDir, "graphql", "schemas", `${service.name}.graphql`);
84
- const schemaFilePath = service.downloadPath ? resolve(service.downloadPath) : defaultPath;
85
- try {
86
- const headers = typeof service.headers === "function" ? service.headers() : service.headers || {};
87
- const schemaSource = service.schema ?? service.endpoint;
88
- const schemas = Array.isArray(schemaSource) ? schemaSource : [schemaSource];
89
- const hasUrlSchemas = schemas.some((schema) => isUrl(schema));
90
- const hasLocalSchemas = schemas.some((schema) => !isUrl(schema));
91
- let shouldDownload = false;
92
- const fileExists = existsSync(schemaFilePath);
93
- if (downloadMode === "always") {
94
- shouldDownload = true;
95
- if (fileExists && hasUrlSchemas) try {
96
- const remoteSchemaString = printSchemaWithDirectives(loadSchemaSync(schemas.filter(isUrl), {
97
- loaders: [new UrlLoader()],
98
- ...Object.keys(headers).length > 0 && { headers }
99
- }));
100
- const remoteHash = createHash("md5").update(remoteSchemaString).digest("hex");
101
- const localSchemaString = readFileSync(schemaFilePath, "utf-8");
102
- if (remoteHash === createHash("md5").update(localSchemaString).digest("hex")) {
103
- shouldDownload = false;
104
- consola$1.info(`[graphql:${service.name}] Schema is up-to-date, using cached version`);
105
- }
106
- } catch {
107
- consola$1.warn(`[graphql:${service.name}] Unable to compare with remote schema, updating local cache`);
108
- shouldDownload = true;
109
- }
110
- else if (fileExists && hasLocalSchemas) {
111
- const localFiles = schemas.filter((schema) => !isUrl(schema));
112
- let sourceIsNewer = false;
113
- for (const localFile of localFiles) if (existsSync(localFile)) {
114
- const { statSync } = await import("node:fs");
115
- const sourceStats = statSync(localFile);
116
- const cachedStats = statSync(schemaFilePath);
117
- if (sourceStats.mtime > cachedStats.mtime) {
118
- sourceIsNewer = true;
119
- break;
120
- }
121
- }
122
- if (!sourceIsNewer) shouldDownload = false;
123
- }
124
- } else if (downloadMode === true || downloadMode === "once") shouldDownload = !fileExists;
125
- if (shouldDownload) {
126
- if (hasUrlSchemas && hasLocalSchemas) {
127
- const schemaString = printSchemaWithDirectives(loadSchemaSync(schemas, {
128
- loaders: [new GraphQLFileLoader(), new UrlLoader()],
129
- ...Object.keys(headers).length > 0 && { headers }
130
- }));
131
- mkdirSync(dirname(schemaFilePath), { recursive: true });
132
- writeFileSync(schemaFilePath, schemaString, "utf-8");
133
- } else if (hasUrlSchemas) {
134
- const schemaString = printSchemaWithDirectives(loadSchemaSync(schemas, {
135
- loaders: [new UrlLoader()],
136
- ...Object.keys(headers).length > 0 && { headers }
137
- }));
138
- mkdirSync(dirname(schemaFilePath), { recursive: true });
139
- writeFileSync(schemaFilePath, schemaString, "utf-8");
140
- } else if (hasLocalSchemas) {
141
- const schemaString = printSchemaWithDirectives(loadSchemaSync(schemas, { loaders: [new GraphQLFileLoader()] }));
142
- mkdirSync(dirname(schemaFilePath), { recursive: true });
143
- writeFileSync(schemaFilePath, schemaString, "utf-8");
144
- }
145
- }
146
- return schemaFilePath;
147
- } catch (error) {
148
- consola$1.error(`[graphql:${service.name}] Failed to download/copy schema:`, error);
149
- return;
150
- }
151
- }
152
- async function loadGraphQLDocuments(patterns) {
153
- try {
154
- return await loadDocuments(patterns, { loaders: [new GraphQLFileLoader()] });
155
- } catch (e) {
156
- if ((e.message || "").includes("Unable to find any GraphQL type definitions for the following pointers:")) return [];
157
- else throw e;
158
- }
159
- }
160
- async function generateClientTypes(schema, docs, config = {}, sdkConfig = {}, outputPath, serviceName, virtualTypesPath, options = {}) {
161
- if (docs.length === 0 && !serviceName) {
162
- if (!options.silent && options.isInitial) consola$1.info("No client GraphQL files found. Skipping client type generation.");
163
- return false;
164
- }
165
- const serviceLabel = serviceName ? `:${serviceName}` : "";
166
- const mergedConfig = defu$1({
167
- emitLegacyCommonJSImports: false,
168
- useTypeImports: true,
169
- enumsAsTypes: true,
170
- strictScalars: true,
171
- maybeValue: "T | null | undefined",
172
- inputMaybeValue: "T | undefined",
173
- documentMode: "string",
174
- pureMagicComment: true,
175
- dedupeOperationSuffix: true,
176
- rawRequest: true,
177
- scalars: DEFAULT_GRAPHQL_SCALARS
178
- }, config);
179
- const mergedSdkConfig = defu$1(mergedConfig, sdkConfig);
180
- try {
181
- if (docs.length === 0) return {
182
- types: await codegen({
183
- filename: outputPath || "client-types.generated.ts",
184
- schema: parse(printSchemaWithDirectives(schema)),
185
- documents: [],
186
- config: mergedConfig,
187
- plugins: [{ pluginContent: {} }, { typescript: {} }],
188
- pluginMap: {
189
- pluginContent: { plugin: pluginContent },
190
- typescript: { plugin: plugin$1 }
191
- }
192
- }),
193
- sdk: `// THIS FILE IS GENERATED, DO NOT EDIT!
194
- /* eslint-disable eslint-comments/no-unlimited-disable */
195
- /* tslint:disable */
196
- /* eslint-disable */
197
- /* prettier-ignore */
198
-
199
- import type { GraphQLResolveInfo } from 'graphql'
200
- export type RequireFields<T, K extends keyof T> = Omit<T, K> & { [P in K]-?: NonNullable<T[P]> }
201
-
202
- export interface Requester<C = {}, E = unknown> {
203
- <R, V>(doc: string, vars?: V, options?: C): Promise<R> | AsyncIterable<R>
204
- }
205
-
206
- export type Sdk = {
207
- request: <R, V = Record<string, any>>(document: string, variables?: V) => Promise<R>
208
- }
209
-
210
- export function getSdk(requester: Requester): Sdk {
211
- return {
212
- request: <R, V = Record<string, any>>(document: string, variables?: V): Promise<R> => {
213
- return requester<R, V>(document, variables)
214
- }
215
- }
216
- }
217
- `
218
- };
219
- const enableTypedDocumentNode = config.typedDocumentNode === true;
220
- const plugins = [
221
- { pluginContent: {} },
222
- { typescript: {} },
223
- { typescriptOperations: {} }
224
- ];
225
- const pluginMap = {
226
- pluginContent: { plugin: pluginContent },
227
- typescript: { plugin: plugin$1 },
228
- typescriptOperations: { plugin: plugin$3 }
229
- };
230
- if (enableTypedDocumentNode) {
231
- plugins.push({ typedDocumentNode: {} });
232
- pluginMap.typedDocumentNode = { plugin };
233
- }
234
- const output = await codegen({
235
- filename: outputPath || "client-types.generated.ts",
236
- schema: parse(printSchemaWithDirectives(schema)),
237
- documents: [...docs],
238
- config: mergedConfig,
239
- plugins,
240
- pluginMap
241
- });
242
- const typesPath = virtualTypesPath || (serviceName ? `#graphql/client/${serviceName}` : "#graphql/client");
243
- const sdkOutput = await preset.buildGeneratesSection({
244
- baseOutputDir: outputPath || "client-types.generated.ts",
245
- schema: parse(printSchemaWithDirectives(schema)),
246
- documents: [...docs],
247
- config: mergedSdkConfig,
248
- presetConfig: { typesPath },
249
- plugins: [{ pluginContent: {} }, { typescriptGenericSdk: {} }],
250
- pluginMap: {
251
- pluginContent: { plugin: pluginContent },
252
- typescriptGenericSdk: { plugin: plugin$2 }
253
- }
254
- });
255
- return {
256
- types: output,
257
- sdk: (await Promise.all(sdkOutput.map(async (config$1) => {
258
- return {
259
- file: config$1.filename,
260
- content: await codegen(config$1)
261
- };
262
- })))[0]?.content || ""
263
- };
264
- } catch (error) {
265
- consola$1.warn(`[graphql${serviceLabel}] Client type generation failed:`, error);
266
- return false;
267
- }
268
- }
269
- /**
270
- * Generate client types for external GraphQL service
271
- */
272
- async function generateExternalClientTypes(service, schema, docs, virtualTypesPath) {
273
- return generateClientTypes(schema, docs, service.codegen?.client || {}, service.codegen?.clientSDK || {}, void 0, service.name, virtualTypesPath);
274
- }
275
-
276
- //#endregion
277
- export { downloadAndSaveSchema, generateClientTypes, generateExternalClientTypes, graphQLLoadSchemaSync, loadExternalSchema, loadGraphQLDocuments };