pure-schemify
v0.1.0
Published
**purecore-schemify** is a **High Fidelity Polyfill** for Zod-like schema validation, designed specifically for the `@purecore` ecosystem. It provides a lightweight, zero-dependency, type-safe runtime validation library that follows the fluent API design
Readme
purecore-schemify
purecore-schemify is a High Fidelity Polyfill for Zod-like schema validation, designed specifically for the @purecore ecosystem. It provides a lightweight, zero-dependency, type-safe runtime validation library that follows the fluent API design pattern familiar to TypeScript developers.
This library allows you to define schemas for your data, infer TypeScript types automatically, and validate data at runtime with informative error reporting.
🚀 Features
- Zero Dependencies: Built entirely with native TypeScript, ensuring minimal footprint and maximum portability.
- Fluent API: Chainable methods (e.g.,
.min(),.optional(),.refine()) for intuitive schema definition. - Static Type Inference: Automatic TypeScript type inference using
z.infer<typeof schema>. - Runtime Validation: Robust
parseandsafeParsemethods to ensure data integrity. - Nominal Typing Support: Built-in support for Nominal Types via
z.nominaland atomic behaviors, enforcing strict domain modeling. - Extensible: check mechanisms, refinements, and transformations.
📦 Installation
Since this is part of the @purecore monorepo structure, you can typically use it by importing the source directly or linking the package.
bun install @purecore/schemify(Note: Adjust installation method based on your specific workspace configuration)
🛠 Usage
Basic Primitives
import { z } from "./src/index";
// String Schema
const emailSchema = z.string().email().min(5);
// Number Schema
const ageSchema = z.number().int().min(18).max(120);
// Parse
emailSchema.parse("[email protected]"); // "[email protected]"
ageSchema.parse(25); // 25Object Schemas
const UserSchema = z.object({
id: z.number(),
username: z.string().min(3),
isActive: z.boolean().default(true),
roles: z.array(z.string()).optional(),
});
type User = z.infer<typeof UserSchema>;
// inferred as: { id: number; username: string; isActive: boolean; roles?: string[] }
const result = UserSchema.safeParse({
id: 1,
username: "alice",
});
if (result.success) {
console.log(result.data);
} else {
console.error(result.error);
}🧠 Advanced Concepts: Nominal & Atomic Types
One of the unique features of purecore-schemify is its first-class support for Nominal Types and Atomic Behaviors. This allows you to create opaque types that are structurally strings/numbers but semantically distinct.
Behaviors
// Define a behavior for a UserID
const UserId = z.behavior("UserId", z.string().uuid());
// Forge a value (validates and brands it)
const id = UserId.forge("123e4567-e89b-12d3-a456-426614174000");
// 'id' is now typed as AtomicType<string, "UserId">
// It cannot be accidentally assigned to a generic string or another nominal type.Nominal Wrapper
const Email = z.nominal("Email", z.string().email());
const myEmail = Email.validate("[email protected]");📚 Technical Deep Dive: How it Works
The Core: SchemifyType
At the heart of the library is the abstract base class SchemifyType<Output, Def, Input>.
_parseSync: Every specific type (String, Number, Object) implements this abstract method to perform its core validation logic._process: This method handles the common logic for all types:- Optional/Nullable/Default: Checks if the value is missing or null and handles it based on configuration.
- Validation: Calls
_parseSync. - Refinements: Executes custom
.refine()checks. - Transforms: Applies
.transform()functions to modify the output.
The Facade: z
The z export acts as a singleton factory. It provides convenient accessors to instantiate specific SchemifyType subclasses (SchemifyString, SchemifyObject, etc.), mimicking the API surface of popular validation libraries for ease of adoption.
Error Handling
Errors are aggregated into a SchemifyError class, which contains an array of SchemifyIssue objects. Each issue pinpoints the path (e.g., user.address.street) and the code of the error, allowing for precise UI feedback (like form validation errors).
🧪 How to Test
You can test the library using bun test or by running a simple script to verify behavior.
Example Test Script (test.ts):
import { z } from "./src/index";
const schema = z.object({
name: z.string(),
age: z.number().min(0),
});
try {
const data = schema.parse({ name: "Bob", age: 30 });
console.log("✅ Validation passed:", data);
} catch (e) {
console.error("❌ Validation failed:", e);
}
try {
schema.parse({ name: "Bob", age: -5 });
} catch (e) {
console.log("✅ Expected failure caught:", e.message);
}Run it with:
wsl bun run test.tsCreated by Antigravity for the @purecore open-source initiative.
