|
| 1 | +import { convertDescription, GraphQLESTreeNode, SafeGraphQLType, convertLocation, convertRange } from "@graphql-eslint/types"; |
| 2 | +import { |
| 3 | + ASTNode, |
| 4 | + TypeNode, |
| 5 | + TypeInfo, |
| 6 | + visit, |
| 7 | + visitWithTypeInfo, |
| 8 | +} from "graphql"; |
| 9 | + |
| 10 | +export function convertToESTree<T extends ASTNode>( |
| 11 | + node: T, |
| 12 | + typeInfo?: TypeInfo |
| 13 | +): GraphQLESTreeNode<T> { |
| 14 | + const visitor = { leave: convertNode(typeInfo) }; |
| 15 | + return visit(node, typeInfo ? visitWithTypeInfo(typeInfo, visitor) : visitor); |
| 16 | +} |
| 17 | + |
| 18 | +function hasTypeField<T extends ASTNode>( |
| 19 | + obj: any |
| 20 | +): obj is T & { readonly type: TypeNode } { |
| 21 | + return obj && !!(obj as any).type; |
| 22 | +} |
| 23 | + |
| 24 | +const convertNode = (typeInfo?: TypeInfo) => <T extends ASTNode>( |
| 25 | + node: T |
| 26 | +): GraphQLESTreeNode<T> => { |
| 27 | + const commonFields = { |
| 28 | + typeInfo: typeInfo |
| 29 | + ? { |
| 30 | + argument: typeInfo.getArgument(), |
| 31 | + defaultValue: typeInfo.getDefaultValue(), |
| 32 | + directive: typeInfo.getDirective(), |
| 33 | + enumValue: typeInfo.getEnumValue(), |
| 34 | + fieldDef: typeInfo.getFieldDef(), |
| 35 | + inputType: typeInfo.getInputType(), |
| 36 | + parentInputType: typeInfo.getParentInputType(), |
| 37 | + parentType: typeInfo.getParentType(), |
| 38 | + gqlType: typeInfo.getType(), |
| 39 | + } |
| 40 | + : {}, |
| 41 | + leadingComments: convertDescription(node), |
| 42 | + trailingComments: [], |
| 43 | + loc: convertLocation(node.loc), |
| 44 | + range: convertRange(node.loc), |
| 45 | + }; |
| 46 | + |
| 47 | + if (hasTypeField<T>(node)) { |
| 48 | + const { type: gqlType, loc: gqlLocation, ...rest } = node; |
| 49 | + const typeFieldSafe: SafeGraphQLType<T> = { |
| 50 | + ...rest, |
| 51 | + gqlType, |
| 52 | + } as SafeGraphQLType<T & { readonly type: TypeNode }>; |
| 53 | + const estreeNode: GraphQLESTreeNode<T> = { |
| 54 | + ...typeFieldSafe, |
| 55 | + ...commonFields, |
| 56 | + type: node.kind, |
| 57 | + rawNode: node, |
| 58 | + gqlLocation, |
| 59 | + } as any as GraphQLESTreeNode<T>; |
| 60 | + |
| 61 | + return estreeNode; |
| 62 | + } else { |
| 63 | + const { loc: gqlLocation, ...rest } = node; |
| 64 | + const typeFieldSafe: SafeGraphQLType<T> = rest as SafeGraphQLType<T & { readonly type: TypeNode }>; |
| 65 | + const estreeNode: GraphQLESTreeNode<T> = { |
| 66 | + ...typeFieldSafe, |
| 67 | + ...commonFields, |
| 68 | + type: node.kind, |
| 69 | + rawNode: node, |
| 70 | + gqlLocation, |
| 71 | + } as any as GraphQLESTreeNode<T>; |
| 72 | + |
| 73 | + return estreeNode; |
| 74 | + } |
| 75 | +}; |
0 commit comments