Common utilities and base classes for GraphQL Code Generator visitor-based plugins
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Helper classes and functions for building TypeScript declarations, managing code formatting, and handling code output. These utilities provide the building blocks for generating clean, well-formatted TypeScript code from GraphQL schemas and operations.
Helper class for building TypeScript declarations with fluent interface for configuration and content management.
/**
* Helper class for building TypeScript declarations
*/
class DeclarationBlock {
/**
* Sets export flag for the declaration
* @param exp - Whether to export (default true)
* @returns DeclarationBlock instance for chaining
*/
export(exp?: boolean): DeclarationBlock;
/**
* Sets declaration kind (type, interface, class, etc.)
* @param kind - TypeScript declaration kind
* @returns DeclarationBlock instance for chaining
*/
asKind(kind: DeclarationKind): DeclarationBlock;
/**
* Sets declaration name and optional generic parameters
* @param name - Declaration name
* @param generics - Generic type parameters string
* @returns DeclarationBlock instance for chaining
*/
withName(name: string, generics?: string): DeclarationBlock;
/**
* Sets declaration block content from array of strings
* @param block - Array of content lines
* @returns DeclarationBlock instance for chaining
*/
withBlock(block: string[]): DeclarationBlock;
/**
* Sets declaration content as single string
* @param content - Declaration content
* @returns DeclarationBlock instance for chaining
*/
withContent(content: string): DeclarationBlock;
/**
* Sets JSDoc comment for the declaration
* @param comment - Comment string or array of comment lines
* @returns DeclarationBlock instance for chaining
*/
withComment(comment: string | string[]): DeclarationBlock;
/**
* Builds the final declaration string
* @returns Complete TypeScript declaration
*/
build(): string;
}
interface DeclarationBlockConfig {
/** Wrapper string for block content (e.g., braces, parentheses) */
blockWrapper?: string;
/** Function to transform the block content before output */
blockTransformer?: (block: string) => string;
/** Separator between enum name and value */
enumNameValueSeparator?: string;
/** Suffix to append to declaration */
suffix?: string;
/** Whether to ignore export keywords */
ignoreExport?: boolean;
}Usage Examples:
import { DeclarationBlock } from "@graphql-codegen/visitor-plugin-common";
// Create a TypeScript interface
const interfaceDecl = new DeclarationBlock()
.export()
.asKind('interface')
.withName('User', '<T = string>')
.withComment(['User interface with generic type parameter', '@template T - ID type'])
.withBlock([
'id: T;',
'name: string;',
'email?: string;'
])
.build();
// Create a type alias
const typeDecl = new DeclarationBlock()
.export('default')
.asKind('type')
.withName('UserID')
.withContent('string | number')
.build();
// Create an enum
const enumDecl = new DeclarationBlock()
.export()
.asKind('enum')
.withName('UserRole')
.withBlock([
'Admin = "admin"',
'User = "user"',
'Guest = "guest"'
])
.build();Core utilities for string manipulation, indentation, and code formatting.
/**
* Indents a string by the specified number of spaces
* @param str - String to indent
* @param count - Number of spaces to indent (default: 2)
* @returns Indented string
*/
function indent(str: string, count?: number): string;
/**
* Indents a multiline string with proper handling of line breaks
* @param str - Multiline string to indent
* @param count - Number of spaces to indent (default: 2)
* @returns Indented multiline string
*/
function indentMultiline(str: string, count?: number): string;
/**
* Transforms JSDoc comments with proper formatting and indentation
* @param comment - Comment string or array of lines
* @param indentLevel - Indentation level for the comment
* @returns Formatted JSDoc comment
*/
function transformComment(comment: string | string[], indentLevel?: number): string;
/**
* Wraps values in single quotes if needed (strings, non-numeric values)
* @param value - Value to potentially quote
* @param skipNumericCheck - Skip checking if value is numeric
* @returns Quoted or original value
*/
function wrapWithSingleQuotes(value: string, skipNumericCheck?: boolean): string;
/**
* Adds a line break to the end of a string if it doesn't already have one
* @param str - String to add line break to
* @returns String with guaranteed line break at end
*/
function breakLine(str: string): string;
/**
* Creates a code block from an array of strings
* @param array - Array of code lines
* @returns Joined code block string
*/
function block(array: string[]): string;
/**
* Quotes array values if needed and joins them
* @param array - Array of values to process
* @param joinWith - String to join values with (default: ', ')
* @returns Joined string with quoted values
*/
function quoteIfNeeded(array: string[], joinWith?: string): string;Utilities for working with GraphQL types, AST nodes, and schema processing.
/**
* Gets the base type node from a potentially wrapped type (NonNull, List)
* @param typeNode - GraphQL type node
* @returns Base named type node
*/
function getBaseTypeNode(typeNode: TypeNode): NamedTypeNode;
/**
* Builds scalar mappings from schema and configuration
* @param schema - GraphQL schema
* @param config - Scalar configuration
* @param defaults - Default scalar mappings
* @returns Normalized scalars map
*/
function buildScalarsFromConfig(
schema: GraphQLSchema,
config: RawConfig,
defaults?: NormalizedScalarsMap
): NormalizedScalarsMap;
/**
* Builds scalar mappings from direct scalar mapping configuration
* @param schema - GraphQL schema
* @param scalarsMapping - Direct scalar mappings
* @param defaults - Default scalar mappings
* @returns Normalized scalars map
*/
function buildScalars(
schema: GraphQLSchema,
scalarsMapping: ScalarsMap,
defaults?: NormalizedScalarsMap
): NormalizedScalarsMap;
/**
* Gets possible types for abstract types (interfaces and unions)
* @param schema - GraphQL schema
* @param type - GraphQL abstract type
* @returns Array of possible concrete types
*/
function getPossibleTypes(schema: GraphQLSchema, type: GraphQLAbstractType): ReadonlyArray<GraphQLObjectType>;
/**
* Wraps TypeScript types with modifiers (optional, array, non-null)
* @param baseType - Base TypeScript type string
* @param type - GraphQL type node
* @param options - Wrapping options
* @returns Type string with appropriate modifiers
*/
function wrapTypeWithModifiers(baseType: string, type: TypeNode, options?: WrapTypeOptions): string;
/**
* Merges two GraphQL selection sets
* @param set1 - First selection set
* @param set2 - Second selection set
* @returns Merged selection set
*/
function mergeSelectionSets(set1: SelectionSetNode, set2: SelectionSetNode): SelectionSetNode;
/**
* Separates selection set into different node types
* @param selections - Array of selection nodes
* @returns Object with selections grouped by type
*/
function separateSelectionSet(selections: ReadonlyArray<SelectionNode>): {
fields: FieldNode[];
inlineFragments: InlineFragmentNode[];
fragmentSpreads: FragmentSpreadNode[];
};
/**
* Checks if an input object type is a OneOf input type
* @param node - Input object type definition node
* @returns True if the input type is OneOf
*/
function isOneOfInputObjectType(node: InputObjectTypeDefinitionNode): boolean;Utility functions for working with configuration values and transformations.
/**
* Gets configuration value with fallback to default
* @param value - Configuration value (may be undefined)
* @param defaultValue - Default value to use if config value is undefined
* @returns Resolved configuration value
*/
function getConfigValue<T>(value: T | undefined, defaultValue: T): T;
/**
* Converts name parts using a transformation function
* @param str - String to convert
* @param func - Transformation function
* @param removeUnderscore - Whether to remove underscores
* @returns Converted string
*/
function convertNameParts(str: string, func: (str: string) => string, removeUnderscore?: boolean): string;
/**
* Strips mapper type interpolation from identifier strings
* @param identifier - Identifier string that may contain interpolation
* @returns Clean identifier without interpolation
*/
function stripMapperTypeInterpolation(identifier: string): string;
/**
* Gets field names from selection set options
* @param options - Selection set processing options
* @returns Array of field names
*/
function getFieldNames(options: { selections: ReadonlyArray<SelectionNode> }): string[];General utility functions for working with arrays and objects.
/**
* Groups array items by a key function
* @param array - Array to group
* @param key - Function that returns grouping key for each item
* @returns Object with items grouped by key
*/
function groupBy<T, K extends string | number>(array: T[], key: (item: T) => K): Record<K, T[]>;
/**
* Flattens nested arrays into a single array
* @param array - Array of arrays to flatten
* @returns Flattened array
*/
function flatten<T>(array: T[][]): T[];
/**
* Gets unique items from array, optionally using a key function
* @param array - Array to process
* @param key - Optional function to determine uniqueness key
* @returns Array with unique items
*/
function unique<T>(array: T[], key?: (item: T) => any): T[];Pre-defined TypeScript utility type definitions for common patterns.
/** TypeScript Omit utility type definition */
const OMIT_TYPE: string;
/** TypeScript RequireFields utility type definition */
const REQUIRE_FIELDS_TYPE: string;Usage Examples:
import {
DeclarationBlock,
indent,
transformComment,
getBaseTypeNode,
wrapTypeWithModifiers
} from "@graphql-codegen/visitor-plugin-common";
// Build a complex interface declaration
const buildUserInterface = () => {
const fields = [
'id: string;',
'name: string;',
'email?: string;',
'roles: UserRole[];'
];
return new DeclarationBlock()
.export()
.asKind('interface')
.withName('User')
.withComment([
'Represents a user in the system',
'@interface User'
])
.withBlock(fields.map(field => indent(field, 2)))
.build();
};
// Process GraphQL type with modifiers
const processGraphQLType = (typeNode, baseType) => {
const baseTypeNode = getBaseTypeNode(typeNode);
return wrapTypeWithModifiers(baseType, typeNode, {
wrapOptional: true,
wrapArray: true
});
};