/**
* Shared Standard Schema V1 validation and issue helpers.
*
* The module preserves provider issue data while giving callers one parse error
* and one path-prefixing operation for composed structures.
*
* @module
*/
import type { StandardSchemaV1 } from '@standard-schema/spec';
import type { Failure, Schema, Success, ValidationResult } from './types.ts';
/** Error raised when a value does not satisfy a Standard Schema contract. */
export class SchemaValidationError extends TypeError {
readonly issues: readonly StandardSchemaV1.Issue[];
constructor(issues: readonly StandardSchemaV1.Issue[], message?: string) {
const details = issues.map((issue) => issue.message).filter((value) => value.length > 0).join('; ');
super(message ?? (details.length === 0
? 'Value does not satisfy the required schema.'
: `Value does not satisfy the required schema: ${details}`));
this.name = 'SchemaValidationError';
this.issues = Object.freeze([...issues]);
}
}
/** Return whether a value implements Standard Schema V1. */
export function is(value: unknown): value is Schema {
if (typeof value !== 'object' || value === null) return false;
const standard = (value as { readonly '~standard'?: unknown })['~standard'];
return typeof standard === 'object' && standard !== null &&
(standard as { readonly version?: unknown }).version === 1 &&
typeof (standard as { readonly vendor?: unknown }).vendor === 'string' &&
typeof (standard as { readonly validate?: unknown }).validate === 'function';
}
/** Validate an unknown value and normalize the Standard Schema result. */
export async function validate(
definition: Schema,
value: unknown,
): Promise> {
assert(definition);
const result = await definition['~standard'].validate(value);
if (result.issues !== undefined) return failure(result.issues);
return success(result.value);
}
/** Validate an unknown value or throw {@link SchemaValidationError}. */
export async function parse(
definition: Schema,
value: unknown,
): Promise