CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-graphql-codegen--core

Core functionality for GraphQL Code Generator - a tool that generates code from GraphQL schemas and operations through a plugin system

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

@graphql-codegen/core

@graphql-codegen/core provides the core functionality for GraphQL Code Generator - a tool that generates code from GraphQL schemas and operations through a plugin system. It serves as the foundational engine that processes GraphQL schemas, analyzes documents, and coordinates with various plugins to generate customized output.

Package Information

  • Package Name: @graphql-codegen/core
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @graphql-codegen/core

Core Imports

import { codegen, executePlugin } from "@graphql-codegen/core";
import type { ExecutePluginOptions } from "@graphql-codegen/core";

For CommonJS:

const { codegen, executePlugin } = require("@graphql-codegen/core");

Basic Usage

import { codegen } from "@graphql-codegen/core";
import { Types } from "@graphql-codegen/plugin-helpers";
import { DocumentNode, GraphQLSchema } from "graphql";

// Example: Basic code generation with a plugin
const generatedCode = await codegen({
  schema: schemaDocumentNode as DocumentNode,
  documents: [
    { 
      location: "queries/users.graphql", 
      document: queryDocumentNode as DocumentNode 
    }
  ],
  plugins: [{ "typescript": {} }],
  pluginMap: { "typescript": typescriptPlugin },
  filename: "generated/types.ts",
  config: {}
} as Types.GenerateOptions);

console.log(generatedCode);

Architecture

@graphql-codegen/core is built around several key components:

  • Core Generation Engine: The codegen function orchestrates the entire generation process
  • Plugin Execution System: The executePlugin function manages individual plugin execution
  • Document Processing: Handles GraphQL document validation, transformation, and deduplication
  • Schema Management: Merges schemas with plugin additions and federation support
  • Validation Engine: Validates GraphQL documents against schemas with configurable rules

Capabilities

Code Generation

Main function that processes GraphQL schemas and documents through plugins to generate code output.

/**
 * Generate code from GraphQL schema and documents using configured plugins
 * @param options - Generation configuration options
 * @returns Promise resolving to generated code string
 */
function codegen(options: Types.GenerateOptions): Promise<string>;

Plugin Execution

Executes a single GraphQL codegen plugin with provided options and handles validation.

/**
 * Execute a single GraphQL codegen plugin
 * @param options - Plugin execution options
 * @param plugin - The plugin instance to execute
 * @returns Promise resolving to plugin output
 */
function executePlugin(
  options: ExecutePluginOptions, 
  plugin: CodegenPlugin
): Promise<Types.PluginOutput>;

Types

interface ExecutePluginOptions {
  /** Plugin name identifier */
  name: string;
  /** Plugin-specific configuration */
  config: Types.PluginConfig;
  /** Parent configuration object */
  parentConfig: Types.PluginConfig;
  /** GraphQL schema as DocumentNode */
  schema: DocumentNode;
  /** Optional GraphQL schema instance */
  schemaAst?: GraphQLSchema;
  /** Array of GraphQL documents to process */
  documents: Types.DocumentFile[];
  /** Target output filename */
  outputFilename: string;
  /** All configured plugins */
  allPlugins: Types.ConfiguredPlugin[];
  /** Document validation options */
  skipDocumentsValidation?: Types.SkipDocumentsValidationOptions;
  /** Additional plugin context data */
  pluginContext?: { [key: string]: any };
  /** Optional performance profiler */
  profiler?: Profiler;
}

Key External Types

These types are imported from @graphql-codegen/plugin-helpers:

interface Types.GenerateOptions {
  /** Target output filename */
  filename: string;
  /** Array of configured plugins */
  plugins: Types.ConfiguredPlugin[];
  /** GraphQL schema as DocumentNode */
  schema: DocumentNode;
  /** Optional GraphQL schema instance */
  schemaAst?: GraphQLSchema;
  /** Array of GraphQL documents */
  documents: Types.DocumentFile[];
  /** Global configuration object */
  config: { [key: string]: any };
  /** Map of plugin names to plugin instances */
  pluginMap: { [name: string]: CodegenPlugin };
  /** Document validation options */
  skipDocumentsValidation?: Types.SkipDocumentsValidationOptions;
  /** Additional plugin context */
  pluginContext?: { [key: string]: any };
  /** Optional performance profiler */
  profiler?: Profiler;
  /** Optional caching function */
  cache?<T>(namespace: string, key: string, factory: () => Promise<T>): Promise<T>;
  /** Optional document transforms */
  documentTransforms?: ConfiguredDocumentTransform[];
}

interface Types.DocumentFile extends Source {
  /** Optional document hash for caching */
  hash?: string;
}

type Types.PluginConfig<T = any> = { [key: string]: T };

interface Types.ConfiguredPlugin {
  /** Plugin configuration where key is plugin name */
  [name: string]: Types.PluginConfig;
}

type Types.SkipDocumentsValidationOptions = {
  /** Skip specific GraphQL validation rules */
  ignoreRules?: string[];
  /** Skip duplicate documents validation */
  skipDuplicateValidation?: boolean;
  /** Skip document validation against schema */
  skipValidationAgainstSchema?: boolean;
} | boolean;

type Types.PluginOutput = string | {
  /** Generated content */
  content: string;
  /** Content to prepend to output */
  prepend?: string[];
  /** Content to append to output */
  append?: string[];
};

interface CodegenPlugin<T = any> {
  /** Main plugin function */
  plugin: PluginFunction<T>;
  /** Optional schema additions */
  addToSchema?: AddToSchemaResult | ((config: T) => AddToSchemaResult);
  /** Optional validation function */
  validate?: PluginValidateFn;
}

// Supporting types
type PluginFunction<T = any> = (
  schema: GraphQLSchema,
  documents: Types.DocumentFile[],
  config: T,
  info?: {
    outputFile?: string;
    allPlugins?: Types.ConfiguredPlugin[];
    pluginContext?: { [key: string]: any };
    [key: string]: any;
  }
) => Types.PluginOutput | Promise<Types.PluginOutput>;

type AddToSchemaResult = DocumentNode | string;
type PluginValidateFn = (
  schema: GraphQLSchema,
  documents: Types.DocumentFile[],
  config: any,
  outputFile: string,
  allPlugins: Types.ConfiguredPlugin[],
  pluginContext: { [key: string]: any }
) => Promise<void> | void;

interface Source {
  location: string;
  document: DocumentNode;
}

interface ConfiguredDocumentTransform {
  name: string;
  config?: any;
  transformObject: {
    transform: (options: {
      documents: Types.DocumentFile[];
      schema: DocumentNode;
      config: any;
      pluginContext?: { [key: string]: any };
    }) => Promise<Types.DocumentFile[]> | Types.DocumentFile[];
  };
}

interface Profiler {
  run<T>(fn: () => Promise<T> | T, name: string): Promise<T>;
}

Error Handling

The library throws errors in several scenarios:

  • Invalid Plugin Structure: When a plugin doesn't export a valid plugin function
  • Document Validation Failures: When GraphQL documents fail validation against the schema
  • Plugin Validation Failures: When a plugin's custom validation function fails
  • Duplicate Document Names: When multiple documents have the same name with different content

Performance Features

  • Profiler Support: Optional performance profiling for generation phases
  • Document Caching: Caches document validation results using schema and document hashes
  • Lazy Schema Building: Only builds schema when necessary for merging
  • Document Deduplication: Removes duplicate documents to avoid redundant processing

docs

index.md

tile.json