nitro-graphql 1.1.1 → 1.1.3
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.
- package/README.md +158 -0
- package/dist/ecosystem/nuxt.d.ts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +11 -3
- package/dist/rollup.js +24 -0
- package/dist/routes/apollo-server.js +11 -6
- package/dist/routes/graphql-yoga.js +9 -3
- package/dist/routes/health.d.ts +2 -2
- package/dist/types/index.d.ts +2 -1
- package/dist/utils/define.d.ts +52 -1
- package/dist/utils/define.js +33 -1
- package/dist/utils/directive-parser.d.ts +80 -0
- package/dist/utils/directive-parser.js +233 -0
- package/dist/utils/index.d.ts +3 -2
- package/dist/utils/index.js +29 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
- 🔄 **Hot Reload**: Development mode with automatic schema and resolver updates
|
|
31
31
|
- 📦 **Optimized Bundling**: Smart chunking and dynamic imports for production
|
|
32
32
|
- 🌐 **Nuxt Integration**: First-class Nuxt.js support with dedicated module
|
|
33
|
+
- 🎭 **Custom Directives**: Create reusable GraphQL directives with automatic schema generation
|
|
33
34
|
|
|
34
35
|
## 🚀 Quick Start
|
|
35
36
|
|
|
@@ -181,6 +182,10 @@ server/
|
|
|
181
182
|
├── graphql/
|
|
182
183
|
│ ├── schema.graphql # Main schema with scalars and base types
|
|
183
184
|
│ ├── hello.resolver.ts # Global resolvers (use named exports)
|
|
185
|
+
│ ├── directives/ # Custom GraphQL directives
|
|
186
|
+
│ │ ├── auth.directive.ts # Authentication directive
|
|
187
|
+
│ │ ├── cache.directive.ts # Caching directive
|
|
188
|
+
│ │ └── validate.directive.ts # Validation directive
|
|
184
189
|
│ ├── users/
|
|
185
190
|
│ │ ├── user.graphql # User schema definitions
|
|
186
191
|
│ │ ├── user-queries.resolver.ts # User query resolvers (use named exports)
|
|
@@ -615,6 +620,90 @@ export const postTypes = defineType({
|
|
|
615
620
|
|
|
616
621
|
</details>
|
|
617
622
|
|
|
623
|
+
<details>
|
|
624
|
+
<summary><strong>defineDirective</strong> - Create custom GraphQL directives</summary>
|
|
625
|
+
|
|
626
|
+
```ts
|
|
627
|
+
import { defineDirective } from 'nitro-graphql/utils/define'
|
|
628
|
+
import { getDirective, MapperKind, mapSchema } from '@graphql-tools/utils'
|
|
629
|
+
import { defaultFieldResolver, GraphQLError } from 'graphql'
|
|
630
|
+
|
|
631
|
+
export const authDirective = defineDirective({
|
|
632
|
+
name: 'auth',
|
|
633
|
+
locations: ['FIELD_DEFINITION', 'OBJECT'],
|
|
634
|
+
args: {
|
|
635
|
+
requires: {
|
|
636
|
+
type: 'String',
|
|
637
|
+
defaultValue: 'USER',
|
|
638
|
+
description: 'Required role to access this field',
|
|
639
|
+
},
|
|
640
|
+
},
|
|
641
|
+
description: 'Directive to check authentication and authorization',
|
|
642
|
+
transformer: (schema) => {
|
|
643
|
+
return mapSchema(schema, {
|
|
644
|
+
[MapperKind.OBJECT_FIELD]: (fieldConfig) => {
|
|
645
|
+
const authDirectiveConfig = getDirective(schema, fieldConfig, 'auth')?.[0]
|
|
646
|
+
|
|
647
|
+
if (authDirectiveConfig) {
|
|
648
|
+
const { resolve = defaultFieldResolver } = fieldConfig
|
|
649
|
+
|
|
650
|
+
fieldConfig.resolve = async function (source, args, context, info) {
|
|
651
|
+
if (!context.user) {
|
|
652
|
+
throw new GraphQLError('You must be logged in')
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
if (context.user.role !== authDirectiveConfig.requires) {
|
|
656
|
+
throw new GraphQLError('Insufficient permissions')
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
return resolve(source, args, context, info)
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
return fieldConfig
|
|
664
|
+
},
|
|
665
|
+
})
|
|
666
|
+
},
|
|
667
|
+
})
|
|
668
|
+
```
|
|
669
|
+
|
|
670
|
+
**Usage in Schema:**
|
|
671
|
+
```graphql
|
|
672
|
+
type User {
|
|
673
|
+
id: ID!
|
|
674
|
+
name: String!
|
|
675
|
+
email: String! @auth(requires: "ADMIN")
|
|
676
|
+
secretData: String @auth(requires: "SUPER_ADMIN")
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
type Query {
|
|
680
|
+
users: [User!]! @auth
|
|
681
|
+
adminStats: AdminStats @auth(requires: "ADMIN")
|
|
682
|
+
}
|
|
683
|
+
```
|
|
684
|
+
|
|
685
|
+
**Available Argument Types:**
|
|
686
|
+
- Basic scalars: `String`, `Int`, `Float`, `Boolean`, `ID`, `JSON`, `DateTime`
|
|
687
|
+
- Non-nullable: `String!`, `Int!`, `Float!`, `Boolean!`, `ID!`, `JSON!`, `DateTime!`
|
|
688
|
+
- Arrays: `[String]`, `[String!]`, `[String]!`, `[String!]!` (and all combinations for other types)
|
|
689
|
+
- Custom types: Any string for your custom GraphQL types
|
|
690
|
+
|
|
691
|
+
**Helper Function:**
|
|
692
|
+
```ts
|
|
693
|
+
export const validateDirective = defineDirective({
|
|
694
|
+
name: 'validate',
|
|
695
|
+
locations: ['FIELD_DEFINITION', 'ARGUMENT_DEFINITION'],
|
|
696
|
+
args: {
|
|
697
|
+
minLength: arg('Int', { description: 'Minimum length' }),
|
|
698
|
+
maxLength: arg('Int', { description: 'Maximum length' }),
|
|
699
|
+
pattern: arg('String', { description: 'Regex pattern' }),
|
|
700
|
+
},
|
|
701
|
+
// ... transformer implementation
|
|
702
|
+
})
|
|
703
|
+
```
|
|
704
|
+
|
|
705
|
+
</details>
|
|
706
|
+
|
|
618
707
|
<details>
|
|
619
708
|
<summary><strong>defineSchema</strong> - Define custom schema with validation</summary>
|
|
620
709
|
|
|
@@ -741,6 +830,75 @@ export default defineNitroConfig({
|
|
|
741
830
|
|
|
742
831
|
## 🔥 Advanced Features
|
|
743
832
|
|
|
833
|
+
<details>
|
|
834
|
+
<summary><strong>Custom Directives</strong></summary>
|
|
835
|
+
|
|
836
|
+
Create reusable GraphQL directives with automatic schema generation:
|
|
837
|
+
|
|
838
|
+
```ts
|
|
839
|
+
// server/graphql/directives/auth.directive.ts
|
|
840
|
+
import { defineDirective } from 'nitro-graphql/utils/define'
|
|
841
|
+
import { getDirective, MapperKind, mapSchema } from '@graphql-tools/utils'
|
|
842
|
+
|
|
843
|
+
export const authDirective = defineDirective({
|
|
844
|
+
name: 'auth',
|
|
845
|
+
locations: ['FIELD_DEFINITION', 'OBJECT'],
|
|
846
|
+
args: {
|
|
847
|
+
requires: {
|
|
848
|
+
type: 'String',
|
|
849
|
+
defaultValue: 'USER',
|
|
850
|
+
description: 'Required role to access this field',
|
|
851
|
+
},
|
|
852
|
+
},
|
|
853
|
+
description: 'Authentication and authorization directive',
|
|
854
|
+
transformer: (schema) => {
|
|
855
|
+
return mapSchema(schema, {
|
|
856
|
+
[MapperKind.OBJECT_FIELD]: (fieldConfig) => {
|
|
857
|
+
const authConfig = getDirective(schema, fieldConfig, 'auth')?.[0]
|
|
858
|
+
if (authConfig) {
|
|
859
|
+
// Transform field resolvers to check authentication
|
|
860
|
+
const { resolve = defaultFieldResolver } = fieldConfig
|
|
861
|
+
fieldConfig.resolve = async (source, args, context, info) => {
|
|
862
|
+
if (!context.user || context.user.role !== authConfig.requires) {
|
|
863
|
+
throw new GraphQLError('Access denied')
|
|
864
|
+
}
|
|
865
|
+
return resolve(source, args, context, info)
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
return fieldConfig
|
|
869
|
+
},
|
|
870
|
+
})
|
|
871
|
+
},
|
|
872
|
+
})
|
|
873
|
+
```
|
|
874
|
+
|
|
875
|
+
**Common Directive Examples:**
|
|
876
|
+
- `@auth(requires: "ADMIN")` - Role-based authentication
|
|
877
|
+
- `@cache(ttl: 300, scope: "PUBLIC")` - Field-level caching
|
|
878
|
+
- `@rateLimit(limit: 10, window: 60)` - Rate limiting
|
|
879
|
+
- `@validate(minLength: 5, maxLength: 100)` - Input validation
|
|
880
|
+
- `@transform(upper: true, trim: true)` - Data transformation
|
|
881
|
+
- `@permission(roles: ["ADMIN", "MODERATOR"])` - Multi-role permissions
|
|
882
|
+
|
|
883
|
+
**Usage in Schema:**
|
|
884
|
+
```graphql
|
|
885
|
+
type User {
|
|
886
|
+
id: ID!
|
|
887
|
+
name: String!
|
|
888
|
+
email: String! @auth(requires: "ADMIN")
|
|
889
|
+
posts: [Post!]! @cache(ttl: 300)
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
type Query {
|
|
893
|
+
users: [User!]! @rateLimit(limit: 100, window: 3600)
|
|
894
|
+
sensitiveData: String @auth(requires: "SUPER_ADMIN")
|
|
895
|
+
}
|
|
896
|
+
```
|
|
897
|
+
|
|
898
|
+
The module automatically generates the directive schema definitions and integrates them with both GraphQL Yoga and Apollo Server.
|
|
899
|
+
|
|
900
|
+
</details>
|
|
901
|
+
|
|
744
902
|
<details>
|
|
745
903
|
<summary><strong>Custom Scalars</strong></summary>
|
|
746
904
|
|
package/dist/ecosystem/nuxt.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as _nuxt_schema0 from "@nuxt/schema";
|
|
2
2
|
|
|
3
3
|
//#region src/ecosystem/nuxt.d.ts
|
|
4
4
|
interface ModuleOptions {}
|
|
5
|
-
declare const _default:
|
|
5
|
+
declare const _default: _nuxt_schema0.NuxtModule<ModuleOptions, ModuleOptions, false>;
|
|
6
6
|
//#endregion
|
|
7
7
|
export { ModuleOptions, _default as default };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { StandardSchemaV1 } from "./types/standard-schema.js";
|
|
2
2
|
import { CodegenClientConfig, CodegenServerConfig, GenImport, GenericSdkConfig, NitroGraphQLOptions } from "./types/index.js";
|
|
3
|
-
import * as
|
|
3
|
+
import * as nitropack1 from "nitropack";
|
|
4
4
|
|
|
5
5
|
//#region src/index.d.ts
|
|
6
|
-
declare const _default:
|
|
6
|
+
declare const _default: nitropack1.NitroModule;
|
|
7
7
|
//#endregion
|
|
8
8
|
export { CodegenClientConfig, CodegenServerConfig, GenImport, GenericSdkConfig, NitroGraphQLOptions, StandardSchemaV1, _default as default };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { generateDirectiveSchemas } from "./utils/directive-parser.js";
|
|
2
|
+
import { relativeWithDot, scanDirectives, scanDocs, scanResolvers, scanSchemas } from "./utils/index.js";
|
|
2
3
|
import { clientTypeGeneration, serverTypeGeneration } from "./utils/type-generation.js";
|
|
3
4
|
import { rollupConfig } from "./rollup.js";
|
|
4
5
|
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
@@ -62,7 +63,7 @@ var src_default = defineNitroModule({
|
|
|
62
63
|
const watcher = watch(watchDirs, {
|
|
63
64
|
persistent: true,
|
|
64
65
|
ignoreInitial: true,
|
|
65
|
-
ignored: nitro.options.ignore
|
|
66
|
+
ignored: [...nitro.options.ignore, "**/server/graphql/_directives.graphql"]
|
|
66
67
|
}).on("all", async (event, path) => {
|
|
67
68
|
if (path.endsWith(".graphql") || path.endsWith(".gql")) await clientTypeGeneration(nitro);
|
|
68
69
|
});
|
|
@@ -78,11 +79,17 @@ var src_default = defineNitroModule({
|
|
|
78
79
|
nitro.scanDocuments = docs;
|
|
79
80
|
const resolvers = await scanResolvers(nitro);
|
|
80
81
|
nitro.scanResolvers = resolvers;
|
|
82
|
+
const directives = await scanDirectives(nitro);
|
|
83
|
+
nitro.scanDirectives = directives;
|
|
84
|
+
await generateDirectiveSchemas(nitro, directives);
|
|
81
85
|
nitro.hooks.hook("dev:start", async () => {
|
|
82
86
|
const schemas$1 = await scanSchemas(nitro);
|
|
83
87
|
nitro.scanSchemas = schemas$1;
|
|
84
88
|
const resolvers$1 = await scanResolvers(nitro);
|
|
85
89
|
nitro.scanResolvers = resolvers$1;
|
|
90
|
+
const directives$1 = await scanDirectives(nitro);
|
|
91
|
+
nitro.scanDirectives = directives$1;
|
|
92
|
+
await generateDirectiveSchemas(nitro, directives$1);
|
|
86
93
|
const docs$1 = await scanDocs(nitro);
|
|
87
94
|
nitro.scanDocuments = docs$1;
|
|
88
95
|
});
|
|
@@ -125,7 +132,8 @@ var src_default = defineNitroModule({
|
|
|
125
132
|
"defineSubscription",
|
|
126
133
|
"defineType",
|
|
127
134
|
"defineGraphQLConfig",
|
|
128
|
-
"defineSchema"
|
|
135
|
+
"defineSchema",
|
|
136
|
+
"defineDirective"
|
|
129
137
|
]
|
|
130
138
|
});
|
|
131
139
|
}
|
package/dist/rollup.js
CHANGED
|
@@ -9,6 +9,7 @@ import { genImport } from "knitwork";
|
|
|
9
9
|
async function rollupConfig(app) {
|
|
10
10
|
virtualSchemas(app);
|
|
11
11
|
virtualResolvers(app);
|
|
12
|
+
virtualDirectives(app);
|
|
12
13
|
getGraphQLConfig(app);
|
|
13
14
|
app.hooks.hook("rollup:before", (nitro, rollupConfig$1) => {
|
|
14
15
|
rollupConfig$1.plugins = rollupConfig$1.plugins || [];
|
|
@@ -85,6 +86,29 @@ function virtualResolvers(app) {
|
|
|
85
86
|
return code;
|
|
86
87
|
};
|
|
87
88
|
}
|
|
89
|
+
function virtualDirectives(app) {
|
|
90
|
+
const getDirectives = () => {
|
|
91
|
+
const directives = [...app.scanDirectives || []];
|
|
92
|
+
return directives;
|
|
93
|
+
};
|
|
94
|
+
app.options.virtual ??= {};
|
|
95
|
+
app.options.virtual["#nitro-internal-virtual/server-directives"] = () => {
|
|
96
|
+
const imports = getDirectives();
|
|
97
|
+
const importsContent = [...imports.map(({ specifier, imports: imports$1, options }) => {
|
|
98
|
+
return genImport(specifier, imports$1, options);
|
|
99
|
+
})];
|
|
100
|
+
const data = imports.map(({ imports: imports$1 }) => imports$1.map((i) => `{ directive: ${i.as} }`).join(",\n")).filter(Boolean).join(",\n");
|
|
101
|
+
const content = [
|
|
102
|
+
"export const directives = [",
|
|
103
|
+
data,
|
|
104
|
+
"]",
|
|
105
|
+
""
|
|
106
|
+
];
|
|
107
|
+
content.unshift(...importsContent);
|
|
108
|
+
const code = content.join("\n");
|
|
109
|
+
return code;
|
|
110
|
+
};
|
|
111
|
+
}
|
|
88
112
|
function getGraphQLConfig(app) {
|
|
89
113
|
const configPath = resolve(app.graphql.serverDir, "config.ts");
|
|
90
114
|
app.options.virtual ??= {};
|
|
@@ -2,21 +2,27 @@ import { startServerAndCreateH3Handler } from "../utils/apollo.js";
|
|
|
2
2
|
import defu from "defu";
|
|
3
3
|
import { mergeResolvers, mergeTypeDefs } from "@graphql-tools/merge";
|
|
4
4
|
import { importedConfig } from "#nitro-internal-virtual/graphql-config";
|
|
5
|
+
import { directives } from "#nitro-internal-virtual/server-directives";
|
|
5
6
|
import { resolvers } from "#nitro-internal-virtual/server-resolvers";
|
|
6
7
|
import { schemas } from "#nitro-internal-virtual/server-schemas";
|
|
7
8
|
import { ApolloServer } from "@apollo/server";
|
|
8
9
|
import { ApolloServerPluginLandingPageLocalDefault } from "@apollo/server/plugin/landingPage/default";
|
|
10
|
+
import { makeExecutableSchema } from "@graphql-tools/schema";
|
|
9
11
|
|
|
10
12
|
//#region src/routes/apollo-server.ts
|
|
11
13
|
function createMergedSchema() {
|
|
12
14
|
try {
|
|
13
|
-
const mergedSchemas = schemas.map((schema) => schema.def).join("\n\n");
|
|
15
|
+
const mergedSchemas = schemas.map((schema$1) => schema$1.def).join("\n\n");
|
|
14
16
|
const typeDefs = mergeTypeDefs([mergedSchemas]);
|
|
15
17
|
const mergedResolvers = mergeResolvers(resolvers.map((r) => r.resolver));
|
|
16
|
-
|
|
18
|
+
let schema = makeExecutableSchema({
|
|
17
19
|
typeDefs,
|
|
18
20
|
resolvers: mergedResolvers
|
|
19
|
-
};
|
|
21
|
+
});
|
|
22
|
+
if (directives && directives.length > 0) {
|
|
23
|
+
for (const { directive } of directives) if (directive.transformer) schema = directive.transformer(schema);
|
|
24
|
+
}
|
|
25
|
+
return schema;
|
|
20
26
|
} catch (error) {
|
|
21
27
|
console.error("Schema merge error:", error);
|
|
22
28
|
throw error;
|
|
@@ -25,10 +31,9 @@ function createMergedSchema() {
|
|
|
25
31
|
let apolloServer = null;
|
|
26
32
|
function createApolloServer() {
|
|
27
33
|
if (!apolloServer) {
|
|
28
|
-
const
|
|
34
|
+
const schema = createMergedSchema();
|
|
29
35
|
apolloServer = new ApolloServer(defu({
|
|
30
|
-
|
|
31
|
-
resolvers: mergedResolvers,
|
|
36
|
+
schema,
|
|
32
37
|
introspection: true,
|
|
33
38
|
plugins: [ApolloServerPluginLandingPageLocalDefault({ embed: true })]
|
|
34
39
|
}, importedConfig));
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import defu from "defu";
|
|
2
2
|
import { mergeResolvers, mergeTypeDefs } from "@graphql-tools/merge";
|
|
3
3
|
import { importedConfig } from "#nitro-internal-virtual/graphql-config";
|
|
4
|
+
import { directives } from "#nitro-internal-virtual/server-directives";
|
|
4
5
|
import { resolvers } from "#nitro-internal-virtual/server-resolvers";
|
|
5
6
|
import { schemas } from "#nitro-internal-virtual/server-schemas";
|
|
7
|
+
import { makeExecutableSchema } from "@graphql-tools/schema";
|
|
6
8
|
import { defineEventHandler, toWebRequest } from "h3";
|
|
7
|
-
import {
|
|
9
|
+
import { createYoga } from "graphql-yoga";
|
|
8
10
|
|
|
9
11
|
//#region src/routes/graphql-yoga.ts
|
|
10
12
|
const apolloSandboxHtml = `<!DOCTYPE html>
|
|
@@ -26,13 +28,17 @@ new window.EmbeddedSandbox({
|
|
|
26
28
|
</html>`;
|
|
27
29
|
function createMergedSchema() {
|
|
28
30
|
try {
|
|
29
|
-
const mergedSchemas = schemas.map((schema) => schema.def).join("\n\n");
|
|
31
|
+
const mergedSchemas = schemas.map((schema$1) => schema$1.def).join("\n\n");
|
|
30
32
|
const typeDefs = mergeTypeDefs([mergedSchemas]);
|
|
31
33
|
const mergedResolvers = mergeResolvers(resolvers.map((r) => r.resolver));
|
|
32
|
-
|
|
34
|
+
let schema = makeExecutableSchema({
|
|
33
35
|
typeDefs,
|
|
34
36
|
resolvers: mergedResolvers
|
|
35
37
|
});
|
|
38
|
+
if (directives && directives.length > 0) {
|
|
39
|
+
for (const { directive } of directives) if (directive.transformer) schema = directive.transformer(schema);
|
|
40
|
+
}
|
|
41
|
+
return schema;
|
|
36
42
|
} catch (error) {
|
|
37
43
|
console.error("Schema merge error:", error);
|
|
38
44
|
throw error;
|
package/dist/routes/health.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as h32 from "h3";
|
|
2
2
|
|
|
3
3
|
//#region src/routes/health.d.ts
|
|
4
|
-
declare const _default:
|
|
4
|
+
declare const _default: h32.EventHandler<h32.EventHandlerRequest, Promise<{
|
|
5
5
|
status: string;
|
|
6
6
|
message: string;
|
|
7
7
|
timestamp: string;
|
package/dist/types/index.d.ts
CHANGED
|
@@ -20,7 +20,7 @@ type CodegenClientConfig = TypeScriptPluginConfig & TypeScriptDocumentsPluginCon
|
|
|
20
20
|
interface IESMImport {
|
|
21
21
|
name: string;
|
|
22
22
|
as?: string;
|
|
23
|
-
type: 'resolver' | 'query' | 'mutation' | 'type' | 'subscription';
|
|
23
|
+
type: 'resolver' | 'query' | 'mutation' | 'type' | 'subscription' | 'directive';
|
|
24
24
|
}
|
|
25
25
|
interface GenImport {
|
|
26
26
|
specifier: string;
|
|
@@ -32,6 +32,7 @@ declare module 'nitropack/types' {
|
|
|
32
32
|
scanSchemas: string[];
|
|
33
33
|
scanDocuments: string[];
|
|
34
34
|
scanResolvers: GenImport[];
|
|
35
|
+
scanDirectives: GenImport[];
|
|
35
36
|
graphql: {
|
|
36
37
|
buildDir: string;
|
|
37
38
|
watchDirs: string[];
|
package/dist/utils/define.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { GraphQLSchema } from "graphql";
|
|
1
2
|
import { ApolloServerOptions } from "@apollo/server";
|
|
2
3
|
import { H3Event } from "h3";
|
|
3
4
|
import { YogaServerOptions } from "graphql-yoga";
|
|
@@ -17,5 +18,55 @@ declare function defineSubscription(resolvers?: Resolvers['Subscription']): Reso
|
|
|
17
18
|
declare function defineType(resolvers: Resolvers): Resolvers;
|
|
18
19
|
type DefineServerConfig<T extends NPMConfig = NPMConfig> = T['framework'] extends 'graphql-yoga' ? Partial<YogaServerOptions<H3Event, Partial<H3Event>>> : T['framework'] extends 'apollo-server' ? Partial<ApolloServerOptions<H3Event>> : Partial<YogaServerOptions<H3Event, Partial<H3Event>>> | Partial<ApolloServerOptions<H3Event>>;
|
|
19
20
|
declare function defineGraphQLConfig<T extends NPMConfig = NPMConfig>(config: Partial<DefineServerConfig<T>>): Partial<DefineServerConfig<T>>;
|
|
21
|
+
type DirectiveLocationName = 'QUERY' | 'MUTATION' | 'SUBSCRIPTION' | 'FIELD' | 'FRAGMENT_DEFINITION' | 'FRAGMENT_SPREAD' | 'INLINE_FRAGMENT' | 'VARIABLE_DEFINITION' | 'SCHEMA' | 'SCALAR' | 'OBJECT' | 'FIELD_DEFINITION' | 'ARGUMENT_DEFINITION' | 'INTERFACE' | 'UNION' | 'ENUM' | 'ENUM_VALUE' | 'INPUT_OBJECT' | 'INPUT_FIELD_DEFINITION';
|
|
22
|
+
type GraphQLScalarType = 'String' | 'Int' | 'Float' | 'Boolean' | 'ID' | 'JSON' | 'DateTime';
|
|
23
|
+
type GraphQLBaseType = GraphQLScalarType | (string & {});
|
|
24
|
+
type GraphQLArgumentType = 'String' | 'Int' | 'Float' | 'Boolean' | 'ID' | 'JSON' | 'DateTime' | 'String!' | 'Int!' | 'Float!' | 'Boolean!' | 'ID!' | 'JSON!' | 'DateTime!' | '[String]' | '[String!]' | '[String]!' | '[String!]!' | '[Int]' | '[Int!]' | '[Int]!' | '[Int!]!' | '[Float]' | '[Float!]' | '[Float]!' | '[Float!]!' | '[Boolean]' | '[Boolean!]' | '[Boolean]!' | '[Boolean!]!' | '[ID]' | '[ID!]' | '[ID]!' | '[ID!]!' | '[JSON]' | '[JSON!]' | '[JSON]!' | '[JSON!]!' | '[DateTime]' | '[DateTime!]' | '[DateTime]!' | '[DateTime!]!' | (string & {});
|
|
25
|
+
interface DirectiveArgument<T extends GraphQLArgumentType = GraphQLArgumentType> {
|
|
26
|
+
/**
|
|
27
|
+
* GraphQL type for the argument
|
|
28
|
+
* @example 'String', 'Int!', '[String!]!', 'DateTime', 'JSON'
|
|
29
|
+
*/
|
|
30
|
+
type: T;
|
|
31
|
+
defaultValue?: any;
|
|
32
|
+
description?: string;
|
|
33
|
+
}
|
|
34
|
+
interface DirectiveArg {
|
|
35
|
+
type: GraphQLArgumentType;
|
|
36
|
+
defaultValue?: any;
|
|
37
|
+
description?: string;
|
|
38
|
+
}
|
|
39
|
+
interface DirectiveDefinition {
|
|
40
|
+
name: string;
|
|
41
|
+
locations: DirectiveLocationName[];
|
|
42
|
+
args?: Record<string, DirectiveArg>;
|
|
43
|
+
description?: string;
|
|
44
|
+
isRepeatable?: boolean;
|
|
45
|
+
transformer?: (schema: GraphQLSchema) => GraphQLSchema;
|
|
46
|
+
}
|
|
47
|
+
interface DefineDirectiveConfig {
|
|
48
|
+
name: string;
|
|
49
|
+
locations: ReadonlyArray<DirectiveLocationName>;
|
|
50
|
+
args?: Record<string, {
|
|
51
|
+
type: GraphQLArgumentType;
|
|
52
|
+
defaultValue?: any;
|
|
53
|
+
description?: string;
|
|
54
|
+
}>;
|
|
55
|
+
description?: string;
|
|
56
|
+
isRepeatable?: boolean;
|
|
57
|
+
transformer?: (schema: GraphQLSchema) => GraphQLSchema;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Helper function to create directive arguments with proper type inference
|
|
61
|
+
* @example
|
|
62
|
+
* args: {
|
|
63
|
+
* myArg: arg('String!', { defaultValue: 'hello' })
|
|
64
|
+
* }
|
|
65
|
+
*/
|
|
66
|
+
declare function arg<T extends GraphQLArgumentType>(type: T, options?: {
|
|
67
|
+
defaultValue?: any;
|
|
68
|
+
description?: string;
|
|
69
|
+
}): DirectiveArgument<T>;
|
|
70
|
+
declare function defineDirective(config: DefineDirectiveConfig): DirectiveDefinition;
|
|
20
71
|
//#endregion
|
|
21
|
-
export { DefineServerConfig, ResolverQuery, defineGraphQLConfig, defineMutation, defineQuery, defineResolver, defineSchema, defineSubscription, defineType };
|
|
72
|
+
export { DefineDirectiveConfig, DefineServerConfig, DirectiveArgument, DirectiveDefinition, GraphQLArgumentType, GraphQLBaseType, GraphQLScalarType, ResolverQuery, arg, defineDirective, defineGraphQLConfig, defineMutation, defineQuery, defineResolver, defineSchema, defineSubscription, defineType };
|
package/dist/utils/define.js
CHANGED
|
@@ -20,6 +20,38 @@ function defineType(resolvers) {
|
|
|
20
20
|
function defineGraphQLConfig(config) {
|
|
21
21
|
return config;
|
|
22
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
|
+
}
|
|
23
55
|
|
|
24
56
|
//#endregion
|
|
25
|
-
export { defineGraphQLConfig, defineMutation, defineQuery, defineResolver, defineSchema, defineSubscription, defineType };
|
|
57
|
+
export { arg, defineDirective, defineGraphQLConfig, defineMutation, defineQuery, defineResolver, defineSchema, defineSubscription, defineType };
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
//#region src/utils/directive-parser.d.ts
|
|
2
|
+
interface ParsedDirective {
|
|
3
|
+
name: string;
|
|
4
|
+
locations: string[];
|
|
5
|
+
args?: Record<string, {
|
|
6
|
+
type: string;
|
|
7
|
+
defaultValue?: any;
|
|
8
|
+
}>;
|
|
9
|
+
description?: string;
|
|
10
|
+
isRepeatable?: boolean;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Clean AST-based directive parser using oxc-parser
|
|
14
|
+
*/
|
|
15
|
+
declare class DirectiveParser {
|
|
16
|
+
private oxc;
|
|
17
|
+
init(): Promise<void>;
|
|
18
|
+
/**
|
|
19
|
+
* Parse directives from a TypeScript/JavaScript file
|
|
20
|
+
*/
|
|
21
|
+
parseDirectives(fileContent: string, filePath: string): Promise<ParsedDirective[]>;
|
|
22
|
+
/**
|
|
23
|
+
* Extract directive definitions from AST
|
|
24
|
+
*/
|
|
25
|
+
private extractDirectiveDefinitions;
|
|
26
|
+
/**
|
|
27
|
+
* Traverse AST nodes recursively
|
|
28
|
+
*/
|
|
29
|
+
private traverse;
|
|
30
|
+
/**
|
|
31
|
+
* Check if node is a defineDirective call
|
|
32
|
+
*/
|
|
33
|
+
private isDefineDirectiveCall;
|
|
34
|
+
/**
|
|
35
|
+
* Extract directive configuration from defineDirective call
|
|
36
|
+
*/
|
|
37
|
+
private extractDirectiveFromCall;
|
|
38
|
+
/**
|
|
39
|
+
* Extract directive properties from object expression
|
|
40
|
+
*/
|
|
41
|
+
private extractDirectiveFromObject;
|
|
42
|
+
/**
|
|
43
|
+
* Extract string literal value
|
|
44
|
+
*/
|
|
45
|
+
private extractStringLiteral;
|
|
46
|
+
/**
|
|
47
|
+
* Extract boolean literal value
|
|
48
|
+
*/
|
|
49
|
+
private extractBooleanLiteral;
|
|
50
|
+
/**
|
|
51
|
+
* Extract array of strings
|
|
52
|
+
*/
|
|
53
|
+
private extractStringArray;
|
|
54
|
+
/**
|
|
55
|
+
* Extract arguments object
|
|
56
|
+
*/
|
|
57
|
+
private extractArgsObject;
|
|
58
|
+
/**
|
|
59
|
+
* Extract argument configuration
|
|
60
|
+
*/
|
|
61
|
+
private extractArgConfig;
|
|
62
|
+
/**
|
|
63
|
+
* Extract literal value (string, number, boolean)
|
|
64
|
+
*/
|
|
65
|
+
private extractLiteralValue;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Generate GraphQL directive schema from parsed directive
|
|
69
|
+
*/
|
|
70
|
+
declare function generateDirectiveSchema(directive: ParsedDirective): string;
|
|
71
|
+
/**
|
|
72
|
+
* Generate directive schemas file from scanned directives
|
|
73
|
+
*/
|
|
74
|
+
declare function generateDirectiveSchemas(nitro: any, directives: any[]): Promise<void>;
|
|
75
|
+
/**
|
|
76
|
+
* Singleton instance for reuse
|
|
77
|
+
*/
|
|
78
|
+
declare const directiveParser: DirectiveParser;
|
|
79
|
+
//#endregion
|
|
80
|
+
export { DirectiveParser, ParsedDirective, directiveParser, generateDirectiveSchema, generateDirectiveSchemas };
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
//#region src/utils/directive-parser.ts
|
|
2
|
+
/**
|
|
3
|
+
* Clean AST-based directive parser using oxc-parser
|
|
4
|
+
*/
|
|
5
|
+
var DirectiveParser = class {
|
|
6
|
+
oxc;
|
|
7
|
+
async init() {
|
|
8
|
+
if (!this.oxc) this.oxc = await import("oxc-parser");
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Parse directives from a TypeScript/JavaScript file
|
|
12
|
+
*/
|
|
13
|
+
async parseDirectives(fileContent, filePath) {
|
|
14
|
+
await this.init();
|
|
15
|
+
try {
|
|
16
|
+
const result = this.oxc.parseSync(filePath, fileContent, {
|
|
17
|
+
lang: filePath.endsWith(".ts") ? "ts" : "js",
|
|
18
|
+
sourceType: "module",
|
|
19
|
+
astType: "ts"
|
|
20
|
+
});
|
|
21
|
+
if (result.errors.length > 0) {
|
|
22
|
+
console.warn(`Parse errors in ${filePath}:`, result.errors.map((e) => e.message));
|
|
23
|
+
return [];
|
|
24
|
+
}
|
|
25
|
+
return this.extractDirectiveDefinitions(result.program);
|
|
26
|
+
} catch (error) {
|
|
27
|
+
console.warn(`Failed to parse ${filePath} with oxc:`, error);
|
|
28
|
+
return [];
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Extract directive definitions from AST
|
|
33
|
+
*/
|
|
34
|
+
extractDirectiveDefinitions(program) {
|
|
35
|
+
const directives = [];
|
|
36
|
+
this.traverse(program, (node) => {
|
|
37
|
+
if (this.isDefineDirectiveCall(node)) {
|
|
38
|
+
const directive = this.extractDirectiveFromCall(node);
|
|
39
|
+
if (directive) directives.push(directive);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
return directives;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Traverse AST nodes recursively
|
|
46
|
+
*/
|
|
47
|
+
traverse(node, visitor) {
|
|
48
|
+
if (!node || typeof node !== "object") return;
|
|
49
|
+
visitor(node);
|
|
50
|
+
for (const key in node) {
|
|
51
|
+
const child = node[key];
|
|
52
|
+
if (Array.isArray(child)) child.forEach((item) => this.traverse(item, visitor));
|
|
53
|
+
else if (child && typeof child === "object") this.traverse(child, visitor);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Check if node is a defineDirective call
|
|
58
|
+
*/
|
|
59
|
+
isDefineDirectiveCall(node) {
|
|
60
|
+
return node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "defineDirective" && node.arguments?.length > 0;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Extract directive configuration from defineDirective call
|
|
64
|
+
*/
|
|
65
|
+
extractDirectiveFromCall(node) {
|
|
66
|
+
const arg = node.arguments[0];
|
|
67
|
+
if (arg?.type !== "ObjectExpression") return null;
|
|
68
|
+
return this.extractDirectiveFromObject(arg);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Extract directive properties from object expression
|
|
72
|
+
*/
|
|
73
|
+
extractDirectiveFromObject(objNode) {
|
|
74
|
+
let name = "";
|
|
75
|
+
let locations = [];
|
|
76
|
+
let args = {};
|
|
77
|
+
let description;
|
|
78
|
+
let isRepeatable;
|
|
79
|
+
for (const prop of objNode.properties || []) {
|
|
80
|
+
if (prop.type !== "Property" || prop.key?.type !== "Identifier") continue;
|
|
81
|
+
switch (prop.key.name) {
|
|
82
|
+
case "name":
|
|
83
|
+
name = this.extractStringLiteral(prop.value) || "";
|
|
84
|
+
break;
|
|
85
|
+
case "locations":
|
|
86
|
+
locations = this.extractStringArray(prop.value);
|
|
87
|
+
break;
|
|
88
|
+
case "args":
|
|
89
|
+
args = this.extractArgsObject(prop.value);
|
|
90
|
+
break;
|
|
91
|
+
case "description":
|
|
92
|
+
description = this.extractStringLiteral(prop.value);
|
|
93
|
+
break;
|
|
94
|
+
case "isRepeatable":
|
|
95
|
+
isRepeatable = this.extractBooleanLiteral(prop.value);
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return name && locations.length > 0 ? {
|
|
100
|
+
name,
|
|
101
|
+
locations,
|
|
102
|
+
args,
|
|
103
|
+
description,
|
|
104
|
+
isRepeatable
|
|
105
|
+
} : null;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Extract string literal value
|
|
109
|
+
*/
|
|
110
|
+
extractStringLiteral(node) {
|
|
111
|
+
if (node?.type === "Literal" && typeof node.value === "string") return node.value;
|
|
112
|
+
return void 0;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Extract boolean literal value
|
|
116
|
+
*/
|
|
117
|
+
extractBooleanLiteral(node) {
|
|
118
|
+
if (node?.type === "Literal" && typeof node.value === "boolean") return node.value;
|
|
119
|
+
return void 0;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Extract array of strings
|
|
123
|
+
*/
|
|
124
|
+
extractStringArray(node) {
|
|
125
|
+
if (node?.type !== "ArrayExpression") return [];
|
|
126
|
+
return (node.elements || []).filter((el) => el?.type === "Literal" && typeof el.value === "string").map((el) => el.value);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Extract arguments object
|
|
130
|
+
*/
|
|
131
|
+
extractArgsObject(node) {
|
|
132
|
+
if (node?.type !== "ObjectExpression") return {};
|
|
133
|
+
const args = {};
|
|
134
|
+
for (const prop of node.properties || []) {
|
|
135
|
+
if (prop.type !== "Property" || prop.key?.type !== "Identifier") continue;
|
|
136
|
+
const argName = prop.key.name;
|
|
137
|
+
const argConfig = this.extractArgConfig(prop.value);
|
|
138
|
+
if (argConfig) args[argName] = argConfig;
|
|
139
|
+
}
|
|
140
|
+
return args;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Extract argument configuration
|
|
144
|
+
*/
|
|
145
|
+
extractArgConfig(node) {
|
|
146
|
+
if (node?.type !== "ObjectExpression") return null;
|
|
147
|
+
let type = "String";
|
|
148
|
+
let defaultValue;
|
|
149
|
+
for (const prop of node.properties || []) {
|
|
150
|
+
if (prop.type !== "Property" || prop.key?.type !== "Identifier") continue;
|
|
151
|
+
switch (prop.key.name) {
|
|
152
|
+
case "type":
|
|
153
|
+
const typeValue = this.extractStringLiteral(prop.value);
|
|
154
|
+
if (typeValue) type = typeValue;
|
|
155
|
+
break;
|
|
156
|
+
case "defaultValue":
|
|
157
|
+
defaultValue = this.extractLiteralValue(prop.value);
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
type,
|
|
163
|
+
...defaultValue !== void 0 && { defaultValue }
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Extract literal value (string, number, boolean)
|
|
168
|
+
*/
|
|
169
|
+
extractLiteralValue(node) {
|
|
170
|
+
if (node?.type === "Literal") return node.value;
|
|
171
|
+
return void 0;
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
/**
|
|
175
|
+
* Generate GraphQL directive schema from parsed directive
|
|
176
|
+
*/
|
|
177
|
+
function generateDirectiveSchema(directive) {
|
|
178
|
+
let args = "";
|
|
179
|
+
if (directive.args && Object.keys(directive.args).length > 0) {
|
|
180
|
+
const argDefs = Object.entries(directive.args).map(([name, arg]) => {
|
|
181
|
+
let defaultValue = "";
|
|
182
|
+
if (arg.defaultValue !== void 0) if (typeof arg.defaultValue === "string") defaultValue = ` = "${arg.defaultValue}"`;
|
|
183
|
+
else defaultValue = ` = ${arg.defaultValue}`;
|
|
184
|
+
return `${name}: ${arg.type}${defaultValue}`;
|
|
185
|
+
});
|
|
186
|
+
args = `(${argDefs.join(", ")})`;
|
|
187
|
+
}
|
|
188
|
+
const locations = directive.locations.join(" | ");
|
|
189
|
+
return `directive @${directive.name}${args} on ${locations}`;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Generate directive schemas file from scanned directives
|
|
193
|
+
*/
|
|
194
|
+
async function generateDirectiveSchemas(nitro, directives) {
|
|
195
|
+
if (directives.length === 0) return;
|
|
196
|
+
const { existsSync, readFileSync, writeFileSync } = await import("node:fs");
|
|
197
|
+
const { readFile } = await import("node:fs/promises");
|
|
198
|
+
const { resolve } = await import("pathe");
|
|
199
|
+
const directiveSchemas = [];
|
|
200
|
+
const seenDirectives = /* @__PURE__ */ new Set();
|
|
201
|
+
for (const dir of directives) for (const _imp of dir.imports) {
|
|
202
|
+
const fileContent = await readFile(dir.specifier, "utf-8");
|
|
203
|
+
const directiveDefs = await directiveParser.parseDirectives(fileContent, dir.specifier);
|
|
204
|
+
for (const def of directiveDefs) {
|
|
205
|
+
if (seenDirectives.has(def.name)) continue;
|
|
206
|
+
seenDirectives.add(def.name);
|
|
207
|
+
const schema = generateDirectiveSchema(def);
|
|
208
|
+
directiveSchemas.push(schema);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
if (directiveSchemas.length > 0) {
|
|
212
|
+
const directivesPath = resolve(nitro.graphql.serverDir, "_directives.graphql");
|
|
213
|
+
const content = `# WARNING: This file is auto-generated by nitro-graphql
|
|
214
|
+
# Do not modify this file directly. It will be overwritten.
|
|
215
|
+
# To define custom directives, create .directive.ts files using defineDirective()
|
|
216
|
+
|
|
217
|
+
${directiveSchemas.join("\n\n")}`;
|
|
218
|
+
let shouldWrite = true;
|
|
219
|
+
if (existsSync(directivesPath)) {
|
|
220
|
+
const existingContent = readFileSync(directivesPath, "utf-8");
|
|
221
|
+
shouldWrite = existingContent !== content;
|
|
222
|
+
}
|
|
223
|
+
if (shouldWrite) writeFileSync(directivesPath, content, "utf-8");
|
|
224
|
+
if (!nitro.scanSchemas.includes(directivesPath)) nitro.scanSchemas.push(directivesPath);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Singleton instance for reuse
|
|
229
|
+
*/
|
|
230
|
+
const directiveParser = new DirectiveParser();
|
|
231
|
+
|
|
232
|
+
//#endregion
|
|
233
|
+
export { DirectiveParser, directiveParser, generateDirectiveSchema, generateDirectiveSchemas };
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { GenImport } from "../types/index.js";
|
|
2
|
+
import { directiveParser, generateDirectiveSchema, generateDirectiveSchemas } from "./directive-parser.js";
|
|
2
3
|
import { Nitro } from "nitropack";
|
|
3
4
|
|
|
4
5
|
//#region src/utils/index.d.ts
|
|
@@ -7,9 +8,9 @@ declare function getImportId(p: string, lazy?: boolean): string;
|
|
|
7
8
|
declare function relativeWithDot(from: string, to: string): string;
|
|
8
9
|
declare function scanGraphql(nitro: Nitro): Promise<string[]>;
|
|
9
10
|
declare function scanResolvers(nitro: Nitro): Promise<GenImport[]>;
|
|
10
|
-
declare function scanDirectives(nitro: Nitro): Promise<
|
|
11
|
+
declare function scanDirectives(nitro: Nitro): Promise<GenImport[]>;
|
|
11
12
|
declare function scanTypeDefs(nitro: Nitro): Promise<string[]>;
|
|
12
13
|
declare function scanSchemas(nitro: Nitro): Promise<string[]>;
|
|
13
14
|
declare function scanDocs(nitro: Nitro): Promise<string[]>;
|
|
14
15
|
//#endregion
|
|
15
|
-
export { GLOB_SCAN_PATTERN, getImportId, relativeWithDot, scanDirectives, scanDocs, scanGraphql, scanResolvers, scanSchemas, scanTypeDefs };
|
|
16
|
+
export { GLOB_SCAN_PATTERN, directiveParser, generateDirectiveSchema, generateDirectiveSchemas, getImportId, relativeWithDot, scanDirectives, scanDocs, scanGraphql, scanResolvers, scanSchemas, scanTypeDefs };
|
package/dist/utils/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { directiveParser, generateDirectiveSchema, generateDirectiveSchemas } from "./directive-parser.js";
|
|
1
2
|
import { join, relative } from "pathe";
|
|
2
3
|
import { readFile } from "node:fs/promises";
|
|
3
4
|
import { hash } from "ohash";
|
|
@@ -56,6 +57,11 @@ async function scanResolvers(nitro) {
|
|
|
56
57
|
type: "subscription",
|
|
57
58
|
as: `_${hash(decl.id.name + file.path).replace(/-/g, "").slice(0, 6)}`
|
|
58
59
|
});
|
|
60
|
+
if (decl.init.callee.type === "Identifier" && decl.init.callee.name === "defineDirective") exports.imports.push({
|
|
61
|
+
name: decl.id.name,
|
|
62
|
+
type: "directive",
|
|
63
|
+
as: `_${hash(decl.id.name + file.path).replace(/-/g, "").slice(0, 6)}`
|
|
64
|
+
});
|
|
59
65
|
}
|
|
60
66
|
}
|
|
61
67
|
}
|
|
@@ -65,7 +71,28 @@ async function scanResolvers(nitro) {
|
|
|
65
71
|
}
|
|
66
72
|
async function scanDirectives(nitro) {
|
|
67
73
|
const files = await scanFiles(nitro, "graphql", "**/*.directive.{ts,js}");
|
|
68
|
-
|
|
74
|
+
const exportName = [];
|
|
75
|
+
for (const file of files) {
|
|
76
|
+
const fileContent = await readFile(file.fullPath, "utf-8");
|
|
77
|
+
const parsed = await parseAsync(file.fullPath, fileContent);
|
|
78
|
+
const exports = {
|
|
79
|
+
imports: [],
|
|
80
|
+
specifier: file.fullPath
|
|
81
|
+
};
|
|
82
|
+
for (const node of parsed.program.body) if (node.type === "ExportNamedDeclaration" && node.declaration && node.declaration.type === "VariableDeclaration") {
|
|
83
|
+
for (const decl of node.declaration.declarations) if (decl.type === "VariableDeclarator" && decl.init && decl.id.type === "Identifier") {
|
|
84
|
+
if (decl.init && decl.init.type === "CallExpression") {
|
|
85
|
+
if (decl.init.callee.type === "Identifier" && decl.init.callee.name === "defineDirective") exports.imports.push({
|
|
86
|
+
name: decl.id.name,
|
|
87
|
+
type: "directive",
|
|
88
|
+
as: `_${hash(decl.id.name + file.path).replace(/-/g, "").slice(0, 6)}`
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (exports.imports.length > 0) exportName.push(exports);
|
|
94
|
+
}
|
|
95
|
+
return exportName;
|
|
69
96
|
}
|
|
70
97
|
async function scanTypeDefs(nitro) {
|
|
71
98
|
const files = await scanFiles(nitro, "graphql", "**/*.typedef.{ts,js}");
|
|
@@ -105,4 +132,4 @@ async function scanDir(nitro, dir, name, globPattern = GLOB_SCAN_PATTERN) {
|
|
|
105
132
|
}
|
|
106
133
|
|
|
107
134
|
//#endregion
|
|
108
|
-
export { GLOB_SCAN_PATTERN, getImportId, relativeWithDot, scanDirectives, scanDocs, scanGraphql, scanResolvers, scanSchemas, scanTypeDefs };
|
|
135
|
+
export { GLOB_SCAN_PATTERN, directiveParser, generateDirectiveSchema, generateDirectiveSchemas, getImportId, relativeWithDot, scanDirectives, scanDocs, scanGraphql, scanResolvers, scanSchemas, scanTypeDefs };
|