Skip to main content
Home
This package works with Node.js, Deno, Bun, BrowsersIt is unknown whether this package works with Cloudflare Workers
It is unknown whether this package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
This package works with Bun
This package works with Browsers
JSR Score
88%
Published
a week ago (0.6.1)

Schema Validator

A cross-platform module for validating OpenAPI, AsyncAPI, and JSON Schema documents against their official specifications. Works with Deno, Node.js, and Bun.

Features

  • ✅ Validates OpenAPI 3.0 and 3.1 documents
  • ✅ Validates AsyncAPI 2.x and 3.x documents
  • ✅ Validates JSON Schema drafts (draft-04, draft-06, draft-07, 2019-09, 2020-12)
  • ✅ Validates data against custom JSON Schemas - Create validators for any JSONSchema
  • ✅ Schema fragment validation - Validate data against parts of larger schemas (e.g., OpenAPI components)
  • ✅ Synchronous validation - All validation methods are synchronous for better performance
  • ✅ Uses official published schemas from specification organizations
  • ✅ Cross-platform - Works with Deno, Node.js, and Bun
  • ✅ Zero file permissions required - schemas are inlined as TypeScript modules
  • ✅ No file I/O - all schemas bundled in the module
  • ✅ Works offline - no network requests required
  • ✅ TypeScript support with full type definitions
  • ✅ Automatic content type detection
  • ✅ Comprehensive error reporting with detailed validation errors

Installation

Deno

# Using JSR
import { validateSchema } from 'jsr:@schema-tools/validate@0.4.0';

# Or using npm specifier
import { validateSchema } from 'npm:@schema-tools/validate@0.4.0';

Node.js / Bun

npm install @schema-tools/validate@0.4.0
# or
bun add @schema-tools/validate@0.4.0
import { validateSchema } from '@schema-tools/validate';

Usage

import { validateSchema } from '@schema-tools/validate';

// Validate an OpenAPI document
const openApiDoc = {
  openapi: '3.0.0',
  info: { title: 'My API', version: '1.0.0' },
  paths: {}
};

const result = validateSchema(openApiDoc);

if (result.errors.length > 0) {
  console.error('Validation errors:', result.errors);
} else {
  console.log('Document is valid!');
}

Supported Schema Types

OpenAPI

  • 3.0.x (using official schema from spec.openapis.org)
  • 3.1.x (using official schema from spec.openapis.org)

AsyncAPI

  • 2.0.0 - 2.6.0 (using official schemas from asyncapi/spec-json-schemas)
  • 3.0.0 (using official schema from asyncapi/spec-json-schemas)

JSON Schema

  • draft-04 (using official meta-schema from json-schema.org)
  • draft-06 (using official meta-schema from json-schema.org)
  • draft-07 (using official meta-schema from json-schema.org)
  • 2019-09 (using official meta-schema from json-schema.org)
  • 2020-12 (using official meta-schema from json-schema.org)

API

validateSchema(content: Record<string, unknown>): ValidationResult

Validates a document against its schema. The function automatically detects the document type and version from the content.

Returns:

{
  success: boolean;  // true if validation passed (no errors)
  type: 'openapi' | 'asyncapi' | 'jsonschema';
  version: string;
  errors: ValidationError[];
}

Example:

const result = validateSchema(openApiDoc);
if (result.success) {
  console.log('Document is valid!');
} else {
  console.error('Validation errors:', result.errors);
}

getSchema(type: SchemaType, version: string): Record<string, unknown>

Gets the schema for a specific type and version. Returns the raw schema object.

Parameters:

  • type: The schema type ('openapi', 'asyncapi', or 'jsonschema')
  • version: The schema version (e.g., '3.0', '2.6.0', 'draft-07')

Returns: The schema object

Example:

const openApiSchema = getSchema('openapi', '3.0');
const asyncApiSchema = getSchema('asyncapi', '2.6.0');
const jsonSchema = getSchema('jsonschema', 'draft-07');

detectContentType(content: Record<string, unknown>): { type: SchemaType; version: string } | null

Detects the type and version of a document from its content.

Returns: An object with type and version, or null if detection fails.

Example:

const metadata = detectContentType({
  openapi: '3.0.0',
  info: { title: 'My API', version: '1.0.0' },
  paths: {}
});
// Returns: { type: 'openapi', version: '3.0.0' }

SchemaValidator

A class for programmatic validation with more control.

Example:

import { SchemaValidator } from '@schema-tools/validate';

const validator = new SchemaValidator('openapi', '3.0');
const errors = validator.validate(openApiDoc);

if (errors.length === 0) {
  console.log('Valid!');
}

