1 | import { oldVisit } from '@graphql-codegen/plugin-helpers';
|
2 | import { optimizeOperations } from '@graphql-codegen/visitor-plugin-common';
|
3 | import { concatAST, Kind } from 'graphql';
|
4 | import { TypeScriptDocumentsVisitor } from './visitor.js';
|
5 | export const plugin = (schema, rawDocuments, config) => {
|
6 | const documents = config.flattenGeneratedTypes
|
7 | ? optimizeOperations(schema, rawDocuments, {
|
8 | includeFragments: config.flattenGeneratedTypesIncludeFragments,
|
9 | })
|
10 | : rawDocuments;
|
11 | const allAst = concatAST(documents.map(v => v.document));
|
12 | const allFragments = [
|
13 | ...allAst.definitions.filter(d => d.kind === Kind.FRAGMENT_DEFINITION).map(fragmentDef => ({
|
14 | node: fragmentDef,
|
15 | name: fragmentDef.name.value,
|
16 | onType: fragmentDef.typeCondition.name.value,
|
17 | isExternal: false,
|
18 | })),
|
19 | ...(config.externalFragments || []),
|
20 | ];
|
21 | const visitor = new TypeScriptDocumentsVisitor(schema, config, allFragments);
|
22 | const visitorResult = oldVisit(allAst, {
|
23 | leave: visitor,
|
24 | });
|
25 | let content = visitorResult.definitions.join('\n');
|
26 | if (config.addOperationExport) {
|
27 | const exportConsts = [];
|
28 | for (const d of allAst.definitions) {
|
29 | if ('name' in d) {
|
30 | exportConsts.push(`export declare const ${d.name.value}: import("graphql").DocumentNode;`);
|
31 | }
|
32 | }
|
33 | content = visitorResult.definitions.concat(exportConsts).join('\n');
|
34 | }
|
35 | if (config.globalNamespace) {
|
36 | content = `
|
37 | declare global {
|
38 | ${content}
|
39 | }`;
|
40 | }
|
41 | return {
|
42 | prepend: [...visitor.getImports(), ...visitor.getGlobalDeclarations(visitor.config.noExport)],
|
43 | content,
|
44 | };
|
45 | };
|
46 | export { TypeScriptDocumentsVisitor };
|