# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

mercurius-validation is a Fastify plugin that adds configurable validation support to Mercurius GraphQL servers. It supports JSON Schema, JTD (JSON Type Definition), custom function validation, and GraphQL `@constraint` directive-based validation.

## Common Commands

```bash
# Run all checks (lint + tests + TypeScript)
npm test

# Run only unit tests
npm run unit

# Run a single test file
npx borp --no-typescript 'test/json-schema-validation.js'

# Run tests with coverage (requires 100% coverage)
npm run cov

# Run linting
npm run lint

# Run TypeScript type checking
npm run typescript
```

## Architecture

### Core Flow

1. **Plugin Registration** (`index.js`): Registers with Fastify/Mercurius, validates options, creates the `Validation` instance, and hooks into schema refresh events for gateway mode.

2. **Validation Orchestrator** (`lib/validation.js`): Manages the three validation strategies and registers them against the GraphQL schema in reverse order of execution (directive → function → schema validators).

3. **Validators** (`lib/validators/`): Four validator types that all override GraphQL field resolvers to inject validation:
   - `json-schema-validator.js`: Validates using AJV with JSON Schema
   - `jtd-validator.js`: Validates using AJV with JTD
   - `function-validator.js`: Executes custom validation functions with full GraphQL context
   - `directive-validator.js`: Extracts `@constraint` directives and converts them to JSON Schema validation

4. **Base Validator** (`lib/validators/validator.js`): Shared resolver-wrapping logic using AJV schemas keyed by `https://mercurius.dev/validation/{type}/{field}`.

### Validation Schema Structure

User-defined validation schemas follow this pattern:
```javascript
{
  schema: {
    TypeName: {           // GraphQL type (Query, Mutation, or Input type)
      fieldOrArg: {       // Field or argument name
        // JSON Schema or validation function
      }
    }
  }
}
```

### Key Exports

- `mercuriusValidation`: The Fastify plugin
- `mercuriusValidation.graphQLTypeDefs`: SDL for `@constraint` directive
- `mercuriusValidation.graphQLDirective`: The directive definition object

### Testing

Tests use Node.js built-in test runner (`node:test`). Each test file covers a specific validation type. Tests create fresh Fastify instances with Mercurius and the validation plugin, then make GraphQL queries via `app.inject()`.
