JSONbored/zodkit(新しいタブで開きます)
主要言語: TypeScript
Static analysis and development tools for Zod schemas - validate files, generate mock data, and catch type safety issues before runtime.
- star 数
- 1
- watcher 数
- 0
- fork 数
- 3
- issue 数
- 0
- 最終更新
- 2026/08/18
主要言語: TypeScript
Static analysis and development tools for Zod schemas - validate files, generate mock data, and catch type safety issues before runtime.
The Complete Zod Schema Toolkit - Production-Ready v0.2.1-beta
A comprehensive, production-grade CLI for Zod schema development - combining static analysis, code generation, testing, and AI-powered assistance in a unified terminal interface.
# Install globally npm install -g zodkit # Initialize a new project zodkit init # Analyze your existing schemas zodkit check # Lint schemas for best practices zodkit lint # Generate statistics and bundle impact zodkit stats # Create schemas interactively zodkit create # Generate Zod from TypeScript zodkit scaffold src/types.ts # Test your schemas zodkit test
Need help? See TROUBLESHOOTING.md for common issues and solutions.
# Run the setup wizard zodkit init # This creates zodkit.config.json with: # - Schema file patterns # - Validation rules # - Output preferences
# Quick validation check zodkit check # Deep analysis with all rules zodkit analyze --mode full # Get detailed output zodkit analyze --mode full --verbose
What you'll see:
# Safe fixes only (reversible) zodkit fix --safe # All fixes including potentially breaking changes zodkit fix --unsafe # Interactive mode - choose what to fix zodkit fix --interactive
# Launch interactive schema builder zodkit create # With predefined name and output zodkit create --name UserProfile --output src/schemas/user-profile.schema.ts
Interactive Flow:
Example output:
import { z } from 'zod'; /** * User profile schema */ export const UserProfile = z.object({ /** User's email address */ email: z.string().email(), /** User's full name */ name: z.string().min(1).max(100), /** User's age */ age: z.number().int().min(0).max(150).optional(), }); export type UserProfile = z.infer<typeof UserProfile>;
# Convert a TypeScript file to Zod schemas zodkit scaffold src/types/user.ts # Output to specific file zodkit scaffold src/types/user.ts --output src/schemas/user.schema.ts # Dry run to preview zodkit scaffold src/types/user.ts --dry-run
Pattern Detection: The scaffold command automatically detects patterns:
.email().url().uuid().min(0).max(150).min(8).max(100)# Markdown documentation (default) zodkit docs # With custom output directory zodkit docs --output ./docs/schemas # HTML documentation with search zodkit docs --format html # JSON Schema export zodkit docs --format json # OpenAPI 3.1 specification zodkit docs --format openapi
Generated files:
README.md - Main documentation with TOC# Run all tests zodkit test # Specific test suite zodkit test --suite unit zodkit test --suite contract zodkit test --suite validation # With fuzzing (1000 iterations) zodkit test --fuzz --iterations 1000 # Performance benchmarks zodkit test --benchmark
# Dry run to preview changes zodkit migrate describe-to-meta --dry-run # Interactive mode with prompts zodkit migrate describe-to-meta --interactive # Automatic migration zodkit migrate describe-to-meta
What it does:
.describe("text") to .meta({ title: "text" })# Watch for changes and re-validate zodkit watch # Watch with specific patterns zodkit watch --patterns "src/schemas/**/*.ts"
# Analyze JSON file and generate Zod schema zodkit generate --from-json user-data.json --name User # With pattern detection enabled zodkit generate --from-json api-response.json --name ApiResponse --strict # Output to specific directory zodkit generate --from-json data.json --output ./src/schemas
What it does:
# Inspect API endpoint and generate schema zodkit generate --from-url https://api.example.com/users --name User # Test multiple HTTP methods zodkit generate --from-url https://api.example.com/data --samples 5 # With custom headers zodkit generate --from-url https://api.example.com/protected --header "Authorization: Bearer TOKEN"
What it does:
⚠️ EXPERIMENTAL FEATURE - Currently returns mock data only.
# Planned: Analyze database schema (not yet fully functional)
zodkit generate --from-database postgresql://localhost/mydb --name DatabaseSchemaCurrent Status:
Future Plans:
pg drivermysql2 driverbetter-sqlite3To use when available, install required drivers:
# PostgreSQL npm install pg @types/pg # MySQL npm install mysql2 # SQLite npm install better-sqlite3
# Generate realistic mock data zodkit mock UserSchema --count 10 # Different output formats zodkit mock UserSchema --count 100 --output users.json zodkit mock ProductSchema --format csv --output products.csv zodkit mock OrderSchema --format sql --output orders.sql # Reproducible data with seed zodkit mock UserSchema --count 50 --seed 12345
Pattern-based generation:
# Compare two schema versions and detect breaking changes zodkit diff --old ./schemas/user.v1.ts --new ./schemas/user.v2.ts # Generate detailed migration guide zodkit diff --old ./old-schema.ts --new ./new-schema.ts --migration # Output to different formats zodkit diff --old v1.ts --new v2.ts --format markdown --output migration.md zodkit diff --old v1.ts --new v2.ts --format html --output report.html zodkit diff --old v1.ts --new v2.ts --format json --output changes.json # Strict mode for detailed comparison zodkit diff --old v1.ts --new v2.ts --strict
What it detects:
Output formats:
# Lint all schema files zodkit lint # Lint specific files zodkit lint "src/schemas/**/*.ts" # Output as JSON zodkit lint --format json # Filter by severity zodkit lint --severity error # Save report to file zodkit lint --output lint-report.txt
What it checks:
.describe() calls.meta() with required fieldsz.any() usage (suggests z.unknown() instead).passthrough() and .catchall() usageOutput:
# Generate comprehensive statistics zodkit stats # Analyze specific files zodkit stats "src/schemas/**/*.ts" # Output as JSON zodkit stats --format json # Verbose output with all details zodkit stats --verbose # Skip specific analyses zodkit stats --no-complexity zodkit stats --no-bundle-impact zodkit stats --no-patterns --no-hotspots # Save report to file zodkit stats --output stats-report.txt
What it provides:
Complexity Analysis:
Bundle Impact Analysis:
# Sync with database schema zodkit sync --target database # Sync with API definitions zodkit sync --target api # Sync TypeScript types zodkit sync --target types
# View schema relationships zodkit map # Focus on specific schema zodkit map UserSchema # Export relationship map zodkit map --export schema-map.json # Interactive visualization zodkit map --visualize
# Get explanation for a schema zodkit explain UserSchema # With complexity analysis zodkit explain UserSchema --verbose
# Start MCP server for AI assistants zodkit mcp serve # Connect to existing MCP server zodkit mcp connect
zodkit init # Setup configuration zodkit scaffold src/types/*.ts # Generate initial schemas zodkit docs # Create documentation zodkit test # Verify everything works
zodkit check # Quick validation zodkit analyze --mode full # Deep analysis zodkit fix --safe # Auto-fix issues zodkit test # Run tests
zodkit docs --format markdown # For GitHub/docs sites zodkit docs --format html # For internal wikis zodkit docs --format openapi # For API documentation
zodkit check --format junit # For test reporters zodkit analyze --mode full --json # For automated analysis zodkit test --suite validation # For validation checks
| Command | Description | Options |
|---|---|---|
zodkit init |
Initialize project with setup wizard | --preset <name> |
zodkit check |
Fast schema validation | --verbose, --json |
zodkit analyze |
Deep schema analysis | --mode <check|hint|fix|full> |
zodkit fix |
Auto-fix schema issues | --safe, --unsafe, --interactive |
zodkit docs |
Generate documentation | --format <markdown|html|json|openapi>, --output <dir> |
zodkit test |
Run schema tests | --suite <unit|contract|validation>, --fuzz, --benchmark |
zodkit watch |
Continuous validation | --patterns <glob> |
| Command | Description | Options |
|---|---|---|
zodkit create |
Interactive schema builder | --name <name>, --output <path>, --no-interactive |
zodkit scaffold <file> |
TypeScript → Zod conversion | --output <file>, --dry-run |
zodkit generate mock <schema> |
Generate mock data | --count <n>, --format <json|ts|csv|sql>, --output <file> |
| Command | Description | Options |
|---|---|---|
zodkit lint [patterns...] |
Lint schemas for best practices | --fix, --severity <level>, --format <text|json> |
zodkit stats [patterns...] |
Generate schema statistics | --format <text|json>, --verbose, --no-complexity, --no-bundle-impact, --output <file> |
zodkit migrate describe-to-meta |
Migrate .describe() to .meta() | --dry-run, --interactive |
zodkit sync |
Sync with external sources | --target <database|api|types> |
zodkit map [schema] |
View schema relationships | --visualize, --export <file> |
| Command | Description | Options |
|---|---|---|
zodkit explain <schema> |
AI-powered explanations | --verbose |
zodkit mcp |
MCP server operations | serve, connect |
zodkit setup |
Configuration wizard | Interactive |
Scaffold automatically detects and adds refinements for common patterns:
| Pattern | Detection | Generated Refinement |
|---|---|---|
email, emailAddress |
.email() |
|
| URL | url, link, href |
.url() |
| UUID | id, uuid, guid |
.uuid() |
| Date | date, createdAt, updatedAt |
.datetime() |
| Age | age |
.min(0).max(150) |
| Port | port |
.min(1).max(65535) |
| Phone | phone, mobile |
.regex(/phone-pattern/) |
| Password | password, secret |
.min(8).max(100) |
Create zodkit.config.js in your project root:
module.exports = { // Schema discovery schemas: { patterns: ['./src/schemas/**/*.ts'], exclude: ['**/*.test.ts'] }, // Validation targets targets: { mdx: { patterns: ['./content/**/*.mdx'], frontmatterSchemas: 'auto' }, components: { patterns: ['./src/**/*.tsx'], propSchemas: 'auto' } }, // Rules rules: { 'require-validation': 'error', 'no-any-fallback': 'warn', 'prefer-strict-schemas': 'warn' }, // Output output: { format: 'pretty', verbose: false } };
Build Zod schemas step-by-step with interactive prompts:
# Launch interactive builder zodkit create # Pre-configure name and output zodkit create --name UserProfile --output src/schemas/user.schema.ts # Use a template zodkit create --template user --name UserProfile # JSON output (for automation) zodkit create --template user --name UserProfile --format json --output schema.json
Features:
class, function, etc.)any type usage)--format json)Available Templates:
Using Templates:
# Use a template via CLI zodkit create --template user --name UserProfile --output src/schemas/user.schema.ts # Or choose interactively zodkit create ? How would you like to create your schema? ❯ Start from a template Start from scratch ? Choose a template: ❯ User - User profile with authentication fields Product - E-commerce product schema Post - Blog post schema ...
Building from Scratch:
? Schema name: UserProfile
? Schema description: User profile information
? Add field? Yes
? Field name: email
? Field type: Email
? Optional field? No
? Nullable field? No
? Add validations? No
? Field description: User's email address
📋 Live Schema Preview:
────────────────────────────────────────
Schema: UserProfile
Description: User profile information
Fields: 1
✓ Valid schema
📝 Generated Code:
────────────────────────────────────────
import { z } from 'zod';
/**
* User profile information
*/
export const UserProfile = z.object({
/** User's email address */
email: z.string().email(),
});
export type UserProfile = z.infer<typeof UserProfile>;
────────────────────────────────────────
Real-time Validation Example:
? Field name: class
❌ Validation Errors:
• class: 'class' is a reserved JavaScript keyword
? Schema has errors. Continue anyway? No
⚠️ Last field removed.
Lint schemas for best practices and anti-patterns:
⚠️ Note: Auto-fix (
--fix) has known limitations with overlapping fixes and should be used with caution. Lint detection works perfectly.
# Lint all schemas zodkit lint # Lint specific patterns zodkit lint "src/schemas/**/*.ts" # Auto-fix safe issues (experimental - use with caution) zodkit lint --fix # Filter by severity zodkit lint --severity error # JSON output zodkit lint --format json --output lint-report.json
Built-in rules:
require-description - Schemas should have .describe() or .meta()prefer-meta - Prefer .meta() over .describe()no-any-type - Avoid z.any() for type safetyprefer-discriminated-union - Use discriminated unions for better performanceno-loose-objects - Avoid .passthrough() and loose .catchall()require-refinements - Suggest refinements for complex validationExample output:
📋 Linting 12 schema files...
❌ src/schemas/user.schema.ts:5:1
Rule: require-description
Severity: error
Message: Schema "UserSchema" is missing a description
Suggestions:
• Add .describe() to document the schema purpose
• Use .meta() to add structured metadata
⚠️ src/schemas/api.schema.ts:10:1
Rule: no-loose-objects
Severity: warning
Message: Loose object definition: Uses .passthrough()
Suggestions:
• Define explicit properties
• Document why passthrough is needed
Total issues: 2 (1 error, 1 warning)
Generate comprehensive statistics about your schemas:
# Analyze all schemas zodkit stats # Specific patterns zodkit stats "src/**/*.schema.ts" # JSON output zodkit stats --format json --output stats.json # Skip analysis zodkit stats --no-complexity --no-patterns --no-hotspots
Metrics:
Example output:
📊 Schema Statistics
Total Schemas: 24
📈 Type Distribution:
object: 18
array: 4
string: 2
🔢 Complexity Metrics:
Average Depth: 2.3
Max Depth: 5
Average Fields: 8.5
Max Fields: 23
Total Refinements: 12
Total Transforms: 3
🎯 Usage Patterns:
Email validation: 8 schemas
URL validation: 5 schemas
UUID validation: 12 schemas
Optional fields: 18 schemas
Custom refinements: 12 schemas
🔥 Hotspots (3):
HIGH: ComplexUserSchema (src/schemas/user.schema.ts)
• Deep nesting (5 levels)
• Many fields (23)
• Missing description
Suggestions:
- Consider flattening the schema
- Split into multiple smaller schemas
- Add .describe() to document purpose
📦 Bundle Impact (Estimated):
Total size: 18.5 KB
Largest schemas (top 5):
ComplexUserSchema: 2.15 KB
Deep nesting, Many fields, Complex refinements
ApiResponseSchema: 1.42 KB
Data transformations, Many fields
ProductSchema: 0.98 KB
Complex refinements
Optimization tips:
• Consider lazy loading schemas with refinements - they add significant bundle size
• Transforms are expensive - consider using .preprocess() or moving logic to application layer
• Largest schema (ComplexUserSchema) could be split into smaller, more focused schemas
💡 Recommendations:
• 6 schema(s) missing descriptions - add .describe() calls
• 2 complex schema(s) detected - consider refactoring
Scenario: You have TypeScript interfaces and want runtime validation.
Step 1: Create your TypeScript types
// src/types/user.ts interface User { id: string; email: string; age: number; createdAt: Date; password: string; website?: string; }
Step 2: Generate Zod schemas
zodkit scaffold src/types/user.ts --output src/schemas/user.schema.ts
Step 3: Review generated schema (with smart patterns)
// src/schemas/user.schema.ts import { z } from 'zod'; export const userSchema = z.object({ id: z.string().uuid(), email: z.string().email(), age: z.number().min(0).max(150), createdAt: z.date(), password: z.string().min(8).max(100), website: z.string().url().optional() }); export type User = z.infer<typeof userSchema>;
Step 4: Use in your application
import { userSchema } from './schemas/user.schema'; const result = userSchema.safeParse(req.body); if (!result.success) { return res.status(400).json({ errors: result.error.errors }); } const validUser = result.data; // Type-safe!
Scenario: Document your schemas for your API consumers.
Step 1: Add metadata to your schemas
export const userSchema = z.object({ id: z.string().uuid(), email: z.string().email(), age: z.number().min(0).max(150) }).meta({ title: 'User', category: 'auth', version: '1.0.0', description: 'User account information' });
Step 2: Generate documentation
zodkit docs --format openapi --output ./api-docs
Step 3: Use generated OpenAPI spec
Scenario: Validate blog post frontmatter in your content files.
Step 1: Create frontmatter schema
// src/schemas/blog.schema.ts export const BlogPostSchema = z.object({ title: z.string().min(1).max(100), date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), published: z.boolean(), tags: z.array(z.string()), author: z.string().optional() }).meta({ title: 'Blog Post', category: 'content' });
Step 2: Configure zodkit for MDX validation
// zodkit.config.json { "targets": { "mdx": { "patterns": ["./content/**/*.mdx"], "frontmatterSchemas": "auto" } } }
Step 3: Run validation
zodkit check
Output:
✓ Found 24 blog posts
✓ All frontmatter valid
Issues found: 0
Scenario: Validate schemas in your CI pipeline.
Step 1: Add to GitHub Actions
# .github/workflows/validate-schemas.yml name: Validate Schemas on: [push, pull_request] jobs: validate: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 - run: npm ci - run: npx zodkit check - run: npx zodkit test --suite validation
Step 2: Commit and push
git add .github/workflows/validate-schemas.yml
git commit -m "Add schema validation to CI"
git pushResult: Automated schema validation on every commit.
Scenario: Need realistic mock data for testing.
Step 1: Generate mock data
zodkit generate mock UserSchema --count 100 --output test-data/users.json
Step 2: Use in tests
import users from './test-data/users.json'; describe('User API', () => { it('should handle bulk user creation', async () => { const response = await api.post('/users/bulk', users); expect(response.status).toBe(201); }); });
// .vscode/tasks.json { "version": "2.0.0", "tasks": [ { "label": "Zodkit Check", "type": "shell", "command": "zodkit", "args": ["check"], "problemMatcher": [], "presentation": { "reveal": "a