Skip to content

Latest commit

 

History

History
83 lines (63 loc) · 2.23 KB

File metadata and controls

83 lines (63 loc) · 2.23 KB

Validation

@safe-shape/validation turns SafeShape parse results into JSON-friendly validation reports.

Validate

import { object, string } from "@safe-shape/core";
import { validateSchema, validateSchemaAsync } from "@safe-shape/validation";

const userSchema = object({
  id: string(),
});

const report = validateSchema(userSchema, { id: "user_1" });

Use validateSchemaAsync() for schemas containing explicit async rules.

Success:

{
  valid: true,
  data: {
    id: "user_1",
  },
}

Failure:

{
  valid: false,
  issues: [],
}

The report shape is designed for tool output, logs, generated validation reports, and transport-safe API boundaries. It does not throw for validation failures. Both success and failure reports include a frozen warnings field when non-fatal diagnostics were emitted. It is omitted when empty.

Native diagnostic codes are preserved, including not_multiple_of for exact numeric increments and string issue codes at constrained record-key paths. Record key and value issues may both be present for the same path.

When every ordinary union choice fails, its invalid_union issue preserves an ordered recursive branches tree. Each branch retains its declaration index, all issue codes, and full paths; the JSON-friendly report does not choose or flatten a branch.

Object reports expose the actual parsed output: explicit strip omits extra properties and passthrough preserves them. The default reject policy keeps returning unexpected_property issues.

Addressable custom diagnostics pass through unchanged. Relative paths from refine() and ordered multi-issue paths from refineWithIssues() remain rooted at their containing schema and retain the custom code.

API

function validateSchema<T>(schema: Schema<T>, input: unknown): ValidationReport<T>;
function validateSchemaAsync<T>(schema: Schema<T>, input: unknown): Promise<ValidationReport<T>>;

type ValidationReport<T> = ValidationSuccess<T> | ValidationFailure;

interface ValidationSuccess<T> {
  readonly valid: true;
  readonly data: T;
  readonly warnings?: readonly Warning[];
}

interface ValidationFailure {
  readonly valid: false;
  readonly issues: readonly Issue[];
  readonly warnings?: readonly Warning[];
}