@ap-ent/schema
v1.0.0
Published
Lightweight zero-dependency TypeScript validation library
Downloads
73
Maintainers
Readme
@ap/schema
Lightweight zero-dependency TypeScript schema validation library — think Zod, but under 2 KB gzipped.
Installation
npm install @ap/schemaQuick Start
import { ap, type Infer } from '@ap/schema';
// Define a schema
const UserSchema = ap.object({
name: ap.string().min(1).max(100),
email: ap.string().email(),
age: ap.number().optional(),
});
// Infer the TypeScript type
type User = Infer<typeof UserSchema>;
// { name: string; email: string; age: number | undefined }
// Validate — throws on failure
const user = UserSchema.parse({ name: 'Alice', email: '[email protected]' });
// Validate — returns result object
const result = UserSchema.safeParse({ name: '', email: 'bad' });
if (!result.success) {
console.error(result.errors);
// [{ path: ['name'], message: 'String must be at least 1 characters' }]
}API Reference
Primitives
ap.string() // string
ap.number() // number (NaN rejected)
ap.boolean() // boolean
ap.null_() // null
ap.undefined_() // undefinedString Constraints
ap.string().min(3) // minimum length
ap.string().max(100) // maximum length
ap.string().email() // valid email format
ap.string().url() // valid URL (uses URL constructor)Objects
const schema = ap.object({
id: ap.number(),
name: ap.string(),
});
type T = Infer<typeof schema>; // { id: number; name: string }Arrays
const schema = ap.array(ap.string());
type T = Infer<typeof schema>; // string[]Modifiers
ap.string().optional() // string | undefined
ap.string().nullable() // string | nullCustom Refinements
const positiveInt = ap.number()
.refine((n) => Number.isInteger(n), 'Must be an integer')
.refine((n) => n > 0, 'Must be positive');Parsing
// .parse() — throws Error on failure
const value = schema.parse(input);
// .safeParse() — returns discriminated union
const result = schema.safeParse(input);
if (result.success) {
console.log(result.data);
} else {
console.error(result.errors); // ValidationError[]
}Validation Errors
interface ValidationError {
path: string[]; // e.g. ['user', 'email'] for nested fields
message: string;
}Type Inference
import { type Infer } from '@ap/schema';
const schema = ap.object({ x: ap.number() });
type MyType = Infer<typeof schema>; // { x: number }License
MIT © Gordon Schauer
