nitro-graphql 2.0.0-beta.4 → 2.0.0-beta.41

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 (168) hide show
  1. package/README.md +438 -27
  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 +46 -0
  7. package/dist/cli/commands/init.mjs +195 -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/config.d.mts +2 -0
  17. package/dist/config.mjs +3 -0
  18. package/dist/core/codegen/client.d.mts +23 -0
  19. package/dist/core/codegen/client.mjs +150 -0
  20. package/dist/core/codegen/document-loader.d.mts +10 -0
  21. package/dist/core/codegen/document-loader.mjs +18 -0
  22. package/dist/core/codegen/index.d.mts +8 -0
  23. package/dist/core/codegen/index.mjs +9 -0
  24. package/dist/core/codegen/plugin.d.mts +20 -0
  25. package/dist/core/codegen/plugin.mjs +30 -0
  26. package/dist/core/codegen/runtime.d.mts +20 -0
  27. package/dist/core/codegen/runtime.mjs +60 -0
  28. package/dist/core/codegen/schema-loader.d.mts +28 -0
  29. package/dist/core/codegen/schema-loader.mjs +128 -0
  30. package/dist/core/codegen/server.d.mts +28 -0
  31. package/dist/core/codegen/server.mjs +143 -0
  32. package/dist/core/codegen/validation.d.mts +13 -0
  33. package/dist/core/codegen/validation.mjs +96 -0
  34. package/dist/core/config.d.mts +50 -0
  35. package/dist/core/config.mjs +82 -0
  36. package/dist/core/constants.d.mts +188 -0
  37. package/dist/core/constants.mjs +210 -0
  38. package/dist/core/index.d.mts +33 -0
  39. package/dist/core/index.mjs +27 -0
  40. package/dist/core/manifest.d.mts +46 -0
  41. package/dist/core/manifest.mjs +76 -0
  42. package/dist/core/scanning/ast-scanner.d.mts +28 -0
  43. package/dist/core/scanning/ast-scanner.mjs +122 -0
  44. package/dist/core/scanning/common.d.mts +37 -0
  45. package/dist/core/scanning/common.mjs +60 -0
  46. package/dist/core/scanning/directives.d.mts +10 -0
  47. package/dist/core/scanning/directives.mjs +29 -0
  48. package/dist/core/scanning/documents.d.mts +21 -0
  49. package/dist/core/scanning/documents.mjs +43 -0
  50. package/dist/core/scanning/index.d.mts +7 -0
  51. package/dist/core/scanning/index.mjs +8 -0
  52. package/dist/core/scanning/resolvers.d.mts +15 -0
  53. package/dist/core/scanning/resolvers.mjs +59 -0
  54. package/dist/core/scanning/schemas.d.mts +14 -0
  55. package/dist/core/scanning/schemas.mjs +64 -0
  56. package/dist/core/schema/builder.d.mts +53 -0
  57. package/dist/core/schema/builder.mjs +70 -0
  58. package/dist/core/schema/federation.d.mts +34 -0
  59. package/dist/core/schema/federation.mjs +40 -0
  60. package/dist/core/schema/index.d.mts +3 -0
  61. package/dist/core/schema/index.mjs +4 -0
  62. package/dist/core/types/adapter.d.mts +58 -0
  63. package/dist/core/types/codegen.d.mts +133 -0
  64. package/dist/core/types/config.d.mts +210 -0
  65. package/dist/core/types/config.mjs +1 -0
  66. package/dist/{utils/define.d.ts → core/types/define.d.mts} +3 -30
  67. package/dist/core/types/define.mjs +1 -0
  68. package/dist/core/types/index.d.mts +5 -0
  69. package/dist/core/types/index.mjs +1 -0
  70. package/dist/core/types/scanning.d.mts +69 -0
  71. package/dist/core/types/scanning.mjs +1 -0
  72. package/dist/{utils/directive-parser.d.ts → core/utils/directive-parser.d.mts} +21 -4
  73. package/dist/{utils/directive-parser.js → core/utils/directive-parser.mjs} +25 -34
  74. package/dist/core/utils/errors.d.mts +77 -0
  75. package/dist/core/utils/errors.mjs +93 -0
  76. package/dist/core/utils/file-io.d.mts +24 -0
  77. package/dist/core/utils/file-io.mjs +47 -0
  78. package/dist/core/utils/imports.d.mts +15 -0
  79. package/dist/core/utils/imports.mjs +25 -0
  80. package/dist/core/utils/index.d.mts +7 -0
  81. package/dist/core/utils/index.mjs +8 -0
  82. package/dist/core/utils/logger.d.mts +19 -0
  83. package/dist/core/utils/logger.mjs +38 -0
  84. package/dist/core/utils/ofetch-templates.d.mts +30 -0
  85. package/dist/core/utils/ofetch-templates.mjs +135 -0
  86. package/dist/core/validation/external-services.d.mts +11 -0
  87. package/dist/core/validation/external-services.mjs +34 -0
  88. package/dist/core/validation/index.d.mts +2 -0
  89. package/dist/core/validation/index.mjs +3 -0
  90. package/dist/define.d.mts +294 -0
  91. package/dist/define.mjs +323 -0
  92. package/dist/index.d.mts +6 -0
  93. package/dist/index.mjs +6 -0
  94. package/dist/nitro/adapter.d.mts +30 -0
  95. package/dist/nitro/adapter.mjs +97 -0
  96. package/dist/{utils/apollo.d.ts → nitro/apollo.d.mts} +3 -3
  97. package/dist/nitro/apollo.mjs +59 -0
  98. package/dist/nitro/codegen.d.mts +19 -0
  99. package/dist/nitro/codegen.mjs +141 -0
  100. package/dist/nitro/config.d.mts +51 -0
  101. package/dist/nitro/config.mjs +57 -0
  102. package/dist/nitro/index.d.mts +46 -0
  103. package/dist/nitro/index.mjs +65 -0
  104. package/dist/nitro/paths.d.mts +54 -0
  105. package/dist/nitro/paths.mjs +92 -0
  106. package/dist/nitro/rollup.d.mts +6 -0
  107. package/dist/nitro/rollup.mjs +95 -0
  108. package/dist/nitro/routes/apollo-server.d.mts +6 -0
  109. package/dist/nitro/routes/apollo-server.mjs +71 -0
  110. package/dist/nitro/routes/debug-template.d.mts +15 -0
  111. package/dist/nitro/routes/debug-template.mjs +385 -0
  112. package/dist/nitro/routes/debug.d.mts +55 -0
  113. package/dist/nitro/routes/debug.mjs +102 -0
  114. package/dist/nitro/routes/graphql-yoga.d.mts +6 -0
  115. package/dist/nitro/routes/graphql-yoga.mjs +62 -0
  116. package/dist/nitro/routes/health.d.mts +10 -0
  117. package/dist/{routes/health.js → nitro/routes/health.mjs} +4 -3
  118. package/dist/nitro/setup/extend-loader.d.mts +19 -0
  119. package/dist/nitro/setup/extend-loader.mjs +129 -0
  120. package/dist/nitro/setup/file-watcher.d.mts +16 -0
  121. package/dist/nitro/setup/file-watcher.mjs +98 -0
  122. package/dist/nitro/setup/logging.d.mts +17 -0
  123. package/dist/nitro/setup/logging.mjs +66 -0
  124. package/dist/nitro/setup/rollup-integration.d.mts +16 -0
  125. package/dist/nitro/setup/rollup-integration.mjs +90 -0
  126. package/dist/nitro/setup/routes.d.mts +10 -0
  127. package/dist/nitro/setup/routes.mjs +35 -0
  128. package/dist/nitro/setup/ts-config.d.mts +11 -0
  129. package/dist/nitro/setup/ts-config.mjs +69 -0
  130. package/dist/nitro/setup.d.mts +12 -0
  131. package/dist/nitro/setup.mjs +234 -0
  132. package/dist/nitro/types.d.mts +374 -0
  133. package/dist/nitro/types.mjs +1 -0
  134. package/dist/nitro/virtual/generators.d.mts +31 -0
  135. package/dist/nitro/virtual/generators.mjs +113 -0
  136. package/dist/nitro/virtual/stubs.d.mts +20 -0
  137. package/dist/nitro/virtual/stubs.mjs +31 -0
  138. package/dist/{ecosystem/nuxt.d.ts → nuxt.d.mts} +1 -1
  139. package/dist/nuxt.mjs +109 -0
  140. package/dist/{graphql/server.d.ts → stubs/index.d.mts} +5 -1
  141. package/dist/stubs/index.mjs +1 -0
  142. package/package.json +102 -77
  143. package/dist/ecosystem/nuxt.js +0 -67
  144. package/dist/graphql/index.d.ts +0 -5
  145. package/dist/index.d.ts +0 -8
  146. package/dist/index.js +0 -264
  147. package/dist/rollup.js +0 -119
  148. package/dist/routes/apollo-server.d.ts +0 -6
  149. package/dist/routes/apollo-server.js +0 -89
  150. package/dist/routes/graphql-yoga.d.ts +0 -6
  151. package/dist/routes/graphql-yoga.js +0 -91
  152. package/dist/routes/health.d.ts +0 -6
  153. package/dist/types/index.d.ts +0 -128
  154. package/dist/types/standard-schema.d.ts +0 -59
  155. package/dist/utils/apollo.js +0 -61
  156. package/dist/utils/client-codegen.d.ts +0 -38
  157. package/dist/utils/client-codegen.js +0 -290
  158. package/dist/utils/define.js +0 -57
  159. package/dist/utils/index.d.ts +0 -39
  160. package/dist/utils/index.js +0 -250
  161. package/dist/utils/server-codegen.d.ts +0 -7
  162. package/dist/utils/server-codegen.js +0 -136
  163. package/dist/utils/type-generation.d.ts +0 -7
  164. package/dist/utils/type-generation.js +0 -287
  165. package/dist/vite.d.ts +0 -25
  166. package/dist/vite.js +0 -40
  167. /package/dist/{graphql/index.js → core/types/adapter.mjs} +0 -0
  168. /package/dist/{graphql/server.js → core/types/codegen.mjs} +0 -0
