npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bernierllc/schema-validator

v1.2.0

Published

Universal data validation utilities using JSON Schema, Zod, and custom validation rules

Downloads

107

Readme

@bernierllc/schema-validator

Universal data validation utilities using JSON Schema, Zod, and custom validation rules.

Installation

npm install @bernierllc/schema-validator

Usage

JSON Schema Validation

import { createValidator } from '@bernierllc/schema-validator';

const schema = {
  type: 'json-schema',
  schema: {
    type: 'object',
    properties: {
      name: { type: 'string', minLength: 1 },
      age: { type: 'number', minimum: 0 },
      email: { type: 'string', format: 'email' }
    },
    required: ['name', 'age']
  }
};

const validator = createValidator(schema);

// Async validation
const result = await validator.validate({
  name: 'John',
  age: 30,
  email: '[email protected]'
});

if (result.valid) {
  console.log('Data is valid:', result.data);
} else {
  console.log('Validation errors:', result.errors);
}

// Sync validation
const syncResult = validator.validateSync(data);

Zod Validation

import { z } from 'zod';
import { createValidator } from '@bernierllc/schema-validator';

const zodSchema = z.object({
  name: z.string().min(1),
  age: z.number().min(0),
  email: z.string().email().optional()
});

const schema = {
  type: 'zod',
  schema: zodSchema
};

const validator = createValidator(schema);
const result = await validator.validate(data);

Custom Validation

import { createValidator, createValidationError } from '@bernierllc/schema-validator';

const customValidator = {
  validate: async (data) => {
    if (typeof data !== 'string' || data.length < 3) {
      return {
        valid: false,
        errors: [createValidationError('', 'String must be at least 3 characters', 'min-length')],
        warnings: [],
        metadata: { backend: 'custom', duration: 0, transformations: [] }
      };
    }
    
    return {
      valid: true,
      data: data,
      errors: [],
      warnings: [],
      metadata: { backend: 'custom', duration: 0, transformations: [] }
    };
  }
};

const schema = {
  type: 'custom',
  schema: customValidator
};

const validator = createValidator(schema);
const result = await validator.validate('hello');

Validation Options

import { createValidator } from '@bernierllc/schema-validator';

const schema = {
  type: 'json-schema',
  schema: {
    type: 'object',
    properties: {
      name: { type: 'string' },
      status: { type: 'string', default: 'active' }
    }
  },
  options: {
    useDefaults: true,    // Apply default values
    coerce: true,         // Type coercion
    strict: true,         // Strict validation
    abortEarly: false,    // Continue on errors
    removeAdditional: false, // Keep extra properties
    allowUnknown: false   // Disallow unknown properties
  }
};

const validator = createValidator(schema);

API Reference

Main Functions

  • createValidator<T>(schema: ValidationSchema): Validator<T> - Create a validator instance
  • validate<T>(data: any, schema: ValidationSchema): Promise<ValidationResult<T>> - One-shot async validation
  • validateSync<T>(data: any, schema: ValidationSchema): ValidationResult<T> - One-shot sync validation
  • compileSchema(schema: ValidationSchema): CompiledSchema - Pre-compile schema for reuse
  • mergeSchemas(schemas: ValidationSchema[]): ValidationSchema - Merge multiple schemas

Types

interface ValidationResult<T> {
  valid: boolean;
  data?: T;
  errors: ValidationError[];
  warnings: ValidationWarning[];
  metadata: {
    backend: string;
    duration: number;
    transformations: string[];
  };
}

interface ValidationError {
  path: string;
  message: string;
  code: string;
  value?: any;
  expected?: any;
}

Features

  • Multiple Backends: JSON Schema (ajv), Zod, and custom validators
  • Type Safety: Full TypeScript support with type inference
  • Performance: Schema compilation and caching
  • Detailed Errors: Structured error reporting with paths
  • Transformations: Data coercion, defaults, and cleanup
  • Async Support: Both synchronous and asynchronous validation
  • Extensible: Custom validation functions and rules

Supported Schema Types

  1. JSON Schema - Industry standard schema validation
  2. Zod - TypeScript-first schema validation
  3. Custom - Your own validation functions

Error Handling

All validation results include detailed error information:

const result = await validator.validate(invalidData);

if (!result.valid) {
  result.errors.forEach(error => {
    console.log(`${error.path}: ${error.message} (${error.code})`);
  });
}

Performance

  • Schemas are compiled once for optimal performance
  • Validation duration is tracked in metadata
  • Support for schema caching and reuse

Integration Documentation

Logger Integration

This package supports optional integration with @bernierllc/logger for enhanced logging capabilities:

import { createValidator } from '@bernierllc/schema-validator';
// Logger integration is automatically detected when available
// No additional setup required - the package provides graceful degradation

When @bernierllc/logger is available in your project:

  • Validation errors are logged with structured data
  • Performance metrics are tracked
  • Debug information is available for troubleshooting

NeverHub Integration

This package supports optional integration with @bernierllc/neverhub-adapter for service discovery and event communication:

// NeverHub integration is automatically detected and configured
// The package provides graceful degradation when NeverHub is not available

When NeverHub is available:

  • Validation events can be published to the event bus
  • Service discovery allows dynamic configuration
  • Health monitoring and metrics reporting is enabled

Graceful Degradation

All integrations are optional and the package works fully without them:

  • No Logger: Uses console logging as fallback
  • No NeverHub: Functions as standalone package
  • No External Dependencies: Core functionality always available

License

Copyright (c) 2025 Bernier LLC. All rights reserved.

This package is licensed under the Bernier LLC license. See LICENSE file for details.