# How Archify Uses AJV for Compile-Time JSON Schema Validation

> Learn how Archify uses AJV to compile JSON Schema into fast, dependency-free validators for diagram-type JSON payloads at compile time. Ensure data integrity with efficient validation.

- Repository: [tt-a1i/archify](https://github.com/tt-a1i/archify)
- Tags: how-to-guide
- Published: 2026-08-30

---

**Archify validates diagram-type JSON payloads by statically compiling JSON Schema definitions into fast, dependency-free validator functions using the AJV library.**

The `tt-a1i/archify` repository implements a high-performance validation layer where **Archify uses AJV for validation** of diagram data. By leveraging AJV's standalone code generation capabilities, the project moves schema validation from runtime to compile-time, eliminating external dependencies in production while maintaining strict data integrity across workflow, sequence, and architecture diagrams.

## The Compile-Time Validation Architecture

Archify's validation strategy relies on **compile-time code generation** rather than runtime schema compilation. This approach ensures that the AJV library itself is only required during the build process, while the generated validation functions run as pure JavaScript with zero external dependencies.

The core generation logic resides in `archify/scripts/generate-validators.mjs`. This Node.js module orchestrates the transformation of static JSON Schema files into executable validation functions bundled with the application.

### Loading AJV 2020 and the Standalone Generator

The script begins by importing AJV's 2020 specification implementation and the standalone code generator:

```javascript
import Ajv2020 from 'ajv/dist/2020.js';
import standaloneCode from 'ajv/dist/standalone/index.js';

```

These imports provide the JSON Schema 2020-12 dialect support and the ability to extract compiled validation logic as source code strings.

### Configuring AJV for Strict Validation

The AJV instance is configured with strict mode and comprehensive error reporting:

```javascript
const ajv = new Ajv2020({
  allErrors: true,
  strict: true,
  code: { source: true, esm: true }
});

```

The `allErrors: true` option ensures validators capture every schema violation rather than failing fast on the first error. The `code` object instructs AJV to emit ECMAScript modules (`esm: true`) with source code exposed (`source: true`), enabling the standalone generator to extract the validation logic.

### Processing Diagram Schema Definitions

The generator loads a common base schema and iterates through diagram-specific definitions:

```javascript
// Located at archify/scripts/generate-validators.mjs#L20-L27
ajv.addSchema(JSON.parse(fs.readFileSync('schemas/common.schema.json', 'utf8')));

const schemaIds = {};
for (const type of ['workflow', 'sequence', 'dataflow', 'lifecycle', 'architecture']) {
  const schema = JSON.parse(fs.readFileSync(`schemas/${type}.schema.json`, 'utf8'));
  ajv.addSchema(schema);
  schemaIds[type] = schema.$id;
}

```

This loop registers each diagram type's schema—referenced by `$id`—into the AJV instance, building a complete validation context that includes shared definitions from [`common.schema.json`](https://github.com/tt-a1i/archify/blob/main/common.schema.json).

### Generating the Standalone Validator Module

After compiling the schemas into memory, the script generates the output module:

```javascript
// Located at archify/scripts/generate-validators.mjs#L43-L50
const validatorCode = standaloneCode(ajv, schemaIds);

// Inline the ucs2length helper and verify no unwanted runtime requires remain

```

The `standaloneCode` function extracts the compiled validation logic into a string, creating a self-contained module. The script specifically handles the `ucs2length` helper—required for accurate Unicode string length calculations—by inlining its implementation and verifying that no unwanted runtime `require` calls remain in the output.

The final code is written to `archify/renderers/shared/generated-validators.mjs`, producing a file containing pure JavaScript validation functions with no external AJV dependency.

## Using the Generated Validators at Runtime

The generated file exports named validation functions for each diagram type. These functions execute without importing AJV, providing immediate validation with minimal overhead:

```javascript
import { validateWorkflow, validateSequence } from './renderers/shared/generated-validators.mjs';

// Validate a workflow JSON object
const isValid = validateWorkflow(diagramData);
if (!isValid) {
  console.error('Validation errors:', validateWorkflow.errors);
}

```

Each exported function returns a boolean and exposes an `errors` property containing detailed validation failures when invalid data is detected.

## Executing the Validator Generation

Invoke the generation process via the provided npm script:

```bash
npm run generate:validators

```

This command executes `archify/scripts/generate-validators.mjs`, reading schemas from the `archify/schemas/` directory and writing the optimized validators to `archify/renderers/shared/generated-validators.mjs`. Run this script from the repository root whenever schema definitions change to synchronize the validation layer with your data models.

## Summary

- **Archify uses AJV for validation** through static code generation, converting JSON Schemas into pure JavaScript functions at build time rather than runtime.
- The generation script at `archify/scripts/generate-validators.mjs` leverages AJV 2020 and the `standaloneCode` utility to eliminate runtime dependencies.
- Configuration includes strict mode (`strict: true`), comprehensive error collection (`allErrors: true`), and ESM output format (`code: { source: true, esm: true }`).
- Validators handle five diagram types—**workflow**, **sequence**, **dataflow**, **lifecycle**, and **architecture**—plus shared definitions from [`common.schema.json`](https://github.com/tt-a1i/archify/blob/main/common.schema.json).
- The resulting `generated-validators.mjs` file provides zero-dependency validation functions used directly by renderers, with the `ucs2length` helper inlined to prevent external imports.

## Frequently Asked Questions

### Why does Archify compile validators at build time instead of runtime?

Compile-time generation removes the AJV library from production bundles, reducing package size and eliminating runtime compilation overhead. The generated validators execute as optimized JavaScript functions without requiring schema parsing or dynamic code generation in the browser or Node.js runtime environment.

### How does Archify handle string length validation without runtime dependencies?

The generation script specifically processes the `ucs2length` helper function required by AJV for accurate Unicode string length calculations. By inlining this utility during the build process, the resulting `generated-validators.mjs` contains all necessary logic internally, avoiding dynamic imports from `ajv/dist/runtime/ucs2length` and verifying no unwanted `require` calls remain.

### What diagram types does Archify validate using AJV?

According to the source code in `archify/scripts/generate-validators.mjs`, Archify validates five diagram types: **workflow**, **sequence**, **dataflow**, **lifecycle**, and **architecture**. Each type has a corresponding schema file (e.g., [`workflow.schema.json`](https://github.com/tt-a1i/archify/blob/main/workflow.schema.json)) and generated validation function (e.g., `validateWorkflow`) exported from the standalone module.

### How do I update validators after modifying a JSON Schema?

Run `npm run generate:validators` from the repository root after editing any file in `archify/schemas/`. This command executes the generation script, which recompiles all schema definitions into `archify/renderers/shared/generated-validators.mjs`, ensuring the runtime validation logic reflects your current schema requirements without manual synchronization.