8 releases
| 0.1.9 | Aug 10, 2025 |
|---|---|
| 0.1.8 | Aug 2, 2025 |
| 0.1.6 | Jul 31, 2025 |
#782 in Command line utilities
84KB
1.5K
SLoC
bagsakan
This is a rust project to implement optimal validation functions based on TypeScript types.
It uses the very fast oxidation compile libraries which are written in rust and highly optimised to parse TypeScript files and resolve imports.
Unlike similar projects it does not require hooking into the TypeScript compiler via ts-patch.
Installation
Using npm/pnpm/yarn
# npm
npm install -D bagsakan
# pnpm
pnpm add -D bagsakan
# yarn
yarn add -D bagsakan
Manual Installation
Download the appropriate binary for your platform from the releases page.
Usage
Basic Usage
Scan for validator function calls and generate validators:
# Using npx/pnpm exec
npx bagsakan
pnpm exec bagsakan
# Or if installed globally
bagsakan
Add Command
Add a validator for a specific interface without scanning for validator calls:
# Add a validator for the User interface
bagsakan add User
# Add a validator for ProductDetails interface
bagsakan add ProductDetails
The add command will:
- Search for the specified interface in your source files
- Generate a validator function for it
- Insert it into your validators file in alphabetical order
- Preserve any existing validators in the file
This is useful when:
- You want to add validators incrementally
- You're adding validators for interfaces that aren't used yet
- You want to generate validators without having to write validator function calls first
Overview
Unlike other projects that need to use a transformer via ts-patch, this code statically generates one file containing validators which can be viewed by the user and stored in the repo.
The file containing the validator functions must be recreated if any interfaces are changed or new interface validators are added to the code.
This project has a toml configuration file which looks like this (the following shows the defaults):
validatorPattern = "validate%(type)"
sourceFiles = "src/**/*.ts"
validatorFile = "src/validators.ts"
useJsExtensions = false
followExternalImports = true
excludePackages = []
conditions = []
Configuration Options
validatorPattern: Pattern for validator function names where%(type)matches[a-z][A-Z]+and identifies whichinterfaceis being validatedsourceFiles: Glob pattern for TypeScript files to scan for validator function callsvalidatorFile: Output path for the generated validator functionsuseJsExtensions: Iftrue, imports in the generated file will end with.js(useful for ESM projects)followExternalImports: Iftrue, bagsakan will follow imports to external packages to find interface definitionsexcludePackages: Array of package names to exclude when following imports (useful for resolving conflicts)conditions: Export conditions to use when resolving package.json exports (e.g.,["dev"],["production"])
How it works
- Uses
oxc-parserto parse all TypeScript files that matchsourceFiles - Finds function calls that match
validatorPatternwhere%(type)identifies the interface name - Follows imports (including to external packages) to find the interface definitions
- Generates validator functions with runtime type checking for each interface
- Stores all generated functions in the
validatorFile
Resolving Interface Conflicts with excludePackages
When multiple packages export interfaces with the same name, you can use excludePackages to ensure the correct interface is used:
# If both 'api-types' and 'legacy-types' packages export a 'User' interface,
# but you want to use the one from 'api-types':
excludePackages = ["legacy-types"]
This is particularly useful in monorepos or projects with multiple type packages where interface names might collide.
Example
Basic Setup
Given a TypeScript file src/api.ts:
import { User, Order } from 'shared-types'
import { Product } from '@company/product-types'
export function handleRequest(data: unknown) {
if (!validateUser(data.user)) {
throw new Error('Invalid user')
}
if (!validateOrder(data.order)) {
throw new Error('Invalid order')
}
// ... handle request
}
Without a bagsakan.toml in the current directory (using default options), running bagsakan will generate src/validators.ts:
// THIS FILE IS AUTO-GENERATED BY BAGSAKAN
// DO NOT EDIT THIS FILE MANUALLY
// To regenerate, run: bagsakan
import type { Order, User } from 'shared-types'
export function validateOrder(value: unknown): value is Order {
if (typeof value !== 'object' || value === null) {
return false
}
const obj = value as Order
// ... property validations
return true
}
export function validateUser(value: unknown): value is User {
if (typeof value !== 'object' || value === null) {
return false
}
const obj = value as User
// ... property validations
return true
}
Advanced Configuration for Monorepos
For projects using export conditions and symlinked packages:
validatorPattern = "validate%(type)"
sourceFiles = "src/**/*.ts"
validatorFile = "src/validators.ts"
useJsExtensions = true
followExternalImports = true
conditions = ["dev"] # Use 'dev' export condition from package.json
excludePackages = ["@legacy/types"] # Exclude legacy type definitions
This configuration is useful when:
- Your monorepo uses export conditions in package.json
- You have multiple versions of type packages
- You need to exclude certain packages to avoid conflicts
Dependencies
~21MB
~376K SLoC