nitro-graphql 0.0.5 → 0.0.7

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 (36) hide show
  1. package/README.md +1 -30
  2. package/dist/ecosystem/nuxt.d.ts +2 -2
  3. package/dist/ecosystem/nuxt.js +14 -13
  4. package/dist/graphql/index.d.ts +5 -0
  5. package/dist/graphql/server.d.ts +5 -0
  6. package/dist/index.d.ts +9 -3
  7. package/dist/index.js +63 -19
  8. package/dist/node_modules/.pnpm/@graphql-codegen_plugin-helpers@3.1.2_graphql@16.11.0/node_modules/@graphql-codegen/plugin-helpers/esm/federation.js +1 -1
  9. package/dist/rollup.js +16 -13
  10. package/dist/routes/apollo-server.d.ts +6 -0
  11. package/dist/routes/apollo-server.js +39 -0
  12. package/dist/routes/graphql-yoga.d.ts +6 -0
  13. package/dist/routes/{graphql.js → graphql-yoga.js} +8 -6
  14. package/dist/routes/health.d.ts +10 -0
  15. package/dist/routes/health.js +44 -0
  16. package/dist/{types.d.ts → types/index.d.ts} +23 -29
  17. package/dist/types/standard-schema.d.ts +59 -0
  18. package/dist/utils/apollo.js +62 -0
  19. package/dist/{client-codegen.js → utils/client-codegen.js} +14 -13
  20. package/dist/utils/define.d.ts +17 -0
  21. package/dist/utils/define.js +25 -0
  22. package/dist/utils/index.d.ts +4 -10
  23. package/dist/utils/index.js +48 -13
  24. package/dist/{codegen.js → utils/server-codegen.js} +54 -35
  25. package/dist/utils/server-type-generation.js +5 -5
  26. package/package.json +17 -5
  27. package/dist/codegen.d.ts +0 -7
  28. package/dist/context.d.ts +0 -10
  29. package/dist/graphql.d.ts +0 -13
  30. package/dist/internal/create-merged-schema.d.ts +0 -7
  31. package/dist/internal/create-merged-schema.js +0 -23
  32. package/dist/internal/index.d.ts +0 -2
  33. package/dist/internal/index.js +0 -3
  34. package/dist/routes/graphql.d.ts +0 -6
  35. /package/dist/{context.js → graphql/index.js} +0 -0
  36. /package/dist/{types.js → graphql/server.js} +0 -0
package/README.md CHANGED
@@ -46,21 +46,6 @@ export default defineNitroConfig({
46
46
  endpoint: '/api/graphql', // default
47
47
  playground: true, // default (Apollo Sandbox)
48
48
  cors: false, // default
49
- cacheHeaders: {
50
- enabled: true, // default
51
- maxAge: 604800, // default (1 week)
52
- },
53
- client: {
54
- enabled: false, // default
55
- outputPath: undefined, // Will default to .nitro/types/graphql-client.generated.ts
56
- watchPatterns: undefined, // Will default to src/**/*.{graphql,gql} excluding server/graphql
57
- config: {
58
- documentMode: 'string',
59
- emitLegacyCommonJSImports: false,
60
- useTypeImports: true,
61
- enumsAsTypes: true,
62
- }
63
- }
64
49
  }
65
50
  })
66
51
  ```
@@ -173,7 +158,7 @@ The module automatically generates TypeScript types from your GraphQL schema:
173
158
  These types are automatically available in your resolvers:
174
159
 
175
160
  ```ts
176
- import type { QueryResolvers } from '#build/graphql-types.generated'
161
+ import type { QueryResolvers } from '#graphql/server'
177
162
  // server/graphql/users/user-queries.ts
178
163
  import { defineResolver } from 'nitro-graphql'
179
164
 
@@ -258,12 +243,6 @@ interface NitroGraphQLYogaOptions {
258
243
  methods?: string[]
259
244
  }
260
245
 
261
- // Cache headers configuration
262
- cacheHeaders?: {
263
- enabled?: boolean // default: true
264
- maxAge?: number // default: 604800 (1 week)
265
- }
266
-
267
246
  // Client type generation