@@ -1,128 +0,0 @@
1
- import { StandardSchemaV1 } from "./standard-schema.js";
2
- import { ESMCodeGenOptions } from "knitwork";
3
- import { IResolvers } from "@graphql-tools/utils";
4
- import { TypeScriptPluginConfig } from "@graphql-codegen/typescript";
5
- import { plugin as plugin$1 } from "@graphql-codegen/typescript-generic-sdk";
6
- import { TypeScriptDocumentsPluginConfig } from "@graphql-codegen/typescript-operations";
7
- import { TypeScriptResolversPluginConfig } from "@graphql-codegen/typescript-resolvers";
8
-
9
- //#region src/types/index.d.ts
10
- type CodegenServerConfig = TypeScriptPluginConfig & TypeScriptResolversPluginConfig;
11
- type DocumentModeConfig = Pick<Parameters<typeof plugin$1>[2], 'documentMode'>;
12
- type DocumentModeEnum = NonNullable<DocumentModeConfig['documentMode']>;
13
- type DocumentModeType = `${DocumentModeEnum}`;
14
- type GenericSdkConfig = Omit<Parameters<typeof plugin$1>[2], 'documentMode'> & {
15
- documentMode?: DocumentModeType;
16
- };
17
- type CodegenClientConfig = TypeScriptPluginConfig & TypeScriptDocumentsPluginConfig & {
18
- endpoint?: string;
19
- };
20
- interface IESMImport {
21
- name: string;
22
- as?: string;
23
- type: 'resolver' | 'query' | 'mutation' | 'type' | 'subscription' | 'directive';
24
- }
25
- interface GenImport {
26
- specifier: string;
27
- imports: IESMImport[];
28
- options?: ESMCodeGenOptions;
29
- }
30
- declare module 'nitro/types' {
31
- interface Nitro {
32
- scanSchemas: string[];
33
- scanDocuments: string[];
34
- scanResolvers: GenImport[];
35
- scanDirectives: GenImport[];
36
- graphql: {
37
- buildDir: string;
38
- watchDirs: string[];
39
- clientDir: string;
40
- serverDir: string;
41
- dir: {
42
- build: string;
43
- client: string;
44
- server: string;
45
- };
46
- };
47
- }
48
- }
49
- declare module 'nitro/types' {
50
- interface NitroOptions {
51
- graphql?: NitroGraphQLOptions;
52
- }
53
- interface NitroRuntimeConfig {
54
- graphql?: NitroGraphQLOptions;
55
- }
56
- interface NitroConfig {
57
- graphql?: NitroGraphQLOptions;
58
- }
59
- }
60
- interface ExternalGraphQLService {
61
- /** Unique name for this service (used for file naming and type generation) */
62
- name: string;
63
- /** Schema source - can be URL(s) for remote schemas or file path(s) for local schemas */
64
- schema: string | string[];
65
- /** GraphQL endpoint for this service */
66
- endpoint: string;
67
- /** Optional headers for schema introspection and client requests */
68
- headers?: Record<string, string> | (() => Record<string, string>);
69
- /** Optional: specific document patterns for this service */
70
- documents?: string[];
71
- /**
72
- * Optional: Download and cache schema locally for offline usage
73
- * - true or 'once': Download if file doesn't exist, then use cached version (offline-friendly)
74
- * - 'always': Check for updates on every build (current behavior)
75
- * - 'manual': Never download automatically, user manages schema files manually
76
- * - false: Disable schema downloading
77
- */
78
- downloadSchema?: boolean | 'once' | 'always' | 'manual';
79
- /** Optional: Custom path to save downloaded schema (default: .nitro/graphql/schemas/[serviceName].graphql) */
80
- downloadPath?: string;
81
- /** Optional: service-specific codegen configuration */
82
- codegen?: {
83
- client?: CodegenClientConfig;
84
- clientSDK?: GenericSdkConfig;
85
- };
86
- }
87
- interface FederationConfig {
88
- /** Enable Apollo Federation subgraph support */
89
- enabled: boolean;
90
- /** Service name for federation (used in subgraph config) */
91
- serviceName?: string;
92
- /** Service version for federation */
93
- serviceVersion?: string;
94
- /** Service URL for federation gateway */
95
- serviceUrl?: string;
96
- }
97
- interface NitroGraphQLOptions {
98
- framework: 'graphql-yoga' | 'apollo-server';
99
- endpoint?: {
100
- graphql?: string;
101
- healthCheck?: string;
102
- };
103
- playground?: boolean;
104
- typedefs?: string[];
105
- resolvers?: Array<IResolvers<any, any>>;
106
- loader?: {
107
- include?: RegExp;
108
- exclude?: RegExp;
109
- validate?: boolean;
110
- };
111
- codegen?: {
112
- server?: CodegenServerConfig;
113
- client?: CodegenClientConfig;
114
- clientSDK?: GenericSdkConfig;
115
- };
116
- /** External GraphQL services to generate types and SDKs for */
117
- externalServices?: ExternalGraphQLService[];
118
- /** Apollo Federation configuration */
119
- federation?: FederationConfig;
120
- /** Server GraphQL directory path */
121
- serverDir?: string;
122
- /** Layer directories (populated by Nuxt module) */
123
- layerDirectories?: string[];
124
- layerServerDirs?: string[];
125
- layerAppDirs?: string[];
126
- }
127
- //#endregion
128
- export { CodegenClientConfig, CodegenServerConfig, ExternalGraphQLService, FederationConfig, GenImport, GenericSdkConfig, NitroGraphQLOptions };
@@ -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,61 +0,0 @@
1
- import { HeaderMap } from "@apollo/server";
2
- import { eventHandler, getHeaders, isMethod, readBody, setHeaders } from "h3";
3
-
4
- //#region src/utils/apollo.ts
5
- function startServerAndCreateH3Handler(server, options) {
6
- const defaultContext = () => Promise.resolve({});
7
- const contextFunction = options?.context ?? defaultContext;
8
- return eventHandler({
9
- handler: async (event) => {
10
- const apolloServer = typeof server === "function" ? server() : server;
11
- if (!options?.serverAlreadyStarted) apolloServer.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests();
12
- if (isMethod(event, "OPTIONS")) return null;
13
- try {
14
- const graphqlRequest = await toGraphqlRequest(event);
15
- const { body, headers, status } = await apolloServer.executeHTTPGraphQLRequest({
16
- httpGraphQLRequest: graphqlRequest,
17
- context: () => contextFunction({ event })
18
- });
19
- if (body.kind === "chunked") throw new Error("Incremental delivery not implemented");
20
- setHeaders(event, Object.fromEntries(headers));
21
- event.res.statusCode = status || 200;
22
- return body.string;
23
- } catch (error) {
24
- if (error instanceof SyntaxError) {
25
- event.res.statusCode = 400;
26
- return error.message;
27
- } else throw error;
28
- }
29
- },
30
- websocket: options?.websocket
31
- });
32
- }
33
- async function toGraphqlRequest(event) {
34
- return {
35
- method: event.req.method || "POST",
36
- headers: normalizeHeaders(getHeaders(event)),
37
- search: normalizeQueryString(event.req.url),
38
- body: await normalizeBody(event)
39
- };
40
- }
41
- function normalizeHeaders(headers) {
42
- const headerMap = new HeaderMap();
43
- for (const [key, value] of Object.entries(headers)) if (Array.isArray(value)) headerMap.set(key, value.join(","));
44
- else if (value) headerMap.set(key, value);
45
- return headerMap;
46
- }
47
- function normalizeQueryString(url) {
48
- if (!url) return "";
49
- return url.split("?")[1] || "";
50
- }
51
- async function normalizeBody(event) {
52
- if (isMethod(event, [
53
- "PATCH",
54
- "POST",
55
- "PUT",
56
- "DELETE"
57
- ])) return await readBody(event);
58
- }
59
-
60
- //#endregion
61
- export { startServerAndCreateH3Handler };
@@ -1,38 +0,0 @@
1
- import { CodegenClientConfig, ExternalGraphQLService, GenericSdkConfig } from "../types/index.js";
2
- import { GraphQLSchema } from "graphql";
3
- import { Source } from "@graphql-tools/utils";
4
- import { LoadSchemaOptions, UnnormalizedTypeDefPointer } from "@graphql-tools/load";
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): Promise<false | {
27
- types: string;
28
- sdk: string;
29
- }>;
30
- /**
31
- * Generate client types for external GraphQL service
32
- */
33
- declare function generateExternalClientTypes(service: ExternalGraphQLService, schema: GraphQLSchema, docs: Source[]): Promise<{
34
- types: string;
35
- sdk: string;
36
- } | false>;
37
- //#endregion
38
- export { GraphQLLoadSchemaOptions, GraphQLTypeDefPointer, downloadAndSaveSchema, generateClientTypes, generateExternalClientTypes, graphQLLoadSchemaSync, loadExternalSchema, loadGraphQLDocuments };
@@ -1,290 +0,0 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { consola as consola$1 } from "consola";
3
- import { defu as defu$1 } from "defu";
4
- import { dirname, resolve } from "pathe";
5
- import { parse } from "graphql";
6
- import { printSchemaWithDirectives } from "@graphql-tools/utils";
7
- import { createHash } from "node:crypto";
8
- import { codegen } from "@graphql-codegen/core";
9
- import { preset } from "@graphql-codegen/import-types-preset";
10
- import { plugin } from "@graphql-codegen/typescript";
11
- import { plugin as plugin$1 } from "@graphql-codegen/typescript-generic-sdk";
12
- import { plugin as plugin$2 } from "@graphql-codegen/typescript-operations";
13
- import { GraphQLFileLoader } from "@graphql-tools/graphql-file-loader";
14
- import { loadDocuments, loadSchemaSync } from "@graphql-tools/load";
15
- import { UrlLoader } from "@graphql-tools/url-loader";
16
- import { CurrencyResolver, DateTimeISOResolver, DateTimeResolver, JSONObjectResolver, JSONResolver, NonEmptyStringResolver, UUIDResolver } from "graphql-scalars";
17
-
18
- //#region src/utils/client-codegen.ts
19
- function pluginContent(_schema, _documents, _config, _info) {
20
- return {
21
- prepend: [
22
- "// THIS FILE IS GENERATED, DO NOT EDIT!",
23
- "/* eslint-disable eslint-comments/no-unlimited-disable */",
24
- "/* tslint:disable */",
25
- "/* eslint-disable */",
26
- "/* prettier-ignore */"
27
- ],
28
- content: ""
29
- };
30
- }
31
- async function graphQLLoadSchemaSync(schemaPointers, data = {}) {
32
- const filteredPointers = [...Array.isArray(schemaPointers) ? schemaPointers : [schemaPointers], "!**/vfs/**"];
33
- let result;
34
- try {
35
- result = loadSchemaSync(filteredPointers, {
36
- ...data,
37
- loaders: [
38
- new GraphQLFileLoader(),
39
- new UrlLoader(),
40
- ...data.loaders || []
41
- ]
42
- });
43
- } catch (e) {
44
- 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.");
45
- else throw e;
46
- }
47
- return result;
48
- }
49
- /**
50
- * Load schema from external GraphQL service
51
- */
52
- async function loadExternalSchema(service, buildDir) {
53
- try {
54
- const headers = typeof service.headers === "function" ? service.headers() : service.headers || {};
55
- const schemas = Array.isArray(service.schema) ? service.schema : [service.schema];
56
- if (service.downloadSchema && buildDir) {
57
- const defaultPath = resolve(buildDir, "graphql", "schemas", `${service.name}.graphql`);
58
- const schemaFilePath = service.downloadPath ? resolve(service.downloadPath) : defaultPath;
59
- if (existsSync(schemaFilePath)) try {
60
- return loadSchemaSync([schemaFilePath], { loaders: [new GraphQLFileLoader()] });
61
- } catch {
62
- consola$1.warn(`[graphql:${service.name}] Cached schema invalid, loading from source`);
63
- }
64
- }
65
- const hasUrls = schemas.some((schema) => isUrl(schema));
66
- const hasLocalFiles = schemas.some((schema) => !isUrl(schema));
67
- const loaders = [];
68
- if (hasLocalFiles) loaders.push(new GraphQLFileLoader());
69
- if (hasUrls) loaders.push(new UrlLoader());
70
- if (loaders.length === 0) throw new Error("No appropriate loaders found for schema sources");
71
- return loadSchemaSync(schemas, {
72
- loaders,
73
- ...Object.keys(headers).length > 0 && { headers }
74
- });
75
- } catch (error) {
76
- consola$1.error(`[graphql:${service.name}] Failed to load external schema:`, error);
77
- return;
78
- }
79
- }
80
- /**
81
- * Check if a path is a URL (http/https)
82
- */
83
- function isUrl(path) {
84
- return path.startsWith("http://") || path.startsWith("https://");
85
- }
86
- /**
87
- * Download and save schema from external service
88
- */
89
- async function downloadAndSaveSchema(service, buildDir) {
90
- const downloadMode = service.downloadSchema;
91
- if (!downloadMode || downloadMode === "manual") return;
92
- const defaultPath = resolve(buildDir, "graphql", "schemas", `${service.name}.graphql`);
93
- const schemaFilePath = service.downloadPath ? resolve(service.downloadPath) : defaultPath;
94
- try {
95
- const headers = typeof service.headers === "function" ? service.headers() : service.headers || {};
96
- const schemas = Array.isArray(service.schema) ? service.schema : [service.schema];
97
- const hasUrlSchemas = schemas.some((schema) => isUrl(schema));
98
- const hasLocalSchemas = schemas.some((schema) => !isUrl(schema));
99
- let shouldDownload = false;
100
- const fileExists = existsSync(schemaFilePath);
101
- if (downloadMode === "always") {
102
- shouldDownload = true;
103
- if (fileExists && hasUrlSchemas) try {
104
- const remoteSchemaString = printSchemaWithDirectives(loadSchemaSync(schemas.filter(isUrl), {
105
- loaders: [new UrlLoader()],
106
- ...Object.keys(headers).length > 0 && { headers }
107
- }));
108
- const remoteHash = createHash("md5").update(remoteSchemaString).digest("hex");
109
- const localSchemaString = readFileSync(schemaFilePath, "utf-8");
110
- if (remoteHash === createHash("md5").update(localSchemaString).digest("hex")) {
111
- shouldDownload = false;
112
- consola$1.info(`[graphql:${service.name}] Schema is up-to-date, using cached version`);
113
- }
114
- } catch {
115
- consola$1.warn(`[graphql:${service.name}] Unable to compare with remote schema, updating local cache`);
116
- shouldDownload = true;
117
- }
118
- else if (fileExists && hasLocalSchemas) {
119
- const localFiles = schemas.filter((schema) => !isUrl(schema));
120
- let sourceIsNewer = false;
121
- for (const localFile of localFiles) if (existsSync(localFile)) {
122
- const { statSync } = await import("node:fs");
123
- const sourceStats = statSync(localFile);
124
- const cachedStats = statSync(schemaFilePath);
125
- if (sourceStats.mtime > cachedStats.mtime) {
126
- sourceIsNewer = true;
127
- break;
128
- }
129
- }
130
- if (!sourceIsNewer) shouldDownload = false;
131
- }
132
- } else if (downloadMode === true || downloadMode === "once") shouldDownload = !fileExists;
133
- if (shouldDownload) {
134
- if (hasUrlSchemas && hasLocalSchemas) {
135
- const schemaString = printSchemaWithDirectives(loadSchemaSync(schemas, {
136
- loaders: [new GraphQLFileLoader(), new UrlLoader()],
137
- ...Object.keys(headers).length > 0 && { headers }
138
- }));
139
- mkdirSync(dirname(schemaFilePath), { recursive: true });
140
- writeFileSync(schemaFilePath, schemaString, "utf-8");
141
- } else if (hasUrlSchemas) {
142
- const schemaString = printSchemaWithDirectives(loadSchemaSync(schemas, {
143
- loaders: [new UrlLoader()],
144
- ...Object.keys(headers).length > 0 && { headers }
145
- }));
146
- mkdirSync(dirname(schemaFilePath), { recursive: true });
147
- writeFileSync(schemaFilePath, schemaString, "utf-8");
148
- } else if (hasLocalSchemas) {
149
- const schemaString = printSchemaWithDirectives(loadSchemaSync(schemas, { loaders: [new GraphQLFileLoader()] }));
150
- mkdirSync(dirname(schemaFilePath), { recursive: true });
151
- writeFileSync(schemaFilePath, schemaString, "utf-8");
152
- }
153
- }
154
- return schemaFilePath;
155
- } catch (error) {
156
- consola$1.error(`[graphql:${service.name}] Failed to download/copy schema:`, error);
157
- return;
158
- }
159
- }
160
- async function loadGraphQLDocuments(patterns) {
161
- try {
162
- return await loadDocuments(patterns, { loaders: [new GraphQLFileLoader()] });
163
- } catch (e) {
164
- if ((e.message || "").includes("Unable to find any GraphQL type definitions for the following pointers:")) return [];
165
- else throw e;
166
- }
167
- }
168
- async function generateClientTypes(schema, docs, config = {}, sdkConfig = {}, outputPath, serviceName) {
169
- if (docs.length === 0 && !serviceName) {
170
- consola$1.info("No client GraphQL files found. Skipping client type generation.");
171
- return false;
172
- }
173
- const serviceLabel = serviceName ? `:${serviceName}` : "";
174
- const mergedConfig = defu$1({
175
- emitLegacyCommonJSImports: false,
176
- useTypeImports: true,
177
- enumsAsTypes: true,
178
- strictScalars: true,
179
- maybeValue: "T | null | undefined",
180
- inputMaybeValue: "T | undefined",
181
- documentMode: "string",
182
- pureMagicComment: true,
183
- dedupeOperationSuffix: true,
184
- rawRequest: true,
185
- scalars: {
186
- DateTime: DateTimeResolver.extensions.codegenScalarType,
187
- DateTimeISO: DateTimeISOResolver.extensions.codegenScalarType,
188
- UUID: UUIDResolver.extensions.codegenScalarType,
189
- JSON: JSONResolver.extensions.codegenScalarType,
190
- JSONObject: JSONObjectResolver.extensions.codegenScalarType,
191
- NonEmptyString: NonEmptyStringResolver.extensions.codegenScalarType,
192
- Currency: CurrencyResolver.extensions.codegenScalarType,
193
- File: {
194
- input: "File",
195
- output: "File"
196
- }
197
- }
198
- }, config);
199
- const mergedSdkConfig = defu$1(mergedConfig, sdkConfig);
200
- try {
201
- if (docs.length === 0) return {
202
- types: await codegen({
203
- filename: outputPath || "client-types.generated.ts",
204
- schema: parse(printSchemaWithDirectives(schema)),
205
- documents: [],
206
- config: mergedConfig,
207
- plugins: [{ pluginContent: {} }, { typescript: {} }],
208
- pluginMap: {
209
- pluginContent: { plugin: pluginContent },
210
- typescript: { plugin }
211
- }
212
- }),
213
- sdk: `// THIS FILE IS GENERATED, DO NOT EDIT!
214
- /* eslint-disable eslint-comments/no-unlimited-disable */
215
- /* tslint:disable */
216
- /* eslint-disable */
217
- /* prettier-ignore */
218
-
219
- import type { GraphQLResolveInfo } from 'graphql'
220
- export type RequireFields<T, K extends keyof T> = Omit<T, K> & { [P in K]-?: NonNullable<T[P]> }
221
-
222
- export interface Requester<C = {}, E = unknown> {
223
- <R, V>(doc: string, vars?: V, options?: C): Promise<R> | AsyncIterable<R>
224
- }
225
-
226
- export type Sdk = {
227
- request: <R, V = Record<string, any>>(document: string, variables?: V) => Promise<R>
228
- }
229
-
230
- export function getSdk(requester: Requester): Sdk {
231
- return {
232
- request: <R, V = Record<string, any>>(document: string, variables?: V): Promise<R> => {
233
- return requester<R, V>(document, variables)
234
- }
235
- }
236
- }
237
- `
238
- };
239
- const output = await codegen({
240
- filename: outputPath || "client-types.generated.ts",
241
- schema: parse(printSchemaWithDirectives(schema)),
242
- documents: [...docs],
243
- config: mergedConfig,
244
- plugins: [
245
- { pluginContent: {} },
246
- { typescript: {} },
247
- { typescriptOperations: {} }
248
- ],
249
- pluginMap: {
250
- pluginContent: { plugin: pluginContent },
251
- typescript: { plugin },
252
- typescriptOperations: { plugin: plugin$2 }
253
- }
254
- });
255
- const typesPath = serviceName ? `#graphql/client/${serviceName}` : "#graphql/client";
256
- const sdkOutput = await preset.buildGeneratesSection({
257
- baseOutputDir: outputPath || "client-types.generated.ts",
258
- schema: parse(printSchemaWithDirectives(schema)),
259
- documents: [...docs],
260
- config: mergedSdkConfig,
261
- presetConfig: { typesPath },
262
- plugins: [{ pluginContent: {} }, { typescriptGenericSdk: {} }],
263
- pluginMap: {
264
- pluginContent: { plugin: pluginContent },
265
- typescriptGenericSdk: { plugin: plugin$1 }
266
- }
267
- });
268
- return {
269
- types: output,
270
- sdk: (await Promise.all(sdkOutput.map(async (config$1) => {
271
- return {
272
- file: config$1.filename,
273
- content: await codegen(config$1)
274
- };
275
- })))[0]?.content || ""
276
- };
277
- } catch (error) {
278
- consola$1.warn(`[graphql${serviceLabel}] Client type generation failed:`, error);
279
- return false;
280
- }
281
- }
282
- /**
283
- * Generate client types for external GraphQL service
284
- */
285
- async function generateExternalClientTypes(service, schema, docs) {
286
- return generateClientTypes(schema, docs, service.codegen?.client || {}, service.codegen?.clientSDK || {}, void 0, service.name);
287
- }
288
-
289
- //#endregion
290
- export { downloadAndSaveSchema, generateClientTypes, generateExternalClientTypes, graphQLLoadSchemaSync, loadExternalSchema, loadGraphQLDocuments };
@@ -1,57 +0,0 @@
1
- //#region src/utils/define.ts
2
- function defineSchema(config) {
3
- return config;
4
- }
5
- function defineResolver(resolvers) {
6
- return resolvers;
7
- }
8
- function defineQuery(resolvers = {}) {
9
- return { Query: { ...resolvers } };
10
- }
11
- function defineMutation(resolvers = {}) {
12
- return { Mutation: { ...resolvers } };
13
- }
14
- function defineSubscription(resolvers = {}) {
15
- return { Subscription: { ...resolvers } };
16
- }
17
- function defineType(resolvers) {
18
- return resolvers;
19
- }
20
- function defineGraphQLConfig(config) {
21
- return config;
22
- }
23
- /**
24
- * Helper function to create directive arguments with proper type inference
25
- * @example
26
- * args: {
27
- * myArg: arg('String!', { defaultValue: 'hello' })
28
- * }
29
- */
30
- function arg(type, options) {
31
- return {
32
- type,
33
- ...options
34
- };
35
- }
36
- function defineDirective(config) {
37
- const args = config.args ? Object.entries(config.args).map(([name, arg$1]) => {
38
- const defaultValue = arg$1.defaultValue !== void 0 ? ` = ${JSON.stringify(arg$1.defaultValue)}` : "";
39
- return `${name}: ${arg$1.type}${defaultValue}`;
40
- }).join(", ") : "";
41
- const argsString = args ? `(${args})` : "";
42
- const locations = config.locations.join(" | ");
43
- const schemaDefinition = `directive @${config.name}${argsString} on ${locations}`;
44
- Object.defineProperty(config, "__schema", {
45
- value: schemaDefinition,
46
- enumerable: false,
47
- configurable: false,
48
- writable: false
49
- });
50
- return {
51
- ...config,
52
- locations: [...config.locations]
53
- };
54
- }
55
-
56
- //#endregion
57
- export { arg, defineDirective, defineGraphQLConfig, defineMutation, defineQuery, defineResolver, defineSchema, defineSubscription, defineType };
@@ -1,39 +0,0 @@
1
- import { GenImport } from "../types/index.js";
2
- import { directiveParser, generateDirectiveSchema, generateDirectiveSchemas } from "./directive-parser.js";
3
- import { Nitro } from "nitro/types";
4
-
5
- //#region src/utils/index.d.ts
6
- declare const GLOB_SCAN_PATTERN = "**/*.{graphql,gql,js,mjs,cjs,ts,mts,cts,tsx,jsx}";
7
- /**
8
- * Get all Nuxt layer directories from Nitro config
9
- */
10
- declare function getLayerDirectories(nitro: Nitro): string[];
11
- /**
12
- * Get all Nuxt layer server directories from Nitro config
13
- */
14
- declare function getLayerServerDirectories(nitro: Nitro): string[];
15
- /**
16
- * Get all Nuxt layer app directories from Nitro config
17
- */
18
- declare function getLayerAppDirectories(nitro: Nitro): string[];
19
- /**
20
- * Generate layer-aware ignore patterns for auto-generated files
21
- */
22
- declare function generateLayerIgnorePatterns(): string[];
23
- declare function getImportId(p: string, lazy?: boolean): string;
24
- declare function relativeWithDot(from: string, to: string): string;
25
- declare function scanGraphql(nitro: Nitro): Promise<string[]>;
26
- declare function scanResolvers(nitro: Nitro): Promise<GenImport[]>;
27
- declare function scanDirectives(nitro: Nitro): Promise<GenImport[]>;
28
- declare function scanSchemas(nitro: Nitro): Promise<string[]>;
29
- declare function scanDocs(nitro: Nitro): Promise<string[]>;
30
- /**
31
- * Scan documents for a specific external service
32
- */
33
- declare function scanExternalServiceDocs(nitro: Nitro, serviceName: string, patterns: string[]): Promise<string[]>;
34
- /**
35
- * Validate external GraphQL service configuration
36
- */
37
- declare function validateExternalServices(services: unknown[]): string[];
38
- //#endregion
39
- export { GLOB_SCAN_PATTERN, directiveParser, generateDirectiveSchema, generateDirectiveSchemas, generateLayerIgnorePatterns, getImportId, getLayerAppDirectories, getLayerDirectories, getLayerServerDirectories, relativeWithDot, scanDirectives, scanDocs, scanExternalServiceDocs, scanGraphql, scanResolvers, scanSchemas, validateExternalServices };