generateValidator(schema: Record<string, unknown>, jsonPointer?: string): (data: unknown) => { success: boolean; errors: ValidationError[] }

Generates a validator function for a custom schema or schema fragment. The schema is automatically validated before use.

Parameters:

  • schema: The schema to validate against (can be a full schema or fragment)
  • jsonPointer: Optional JSON Pointer to extract schema fragment (default: "#/" for entire schema)

Returns: A validation function that takes data and returns { success: boolean; errors: ValidationError[] }

Example:

import { generateValidator } from '@schema-tools/validate';

// Create a validator for a custom schema
const mySchema = {
  type: 'object',
  properties: {
    name: { type: 'string' },
    age: { type: 'number' }
  },
  required: ['name']
};

const validate = generateValidator(mySchema);
const result = validate({ name: 'John', age: 30 });
// result: { success: true, errors: [] }

// Validate against a fragment of an OpenAPI schema
const openApiDoc = {
  openapi: '3.0.0',
  info: { title: 'Test API', version: '1.0.0' },
  paths: {},
  components: {
    schemas: {
      Pet: {
        type: 'object',
        properties: {
          name: { type: 'string' },
          type: { type: 'string' }
        },
        required: ['name']
      }
    }
  }
};

const validatePet = generateValidator(openApiDoc, '#/components/schemas/Pet');
const petResult = validatePet({ name: 'Fluffy', type: 'cat' });
// petResult: { success: true, errors: [] }

DataValidator

A class for validating data against custom schemas or schema fragments.

Example:

import { DataValidator } from '@schema-tools/validate';

const schema = {
  type: 'object',
  properties: {
    name: { type: 'string' }
  }
};

const validator = new DataValidator(schema);
const errors = validator.validate({ name: 'John' });

if (errors.length === 0) {
  console.log('Valid!');
}

clearSchemaCache(): void

Clears the internal schema cache. Useful for testing or memory management.

ValidationError

{
  type: ValidationErrorType;
  message: string;
  path?: string;
  details?: unknown;
}

ValidationErrorType

  • MISSING_REQUIRED_FIELD - Required field is missing
  • INVALID_TYPE - Field has incorrect type
  • INVALID_FORMAT - Field format is invalid
  • CONSTRAINT_VIOLATION - Min/max/length constraint violated
  • PATTERN_MISMATCH - Pattern/regex validation failed
  • ENUM_MISMATCH - Value not in allowed enum values
  • INVALID_REFERENCE - Reference cannot be resolved
  • SCHEMA_VIOLATION - General schema violation
  • UNKNOWN_ERROR - Unexpected error occurred

Implementation Details

This module uses an innovative approach to schema validation:

  • Inlined Schemas: All official schemas are converted to TypeScript modules and bundled with the package
  • No File I/O: Schemas are imported directly, eliminating the need for file system access
  • Zero Permissions: The module works without any Deno permission flags
  • Fast Performance: Schemas are loaded once and cached in memory
  • Offline Ready: No network requests required - everything is bundled
  • Cross-Platform: Works identically on Deno, Node.js, and Bun

Platform Support

This package is designed to work across multiple JavaScript runtimes:

  • Deno: Full support via JSR or npm specifier
  • Node.js: Full support via npm (requires Node.js 18+)
  • Bun: Full support via npm

All platforms use the same codebase with no platform-specific code paths.

Development

# Run tests (Deno)
deno task test

# Run tests in watch mode
deno task test:watch

# Format code
deno task fmt

# Lint code
deno task lint

License

MIT

New Ticket: Report package

Please provide a reason for reporting this package. We will review your report and take appropriate action.

Please review the JSR usage policy before submitting a report.

Add Package

deno add jsr:@schema-tools/validate

Import symbol

import * as validate from "@schema-tools/validate";
or

Import directly with a jsr specifier

import * as validate from "jsr:@schema-tools/validate";

Add Package

pnpm i jsr:@schema-tools/validate
or (using pnpm 10.8 or older)
pnpm dlx jsr add @schema-tools/validate

Import symbol

import * as validate from "@schema-tools/validate";

Add Package

yarn add jsr:@schema-tools/validate
or (using Yarn 4.8 or older)
yarn dlx jsr add @schema-tools/validate

Import symbol

import * as validate from "@schema-tools/validate";

Add Package

vlt install jsr:@schema-tools/validate

Import symbol

import * as validate from "@schema-tools/validate";

Add Package

npx jsr add @schema-tools/validate

Import symbol

import * as validate from "@schema-tools/validate";

Add Package

bunx jsr add @schema-tools/validate

Import symbol

import * as validate from "@schema-tools/validate";