268
247
  client?: {
269
248
  enabled?: boolean // default: false
@@ -362,14 +341,6 @@ Enable client type generation for your frontend queries:
362
341
  // nitro.config.ts
363
342
  export default defineNitroConfig({
364
343
  graphqlYoga: {
365
- client: {
366
- enabled: true,
367
- watchPatterns: [
368
- 'client/**/*.graphql',
369
- 'pages/**/*.vue',
370
- 'components/**/*.vue'
371
- ]
372
- }
373
344
  }
374
345
  })
375
346
  ```
@@ -1,7 +1,7 @@
1
- import * as _nuxt_schema2 from "@nuxt/schema";
1
+ import * as _nuxt_schema1 from "@nuxt/schema";
2
2
 
3
3
  //#region src/ecosystem/nuxt.d.ts
4
4
  interface ModuleOptions {}
5
- declare const _default: _nuxt_schema2.NuxtModule<ModuleOptions, ModuleOptions, false>;
5
+ declare const _default: _nuxt_schema1.NuxtModule<ModuleOptions, ModuleOptions, false>;
6
6
  //#endregion
7
7
  export { ModuleOptions, _default as default };
@@ -1,5 +1,5 @@
1
- import { join } from "pathe";
2
- import { addImportsDir, defineNuxtModule } from "@nuxt/kit";
1
+ import { join, resolve } from "pathe";
2
+ import { defineNuxtModule } from "@nuxt/kit";
3
3
 
4
4
  //#region src/ecosystem/nuxt.ts
5
5
  var nuxt_default = defineNuxtModule({
@@ -8,20 +8,21 @@ var nuxt_default = defineNuxtModule({
8
8
  configKey: "nitro-graphql-nuxt",
9
9
  compatibility: { nuxt: ">=3.16.0" }
10
10
  },
11
- defaults: {},
12
- setup: (options, nuxt) => {
13
- nuxt.hooks.hook("prepare:types", (options$1) => {
14
- options$1.references.push({ path: "types/nitro-graphql-client.d.ts" });
15
- options$1.tsConfig ??= {};
16
- options$1.tsConfig.compilerOptions ??= {};
17
- options$1.tsConfig.compilerOptions.paths ??= {};
18
- options$1.tsConfig.compilerOptions.paths["#graphql/client"] = ["./types/nitro-graphql-client.d.ts"];
19
- options$1.tsConfig.include = options$1.tsConfig.include || [];
20
- options$1.tsConfig.include.push("./types/nitro-graphql-client.d.ts");
11
+ setup: async (_options, nuxt) => {
12
+ nuxt.hooks.hook("prepare:types", (options) => {
13
+ options.references.push({ path: "types/nitro-graphql-client.d.ts" });
14
+ options.tsConfig ??= {};
15
+ options.tsConfig.compilerOptions ??= {};
16
+ options.tsConfig.compilerOptions.paths ??= {};
17
+ options.tsConfig.compilerOptions.paths["#graphql/client"] = ["./types/nitro-graphql-client.d.ts"];
18
+ options.tsConfig.include = options.tsConfig.include || [];
19
+ options.tsConfig.include.push("./types/nitro-graphql-client.d.ts");
21
20
  });
22
21
  nuxt.options.alias = nuxt.options.alias || {};
23
22
  nuxt.options.alias["#graphql/client"] = join(nuxt.options.buildDir, "types/nitro-graphql-client.d.ts");
24
- addImportsDir(join(nuxt.options.srcDir, "graphql"));
23
+ nuxt.hook("imports:dirs", (dirs) => {
24
+ dirs.push(resolve(nuxt.options.srcDir, "graphql"));
25
+ });
25
26
  }
26
27
  });
27
28
 
@@ -0,0 +1,5 @@
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 };
@@ -0,0 +1,5 @@
1
+ //#region src/graphql/server.d.ts
2
+ interface StandardSchemaV1 extends Record<string, any> {}
3
+ interface ResolversTypes extends Record<string, any> {}
4
+ //#endregion
5
+ export { ResolversTypes, StandardSchemaV1 };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,12 @@
1
- import * as nitropack5 from "nitropack";
1
+ import { StandardSchemaV1 } from "./types/standard-schema.js";
2
+ import { CodegenClientConfig, CodegenServerConfig, GenImport, NitroGraphQLOptions } from "./types/index.js";
3
+ import { defineGraphQLConfig, defineMutation, defineQuery, defineResolver, defineSchema, defineSubscription, defineType } from "./utils/define.js";
4
+ import * as nitropack0 from "nitropack";
2
5
 
3
6
  //#region src/index.d.ts
4
- declare const _default: nitropack5.NitroModule;
7
+ interface Resolvers extends Record<string, any> {}
8
+ interface CustomSchema extends Record<string, any> {}
9
+ type GraphQLFramework = 'graphql-yoga';
10
+ declare const _default: nitropack0.NitroModule;
5
11
  //#endregion
6
- export { _default as default };
12
+ export { CodegenClientConfig, CodegenServerConfig, CustomSchema, GenImport, GraphQLFramework, NitroGraphQLOptions, Resolvers, StandardSchemaV1, _default as default, defineGraphQLConfig, defineMutation, defineQuery, defineResolver, defineSchema, defineSubscription, defineType };
package/dist/index.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import { relativeWithDot, scanDefs, scanResolvers } from "./utils/index.js";
2
2
  import { clientTypeGeneration, serverTypeGeneration } from "./utils/server-type-generation.js";
3
3
  import { rollupConfig } from "./rollup.js";
4
+ import { defineGraphQLConfig, defineMutation, defineQuery, defineResolver, defineSchema, defineSubscription, defineType } from "./utils/define.js";
4
5
  import { writeFileSync } from "node:fs";
5
6
  import { fileURLToPath } from "node:url";
6
7
  import { watch } from "chokidar";
8
+ import defu from "defu";
7
9
  import { defineNitroModule } from "nitropack/kit";
8
10
  import { dirname, join, resolve } from "pathe";
9
11
 
@@ -14,8 +16,28 @@ var src_default = defineNitroModule({
14
16
  nitro.graphql ||= {
15
17
  buildDir: "",
16
18
  watchDirs: [],
17
- clientDir: ""
19
+ clientDir: "",
20
+ serverDir: resolve(nitro.options.srcDir, "graphql")
18
21
  };
22
+ nitro.hooks.hook("rollup:before", (nitro$1, rollupConfig$1) => {
23
+ rollupConfig$1.external = rollupConfig$1.external || [];
24
+ const codegenExternals = ["oxc-parser", "@oxc-parser"];
25
+ if (Array.isArray(rollupConfig$1.external)) rollupConfig$1.external.push(...codegenExternals);
26
+ else if (typeof rollupConfig$1.external === "function") {
27
+ const originalExternal = rollupConfig$1.external;
28
+ rollupConfig$1.external = (id, parent, isResolved) => {
29
+ if (codegenExternals.some((external) => id.includes(external))) return true;
30
+ return originalExternal(id, parent, isResolved);
31
+ };
32
+ }
33
+ });
34
+ nitro.options.runtimeConfig.graphql = defu(nitro.options.runtimeConfig.graphql || {}, {
35
+ endpoint: {
36
+ graphql: "/api/graphql",
37
+ healthCheck: "/api/graphql/health"
38
+ },
39
+ playground: true
40
+ });
19
41
  const graphqlBuildDir = resolve(nitro.options.buildDir, "graphql");
20
42
  nitro.graphql.buildDir = graphqlBuildDir;
21
43
  const watchDirs = [];
@@ -26,13 +48,16 @@ var src_default = defineNitroModule({
26
48
  break;
27
49
  default:
28
50
  }
29
- watch(watchDirs, {
51
+ const watcher = watch(watchDirs, {
30
52
  persistent: true,
31
53
  ignoreInitial: true,
32
54
  ignored: nitro.options.ignore
33
55
  }).on("all", async (event, path) => {
34
56
  if (path.endsWith(".graphql") || path.endsWith(".gql")) await clientTypeGeneration(nitro, path);
35
57
  });
58
+ nitro.hooks.hook("close", () => {
59
+ watcher.close();
60
+ });
36
61
  const tsConfigPath = resolve(nitro.options.buildDir, nitro.options.typescript.tsconfigPath);
37
62
  const tsconfigDir = dirname(tsConfigPath);
38
63
  const typesDir = resolve(nitro.options.buildDir, "types");
@@ -49,26 +74,38 @@ var src_default = defineNitroModule({
49
74
  await rollupConfig(nitro);
50
75
  await serverTypeGeneration(nitro);
51
76
  await clientTypeGeneration(nitro, nitro.graphql.clientDir);
52
- const endpoint = "/api/graphql";
53
77
  const runtime = fileURLToPath(new URL("routes", import.meta.url));
54
- nitro.options.handlers.push({
55
- route: endpoint,
56
- handler: join(runtime, "graphql"),
57
- method: "get"
78
+ const methods = [
79
+ "get",
80
+ "post",
81
+ "options"
82
+ ];
83
+ if (nitro.options.graphql?.framework === "graphql-yoga") for (const method of methods) nitro.options.handlers.push({
84
+ route: nitro.options.runtimeConfig.graphql?.endpoint?.graphql || "/api/graphql",
85
+ handler: join(runtime, "graphql-yoga"),
86
+ method
58
87
  });
59
- nitro.options.handlers.push({
60
- route: endpoint,
61
- handler: join(runtime, "graphql"),
62
- method: "post"
88
+ if (nitro.options.graphql?.framework === "apollo-server") for (const method of methods) nitro.options.handlers.push({
89
+ route: nitro.options.runtimeConfig.graphql?.endpoint?.graphql || "/api/graphql",
90
+ handler: join(runtime, "apollo-server"),
91
+ method
63
92
  });
64
93
  nitro.options.handlers.push({
65
- route: endpoint,
66
- handler: join(runtime, "graphql"),
67
- method: "options"
94
+ route: nitro.options.runtimeConfig.graphql?.endpoint?.healthCheck || "/api/graphql/health",
95
+ handler: join(runtime, "health"),
96
+ method: "get"
68
97
  });
69
98
  if (nitro.options.imports) nitro.options.imports.presets.push({
70
- from: "nitro-graphql/utils",
71
- imports: ["defineResolver", "defineYogaConfig"]
99
+ from: "nitro-graphql/utils/define",
100
+ imports: [
101
+ "defineResolver",
102
+ "defineMutation",
103
+ "defineQuery",
104
+ "defineSubscription",
105
+ "defineType",
106
+ "defineGraphQLConfig",
107
+ "defineSchema"
108
+ ]
72
109
  });
73
110
  nitro.hooks.hook("rollup:before", (nitro$1, rollupConfig$1) => {
74
111
  const manualChunks = rollupConfig$1.output?.manualChunks;
@@ -86,19 +123,26 @@ var src_default = defineNitroModule({
86
123
  };
87
124
  });
88
125
  const graphqlDtsContent = `// Auto-generated by nitro-graphql
89
- import type { Resolvers as Test } from './nitro-graphql-server.d.ts'
90
126
 
91
- declare module 'nitro-graphql/types' {
127
+ import type { Resolvers as Test, SchemaType } from './nitro-graphql-server.d.ts'
128
+
129
+ declare module 'nitro-graphql' {
92
130
  interface Resolvers extends Test {}
131
+
132
+ interface CustomSchema extends SchemaType {}
133
+
134
+ type GraphQLFramework = '${nitro.options.graphql?.framework || "graphql-yoga"}'
93
135
  }
94
136
  `;
95
137
  writeFileSync(join(typesDir, "graphql.d.ts"), graphqlDtsContent);
138
+ nitro.options.typescript.strict = true;
96
139
  nitro.hooks.hook("types:extend", (types) => {
97
140
  types.tsConfig ||= {};
98
141
  types.tsConfig.compilerOptions ??= {};
99
142
  types.tsConfig.compilerOptions.paths ??= {};
100
143
  types.tsConfig.compilerOptions.paths["#graphql/server"] = [relativeWithDot(tsconfigDir, join(typesDir, "nitro-graphql-server.d.ts"))];
101
144
  types.tsConfig.compilerOptions.paths["#graphql/client"] = [relativeWithDot(tsconfigDir, join(typesDir, "nitro-graphql-client.d.ts"))];
145
+ types.tsConfig.compilerOptions.paths["#graphql/schemas"] = [relativeWithDot(tsconfigDir, join(nitro.graphql.serverDir, "schemas.ts"))];
102
146
  types.tsConfig.include = types.tsConfig.include || [];
103
147
  types.tsConfig.include.push(relativeWithDot(tsconfigDir, join(typesDir, "nitro-graphql-server.d.ts")), relativeWithDot(tsconfigDir, join(typesDir, "nitro-graphql-client.d.ts")), relativeWithDot(tsconfigDir, join(typesDir, "graphql.d.ts")));
104
148
  });
@@ -106,4 +150,4 @@ declare module 'nitro-graphql/types' {
106
150
  });
107
151
 
108
152
  //#endregion
109
- export { src_default as default };
153
+ export { src_default as default, defineGraphQLConfig, defineMutation, defineQuery, defineResolver, defineSchema, defineSubscription, defineType };
@@ -2,8 +2,8 @@ import { __toESM } from "../../../../../../../_virtual/rolldown_runtime.js";
2
2
  import "./utils.js";
3
3
  import { require_merge } from "../../../../../lodash@4.17.21/node_modules/lodash/merge.js";
4
4
  import "./index.js";
5
- import "@graphql-tools/utils";
6
5
  import { isObjectType, parse } from "graphql";
6
+ import "@graphql-tools/utils";
7
7
 
8
8
  //#region node_modules/.pnpm/@graphql-codegen+plugin-helpers@3.1.2_graphql@16.11.0/node_modules/@graphql-codegen/plugin-helpers/esm/federation.js
9
9
  var import_merge = __toESM(require_merge(), 1);
package/dist/rollup.js CHANGED
@@ -1,8 +1,8 @@
1
- import { scanGraphql } from "./utils/index.js";
1
+ import { getImportId, scanGraphql } from "./utils/index.js";
2
2
  import { serverTypeGeneration } from "./utils/server-type-generation.js";
3
- import { parse } from "graphql";
4
3
  import { readFile } from "node:fs/promises";
5
- import { hash } from "ohash";
4
+ import { parse } from "graphql";
5
+ import { genImport } from "knitwork";
6
6
 
7
7
  //#region src/rollup.ts
8
8
  async function rollupConfig(app) {
@@ -41,9 +41,6 @@ async function rollupConfig(app) {
41
41
  await serverTypeGeneration(app);
42
42
  });
43
43
  }
44
- function getImportId(p, lazy) {
45
- return (lazy ? "_lazy_" : "_") + hash(p).replace(/-/g, "").slice(0, 6);
46
- }
47
44
  function virtualDefs(app) {
48
45
  const getDefs = () => {
49
46
  const defs = [...app.scanDefs, ...app.options.graphql?.typedefs ?? []];
@@ -64,18 +61,24 @@ ${imports.map((h) => `{ def: ${getImportId(h)} }`).join(",\n")}
64
61
  }
65
62
  function virtualResolvers(app) {
66
63
  const getResolvers = () => {
67
- const resolvers = [...app.scanResolvers, ...app.options.graphql?.resolvers ?? []];
64
+ const resolvers = [...app.scanResolvers];
68
65
  return resolvers;
69
66
  };
70
67
  app.options.virtual ??= {};
71
68
  app.options.virtual["#nitro-internal-virtual/server-resolvers"] = () => {
72
69
  const imports = getResolvers();
73
- const code = `
74
- ${imports.map((handler) => `import ${getImportId(handler)} from '${handler}';`).join("\n")}
75
- export const resolvers = [
76
- ${imports.map((h) => `{ resolver: ${getImportId(h)} }`).join(",\n")}
77
- ];
78
- `;
70
+ const importsContent = [...imports.map(({ specifier, imports: imports$1, options }) => {
71
+ return genImport(specifier, imports$1, options);
72
+ })];
73
+ const data = imports.map(({ imports: imports$1 }) => imports$1.map((i) => `{ resolver: ${i.as} }`).join(",\n")).filter(Boolean).join(",\n");
74
+ const content = [
75
+ "export const resolvers = [",
76
+ data,
77
+ "]",
78
+ ""
79
+ ];
80
+ content.unshift(...importsContent);
81
+ const code = content.join("\n");
79
82
  return code;
80
83
  };
81
84
  }
@@ -0,0 +1,6 @@
1
+ import * as h34 from "h3";
2
+
3
+ //#region src/routes/apollo-server.d.ts
4
+ declare const _default: h34.EventHandler<h34.EventHandlerRequest, any>;
5
+ //#endregion
6
+ export { _default as default };
@@ -0,0 +1,39 @@
1
+ import { startServerAndCreateH3Handler } from "../utils/apollo.js";
2
+ import { mergeResolvers, mergeTypeDefs } from "@graphql-tools/merge";
3
+ import { defs } from "#nitro-internal-virtual/server-defs";
4
+ import { resolvers } from "#nitro-internal-virtual/server-resolvers";
5
+ import { ApolloServer } from "@apollo/server";
6
+ import { ApolloServerPluginLandingPageLocalDefault } from "@apollo/server/plugin/landingPage/default";
7
+
8
+ //#region src/routes/apollo-server.ts
9
+ function createMergedSchema() {
10
+ try {
11
+ const mergedDefs = defs.map((schema) => schema.def).join("\n\n");
12
+ const typeDefs = mergeTypeDefs([mergedDefs]);
13
+ const mergedResolvers = mergeResolvers(resolvers.map((r) => r.resolver));
14
+ return {
15
+ typeDefs,
16
+ resolvers: mergedResolvers
17
+ };
18
+ } catch (error) {
19
+ console.error("Schema merge error:", error);
20
+ throw error;
21
+ }
22
+ }
23
+ let apolloServer;
24
+ function createApolloServer() {
25
+ if (!apolloServer) {
26
+ const { typeDefs, resolvers: mergedResolvers } = createMergedSchema();
27
+ apolloServer = new ApolloServer({
28
+ typeDefs,
29
+ resolvers: mergedResolvers,
30
+ introspection: true,
31
+ plugins: [ApolloServerPluginLandingPageLocalDefault({ embed: true })]
32
+ });
33
+ }
34
+ return apolloServer;
35
+ }
36
+ var apollo_server_default = startServerAndCreateH3Handler(createApolloServer, { context: async (event) => ({ event }) });
37
+
38
+ //#endregion
39
+ export { apollo_server_default as default };
@@ -0,0 +1,6 @@
1
+ import * as h32 from "h3";
2
+
3
+ //#region src/routes/graphql-yoga.d.ts
4
+ declare const _default: h32.EventHandler<h32.EventHandlerRequest, Promise<Response>>;
5
+ //#endregion
6
+ export { _default as default };
@@ -1,10 +1,10 @@
1
- import { createSchema, createYoga } from "graphql-yoga";
2
1
  import { mergeResolvers, mergeTypeDefs } from "@graphql-tools/merge";
3
2
  import { defs } from "#nitro-internal-virtual/server-defs";
4
3
  import { resolvers } from "#nitro-internal-virtual/server-resolvers";
5
- import { defineEventHandler } from "h3";
4
+ import { defineEventHandler, toWebRequest } from "h3";
5
+ import { createSchema, createYoga } from "graphql-yoga";
6
6
 
7
- //#region src/routes/graphql.ts
7
+ //#region src/routes/graphql-yoga.ts
8
8
  const apolloSandboxHtml = `<!DOCTYPE html>
9
9
  <html lang="en">
10
10
  <body style="margin: 0; overflow-x: hidden; overflow-y: hidden">
@@ -37,7 +37,7 @@ function createMergedSchema() {
37
37
  }
38
38
  }
39
39
  let yoga;
40
- var graphql_default = defineEventHandler(async (event) => {
40
+ var graphql_yoga_default = defineEventHandler(async (event) => {
41
41
  if (!yoga) {
42
42
  const schema = createMergedSchema();
43
43
  yoga = createYoga({
@@ -47,8 +47,10 @@ var graphql_default = defineEventHandler(async (event) => {
47
47
  renderGraphiQL: () => apolloSandboxHtml
48
48
  });
49
49
  }
50
- return yoga.handle(event.node.req, event.node.res);
50
+ const request = toWebRequest(event);
51
+ const response = await yoga.handleRequest(request, event);
52
+ return new Response(response.body, response);
51
53
  });
52
54
 
53
55
  //#endregion
54
- export { graphql_default as default };
56
+ export { graphql_yoga_default as default };
@@ -0,0 +1,10 @@
1
+ import * as h36 from "h3";
2
+
3
+ //#region src/routes/health.d.ts
4
+ declare const _default: h36.EventHandler<h36.EventHandlerRequest, Promise<{
5
+ status: string;
6
+ message: string;
7
+ timestamp: string;
8
+ }>>;
9
+ //#endregion
10
+ export { _default as default };
@@ -0,0 +1,44 @@
1
+ import { defineEventHandler, setResponseStatus } from "h3";
2
+ import { useRuntimeConfig } from "nitropack/runtime";
3
+
4
+ //#region src/routes/health.ts
5
+ var health_default = defineEventHandler(async (event) => {
6
+ const runtime = useRuntimeConfig();
7
+ if (!runtime.graphql || !runtime.graphql.endpoint?.graphql) {
8
+ setResponseStatus(event, 404);
9
+ return {
10
+ status: "error",
11
+ message: "GraphQL health check endpoint is not configured",
12
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
13
+ };
14
+ }
15
+ try {
16
+ const response = await $fetch(runtime.graphql.endpoint?.graphql, {
17
+ method: "POST",
18
+ body: {
19
+ query: "query Health { __typename }",
20
+ operationName: "Health"
21
+ },
22
+ headers: {
23
+ "Content-Type": "application/json",
24
+ "Accept": "application/json"
25
+ }
26
+ });
27
+ if (response && typeof response === "object" && "data" in response) return {
28
+ status: "healthy",
29
+ message: "GraphQL server is running",
30
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
31
+ };
32
+ throw new Error("Invalid response from GraphQL server");
33
+ } catch (error) {
34
+ setResponseStatus(event, 503);
35
+ return {
36
+ status: "unhealthy",
37
+ message: error instanceof Error ? error.message : "GraphQL server is not responding",
38
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
39
+ };
40
+ }
41
+ });
42
+
43
+ //#endregion
44
+ export { health_default as default };
@@ -1,20 +1,31 @@
1
- import { TypeScriptPluginConfig } from "@graphql-codegen/typescript";
2
- import { TypeScriptResolversPluginConfig } from "@graphql-codegen/typescript-resolvers";
1
+ import { StandardSchemaV1 } from "./standard-schema.js";
2
+ import { ESMCodeGenOptions } from "knitwork";
3
3
  import { IResolvers } from "@graphql-tools/utils";
4
+ import { TypeScriptPluginConfig } from "@graphql-codegen/typescript";
4
5
  import { TypeScriptDocumentsPluginConfig } from "@graphql-codegen/typescript-operations";
5
- import { YogaServerOptions } from "graphql-yoga";
6
- import { IncomingMessage, ServerResponse } from "node:http";
6
+ import { TypeScriptResolversPluginConfig } from "@graphql-codegen/typescript-resolvers";
7
7
 
8
- //#region src/types.d.ts
8
+ //#region src/types/index.d.ts
9
9
  type CodegenServerConfig = TypeScriptPluginConfig & TypeScriptResolversPluginConfig;
10
+ interface IESMImport {
11
+ name: string;
12
+ as?: string;
13
+ type: 'resolver' | 'query' | 'mutation' | 'type' | 'subscription';
14
+ }
15
+ interface GenImport {
16
+ specifier: string;
17
+ imports: IESMImport[];
18
+ options?: ESMCodeGenOptions;
19
+ }
10
20
  declare module 'nitropack/types' {
11
21
  interface Nitro {
12
22
  scanDefs: string[];
13
- scanResolvers: any;
23
+ scanResolvers: GenImport[];
14
24
  graphql: {
15
25
  buildDir: string;
16
26
  watchDirs: string[];
17
27
  clientDir: string;
28
+ serverDir: string;
18
29
  };
19
30
  }
20
31
  }
@@ -29,22 +40,17 @@ declare module 'nitropack' {
29
40
  graphql?: NitroGraphQLOptions;
30
41
  }
31
42
  }
32
- interface GraphQLSchemaConfig {
33
- typeDefs: string | string[];
34
- resolvers: any;
35
- }
36
43
  interface CodegenClientConfig extends TypeScriptPluginConfig, TypeScriptDocumentsPluginConfig {
37
44
  endpoint?: string;
38
45
  documentMode?: 'string' | 'graphQLTag' | 'documentNode' | 'documentNodeImportFragments' | 'external';
39
46
  }
40
47
  interface NitroGraphQLOptions {
41
- endpoint?: string;
42
- healthCheckEndpoint?: string;
48
+ framework: 'graphql-yoga' | 'apollo-server';
49
+ endpoint?: {
50
+ graphql?: string;
51
+ healthCheck?: string;
52
+ };
43
53
  playground?: boolean;
44
- cors?: YogaServerOptions<{
45
- req: IncomingMessage;
46
- res: ServerResponse;
47
- }, any>['cors'];
48
54
  typedefs?: string[];
49
55
  resolvers?: Array<IResolvers<any, any>>;
50
56
  loader?: {
@@ -52,22 +58,10 @@ interface NitroGraphQLOptions {
52
58
  exclude?: RegExp;
53
59
  validate?: boolean;
54
60
  };
55
- cacheHeaders?: {
56
- enabled?: boolean;
57
- maxAge?: number;
58
- };
59
61
  codegen?: {
60
62
  server?: CodegenServerConfig;
61
63
  client?: CodegenClientConfig;
62
64
  };
63
- client?: {
64
- enabled?: boolean;
65
- outputPath?: string;
66
- watchPatterns?: string[];
67
- nuxtPatterns?: string[];
68
- };
69
- yogaConfig?: Partial<YogaServerOptions<any, any>>;
70
65
  }
71
- interface Resolvers {}
72
66
  //#endregion
73
- export { CodegenClientConfig, CodegenServerConfig, GraphQLSchemaConfig, NitroGraphQLOptions, Resolvers };
67
+ export { CodegenClientConfig, CodegenServerConfig, GenImport, NitroGraphQLOptions };
@@ -0,0 +1,59 @@
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 };
@@ -0,0 +1,62 @@
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 apolloServer = typeof server === "function" ? server() : server;
7
+ apolloServer.startInBackgroundHandlingStartupErrorsByLoggingAndFailingAllRequests();
8
+ const defaultContext = () => Promise.resolve({});
9
+ const contextFunction = options?.context ?? defaultContext;
10
+ return eventHandler({
11
+ handler: async (event) => {
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
+ const PayloadMethods = [
53
+ "PATCH",
54
+ "POST",
55
+ "PUT",
56
+ "DELETE"
57
+ ];
58
+ if (isMethod(event, PayloadMethods)) return await readBody(event);
59
+ }
60
+
61
+ //#endregion
62
+ export { startServerAndCreateH3Handler };
@@ -1,16 +1,16 @@
1
- import { preset } from "./node_modules/.pnpm/@graphql-codegen_import-types-preset@3.0.1_graphql@16.11.0/node_modules/@graphql-codegen/import-types-preset/esm/index.js";
2
- import { codegen } from "@graphql-codegen/core";
3
- import { plugin } from "@graphql-codegen/typescript";
1
+ import { preset } from "../node_modules/.pnpm/@graphql-codegen_import-types-preset@3.0.1_graphql@16.11.0/node_modules/@graphql-codegen/import-types-preset/esm/index.js";
2
+ import { defu as defu$1 } from "defu";
3
+ import { parse } from "graphql";
4
4
  import { printSchemaWithDirectives } from "@graphql-tools/utils";
5
5
  import { consola as consola$1 } from "consola";
6
- import { defu } from "defu";
7
- import { parse } from "graphql";
8
- import { plugin as plugin$1 } from "@graphql-codegen/typescript-operations";
9
- import { plugin as plugin$2 } from "@graphql-codegen/typescript-generic-sdk";
6
+ import { codegen } from "@graphql-codegen/core";
7
+ import { plugin } from "@graphql-codegen/typescript";
8
+ import { plugin as plugin$1 } from "@graphql-codegen/typescript-generic-sdk";
9
+ import { plugin as plugin$2 } from "@graphql-codegen/typescript-operations";
10
10
  import { GraphQLFileLoader } from "@graphql-tools/graphql-file-loader";
11
11
  import { loadDocuments } from "@graphql-tools/load";
12
12
 
13
- //#region src/client-codegen.ts
13
+ //#region src/utils/client-codegen.ts
14
14
  function pluginContent(_schema, _documents, _config, _info) {
15
15
  return {
16
16
  prepend: [
@@ -54,7 +54,7 @@ async function generateClientTypes(schema, docs, config = {}, outputPath) {
54
54
  Currency: "string"
55
55
  }
56
56
  };
57
- const mergedConfig = defu(config, defaultConfig);
57
+ const mergedConfig = defu$1(config, defaultConfig);
58
58
  try {
59
59
  const output = await codegen({
60
60
  filename: outputPath || "client-types.generated.ts",
@@ -69,7 +69,7 @@ async function generateClientTypes(schema, docs, config = {}, outputPath) {
69
69
  pluginMap: {
70
70
  pluginContent: { plugin: pluginContent },
71
71
  typescript: { plugin },
72
- typescriptOperations: { plugin: plugin$1 }
72
+ typescriptOperations: { plugin: plugin$2 }
73
73
  }
74
74
  });
75
75
  const sdkOutput = await preset.buildGeneratesSection({
@@ -86,7 +86,8 @@ async function generateClientTypes(schema, docs, config = {}, outputPath) {
86
86
  UUID: "string",
87
87
  NonEmptyString: "string",
88
88
  Currency: "string"
89
- }
89
+ },
90
+ useTypeImports: true
90
91
  },
91
92
  presetConfig: { typesPath: "#graphql/client" },
92
93
  plugins: [
@@ -96,8 +97,8 @@ async function generateClientTypes(schema, docs, config = {}, outputPath) {
96
97
  ],
97
98
  pluginMap: {
98
99
  pluginContent: { plugin: pluginContent },
99
- typescriptOperations: { plugin: plugin$1 },
100
- typescriptGenericSdk: { plugin: plugin$2 }
100
+ typescriptOperations: { plugin: plugin$2 },
101
+ typescriptGenericSdk: { plugin: plugin$1 }
101
102
  }
102
103
  });
103
104
  const results = await Promise.all(sdkOutput.map(async (config$1) => {
@@ -0,0 +1,17 @@
1
+ import { ApolloServerOptions, BaseContext } from "@apollo/server";
2
+ import { YogaServerOptions } from "graphql-yoga";
3
+ import { ResolversTypes, StandardSchemaV1 } from "#graphql/server";
4
+ import { GraphQLFramework, Resolvers } from "nitro-graphql";
5
+
6
+ //#region src/utils/define.d.ts
7
+ type Flatten<T> = T extends infer U ? { [K in keyof U]: U[K] } : never;
8
+ declare function defineSchema<T extends Partial<Record<keyof ResolversTypes, StandardSchemaV1>>>(config: T): Flatten<T>;
9
+ declare function defineResolver(resolvers: Resolvers): Resolvers;
10
+ declare function defineQuery(resolvers?: Resolvers['Query']): Resolvers;
11
+ declare function defineMutation(resolvers?: Resolvers['Mutation']): Resolvers;
12
+ declare function defineSubscription(resolvers?: Resolvers['Subscription']): Resolvers;
13
+ declare function defineType(resolvers: Resolvers): Resolvers;
14
+ type DefineServerConfig = GraphQLFramework extends 'graphql-yoga' ? Partial<YogaServerOptions<any, any>> : GraphQLFramework extends 'apollo-server' ? Partial<ApolloServerOptions<BaseContext>> : Record<string, any>;
15
+ declare function defineGraphQLConfig(config: Partial<DefineServerConfig>): Partial<DefineServerConfig>;
16
+ //#endregion
17
+ export { defineGraphQLConfig, defineMutation, defineQuery, defineResolver, defineSchema, defineSubscription, defineType };
@@ -0,0 +1,25 @@
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
+ //#endregion
25
+ export { defineGraphQLConfig, defineMutation, defineQuery, defineResolver, defineSchema, defineSubscription, defineType };
@@ -1,21 +1,15 @@
1
+ import { GenImport } from "../types/index.js";
1
2
  import { Nitro } from "nitropack";
2
- import { YogaServerOptions } from "graphql-yoga";
3
- import { GraphQLSchemaConfig, Resolvers } from "nitro-graphql/types";
4
3
 
5
4
  //#region src/utils/index.d.ts
6
5
  declare const GLOB_SCAN_PATTERN = "**/*.{graphql,gql,js,mjs,cjs,ts,mts,cts,tsx,jsx}";
7
- declare function defineGraphQLSchema(config: GraphQLSchemaConfig): GraphQLSchemaConfig;
8
- declare function defineResolver(resolvers: Resolvers): Resolvers;
9
- /**
10
- * Helper function to define GraphQL Yoga configuration with type safety
11
- */
12
- declare function defineYogaConfig<TServerContext = any, TUserContext = any>(config: Partial<YogaServerOptions<TServerContext, TUserContext>>): Partial<YogaServerOptions<TServerContext, TUserContext>>;
6
+ declare function getImportId(p: string, lazy?: boolean): string;
13
7
  declare function relativeWithDot(from: string, to: string): string;
14
8
  declare function scanGraphql(nitro: Nitro): Promise<string[]>;
15
- declare function scanResolvers(nitro: Nitro): Promise<string[]>;
9
+ declare function scanResolvers(nitro: Nitro): Promise<GenImport[]>;
16
10
  declare function scanDirectives(nitro: Nitro): Promise<string[]>;
17
11
  declare function scanTypeDefs(nitro: Nitro): Promise<string[]>;
18
12
  declare function scanDefs(nitro: Nitro): Promise<string[]>;
19
13
  declare function unique(arr: any[]): any[];
20
14
  //#endregion
21
- export { GLOB_SCAN_PATTERN, defineGraphQLSchema, defineResolver, defineYogaConfig, relativeWithDot, scanDefs, scanDirectives, scanGraphql, scanResolvers, scanTypeDefs, unique };
15
+ export { GLOB_SCAN_PATTERN, getImportId, relativeWithDot, scanDefs, scanDirectives, scanGraphql, scanResolvers, scanTypeDefs, unique };
@@ -1,19 +1,13 @@
1
1
  import { join, relative } from "pathe";
2
+ import { readFile } from "node:fs/promises";
3
+ import { hash } from "ohash";
4
+ import { parseAsync } from "oxc-parser";
2
5
  import { glob } from "tinyglobby";
3
6
 
4
7
  //#region src/utils/index.ts
5
8
  const GLOB_SCAN_PATTERN = "**/*.{graphql,gql,js,mjs,cjs,ts,mts,cts,tsx,jsx}";
6
- function defineGraphQLSchema(config) {
7
- return config;
8
- }
9
- function defineResolver(resolvers) {
10
- return resolvers;
11
- }
12
- /**
13
- * Helper function to define GraphQL Yoga configuration with type safety
14
- */
15
- function defineYogaConfig(config) {
16
- return config;
9
+ function getImportId(p, lazy) {
10
+ return (lazy ? "_lazy_" : "_") + hash(p).replace(/-/g, "").slice(0, 6);
17
11
  }
18
12
  const RELATIVE_RE = /^\.{1,2}\//;
19
13
  function relativeWithDot(from, to) {
@@ -26,7 +20,48 @@ async function scanGraphql(nitro) {
26
20
  }
27
21
  async function scanResolvers(nitro) {
28
22
  const files = await scanFiles(nitro, "graphql", "**/*.resolver.{ts,js}");
29
- return files.map((f) => f.fullPath);
23
+ const exportName = [];
24
+ for (const file of files) {
25
+ const fileContent = await readFile(file.fullPath, "utf-8");
26
+ const parsed = await parseAsync(file.fullPath, fileContent);
27
+ const exports = {
28
+ imports: [],
29
+ specifier: file.fullPath
30
+ };
31
+ for (const node of parsed.program.body) if (node.type === "ExportNamedDeclaration" && node.declaration && node.declaration.type === "VariableDeclaration") {
32
+ for (const decl of node.declaration.declarations) if (decl.type === "VariableDeclarator" && decl.init && decl.id.type === "Identifier") {
33
+ if (decl.init && decl.init.type === "CallExpression") {
34
+ if (decl.init.callee.type === "Identifier" && decl.init.callee.name === "defineResolver") exports.imports.push({
35
+ name: decl.id.name,
36
+ type: "resolver",
37
+ as: `_${hash(decl.id.name + file.path).replace(/-/g, "").slice(0, 6)}`
38
+ });
39
+ if (decl.init.callee.type === "Identifier" && decl.init.callee.name === "defineQuery") exports.imports.push({
40
+ name: decl.id.name,
41
+ type: "query",
42
+ as: `_${hash(decl.id.name + file.path).replace(/-/g, "").slice(0, 6)}`
43
+ });
44
+ if (decl.init.callee.type === "Identifier" && decl.init.callee.name === "defineMutation") exports.imports.push({
45
+ name: decl.id.name,
46
+ type: "mutation",
47
+ as: `_${hash(decl.id.name + file.path).replace(/-/g, "").slice(0, 6)}`
48
+ });
49
+ if (decl.init.callee.type === "Identifier" && decl.init.callee.name === "defineType") exports.imports.push({
50
+ name: decl.id.name,
51
+ type: "type",
52
+ as: `_${hash(decl.id.name + file.path).replace(/-/g, "").slice(0, 6)}`
53
+ });
54
+ if (decl.init.callee.type === "Identifier" && decl.init.callee.name === "defineSubscription") exports.imports.push({
55
+ name: decl.id.name,
56
+ type: "subscription",
57
+ as: `_${hash(decl.id.name + file.path).replace(/-/g, "").slice(0, 6)}`
58
+ });
59
+ }
60
+ }
61
+ }
62
+ if (exports.imports.length > 0) exportName.push(exports);
63
+ }
64
+ return exportName;
30
65
  }
31
66
  async function scanDirectives(nitro) {
32
67
  const files = await scanFiles(nitro, "graphql", "**/*.directive.{ts,js}");
@@ -69,4 +104,4 @@ function unique(arr) {
69
104
  }
70
105
 
71
106
  //#endregion
72
- export { GLOB_SCAN_PATTERN, defineGraphQLSchema, defineResolver, defineYogaConfig, relativeWithDot, scanDefs, scanDirectives, scanGraphql, scanResolvers, scanTypeDefs, unique };
107
+ export { GLOB_SCAN_PATTERN, getImportId, relativeWithDot, scanDefs, scanDirectives, scanGraphql, scanResolvers, scanTypeDefs, unique };
@@ -1,13 +1,13 @@
1
+ import { defu as defu$1 } from "defu";
2
+ import { parse } from "graphql";
3
+ import { printSchemaWithDirectives } from "@graphql-tools/utils";
4
+ import consola from "consola";
1
5
  import { codegen } from "@graphql-codegen/core";
2
6
  import * as typescriptPlugin from "@graphql-codegen/typescript";
3
7
  import * as typescriptResolversPlugin from "@graphql-codegen/typescript-resolvers";
4
- import { printSchemaWithDirectives } from "@graphql-tools/utils";
5
- import consola from "consola";
6
- import { defu } from "defu";
7
- import { parse } from "graphql";
8
8
  import { CurrencyResolver, DateTimeResolver, JSONResolver, NonEmptyStringResolver, UUIDResolver } from "graphql-scalars";
9
9
 
10
- //#region src/codegen.ts
10
+ //#region src/utils/server-codegen.ts
11
11
  function pluginContent(_schema, _documents, _config, _info) {
12
12
  return {
13
13
  prepend: [
@@ -45,15 +45,12 @@ async function generateTypes(schema, config = {}, outputPath) {
45
45
  },
46
46
  defaultScalarType: "unknown",
47
47
  defaultMapper: `ResolverReturnType<{T}>`,
48
- contextType: "./context#GraphQLContext",
48
+ contextType: "h3#H3Event",
49
49
  maybeValue: "T | null | undefined",
50
50
  inputMaybeValue: "T | undefined",
51
- enumsAsTypes: true,
52
- useTypeImports: true,
53
- strictScalars: true,
54
- emitLegacyCommonJSImports: false
51
+ declarationKind: "interface"
55
52
  };
56
- const mergedConfig = defu(config, defaultConfig);
53
+ const mergedConfig = defu$1(config, defaultConfig);
57
54
  const output = await codegen({
58
55
  filename: outputPath || "types.generated.ts",
59
56
  schema: parse(printSchemaWithDirectives(schema)),
@@ -67,35 +64,57 @@ async function generateTypes(schema, config = {}, outputPath) {
67
64
  ],
68
65
  pluginMap: {
69
66
  pluginContent: { plugin: pluginContent },
70
- imports: { plugin: () => ({
71
- prepend: [`type Primitive =
72
- | null
73
- | undefined
74
- | string
75
- | number
76
- | boolean
77
- | symbol
78
- | bigint;
67
+ imports: { plugin: () => {
68
+ return {
69
+ prepend: [
70
+ `import schemas from '#graphql/schemas'`,
71
+ `import type { StandardSchemaV1 } from 'nitro-graphql'`,
72
+ `
73
+ export type SchemaType = Partial<Record<Partial<keyof ResolversTypes>, StandardSchemaV1>>
74
+ type SchemaKeys = keyof typeof schemas;
75
+
76
+ type InferInput<T> = T extends StandardSchemaV1 ? StandardSchemaV1.InferInput<T> : unknown;
77
+ type InferOutput<T> = T extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<T> : unknown;
78
+
79
+ type InferInputFromSchema<T extends SchemaKeys> = InferInput<(typeof schemas)[T]>;
80
+ type InferOutputFromSchema<T extends SchemaKeys> = InferOutput<(typeof schemas)[T]>;
81
+
82
+ type Primitive =
83
+ | null
84
+ | undefined
85
+ | string
86
+ | number
87
+ | boolean
88
+ | symbol
89
+ | bigint;
79
90
 
80
91
  type BuiltIns = Primitive | void | Date | RegExp;
81
92
 
93
+
82
94
  type ResolverReturnType<T> = T extends BuiltIns
83
- ? T
84
- : T extends (...args: any[]) => unknown
85
- ? T | undefined
86
- : T extends object
87
- ? T extends Array<infer ItemType> // Test for arrays/tuples, per https://github.com/microsoft/TypeScript/issues/35156
88
- ? ItemType[] extends T // Test for arrays (non-tuples) specifically
89
- ? Array<ResolverReturnType<ItemType>>
90
- : ResolverReturnTypeObject<T> // Tuples behave properly
91
- : ResolverReturnTypeObject<T>
92
- : unknown;
95
+ ? T
96
+ : T extends (...args: any[]) => unknown
97
+ ? T | undefined
98
+ : T extends object
99
+ ? T extends Array<infer ItemType> // Test for arrays/tuples, per https://github.com/microsoft/TypeScript/issues/35156
100
+ ? ItemType[] extends T // Test for arrays (non-tuples) specifically
101
+ ? Array<ResolverReturnType<ItemType>>
102
+ : ResolverReturnTypeObject<T> // Tuples behave properly
103
+ : ResolverReturnTypeObject<T>
104
+ : unknown;
93
105
 
94
- type ResolverReturnTypeObject<T extends object> = {
95
- [K in keyof T]: ResolverReturnType<T[K]>
96
- };`, ""],
97
- content: ""
98
- }) },
106
+ type ResolverReturnTypeObject<T extends object> =
107
+ T extends { __typename?: infer TTypename }
108
+ ? TTypename extends SchemaKeys
109
+ ? InferOutputFromSchema<TTypename>
110
+ : { [K in keyof T]: ResolverReturnType<T[K]> }
111
+ : { [K in keyof T]: ResolverReturnType<T[K]> };
112
+ `,
113
+ ""
114
+ ],
115
+ content: ""
116
+ };
117
+ } },
99
118
  typescript: typescriptPlugin,
100
119
  typescriptResolvers: typescriptResolversPlugin
101
120
  }
@@ -1,12 +1,12 @@
1
- import { generateTypes } from "../codegen.js";
2
- import { generateClientTypes, loadGraphQLDocuments } from "../client-codegen.js";
3
- import { printSchemaWithDirectives } from "@graphql-tools/utils";
4
- import consola from "consola";
5
- import { buildASTSchema, buildSchema } from "graphql";
1
+ import { generateClientTypes, loadGraphQLDocuments } from "./client-codegen.js";
2
+ import { generateTypes } from "./server-codegen.js";
6
3
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
4
  import { dirname, join, resolve } from "pathe";
5
+ import { buildASTSchema, buildSchema } from "graphql";
8
6
  import { loadFilesSync } from "@graphql-tools/load-files";
9
7
  import { mergeTypeDefs } from "@graphql-tools/merge";
8
+ import { printSchemaWithDirectives } from "@graphql-tools/utils";
9
+ import consola from "consola";
10
10
 
11
11
  //#region src/utils/server-type-generation.ts
12
12
  async function serverTypeGeneration(app) {
package/package.json CHANGED
@@ -1,10 +1,16 @@
1
1
  {
2
2
  "name": "nitro-graphql",
3
3
  "type": "module",
4
- "version": "0.0.5",
4
+ "version": "0.0.7",
5
5
  "description": "GraphQL integration for Nitro",
6
6
  "license": "MIT",
7
7
  "sideEffects": false,
8
+ "imports": {
9
+ "#graphql/server": {
10
+ "types": "./dist/graphql/server.d.ts",
11
+ "import": "./dist/graphql/server.js"
12
+ }
13
+ },
8
14
  "exports": {
9
15
  ".": {
10
16
  "types": "./dist/index.d.ts",
@@ -30,9 +36,9 @@
30
36
  "types": "./dist/utils/index.d.ts",
31
37
  "import": "./dist/utils/index.js"
32
38
  },
33
- "./types": {
34
- "types": "./dist/types.d.ts",
35
- "import": "./dist/types.js"
39
+ "./utils/define": {
40
+ "types": "./dist/utils/define.d.ts",
41
+ "import": "./dist/utils/define.js"
36
42
  },
37
43
  "./internal": {
38
44
  "types": "./dist/internal/index.d.ts",
@@ -54,6 +60,8 @@
54
60
  "nitropack": "^2.11.13"
55
61
  },
56
62
  "dependencies": {
63
+ "@apollo/utils.withrequired": "^3.0.0",
64
+ "@as-integrations/h3": "^2.0.0",
57
65
  "@graphql-codegen/core": "^4.0.2",
58
66
  "@graphql-codegen/typescript": "^4.1.6",
59
67
  "@graphql-codegen/typescript-generic-sdk": "^4.0.2",
@@ -69,21 +77,25 @@
69
77
  "consola": "^3.4.2",
70
78
  "defu": "^6.1.4",
71
79
  "graphql-scalars": "^1.24.2",
72
- "graphql-yoga": "^5.15.1",
80
+ "knitwork": "^1.2.0",
73
81
  "ohash": "^2.0.11",
82
+ "oxc-parser": "^0.77.0",
74
83
  "pathe": "^2.0.3",
75
84
  "tinyglobby": "^0.2.14"
76
85
  },
77
86
  "devDependencies": {
78
87
  "@antfu/eslint-config": "^4.16.2",
88
+ "@apollo/server": "^4.12.2",
79
89
  "@graphql-codegen/import-types-preset": "^3.0.1",
80
90
  "@nuxt/kit": "4.0.0-rc.0",
81
91
  "@nuxt/schema": "4.0.0-rc.0",
82
92
  "@types/node": "^20.19.7",
83
93
  "bumpp": "^10.2.0",
84
94
  "changelogen": "^0.6.2",
95
+ "crossws": "0.3.5",
85
96
  "eslint": "^9.31.0",
86
97
  "graphql": "^16.11.0",
98
+ "graphql-yoga": "^5.15.1",
87
99
  "h3": "^1.15.3",
88
100
  "nitropack": "^2.11.13",
89
101
  "tsdown": "^0.12.9",
package/dist/codegen.d.ts DELETED
@@ -1,7 +0,0 @@
1
- import { CodegenServerConfig } from "./types.js";
2
- import { GraphQLSchema } from "graphql";
3
-
4
- //#region src/codegen.d.ts
5
- declare function generateTypes(schema: GraphQLSchema, config?: CodegenServerConfig, outputPath?: string): Promise<string>;
6
- //#endregion
7
- export { generateTypes };
package/dist/context.d.ts DELETED
@@ -1,10 +0,0 @@
1
- import { YogaInitialContext } from "graphql-yoga";
2
- import { H3Event } from "h3";
3
-
4
- //#region src/context.d.ts
5
- interface GraphQLContext extends YogaInitialContext {
6
- event: H3Event;
7
- storage: any;
8
- }
9
- //#endregion
10
- export { GraphQLContext };
package/dist/graphql.d.ts DELETED
@@ -1,13 +0,0 @@
1
- import { NitroGraphQLOptions } from "./types.js";
2
- import { NitroConfig } from "nitropack";
3
-
4
- //#region src/graphql.d.ts
5
- declare module 'nitropack' {
6
- interface NitroRuntimeHooks {}
7
- interface NitroRuntimeConfig {}
8
- }
9
- declare module 'nitropack/config' {
10
- function defineNitroConfig(config: NitroConfig & {
11
- graphql?: NitroGraphQLOptions;
12
- }): NitroConfig;
13
- }
@@ -1,7 +0,0 @@
1
- import * as graphql8 from "graphql";
2
- import * as graphql_yoga9 from "graphql-yoga";
3
-
4
- //#region src/internal/create-merged-schema.d.ts
5
- declare function createMergedSchema(): graphql_yoga9.GraphQLSchemaWithContext<graphql8.GraphQLResolveInfo & graphql_yoga9.YogaInitialContext>;
6
- //#endregion
7
- export { createMergedSchema };
@@ -1,23 +0,0 @@
1
- import { createSchema } from "graphql-yoga";
2
- import { mergeResolvers, mergeTypeDefs } from "@graphql-tools/merge";
3
- import { defs } from "#nitro-internal-virtual/server-defs";
4
- import { resolvers } from "#nitro-internal-virtual/server-resolvers";
5
-
6
- //#region src/internal/create-merged-schema.ts
7
- function createMergedSchema() {
8
- try {
9
- const mergedDefs = defs.map((schema) => schema.def).join("\n\n");
10
- const typeDefs = mergeTypeDefs([mergedDefs]);
11
- const mergedResolvers = mergeResolvers(resolvers.map((r) => r.resolver));
12
- return createSchema({
13
- typeDefs,
14
- resolvers: mergedResolvers
15
- });
16
- } catch (error) {
17
- console.error("Schema merge error:", error);
18
- throw error;
19
- }
20
- }
21
-
22
- //#endregion
23
- export { createMergedSchema };
@@ -1,2 +0,0 @@
1
- import { createMergedSchema } from "./create-merged-schema.js";
2
- export { createMergedSchema };
@@ -1,3 +0,0 @@
1
- import { createMergedSchema } from "./create-merged-schema.js";
2
-
3
- export { createMergedSchema };
@@ -1,6 +0,0 @@
1
- import * as h36 from "h3";
2
-
3
- //#region src/routes/graphql.d.ts
4
- declare const _default: h36.EventHandler<h36.EventHandlerRequest, Promise<void>>;
5
- //#endregion
6
- export { _default as default };
File without changes
File without changes