feat: v2.0 iteration — test coverage, reliability, observability

M0: Test coverage expansion (151 → 321 tests, 61% → 66% lines)
  - normalizeKnowledge CRLF/LF normalization fix
  - gooseReviewer: 11 tests, 97.35% coverage
  - r2 storage: 22 tests, 100% coverage
  - triage processor: 11 tests, exported buildTriagePrompt/labelName
  - webhook processor: 35 tests, 72.39% coverage
  - conflict resolver: 12 tests
  - review processor: 7 tests

M1: Reliability hardening
  - Smart retry with jitter, maxTotalTimeoutMs, custom retryable predicate
  - MergeGuard: in-memory merge dedup tracker (100% coverage)
  - failureMessages: 7-category failure classifier (100% coverage)

M2: Observability
  - MetricsCollector: Actions-run metrics with snapshot/markdown/reset
  - 11 tests, 100% coverage

New files: 12 test files, 3 source modules
All gates: typecheck ✓ lint ✓ format ✓ 321/321 tests ✓ build ✓
This commit is contained in:
ghbot committed 2026-08-24 17:34:04 +08:00
1 parent db53296d78
commit 78bf8e9e41
87 files changed
+5752 -2336

No files matched your search

+35 -58
View File
@@ -68,9 +68,9 @@ const fastify = Fastify({
level: process.env.LOG_LEVEL || "info", level: process.env.LOG_LEVEL || "info",
transport: { transport: {
target: "pino-pretty", target: "pino-pretty",
options: { colorize: true }, options: { colorize: true }
}, }
}, }
}); });
// Plugins // Plugins
@@ -91,15 +91,15 @@ fastify.post<{
required: ["name", "email"], required: ["name", "email"],
properties: { properties: {
name: { type: "string", minLength: 1 }, name: { type: "string", minLength: 1 },
email: { type: "string", format: "email" }, email: { type: "string", format: "email" }
}, }
}, }
}, }
}, },
async (request, reply) => { async (request, reply) => {
const { name, email } = request.body; const { name, email } = request.body;
return { id: "123", name }; return { id: "123", name };
}, }
); );
await fastify.listen({ port: 3000, host: "0.0.0.0" }); await fastify.listen({ port: 3000, host: "0.0.0.0" });
@@ -203,7 +203,7 @@ export class UserService {
// Create user // Create user
const user = await this.userRepository.create({ const user = await this.userRepository.create({
...userData, ...userData,
password: hashedPassword, password: hashedPassword
}); });
// Remove password from response // Remove password from response
@@ -248,19 +248,13 @@ import { CreateUserDTO, UpdateUserDTO, UserEntity } from "../types/user.types";
export class UserRepository { export class UserRepository {
constructor(private db: Pool) {} constructor(private db: Pool) {}
async create( async create(userData: CreateUserDTO & { password: string }): Promise<UserEntity> {
userData: CreateUserDTO & { password: string },
): Promise<UserEntity> {
const query = ` const query = `
INSERT INTO users (name, email, password) INSERT INTO users (name, email, password)
VALUES ($1, $2, $3) VALUES ($1, $2, $3)
RETURNING id, name, email, password, created_at, updated_at RETURNING id, name, email, password, created_at, updated_at
`; `;
const { rows } = await this.db.query(query, [ const { rows } = await this.db.query(query, [userData.name, userData.email, userData.password]);
userData.name,
userData.email,
userData.password,
]);
return rows[0]; return rows[0];
} }
@@ -280,9 +274,7 @@ export class UserRepository {
const fields = Object.keys(updates); const fields = Object.keys(updates);
const values = Object.values(updates); const values = Object.values(updates);
const setClause = fields const setClause = fields.map((field, idx) => `${field} = $${idx + 2}`).join(", ");
.map((field, idx) => `${field} = $${idx + 2}`)
.join(", ");
const query = ` const query = `
UPDATE users UPDATE users
@@ -330,11 +322,7 @@ declare global {
} }
} }
export const authenticate = async ( export const authenticate = async (req: Request, res: Response, next: NextFunction) => {
req: Request,
res: Response,
next: NextFunction,
) => {
try { try {
const token = req.headers.authorization?.replace("Bearer ", ""); const token = req.headers.authorization?.replace("Bearer ", "");
@@ -383,14 +371,14 @@ export const validate = (schema: AnyZodObject) => {
await schema.parseAsync({ await schema.parseAsync({
body: req.body, body: req.body,
query: req.query, query: req.query,
params: req.params, params: req.params
}); });
next(); next();
} catch (error) { } catch (error) {
if (error instanceof ZodError) { if (error instanceof ZodError) {
const errors = error.errors.map((err) => ({ const errors = error.errors.map((err) => ({
field: err.path.join("."), field: err.path.join("."),
message: err.message, message: err.message
})); }));
next(new ValidationError("Validation failed", errors)); next(new ValidationError("Validation failed", errors));
} else { } else {
@@ -407,8 +395,8 @@ const createUserSchema = z.object({
body: z.object({ body: z.object({
name: z.string().min(1), name: z.string().min(1),
email: z.string().email(), email: z.string().email(),
password: z.string().min(8), password: z.string().min(8)
}), })
}); });
router.post("/users", validate(createUserSchema), userController.createUser); router.post("/users", validate(createUserSchema), userController.createUser);
@@ -424,29 +412,29 @@ import Redis from "ioredis";
const redis = new Redis({ const redis = new Redis({
host: process.env.REDIS_HOST, host: process.env.REDIS_HOST,
port: parseInt(process.env.REDIS_PORT || "6379"), port: parseInt(process.env.REDIS_PORT || "6379")
}); });
export const apiLimiter = rateLimit({ export const apiLimiter = rateLimit({
store: new RedisStore({ store: new RedisStore({
client: redis, client: redis,
prefix: "rl:", prefix: "rl:"
}), }),
windowMs: 15 * 60 * 1000, // 15 minutes windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs max: 100, // Limit each IP to 100 requests per windowMs
message: "Too many requests from this IP, please try again later", message: "Too many requests from this IP, please try again later",
standardHeaders: true, standardHeaders: true,
legacyHeaders: false, legacyHeaders: false
}); });
export const authLimiter = rateLimit({ export const authLimiter = rateLimit({
store: new RedisStore({ store: new RedisStore({
client: redis, client: redis,
prefix: "rl:auth:", prefix: "rl:auth:"
}), }),
windowMs: 15 * 60 * 1000, windowMs: 15 * 60 * 1000,
max: 5, // Stricter limit for auth endpoints max: 5, // Stricter limit for auth endpoints
skipSuccessfulRequests: true, skipSuccessfulRequests: true
}); });
``` ```
@@ -461,15 +449,11 @@ const logger = pino({
level: process.env.LOG_LEVEL || "info", level: process.env.LOG_LEVEL || "info",
transport: { transport: {
target: "pino-pretty", target: "pino-pretty",
options: { colorize: true }, options: { colorize: true }
}, }
}); });
export const requestLogger = ( export const requestLogger = (req: Request, res: Response, next: NextFunction) => {
req: Request,
res: Response,
next: NextFunction,
) => {
const start = Date.now(); const start = Date.now();
// Log response when finished // Log response when finished
@@ -481,7 +465,7 @@ export const requestLogger = (
status: res.statusCode, status: res.statusCode,
duration: `${duration}ms`, duration: `${duration}ms`,
userAgent: req.headers["user-agent"], userAgent: req.headers["user-agent"],
ip: req.ip, ip: req.ip
}); });
}); });
@@ -501,7 +485,7 @@ export class AppError extends Error {
constructor( constructor(
public message: string, public message: string,
public statusCode: number = 500, public statusCode: number = 500,
public isOperational: boolean = true, public isOperational: boolean = true
) { ) {
super(message); super(message);
Object.setPrototypeOf(this, AppError.prototype); Object.setPrototypeOf(this, AppError.prototype);
@@ -512,7 +496,7 @@ export class AppError extends Error {
export class ValidationError extends AppError { export class ValidationError extends AppError {
constructor( constructor(
message: string, message: string,
public errors?: any[], public errors?: any[]
) { ) {
super(message, 400); super(message, 400);
} }
@@ -551,17 +535,12 @@ import { Request, Response, NextFunction } from "express";
import { AppError } from "../utils/errors"; import { AppError } from "../utils/errors";
import { logger } from "./logger.middleware"; import { logger } from "./logger.middleware";
export const errorHandler = ( export const errorHandler = (err: Error, req: Request, res: Response, next: NextFunction) => {
err: Error,
req: Request,
res: Response,
next: NextFunction,
) => {
if (err instanceof AppError) { if (err instanceof AppError) {
return res.status(err.statusCode).json({ return res.status(err.statusCode).json({
status: "error", status: "error",
message: err.message, message: err.message,
...(err instanceof ValidationError && { errors: err.errors }), ...(err instanceof ValidationError && { errors: err.errors })
}); });
} }
@@ -570,24 +549,21 @@ export const errorHandler = (
error: err.message, error: err.message,
stack: err.stack, stack: err.stack,
url: req.url, url: req.url,
method: req.method, method: req.method
}); });
// Don't leak error details in production // Don't leak error details in production
const message = const message = process.env.NODE_ENV === "production" ? "Internal server error" : err.message;
process.env.NODE_ENV === "production"
? "Internal server error"
: err.message;
res.status(500).json({ res.status(500).json({
status: "error", status: "error",
message, message
}); });
}; };
// Async error wrapper // Async error wrapper
export const asyncHandler = ( export const asyncHandler = (
fn: (req: Request, res: Response, next: NextFunction) => Promise<any>, fn: (req: Request, res: Response, next: NextFunction) => Promise<any>
) => { ) => {
return (req: Request, res: Response, next: NextFunction) => { return (req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req, res, next)).catch(next); Promise.resolve(fn(req, res, next)).catch(next);
@@ -600,6 +576,7 @@ export const asyncHandler = (
Node.js supports both SQL and NoSQL databases. Use connection pooling for all production databases. Node.js supports both SQL and NoSQL databases. Use connection pooling for all production databases.
Key patterns covered in [references/advanced-patterns.md](references/advanced-patterns.md): Key patterns covered in [references/advanced-patterns.md](references/advanced-patterns.md):
- **PostgreSQL with connection pool** — `pg` Pool configuration and graceful shutdown - **PostgreSQL with connection pool** — `pg` Pool configuration and graceful shutdown
- **MongoDB with Mongoose** — connection management and schema definition - **MongoDB with Mongoose** — connection management and schema definition
- **Transaction pattern** — `BEGIN`/`COMMIT`/`ROLLBACK` with `pg` client - **Transaction pattern** — `BEGIN`/`COMMIT`/`ROLLBACK` with `pg` client
@@ -54,29 +54,17 @@ container.singleton(
password: process.env.DB_PASSWORD, password: process.env.DB_PASSWORD,
max: 20, max: 20,
idleTimeoutMillis: 30000, idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000, connectionTimeoutMillis: 2000
}), })
); );
container.singleton( container.singleton("userRepository", () => new UserRepository(container.resolve("db")));
"userRepository",
() => new UserRepository(container.resolve("db")),
);
container.singleton( container.singleton("userService", () => new UserService(container.resolve("userRepository")));
"userService",
() => new UserService(container.resolve("userRepository")),
);
container.register( container.register("userController", () => new UserController(container.resolve("userService")));
"userController",
() => new UserController(container.resolve("userService")),
);
container.singleton( container.singleton("authService", () => new AuthService(container.resolve("userRepository")));
"authService",
() => new AuthService(container.resolve("userRepository")),
);
``` ```
## Database Patterns ## Database Patterns
@@ -95,7 +83,7 @@ const poolConfig: PoolConfig = {
password: process.env.DB_PASSWORD, password: process.env.DB_PASSWORD,
max: 20, max: 20,
idleTimeoutMillis: 30000, idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000, connectionTimeoutMillis: 2000
}; };
export const pool = new Pool(poolConfig); export const pool = new Pool(poolConfig);
@@ -128,7 +116,7 @@ const connectDB = async () => {
await mongoose.connect(process.env.MONGODB_URI!, { await mongoose.connect(process.env.MONGODB_URI!, {
maxPoolSize: 10, maxPoolSize: 10,
serverSelectionTimeoutMS: 5000, serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000, socketTimeoutMS: 45000
}); });
console.log("MongoDB connected"); console.log("MongoDB connected");
@@ -163,11 +151,11 @@ const userSchema = new Schema<IUser>(
{ {
name: { type: String, required: true }, name: { type: String, required: true },
email: { type: String, required: true, unique: true }, email: { type: String, required: true, unique: true },
password: { type: String, required: true }, password: { type: String, required: true }
}, },
{ {
timestamps: true, timestamps: true
}, }
); );
// Indexes // Indexes
@@ -194,7 +182,7 @@ export class OrderService {
// Create order // Create order
const orderResult = await client.query( const orderResult = await client.query(
"INSERT INTO orders (user_id, total) VALUES ($1, $2) RETURNING id", "INSERT INTO orders (user_id, total) VALUES ($1, $2) RETURNING id",
[userId, calculateTotal(items)], [userId, calculateTotal(items)]
); );
const orderId = orderResult.rows[0].id; const orderId = orderResult.rows[0].id;
@@ -202,14 +190,14 @@ export class OrderService {
for (const item of items) { for (const item of items) {
await client.query( await client.query(
"INSERT INTO order_items (order_id, product_id, quantity, price) VALUES ($1, $2, $3, $4)", "INSERT INTO order_items (order_id, product_id, quantity, price) VALUES ($1, $2, $3, $4)",
[orderId, item.productId, item.quantity, item.price], [orderId, item.productId, item.quantity, item.price]
); );
// Update inventory // Update inventory
await client.query( await client.query("UPDATE products SET stock = stock - $1 WHERE id = $2", [
"UPDATE products SET stock = stock - $1 WHERE id = $2", item.quantity,
[item.quantity, item.productId], item.productId
); ]);
} }
await client.query("COMMIT"); await client.query("COMMIT");
@@ -253,11 +241,11 @@ export class AuthService {
const token = this.generateToken({ const token = this.generateToken({
userId: user.id, userId: user.id,
email: user.email, email: user.email
}); });
const refreshToken = this.generateRefreshToken({ const refreshToken = this.generateRefreshToken({
userId: user.id, userId: user.id
}); });
return { return {
@@ -266,17 +254,16 @@ export class AuthService {
user: { user: {
id: user.id, id: user.id,
name: user.name, name: user.name,
email: user.email, email: user.email
}, }
}; };
} }
async refreshToken(refreshToken: string) { async refreshToken(refreshToken: string) {
try { try {
const payload = jwt.verify( const payload = jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET!) as {
refreshToken, userId: string;
process.env.REFRESH_TOKEN_SECRET!, };
) as { userId: string };
const user = await this.userRepository.findById(payload.userId); const user = await this.userRepository.findById(payload.userId);
@@ -286,7 +273,7 @@ export class AuthService {
const token = this.generateToken({ const token = this.generateToken({
userId: user.id, userId: user.id,
email: user.email, email: user.email
}); });
return { token }; return { token };
@@ -297,13 +284,13 @@ export class AuthService {
private generateToken(payload: any): string { private generateToken(payload: any): string {
return jwt.sign(payload, process.env.JWT_SECRET!, { return jwt.sign(payload, process.env.JWT_SECRET!, {
expiresIn: "15m", expiresIn: "15m"
}); });
} }
private generateRefreshToken(payload: any): string { private generateRefreshToken(payload: any): string {
return jwt.sign(payload, process.env.REFRESH_TOKEN_SECRET!, { return jwt.sign(payload, process.env.REFRESH_TOKEN_SECRET!, {
expiresIn: "7d", expiresIn: "7d"
}); });
} }
} }
@@ -321,7 +308,7 @@ const redis = new Redis({
retryStrategy: (times) => { retryStrategy: (times) => {
const delay = Math.min(times * 50, 2000); const delay = Math.min(times * 50, 2000);
return delay; return delay;
}, }
}); });
export class CacheService { export class CacheService {
@@ -353,11 +340,7 @@ export class CacheService {
// Cache decorator // Cache decorator
export function Cacheable(ttl: number = 300) { export function Cacheable(ttl: number = 300) {
return function ( return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
target: any,
propertyKey: string,
descriptor: PropertyDescriptor,
) {
const originalMethod = descriptor.value; const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) { descriptor.value = async function (...args: any[]) {
@@ -387,16 +370,11 @@ export function Cacheable(ttl: number = 300) {
import { Response } from "express"; import { Response } from "express";
export class ApiResponse { export class ApiResponse {
static success<T>( static success<T>(res: Response, data: T, message?: string, statusCode = 200) {
res: Response,
data: T,
message?: string,
statusCode = 200,
) {
return res.status(statusCode).json({ return res.status(statusCode).json({
status: "success", status: "success",
message, message,
data, data
}); });
} }
@@ -404,17 +382,11 @@ export class ApiResponse {
return res.status(statusCode).json({ return res.status(statusCode).json({
status: "error", status: "error",
message, message,
...(errors && { errors }), ...(errors && { errors })
}); });
} }
static paginated<T>( static paginated<T>(res: Response, data: T[], page: number, limit: number, total: number) {
res: Response,
data: T[],
page: number,
limit: number,
total: number,
) {
return res.json({ return res.json({
status: "success", status: "success",
data, data,
@@ -422,8 +394,8 @@ export class ApiResponse {
page, page,
limit, limit,
total, total,
pages: Math.ceil(total / limit), pages: Math.ceil(total / limit)
}, }
}); });
} }
} }
+13 -6
View File
@@ -12,6 +12,7 @@ date_added: "2026-02-27"
> **Learn to THINK, not memorize code patterns.** > **Learn to THINK, not memorize code patterns.**
## When to Use ## When to Use
Use this skill when making Node.js architecture decisions, choosing frameworks, designing async patterns, or applying security and deployment best practices. Use this skill when making Node.js architecture decisions, choosing frameworks, designing async patterns, or applying security and deployment best practices.
--- ---
@@ -52,7 +53,7 @@ What are you building?
### Comparison Principles ### Comparison Principles
| Factor | Hono | Fastify | Express | | Factor | Hono | Fastify | Express |
|--------|------|---------|---------| | ------------------ | ---------------- | ----------- | ---------------- |
| **Best for** | Edge, serverless | Performance | Legacy, learning | | **Best for** | Edge, serverless | Performance | Legacy, learning |
| **Cold start** | Fastest | Fast | Moderate | | **Cold start** | Fastest | Fast | Moderate |
| **Ecosystem** | Growing | Good | Largest | | **Ecosystem** | Growing | Good | Largest |
@@ -60,6 +61,7 @@ What are you building?
| **Learning curve** | Low | Medium | Low | | **Learning curve** | Low | Medium | Low |
### Selection Questions to Ask: ### Selection Questions to Ask:
1. What's the deployment target? 1. What's the deployment target?
2. Is cold start time critical? 2. Is cold start time critical?
3. Does team have existing experience? 3. Does team have existing experience?
@@ -96,7 +98,7 @@ CommonJS (require)
### Runtime Selection ### Runtime Selection
| Runtime | Best For | | Runtime | Best For |
|---------|----------| | ----------- | ----------------------------------- |
| **Node.js** | General purpose, largest ecosystem | | **Node.js** | General purpose, largest ecosystem |
| **Bun** | Performance, built-in bundler | | **Bun** | Performance, built-in bundler |
| **Deno** | Security-first, built-in TypeScript | | **Deno** | Security-first, built-in TypeScript |
@@ -127,11 +129,13 @@ Request Flow:
``` ```
### Why This Matters: ### Why This Matters:
- **Testability**: Mock layers independently - **Testability**: Mock layers independently
- **Flexibility**: Swap database without touching business logic - **Flexibility**: Swap database without touching business logic
- **Clarity**: Each layer has single responsibility - **Clarity**: Each layer has single responsibility
### When to Simplify: ### When to Simplify:
- Small scripts → Single file OK - Small scripts → Single file OK
- Prototypes → Less structure acceptable - Prototypes → Less structure acceptable
- Always ask: "Will this grow?" - Always ask: "Will this grow?"
@@ -169,7 +173,7 @@ Logs get:
### Status Code Selection ### Status Code Selection
| Situation | Status | When | | Situation | Status | When |
|-----------|--------|------| | ------------- | ------ | ------------------------------------ |
| Bad input | 400 | Client sent invalid data | | Bad input | 400 | Client sent invalid data |
| No auth | 401 | Missing or invalid credentials | | No auth | 401 | Missing or invalid credentials |
| No permission | 403 | Valid auth, but not allowed | | No permission | 403 | Valid auth, but not allowed |
@@ -185,7 +189,7 @@ Logs get:
### When to Use Each ### When to Use Each
| Pattern | Use When | | Pattern | Use When |
|---------|----------| | -------------------- | ------------------------------- |
| `async/await` | Sequential async operations | | `async/await` | Sequential async operations |
| `Promise.all` | Parallel independent operations | | `Promise.all` | Parallel independent operations |
| `Promise.allSettled` | Parallel where some can fail | | `Promise.allSettled` | Parallel where some can fail |
@@ -230,7 +234,7 @@ Where to validate:
### Validation Library Selection ### Validation Library Selection
| Library | Best For | | Library | Best For |
|---------|----------| | ----------- | ------------------------------- |
| **Zod** | TypeScript first, inference | | **Zod** | TypeScript first, inference |
| **Valibot** | Smaller bundle (tree-shakeable) | | **Valibot** | Smaller bundle (tree-shakeable) |
| **ArkType** | Performance critical | | **ArkType** | Performance critical |
@@ -278,7 +282,7 @@ Trust nothing:
### Test Strategy Selection ### Test Strategy Selection
| Type | Purpose | Tools | | Type | Purpose | Tools |
|------|---------|-------| | --------------- | -------------- | ----------------- |
| **Unit** | Business logic | node:test, Vitest | | **Unit** | Business logic | node:test, Vitest |
| **Integration** | API endpoints | Supertest | | **Integration** | API endpoints | Supertest |
| **E2E** | Full flows | Playwright | | **E2E** | Full flows | Playwright |
@@ -304,6 +308,7 @@ node --test src/**/*.test.ts
## 9. Anti-Patterns to Avoid ## 9. Anti-Patterns to Avoid
### ❌ DON'T: ### ❌ DON'T:
- Use Express for new edge projects (use Hono) - Use Express for new edge projects (use Hono)
- Use sync methods in production code - Use sync methods in production code
- Put business logic in controllers - Put business logic in controllers
@@ -313,6 +318,7 @@ node --test src/**/*.test.ts
- Block event loop with CPU work - Block event loop with CPU work
### ✅ DO: ### ✅ DO:
- Choose framework based on context - Choose framework based on context
- Ask user for preferences when unclear - Ask user for preferences when unclear
- Use layered architecture for growing projects - Use layered architecture for growing projects
@@ -338,6 +344,7 @@ Before implementing:
> **Remember**: Node.js best practices are about decision-making, not memorizing patterns. Every project deserves fresh consideration based on its requirements. > **Remember**: Node.js best practices are about decision-making, not memorizing patterns. Every project deserves fresh consideration based on its requirements.
## Limitations ## Limitations
- Use this skill only when the task clearly matches the scope described above. - Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review. - Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing. - Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
@@ -335,7 +335,7 @@ class APIClient<Config extends Record<string, Record<HTTPMethod, any>>> {
{ {
params: ExtractParams<Config[Path][Method]>; params: ExtractParams<Config[Path][Method]>;
body?: ExtractBody<Config[Path][Method]>; body?: ExtractBody<Config[Path][Method]>;
}, }
] ]
): Promise<ExtractResponse<Config[Path][Method]>> { ): Promise<ExtractResponse<Config[Path][Method]>> {
// Implementation here // Implementation here
@@ -350,12 +350,12 @@ const users = await api.request("/users", "GET");
// Type: User[] // Type: User[]
const newUser = await api.request("/users", "POST", { const newUser = await api.request("/users", "POST", {
body: { name: "John", email: "john@example.com" }, body: { name: "John", email: "john@example.com" }
}); });
// Type: User // Type: User
const user = await api.request("/users/:id", "GET", { const user = await api.request("/users/:id", "GET", {
params: { id: "123" }, params: { id: "123" }
}); });
// Type: User // Type: User
``` ```
@@ -376,11 +376,7 @@ type OptionalKeys<T> = {
}[keyof T]; }[keyof T];
type IsComplete<T, S> = type IsComplete<T, S> =
RequiredKeys<T> extends keyof S RequiredKeys<T> extends keyof S ? (S[RequiredKeys<T>] extends undefined ? false : true) : false;
? S[RequiredKeys<T>] extends undefined
? false
: true
: false;
class Builder<T, S extends BuilderState<T> = {}> { class Builder<T, S extends BuilderState<T> = {}> {
private state: S = {} as S; private state: S = {} as S;
@@ -404,11 +400,7 @@ interface User {
const builder = new Builder<User>(); const builder = new Builder<User>();
const user = builder const user = builder.set("id", "1").set("name", "John").set("email", "john@example.com").build(); // OK: all required fields set
.set("id", "1")
.set("name", "John")
.set("email", "john@example.com")
.build(); // OK: all required fields set
// const incomplete = builder // const incomplete = builder
// .set("id", "1") // .set("id", "1")
@@ -515,24 +507,24 @@ const validator = new FormValidator<LoginForm>({
email: [ email: [
{ {
validate: (v) => v.includes("@"), validate: (v) => v.includes("@"),
message: "Email must contain @", message: "Email must contain @"
}, },
{ {
validate: (v) => v.length > 0, validate: (v) => v.length > 0,
message: "Email is required", message: "Email is required"
}, }
], ],
password: [ password: [
{ {
validate: (v) => v.length >= 8, validate: (v) => v.length >= 8,
message: "Password must be at least 8 characters", message: "Password must be at least 8 characters"
}, }
], ]
}); });
const errors = validator.validate({ const errors = validator.validate({
email: "invalid", email: "invalid",
password: "short", password: "short"
}); });
// Type: { email?: string[]; password?: string[]; } | null // Type: { email?: string[]; password?: string[]; } | null
``` ```
@@ -586,9 +578,7 @@ type Event =
function reducer(state: State, event: Event): State { function reducer(state: State, event: Event): State {
switch (state.type) { switch (state.type) {
case "idle": case "idle":
return event.type === "FETCH" return event.type === "FETCH" ? { type: "fetching", requestId: event.requestId } : state;
? { type: "fetching", requestId: event.requestId }
: state;
case "fetching": case "fetching":
if (event.type === "SUCCESS") { if (event.type === "SUCCESS") {
return { type: "success", data: event.data }; return { type: "success", data: event.data };
@@ -634,10 +624,7 @@ function isString(value: unknown): value is string {
return typeof value === "string"; return typeof value === "string";
} }
function isArrayOf<T>( function isArrayOf<T>(value: unknown, guard: (item: unknown) => item is T): value is T[] {
value: unknown,
guard: (item: unknown) => item is T,
): value is T[] {
return Array.isArray(value) && value.every(guard); return Array.isArray(value) && value.every(guard);
} }
@@ -681,11 +668,7 @@ function processValue(value: unknown) {
```typescript ```typescript
// Type assertion tests // Type assertion tests
type AssertEqual<T, U> = [T] extends [U] type AssertEqual<T, U> = [T] extends [U] ? ([U] extends [T] ? true : false) : false;
? [U] extends [T]
? true
: false
: false;
type Test1 = AssertEqual<string, string>; // true type Test1 = AssertEqual<string, string>; // true
type Test2 = AssertEqual<string, number>; // false type Test2 = AssertEqual<string, number>; // false
+1 -1
View File
@@ -90,7 +90,7 @@ Comprehensive schema validation guide for Zod in TypeScript applications, design
This document was compiled from individual reference files. For detailed editing or extension: This document was compiled from individual reference files. For detailed editing or extension:
| File | Description | | File | Description |
|------|-------------| | -------------------------------------------------------------- | ---------------------------------------- |
| [references/_sections.md](references/_sections.md) | Category definitions and impact ordering | | [references/_sections.md](references/_sections.md) | Category definitions and impact ordering |
| [assets/templates/_template.md](assets/templates/_template.md) | Template for creating new rules | | [assets/templates/_template.md](assets/templates/_template.md) | Template for creating new rules |
| [SKILL.md](SKILL.md) | Quick reference entry point | | [SKILL.md](SKILL.md) | Quick reference entry point |
+1 -1
View File
@@ -53,7 +53,7 @@ zod/
## Rule Categories ## Rule Categories
| Priority | Category | Rules | Impact | | Priority | Category | Rules | Impact |
|----------|----------|-------|--------| | -------- | ------------------------ | ----- | ----------- |
| 1 | Schema Definition | 6 | CRITICAL | | 1 | Schema Definition | 6 | CRITICAL |
| 2 | Parsing & Validation | 6 | CRITICAL | | 2 | Parsing & Validation | 6 | CRITICAL |
| 3 | Type Inference | 5 | HIGH | | 3 | Type Inference | 5 | HIGH |
+2 -1
View File
@@ -10,6 +10,7 @@ Comprehensive schema validation guide for Zod in TypeScript applications. Contai
## When to Apply ## When to Apply
Reference these guidelines when: Reference these guidelines when:
- Writing new Zod schemas - Writing new Zod schemas
- Choosing between parse() and safeParse() - Choosing between parse() and safeParse()
- Implementing type inference with z.infer - Implementing type inference with z.infer
@@ -22,7 +23,7 @@ Reference these guidelines when:
## Rule Categories by Priority ## Rule Categories by Priority
| Priority | Category | Impact | Prefix | | Priority | Category | Impact | Prefix |
|----------|----------|--------|--------| | -------- | ------------------------ | ----------- | ---------- |
| 1 | Schema Definition | CRITICAL | `schema-` | | 1 | Schema Definition | CRITICAL | `schema-` |
| 2 | Parsing & Validation | CRITICAL | `parse-` | | 2 | Parsing & Validation | CRITICAL | `parse-` |
| 3 | Type Inference | HIGH | `type-` | | 3 | Type Inference | HIGH | `type-` |
@@ -24,6 +24,7 @@ tags: section-prefix, technique, tool, related-concepts
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Exception 1 - Exception 1
- Exception 2 - Exception 2
@@ -12,23 +12,23 @@ When you need an object that satisfies multiple schemas simultaneously (like com
**Incorrect (manual combination):** **Incorrect (manual combination):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const timestampsSchema = z.object({ const timestampsSchema = z.object({
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}) });
const softDeleteSchema = z.object({ const softDeleteSchema = z.object({
deletedAt: z.date().nullable(), deletedAt: z.date().nullable(),
deletedBy: z.string().nullable(), deletedBy: z.string().nullable()
}) });
const userSchema = z.object({ const userSchema = z.object({
id: z.string(), id: z.string(),
name: z.string(), name: z.string(),
email: z.string().email(), email: z.string().email()
}) });
// Manual combination - verbose and error-prone // Manual combination - verbose and error-prone
const fullUserSchema = z.object({ const fullUserSchema = z.object({
@@ -38,43 +38,41 @@ const fullUserSchema = z.object({
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
deletedAt: z.date().nullable(), deletedAt: z.date().nullable(),
deletedBy: z.string().nullable(), deletedBy: z.string().nullable()
}) });
``` ```
**Correct (using intersection):** **Correct (using intersection):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const timestampsSchema = z.object({ const timestampsSchema = z.object({
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}) });
const softDeleteSchema = z.object({ const softDeleteSchema = z.object({
deletedAt: z.date().nullable(), deletedAt: z.date().nullable(),
deletedBy: z.string().nullable(), deletedBy: z.string().nullable()
}) });
const userSchema = z.object({ const userSchema = z.object({
id: z.string(), id: z.string(),
name: z.string(), name: z.string(),
email: z.string().email(), email: z.string().email()
}) });
// Using .and() for intersection // Using .and() for intersection
const fullUserSchema = userSchema const fullUserSchema = userSchema.and(timestampsSchema).and(softDeleteSchema);
.and(timestampsSchema)
.and(softDeleteSchema)
// Or using z.intersection() // Or using z.intersection()
const fullUserSchema2 = z.intersection( const fullUserSchema2 = z.intersection(
z.intersection(userSchema, timestampsSchema), z.intersection(userSchema, timestampsSchema),
softDeleteSchema softDeleteSchema
) );
type FullUser = z.infer<typeof fullUserSchema> type FullUser = z.infer<typeof fullUserSchema>;
// { // {
// id: string; // id: string;
// name: string; // name: string;
@@ -92,51 +90,52 @@ type FullUser = z.infer<typeof fullUserSchema>
// Reusable mixins // Reusable mixins
const auditable = z.object({ const auditable = z.object({
createdBy: z.string(), createdBy: z.string(),
updatedBy: z.string(), updatedBy: z.string()
}) });
const versioned = z.object({ const versioned = z.object({
version: z.number().int().positive(), version: z.number().int().positive()
}) });
const tagged = z.object({ const tagged = z.object({
tags: z.array(z.string()), tags: z.array(z.string())
}) });
// Apply mixins to any schema // Apply mixins to any schema
function withAudit<T extends z.ZodRawShape>(schema: z.ZodObject<T>) { function withAudit<T extends z.ZodRawShape>(schema: z.ZodObject<T>) {
return schema.and(auditable).and(timestampsSchema) return schema.and(auditable).and(timestampsSchema);
} }
function withVersioning<T extends z.ZodRawShape>(schema: z.ZodObject<T>) { function withVersioning<T extends z.ZodRawShape>(schema: z.ZodObject<T>) {
return schema.and(versioned) return schema.and(versioned);
} }
// Usage // Usage
const documentSchema = z.object({ const documentSchema = z.object({
id: z.string(), id: z.string(),
title: z.string(), title: z.string(),
content: z.string(), content: z.string()
}) });
const fullDocumentSchema = withAudit(withVersioning(documentSchema)) const fullDocumentSchema = withAudit(withVersioning(documentSchema));
``` ```
**Intersection vs Merge:** **Intersection vs Merge:**
```typescript ```typescript
// .merge() - replaces fields from first with second // .merge() - replaces fields from first with second
const a = z.object({ x: z.string(), y: z.number() }) const a = z.object({ x: z.string(), y: z.number() });
const b = z.object({ y: z.string() }) // y is string, not number const b = z.object({ y: z.string() }); // y is string, not number
a.merge(b) // { x: string, y: string } - b's y wins a.merge(b); // { x: string, y: string } - b's y wins
// .and() - requires fields to be compatible // .and() - requires fields to be compatible
// If both have y with different types, intersection fails at runtime // If both have y with different types, intersection fails at runtime
a.and(b) // Validation will fail - y can't be both number and string a.and(b); // Validation will fail - y can't be both number and string
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When schemas have overlapping fields with different types (use merge) - When schemas have overlapping fields with different types (use merge)
- When you need to override fields (use extend) - When you need to override fields (use extend)
- Simple cases where extend works fine - Simple cases where extend works fine
@@ -12,50 +12,50 @@ TypeScript can't infer recursive Zod schema types automatically. Use `z.lazy()`
**Incorrect (direct self-reference):** **Incorrect (direct self-reference):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// This fails - categorySchema used before it's defined // This fails - categorySchema used before it's defined
const categorySchema = z.object({ const categorySchema = z.object({
id: z.string(), id: z.string(),
name: z.string(), name: z.string(),
children: z.array(categorySchema), // Error: Block-scoped variable used before declaration children: z.array(categorySchema) // Error: Block-scoped variable used before declaration
}) });
``` ```
**Correct (using z.lazy with type annotation):** **Correct (using z.lazy with type annotation):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Define the type manually // Define the type manually
interface Category { interface Category {
id: string id: string;
name: string name: string;
children: Category[] children: Category[];
} }
// Use z.lazy() to defer schema reference // Use z.lazy() to defer schema reference
const categorySchema: z.ZodType<Category> = z.object({ const categorySchema: z.ZodType<Category> = z.object({
id: z.string(), id: z.string(),
name: z.string(), name: z.string(),
children: z.lazy(() => z.array(categorySchema)), children: z.lazy(() => z.array(categorySchema))
}) });
// Now it works // Now it works
const tree = categorySchema.parse({ const tree = categorySchema.parse({
id: '1', id: "1",
name: 'Electronics', name: "Electronics",
children: [ children: [
{ {
id: '2', id: "2",
name: 'Phones', name: "Phones",
children: [ children: [
{ id: '3', name: 'iPhones', children: [] }, { id: "3", name: "iPhones", children: [] },
{ id: '4', name: 'Android', children: [] }, { id: "4", name: "Android", children: [] }
], ]
}, }
], ]
}) });
``` ```
**Common recursive patterns:** **Common recursive patterns:**
@@ -63,56 +63,50 @@ const tree = categorySchema.parse({
```typescript ```typescript
// Comments with replies // Comments with replies
interface Comment { interface Comment {
id: string id: string;
content: string content: string;
author: string author: string;
replies: Comment[] replies: Comment[];
} }
const commentSchema: z.ZodType<Comment> = z.object({ const commentSchema: z.ZodType<Comment> = z.object({
id: z.string(), id: z.string(),
content: z.string(), content: z.string(),
author: z.string(), author: z.string(),
replies: z.lazy(() => z.array(commentSchema)), replies: z.lazy(() => z.array(commentSchema))
}) });
// Binary tree // Binary tree
interface TreeNode { interface TreeNode {
value: number value: number;
left: TreeNode | null left: TreeNode | null;
right: TreeNode | null right: TreeNode | null;
} }
const treeNodeSchema: z.ZodType<TreeNode> = z.object({ const treeNodeSchema: z.ZodType<TreeNode> = z.object({
value: z.number(), value: z.number(),
left: z.lazy(() => treeNodeSchema.nullable()), left: z.lazy(() => treeNodeSchema.nullable()),
right: z.lazy(() => treeNodeSchema.nullable()), right: z.lazy(() => treeNodeSchema.nullable())
}) });
// Nested menu structure // Nested menu structure
interface MenuItem { interface MenuItem {
label: string label: string;
href?: string href?: string;
children?: MenuItem[] children?: MenuItem[];
} }
const menuItemSchema: z.ZodType<MenuItem> = z.object({ const menuItemSchema: z.ZodType<MenuItem> = z.object({
label: z.string(), label: z.string(),
href: z.string().url().optional(), href: z.string().url().optional(),
children: z.lazy(() => z.array(menuItemSchema)).optional(), children: z.lazy(() => z.array(menuItemSchema)).optional()
}) });
``` ```
**JSON Schema (any valid JSON):** **JSON Schema (any valid JSON):**
```typescript ```typescript
type JSONValue = type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue };
| string
| number
| boolean
| null
| JSONValue[]
| { [key: string]: JSONValue }
const jsonValueSchema: z.ZodType<JSONValue> = z.lazy(() => const jsonValueSchema: z.ZodType<JSONValue> = z.lazy(() =>
z.union([ z.union([
@@ -121,9 +115,9 @@ const jsonValueSchema: z.ZodType<JSONValue> = z.lazy(() =>
z.boolean(), z.boolean(),
z.null(), z.null(),
z.array(jsonValueSchema), z.array(jsonValueSchema),
z.record(jsonValueSchema), z.record(jsonValueSchema)
]) ])
) );
``` ```
**Performance consideration:** **Performance consideration:**
@@ -137,6 +131,7 @@ const jsonValueSchema: z.ZodType<JSONValue> = z.lazy(() =>
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Non-recursive schemas (lazy adds unnecessary indirection) - Non-recursive schemas (lazy adds unnecessary indirection)
- When you can flatten the structure instead - When you can flatten the structure instead
+27 -26
View File
@@ -12,16 +12,16 @@ When data needs to pass through multiple validation stages (coerce string to num
**Incorrect (unclear transformation chain):** **Incorrect (unclear transformation chain):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// All transforms in one long chain - hard to understand stages // All transforms in one long chain - hard to understand stages
const priceSchema = z const priceSchema = z
.string() .string()
.transform((s) => parseFloat(s.replace(/[$,]/g, ''))) .transform((s) => parseFloat(s.replace(/[$,]/g, "")))
.refine((n) => !isNaN(n), 'Invalid number') .refine((n) => !isNaN(n), "Invalid number")
.refine((n) => n >= 0, 'Must be positive') .refine((n) => n >= 0, "Must be positive")
.refine((n) => n <= 1000000, 'Too large') .refine((n) => n <= 1000000, "Too large")
.transform((n) => Math.round(n * 100)) .transform((n) => Math.round(n * 100));
// What type is n at each stage? Hard to tell // What type is n at each stage? Hard to tell
``` ```
@@ -29,24 +29,24 @@ const priceSchema = z
**Correct (using pipe for clear stages):** **Correct (using pipe for clear stages):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Stage 1: Coerce string to number // Stage 1: Coerce string to number
const parsePrice = z.string().transform((s) => { const parsePrice = z.string().transform((s) => {
const cleaned = s.replace(/[$,]/g, '') const cleaned = s.replace(/[$,]/g, "");
const parsed = parseFloat(cleaned) const parsed = parseFloat(cleaned);
if (isNaN(parsed)) throw new Error('Invalid number') if (isNaN(parsed)) throw new Error("Invalid number");
return parsed return parsed;
}) });
// Stage 2: Validate number constraints // Stage 2: Validate number constraints
const validPrice = z.number().min(0, 'Must be positive').max(1000000, 'Too large') const validPrice = z.number().min(0, "Must be positive").max(1000000, "Too large");
// Stage 3: Transform to cents // Stage 3: Transform to cents
const centsPrice = z.number().transform((n) => Math.round(n * 100)) const centsPrice = z.number().transform((n) => Math.round(n * 100));
// Pipe them together - clear data flow // Pipe them together - clear data flow
const priceSchema = parsePrice.pipe(validPrice).pipe(centsPrice) const priceSchema = parsePrice.pipe(validPrice).pipe(centsPrice);
// Type at each stage is clear: // Type at each stage is clear:
// string -> number (parsePrice) // string -> number (parsePrice)
@@ -58,12 +58,12 @@ const priceSchema = parsePrice.pipe(validPrice).pipe(centsPrice)
```typescript ```typescript
// Without pipe - validation runs on raw input // Without pipe - validation runs on raw input
const schema1 = z.coerce.number().min(1) const schema1 = z.coerce.number().min(1);
schema1.parse('') // Passes! Empty string coerces to 0, but then... wait, 0 < 1 schema1.parse(""); // Passes! Empty string coerces to 0, but then... wait, 0 < 1
// With pipe - validation runs on coerced value // With pipe - validation runs on coerced value
const schema2 = z.coerce.number().pipe(z.number().min(1)) const schema2 = z.coerce.number().pipe(z.number().min(1));
schema2.parse('') // Fails correctly: 0 is less than 1 schema2.parse(""); // Fails correctly: 0 is less than 1
``` ```
**Complex data transformation:** **Complex data transformation:**
@@ -75,7 +75,7 @@ schema2.parse('') // Fails correctly: 0 is less than 1
const emailArraySchema = z const emailArraySchema = z
.string() .string()
// Stage 1: Split CSV // Stage 1: Split CSV
.transform((s) => s.split(',').map((e) => e.trim())) .transform((s) => s.split(",").map((e) => e.trim()))
// Stage 2: Validate as email array // Stage 2: Validate as email array
.pipe(z.array(z.string().email())) .pipe(z.array(z.string().email()))
// Stage 3: Transform to objects // Stage 3: Transform to objects
@@ -83,12 +83,12 @@ const emailArraySchema = z
z.array(z.string()).transform((emails) => z.array(z.string()).transform((emails) =>
emails.map((email) => ({ emails.map((email) => ({
address: email.toLowerCase(), address: email.toLowerCase(),
domain: email.split('@')[1], domain: email.split("@")[1]
})) }))
) )
) );
emailArraySchema.parse('John@Example.com, jane@test.com') emailArraySchema.parse("John@Example.com, jane@test.com");
// [ // [
// { address: 'john@example.com', domain: 'Example.com' }, // { address: 'john@example.com', domain: 'Example.com' },
// { address: 'jane@test.com', domain: 'test.com' } // { address: 'jane@test.com', domain: 'test.com' }
@@ -98,15 +98,16 @@ emailArraySchema.parse('John@Example.com, jane@test.com')
**Type inference with pipe:** **Type inference with pipe:**
```typescript ```typescript
const schema = z.string().pipe(z.coerce.number()).pipe(z.number().positive()) const schema = z.string().pipe(z.coerce.number()).pipe(z.number().positive());
type Input = z.input<typeof schema> // string type Input = z.input<typeof schema>; // string
type Output = z.output<typeof schema> // number type Output = z.output<typeof schema>; // number
// Each pipe stage has clear input/output types // Each pipe stage has clear input/output types
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Simple single-stage validation (adds unnecessary complexity) - Simple single-stage validation (adds unnecessary complexity)
- When `.refine()` chain is sufficient and readable - When `.refine()` chain is sufficient and readable
@@ -12,70 +12,70 @@ When incoming data needs normalization before validation (trimming whitespace, p
**Incorrect (validation fails on unnormalized data):** **Incorrect (validation fails on unnormalized data):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userSchema = z.object({ const userSchema = z.object({
name: z.string().min(1), name: z.string().min(1),
email: z.string().email(), email: z.string().email(),
config: z.object({ config: z.object({
theme: z.string(), theme: z.string()
}), })
}) });
// Raw form data // Raw form data
const formData = { const formData = {
name: ' John Doe ', // Has whitespace name: " John Doe ", // Has whitespace
email: 'JOHN@EXAMPLE.COM', // Uppercase email: "JOHN@EXAMPLE.COM", // Uppercase
config: '{"theme": "dark"}', // JSON string, not object config: '{"theme": "dark"}' // JSON string, not object
} };
userSchema.parse(formData) userSchema.parse(formData);
// ZodError: Expected object, received string at "config" // ZodError: Expected object, received string at "config"
``` ```
**Correct (using preprocess):** **Correct (using preprocess):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Preprocess normalizes before validation // Preprocess normalizes before validation
const trimmedString = z.preprocess( const trimmedString = z.preprocess(
(val) => (typeof val === 'string' ? val.trim() : val), (val) => (typeof val === "string" ? val.trim() : val),
z.string() z.string()
) );
const lowercaseEmail = z.preprocess( const lowercaseEmail = z.preprocess(
(val) => (typeof val === 'string' ? val.toLowerCase().trim() : val), (val) => (typeof val === "string" ? val.toLowerCase().trim() : val),
z.string().email() z.string().email()
) );
const jsonObject = z.preprocess( const jsonObject = z.preprocess(
(val) => { (val) => {
if (typeof val === 'string') { if (typeof val === "string") {
try { try {
return JSON.parse(val) return JSON.parse(val);
} catch { } catch {
return val // Let Zod report the error return val; // Let Zod report the error
} }
} }
return val return val;
}, },
z.object({ theme: z.string() }) z.object({ theme: z.string() })
) );
const userSchema = z.object({ const userSchema = z.object({
name: trimmedString.pipe(z.string().min(1)), name: trimmedString.pipe(z.string().min(1)),
email: lowercaseEmail, email: lowercaseEmail,
config: jsonObject, config: jsonObject
}) });
const formData = { const formData = {
name: ' John Doe ', name: " John Doe ",
email: 'JOHN@EXAMPLE.COM', email: "JOHN@EXAMPLE.COM",
config: '{"theme": "dark"}', config: '{"theme": "dark"}'
} };
const user = userSchema.parse(formData) const user = userSchema.parse(formData);
// { name: 'John Doe', email: 'john@example.com', config: { theme: 'dark' } } // { name: 'John Doe', email: 'john@example.com', config: { theme: 'dark' } }
``` ```
@@ -84,37 +84,31 @@ const user = userSchema.parse(formData)
```typescript ```typescript
// Trim all strings // Trim all strings
const trimmedString = z.preprocess( const trimmedString = z.preprocess(
(val) => (typeof val === 'string' ? val.trim() : val), (val) => (typeof val === "string" ? val.trim() : val),
z.string() z.string()
) );
// Parse numeric strings // Parse numeric strings
const numericString = z.preprocess( const numericString = z.preprocess(
(val) => (typeof val === 'string' ? Number(val) : val), (val) => (typeof val === "string" ? Number(val) : val),
z.number() z.number()
) );
// Parse boolean-like values // Parse boolean-like values
const booleanLike = z.preprocess( const booleanLike = z.preprocess((val) => {
(val) => { if (val === "true" || val === "1" || val === 1) return true;
if (val === 'true' || val === '1' || val === 1) return true if (val === "false" || val === "0" || val === 0) return false;
if (val === 'false' || val === '0' || val === 0) return false return val;
return val }, z.boolean());
},
z.boolean()
)
// Parse date strings // Parse date strings
const dateString = z.preprocess( const dateString = z.preprocess((val) => (typeof val === "string" ? new Date(val) : val), z.date());
(val) => (typeof val === 'string' ? new Date(val) : val),
z.date()
)
// Split comma-separated strings into arrays // Split comma-separated strings into arrays
const csvArray = z.preprocess( const csvArray = z.preprocess(
(val) => (typeof val === 'string' ? val.split(',').map(s => s.trim()) : val), (val) => (typeof val === "string" ? val.split(",").map((s) => s.trim()) : val),
z.array(z.string()) z.array(z.string())
) );
``` ```
**Preprocess vs Transform:** **Preprocess vs Transform:**
@@ -122,11 +116,11 @@ const csvArray = z.preprocess(
```typescript ```typescript
// preprocess() runs BEFORE type checking // preprocess() runs BEFORE type checking
// Use for: Normalizing input format before validation // Use for: Normalizing input format before validation
z.preprocess(val => String(val).trim(), z.string().min(1)) z.preprocess((val) => String(val).trim(), z.string().min(1));
// transform() runs AFTER type checking // transform() runs AFTER type checking
// Use for: Converting validated data to different format // Use for: Converting validated data to different format
z.string().transform(s => s.toUpperCase()) z.string().transform((s) => s.toUpperCase());
// Order of operations: // Order of operations:
// 1. preprocess receives raw unknown input // 1. preprocess receives raw unknown input
@@ -135,6 +129,7 @@ z.string().transform(s => s.toUpperCase())
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When `.coerce` methods handle the conversion (simpler) - When `.coerce` methods handle the conversion (simpler)
- When transformation should happen after validation (use transform) - When transformation should happen after validation (use transform)
- When normalization could hide validation errors - When normalization could hide validation errors
@@ -13,99 +13,103 @@ When the same schema pattern appears in multiple places, extract it into a share
```typescript ```typescript
// api/users.ts // api/users.ts
import { z } from 'zod' import { z } from "zod";
const userSchema = z.object({ const userSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
email: z.string().email(), email: z.string().email(),
name: z.string().min(1), name: z.string().min(1),
createdAt: z.date(), createdAt: z.date()
}) });
// api/orders.ts // api/orders.ts
import { z } from 'zod' import { z } from "zod";
const orderSchema = z.object({ const orderSchema = z.object({
id: z.string().uuid(), // Duplicated id: z.string().uuid(), // Duplicated
userId: z.string().uuid(), // Same pattern userId: z.string().uuid(), // Same pattern
items: z.array(z.object({ items: z.array(
z.object({
productId: z.string().uuid(), // Duplicated productId: z.string().uuid(), // Duplicated
quantity: z.number().int().positive(), quantity: z.number().int().positive()
})), })
createdAt: z.date(), // Duplicated ),
}) createdAt: z.date() // Duplicated
});
// api/comments.ts // api/comments.ts
import { z } from 'zod' import { z } from "zod";
const commentSchema = z.object({ const commentSchema = z.object({
id: z.string().uuid(), // Same duplication id: z.string().uuid(), // Same duplication
userId: z.string().uuid(), userId: z.string().uuid(),
content: z.string().min(1), content: z.string().min(1),
createdAt: z.date(), // Inconsistency risk createdAt: z.date() // Inconsistency risk
}) });
``` ```
**Correct (shared schema modules):** **Correct (shared schema modules):**
```typescript ```typescript
// schemas/common.ts // schemas/common.ts
import { z } from 'zod' import { z } from "zod";
// Reusable ID types // Reusable ID types
export const uuid = z.string().uuid() export const uuid = z.string().uuid();
export type UUID = z.infer<typeof uuid> export type UUID = z.infer<typeof uuid>;
// Timestamps // Timestamps
export const timestamps = z.object({ export const timestamps = z.object({
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}) });
// Base entity with ID // Base entity with ID
export const baseEntity = z.object({ export const baseEntity = z
id: uuid, .object({
}).merge(timestamps) id: uuid
})
.merge(timestamps);
export type BaseEntity = z.infer<typeof baseEntity> export type BaseEntity = z.infer<typeof baseEntity>;
// Pagination // Pagination
export const paginationParams = z.object({ export const paginationParams = z.object({
page: z.coerce.number().int().positive().default(1), page: z.coerce.number().int().positive().default(1),
limit: z.coerce.number().int().min(1).max(100).default(20), limit: z.coerce.number().int().min(1).max(100).default(20)
}) });
``` ```
```typescript ```typescript
// schemas/user.ts // schemas/user.ts
import { z } from 'zod' import { z } from "zod";
import { baseEntity, uuid } from './common' import { baseEntity, uuid } from "./common";
export const userSchema = baseEntity.extend({ export const userSchema = baseEntity.extend({
email: z.string().email(), email: z.string().email(),
name: z.string().min(1), name: z.string().min(1)
}) });
export type User = z.infer<typeof userSchema> export type User = z.infer<typeof userSchema>;
``` ```
```typescript ```typescript
// schemas/order.ts // schemas/order.ts
import { z } from 'zod' import { z } from "zod";
import { baseEntity, uuid } from './common' import { baseEntity, uuid } from "./common";
const orderItemSchema = z.object({ const orderItemSchema = z.object({
productId: uuid, productId: uuid,
quantity: z.number().int().positive(), quantity: z.number().int().positive()
}) });
export const orderSchema = baseEntity.extend({ export const orderSchema = baseEntity.extend({
userId: uuid, userId: uuid,
items: z.array(orderItemSchema).min(1), items: z.array(orderItemSchema).min(1),
total: z.number().positive(), total: z.number().positive()
}) });
export type Order = z.infer<typeof orderSchema> export type Order = z.infer<typeof orderSchema>;
``` ```
**Organizing schema modules:** **Organizing schema modules:**
@@ -121,16 +125,17 @@ schemas/
```typescript ```typescript
// schemas/index.ts // schemas/index.ts
export * from './common' export * from "./common";
export * from './user' export * from "./user";
export * from './order' export * from "./order";
export * from './product' export * from "./product";
// Usage // Usage
import { userSchema, orderSchema, uuid, type User } from '@/schemas' import { userSchema, orderSchema, uuid, type User } from "@/schemas";
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- One-off schemas used only in a single file - One-off schemas used only in a single file
- When schemas look similar but have different semantics (don't over-abstract) - When schemas look similar but have different semantics (don't over-abstract)
@@ -12,31 +12,33 @@ When using `.refine()` for custom validation, return `false` for invalid data in
**Incorrect (throwing in refine):** **Incorrect (throwing in refine):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const passwordSchema = z.object({ const passwordSchema = z
.object({
password: z.string().min(8), password: z.string().min(8),
confirmPassword: z.string(), confirmPassword: z.string()
}).refine((data) => { })
.refine((data) => {
if (data.password !== data.confirmPassword) { if (data.password !== data.confirmPassword) {
// Throwing stops all further validation // Throwing stops all further validation
throw new Error('Passwords do not match') throw new Error("Passwords do not match");
} }
return true return true;
}) });
const formSchema = z.object({ const formSchema = z.object({
email: z.string().email(), email: z.string().email(),
passwords: passwordSchema, passwords: passwordSchema,
terms: z.boolean().refine((v) => v === true, 'Must accept terms'), terms: z.boolean().refine((v) => v === true, "Must accept terms")
}) });
// If passwords don't match, user never learns about other errors // If passwords don't match, user never learns about other errors
formSchema.safeParse({ formSchema.safeParse({
email: 'bad-email', email: "bad-email",
passwords: { password: '12345678', confirmPassword: 'different' }, passwords: { password: "12345678", confirmPassword: "different" },
terms: false, terms: false
}) });
// Only shows: "Passwords do not match" // Only shows: "Passwords do not match"
// Hidden: "Invalid email", "Must accept terms" // Hidden: "Invalid email", "Must accept terms"
``` ```
@@ -44,28 +46,30 @@ formSchema.safeParse({
**Correct (returning false in refine):** **Correct (returning false in refine):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const passwordSchema = z.object({ const passwordSchema = z
.object({
password: z.string().min(8), password: z.string().min(8),
confirmPassword: z.string(), confirmPassword: z.string()
}).refine( })
(data) => data.password === data.confirmPassword, .refine((data) => data.password === data.confirmPassword, {
{ message: 'Passwords do not match', path: ['confirmPassword'] } message: "Passwords do not match",
) path: ["confirmPassword"]
});
const formSchema = z.object({ const formSchema = z.object({
email: z.string().email(), email: z.string().email(),
passwords: passwordSchema, passwords: passwordSchema,
terms: z.boolean().refine((v) => v === true, 'Must accept terms'), terms: z.boolean().refine((v) => v === true, "Must accept terms")
}) });
// All errors are collected // All errors are collected
formSchema.safeParse({ formSchema.safeParse({
email: 'bad-email', email: "bad-email",
passwords: { password: '12345678', confirmPassword: 'different' }, passwords: { password: "12345678", confirmPassword: "different" },
terms: false, terms: false
}) });
// Shows all errors: // Shows all errors:
// - "Invalid email" // - "Invalid email"
// - "Passwords do not match" // - "Passwords do not match"
@@ -80,47 +84,50 @@ const passwordSchema = z.string().superRefine((password, ctx) => {
if (password.length < 8) { if (password.length < 8) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: 'Password must be at least 8 characters', message: "Password must be at least 8 characters"
}) });
} }
if (!/[A-Z]/.test(password)) { if (!/[A-Z]/.test(password)) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: 'Password must contain an uppercase letter', message: "Password must contain an uppercase letter"
}) });
} }
if (!/[0-9]/.test(password)) { if (!/[0-9]/.test(password)) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: 'Password must contain a number', message: "Password must contain a number"
}) });
} }
// Don't return anything - issues are added via ctx // Don't return anything - issues are added via ctx
}) });
passwordSchema.safeParse('weak') passwordSchema.safeParse("weak");
// All three errors reported at once // All three errors reported at once
``` ```
**Correct pattern for async validation:** **Correct pattern for async validation:**
```typescript ```typescript
const schema = z.object({ const schema = z
email: z.string().email(), .object({
}).refine( email: z.string().email()
})
.refine(
async (data) => { async (data) => {
// Return boolean, don't throw // Return boolean, don't throw
const exists = await checkEmailExists(data.email) const exists = await checkEmailExists(data.email);
return !exists return !exists;
}, },
{ message: 'Email already registered', path: ['email'] } { message: "Email already registered", path: ["email"] }
) );
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When you need to abort validation entirely (security issues) - When you need to abort validation entirely (security issues)
- When subsequent validations depend on current check passing - When subsequent validations depend on current check passing
@@ -12,15 +12,15 @@ Zod's default error messages are technical and confusing for end users. Provide
**Incorrect (default error messages):** **Incorrect (default error messages):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const signupSchema = z.object({ const signupSchema = z.object({
email: z.string().email(), email: z.string().email(),
password: z.string().min(8), password: z.string().min(8),
age: z.number().min(18), age: z.number().min(18)
}) });
signupSchema.parse({ email: 'bad', password: '123', age: 15 }) signupSchema.parse({ email: "bad", password: "123", age: 15 });
// ZodError issues: // ZodError issues:
// - "Invalid email" // - "Invalid email"
// - "String must contain at least 8 character(s)" // - "String must contain at least 8 character(s)"
@@ -31,25 +31,31 @@ signupSchema.parse({ email: 'bad', password: '123', age: 15 })
**Correct (custom error messages):** **Correct (custom error messages):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const signupSchema = z.object({ const signupSchema = z.object({
email: z.string({ email: z
required_error: 'Email is required', .string({
invalid_type_error: 'Email must be text', required_error: "Email is required",
}).email('Please enter a valid email address'), invalid_type_error: "Email must be text"
})
.email("Please enter a valid email address"),
password: z.string({ password: z
required_error: 'Password is required', .string({
}).min(8, 'Password must be at least 8 characters'), required_error: "Password is required"
})
.min(8, "Password must be at least 8 characters"),
age: z.number({ age: z
required_error: 'Age is required', .number({
invalid_type_error: 'Age must be a number', required_error: "Age is required",
}).min(18, 'You must be at least 18 years old'), invalid_type_error: "Age must be a number"
}) })
.min(18, "You must be at least 18 years old")
});
signupSchema.parse({ email: 'bad', password: '123', age: 15 }) signupSchema.parse({ email: "bad", password: "123", age: 15 });
// ZodError issues: // ZodError issues:
// - "Please enter a valid email address" // - "Please enter a valid email address"
// - "Password must be at least 8 characters" // - "Password must be at least 8 characters"
@@ -59,19 +65,20 @@ signupSchema.parse({ email: 'bad', password: '123', age: 15 })
**Message types and when they trigger:** **Message types and when they trigger:**
```typescript ```typescript
const schema = z.string({ const schema = z
.string({
// When field is undefined // When field is undefined
required_error: 'This field is required', required_error: "This field is required",
// When field is wrong type (e.g., number instead of string) // When field is wrong type (e.g., number instead of string)
invalid_type_error: 'This field must be text', invalid_type_error: "This field must be text",
// Fallback for any other error // Fallback for any other error
message: 'Invalid value', message: "Invalid value"
}) })
.min(1, 'Cannot be empty') // When length < 1 .min(1, "Cannot be empty") // When length < 1
.max(100, 'Too long') // When length > 100 .max(100, "Too long") // When length > 100
.email('Invalid email format') // When format fails .email("Invalid email format"); // When format fails
``` ```
**Using error maps for consistent messaging:** **Using error maps for consistent messaging:**
@@ -80,38 +87,40 @@ const schema = z.string({
const customErrorMap: z.ZodErrorMap = (issue, ctx) => { const customErrorMap: z.ZodErrorMap = (issue, ctx) => {
// Customize messages by error code // Customize messages by error code
if (issue.code === z.ZodIssueCode.too_small) { if (issue.code === z.ZodIssueCode.too_small) {
if (issue.type === 'string') { if (issue.type === "string") {
return { message: `Must be at least ${issue.minimum} characters` } return { message: `Must be at least ${issue.minimum} characters` };
} }
if (issue.type === 'number') { if (issue.type === "number") {
return { message: `Must be at least ${issue.minimum}` } return { message: `Must be at least ${issue.minimum}` };
} }
} }
if (issue.code === z.ZodIssueCode.invalid_type) { if (issue.code === z.ZodIssueCode.invalid_type) {
if (issue.expected === 'string') { if (issue.expected === "string") {
return { message: 'Must be text' } return { message: "Must be text" };
} }
} }
// Default to Zod's message // Default to Zod's message
return { message: ctx.defaultError } return { message: ctx.defaultError };
} };
// Apply globally // Apply globally
z.setErrorMap(customErrorMap) z.setErrorMap(customErrorMap);
// Or per-schema // Or per-schema
schema.parse(data, { errorMap: customErrorMap }) schema.parse(data, { errorMap: customErrorMap });
``` ```
**Good error message principles:** **Good error message principles:**
- Say what's wrong: "Password too short" not "Invalid password" - Say what's wrong: "Password too short" not "Invalid password"
- Say how to fix it: "at least 8 characters" not just "too short" - Say how to fix it: "at least 8 characters" not just "too short"
- Use user's language: "email" not "string field at path .email" - Use user's language: "email" not "string field at path .email"
- Be specific: "Must be a positive number" not "Invalid" - Be specific: "Must be a positive number" not "Invalid"
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Internal development scripts where technical errors are fine - Internal development scripts where technical errors are fine
- When you'll map errors to user-facing messages in the UI layer - When you'll map errors to user-facing messages in the UI layer
+46 -51
View File
@@ -12,13 +12,13 @@ Hardcoded error messages in English exclude users who speak other languages. Use
**Incorrect (hardcoded English messages):** **Incorrect (hardcoded English messages):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userSchema = z.object({ const userSchema = z.object({
name: z.string().min(1, 'Name is required'), name: z.string().min(1, "Name is required"),
email: z.string().email('Invalid email address'), email: z.string().email("Invalid email address"),
age: z.number().min(18, 'You must be at least 18 years old'), age: z.number().min(18, "You must be at least 18 years old")
}) });
// French users see English errors - poor UX // French users see English errors - poor UX
``` ```
@@ -26,77 +26,74 @@ const userSchema = z.object({
**Correct (localized error messages):** **Correct (localized error messages):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Translation dictionaries // Translation dictionaries
const translations = { const translations = {
en: { en: {
required: 'This field is required', required: "This field is required",
invalidEmail: 'Please enter a valid email address', invalidEmail: "Please enter a valid email address",
tooShort: (min: number) => `Must be at least ${min} characters`, tooShort: (min: number) => `Must be at least ${min} characters`,
tooYoung: (min: number) => `You must be at least ${min} years old`, tooYoung: (min: number) => `You must be at least ${min} years old`
}, },
fr: { fr: {
required: 'Ce champ est obligatoire', required: "Ce champ est obligatoire",
invalidEmail: 'Veuillez entrer une adresse email valide', invalidEmail: "Veuillez entrer une adresse email valide",
tooShort: (min: number) => `Doit contenir au moins ${min} caractères`, tooShort: (min: number) => `Doit contenir au moins ${min} caractères`,
tooYoung: (min: number) => `Vous devez avoir au moins ${min} ans`, tooYoung: (min: number) => `Vous devez avoir au moins ${min} ans`
}, },
es: { es: {
required: 'Este campo es requerido', required: "Este campo es requerido",
invalidEmail: 'Por favor ingrese un correo electrónico válido', invalidEmail: "Por favor ingrese un correo electrónico válido",
tooShort: (min: number) => `Debe tener al menos ${min} caracteres`, tooShort: (min: number) => `Debe tener al menos ${min} caracteres`,
tooYoung: (min: number) => `Debes tener al menos ${min} años`, tooYoung: (min: number) => `Debes tener al menos ${min} años`
}, }
} as const } as const;
type Locale = keyof typeof translations type Locale = keyof typeof translations;
function createErrorMap(locale: Locale): z.ZodErrorMap { function createErrorMap(locale: Locale): z.ZodErrorMap {
const t = translations[locale] const t = translations[locale];
return (issue, ctx) => { return (issue, ctx) => {
switch (issue.code) { switch (issue.code) {
case z.ZodIssueCode.invalid_type: case z.ZodIssueCode.invalid_type:
if (issue.received === 'undefined') { if (issue.received === "undefined") {
return { message: t.required } return { message: t.required };
} }
break break;
case z.ZodIssueCode.invalid_string: case z.ZodIssueCode.invalid_string:
if (issue.validation === 'email') { if (issue.validation === "email") {
return { message: t.invalidEmail } return { message: t.invalidEmail };
} }
break break;
case z.ZodIssueCode.too_small: case z.ZodIssueCode.too_small:
if (issue.type === 'string') { if (issue.type === "string") {
return { message: t.tooShort(issue.minimum as number) } return { message: t.tooShort(issue.minimum as number) };
} }
if (issue.type === 'number') { if (issue.type === "number") {
return { message: t.tooYoung(issue.minimum as number) } return { message: t.tooYoung(issue.minimum as number) };
} }
break break;
} }
return { message: ctx.defaultError } return { message: ctx.defaultError };
} };
} }
// Usage with user's locale // Usage with user's locale
const userLocale: Locale = 'fr' const userLocale: Locale = "fr";
const errorMap = createErrorMap(userLocale) const errorMap = createErrorMap(userLocale);
const userSchema = z.object({ const userSchema = z.object({
name: z.string().min(1), name: z.string().min(1),
email: z.string().email(), email: z.string().email(),
age: z.number().min(18), age: z.number().min(18)
}) });
const result = userSchema.safeParse( const result = userSchema.safeParse({ name: "", email: "bad", age: 15 }, { errorMap });
{ name: '', email: 'bad', age: 15 },
{ errorMap }
)
// French error messages: // French error messages:
// - "Ce champ est obligatoire" // - "Ce champ est obligatoire"
@@ -108,8 +105,8 @@ const result = userSchema.safeParse(
```typescript ```typescript
// At application startup // At application startup
const userLocale = getUserLocale() // From cookie, header, etc. const userLocale = getUserLocale(); // From cookie, header, etc.
z.setErrorMap(createErrorMap(userLocale)) z.setErrorMap(createErrorMap(userLocale));
// All schemas now use localized messages // All schemas now use localized messages
``` ```
@@ -117,28 +114,26 @@ z.setErrorMap(createErrorMap(userLocale))
**With i18n libraries (react-intl, i18next):** **With i18n libraries (react-intl, i18next):**
```typescript ```typescript
import { useIntl } from 'react-intl' import { useIntl } from "react-intl";
function useZodErrorMap() { function useZodErrorMap() {
const intl = useIntl() const intl = useIntl();
return (issue: z.ZodIssue, ctx: z.ErrorMapCtx) => { return (issue: z.ZodIssue, ctx: z.ErrorMapCtx) => {
switch (issue.code) { switch (issue.code) {
case z.ZodIssueCode.too_small: case z.ZodIssueCode.too_small:
return { return {
message: intl.formatMessage( message: intl.formatMessage({ id: "validation.tooShort" }, { min: issue.minimum })
{ id: 'validation.tooShort' }, };
{ min: issue.minimum }
)
}
// ... // ...
} }
return { message: ctx.defaultError } return { message: ctx.defaultError };
} };
} }
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Internal tools used only by your team - Internal tools used only by your team
- Single-language applications - Single-language applications
@@ -12,69 +12,73 @@ When validating nested objects or arrays, `issue.path` tells you exactly where t
**Incorrect (ignoring path information):** **Incorrect (ignoring path information):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const orderSchema = z.object({ const orderSchema = z.object({
customer: z.object({ customer: z.object({
name: z.string().min(1, 'Name required'), name: z.string().min(1, "Name required"),
address: z.object({ address: z.object({
street: z.string().min(1, 'Street required'), street: z.string().min(1, "Street required"),
city: z.string().min(1, 'City required'), city: z.string().min(1, "City required")
})
}), }),
}), items: z.array(
items: z.array(z.object({ z.object({
productId: z.string(), productId: z.string(),
quantity: z.number().positive('Quantity must be positive'), quantity: z.number().positive("Quantity must be positive")
})), })
}) )
});
const result = orderSchema.safeParse({ const result = orderSchema.safeParse({
customer: { name: '', address: { street: '', city: '' } }, customer: { name: "", address: { street: "", city: "" } },
items: [{ productId: 'abc', quantity: -1 }], items: [{ productId: "abc", quantity: -1 }]
}) });
if (!result.success) { if (!result.success) {
// Only showing message, not WHERE the error is // Only showing message, not WHERE the error is
result.error.issues.forEach(issue => { result.error.issues.forEach((issue) => {
console.log(issue.message) // 'Name required', 'Street required', 'Quantity must be positive' console.log(issue.message); // 'Name required', 'Street required', 'Quantity must be positive'
// User: "Which quantity? Which field?" // User: "Which quantity? Which field?"
}) });
} }
``` ```
**Correct (using path information):** **Correct (using path information):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const orderSchema = z.object({ const orderSchema = z.object({
customer: z.object({ customer: z.object({
name: z.string().min(1, 'Name required'), name: z.string().min(1, "Name required"),
address: z.object({ address: z.object({
street: z.string().min(1, 'Street required'), street: z.string().min(1, "Street required"),
city: z.string().min(1, 'City required'), city: z.string().min(1, "City required")
})
}), }),
}), items: z.array(
items: z.array(z.object({ z.object({
productId: z.string(), productId: z.string(),
quantity: z.number().positive('Quantity must be positive'), quantity: z.number().positive("Quantity must be positive")
})), })
}) )
});
const result = orderSchema.safeParse({ const result = orderSchema.safeParse({
customer: { name: '', address: { street: '', city: '' } }, customer: { name: "", address: { street: "", city: "" } },
items: [{ productId: 'abc', quantity: -1 }], items: [{ productId: "abc", quantity: -1 }]
}) });
if (!result.success) { if (!result.success) {
result.error.issues.forEach(issue => { result.error.issues.forEach((issue) => {
// path is an array of keys/indices // path is an array of keys/indices
console.log(`${issue.path.join('.')}: ${issue.message}`) console.log(`${issue.path.join(".")}: ${issue.message}`);
// 'customer.name: Name required' // 'customer.name: Name required'
// 'customer.address.street: Street required' // 'customer.address.street: Street required'
// 'customer.address.city: City required' // 'customer.address.city: City required'
// 'items.0.quantity: Quantity must be positive' // 'items.0.quantity: Quantity must be positive'
}) });
} }
``` ```
@@ -82,33 +86,33 @@ if (!result.success) {
```typescript ```typescript
function mapErrorsToFields(error: z.ZodError) { function mapErrorsToFields(error: z.ZodError) {
const fieldErrors: Map<string, string[]> = new Map() const fieldErrors: Map<string, string[]> = new Map();
for (const issue of error.issues) { for (const issue of error.issues) {
const fieldPath = issue.path.join('.') const fieldPath = issue.path.join(".");
const existing = fieldErrors.get(fieldPath) ?? [] const existing = fieldErrors.get(fieldPath) ?? [];
fieldErrors.set(fieldPath, [...existing, issue.message]) fieldErrors.set(fieldPath, [...existing, issue.message]);
} }
return fieldErrors return fieldErrors;
} }
// Usage // Usage
const errors = mapErrorsToFields(result.error) const errors = mapErrorsToFields(result.error);
errors.get('customer.name') // ['Name required'] errors.get("customer.name"); // ['Name required']
errors.get('items.0.quantity') // ['Quantity must be positive'] errors.get("items.0.quantity"); // ['Quantity must be positive']
``` ```
**For array items, get index from path:** **For array items, get index from path:**
```typescript ```typescript
const itemsWithErrors: Set<number> = new Set() const itemsWithErrors: Set<number> = new Set();
result.error.issues.forEach(issue => { result.error.issues.forEach((issue) => {
if (issue.path[0] === 'items' && typeof issue.path[1] === 'number') { if (issue.path[0] === "items" && typeof issue.path[1] === "number") {
itemsWithErrors.add(issue.path[1]) itemsWithErrors.add(issue.path[1]);
} }
}) });
// Highlight items at indices: Set { 0 } // Highlight items at indices: Set { 0 }
``` ```
@@ -116,14 +120,15 @@ result.error.issues.forEach(issue => {
**Using path with format():** **Using path with format():**
```typescript ```typescript
const formatted = result.error.format() const formatted = result.error.format();
// Access errors at any path level // Access errors at any path level
formatted.customer?.address?.city?._errors // ['City required'] formatted.customer?.address?.city?._errors; // ['City required']
formatted.items?.[0]?.quantity?._errors // ['Quantity must be positive'] formatted.items?.[0]?.quantity?._errors; // ['Quantity must be positive']
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Flat objects where field name is obvious - Flat objects where field name is obvious
- When using form libraries that handle path mapping - When using form libraries that handle path mapping
@@ -12,33 +12,33 @@ tags: error, flatten, forms, user-experience
**Incorrect (manual issue processing):** **Incorrect (manual issue processing):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const formSchema = z.object({ const formSchema = z.object({
email: z.string().email('Invalid email'), email: z.string().email("Invalid email"),
password: z.string().min(8, 'Password too short'), password: z.string().min(8, "Password too short"),
profile: z.object({ profile: z.object({
name: z.string().min(1, 'Name required'), name: z.string().min(1, "Name required")
}), })
}) });
function getFieldErrors(error: z.ZodError) { function getFieldErrors(error: z.ZodError) {
const errors: Record<string, string> = {} const errors: Record<string, string> = {};
for (const issue of error.issues) { for (const issue of error.issues) {
// Manual path joining - error prone // Manual path joining - error prone
const field = issue.path.join('.') const field = issue.path.join(".");
if (!errors[field]) { if (!errors[field]) {
errors[field] = issue.message errors[field] = issue.message;
} }
} }
return errors return errors;
} }
const result = formSchema.safeParse(data) const result = formSchema.safeParse(data);
if (!result.success) { if (!result.success) {
const errors = getFieldErrors(result.error) const errors = getFieldErrors(result.error);
// { email: 'Invalid email', 'profile.name': 'Name required' } // { email: 'Invalid email', 'profile.name': 'Name required' }
} }
``` ```
@@ -46,26 +46,26 @@ if (!result.success) {
**Correct (using flatten):** **Correct (using flatten):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const formSchema = z.object({ const formSchema = z.object({
email: z.string().email('Invalid email'), email: z.string().email("Invalid email"),
password: z.string().min(8, 'Password too short'), password: z.string().min(8, "Password too short"),
profile: z.object({ profile: z.object({
name: z.string().min(1, 'Name required'), name: z.string().min(1, "Name required")
}), })
}) });
const result = formSchema.safeParse(data) const result = formSchema.safeParse(data);
if (!result.success) { if (!result.success) {
const { formErrors, fieldErrors } = result.error.flatten() const { formErrors, fieldErrors } = result.error.flatten();
// formErrors: string[] - top-level errors (from .refine on the object) // formErrors: string[] - top-level errors (from .refine on the object)
// fieldErrors: { [key]: string[] } - errors by field // fieldErrors: { [key]: string[] } - errors by field
// Ready for form display // Ready for form display
console.log(fieldErrors) console.log(fieldErrors);
// { // {
// email: ['Invalid email'], // email: ['Invalid email'],
// password: ['Password too short'], // password: ['Password too short'],
@@ -77,12 +77,15 @@ if (!result.success) {
**With React Hook Form:** **With React Hook Form:**
```typescript ```typescript
import { zodResolver } from '@hookform/resolvers/zod' import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from 'react-hook-form' import { useForm } from "react-hook-form";
const { register, formState: { errors } } = useForm({ const {
resolver: zodResolver(formSchema), register,
}) formState: { errors }
} = useForm({
resolver: zodResolver(formSchema)
});
// errors are already flattened by the resolver // errors are already flattened by the resolver
// <input {...register('email')} /> // <input {...register('email')} />
@@ -94,8 +97,8 @@ const { register, formState: { errors } } = useForm({
```typescript ```typescript
const flattened = result.error.flatten((issue) => ({ const flattened = result.error.flatten((issue) => ({
message: issue.message, message: issue.message,
code: issue.code, code: issue.code
})) }));
// fieldErrors now contains custom objects // fieldErrors now contains custom objects
// { // {
@@ -106,10 +109,10 @@ const flattened = result.error.flatten((issue) => ({
**For deeply nested objects, use format():** **For deeply nested objects, use format():**
```typescript ```typescript
const result = formSchema.safeParse(data) const result = formSchema.safeParse(data);
if (!result.success) { if (!result.success) {
const formatted = result.error.format() const formatted = result.error.format();
// { // {
// _errors: [], // _errors: [],
// email: { _errors: ['Invalid email'] }, // email: { _errors: ['Invalid email'] },
@@ -120,11 +123,12 @@ if (!result.success) {
// } // }
// Access nested errors naturally // Access nested errors naturally
formatted.profile?.name?._errors // ['Name required'] formatted.profile?.name?._errors; // ['Name required']
} }
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When you need access to full issue metadata (code, path as array) - When you need access to full issue metadata (code, path as array)
- When using a form library that expects different error format - When using a form library that expects different error format
@@ -12,27 +12,27 @@ When a field's type depends on another field's value (e.g., `type: 'success'` me
**Incorrect (regular union - no automatic narrowing):** **Incorrect (regular union - no automatic narrowing):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const successSchema = z.object({ const successSchema = z.object({
type: z.literal('success'), type: z.literal("success"),
data: z.object({ id: z.string() }), data: z.object({ id: z.string() })
}) });
const errorSchema = z.object({ const errorSchema = z.object({
type: z.literal('error'), type: z.literal("error"),
message: z.string(), message: z.string()
}) });
// Regular union - Zod tries each option in order // Regular union - Zod tries each option in order
const responseSchema = z.union([successSchema, errorSchema]) const responseSchema = z.union([successSchema, errorSchema]);
type Response = z.infer<typeof responseSchema> type Response = z.infer<typeof responseSchema>;
function handleResponse(response: Response) { function handleResponse(response: Response) {
// TypeScript doesn't narrow automatically // TypeScript doesn't narrow automatically
if (response.type === 'success') { if (response.type === "success") {
response.data // Error: Property 'data' does not exist on type 'Response' response.data; // Error: Property 'data' does not exist on type 'Response'
// Must cast or use type guards // Must cast or use type guards
} }
} }
@@ -41,32 +41,29 @@ function handleResponse(response: Response) {
**Correct (discriminated union):** **Correct (discriminated union):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const successSchema = z.object({ const successSchema = z.object({
type: z.literal('success'), type: z.literal("success"),
data: z.object({ id: z.string() }), data: z.object({ id: z.string() })
}) });
const errorSchema = z.object({ const errorSchema = z.object({
type: z.literal('error'), type: z.literal("error"),
message: z.string(), message: z.string()
}) });
// Discriminated union - Zod uses 'type' field for O(1) dispatch // Discriminated union - Zod uses 'type' field for O(1) dispatch
const responseSchema = z.discriminatedUnion('type', [ const responseSchema = z.discriminatedUnion("type", [successSchema, errorSchema]);
successSchema,
errorSchema,
])
type Response = z.infer<typeof responseSchema> type Response = z.infer<typeof responseSchema>;
function handleResponse(response: Response) { function handleResponse(response: Response) {
// TypeScript narrows automatically! // TypeScript narrows automatically!
if (response.type === 'success') { if (response.type === "success") {
response.data.id // Works - TypeScript knows data exists response.data.id; // Works - TypeScript knows data exists
} else { } else {
response.message // Works - TypeScript knows message exists response.message; // Works - TypeScript knows message exists
} }
} }
``` ```
@@ -75,63 +72,64 @@ function handleResponse(response: Response) {
```typescript ```typescript
// API responses // API responses
const apiResponse = z.discriminatedUnion('status', [ const apiResponse = z.discriminatedUnion("status", [
z.object({ status: z.literal('success'), data: z.unknown() }), z.object({ status: z.literal("success"), data: z.unknown() }),
z.object({ status: z.literal('error'), error: z.string(), code: z.number() }), z.object({ status: z.literal("error"), error: z.string(), code: z.number() }),
z.object({ status: z.literal('loading') }), z.object({ status: z.literal("loading") })
]) ]);
// Event types // Event types
const event = z.discriminatedUnion('type', [ const event = z.discriminatedUnion("type", [
z.object({ type: z.literal('click'), x: z.number(), y: z.number() }), z.object({ type: z.literal("click"), x: z.number(), y: z.number() }),
z.object({ type: z.literal('keypress'), key: z.string() }), z.object({ type: z.literal("keypress"), key: z.string() }),
z.object({ type: z.literal('scroll'), delta: z.number() }), z.object({ type: z.literal("scroll"), delta: z.number() })
]) ]);
// Database records with polymorphic types // Database records with polymorphic types
const notification = z.discriminatedUnion('channel', [ const notification = z.discriminatedUnion("channel", [
z.object({ channel: z.literal('email'), address: z.string().email() }), z.object({ channel: z.literal("email"), address: z.string().email() }),
z.object({ channel: z.literal('sms'), phoneNumber: z.string() }), z.object({ channel: z.literal("sms"), phoneNumber: z.string() }),
z.object({ channel: z.literal('push'), deviceToken: z.string() }), z.object({ channel: z.literal("push"), deviceToken: z.string() })
]) ]);
``` ```
**Type-safe handling:** **Type-safe handling:**
```typescript ```typescript
const paymentSchema = z.discriminatedUnion('method', [ const paymentSchema = z.discriminatedUnion("method", [
z.object({ z.object({
method: z.literal('card'), method: z.literal("card"),
cardNumber: z.string(), cardNumber: z.string(),
expiryDate: z.string(), expiryDate: z.string()
}), }),
z.object({ z.object({
method: z.literal('bank'), method: z.literal("bank"),
accountNumber: z.string(), accountNumber: z.string(),
routingNumber: z.string(), routingNumber: z.string()
}), }),
z.object({ z.object({
method: z.literal('crypto'), method: z.literal("crypto"),
walletAddress: z.string(), walletAddress: z.string()
}), })
]) ]);
type Payment = z.infer<typeof paymentSchema> type Payment = z.infer<typeof paymentSchema>;
function processPayment(payment: Payment) { function processPayment(payment: Payment) {
switch (payment.method) { switch (payment.method) {
case 'card': case "card":
return chargeCard(payment.cardNumber, payment.expiryDate) return chargeCard(payment.cardNumber, payment.expiryDate);
case 'bank': case "bank":
return initiateBankTransfer(payment.accountNumber, payment.routingNumber) return initiateBankTransfer(payment.accountNumber, payment.routingNumber);
case 'crypto': case "crypto":
return sendCrypto(payment.walletAddress) return sendCrypto(payment.walletAddress);
// TypeScript exhaustiveness check - no default needed // TypeScript exhaustiveness check - no default needed
} }
} }
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When variants don't share a common discriminator field - When variants don't share a common discriminator field
- When the discriminator isn't a literal type (use regular union) - When the discriminator isn't a literal type (use regular union)
@@ -12,19 +12,19 @@ When building on existing schemas, use `.extend()` to add new fields rather than
**Incorrect (manual object spreading):** **Incorrect (manual object spreading):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const baseUserSchema = z.object({ const baseUserSchema = z.object({
id: z.string(), id: z.string(),
name: z.string(), name: z.string()
}) });
// Manual spreading loses Zod's schema relationship // Manual spreading loses Zod's schema relationship
const adminUserSchema = z.object({ const adminUserSchema = z.object({
...baseUserSchema.shape, // Accessing internal .shape ...baseUserSchema.shape, // Accessing internal .shape
role: z.literal('admin'), role: z.literal("admin"),
permissions: z.array(z.string()), permissions: z.array(z.string())
}) });
// Problems: // Problems:
// 1. If baseUserSchema changes, TypeScript might not catch issues // 1. If baseUserSchema changes, TypeScript might not catch issues
@@ -35,21 +35,21 @@ const adminUserSchema = z.object({
**Correct (using extend):** **Correct (using extend):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const baseUserSchema = z.object({ const baseUserSchema = z.object({
id: z.string(), id: z.string(),
name: z.string(), name: z.string(),
email: z.string().email(), email: z.string().email()
}) });
// Extend to add fields // Extend to add fields
const adminUserSchema = baseUserSchema.extend({ const adminUserSchema = baseUserSchema.extend({
role: z.literal('admin'), role: z.literal("admin"),
permissions: z.array(z.string()), permissions: z.array(z.string())
}) });
type AdminUser = z.infer<typeof adminUserSchema> type AdminUser = z.infer<typeof adminUserSchema>;
// { // {
// id: string; // id: string;
// name: string; // name: string;
@@ -60,8 +60,8 @@ type AdminUser = z.infer<typeof adminUserSchema>
// Override existing fields // Override existing fields
const strictEmailSchema = baseUserSchema.extend({ const strictEmailSchema = baseUserSchema.extend({
email: z.string().email().endsWith('@company.com'), // Stricter validation email: z.string().email().endsWith("@company.com") // Stricter validation
}) });
``` ```
**Building hierarchies with extend:** **Building hierarchies with extend:**
@@ -71,31 +71,33 @@ const strictEmailSchema = baseUserSchema.extend({
const entitySchema = z.object({ const entitySchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}) });
// User extends entity // User extends entity
const userSchema = entitySchema.extend({ const userSchema = entitySchema.extend({
email: z.string().email(), email: z.string().email(),
name: z.string(), name: z.string()
}) });
// Product extends entity // Product extends entity
const productSchema = entitySchema.extend({ const productSchema = entitySchema.extend({
name: z.string(), name: z.string(),
price: z.number().positive(), price: z.number().positive(),
sku: z.string(), sku: z.string()
}) });
// Order extends entity with references // Order extends entity with references
const orderSchema = entitySchema.extend({ const orderSchema = entitySchema.extend({
userId: z.string().uuid(), userId: z.string().uuid(),
items: z.array(z.object({ items: z.array(
z.object({
productId: z.string().uuid(), productId: z.string().uuid(),
quantity: z.number().int().positive(), quantity: z.number().int().positive()
})), })
total: z.number().positive(), ),
}) total: z.number().positive()
});
``` ```
**Combining extend with other methods:** **Combining extend with other methods:**
@@ -104,22 +106,18 @@ const orderSchema = entitySchema.extend({
const baseSchema = z.object({ const baseSchema = z.object({
id: z.string(), id: z.string(),
name: z.string(), name: z.string(),
email: z.string(), email: z.string()
}) });
// Create input: no id, add password // Create input: no id, add password
const createSchema = baseSchema const createSchema = baseSchema.omit({ id: true }).extend({
.omit({ id: true }) password: z.string().min(8)
.extend({ });
password: z.string().min(8),
})
// Update input: all optional except id // Update input: all optional except id
const updateSchema = baseSchema const updateSchema = baseSchema.partial().extend({
.partial() id: z.string() // Override to make required
.extend({ });
id: z.string(), // Override to make required
})
``` ```
**Merge for combining independent schemas:** **Merge for combining independent schemas:**
@@ -127,20 +125,21 @@ const updateSchema = baseSchema
```typescript ```typescript
const addressSchema = z.object({ const addressSchema = z.object({
street: z.string(), street: z.string(),
city: z.string(), city: z.string()
}) });
const contactSchema = z.object({ const contactSchema = z.object({
email: z.string().email(), email: z.string().email(),
phone: z.string(), phone: z.string()
}) });
// Merge combines two schemas (both required) // Merge combines two schemas (both required)
const customerSchema = addressSchema.merge(contactSchema) const customerSchema = addressSchema.merge(contactSchema);
// { street: string; city: string; email: string; phone: string } // { street: string; city: string; email: string; phone: string }
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When schemas are genuinely independent (use merge or intersection) - When schemas are genuinely independent (use merge or intersection)
- When you need to remove fields (use omit) - When you need to remove fields (use omit)
@@ -12,29 +12,29 @@ tags: object, optional, nullable, undefined
**Incorrect (confusing optional and nullable):** **Incorrect (confusing optional and nullable):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userSchema = z.object({ const userSchema = z.object({
name: z.string(), name: z.string(),
// Intended: field might not exist // Intended: field might not exist
nickname: z.string().nullable(), // Wrong! Requires field to be present nickname: z.string().nullable(), // Wrong! Requires field to be present
// Intended: field exists but might be null // Intended: field exists but might be null
deletedAt: z.date().optional(), // Wrong! Allows field to be missing deletedAt: z.date().optional() // Wrong! Allows field to be missing
}) });
// This fails - nickname is required // This fails - nickname is required
userSchema.parse({ name: 'John' }) userSchema.parse({ name: "John" });
// ZodError: Required at "nickname" // ZodError: Required at "nickname"
// This passes but loses semantic meaning // This passes but loses semantic meaning
userSchema.parse({ name: 'John', nickname: null, deletedAt: undefined }) userSchema.parse({ name: "John", nickname: null, deletedAt: undefined });
// Is deletedAt undefined because not deleted, or because data is incomplete? // Is deletedAt undefined because not deleted, or because data is incomplete?
``` ```
**Correct (using optional and nullable deliberately):** **Correct (using optional and nullable deliberately):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userSchema = z.object({ const userSchema = z.object({
name: z.string(), name: z.string(),
@@ -44,23 +44,23 @@ const userSchema = z.object({
// Type: string | undefined // Type: string | undefined
// nullable() - field must exist, but value can be null // nullable() - field must exist, but value can be null
deletedAt: z.date().nullable(), deletedAt: z.date().nullable()
// Type: Date | null // Type: Date | null
}) });
// Field can be omitted // Field can be omitted
userSchema.parse({ name: 'John', deletedAt: null }) // Valid userSchema.parse({ name: "John", deletedAt: null }); // Valid
// Field must be present (even if null) // Field must be present (even if null)
userSchema.parse({ name: 'John', nickname: 'Johnny' }) userSchema.parse({ name: "John", nickname: "Johnny" });
// ZodError: Required at "deletedAt" // ZodError: Required at "deletedAt"
// Correct usage // Correct usage
userSchema.parse({ userSchema.parse({
name: 'John', name: "John",
nickname: 'Johnny', // Or omit entirely nickname: "Johnny", // Or omit entirely
deletedAt: null, // Must be present, null means "not deleted" deletedAt: null // Must be present, null means "not deleted"
}) });
``` ```
**When to use each:** **When to use each:**
@@ -70,22 +70,22 @@ userSchema.parse({
// Use for: Optional form fields, sparse updates, optional config // Use for: Optional form fields, sparse updates, optional config
z.object({ z.object({
bio: z.string().optional(), // User might not have filled this bio: z.string().optional(), // User might not have filled this
middleName: z.string().optional(), // Not everyone has one middleName: z.string().optional() // Not everyone has one
}) });
// nullable() - field exists but value can be null // nullable() - field exists but value can be null
// Use for: Database nullable columns, "cleared" values, explicit absence // Use for: Database nullable columns, "cleared" values, explicit absence
z.object({ z.object({
deletedAt: z.date().nullable(), // null = not deleted, Date = when deleted deletedAt: z.date().nullable(), // null = not deleted, Date = when deleted
parentId: z.string().nullable(), // null = root node, string = has parent parentId: z.string().nullable(), // null = root node, string = has parent
approvedBy: z.string().nullable(), // null = pending, string = approver approvedBy: z.string().nullable() // null = pending, string = approver
}) });
// nullish() - either undefined or null // nullish() - either undefined or null
// Use for: Lenient APIs, legacy data, optional nullable DB columns // Use for: Lenient APIs, legacy data, optional nullable DB columns
z.object({ z.object({
legacyField: z.string().nullish(), // string | null | undefined legacyField: z.string().nullish() // string | null | undefined
}) });
``` ```
**API response patterns:** **API response patterns:**
@@ -94,23 +94,26 @@ z.object({
// API includes null for "no value" (good for explicit absence) // API includes null for "no value" (good for explicit absence)
const apiResponseSchema = z.object({ const apiResponseSchema = z.object({
data: z.object({ data: z.object({
user: z.object({ user: z
.object({
name: z.string(), name: z.string(),
avatar: z.string().nullable(), // null = no avatar set avatar: z.string().nullable() // null = no avatar set
}).nullable(), // null = user not found })
}), .nullable() // null = user not found
}) })
});
// Type: { data: { user: { name: string; avatar: string | null } | null } } // Type: { data: { user: { name: string; avatar: string | null } | null } }
// Partial updates send only changed fields // Partial updates send only changed fields
const updateSchema = z.object({ const updateSchema = z.object({
name: z.string().optional(), // Omitted = don't change name: z.string().optional(), // Omitted = don't change
avatar: z.string().nullable().optional(), // null = clear avatar avatar: z.string().nullable().optional() // null = clear avatar
}) });
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When interacting with systems that treat null and undefined as equivalent - When interacting with systems that treat null and undefined as equivalent
- When using nullish() for maximum flexibility is acceptable - When using nullish() for maximum flexibility is acceptable
@@ -12,23 +12,23 @@ When handling PATCH/PUT updates, you need a schema where all fields are optional
**Incorrect (duplicating schemas):** **Incorrect (duplicating schemas):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Base schema // Base schema
const userSchema = z.object({ const userSchema = z.object({
name: z.string().min(1), name: z.string().min(1),
email: z.string().email(), email: z.string().email(),
age: z.number().int().positive(), age: z.number().int().positive(),
role: z.enum(['admin', 'user']), role: z.enum(["admin", "user"])
}) });
// Manually duplicated for updates - will drift! // Manually duplicated for updates - will drift!
const updateUserSchema = z.object({ const updateUserSchema = z.object({
name: z.string().min(1).optional(), name: z.string().min(1).optional(),
email: z.string().email().optional(), email: z.string().email().optional(),
age: z.number().int().positive().optional(), age: z.number().int().positive().optional()
// Forgot to add role - schemas out of sync! // Forgot to add role - schemas out of sync!
}) });
// Later, you add a field to userSchema but forget updateUserSchema // Later, you add a field to userSchema but forget updateUserSchema
// Now updates silently ignore the new field // Now updates silently ignore the new field
@@ -37,28 +37,28 @@ const updateUserSchema = z.object({
**Correct (using partial):** **Correct (using partial):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Base schema - single source of truth // Base schema - single source of truth
const userSchema = z.object({ const userSchema = z.object({
name: z.string().min(1), name: z.string().min(1),
email: z.string().email(), email: z.string().email(),
age: z.number().int().positive(), age: z.number().int().positive(),
role: z.enum(['admin', 'user']), role: z.enum(["admin", "user"])
}) });
// All fields optional for updates // All fields optional for updates
const updateUserSchema = userSchema.partial() const updateUserSchema = userSchema.partial();
type User = z.infer<typeof userSchema> type User = z.infer<typeof userSchema>;
// { name: string; email: string; age: number; role: 'admin' | 'user' } // { name: string; email: string; age: number; role: 'admin' | 'user' }
type UpdateUser = z.infer<typeof updateUserSchema> type UpdateUser = z.infer<typeof updateUserSchema>;
// { name?: string; email?: string; age?: number; role?: 'admin' | 'user' } // { name?: string; email?: string; age?: number; role?: 'admin' | 'user' }
// Validate partial updates // Validate partial updates
updateUserSchema.parse({ email: 'new@example.com' }) // Valid updateUserSchema.parse({ email: "new@example.com" }); // Valid
updateUserSchema.parse({}) // Valid - all fields optional updateUserSchema.parse({}); // Valid - all fields optional
``` ```
**Partial specific fields only:** **Partial specific fields only:**
@@ -67,10 +67,10 @@ updateUserSchema.parse({}) // Valid - all fields optional
// Only name and email are optional for updates // Only name and email are optional for updates
const updateUserSchema = userSchema.partial({ const updateUserSchema = userSchema.partial({
name: true, name: true,
email: true, email: true
}) });
type UpdateUser = z.infer<typeof updateUserSchema> type UpdateUser = z.infer<typeof updateUserSchema>;
// { name?: string; email?: string; age: number; role: 'admin' | 'user' } // { name?: string; email?: string; age: number; role: 'admin' | 'user' }
// age and role still required // age and role still required
``` ```
@@ -81,21 +81,21 @@ type UpdateUser = z.infer<typeof updateUserSchema>
const addressSchema = z.object({ const addressSchema = z.object({
street: z.string(), street: z.string(),
city: z.string(), city: z.string(),
country: z.string(), country: z.string()
}) });
const userSchema = z.object({ const userSchema = z.object({
name: z.string(), name: z.string(),
address: addressSchema, address: addressSchema
}) });
// .partial() only makes top-level fields optional // .partial() only makes top-level fields optional
const shallowPartial = userSchema.partial() const shallowPartial = userSchema.partial();
// { name?: string; address?: { street: string; city: string; country: string } } // { name?: string; address?: { street: string; city: string; country: string } }
// If address is provided, all its fields are still required! // If address is provided, all its fields are still required!
// Use deepPartial for nested optionality // Use deepPartial for nested optionality
const deepPartialSchema = userSchema.deepPartial() const deepPartialSchema = userSchema.deepPartial();
// { name?: string; address?: { street?: string; city?: string; country?: string } } // { name?: string; address?: { street?: string; city?: string; country?: string } }
``` ```
@@ -106,17 +106,18 @@ const baseSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
name: z.string(), name: z.string(),
email: z.string().email(), email: z.string().email(),
createdAt: z.date(), createdAt: z.date()
}) });
// Create: id and createdAt are generated, rest required // Create: id and createdAt are generated, rest required
const createSchema = baseSchema.omit({ id: true, createdAt: true }) const createSchema = baseSchema.omit({ id: true, createdAt: true });
// Update: all user-editable fields optional // Update: all user-editable fields optional
const updateSchema = baseSchema.partial().omit({ id: true, createdAt: true }) const updateSchema = baseSchema.partial().omit({ id: true, createdAt: true });
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When update logic differs significantly from create (different validations) - When update logic differs significantly from create (different validations)
- When using GraphQL with explicit input types - When using GraphQL with explicit input types
@@ -12,7 +12,7 @@ When you need different views of the same data (public vs private, create vs res
**Incorrect (duplicating for variants):** **Incorrect (duplicating for variants):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Full user schema // Full user schema
const userSchema = z.object({ const userSchema = z.object({
@@ -21,8 +21,8 @@ const userSchema = z.object({
passwordHash: z.string(), passwordHash: z.string(),
name: z.string(), name: z.string(),
createdAt: z.date(), createdAt: z.date(),
isAdmin: z.boolean(), isAdmin: z.boolean()
}) });
// Public view - manually duplicated // Public view - manually duplicated
const publicUserSchema = z.object({ const publicUserSchema = z.object({
@@ -30,22 +30,22 @@ const publicUserSchema = z.object({
name: z.string(), name: z.string(),
// Forgot email - now users can't see it // Forgot email - now users can't see it
// Added avatar field - doesn't exist in base schema // Added avatar field - doesn't exist in base schema
avatar: z.string().optional(), avatar: z.string().optional()
}) });
// Create input - manually duplicated // Create input - manually duplicated
const createUserSchema = z.object({ const createUserSchema = z.object({
email: z.string().email(), email: z.string().email(),
password: z.string().min(8), // Different from passwordHash password: z.string().min(8), // Different from passwordHash
name: z.string(), name: z.string()
// Missing isAdmin - can't set on create? Intentional? // Missing isAdmin - can't set on create? Intentional?
}) });
``` ```
**Correct (using pick and omit):** **Correct (using pick and omit):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Full user schema - single source of truth // Full user schema - single source of truth
const userSchema = z.object({ const userSchema = z.object({
@@ -54,35 +54,35 @@ const userSchema = z.object({
passwordHash: z.string(), passwordHash: z.string(),
name: z.string(), name: z.string(),
createdAt: z.date(), createdAt: z.date(),
isAdmin: z.boolean(), isAdmin: z.boolean()
}) });
// Public view - explicitly pick public fields // Public view - explicitly pick public fields
const publicUserSchema = userSchema.pick({ const publicUserSchema = userSchema.pick({
id: true, id: true,
email: true, email: true,
name: true, name: true
}) });
type PublicUser = z.infer<typeof publicUserSchema> type PublicUser = z.infer<typeof publicUserSchema>;
// { id: string; email: string; name: string } // { id: string; email: string; name: string }
// API response - omit sensitive fields // API response - omit sensitive fields
const userResponseSchema = userSchema.omit({ const userResponseSchema = userSchema.omit({
passwordHash: true, passwordHash: true
}) });
type UserResponse = z.infer<typeof userResponseSchema> type UserResponse = z.infer<typeof userResponseSchema>;
// { id: string; email: string; name: string; createdAt: Date; isAdmin: boolean } // { id: string; email: string; name: string; createdAt: Date; isAdmin: boolean }
// Create input - omit generated fields // Create input - omit generated fields
const createUserInputSchema = userSchema const createUserInputSchema = userSchema
.omit({ id: true, createdAt: true, passwordHash: true }) .omit({ id: true, createdAt: true, passwordHash: true })
.extend({ .extend({
password: z.string().min(8), // Add password (different from hash) password: z.string().min(8) // Add password (different from hash)
}) });
type CreateUserInput = z.infer<typeof createUserInputSchema> type CreateUserInput = z.infer<typeof createUserInputSchema>;
// { email: string; name: string; isAdmin: boolean; password: string } // { email: string; name: string; isAdmin: boolean; password: string }
``` ```
@@ -96,27 +96,27 @@ const dbRowSchema = z.object({
email: z.string(), email: z.string(),
password_hash: z.string(), password_hash: z.string(),
internal_notes: z.string(), internal_notes: z.string(),
created_at: z.date(), created_at: z.date()
}) });
const apiResponseSchema = dbRowSchema.omit({ const apiResponseSchema = dbRowSchema.omit({
id: true, // Internal DB id id: true, // Internal DB id
password_hash: true, // Sensitive password_hash: true, // Sensitive
internal_notes: true, // Staff only internal_notes: true // Staff only
}) });
// Form data → Database insert (add generated fields) // Form data → Database insert (add generated fields)
const formSchema = z.object({ const formSchema = z.object({
title: z.string(), title: z.string(),
content: z.string(), content: z.string()
}) });
const dbInsertSchema = formSchema.extend({ const dbInsertSchema = formSchema.extend({
id: z.string().uuid(), id: z.string().uuid(),
authorId: z.string().uuid(), authorId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}) });
``` ```
**Chaining operations:** **Chaining operations:**
@@ -126,20 +126,21 @@ const baseSchema = z.object({
id: z.string(), id: z.string(),
name: z.string(), name: z.string(),
email: z.string(), email: z.string(),
role: z.enum(['admin', 'user']), role: z.enum(["admin", "user"]),
secret: z.string(), secret: z.string()
}) });
// Combine pick, omit, partial, extend // Combine pick, omit, partial, extend
const updateSchema = baseSchema const updateSchema = baseSchema
.omit({ id: true, secret: true }) // Remove immutable/sensitive .omit({ id: true, secret: true }) // Remove immutable/sensitive
.partial() // Make all optional for updates .partial() // Make all optional for updates
.extend({ .extend({
updatedAt: z.date().optional(), // Add update timestamp updatedAt: z.date().optional() // Add update timestamp
}) });
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When derived schemas need different validation rules (not just different fields) - When derived schemas need different validation rules (not just different fields)
- When the relationship between schemas is not subset/superset - When the relationship between schemas is not subset/superset
@@ -12,21 +12,21 @@ By default, Zod objects use `.strip()` behavior, silently removing unrecognized
**Default behavior (strip - silent removal):** **Default behavior (strip - silent removal):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userSchema = z.object({ const userSchema = z.object({
id: z.string(), id: z.string(),
name: z.string(), name: z.string()
}) });
const input = { const input = {
id: '123', id: "123",
name: 'John', name: "John",
role: 'admin', // Extra field role: "admin", // Extra field
secretToken: 'abc123', // Another extra field secretToken: "abc123" // Another extra field
} };
const user = userSchema.parse(input) const user = userSchema.parse(input);
// { id: '123', name: 'John' } // { id: '123', name: 'John' }
// Extra fields silently removed - was this intentional? // Extra fields silently removed - was this intentional?
``` ```
@@ -34,20 +34,22 @@ const user = userSchema.parse(input)
**Using strict() to catch schema mismatches:** **Using strict() to catch schema mismatches:**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userSchema = z.object({ const userSchema = z
.object({
id: z.string(), id: z.string(),
name: z.string(), name: z.string()
}).strict() })
.strict();
const input = { const input = {
id: '123', id: "123",
name: 'John', name: "John",
role: 'admin', role: "admin"
} };
userSchema.parse(input) userSchema.parse(input);
// ZodError: Unrecognized key(s) in object: 'role' // ZodError: Unrecognized key(s) in object: 'role'
// This catches: // This catches:
@@ -60,30 +62,36 @@ userSchema.parse(input)
```typescript ```typescript
// strict() - Catch unexpected data (API contracts) // strict() - Catch unexpected data (API contracts)
const apiRequestSchema = z.object({ const apiRequestSchema = z
.object({
action: z.string(), action: z.string(),
payload: z.unknown(), payload: z.unknown()
}).strict() // Fail if client sends unknown fields })
.strict(); // Fail if client sends unknown fields
// strip() - Clean up data (explicit intention) // strip() - Clean up data (explicit intention)
const dbInsertSchema = z.object({ const dbInsertSchema = z
.object({
name: z.string(), name: z.string(),
email: z.string(), email: z.string()
}).strip() // Explicitly remove metadata before insert })
.strip(); // Explicitly remove metadata before insert
// passthrough() - Keep everything (pass-through proxy) // passthrough() - Keep everything (pass-through proxy)
const proxySchema = z.object({ const proxySchema = z
id: z.string(), .object({
}).passthrough() // Keep fields we don't validate id: z.string()
})
.passthrough(); // Keep fields we don't validate
const input = { id: '123', extra: 'data' } const input = { id: "123", extra: "data" };
proxySchema.parse(input) // { id: '123', extra: 'data' } proxySchema.parse(input); // { id: '123', extra: 'data' }
``` ```
**Choosing the right mode:** **Choosing the right mode:**
| Mode | Behavior | Use When | | Mode | Behavior | Use When |
|------|----------|----------| | -------------------- | ------------------- | -------------------------------------------- |
| `.strict()` | Reject unknown keys | API contracts, security-sensitive, debugging | | `.strict()` | Reject unknown keys | API contracts, security-sensitive, debugging |
| `.strip()` (default) | Remove unknown keys | General validation, data cleaning | | `.strip()` (default) | Remove unknown keys | General validation, data cleaning |
| `.passthrough()` | Keep unknown keys | Proxying, partial validation | | `.passthrough()` | Keep unknown keys | Proxying, partial validation |
@@ -91,18 +99,23 @@ proxySchema.parse(input) // { id: '123', extra: 'data' }
**Handling specific unknown keys:** **Handling specific unknown keys:**
```typescript ```typescript
const schema = z.object({ const schema = z
.object({
id: z.string(), id: z.string(),
name: z.string(), name: z.string()
}).catchall(z.unknown()) // Allow any additional fields of any type })
.catchall(z.unknown()); // Allow any additional fields of any type
// Or restrict additional fields to specific type // Or restrict additional fields to specific type
const metadataSchema = z.object({ const metadataSchema = z
id: z.string(), .object({
}).catchall(z.string()) // Only allow string extras id: z.string()
})
.catchall(z.string()); // Only allow string extras
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- `.strict()`: When forwarding data to another system that may add fields - `.strict()`: When forwarding data to another system that may add fields
- `.passthrough()`: When you need to ensure only known fields are stored - `.passthrough()`: When you need to ensure only known fields are stored
@@ -12,22 +12,24 @@ If your schema uses `refine()` or `superRefine()` with async validation (like da
**Incorrect (sync parse with async refinement):** **Incorrect (sync parse with async refinement):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userSchema = z.object({ const userSchema = z
.object({
email: z.string().email(), email: z.string().email(),
username: z.string().min(3), username: z.string().min(3)
}).refine( })
.refine(
async (data) => { async (data) => {
// Async database check // Async database check
const exists = await db.users.findByEmail(data.email) const exists = await db.users.findByEmail(data.email);
return !exists return !exists;
}, },
{ message: 'Email already registered' } { message: "Email already registered" }
) );
// This throws an error! // This throws an error!
const user = userSchema.parse(formData) const user = userSchema.parse(formData);
// Error: Async refinement encountered during synchronous parse operation. // Error: Async refinement encountered during synchronous parse operation.
// Use .parseAsync instead. // Use .parseAsync instead.
``` ```
@@ -35,76 +37,82 @@ const user = userSchema.parse(formData)
**Correct (using parseAsync):** **Correct (using parseAsync):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userSchema = z.object({ const userSchema = z
.object({
email: z.string().email(), email: z.string().email(),
username: z.string().min(3), username: z.string().min(3)
}).refine( })
.refine(
async (data) => { async (data) => {
const exists = await db.users.findByEmail(data.email) const exists = await db.users.findByEmail(data.email);
return !exists return !exists;
}, },
{ message: 'Email already registered' } { message: "Email already registered" }
) );
// Use parseAsync for async refinements // Use parseAsync for async refinements
const user = await userSchema.parseAsync(formData) const user = await userSchema.parseAsync(formData);
// Or safeParseAsync for error handling // Or safeParseAsync for error handling
const result = await userSchema.safeParseAsync(formData) const result = await userSchema.safeParseAsync(formData);
if (!result.success) { if (!result.success) {
console.log(result.error.issues) console.log(result.error.issues);
} }
``` ```
**Async transforms also require parseAsync:** **Async transforms also require parseAsync:**
```typescript ```typescript
const enrichedUserSchema = z.object({ const enrichedUserSchema = z
userId: z.string().uuid(), .object({
}).transform(async (data) => { userId: z.string().uuid()
})
.transform(async (data) => {
// Async data enrichment // Async data enrichment
const user = await db.users.findById(data.userId) const user = await db.users.findById(data.userId);
return { return {
...data, ...data,
email: user.email, email: user.email,
name: user.name, name: user.name
} };
}) });
// Must use parseAsync // Must use parseAsync
const enrichedUser = await enrichedUserSchema.parseAsync({ userId: '123' }) const enrichedUser = await enrichedUserSchema.parseAsync({ userId: "123" });
``` ```
**Pattern for API routes:** **Pattern for API routes:**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from "next/server";
const registerSchema = z.object({ const registerSchema = z
.object({
email: z.string().email(), email: z.string().email(),
password: z.string().min(8), password: z.string().min(8)
}).superRefine(async (data, ctx) => { })
const existingUser = await db.users.findByEmail(data.email) .superRefine(async (data, ctx) => {
const existingUser = await db.users.findByEmail(data.email);
if (existingUser) { if (existingUser) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
path: ['email'], path: ["email"],
message: 'Email already registered', message: "Email already registered"
}) });
} }
}) });
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
const body = await req.json() const body = await req.json();
// Always use safeParseAsync with async schemas // Always use safeParseAsync with async schemas
const result = await registerSchema.safeParseAsync(body) const result = await registerSchema.safeParseAsync(body);
if (!result.success) { if (!result.success) {
return NextResponse.json({ errors: result.error.issues }, { status: 400 }) return NextResponse.json({ errors: result.error.issues }, { status: 400 });
} }
// Proceed with registration // Proceed with registration
@@ -112,6 +120,7 @@ export async function POST(req: NextRequest) {
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Schemas with only synchronous validation (use parse/safeParse) - Schemas with only synchronous validation (use parse/safeParse)
- When async validation can be moved outside Zod (validate, then check) - When async validation can be moved outside Zod (validate, then check)
@@ -12,78 +12,78 @@ Once data is validated by Zod, trust the result. Re-validating the same data in
**Incorrect (validating at every layer):** **Incorrect (validating at every layer):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userSchema = z.object({ const userSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
email: z.string().email(), email: z.string().email(),
name: z.string(), name: z.string()
}) });
// Controller validates // Controller validates
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
const body = await req.json() const body = await req.json();
const user = userSchema.parse(body) // First parse const user = userSchema.parse(body); // First parse
return await userService.create(user) return await userService.create(user);
} }
// Service validates again // Service validates again
const userService = { const userService = {
async create(data: unknown) { async create(data: unknown) {
const user = userSchema.parse(data) // Second parse - redundant const user = userSchema.parse(data); // Second parse - redundant
return await userRepository.insert(user) return await userRepository.insert(user);
} }
} };
// Repository validates again // Repository validates again
const userRepository = { const userRepository = {
async insert(data: unknown) { async insert(data: unknown) {
const user = userSchema.parse(data) // Third parse - wasteful const user = userSchema.parse(data); // Third parse - wasteful
return await db.users.create({ data: user }) return await db.users.create({ data: user });
} }
} };
``` ```
**Correct (validate once, pass typed data):** **Correct (validate once, pass typed data):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userSchema = z.object({ const userSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
email: z.string().email(), email: z.string().email(),
name: z.string(), name: z.string()
}) });
type User = z.infer<typeof userSchema> type User = z.infer<typeof userSchema>;
// Controller validates at boundary // Controller validates at boundary
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
const body = await req.json() const body = await req.json();
const result = userSchema.safeParse(body) const result = userSchema.safeParse(body);
if (!result.success) { if (!result.success) {
return NextResponse.json({ errors: result.error.issues }, { status: 400 }) return NextResponse.json({ errors: result.error.issues }, { status: 400 });
} }
// Pass validated, typed data // Pass validated, typed data
return await userService.create(result.data) return await userService.create(result.data);
} }
// Service receives typed data, no re-validation needed // Service receives typed data, no re-validation needed
const userService = { const userService = {
async create(user: User) { async create(user: User) {
// user is guaranteed to match schema // user is guaranteed to match schema
return await userRepository.insert(user) return await userRepository.insert(user);
} }
} };
// Repository receives typed data // Repository receives typed data
const userRepository = { const userRepository = {
async insert(user: User) { async insert(user: User) {
return await db.users.create({ data: user }) return await db.users.create({ data: user });
} }
} };
``` ```
**When you might validate at multiple layers:** **When you might validate at multiple layers:**
@@ -92,20 +92,20 @@ const userRepository = {
// Different schemas for different layers // Different schemas for different layers
const apiUserSchema = z.object({ const apiUserSchema = z.object({
email: z.string().email(), email: z.string().email(),
password: z.string().min(8), // Only in API layer password: z.string().min(8) // Only in API layer
}) });
const dbUserSchema = z.object({ const dbUserSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
email: z.string().email(), email: z.string().email(),
passwordHash: z.string(), // Transformed before storage passwordHash: z.string() // Transformed before storage
}) });
// API validates input format // API validates input format
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
const input = apiUserSchema.parse(await req.json()) const input = apiUserSchema.parse(await req.json());
const user = await userService.create(input) const user = await userService.create(input);
return NextResponse.json(user) return NextResponse.json(user);
} }
// Service transforms and validates for storage // Service transforms and validates for storage
@@ -114,14 +114,15 @@ const userService = {
const dbUser = dbUserSchema.parse({ const dbUser = dbUserSchema.parse({
id: crypto.randomUUID(), id: crypto.randomUUID(),
email: input.email, email: input.email,
passwordHash: await hash(input.password), passwordHash: await hash(input.password)
}) });
return await userRepository.insert(dbUser) return await userRepository.insert(dbUser);
} }
} };
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When schemas differ between layers (API vs DB shape) - When schemas differ between layers (API vs DB shape)
- When data crosses trust boundaries (external service response) - When data crosses trust boundaries (external service response)
- During development when debugging data flow - During development when debugging data flow
@@ -12,28 +12,28 @@ Zod collects all validation failures, not just the first one. When displaying er
**Incorrect (showing only first error):** **Incorrect (showing only first error):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const formSchema = z.object({ const formSchema = z.object({
email: z.string().email('Invalid email'), email: z.string().email("Invalid email"),
password: z.string().min(8, 'Password must be 8+ characters'), password: z.string().min(8, "Password must be 8+ characters"),
confirmPassword: z.string(), confirmPassword: z.string(),
age: z.number().min(18, 'Must be 18 or older'), age: z.number().min(18, "Must be 18 or older")
}) });
function validateForm(data: unknown) { function validateForm(data: unknown) {
const result = formSchema.safeParse(data) const result = formSchema.safeParse(data);
if (!result.success) { if (!result.success) {
// Only shows first error - terrible UX // Only shows first error - terrible UX
return { error: result.error.issues[0].message } return { error: result.error.issues[0].message };
} }
return { data: result.data } return { data: result.data };
} }
// User submits empty form // User submits empty form
validateForm({}) validateForm({});
// Returns: { error: 'Invalid email' } // Returns: { error: 'Invalid email' }
// User fixes email, submits again // User fixes email, submits again
// Returns: { error: 'Password must be 8+ characters' } // Returns: { error: 'Password must be 8+ characters' }
@@ -44,38 +44,38 @@ validateForm({})
**Correct (showing all errors):** **Correct (showing all errors):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const formSchema = z.object({ const formSchema = z.object({
email: z.string().email('Invalid email'), email: z.string().email("Invalid email"),
password: z.string().min(8, 'Password must be 8+ characters'), password: z.string().min(8, "Password must be 8+ characters"),
confirmPassword: z.string(), confirmPassword: z.string(),
age: z.number().min(18, 'Must be 18 or older'), age: z.number().min(18, "Must be 18 or older")
}) });
function validateForm(data: unknown) { function validateForm(data: unknown) {
const result = formSchema.safeParse(data) const result = formSchema.safeParse(data);
if (!result.success) { if (!result.success) {
// Collect errors by field for form display // Collect errors by field for form display
const fieldErrors: Record<string, string[]> = {} const fieldErrors: Record<string, string[]> = {};
for (const issue of result.error.issues) { for (const issue of result.error.issues) {
const field = issue.path.join('.') const field = issue.path.join(".");
if (!fieldErrors[field]) { if (!fieldErrors[field]) {
fieldErrors[field] = [] fieldErrors[field] = [];
} }
fieldErrors[field].push(issue.message) fieldErrors[field].push(issue.message);
} }
return { errors: fieldErrors } return { errors: fieldErrors };
} }
return { data: result.data } return { data: result.data };
} }
// User submits empty form // User submits empty form
validateForm({}) validateForm({});
// Returns: { // Returns: {
// errors: { // errors: {
// email: ['Invalid email'], // email: ['Invalid email'],
@@ -90,10 +90,10 @@ validateForm({})
**Using flatten() for simpler error structure:** **Using flatten() for simpler error structure:**
```typescript ```typescript
const result = formSchema.safeParse(data) const result = formSchema.safeParse(data);
if (!result.success) { if (!result.success) {
const flattened = result.error.flatten() const flattened = result.error.flatten();
// { // {
// formErrors: [], // Top-level errors // formErrors: [], // Top-level errors
// fieldErrors: { // fieldErrors: {
@@ -102,23 +102,24 @@ if (!result.success) {
// ... // ...
// } // }
// } // }
return { errors: flattened.fieldErrors } return { errors: flattened.fieldErrors };
} }
``` ```
**With React Hook Form integration:** **With React Hook Form integration:**
```typescript ```typescript
import { zodResolver } from '@hookform/resolvers/zod' import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from 'react-hook-form' import { useForm } from "react-hook-form";
const form = useForm({ const form = useForm({
resolver: zodResolver(formSchema), resolver: zodResolver(formSchema)
// All errors are automatically collected and displayed // All errors are automatically collected and displayed
}) });
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Rate-limited APIs where you want to fail fast on first error - Rate-limited APIs where you want to fail fast on first error
- Large batch processing where full validation is expensive - Large batch processing where full validation is expensive
@@ -13,50 +13,50 @@ tags: parse, json, security, type-safety
```typescript ```typescript
// JSON.parse returns any - no type safety // JSON.parse returns any - no type safety
const config = JSON.parse(fs.readFileSync('config.json', 'utf-8')) const config = JSON.parse(fs.readFileSync("config.json", "utf-8"));
// config is 'any' - TypeScript allows anything // config is 'any' - TypeScript allows anything
// This might crash at runtime if structure changed // This might crash at runtime if structure changed
console.log(config.database.host) // TypeError: Cannot read property 'host' of undefined console.log(config.database.host); // TypeError: Cannot read property 'host' of undefined
// API response - also unvalidated // API response - also unvalidated
const response = await fetch('/api/user') const response = await fetch("/api/user");
const user = await response.json() // any type const user = await response.json(); // any type
console.log(user.name.toUpperCase()) // Crash if name is null/undefined console.log(user.name.toUpperCase()); // Crash if name is null/undefined
``` ```
**Correct (validate after JSON.parse):** **Correct (validate after JSON.parse):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const configSchema = z.object({ const configSchema = z.object({
database: z.object({ database: z.object({
host: z.string(), host: z.string(),
port: z.number(), port: z.number(),
name: z.string(), name: z.string()
}), }),
api: z.object({ api: z.object({
key: z.string(), key: z.string(),
timeout: z.number().default(5000), timeout: z.number().default(5000)
}), })
}) });
// Parse JSON then validate // Parse JSON then validate
const rawConfig = JSON.parse(fs.readFileSync('config.json', 'utf-8')) const rawConfig = JSON.parse(fs.readFileSync("config.json", "utf-8"));
const config = configSchema.parse(rawConfig) const config = configSchema.parse(rawConfig);
// config is fully typed: { database: { host: string, ... }, ... } // config is fully typed: { database: { host: string, ... }, ... }
// API response validation // API response validation
const userSchema = z.object({ const userSchema = z.object({
id: z.string(), id: z.string(),
name: z.string(), name: z.string(),
email: z.string().email(), email: z.string().email()
}) });
const response = await fetch('/api/user') const response = await fetch("/api/user");
const rawUser = await response.json() const rawUser = await response.json();
const user = userSchema.parse(rawUser) const user = userSchema.parse(rawUser);
// user is fully typed and validated // user is fully typed and validated
``` ```
@@ -64,50 +64,53 @@ const user = userSchema.parse(rawUser)
```typescript ```typescript
function parseJSON<T>(schema: z.ZodType<T>, json: string): T { function parseJSON<T>(schema: z.ZodType<T>, json: string): T {
return schema.parse(JSON.parse(json)) return schema.parse(JSON.parse(json));
} }
function safeParseJSON<T>(schema: z.ZodType<T>, json: string) { function safeParseJSON<T>(schema: z.ZodType<T>, json: string) {
try { try {
return { success: true as const, data: schema.parse(JSON.parse(json)) } return { success: true as const, data: schema.parse(JSON.parse(json)) };
} catch (error) { } catch (error) {
if (error instanceof SyntaxError) { if (error instanceof SyntaxError) {
return { success: false as const, error: 'Invalid JSON' } return { success: false as const, error: "Invalid JSON" };
} }
if (error instanceof z.ZodError) { if (error instanceof z.ZodError) {
return { success: false as const, error: error.issues } return { success: false as const, error: error.issues };
} }
throw error throw error;
} }
} }
// Usage // Usage
const config = parseJSON(configSchema, fs.readFileSync('config.json', 'utf-8')) const config = parseJSON(configSchema, fs.readFileSync("config.json", "utf-8"));
``` ```
**Validate localStorage/sessionStorage:** **Validate localStorage/sessionStorage:**
```typescript ```typescript
const cartSchema = z.array(z.object({ const cartSchema = z.array(
z.object({
productId: z.string(), productId: z.string(),
quantity: z.number().int().positive(), quantity: z.number().int().positive()
})) })
);
function getCart() { function getCart() {
const raw = localStorage.getItem('cart') const raw = localStorage.getItem("cart");
if (!raw) return [] if (!raw) return [];
const result = cartSchema.safeParse(JSON.parse(raw)) const result = cartSchema.safeParse(JSON.parse(raw));
if (!result.success) { if (!result.success) {
// Corrupted cart data - clear it // Corrupted cart data - clear it
localStorage.removeItem('cart') localStorage.removeItem("cart");
return [] return [];
} }
return result.data return result.data;
} }
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When you genuinely need to pass through arbitrary JSON without processing - When you genuinely need to pass through arbitrary JSON without processing
Reference: [Zod API - parse](https://zod.dev/api#parse) Reference: [Zod API - parse](https://zod.dev/api#parse)
@@ -12,23 +12,23 @@ tags: parse, safeParse, error-handling, validation
**Incorrect (parse without error handling):** **Incorrect (parse without error handling):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from "next/server";
const createUserSchema = z.object({ const createUserSchema = z.object({
email: z.string().email(), email: z.string().email(),
name: z.string().min(1), name: z.string().min(1)
}) });
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
const body = await req.json() const body = await req.json();
// If validation fails, this throws and crashes the handler // If validation fails, this throws and crashes the handler
const user = createUserSchema.parse(body) const user = createUserSchema.parse(body);
// Never reached if parse throws // Never reached if parse throws
await db.users.create({ data: user }) await db.users.create({ data: user });
return NextResponse.json({ success: true }) return NextResponse.json({ success: true });
} }
// Result: 500 Internal Server Error with stack trace // Result: 500 Internal Server Error with stack trace
``` ```
@@ -36,30 +36,30 @@ export async function POST(req: NextRequest) {
**Correct (using safeParse):** **Correct (using safeParse):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
import { NextRequest, NextResponse } from 'next/server' import { NextRequest, NextResponse } from "next/server";
const createUserSchema = z.object({ const createUserSchema = z.object({
email: z.string().email(), email: z.string().email(),
name: z.string().min(1), name: z.string().min(1)
}) });
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
const body = await req.json() const body = await req.json();
const result = createUserSchema.safeParse(body) const result = createUserSchema.safeParse(body);
if (!result.success) { if (!result.success) {
// Return structured error response // Return structured error response
return NextResponse.json( return NextResponse.json(
{ error: 'Validation failed', issues: result.error.issues }, { error: "Validation failed", issues: result.error.issues },
{ status: 400 } { status: 400 }
) );
} }
// result.data is typed correctly // result.data is typed correctly
await db.users.create({ data: result.data }) await db.users.create({ data: result.data });
return NextResponse.json({ success: true }) return NextResponse.json({ success: true });
} }
``` ```
@@ -85,16 +85,17 @@ if (result.success) {
```typescript ```typescript
// Internal data you control - parse is fine // Internal data you control - parse is fine
const config = configSchema.parse(JSON.parse(process.env.CONFIG)) const config = configSchema.parse(JSON.parse(process.env.CONFIG));
// Test assertions - parse throws helpful errors // Test assertions - parse throws helpful errors
expect(() => schema.parse(invalidData)).toThrow() expect(() => schema.parse(invalidData)).toThrow();
// Schema development - see errors immediately // Schema development - see errors immediately
schema.parse(testData) // See what fails during development schema.parse(testData); // See what fails during development
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Internal configuration parsing where invalid data should crash early - Internal configuration parsing where invalid data should crash early
- Tests where you want exceptions to fail the test - Tests where you want exceptions to fail the test
- Scripts where you want to see the full error - Scripts where you want to see the full error
@@ -12,24 +12,24 @@ Validate external data immediately when it enters your system—at API endpoints
**Incorrect (validating deep in business logic):** **Incorrect (validating deep in business logic):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// No validation at API boundary // No validation at API boundary
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
const body = await req.json() const body = await req.json();
// Raw unknown data passed through // Raw unknown data passed through
return await processOrder(body) return await processOrder(body);
} }
async function processOrder(data: unknown) { async function processOrder(data: unknown) {
// Data passed around unvalidated // Data passed around unvalidated
const items = await calculateTotals(data) const items = await calculateTotals(data);
return await chargeCustomer(data, items) return await chargeCustomer(data, items);
} }
async function calculateTotals(data: unknown) { async function calculateTotals(data: unknown) {
// Finally validating way too late // Finally validating way too late
const order = orderSchema.parse(data) // Throws here, far from entry point const order = orderSchema.parse(data); // Throws here, far from entry point
// ... // ...
} }
// Hard to trace where bad data came from // Hard to trace where bad data came from
@@ -38,52 +38,56 @@ async function calculateTotals(data: unknown) {
**Correct (validating at boundary):** **Correct (validating at boundary):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const orderSchema = z.object({ const orderSchema = z.object({
customerId: z.string().uuid(), customerId: z.string().uuid(),
items: z.array(z.object({ items: z
.array(
z.object({
productId: z.string(), productId: z.string(),
quantity: z.number().int().positive(), quantity: z.number().int().positive()
})).min(1), })
)
.min(1),
shippingAddress: z.object({ shippingAddress: z.object({
street: z.string(), street: z.string(),
city: z.string(), city: z.string(),
country: z.string(), country: z.string()
}), })
}) });
type Order = z.infer<typeof orderSchema> type Order = z.infer<typeof orderSchema>;
// Validate immediately at boundary // Validate immediately at boundary
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
const body = await req.json() const body = await req.json();
const result = orderSchema.safeParse(body) const result = orderSchema.safeParse(body);
if (!result.success) { if (!result.success) {
return NextResponse.json( return NextResponse.json(
{ error: 'Invalid order', issues: result.error.issues }, { error: "Invalid order", issues: result.error.issues },
{ status: 400 } { status: 400 }
) );
} }
// Now data is validated and typed // Now data is validated and typed
return await processOrder(result.data) return await processOrder(result.data);
} }
// Business logic receives typed, validated data // Business logic receives typed, validated data
async function processOrder(order: Order) { async function processOrder(order: Order) {
// order is guaranteed to match schema // order is guaranteed to match schema
const items = await calculateTotals(order) const items = await calculateTotals(order);
return await chargeCustomer(order, items) return await chargeCustomer(order, items);
} }
async function calculateTotals(order: Order) { async function calculateTotals(order: Order) {
// No validation needed - type guarantees shape // No validation needed - type guarantees shape
return order.items.map(item => ({ return order.items.map((item) => ({
...item, ...item,
total: item.quantity * getPrice(item.productId), total: item.quantity * getPrice(item.productId)
})) }));
} }
``` ```
@@ -92,28 +96,29 @@ async function calculateTotals(order: Order) {
```typescript ```typescript
// API endpoints // API endpoints
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
const data = await req.json() const data = await req.json();
const validated = requestSchema.safeParse(data) const validated = requestSchema.safeParse(data);
// ... // ...
} }
// Message queue consumers // Message queue consumers
async function handleMessage(rawMessage: string) { async function handleMessage(rawMessage: string) {
const data = JSON.parse(rawMessage) const data = JSON.parse(rawMessage);
const validated = messageSchema.safeParse(data) const validated = messageSchema.safeParse(data);
// ... // ...
} }
// Configuration loading // Configuration loading
const config = configSchema.parse(JSON.parse(process.env.CONFIG!)) const config = configSchema.parse(JSON.parse(process.env.CONFIG!));
// External API responses // External API responses
const response = await fetch('/api/users') const response = await fetch("/api/users");
const data = await response.json() const data = await response.json();
const users = usersResponseSchema.parse(data) const users = usersResponseSchema.parse(data);
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Internal function calls with already-validated data - Internal function calls with already-validated data
- Performance-critical hot paths (validate once, trust afterward) - Performance-critical hot paths (validate once, trust afterward)
+37 -36
View File
@@ -12,40 +12,40 @@ Validating large arrays (thousands of items) can become a performance bottleneck
**Baseline performance:** **Baseline performance:**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const itemSchema = z.object({ const itemSchema = z.object({
id: z.string(), id: z.string(),
value: z.number(), value: z.number()
}) });
const arraySchema = z.array(itemSchema) const arraySchema = z.array(itemSchema);
// 10,000 items: ~100ms // 10,000 items: ~100ms
// 100,000 items: ~1000ms // 100,000 items: ~1000ms
arraySchema.parse(largeArray) arraySchema.parse(largeArray);
``` ```
**Early exit on first error:** **Early exit on first error:**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
function validateArrayFastFail<T>( function validateArrayFastFail<T>(
schema: z.ZodType<T>, schema: z.ZodType<T>,
items: unknown[] items: unknown[]
): { success: true; data: T[] } | { success: false; error: z.ZodError; index: number } { ): { success: true; data: T[] } | { success: false; error: z.ZodError; index: number } {
const validated: T[] = [] const validated: T[] = [];
for (let i = 0; i < items.length; i++) { for (let i = 0; i < items.length; i++) {
const result = schema.safeParse(items[i]) const result = schema.safeParse(items[i]);
if (!result.success) { if (!result.success) {
return { success: false, error: result.error, index: i } return { success: false, error: result.error, index: i };
} }
validated.push(result.data) validated.push(result.data);
} }
return { success: true, data: validated } return { success: true, data: validated };
} }
// Stops at first invalid item instead of validating all // Stops at first invalid item instead of validating all
@@ -60,27 +60,25 @@ function validateSample<T>(
sampleSize: number = 100 sampleSize: number = 100
): { valid: boolean; sampleErrors?: z.ZodIssue[] } { ): { valid: boolean; sampleErrors?: z.ZodIssue[] } {
// Validate random sample // Validate random sample
const indices = new Set<number>() const indices = new Set<number>();
while (indices.size < Math.min(sampleSize, items.length)) { while (indices.size < Math.min(sampleSize, items.length)) {
indices.add(Math.floor(Math.random() * items.length)) indices.add(Math.floor(Math.random() * items.length));
} }
const errors: z.ZodIssue[] = [] const errors: z.ZodIssue[] = [];
for (const i of indices) { for (const i of indices) {
const result = schema.safeParse(items[i]) const result = schema.safeParse(items[i]);
if (!result.success) { if (!result.success) {
errors.push(...result.error.issues) errors.push(...result.error.issues);
} }
} }
return errors.length > 0 return errors.length > 0 ? { valid: false, sampleErrors: errors } : { valid: true };
? { valid: false, sampleErrors: errors }
: { valid: true }
} }
// Check 100 random items from 100,000 - very fast // Check 100 random items from 100,000 - very fast
const check = validateSample(itemSchema, hugeArray) const check = validateSample(itemSchema, hugeArray);
``` ```
**Batched validation with progress:** **Batched validation with progress:**
@@ -92,40 +90,42 @@ async function validateInBatches<T>(
batchSize: number = 1000, batchSize: number = 1000,
onProgress?: (percent: number) => void onProgress?: (percent: number) => void
): Promise<z.SafeParseReturnType<unknown, T[]>> { ): Promise<z.SafeParseReturnType<unknown, T[]>> {
const validated: T[] = [] const validated: T[] = [];
const errors: z.ZodIssue[] = [] const errors: z.ZodIssue[] = [];
for (let i = 0; i < items.length; i += batchSize) { for (let i = 0; i < items.length; i += batchSize) {
const batch = items.slice(i, i + batchSize) const batch = items.slice(i, i + batchSize);
// Validate batch // Validate batch
for (let j = 0; j < batch.length; j++) { for (let j = 0; j < batch.length; j++) {
const result = schema.safeParse(batch[j]) const result = schema.safeParse(batch[j]);
if (result.success) { if (result.success) {
validated.push(result.data) validated.push(result.data);
} else { } else {
errors.push(...result.error.issues.map(issue => ({ errors.push(
...result.error.issues.map((issue) => ({
...issue, ...issue,
path: [i + j, ...issue.path], path: [i + j, ...issue.path]
}))) }))
);
} }
} }
// Report progress and yield to event loop // Report progress and yield to event loop
onProgress?.(Math.min(100, ((i + batchSize) / items.length) * 100)) onProgress?.(Math.min(100, ((i + batchSize) / items.length) * 100));
await new Promise(resolve => setTimeout(resolve, 0)) await new Promise((resolve) => setTimeout(resolve, 0));
} }
if (errors.length > 0) { if (errors.length > 0) {
return { success: false, error: new z.ZodError(errors) } return { success: false, error: new z.ZodError(errors) };
} }
return { success: true, data: validated } return { success: true, data: validated };
} }
// Use with progress reporting // Use with progress reporting
await validateInBatches(itemSchema, largeArray, 1000, (percent) => { await validateInBatches(itemSchema, largeArray, 1000, (percent) => {
console.log(`Validating: ${percent.toFixed(1)}%`) console.log(`Validating: ${percent.toFixed(1)}%`);
}) });
``` ```
**Streaming validation:** **Streaming validation:**
@@ -136,17 +136,18 @@ async function* validateStream<T>(
items: AsyncIterable<unknown> items: AsyncIterable<unknown>
): AsyncGenerator<T, void, unknown> { ): AsyncGenerator<T, void, unknown> {
for await (const item of items) { for await (const item of items) {
yield schema.parse(item) // Throws on invalid yield schema.parse(item); // Throws on invalid
} }
} }
// Process items as they arrive // Process items as they arrive
for await (const validItem of validateStream(itemSchema, dataStream)) { for await (const validItem of validateStream(itemSchema, dataStream)) {
await processItem(validItem) await processItem(validItem);
} }
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Small arrays (< 1000 items) - standard validation is fine - Small arrays (< 1000 items) - standard validation is fine
- When all items must be validated for correctness guarantees - When all items must be validated for correctness guarantees
@@ -12,22 +12,22 @@ Zod 4 uses JIT (Just-In-Time) compilation to speed up repeated parsing, but this
**Incorrect (schema creation in hot path):** **Incorrect (schema creation in hot path):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
async function validateBatch(items: unknown[]) { async function validateBatch(items: unknown[]) {
const results = [] const results = [];
for (const item of items) { for (const item of items) {
// Schema created for EACH item - slow! // Schema created for EACH item - slow!
const schema = z.object({ const schema = z.object({
id: z.string(), id: z.string(),
value: z.number(), value: z.number()
}) });
results.push(schema.safeParse(item)) results.push(schema.safeParse(item));
} }
return results return results;
} }
// 1000 items = 1000 schema creations = ~150ms overhead // 1000 items = 1000 schema creations = ~150ms overhead
@@ -36,17 +36,17 @@ async function validateBatch(items: unknown[]) {
**Correct (pre-created schema):** **Correct (pre-created schema):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Schema created ONCE // Schema created ONCE
const itemSchema = z.object({ const itemSchema = z.object({
id: z.string(), id: z.string(),
value: z.number(), value: z.number()
}) });
async function validateBatch(items: unknown[]) { async function validateBatch(items: unknown[]) {
// Reuse the same schema instance // Reuse the same schema instance
return items.map(item => itemSchema.safeParse(item)) return items.map((item) => itemSchema.safeParse(item));
} }
// 1000 items = 1 schema creation + 1000 fast parses // 1000 items = 1 schema creation + 1000 fast parses
@@ -55,26 +55,26 @@ async function validateBatch(items: unknown[]) {
**Dynamic schemas with caching:** **Dynamic schemas with caching:**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Cache for dynamically-configured schemas // Cache for dynamically-configured schemas
const schemaCache = new WeakMap<object, z.ZodType>() const schemaCache = new WeakMap<object, z.ZodType>();
function getSchemaForConfig(config: { fields: string[] }) { function getSchemaForConfig(config: { fields: string[] }) {
// Check cache first // Check cache first
if (schemaCache.has(config)) { if (schemaCache.has(config)) {
return schemaCache.get(config)! return schemaCache.get(config)!;
} }
// Create and cache // Create and cache
const shape: Record<string, z.ZodString> = {} const shape: Record<string, z.ZodString> = {};
for (const field of config.fields) { for (const field of config.fields) {
shape[field] = z.string() shape[field] = z.string();
} }
const schema = z.object(shape) const schema = z.object(shape);
schemaCache.set(config, schema) schemaCache.set(config, schema);
return schema return schema;
} }
// Subsequent calls with same config reuse cached schema // Subsequent calls with same config reuse cached schema
@@ -83,10 +83,10 @@ function getSchemaForConfig(config: { fields: string[] }) {
**Lazy schema creation:** **Lazy schema creation:**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Schema created only when first used // Schema created only when first used
let _userSchema: z.ZodObject<any> | null = null let _userSchema: z.ZodObject<any> | null = null;
function getUserSchema() { function getUserSchema() {
if (!_userSchema) { if (!_userSchema) {
@@ -95,11 +95,11 @@ function getUserSchema() {
email: z.string().email(), email: z.string().email(),
profile: z.object({ profile: z.object({
name: z.string(), name: z.string(),
avatar: z.string().url().optional(), avatar: z.string().url().optional()
}),
}) })
});
} }
return _userSchema return _userSchema;
} }
// Or use a getter // Or use a getter
@@ -107,11 +107,11 @@ const schemas = {
_user: null as z.ZodType | null, _user: null as z.ZodType | null,
get user() { get user() {
if (!this._user) { if (!this._user) {
this._user = z.object({ /* ... */ }) this._user = z.object({/* ... */});
} }
return this._user return this._user;
} }
} };
``` ```
**Benchmark considerations:** **Benchmark considerations:**
@@ -132,6 +132,7 @@ const schemas = {
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- One-off validation where schema is used once - One-off validation where schema is used once
- Dynamically generated forms where fields change per request - Dynamically generated forms where fields change per request
- Test files where performance doesn't matter - Test files where performance doesn't matter
@@ -58,18 +58,19 @@ function UserForm() {
**For dynamic schemas, use useMemo:** **For dynamic schemas, use useMemo:**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
import { useMemo } from 'react' import { useMemo } from "react";
function DynamicForm({ minAge }: { minAge: number }) { function DynamicForm({ minAge }: { minAge: number }) {
// Schema only recreated when minAge changes // Schema only recreated when minAge changes
const userSchema = useMemo(() => const userSchema = useMemo(
() =>
z.object({ z.object({
name: z.string().min(1), name: z.string().min(1),
age: z.number().min(minAge), age: z.number().min(minAge)
}), }),
[minAge] [minAge]
) );
// ... // ...
} }
@@ -79,19 +80,19 @@ function DynamicForm({ minAge }: { minAge: number }) {
```typescript ```typescript
// schemas/user.ts - created once per process // schemas/user.ts - created once per process
import { z } from 'zod' import { z } from "zod";
export const userSchema = z.object({ export const userSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
email: z.string().email(), email: z.string().email()
}) });
// api/users.ts // api/users.ts
import { userSchema } from '@/schemas/user' import { userSchema } from "@/schemas/user";
export async function POST(req: Request) { export async function POST(req: Request) {
const body = await req.json() const body = await req.json();
const result = userSchema.safeParse(body) // Reuses cached schema const result = userSchema.safeParse(body); // Reuses cached schema
// ... // ...
} }
``` ```
@@ -103,35 +104,39 @@ export async function POST(req: Request) {
function createUserSchema(role: string) { function createUserSchema(role: string) {
return z.object({ return z.object({
name: z.string(), name: z.string(),
permissions: z.array(z.string()), permissions: z.array(z.string())
}) });
} }
// Called in hot loop // Called in hot loop
users.forEach(user => { users.forEach((user) => {
createUserSchema(user.role).parse(user) // New schema every iteration! createUserSchema(user.role).parse(user); // New schema every iteration!
}) });
// GOOD: Cache by key // GOOD: Cache by key
const schemaCache = new Map<string, z.ZodObject<any>>() const schemaCache = new Map<string, z.ZodObject<any>>();
function getUserSchema(role: string) { function getUserSchema(role: string) {
if (!schemaCache.has(role)) { if (!schemaCache.has(role)) {
schemaCache.set(role, z.object({ schemaCache.set(
role,
z.object({
name: z.string(), name: z.string(),
permissions: z.array(z.string()), permissions: z.array(z.string())
})) })
);
} }
return schemaCache.get(role)! return schemaCache.get(role)!;
} }
// Reuses cached schemas // Reuses cached schemas
users.forEach(user => { users.forEach((user) => {
getUserSchema(user.role).parse(user) getUserSchema(user.role).parse(user);
}) });
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- One-off validation where schema is used once - One-off validation where schema is used once
- Test files where performance doesn't matter - Test files where performance doesn't matter
@@ -13,15 +13,15 @@ For applications with many complex schemas, importing all of them upfront increa
```typescript ```typescript
// schemas/index.ts - barrel file with everything // schemas/index.ts - barrel file with everything
export * from './user' export * from "./user";
export * from './order' export * from "./order";
export * from './product' export * from "./product";
export * from './analytics' // Large, complex schema export * from "./analytics"; // Large, complex schema
export * from './reports' // Another large schema export * from "./reports"; // Another large schema
export * from './admin' // Admin-only schemas export * from "./admin"; // Admin-only schemas
// app/page.tsx // app/page.tsx
import { userSchema, orderSchema, analyticsSchema, reportsSchema } from '@/schemas' import { userSchema, orderSchema, analyticsSchema, reportsSchema } from "@/schemas";
// All schemas loaded even if not used on this page // All schemas loaded even if not used on this page
``` ```
@@ -29,17 +29,17 @@ import { userSchema, orderSchema, analyticsSchema, reportsSchema } from '@/schem
```typescript ```typescript
// Only import what's immediately needed // Only import what's immediately needed
import { userSchema } from '@/schemas/user' import { userSchema } from "@/schemas/user";
async function loadAnalyticsSchema() { async function loadAnalyticsSchema() {
const { analyticsSchema } = await import('@/schemas/analytics') const { analyticsSchema } = await import("@/schemas/analytics");
return analyticsSchema return analyticsSchema;
} }
// Use when needed // Use when needed
async function handleAnalyticsData(data: unknown) { async function handleAnalyticsData(data: unknown) {
const schema = await loadAnalyticsSchema() const schema = await loadAnalyticsSchema();
return schema.safeParse(data) return schema.safeParse(data);
} }
``` ```
@@ -104,30 +104,31 @@ export default function ReportsForm() {
```typescript ```typescript
// schemas/registry.ts // schemas/registry.ts
const schemaLoaders = { const schemaLoaders = {
user: () => import('./user').then(m => m.userSchema), user: () => import("./user").then((m) => m.userSchema),
order: () => import('./order').then(m => m.orderSchema), order: () => import("./order").then((m) => m.orderSchema),
analytics: () => import('./analytics').then(m => m.analyticsSchema), analytics: () => import("./analytics").then((m) => m.analyticsSchema),
reports: () => import('./reports').then(m => m.reportsSchema), reports: () => import("./reports").then((m) => m.reportsSchema)
} as const } as const;
type SchemaName = keyof typeof schemaLoaders type SchemaName = keyof typeof schemaLoaders;
const schemaCache = new Map<SchemaName, z.ZodType>() const schemaCache = new Map<SchemaName, z.ZodType>();
export async function getSchema(name: SchemaName) { export async function getSchema(name: SchemaName) {
if (!schemaCache.has(name)) { if (!schemaCache.has(name)) {
const schema = await schemaLoaders[name]() const schema = await schemaLoaders[name]();
schemaCache.set(name, schema) schemaCache.set(name, schema);
} }
return schemaCache.get(name)! return schemaCache.get(name)!;
} }
// Usage // Usage
const schema = await getSchema('analytics') const schema = await getSchema("analytics");
schema.parse(data) schema.parse(data);
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Server-side rendering where all code is available - Server-side rendering where all code is available
- Small applications with few schemas - Small applications with few schemas
- Schemas used on every page (defeats purpose) - Schemas used on every page (defeats purpose)
+22 -21
View File
@@ -19,58 +19,58 @@ For frontend applications where bundle size is critical, use `@zod/mini` instead
// - Tree-shaking is important // - Tree-shaking is important
// Zod: ~17kb gzipped // Zod: ~17kb gzipped
import { z } from 'zod' import { z } from "zod";
// Zod Mini: ~1.9kb gzipped (when tree-shaken) // Zod Mini: ~1.9kb gzipped (when tree-shaken)
import * as z from '@zod/mini' import * as z from "@zod/mini";
``` ```
**Standard Zod (method chaining):** **Standard Zod (method chaining):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Methods are attached to schema objects - hard to tree-shake // Methods are attached to schema objects - hard to tree-shake
const userSchema = z.object({ const userSchema = z.object({
name: z.string().min(1).max(100), name: z.string().min(1).max(100),
email: z.string().email(), email: z.string().email(),
age: z.number().int().positive(), age: z.number().int().positive()
}) });
const result = userSchema.safeParse(data) const result = userSchema.safeParse(data);
``` ```
**Zod Mini (functional API):** **Zod Mini (functional API):**
```typescript ```typescript
import * as z from '@zod/mini' import * as z from "@zod/mini";
// Functions are imported individually - tree-shakeable // Functions are imported individually - tree-shakeable
const userSchema = z.object({ const userSchema = z.object({
name: z.pipe(z.string(), z.minLength(1), z.maxLength(100)), name: z.pipe(z.string(), z.minLength(1), z.maxLength(100)),
email: z.pipe(z.string(), z.email()), email: z.pipe(z.string(), z.email()),
age: z.pipe(z.number(), z.int(), z.positive()), age: z.pipe(z.number(), z.int(), z.positive())
}) });
const result = z.safeParse(userSchema, data) const result = z.safeParse(userSchema, data);
``` ```
**API differences:** **API differences:**
```typescript ```typescript
// Standard Zod // Standard Zod
z.string().min(5).max(100).email() z.string().min(5).max(100).email();
z.number().int().positive() z.number().int().positive();
z.array(z.string()).min(1) z.array(z.string()).min(1);
schema.parse(data) schema.parse(data);
schema.safeParse(data) schema.safeParse(data);
// Zod Mini // Zod Mini
z.pipe(z.string(), z.minLength(5), z.maxLength(100), z.email()) z.pipe(z.string(), z.minLength(5), z.maxLength(100), z.email());
z.pipe(z.number(), z.int(), z.positive()) z.pipe(z.number(), z.int(), z.positive());
z.pipe(z.array(z.string()), z.minLength(1)) z.pipe(z.array(z.string()), z.minLength(1));
z.parse(schema, data) z.parse(schema, data);
z.safeParse(schema, data) z.safeParse(schema, data);
``` ```
**When to stick with regular Zod:** **When to stick with regular Zod:**
@@ -104,12 +104,13 @@ z.safeParse(schema, data)
**Bundle size comparison:** **Bundle size comparison:**
| Package | Gzipped Size | Use Case | | Package | Gzipped Size | Use Case |
|---------|--------------|----------| | ----------- | ------------ | --------------- |
| `zod@3` | ~13kb | Legacy, stable | | `zod@3` | ~13kb | Legacy, stable |
| `zod@4` | ~17kb | Full features | | `zod@4` | ~17kb | Full features |
| `@zod/mini` | ~1.9kb | Bundle-critical | | `@zod/mini` | ~1.9kb | Bundle-critical |
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Server-side applications (bundle size irrelevant) - Server-side applications (bundle size irrelevant)
- When method chaining ergonomics are preferred - When method chaining ergonomics are preferred
- Complex schemas that benefit from full API - Complex schemas that benefit from full API
@@ -12,23 +12,25 @@ When using `.refine()` on object schemas for cross-field validation, add a `path
**Incorrect (error at object level):** **Incorrect (error at object level):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const formSchema = z.object({ const formSchema = z
.object({
password: z.string().min(8), password: z.string().min(8),
confirmPassword: z.string(), confirmPassword: z.string()
}).refine( })
.refine(
(data) => data.password === data.confirmPassword, (data) => data.password === data.confirmPassword,
{ message: 'Passwords do not match' } // No path specified { message: "Passwords do not match" } // No path specified
) );
const result = formSchema.safeParse({ const result = formSchema.safeParse({
password: 'secret123', password: "secret123",
confirmPassword: 'different', confirmPassword: "different"
}) });
if (!result.success) { if (!result.success) {
const flattened = result.error.flatten() const flattened = result.error.flatten();
// { // {
// formErrors: ['Passwords do not match'], // At form level! // formErrors: ['Passwords do not match'], // At form level!
// fieldErrors: {} // Empty - no field association // fieldErrors: {} // Empty - no field association
@@ -41,26 +43,25 @@ if (!result.success) {
**Correct (error with path):** **Correct (error with path):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const formSchema = z.object({ const formSchema = z
.object({
password: z.string().min(8), password: z.string().min(8),
confirmPassword: z.string(), confirmPassword: z.string()
}).refine( })
(data) => data.password === data.confirmPassword, .refine((data) => data.password === data.confirmPassword, {
{ message: "Passwords do not match",
message: 'Passwords do not match', path: ["confirmPassword"] // Error appears on this field
path: ['confirmPassword'], // Error appears on this field });
}
)
const result = formSchema.safeParse({ const result = formSchema.safeParse({
password: 'secret123', password: "secret123",
confirmPassword: 'different', confirmPassword: "different"
}) });
if (!result.success) { if (!result.success) {
const flattened = result.error.flatten() const flattened = result.error.flatten();
// { // {
// formErrors: [], // formErrors: [],
// fieldErrors: { // fieldErrors: {
@@ -75,66 +76,73 @@ if (!result.success) {
**Multiple cross-field validations:** **Multiple cross-field validations:**
```typescript ```typescript
const dateRangeSchema = z.object({ const dateRangeSchema = z
.object({
startDate: z.coerce.date(), startDate: z.coerce.date(),
endDate: z.coerce.date(), endDate: z.coerce.date(),
minDays: z.number().optional(), minDays: z.number().optional(),
maxDays: z.number().optional(), maxDays: z.number().optional()
}).refine( })
(data) => data.endDate >= data.startDate, .refine((data) => data.endDate >= data.startDate, {
{ message: 'End date must be after start date', path: ['endDate'] } message: "End date must be after start date",
).refine( path: ["endDate"]
})
.refine(
(data) => { (data) => {
if (!data.minDays) return true if (!data.minDays) return true;
const days = (data.endDate.getTime() - data.startDate.getTime()) / 86400000 const days = (data.endDate.getTime() - data.startDate.getTime()) / 86400000;
return days >= data.minDays return days >= data.minDays;
}, },
{ message: 'Date range is too short', path: ['endDate'] } { message: "Date range is too short", path: ["endDate"] }
).refine( )
.refine(
(data) => { (data) => {
if (!data.maxDays) return true if (!data.maxDays) return true;
const days = (data.endDate.getTime() - data.startDate.getTime()) / 86400000 const days = (data.endDate.getTime() - data.startDate.getTime()) / 86400000;
return days <= data.maxDays return days <= data.maxDays;
}, },
{ message: 'Date range is too long', path: ['endDate'] } { message: "Date range is too long", path: ["endDate"] }
) );
``` ```
**With superRefine for multiple path errors:** **With superRefine for multiple path errors:**
```typescript ```typescript
const orderSchema = z.object({ const orderSchema = z
.object({
billingAddress: z.object({ billingAddress: z.object({
street: z.string(), street: z.string(),
city: z.string(), city: z.string()
}), }),
shippingAddress: z.object({ shippingAddress: z.object({
street: z.string(), street: z.string(),
city: z.string(), city: z.string()
}), }),
sameAsBilling: z.boolean(), sameAsBilling: z.boolean()
}).superRefine((data, ctx) => { })
.superRefine((data, ctx) => {
if (data.sameAsBilling) { if (data.sameAsBilling) {
// If sameAsBilling but addresses differ, show errors on shipping // If sameAsBilling but addresses differ, show errors on shipping
if (data.shippingAddress.street !== data.billingAddress.street) { if (data.shippingAddress.street !== data.billingAddress.street) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: 'Must match billing address', message: "Must match billing address",
path: ['shippingAddress', 'street'], // Nested path path: ["shippingAddress", "street"] // Nested path
}) });
} }
if (data.shippingAddress.city !== data.billingAddress.city) { if (data.shippingAddress.city !== data.billingAddress.city) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: 'Must match billing address', message: "Must match billing address",
path: ['shippingAddress', 'city'], path: ["shippingAddress", "city"]
}) });
} }
} }
}) });
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When the error genuinely applies to the whole object - When the error genuinely applies to the whole object
- Simple single-field refinements (path is implicit) - Simple single-field refinements (path is implicit)
+36 -41
View File
@@ -12,24 +12,24 @@ When parsing data that might have some invalid fields but you want to accept wha
**Incorrect (all-or-nothing parsing):** **Incorrect (all-or-nothing parsing):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userPrefsSchema = z.object({ const userPrefsSchema = z.object({
theme: z.enum(['light', 'dark']), theme: z.enum(["light", "dark"]),
fontSize: z.number().min(8).max(32), fontSize: z.number().min(8).max(32),
language: z.string(), language: z.string(),
notifications: z.boolean(), notifications: z.boolean()
}) });
// Corrupted localStorage data // Corrupted localStorage data
const stored = { const stored = {
theme: 'invalid-theme', // Bad theme: "invalid-theme", // Bad
fontSize: 200, // Bad fontSize: 200, // Bad
language: 'en', // Good language: "en", // Good
notifications: 'yes', // Bad - should be boolean notifications: "yes" // Bad - should be boolean
} };
userPrefsSchema.parse(stored) userPrefsSchema.parse(stored);
// ZodError: Invalid enum value at "theme" // ZodError: Invalid enum value at "theme"
// User loses ALL their preferences because one field is bad // User loses ALL their preferences because one field is bad
``` ```
@@ -37,24 +37,24 @@ userPrefsSchema.parse(stored)
**Correct (fault-tolerant with catch):** **Correct (fault-tolerant with catch):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userPrefsSchema = z.object({ const userPrefsSchema = z.object({
theme: z.enum(['light', 'dark']).catch('light'), theme: z.enum(["light", "dark"]).catch("light"),
fontSize: z.number().min(8).max(32).catch(16), fontSize: z.number().min(8).max(32).catch(16),
language: z.string().catch('en'), language: z.string().catch("en"),
notifications: z.boolean().catch(true), notifications: z.boolean().catch(true)
}) });
// Corrupted data // Corrupted data
const stored = { const stored = {
theme: 'invalid-theme', theme: "invalid-theme",
fontSize: 200, fontSize: 200,
language: 'en', language: "en",
notifications: 'yes', notifications: "yes"
} };
const prefs = userPrefsSchema.parse(stored) const prefs = userPrefsSchema.parse(stored);
// { // {
// theme: 'light', // Fallback used // theme: 'light', // Fallback used
// fontSize: 16, // Fallback used // fontSize: 16, // Fallback used
@@ -70,10 +70,10 @@ const prefs = userPrefsSchema.parse(stored)
// Factory function receives the caught error // Factory function receives the caught error
const schema = z.object({ const schema = z.object({
data: z.array(z.number()).catch((ctx) => { data: z.array(z.number()).catch((ctx) => {
console.warn('Invalid data array:', ctx.error) console.warn("Invalid data array:", ctx.error);
return [] // Return empty array as fallback return []; // Return empty array as fallback
}), })
}) });
``` ```
**Use case: API response resilience:** **Use case: API response resilience:**
@@ -84,21 +84,21 @@ const productSchema = z.object({
name: z.string(), name: z.string(),
price: z.number().positive(), price: z.number().positive(),
// Legacy field that might be missing or wrong format // Legacy field that might be missing or wrong format
legacyCode: z.string().catch('UNKNOWN'), legacyCode: z.string().catch("UNKNOWN"),
// External data that might be malformed // External data that might be malformed
metadata: z.record(z.string()).catch({}), metadata: z.record(z.string()).catch({})
}) });
// API returns partial data // API returns partial data
const apiResponse = { const apiResponse = {
id: 'prod-123', id: "prod-123",
name: 'Widget', name: "Widget",
price: 29.99, price: 29.99,
legacyCode: null, // Bad - should be string legacyCode: null, // Bad - should be string
metadata: 'invalid', // Bad - should be object metadata: "invalid" // Bad - should be object
} };
const product = productSchema.parse(apiResponse) const product = productSchema.parse(apiResponse);
// Works! Returns product with fallbacks for bad fields // Works! Returns product with fallbacks for bad fields
``` ```
@@ -106,13 +106,13 @@ const product = productSchema.parse(apiResponse)
```typescript ```typescript
// .default() - only fills in undefined // .default() - only fills in undefined
z.string().default('fallback') z.string().default("fallback");
// undefined -> 'fallback' // undefined -> 'fallback'
// null -> ZodError // null -> ZodError
// '' -> '' (empty string is valid) // '' -> '' (empty string is valid)
// .catch() - fallback for ANY parse failure // .catch() - fallback for ANY parse failure
z.string().catch('fallback') z.string().catch("fallback");
// undefined -> 'fallback' // undefined -> 'fallback'
// null -> 'fallback' // null -> 'fallback'
// 123 -> 'fallback' // 123 -> 'fallback'
@@ -123,19 +123,14 @@ z.string().catch('fallback')
```typescript ```typescript
// Catch only specific validation failures // Catch only specific validation failures
const schema = z.string() const schema = z.string().email().catch("invalid@example.com"); // Fallback if not valid email
.email()
.catch('invalid@example.com') // Fallback if not valid email
// Chain for complex defaults // Chain for complex defaults
const ageSchema = z.coerce.number() const ageSchema = z.coerce.number().int().min(0).max(120).catch(0); // Invalid ages become 0
.int()
.min(0)
.max(120)
.catch(0) // Invalid ages become 0
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When invalid data should cause errors (strict validation) - When invalid data should cause errors (strict validation)
- When you need to know which fields failed (use safeParse) - When you need to know which fields failed (use safeParse)
- Critical fields that must be valid - Critical fields that must be valid
@@ -12,30 +12,30 @@ When a field is optional but should have a default value when missing, use `.def
**Incorrect (defaults spread across codebase):** **Incorrect (defaults spread across codebase):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const configSchema = z.object({ const configSchema = z.object({
timeout: z.number().optional(), timeout: z.number().optional(),
retries: z.number().optional(), retries: z.number().optional(),
debug: z.boolean().optional(), debug: z.boolean().optional()
}) });
type Config = z.infer<typeof configSchema> type Config = z.infer<typeof configSchema>;
function createClient(config: Config) { function createClient(config: Config) {
// Defaults handled in business logic - duplicated everywhere // Defaults handled in business logic - duplicated everywhere
const timeout = config.timeout ?? 5000 const timeout = config.timeout ?? 5000;
const retries = config.retries ?? 3 const retries = config.retries ?? 3;
const debug = config.debug ?? false const debug = config.debug ?? false;
// ... // ...
} }
function createOtherClient(config: Config) { function createOtherClient(config: Config) {
// Same defaults duplicated - risk of inconsistency // Same defaults duplicated - risk of inconsistency
const timeout = config.timeout ?? 5000 const timeout = config.timeout ?? 5000;
const retries = config.retries ?? 3 // What if someone uses 2 here? const retries = config.retries ?? 3; // What if someone uses 2 here?
const debug = config.debug ?? false const debug = config.debug ?? false;
// ... // ...
} }
@@ -44,30 +44,30 @@ function createOtherClient(config: Config) {
**Correct (defaults in schema):** **Correct (defaults in schema):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const configSchema = z.object({ const configSchema = z.object({
timeout: z.number().default(5000), timeout: z.number().default(5000),
retries: z.number().default(3), retries: z.number().default(3),
debug: z.boolean().default(false), debug: z.boolean().default(false)
}) });
type Config = z.infer<typeof configSchema> type Config = z.infer<typeof configSchema>;
// { timeout: number; retries: number; debug: boolean } // { timeout: number; retries: number; debug: boolean }
// No optional - defaults fill in missing values // No optional - defaults fill in missing values
function createClient(config: Config) { function createClient(config: Config) {
// config.timeout is guaranteed to exist // config.timeout is guaranteed to exist
console.log(config.timeout) // 5000 if not provided console.log(config.timeout); // 5000 if not provided
console.log(config.retries) // 3 if not provided console.log(config.retries); // 3 if not provided
console.log(config.debug) // false if not provided console.log(config.debug); // false if not provided
} }
// Parse fills in defaults // Parse fills in defaults
configSchema.parse({}) configSchema.parse({});
// { timeout: 5000, retries: 3, debug: false } // { timeout: 5000, retries: 3, debug: false }
configSchema.parse({ timeout: 10000 }) configSchema.parse({ timeout: 10000 });
// { timeout: 10000, retries: 3, debug: false } // { timeout: 10000, retries: 3, debug: false }
``` ```
@@ -76,13 +76,13 @@ configSchema.parse({ timeout: 10000 })
```typescript ```typescript
const schema = z.object({ const schema = z.object({
name: z.string(), name: z.string(),
role: z.enum(['admin', 'user']).default('user'), role: z.enum(["admin", "user"]).default("user")
}) });
type SchemaInput = z.input<typeof schema> type SchemaInput = z.input<typeof schema>;
// { name: string; role?: 'admin' | 'user' } // { name: string; role?: 'admin' | 'user' }
type SchemaOutput = z.output<typeof schema> type SchemaOutput = z.output<typeof schema>;
// { name: string; role: 'admin' | 'user' } // { name: string; role: 'admin' | 'user' }
// Input type is optional, output type is required // Input type is optional, output type is required
@@ -93,38 +93,39 @@ type SchemaOutput = z.output<typeof schema>
```typescript ```typescript
// Static default // Static default
const schema1 = z.object({ const schema1 = z.object({
id: z.string().default('temp-id'), id: z.string().default("temp-id")
}) });
// Factory function for dynamic defaults // Factory function for dynamic defaults
const schema2 = z.object({ const schema2 = z.object({
id: z.string().default(() => crypto.randomUUID()), id: z.string().default(() => crypto.randomUUID()),
createdAt: z.date().default(() => new Date()), createdAt: z.date().default(() => new Date())
}) });
// Each parse creates new values // Each parse creates new values
schema2.parse({}) // { id: 'abc-123...', createdAt: 2024-01-15... } schema2.parse({}); // { id: 'abc-123...', createdAt: 2024-01-15... }
schema2.parse({}) // { id: 'def-456...', createdAt: 2024-01-15... } schema2.parse({}); // { id: 'def-456...', createdAt: 2024-01-15... }
``` ```
**Combining with optional/nullable:** **Combining with optional/nullable:**
```typescript ```typescript
// .optional().default() - if undefined, use default // .optional().default() - if undefined, use default
z.string().optional().default('fallback') z.string().optional().default("fallback");
// .nullable().default() - null stays null, only undefined gets default // .nullable().default() - null stays null, only undefined gets default
z.string().nullable().default('fallback') z.string().nullable().default("fallback");
// null -> null // null -> null
// undefined -> 'fallback' // undefined -> 'fallback'
// .nullish().default() - both null and undefined get default // .nullish().default() - both null and undefined get default
z.string().nullish().default('fallback') z.string().nullish().default("fallback");
// null -> 'fallback' // null -> 'fallback'
// undefined -> 'fallback' // undefined -> 'fallback'
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When absence of value has different meaning than default - When absence of value has different meaning than default
- When defaults depend on other fields (use transform) - When defaults depend on other fields (use transform)
@@ -12,19 +12,19 @@ tags: refine, transform, coerce, conversion
**Purpose of each method:** **Purpose of each method:**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// coerce: Convert type BEFORE validation // coerce: Convert type BEFORE validation
// Input: unknown -> Output: validated type // Input: unknown -> Output: validated type
z.coerce.number().parse('42') // Converts "42" to 42, then validates as number z.coerce.number().parse("42"); // Converts "42" to 42, then validates as number
// refine: Validate with custom logic, return boolean // refine: Validate with custom logic, return boolean
// Input: T -> Output: T (unchanged, but validated) // Input: T -> Output: T (unchanged, but validated)
z.number().refine((n) => n > 0) // Validates n > 0, returns n unchanged z.number().refine((n) => n > 0); // Validates n > 0, returns n unchanged
// transform: Convert to different type AFTER validation // transform: Convert to different type AFTER validation
// Input: T -> Output: U (different type) // Input: T -> Output: U (different type)
z.string().transform((s) => s.length) // Validates string, returns length z.string().transform((s) => s.length); // Validates string, returns length
``` ```
**Incorrect (using transform for validation):** **Incorrect (using transform for validation):**
@@ -32,36 +32,33 @@ z.string().transform((s) => s.length) // Validates string, returns length
```typescript ```typescript
// Wrong: transform should convert, not validate // Wrong: transform should convert, not validate
const schema = z.number().transform((n) => { const schema = z.number().transform((n) => {
if (n < 0) throw new Error('Must be positive') // Don't throw in transform if (n < 0) throw new Error("Must be positive"); // Don't throw in transform
return n return n;
}) });
``` ```
**Correct (using appropriate method):** **Correct (using appropriate method):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// VALIDATION: Use refine - returns boolean, data unchanged // VALIDATION: Use refine - returns boolean, data unchanged
const positiveNumber = z.number().refine( const positiveNumber = z.number().refine((n) => n > 0, { message: "Must be positive" });
(n) => n > 0,
{ message: 'Must be positive' }
)
positiveNumber.parse(5) // 5 positiveNumber.parse(5); // 5
positiveNumber.parse(-1) // ZodError: Must be positive positiveNumber.parse(-1); // ZodError: Must be positive
// CONVERSION: Use transform - returns new value // CONVERSION: Use transform - returns new value
const stringLength = z.string().transform((s) => s.length) const stringLength = z.string().transform((s) => s.length);
type StringLength = z.infer<typeof stringLength> // number type StringLength = z.infer<typeof stringLength>; // number
stringLength.parse('hello') // 5 stringLength.parse("hello"); // 5
// COERCION: Use coerce - converts input type // COERCION: Use coerce - converts input type
const coercedNumber = z.coerce.number() const coercedNumber = z.coerce.number();
coercedNumber.parse('42') // 42 (from string) coercedNumber.parse("42"); // 42 (from string)
coercedNumber.parse(42) // 42 (already number) coercedNumber.parse(42); // 42 (already number)
``` ```
**Combining methods correctly:** **Combining methods correctly:**
@@ -70,21 +67,21 @@ coercedNumber.parse(42) // 42 (already number)
// Input: string -> Coerce to number -> Validate positive -> Transform to dollars // Input: string -> Coerce to number -> Validate positive -> Transform to dollars
const priceSchema = z.coerce const priceSchema = z.coerce
.number() .number()
.refine((n) => n >= 0, 'Price cannot be negative') .refine((n) => n >= 0, "Price cannot be negative")
.transform((cents) => `$${(cents / 100).toFixed(2)}`) .transform((cents) => `$${(cents / 100).toFixed(2)}`);
priceSchema.parse('1999') // "$19.99" priceSchema.parse("1999"); // "$19.99"
priceSchema.parse('-100') // ZodError: Price cannot be negative priceSchema.parse("-100"); // ZodError: Price cannot be negative
``` ```
**Order of operations:** **Order of operations:**
```typescript ```typescript
const schema = z const schema = z
.preprocess(val => val, z.string()) // 1. preprocess (before type check) .preprocess((val) => val, z.string()) // 1. preprocess (before type check)
.transform(s => s.trim()) // 2. transform (after type check) .transform((s) => s.trim()) // 2. transform (after type check)
.refine(s => s.length > 0) // 3. refine (custom validation) .refine((s) => s.length > 0) // 3. refine (custom validation)
.transform(s => s.toUpperCase()) // 4. another transform .transform((s) => s.toUpperCase()); // 4. another transform
// Input flows: preprocess -> type check -> transforms/refines in order // Input flows: preprocess -> type check -> transforms/refines in order
``` ```
@@ -92,13 +89,14 @@ const schema = z
**Use case comparison:** **Use case comparison:**
| Need | Method | Example | | Need | Method | Example |
|------|--------|---------| | ---------------------------- | ------------------------ | -------------- |
| Convert string to number | `z.coerce.number()` | Form input | | Convert string to number | `z.coerce.number()` | Form input |
| Validate number is positive | `.refine(n => n > 0)` | Business rule | | Validate number is positive | `.refine(n => n > 0)` | Business rule |
| Convert cents to dollars | `.transform(n => n/100)` | Display format | | Convert cents to dollars | `.transform(n => n/100)` | Display format |
| Trim whitespace before check | `z.preprocess` | Input cleanup | | Trim whitespace before check | `z.preprocess` | Input cleanup |
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Simple type coercion: use `z.coerce.*` - Simple type coercion: use `z.coerce.*`
- Simple validation: use built-in methods like `.min()`, `.email()` - Simple validation: use built-in methods like `.min()`, `.email()`
@@ -12,21 +12,21 @@ tags: refine, superRefine, validation, custom
**Incorrect (using refine for multiple checks):** **Incorrect (using refine for multiple checks):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// refine can only report one error at a time // refine can only report one error at a time
const passwordSchema = z.string().refine( const passwordSchema = z.string().refine(
(password) => { (password) => {
// Checks all conditions but only reports first failure // Checks all conditions but only reports first failure
if (password.length < 8) return false // Only this error shown if (password.length < 8) return false; // Only this error shown
if (!/[A-Z]/.test(password)) return false if (!/[A-Z]/.test(password)) return false;
if (!/[0-9]/.test(password)) return false if (!/[0-9]/.test(password)) return false;
return true return true;
}, },
{ message: 'Password does not meet requirements' } { message: "Password does not meet requirements" }
) );
passwordSchema.parse('weak') passwordSchema.parse("weak");
// Only shows: "Password does not meet requirements" // Only shows: "Password does not meet requirements"
// User doesn't know WHICH requirements failed // User doesn't know WHICH requirements failed
``` ```
@@ -34,39 +34,39 @@ passwordSchema.parse('weak')
**Correct (using superRefine for multiple issues):** **Correct (using superRefine for multiple issues):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const passwordSchema = z.string().superRefine((password, ctx) => { const passwordSchema = z.string().superRefine((password, ctx) => {
if (password.length < 8) { if (password.length < 8) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: 'Password must be at least 8 characters', message: "Password must be at least 8 characters"
}) });
} }
if (!/[A-Z]/.test(password)) { if (!/[A-Z]/.test(password)) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: 'Password must contain an uppercase letter', message: "Password must contain an uppercase letter"
}) });
} }
if (!/[0-9]/.test(password)) { if (!/[0-9]/.test(password)) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: 'Password must contain a number', message: "Password must contain a number"
}) });
} }
if (!/[!@#$%^&*]/.test(password)) { if (!/[!@#$%^&*]/.test(password)) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: 'Password must contain a special character', message: "Password must contain a special character"
}) });
} }
}) });
passwordSchema.safeParse('weak') passwordSchema.safeParse("weak");
// Shows ALL failures: // Shows ALL failures:
// - "Password must be at least 8 characters" // - "Password must be at least 8 characters"
// - "Password must contain an uppercase letter" // - "Password must contain an uppercase letter"
@@ -78,28 +78,30 @@ passwordSchema.safeParse('weak')
```typescript ```typescript
// Simple boolean condition with one error message // Simple boolean condition with one error message
const adultSchema = z.number().refine( const adultSchema = z.number().refine((age) => age >= 18, { message: "Must be 18 or older" });
(age) => age >= 18,
{ message: 'Must be 18 or older' }
)
// Cross-field validation with single outcome // Cross-field validation with single outcome
const formSchema = z.object({ const formSchema = z
.object({
password: z.string(), password: z.string(),
confirmPassword: z.string(), confirmPassword: z.string()
}).refine( })
(data) => data.password === data.confirmPassword, .refine((data) => data.password === data.confirmPassword, {
{ message: 'Passwords must match', path: ['confirmPassword'] } message: "Passwords must match",
) path: ["confirmPassword"]
});
// Async validation // Async validation
const emailSchema = z.string().email().refine( const emailSchema = z
.string()
.email()
.refine(
async (email) => { async (email) => {
const exists = await checkEmailExists(email) const exists = await checkEmailExists(email);
return !exists return !exists;
}, },
{ message: 'Email already registered' } { message: "Email already registered" }
) );
``` ```
**When to use superRefine():** **When to use superRefine():**
@@ -110,42 +112,47 @@ const emailSchema = z.string().email().refine(
// Need custom error codes for i18n or client handling // Need custom error codes for i18n or client handling
// Need to add issues at specific paths // Need to add issues at specific paths
const orderSchema = z.object({ const orderSchema = z
items: z.array(z.object({ .object({
items: z.array(
z.object({
productId: z.string(), productId: z.string(),
quantity: z.number(), quantity: z.number()
})), })
promoCode: z.string().optional(), ),
}).superRefine(async (order, ctx) => { promoCode: z.string().optional()
})
.superRefine(async (order, ctx) => {
// Check each item's availability // Check each item's availability
for (let i = 0; i < order.items.length; i++) { for (let i = 0; i < order.items.length; i++) {
const item = order.items[i] const item = order.items[i];
const available = await checkInventory(item.productId, item.quantity) const available = await checkInventory(item.productId, item.quantity);
if (!available) { if (!available) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
path: ['items', i, 'quantity'], // Specific path path: ["items", i, "quantity"], // Specific path
message: `Only ${available} units available`, message: `Only ${available} units available`
}) });
} }
} }
// Validate promo code // Validate promo code
if (order.promoCode) { if (order.promoCode) {
const valid = await validatePromoCode(order.promoCode) const valid = await validatePromoCode(order.promoCode);
if (!valid) { if (!valid) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
path: ['promoCode'], path: ["promoCode"],
message: 'Invalid or expired promo code', message: "Invalid or expired promo code"
}) });
} }
} }
}) });
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Simple single-condition checks (use refine for simplicity) - Simple single-condition checks (use refine for simplicity)
- Transform needed instead of validation (use transform) - Transform needed instead of validation (use transform)
@@ -12,28 +12,28 @@ Making too many fields optional creates overly permissive schemas that validate
**Incorrect (optional abuse):** **Incorrect (optional abuse):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Every field optional - almost anything passes // Every field optional - almost anything passes
const userSchema = z.object({ const userSchema = z.object({
id: z.string().optional(), id: z.string().optional(),
name: z.string().optional(), name: z.string().optional(),
email: z.string().optional(), email: z.string().optional(),
role: z.string().optional(), role: z.string().optional()
}) });
type User = z.infer<typeof userSchema> type User = z.infer<typeof userSchema>;
// { id?: string; name?: string; email?: string; role?: string } // { id?: string; name?: string; email?: string; role?: string }
// Empty object passes validation! // Empty object passes validation!
userSchema.parse({}) // ✓ Valid: {} userSchema.parse({}); // ✓ Valid: {}
function greetUser(user: User) { function greetUser(user: User) {
// Forced to add null checks everywhere // Forced to add null checks everywhere
if (user.name) { if (user.name) {
console.log(`Hello, ${user.name}`) console.log(`Hello, ${user.name}`);
} else { } else {
console.log('Hello, stranger') // Shouldn't happen if data is clean console.log("Hello, stranger"); // Shouldn't happen if data is clean
} }
} }
``` ```
@@ -41,30 +41,30 @@ function greetUser(user: User) {
**Correct (explicit required vs optional):** **Correct (explicit required vs optional):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Required fields are required, optional fields are intentional // Required fields are required, optional fields are intentional
const userSchema = z.object({ const userSchema = z.object({
id: z.string().uuid(), // Required id: z.string().uuid(), // Required
name: z.string().min(1), // Required, non-empty name: z.string().min(1), // Required, non-empty
email: z.string().email(), // Required email: z.string().email(), // Required
role: z.enum(['admin', 'user', 'guest']), // Required role: z.enum(["admin", "user", "guest"]), // Required
nickname: z.string().optional(), // Intentionally optional nickname: z.string().optional(), // Intentionally optional
bio: z.string().nullable(), // Can be explicitly null bio: z.string().nullable() // Can be explicitly null
}) });
type User = z.infer<typeof userSchema> type User = z.infer<typeof userSchema>;
// Empty object fails validation // Empty object fails validation
userSchema.parse({}) // ✗ Throws ZodError userSchema.parse({}); // ✗ Throws ZodError
function greetUser(user: User) { function greetUser(user: User) {
// user.name is guaranteed to exist // user.name is guaranteed to exist
console.log(`Hello, ${user.name}`) console.log(`Hello, ${user.name}`);
// Only optional fields need checks // Only optional fields need checks
if (user.nickname) { if (user.nickname) {
console.log(`Also known as: ${user.nickname}`) console.log(`Also known as: ${user.nickname}`);
} }
} }
``` ```
@@ -76,17 +76,18 @@ function greetUser(user: User) {
const userSchema = z.object({ const userSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
name: z.string().min(1), name: z.string().min(1),
email: z.string().email(), email: z.string().email()
}) });
// All fields optional for PATCH updates // All fields optional for PATCH updates
const updateUserSchema = userSchema.partial() const updateUserSchema = userSchema.partial();
// Only specific fields optional // Only specific fields optional
const createUserSchema = userSchema.partial({ id: true }) const createUserSchema = userSchema.partial({ id: true });
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When modeling partial updates (PATCH endpoints) - When modeling partial updates (PATCH endpoints)
- When fields genuinely may not exist (legacy data, external APIs) - When fields genuinely may not exist (legacy data, external APIs)
@@ -12,21 +12,21 @@ HTML forms and URL query parameters always transmit data as strings. Using `z.nu
**Incorrect (no coercion for form data):** **Incorrect (no coercion for form data):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const searchSchema = z.object({ const searchSchema = z.object({
query: z.string(), query: z.string(),
page: z.number(), // Expects actual number page: z.number(), // Expects actual number
limit: z.number(), limit: z.number(),
showDeleted: z.boolean(), // Expects actual boolean showDeleted: z.boolean() // Expects actual boolean
}) });
// Form data / query params are strings // Form data / query params are strings
const formData = new URLSearchParams('query=test&page=1&limit=10&showDeleted=true') const formData = new URLSearchParams("query=test&page=1&limit=10&showDeleted=true");
const params = Object.fromEntries(formData) const params = Object.fromEntries(formData);
// { query: 'test', page: '1', limit: '10', showDeleted: 'true' } // { query: 'test', page: '1', limit: '10', showDeleted: 'true' }
searchSchema.parse(params) searchSchema.parse(params);
// ZodError: Expected number, received string at "page" // ZodError: Expected number, received string at "page"
// ZodError: Expected number, received string at "limit" // ZodError: Expected number, received string at "limit"
// ZodError: Expected boolean, received string at "showDeleted" // ZodError: Expected boolean, received string at "showDeleted"
@@ -35,20 +35,20 @@ searchSchema.parse(params)
**Correct (using coercion):** **Correct (using coercion):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const searchSchema = z.object({ const searchSchema = z.object({
query: z.string(), query: z.string(),
page: z.coerce.number().int().positive().default(1), page: z.coerce.number().int().positive().default(1),
limit: z.coerce.number().int().min(1).max(100).default(10), limit: z.coerce.number().int().min(1).max(100).default(10),
showDeleted: z.coerce.boolean().default(false), showDeleted: z.coerce.boolean().default(false)
}) });
// Form data / query params are strings // Form data / query params are strings
const formData = new URLSearchParams('query=test&page=1&limit=10&showDeleted=true') const formData = new URLSearchParams("query=test&page=1&limit=10&showDeleted=true");
const params = Object.fromEntries(formData) const params = Object.fromEntries(formData);
const result = searchSchema.parse(params) const result = searchSchema.parse(params);
// { query: 'test', page: 1, limit: 10, showDeleted: true } // { query: 'test', page: 1, limit: 10, showDeleted: true }
// Types are correct: number, number, boolean // Types are correct: number, number, boolean
``` ```
@@ -56,32 +56,33 @@ const result = searchSchema.parse(params)
**Available coercion types:** **Available coercion types:**
```typescript ```typescript
z.coerce.string() // Converts anything to string via String(value) z.coerce.string(); // Converts anything to string via String(value)
z.coerce.number() // Converts via Number(value), NaN fails validation z.coerce.number(); // Converts via Number(value), NaN fails validation
z.coerce.boolean() // Truthy/falsy conversion z.coerce.boolean(); // Truthy/falsy conversion
z.coerce.bigint() // Converts via BigInt(value) z.coerce.bigint(); // Converts via BigInt(value)
z.coerce.date() // Converts via new Date(value) z.coerce.date(); // Converts via new Date(value)
``` ```
**Coercion edge cases:** **Coercion edge cases:**
```typescript ```typescript
// z.coerce.number() behavior // z.coerce.number() behavior
z.coerce.number().parse("42") // 42 z.coerce.number().parse("42"); // 42
z.coerce.number().parse("") // 0 (empty string becomes 0!) z.coerce.number().parse(""); // 0 (empty string becomes 0!)
z.coerce.number().parse("abc") // ZodError (NaN fails) z.coerce.number().parse("abc"); // ZodError (NaN fails)
// z.coerce.boolean() behavior // z.coerce.boolean() behavior
z.coerce.boolean().parse("true") // true z.coerce.boolean().parse("true"); // true
z.coerce.boolean().parse("false") // true! (non-empty string is truthy) z.coerce.boolean().parse("false"); // true! (non-empty string is truthy)
z.coerce.boolean().parse("") // false z.coerce.boolean().parse(""); // false
z.coerce.boolean().parse("0") // true! (non-empty string) z.coerce.boolean().parse("0"); // true! (non-empty string)
// For strict boolean parsing from strings: // For strict boolean parsing from strings:
const strictBooleanSchema = z.enum(['true', 'false']).transform(v => v === 'true') const strictBooleanSchema = z.enum(["true", "false"]).transform((v) => v === "true");
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When receiving JSON payloads (already typed correctly) - When receiving JSON payloads (already typed correctly)
- When you want strict type checking without conversion - When you want strict type checking without conversion
@@ -12,78 +12,75 @@ Plain `z.string()` accepts any string including empty strings, extremely long st
**Incorrect (no string validations):** **Incorrect (no string validations):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const commentSchema = z.object({ const commentSchema = z.object({
author: z.string(), // Empty string passes author: z.string(), // Empty string passes
email: z.string(), // "not-an-email" passes email: z.string(), // "not-an-email" passes
content: z.string(), // 10MB string passes, script tags pass content: z.string(), // 10MB string passes, script tags pass
website: z.string().optional(), // "javascript:alert(1)" passes website: z.string().optional() // "javascript:alert(1)" passes
}) });
// All of these pass validation // All of these pass validation
commentSchema.parse({ commentSchema.parse({
author: '', // Empty - who wrote this? author: "", // Empty - who wrote this?
email: 'invalid', // Not a real email email: "invalid", // Not a real email
content: '<script>alert("XSS")</script>'.repeat(100000), // XSS + huge content: '<script>alert("XSS")</script>'.repeat(100000), // XSS + huge
website: 'javascript:void(0)', // Dangerous URL website: "javascript:void(0)" // Dangerous URL
}) });
``` ```
**Correct (string validations applied):** **Correct (string validations applied):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const commentSchema = z.object({ const commentSchema = z.object({
author: z.string() author: z.string().min(1, "Author is required").max(100, "Author name too long"),
.min(1, 'Author is required')
.max(100, 'Author name too long'),
email: z.string() email: z.string().email("Invalid email address"),
.email('Invalid email address'),
content: z.string() content: z.string().min(1, "Comment cannot be empty").max(5000, "Comment too long"),
.min(1, 'Comment cannot be empty')
.max(5000, 'Comment too long'),
website: z.string() website: z
.url('Invalid URL') .string()
.url("Invalid URL")
.refine( .refine(
url => url.startsWith('http://') || url.startsWith('https://'), (url) => url.startsWith("http://") || url.startsWith("https://"),
'Only http/https URLs allowed' "Only http/https URLs allowed"
) )
.optional(), .optional()
}) });
// Invalid data is rejected // Invalid data is rejected
commentSchema.parse({ commentSchema.parse({
author: '', author: "",
email: 'invalid', email: "invalid",
content: '', content: ""
}) });
// ZodError with all violations listed // ZodError with all violations listed
``` ```
**Common string validations:** **Common string validations:**
```typescript ```typescript
z.string().min(1) // Non-empty (most common need) z.string().min(1); // Non-empty (most common need)
z.string().max(255) // Database varchar limit z.string().max(255); // Database varchar limit
z.string().length(36) // Exact length (UUIDs) z.string().length(36); // Exact length (UUIDs)
z.string().email() // Email format z.string().email(); // Email format
z.string().url() // URL format z.string().url(); // URL format
z.string().uuid() // UUID format z.string().uuid(); // UUID format
z.string().cuid() // CUID format z.string().cuid(); // CUID format
z.string().regex(/^[a-z0-9-]+$/) // Custom pattern (slugs) z.string().regex(/^[a-z0-9-]+$/); // Custom pattern (slugs)
z.string().startsWith('https://') // Prefix check z.string().startsWith("https://"); // Prefix check
z.string().endsWith('.pdf') // Suffix check z.string().endsWith(".pdf"); // Suffix check
z.string().includes('@') // Contains check z.string().includes("@"); // Contains check
z.string().trim() // Strips whitespace (transform) z.string().trim(); // Strips whitespace (transform)
z.string().toLowerCase() // Normalizes case (transform) z.string().toLowerCase(); // Normalizes case (transform)
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When accepting arbitrary user content for display only (sanitize on output instead) - When accepting arbitrary user content for display only (sanitize on output instead)
- When building a passthrough/proxy that shouldn't validate content - When building a passthrough/proxy that shouldn't validate content
@@ -12,26 +12,27 @@ When a field should only accept specific values (status, role, type), use `z.enu
**Incorrect (plain string for fixed values):** **Incorrect (plain string for fixed values):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const orderSchema = z.object({ const orderSchema = z.object({
id: z.string(), id: z.string(),
status: z.string(), // Accepts any string status: z.string(), // Accepts any string
priority: z.string(), // No constraints priority: z.string() // No constraints
}) });
type Order = z.infer<typeof orderSchema> type Order = z.infer<typeof orderSchema>;
// { id: string; status: string; priority: string } // { id: string; status: string; priority: string }
// Typos and invalid values pass validation // Typos and invalid values pass validation
orderSchema.parse({ orderSchema.parse({
id: '123', id: "123",
status: 'pendng', // Typo passes status: "pendng", // Typo passes
priority: 'super-urgent', // Invalid value passes priority: "super-urgent" // Invalid value passes
}) });
function processOrder(order: Order) { function processOrder(order: Order) {
if (order.status === 'pending') { // Might never match due to typos if (order.status === "pending") {
// Might never match due to typos
// ... // ...
} }
} }
@@ -40,67 +41,65 @@ function processOrder(order: Order) {
**Correct (using z.enum):** **Correct (using z.enum):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const OrderStatus = z.enum(['pending', 'processing', 'shipped', 'delivered']) const OrderStatus = z.enum(["pending", "processing", "shipped", "delivered"]);
const Priority = z.enum(['low', 'medium', 'high']) const Priority = z.enum(["low", "medium", "high"]);
const orderSchema = z.object({ const orderSchema = z.object({
id: z.string(), id: z.string(),
status: OrderStatus, status: OrderStatus,
priority: Priority, priority: Priority
}) });
type Order = z.infer<typeof orderSchema> type Order = z.infer<typeof orderSchema>;
// { id: string; status: 'pending' | 'processing' | 'shipped' | 'delivered'; priority: 'low' | 'medium' | 'high' } // { id: string; status: 'pending' | 'processing' | 'shipped' | 'delivered'; priority: 'low' | 'medium' | 'high' }
// Typos are caught at validation // Typos are caught at validation
orderSchema.parse({ orderSchema.parse({
id: '123', id: "123",
status: 'pendng', // ZodError: Invalid enum value status: "pendng", // ZodError: Invalid enum value
priority: 'super-urgent', // ZodError: Invalid enum value priority: "super-urgent" // ZodError: Invalid enum value
}) });
// Extract enum values for reuse // Extract enum values for reuse
OrderStatus.options // ['pending', 'processing', 'shipped', 'delivered'] OrderStatus.options; // ['pending', 'processing', 'shipped', 'delivered']
type OrderStatusType = z.infer<typeof OrderStatus> // 'pending' | 'processing' | ... type OrderStatusType = z.infer<typeof OrderStatus>; // 'pending' | 'processing' | ...
``` ```
**For native TypeScript enums:** **For native TypeScript enums:**
```typescript ```typescript
enum Role { enum Role {
Admin = 'admin', Admin = "admin",
User = 'user', User = "user",
Guest = 'guest', Guest = "guest"
} }
// Use z.nativeEnum for TS enums // Use z.nativeEnum for TS enums
const userSchema = z.object({ const userSchema = z.object({
role: z.nativeEnum(Role), role: z.nativeEnum(Role)
}) });
``` ```
**For single literal values (discriminated unions):** **For single literal values (discriminated unions):**
```typescript ```typescript
const successResponse = z.object({ const successResponse = z.object({
status: z.literal('success'), status: z.literal("success"),
data: z.unknown(), data: z.unknown()
}) });
const errorResponse = z.object({ const errorResponse = z.object({
status: z.literal('error'), status: z.literal("error"),
message: z.string(), message: z.string()
}) });
const response = z.discriminatedUnion('status', [ const response = z.discriminatedUnion("status", [successResponse, errorResponse]);
successResponse,
errorResponse,
])
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When the set of valid values is dynamic or user-defined - When the set of valid values is dynamic or user-defined
- When values come from a database that may have more options - When values come from a database that may have more options
@@ -12,37 +12,38 @@ Zod provides specific schemas for each primitive type. Using the wrong schema (e
**Incorrect (wrong primitive or any):** **Incorrect (wrong primitive or any):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Using any loses all type safety // Using any loses all type safety
const userSchema = z.object({ const userSchema = z.object({
id: z.any(), // Accepts anything - no validation id: z.any(), // Accepts anything - no validation
age: z.string(), // Wrong type - age should be number age: z.string(), // Wrong type - age should be number
active: z.any(), // Should be boolean active: z.any() // Should be boolean
}) });
// This passes validation but data is wrong // This passes validation but data is wrong
userSchema.parse({ id: null, age: "twenty", active: "yes" }) userSchema.parse({ id: null, age: "twenty", active: "yes" });
// Result: { id: null, age: "twenty", active: "yes" } // Result: { id: null, age: "twenty", active: "yes" }
``` ```
**Correct (specific primitives):** **Correct (specific primitives):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userSchema = z.object({ const userSchema = z.object({
id: z.string().uuid(), // Specific format validation id: z.string().uuid(), // Specific format validation
age: z.number().int().positive(), // Correct type with constraints age: z.number().int().positive(), // Correct type with constraints
active: z.boolean(), // Exact boolean type active: z.boolean() // Exact boolean type
}) });
// Now invalid data is rejected // Now invalid data is rejected
userSchema.parse({ id: null, age: "twenty", active: "yes" }) userSchema.parse({ id: null, age: "twenty", active: "yes" });
// Throws ZodError with specific field errors // Throws ZodError with specific field errors
``` ```
**Available primitive schemas:** **Available primitive schemas:**
- `z.string()` - strings with optional regex, min, max, email, url, uuid - `z.string()` - strings with optional regex, min, max, email, url, uuid
- `z.number()` - numbers with optional int, positive, negative, min, max - `z.number()` - numbers with optional int, positive, negative, min, max
- `z.bigint()` - BigInt values - `z.bigint()` - BigInt values
@@ -55,6 +56,7 @@ userSchema.parse({ id: null, age: "twenty", active: "yes" })
- `z.never()` - no valid value - `z.never()` - no valid value
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When you genuinely need to accept any value (rare - consider `z.unknown()` instead) - When you genuinely need to accept any value (rare - consider `z.unknown()` instead)
- When migrating legacy code incrementally (use `z.any()` temporarily, then fix) - When migrating legacy code incrementally (use `z.any()` temporarily, then fix)
@@ -12,41 +12,41 @@ tags: schema, unknown, any, type-safety
**Incorrect (using z.any):** **Incorrect (using z.any):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const eventSchema = z.object({ const eventSchema = z.object({
type: z.string(), type: z.string(),
payload: z.any(), // Infers to 'any' payload: z.any() // Infers to 'any'
}) });
type Event = z.infer<typeof eventSchema> type Event = z.infer<typeof eventSchema>;
// { type: string; payload: any } // { type: string; payload: any }
function handleEvent(event: Event) { function handleEvent(event: Event) {
// No type error - TypeScript allows anything // No type error - TypeScript allows anything
console.log(event.payload.foo.bar.baz) // Runtime crash if structure is wrong console.log(event.payload.foo.bar.baz); // Runtime crash if structure is wrong
} }
``` ```
**Correct (using z.unknown):** **Correct (using z.unknown):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const eventSchema = z.object({ const eventSchema = z.object({
type: z.string(), type: z.string(),
payload: z.unknown(), // Infers to 'unknown' payload: z.unknown() // Infers to 'unknown'
}) });
type Event = z.infer<typeof eventSchema> type Event = z.infer<typeof eventSchema>;
// { type: string; payload: unknown } // { type: string; payload: unknown }
function handleEvent(event: Event) { function handleEvent(event: Event) {
// TypeScript error: Object is of type 'unknown' // TypeScript error: Object is of type 'unknown'
console.log(event.payload.foo) // Won't compile console.log(event.payload.foo); // Won't compile
// Must narrow type first // Must narrow type first
if (typeof event.payload === 'object' && event.payload !== null) { if (typeof event.payload === "object" && event.payload !== null) {
// Now TypeScript knows it's an object // Now TypeScript knows it's an object
} }
} }
@@ -55,33 +55,31 @@ function handleEvent(event: Event) {
**Better approach with discriminated unions:** **Better approach with discriminated unions:**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userCreatedSchema = z.object({ const userCreatedSchema = z.object({
type: z.literal('user.created'), type: z.literal("user.created"),
payload: z.object({ payload: z.object({
userId: z.string(), userId: z.string(),
email: z.string().email(), email: z.string().email()
}), })
}) });
const orderPlacedSchema = z.object({ const orderPlacedSchema = z.object({
type: z.literal('order.placed'), type: z.literal("order.placed"),
payload: z.object({ payload: z.object({
orderId: z.string(), orderId: z.string(),
amount: z.number(), amount: z.number()
}), })
}) });
const eventSchema = z.discriminatedUnion('type', [ const eventSchema = z.discriminatedUnion("type", [userCreatedSchema, orderPlacedSchema]);
userCreatedSchema,
orderPlacedSchema,
])
// Full type safety for each event type // Full type safety for each event type
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When you're consuming a third-party API where you truly don't know the shape - When you're consuming a third-party API where you truly don't know the shape
- When prototyping and will add proper types later - When prototyping and will add proper types later
@@ -12,89 +12,93 @@ Plain strings and numbers are interchangeable in TypeScript's structural type sy
**Incorrect (plain IDs are interchangeable):** **Incorrect (plain IDs are interchangeable):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userIdSchema = z.string().uuid() const userIdSchema = z.string().uuid();
const orderIdSchema = z.string().uuid() const orderIdSchema = z.string().uuid();
type UserId = z.infer<typeof userIdSchema> // string type UserId = z.infer<typeof userIdSchema>; // string
type OrderId = z.infer<typeof orderIdSchema> // string - same type! type OrderId = z.infer<typeof orderIdSchema>; // string - same type!
async function getOrder(orderId: OrderId) { async function getOrder(orderId: OrderId) {
return db.orders.findUnique({ where: { id: orderId } }) return db.orders.findUnique({ where: { id: orderId } });
} }
const userId: UserId = '550e8400-e29b-41d4-a716-446655440000' const userId: UserId = "550e8400-e29b-41d4-a716-446655440000";
getOrder(userId) // No error! TypeScript allows this bug getOrder(userId); // No error! TypeScript allows this bug
// Runtime: queries orders table with user ID, returns nothing or wrong data // Runtime: queries orders table with user ID, returns nothing or wrong data
``` ```
**Correct (using branded types):** **Correct (using branded types):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userIdSchema = z.string().uuid().brand<'UserId'>() const userIdSchema = z.string().uuid().brand<"UserId">();
const orderIdSchema = z.string().uuid().brand<'OrderId'>() const orderIdSchema = z.string().uuid().brand<"OrderId">();
type UserId = z.infer<typeof userIdSchema> type UserId = z.infer<typeof userIdSchema>;
// string & { __brand: 'UserId' } // string & { __brand: 'UserId' }
type OrderId = z.infer<typeof orderIdSchema> type OrderId = z.infer<typeof orderIdSchema>;
// string & { __brand: 'OrderId' } // string & { __brand: 'OrderId' }
async function getOrder(orderId: OrderId) { async function getOrder(orderId: OrderId) {
return db.orders.findUnique({ where: { id: orderId } }) return db.orders.findUnique({ where: { id: orderId } });
} }
const userId = userIdSchema.parse('550e8400-e29b-41d4-a716-446655440000') const userId = userIdSchema.parse("550e8400-e29b-41d4-a716-446655440000");
getOrder(userId) // TypeScript error: Argument of type 'UserId' is not assignable to parameter of type 'OrderId' getOrder(userId); // TypeScript error: Argument of type 'UserId' is not assignable to parameter of type 'OrderId'
const orderId = orderIdSchema.parse('660e8400-e29b-41d4-a716-446655440001') const orderId = orderIdSchema.parse("660e8400-e29b-41d4-a716-446655440001");
getOrder(orderId) // Works correctly getOrder(orderId); // Works correctly
``` ```
**Common branded types:** **Common branded types:**
```typescript ```typescript
// IDs for different entities // IDs for different entities
const UserId = z.string().uuid().brand<'UserId'>() const UserId = z.string().uuid().brand<"UserId">();
const ProductId = z.string().uuid().brand<'ProductId'>() const ProductId = z.string().uuid().brand<"ProductId">();
const OrderId = z.string().uuid().brand<'OrderId'>() const OrderId = z.string().uuid().brand<"OrderId">();
// Email (validated and branded) // Email (validated and branded)
const Email = z.string().email().brand<'Email'>() const Email = z.string().email().brand<"Email">();
// Positive numbers // Positive numbers
const PositiveInt = z.number().int().positive().brand<'PositiveInt'>() const PositiveInt = z.number().int().positive().brand<"PositiveInt">();
// Money amounts (in cents) // Money amounts (in cents)
const Cents = z.number().int().nonnegative().brand<'Cents'>() const Cents = z.number().int().nonnegative().brand<"Cents">();
// Slugs // Slugs
const Slug = z.string().regex(/^[a-z0-9-]+$/).brand<'Slug'>() const Slug = z
.string()
.regex(/^[a-z0-9-]+$/)
.brand<"Slug">();
``` ```
**Using with object schemas:** **Using with object schemas:**
```typescript ```typescript
const User = z.object({ const User = z.object({
id: z.string().uuid().brand<'UserId'>(), id: z.string().uuid().brand<"UserId">(),
email: z.string().email().brand<'Email'>(), email: z.string().email().brand<"Email">(),
referredBy: z.string().uuid().brand<'UserId'>().optional(), referredBy: z.string().uuid().brand<"UserId">().optional()
}) });
type User = z.infer<typeof User> type User = z.infer<typeof User>;
function sendReferralBonus( function sendReferralBonus(
referrerId: z.infer<typeof User>['id'], referrerId: z.infer<typeof User>["id"],
refereeId: z.infer<typeof User>['id'] refereeId: z.infer<typeof User>["id"]
) { ) {
// Can't accidentally swap these - both are UserId but distinct values // Can't accidentally swap these - both are UserId but distinct values
} }
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Simple applications without ID confusion risk - Simple applications without ID confusion risk
- When interoperating with external systems that expect plain strings - When interoperating with external systems that expect plain strings
- Performance-critical paths (brand adds tiny overhead) - Performance-critical paths (brand adds tiny overhead)
@@ -21,23 +21,23 @@ Zod requires TypeScript's strict mode to work correctly. Without it, `undefined`
``` ```
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userSchema = z.object({ const userSchema = z.object({
name: z.string(), name: z.string(),
email: z.string().email(), email: z.string().email()
}) });
type User = z.infer<typeof userSchema> type User = z.infer<typeof userSchema>;
// With strict:false, type might include undefined implicitly // With strict:false, type might include undefined implicitly
function processUser(user: User) { function processUser(user: User) {
// No error even if user.name could be undefined // No error even if user.name could be undefined
console.log(user.name.toUpperCase()) // Potential runtime crash console.log(user.name.toUpperCase()); // Potential runtime crash
} }
// TypeScript allows calling with undefined // TypeScript allows calling with undefined
processUser(undefined as any) // No warning processUser(undefined as any); // No warning
``` ```
**Correct (strict mode enabled):** **Correct (strict mode enabled):**
@@ -52,23 +52,23 @@ processUser(undefined as any) // No warning
``` ```
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const userSchema = z.object({ const userSchema = z.object({
name: z.string(), name: z.string(),
email: z.string().email(), email: z.string().email()
}) });
type User = z.infer<typeof userSchema> type User = z.infer<typeof userSchema>;
// { name: string; email: string } - no implicit undefined // { name: string; email: string } - no implicit undefined
function processUser(user: User) { function processUser(user: User) {
// TypeScript knows name is always string // TypeScript knows name is always string
console.log(user.name.toUpperCase()) // Safe console.log(user.name.toUpperCase()); // Safe
} }
// TypeScript catches potential undefined // TypeScript catches potential undefined
processUser(undefined as any) // Error with strict null checks processUser(undefined as any); // Error with strict null checks
``` ```
**Minimum strict settings for Zod:** **Minimum strict settings for Zod:**
@@ -91,14 +91,14 @@ processUser(undefined as any) // Error with strict null checks
```typescript ```typescript
// Without strictNullChecks // Without strictNullChecks
const schema = z.string().optional() const schema = z.string().optional();
type MaybeString = z.infer<typeof schema> type MaybeString = z.infer<typeof schema>;
// Should be: string | undefined // Should be: string | undefined
// Without strict: just string (undefined is implicit) // Without strict: just string (undefined is implicit)
// Without noImplicitAny // Without noImplicitAny
const schema = z.object({ name: z.string() }) const schema = z.object({ name: z.string() });
schema.parse(data) // data could be 'any', bypassing validation schema.parse(data); // data could be 'any', bypassing validation
``` ```
**Migrating to strict mode:** **Migrating to strict mode:**
@@ -109,22 +109,24 @@ schema.parse(data) // data could be 'any', bypassing validation
// 1. Add null checks // 1. Add null checks
if (user.name !== undefined) { if (user.name !== undefined) {
console.log(user.name.toUpperCase()) console.log(user.name.toUpperCase());
} }
// 2. Add explicit types // 2. Add explicit types
function processData(data: unknown) { // Was implicit any function processData(data: unknown) {
const validated = schema.parse(data) // Was implicit any
const validated = schema.parse(data);
} }
// 3. Handle optional fields // 3. Handle optional fields
const user: User = { const user: User = {
name: 'John', name: "John",
email: 'john@example.com', // Now required, was optional without strict email: "john@example.com" // Now required, was optional without strict
} };
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Never - always enable strict mode for Zod projects - Never - always enable strict mode for Zod projects
Reference: [Zod Requirements](https://zod.dev/#requirements) Reference: [Zod Requirements](https://zod.dev/#requirements)
@@ -13,52 +13,52 @@ When defining schemas in shared modules, export both the schema and its inferred
```typescript ```typescript
// schemas/user.ts // schemas/user.ts
import { z } from 'zod' import { z } from "zod";
export const userSchema = z.object({ export const userSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
email: z.string().email(), email: z.string().email(),
name: z.string(), name: z.string(),
role: z.enum(['admin', 'user']), role: z.enum(["admin", "user"])
}) });
// Every consumer must derive the type // Every consumer must derive the type
// api/users.ts // api/users.ts
import { userSchema } from '@/schemas/user' import { userSchema } from "@/schemas/user";
import type { z } from 'zod' import type { z } from "zod";
type User = z.infer<typeof userSchema> // Repeated everywhere type User = z.infer<typeof userSchema>; // Repeated everywhere
// components/UserCard.tsx // components/UserCard.tsx
import { userSchema } from '@/schemas/user' import { userSchema } from "@/schemas/user";
import type { z } from 'zod' import type { z } from "zod";
type User = z.infer<typeof userSchema> // Same boilerplate again type User = z.infer<typeof userSchema>; // Same boilerplate again
``` ```
**Correct (exporting schema and type):** **Correct (exporting schema and type):**
```typescript ```typescript
// schemas/user.ts // schemas/user.ts
import { z } from 'zod' import { z } from "zod";
export const userSchema = z.object({ export const userSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
email: z.string().email(), email: z.string().email(),
name: z.string(), name: z.string(),
role: z.enum(['admin', 'user']), role: z.enum(["admin", "user"])
}) });
export type User = z.infer<typeof userSchema> export type User = z.infer<typeof userSchema>;
// For schemas with transforms, export both // For schemas with transforms, export both
export const apiUserSchema = z.object({ export const apiUserSchema = z.object({
id: z.string(), id: z.string(),
created_at: z.string().transform(s => new Date(s)), created_at: z.string().transform((s) => new Date(s))
}) });
export type ApiUserInput = z.input<typeof apiUserSchema> export type ApiUserInput = z.input<typeof apiUserSchema>;
export type ApiUser = z.infer<typeof apiUserSchema> export type ApiUser = z.infer<typeof apiUserSchema>;
``` ```
```typescript ```typescript
@@ -82,34 +82,35 @@ function UserCard({ user }: { user: User }) {
```typescript ```typescript
// schemas/index.ts - barrel file for schemas // schemas/index.ts - barrel file for schemas
export { userSchema, type User, type UserInput } from './user' export { userSchema, type User, type UserInput } from "./user";
export { orderSchema, type Order } from './order' export { orderSchema, type Order } from "./order";
export { productSchema, type Product } from './product' export { productSchema, type Product } from "./product";
// Usage // Usage
import { userSchema, type User, type Order } from '@/schemas' import { userSchema, type User, type Order } from "@/schemas";
``` ```
**With enums, export the enum values too:** **With enums, export the enum values too:**
```typescript ```typescript
// schemas/user.ts // schemas/user.ts
export const UserRole = z.enum(['admin', 'user', 'guest']) export const UserRole = z.enum(["admin", "user", "guest"]);
export type UserRole = z.infer<typeof UserRole> export type UserRole = z.infer<typeof UserRole>;
export const userSchema = z.object({ export const userSchema = z.object({
id: z.string(), id: z.string(),
role: UserRole, role: UserRole
}) });
export type User = z.infer<typeof userSchema> export type User = z.infer<typeof userSchema>;
// Access enum values // Access enum values
UserRole.options // ['admin', 'user', 'guest'] UserRole.options; // ['admin', 'user', 'guest']
UserRole.enum.admin // 'admin' UserRole.enum.admin; // 'admin'
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Internal schemas that won't be used outside the module - Internal schemas that won't be used outside the module
- Transient schemas used only for validation (not as types) - Transient schemas used only for validation (not as types)
@@ -12,44 +12,44 @@ When schemas use `.transform()`, the input and output types differ. `z.infer` (s
**Incorrect (using infer for input type):** **Incorrect (using infer for input type):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const dateSchema = z.string().transform(s => new Date(s)) const dateSchema = z.string().transform((s) => new Date(s));
type DateOutput = z.infer<typeof dateSchema> type DateOutput = z.infer<typeof dateSchema>;
// Date (post-transform) // Date (post-transform)
// Wrong! Expecting Date but should accept string // Wrong! Expecting Date but should accept string
function handleDate(input: DateOutput) { function handleDate(input: DateOutput) {
return dateSchema.parse(input) // Error: Argument of type 'Date' is not assignable to type 'string' return dateSchema.parse(input); // Error: Argument of type 'Date' is not assignable to type 'string'
} }
// Caller passes string, but type says Date // Caller passes string, but type says Date
handleDate('2024-01-15') // TypeScript error handleDate("2024-01-15"); // TypeScript error
``` ```
**Correct (using z.input for pre-transform type):** **Correct (using z.input for pre-transform type):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
const dateSchema = z.string().transform(s => new Date(s)) const dateSchema = z.string().transform((s) => new Date(s));
// Input type = what parse() accepts // Input type = what parse() accepts
type DateInput = z.input<typeof dateSchema> type DateInput = z.input<typeof dateSchema>;
// string (pre-transform) // string (pre-transform)
// Output type = what parse() returns // Output type = what parse() returns
type DateOutput = z.output<typeof dateSchema> type DateOutput = z.output<typeof dateSchema>;
// Date (post-transform) // Date (post-transform)
// Use input type for function parameters // Use input type for function parameters
function handleDate(input: DateInput) { function handleDate(input: DateInput) {
const parsed = dateSchema.parse(input) // parsed is Date const parsed = dateSchema.parse(input); // parsed is Date
return parsed return parsed;
} }
handleDate('2024-01-15') // Works - string input handleDate("2024-01-15"); // Works - string input
``` ```
**Complex example with object transforms:** **Complex example with object transforms:**
@@ -57,14 +57,13 @@ handleDate('2024-01-15') // Works - string input
```typescript ```typescript
const apiUserSchema = z.object({ const apiUserSchema = z.object({
id: z.string(), id: z.string(),
created_at: z.string().transform(s => new Date(s)), created_at: z.string().transform((s) => new Date(s)),
tags: z.string().transform(s => s.split(',')), tags: z.string().transform((s) => s.split(",")),
is_active: z.union([z.boolean(), z.literal(1), z.literal(0)]) is_active: z.union([z.boolean(), z.literal(1), z.literal(0)]).transform((v) => Boolean(v))
.transform(v => Boolean(v)), });
})
// What the API sends // What the API sends
type ApiUserInput = z.input<typeof apiUserSchema> type ApiUserInput = z.input<typeof apiUserSchema>;
// { // {
// id: string // id: string
// created_at: string // created_at: string
@@ -73,7 +72,7 @@ type ApiUserInput = z.input<typeof apiUserSchema>
// } // }
// What your code works with // What your code works with
type ApiUser = z.infer<typeof apiUserSchema> type ApiUser = z.infer<typeof apiUserSchema>;
// { // {
// id: string // id: string
// created_at: Date // created_at: Date
@@ -83,11 +82,11 @@ type ApiUser = z.infer<typeof apiUserSchema>
// API response handler // API response handler
function handleApiResponse(rawData: ApiUserInput) { function handleApiResponse(rawData: ApiUserInput) {
const user = apiUserSchema.parse(rawData) const user = apiUserSchema.parse(rawData);
// user.created_at is Date // user.created_at is Date
// user.tags is string[] // user.tags is string[]
// user.is_active is boolean // user.is_active is boolean
return user return user;
} }
``` ```
@@ -95,21 +94,22 @@ function handleApiResponse(rawData: ApiUserInput) {
```typescript ```typescript
const formSchema = z.object({ const formSchema = z.object({
amount: z.string().transform(s => parseFloat(s)), amount: z.string().transform((s) => parseFloat(s)),
quantity: z.string().transform(s => parseInt(s, 10)), quantity: z.string().transform((s) => parseInt(s, 10))
}) });
type FormInput = z.input<typeof formSchema> type FormInput = z.input<typeof formSchema>;
type FormOutput = z.output<typeof formSchema> type FormOutput = z.output<typeof formSchema>;
// Form handler receives raw strings // Form handler receives raw strings
type FormHandler = (input: FormInput) => Promise<void> type FormHandler = (input: FormInput) => Promise<void>;
// Business logic receives parsed values // Business logic receives parsed values
type OrderProcessor = (order: FormOutput) => Promise<void> type OrderProcessor = (order: FormOutput) => Promise<void>;
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- Schemas without transforms (input and output are identical) - Schemas without transforms (input and output are identical)
- When you only work with validated data (just use z.infer) - When you only work with validated data (just use z.infer)
@@ -12,14 +12,14 @@ Defining TypeScript types separately from Zod schemas creates duplication that i
**Incorrect (manual type definitions):** **Incorrect (manual type definitions):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Manual type definition // Manual type definition
interface User { interface User {
id: string id: string;
name: string name: string;
email: string email: string;
age: number age: number;
} }
// Separate schema // Separate schema
@@ -28,20 +28,20 @@ const userSchema = z.object({
name: z.string().min(1), name: z.string().min(1),
email: z.string().email(), email: z.string().email(),
age: z.number().int().positive(), age: z.number().int().positive(),
role: z.enum(['admin', 'user']), // Added to schema, forgot to add to interface! role: z.enum(["admin", "user"]) // Added to schema, forgot to add to interface!
}) });
// Type and schema are now out of sync // Type and schema are now out of sync
function createUser(user: User) { function createUser(user: User) {
const validated = userSchema.parse(user) // Has role const validated = userSchema.parse(user); // Has role
saveToDb(user) // Missing role - TypeScript doesn't warn saveToDb(user); // Missing role - TypeScript doesn't warn
} }
``` ```
**Correct (using z.infer):** **Correct (using z.infer):**
```typescript ```typescript
import { z } from 'zod' import { z } from "zod";
// Schema is the single source of truth // Schema is the single source of truth
const userSchema = z.object({ const userSchema = z.object({
@@ -49,17 +49,17 @@ const userSchema = z.object({
name: z.string().min(1), name: z.string().min(1),
email: z.string().email(), email: z.string().email(),
age: z.number().int().positive(), age: z.number().int().positive(),
role: z.enum(['admin', 'user']), role: z.enum(["admin", "user"])
}) });
// Type is always in sync with schema // Type is always in sync with schema
type User = z.infer<typeof userSchema> type User = z.infer<typeof userSchema>;
// { id: string; name: string; email: string; age: number; role: 'admin' | 'user' } // { id: string; name: string; email: string; age: number; role: 'admin' | 'user' }
function createUser(user: User) { function createUser(user: User) {
// user.role exists because type is derived from schema // user.role exists because type is derived from schema
const validated = userSchema.parse(user) const validated = userSchema.parse(user);
saveToDb(validated) saveToDb(validated);
} }
``` ```
@@ -68,21 +68,21 @@ function createUser(user: User) {
```typescript ```typescript
const userSchema = z.object({ const userSchema = z.object({
name: z.string(), name: z.string(),
createdAt: z.string().transform(s => new Date(s)), // String in, Date out createdAt: z.string().transform((s) => new Date(s)) // String in, Date out
}) });
// z.infer gives output type (after transforms) // z.infer gives output type (after transforms)
type User = z.infer<typeof userSchema> type User = z.infer<typeof userSchema>;
// { name: string; createdAt: Date } // { name: string; createdAt: Date }
// z.input gives input type (before transforms) // z.input gives input type (before transforms)
type UserInput = z.input<typeof userSchema> type UserInput = z.input<typeof userSchema>;
// { name: string; createdAt: string } // { name: string; createdAt: string }
// Use input type for function parameters accepting raw data // Use input type for function parameters accepting raw data
function processUser(input: UserInput) { function processUser(input: UserInput) {
const user = userSchema.parse(input) // user is User type const user = userSchema.parse(input); // user is User type
return user.createdAt.getTime() // Date methods available return user.createdAt.getTime(); // Date methods available
} }
``` ```
@@ -92,18 +92,19 @@ function processUser(input: UserInput) {
// Schema named with Schema suffix // Schema named with Schema suffix
const UserSchema = z.object({ const UserSchema = z.object({
id: z.string(), id: z.string(),
name: z.string(), name: z.string()
}) });
// Type named without suffix // Type named without suffix
type User = z.infer<typeof UserSchema> type User = z.infer<typeof UserSchema>;
// Alternative: lowercase schema, uppercase type // Alternative: lowercase schema, uppercase type
const userSchema = z.object({/*...*/}) const userSchema = z.object({/*...*/});
type User = z.infer<typeof userSchema> type User = z.infer<typeof userSchema>;
``` ```
**When NOT to use this pattern:** **When NOT to use this pattern:**
- When you need a type that's different from the validation schema - When you need a type that's different from the validation schema
- When interfacing with external types you don't control - When interfacing with external types you don't control
+31 -15
View File
@@ -1,33 +1,45 @@
#!/usr/bin/env node #!/usr/bin/env node
const path = require('path'); const path = require("path");
const fs = require('fs'); const fs = require("fs");
const { pathToFileURL } = require('url'); const { pathToFileURL } = require("url");
const { execFileSync } = require('child_process'); const { execFileSync } = require("child_process");
const dir = process.env.CLAUDE_PROJECT_DIR || process.cwd(); const dir = process.env.CLAUDE_PROJECT_DIR || process.cwd();
const BAKED = "C:\\Users\\Administrator.DESKTOP-EGNE9ND\\AppData\\Roaming\\npm\\node_modules\\@nanonets\\graft\\dist\\claude"; const BAKED =
"C:\\Users\\Administrator.DESKTOP-EGNE9ND\\AppData\\Roaming\\npm\\node_modules\\@nanonets\\graft\\dist\\claude";
// The dist/claude dir of @nanonets/graft resolved from a base whose node_modules is searched. // The dist/claude dir of @nanonets/graft resolved from a base whose node_modules is searched.
function fromPkg(base) { function fromPkg(base) {
try { try {
const pkg = require.resolve('@nanonets/graft/package.json', { paths: [base] }); const pkg = require.resolve("@nanonets/graft/package.json", { paths: [base] });
return path.join(path.dirname(pkg), 'dist', 'claude'); return path.join(path.dirname(pkg), "dist", "claude");
} catch { return null; } } catch {
return null;
}
} }
// The global node_modules dir per npm (handles Homebrew/Windows/volta). Queried on demand. // The global node_modules dir per npm (handles Homebrew/Windows/volta). Queried on demand.
function globalRoot() { function globalRoot() {
try { try {
const root = execFileSync('npm', ['root', '-g'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], shell: process.platform === 'win32' }).trim(); const root = execFileSync("npm", ["root", "-g"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
shell: process.platform === "win32"
}).trim();
return root || null; return root || null;
} catch { return null; /* npm unavailable */ } } catch {
return null; /* npm unavailable */
}
} }
function candidates() { function candidates() {
const out = []; const out = [];
if (BAKED) out.push(BAKED); if (BAKED) out.push(BAKED);
const local = fromPkg(dir); if (local) out.push(local); const local = fromPkg(dir);
const legacy = fromPkg(path.join(path.dirname(process.execPath), '..', 'lib')); if (legacy) out.push(legacy); if (local) out.push(local);
const gr = globalRoot(); if (gr) out.push(path.join(gr, '@nanonets', 'graft', 'dist', 'claude')); const legacy = fromPkg(path.join(path.dirname(process.execPath), "..", "lib"));
if (legacy) out.push(legacy);
const gr = globalRoot();
if (gr) out.push(path.join(gr, "@nanonets", "graft", "dist", "claude"));
return out; return out;
} }
@@ -36,7 +48,11 @@ function entry(name) {
const f = path.join(d, name); const f = path.join(d, name);
if (fs.existsSync(f)) return f; if (fs.existsSync(f)) return f;
} }
return path.join(dir, 'dist', 'claude', name); // last-ditch; import will no-op if absent return path.join(dir, "dist", "claude", name); // last-ditch; import will no-op if absent
} }
import(pathToFileURL(entry("hooks.js")).href).then((m) => m.main(process.argv[2])).catch(() => { /* graft unavailable — no-op */ }); import(pathToFileURL(entry("hooks.js")).href)
.then((m) => m.main(process.argv[2]))
.catch(() => {
/* graft unavailable — no-op */
});
+31 -15
View File
@@ -1,33 +1,45 @@
#!/usr/bin/env node #!/usr/bin/env node
const path = require('path'); const path = require("path");
const fs = require('fs'); const fs = require("fs");
const { pathToFileURL } = require('url'); const { pathToFileURL } = require("url");
const { execFileSync } = require('child_process'); const { execFileSync } = require("child_process");
const dir = process.env.CLAUDE_PROJECT_DIR || process.cwd(); const dir = process.env.CLAUDE_PROJECT_DIR || process.cwd();
const BAKED = "C:\\Users\\Administrator.DESKTOP-EGNE9ND\\AppData\\Roaming\\npm\\node_modules\\@nanonets\\graft\\dist\\claude"; const BAKED =
"C:\\Users\\Administrator.DESKTOP-EGNE9ND\\AppData\\Roaming\\npm\\node_modules\\@nanonets\\graft\\dist\\claude";
// The dist/claude dir of @nanonets/graft resolved from a base whose node_modules is searched. // The dist/claude dir of @nanonets/graft resolved from a base whose node_modules is searched.
function fromPkg(base) { function fromPkg(base) {
try { try {
const pkg = require.resolve('@nanonets/graft/package.json', { paths: [base] }); const pkg = require.resolve("@nanonets/graft/package.json", { paths: [base] });
return path.join(path.dirname(pkg), 'dist', 'claude'); return path.join(path.dirname(pkg), "dist", "claude");
} catch { return null; } } catch {
return null;
}
} }
// The global node_modules dir per npm (handles Homebrew/Windows/volta). Queried on demand. // The global node_modules dir per npm (handles Homebrew/Windows/volta). Queried on demand.
function globalRoot() { function globalRoot() {
try { try {
const root = execFileSync('npm', ['root', '-g'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], shell: process.platform === 'win32' }).trim(); const root = execFileSync("npm", ["root", "-g"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
shell: process.platform === "win32"
}).trim();
return root || null; return root || null;
} catch { return null; /* npm unavailable */ } } catch {
return null; /* npm unavailable */
}
} }
function candidates() { function candidates() {
const out = []; const out = [];
if (BAKED) out.push(BAKED); if (BAKED) out.push(BAKED);
const local = fromPkg(dir); if (local) out.push(local); const local = fromPkg(dir);
const legacy = fromPkg(path.join(path.dirname(process.execPath), '..', 'lib')); if (legacy) out.push(legacy); if (local) out.push(local);
const gr = globalRoot(); if (gr) out.push(path.join(gr, '@nanonets', 'graft', 'dist', 'claude')); const legacy = fromPkg(path.join(path.dirname(process.execPath), "..", "lib"));
if (legacy) out.push(legacy);
const gr = globalRoot();
if (gr) out.push(path.join(gr, "@nanonets", "graft", "dist", "claude"));
return out; return out;
} }
@@ -36,7 +48,11 @@ function entry(name) {
const f = path.join(d, name); const f = path.join(d, name);
if (fs.existsSync(f)) return f; if (fs.existsSync(f)) return f;
} }
return path.join(dir, 'dist', 'claude', name); // last-ditch; import will no-op if absent return path.join(dir, "dist", "claude", name); // last-ditch; import will no-op if absent
} }
import(pathToFileURL(entry("statusline.js")).href).then((m) => m.main()).catch(() => { /* graft unavailable — no-op */ }); import(pathToFileURL(entry("statusline.js")).href)
.then((m) => m.main())
.catch(() => {
/* graft unavailable — no-op */
});
+2 -9
View File
@@ -64,15 +64,8 @@
} }
] ]
}, },
"footerLinksRegexes": [ "footerLinksRegexes": ["graft/[\\w./-]+\\.md"],
"graft/[\\w./-]+\\.md"
],
"permissions": { "permissions": {
"allow": [ "allow": ["Bash(graft:*)", "Bash(npx graft:*)", "Bash(graft-dev:*)", "Bash(node dist/cli.js:*)"]
"Bash(graft:*)",
"Bash(npx graft:*)",
"Bash(graft-dev:*)",
"Bash(node dist/cli.js:*)"
]
} }
} }
@@ -9,18 +9,22 @@ metadata:
# ghbot production hardening skill # ghbot production hardening skill
## When to use ## When to use
Closing a production iteration of this GitHub review bot. Not for adding unrelated SaaS features. Closing a production iteration of this GitHub review bot. Not for adding unrelated SaaS features.
## Do not use ## Do not use
- Changing AUTO_MERGE default - Changing AUTO_MERGE default
- Reusing old review cache as a new-head approval - Reusing old review cache as a new-head approval
- Running paid LLM E2E without budget - Running paid LLM E2E without budget
- Pushing to remotes without write permission - Pushing to remotes without write permission
## Inputs ## Inputs
Current repo, CLAUDE.md red lines, `.specify/memory/constitution.md`. Current repo, CLAUDE.md red lines, `.specify/memory/constitution.md`.
## Steps ## Steps
1. Read constitution, CLAUDE.md, workflow_status.md, last verification record. 1. Read constitution, CLAUDE.md, workflow_status.md, last verification record.
2. Rebuild facts: git status, typecheck, test. 2. Rebuild facts: git status, typecheck, test.
3. Audit contract/security/error/docs before coding. 3. Audit contract/security/error/docs before coding.
@@ -31,7 +35,9 @@ Current repo, CLAUDE.md red lines, `.specify/memory/constitution.md`.
8. Sync README/.env.example/workflows. Write HTML report under docs/reports/. 8. Sync README/.env.example/workflows. Write HTML report under docs/reports/.
## Stop ## Stop
Missing credentials, origin 403, paid API, production deploy, no progress after two review loops. Missing credentials, origin 403, paid API, production deploy, no progress after two review loops.
## Verify ## Verify
Never claim LLM review E2E or origin push without command evidence. Never claim LLM review E2E or origin push without command evidence.
+4
View File
@@ -16,11 +16,13 @@
## 技术原则 ## 技术原则
### 架构 ### 架构
- 单一职责:一个模块只回答一个问题(谁调用它、它调用谁、失败时谁兜底)。 - 单一职责:一个模块只回答一个问题(谁调用它、它调用谁、失败时谁兜底)。
- 共享清单单一来源:安全排除/脱敏/路径策略只允许一份实现(src/security/, src/runtimePaths.ts)。 - 共享清单单一来源:安全排除/脱敏/路径策略只允许一份实现(src/security/, src/runtimePaths.ts)。
- 行为不变的重构必须与功能变更分开提交,且全量测试保护。 - 行为不变的重构必须与功能变更分开提交,且全量测试保护。
### 质量门禁(提交前全部通过) ### 质量门禁(提交前全部通过)
1. `npm run typecheck` — 0 错误 1. `npm run typecheck` — 0 错误
2. `npm run lint` — 0 error 2. `npm run lint` — 0 error
3. `npm run format:check` — 通过 3. `npm run format:check` — 通过
@@ -29,6 +31,7 @@
6. `npm audit --omit=dev` — 无 high 以上 6. `npm audit --omit=dev` — 无 high 以上
### 安全红线(继承 CLAUDE.md,不可协商) ### 安全红线(继承 CLAUDE.md,不可协商)
- AUTO_MERGE=false 默认值不可改 - AUTO_MERGE=false 默认值不可改
- 恢复缓存审查结果必须重新完整审查,不得直接复用旧决策 - 恢复缓存审查结果必须重新完整审查,不得直接复用旧决策
- fork 推送必须 SHA 钉住 --force-with-lease - fork 推送必须 SHA 钉住 --force-with-lease
@@ -37,6 +40,7 @@
## 决策框架 ## 决策框架
技术选型按序评估: 技术选型按序评估:
1. 是否触碰安全红线?(触碰 → 拒绝) 1. 是否触碰安全红线?(触碰 → 拒绝)
2. 是否可用现有轮子解决?(可以 → 不写新代码) 2. 是否可用现有轮子解决?(可以 → 不写新代码)
3. 失败时的降级行为是否清晰?(不清晰 → 先设计降级) 3. 失败时的降级行为是否清晰?(不清晰 → 先设计降级)
@@ -9,36 +9,46 @@ ghbot 已在生产仓库运行(自动审查/分类/合并/冲突修复)。
## 用户故事 ## 用户故事
### US-1: 部署者首次接入 ### US-1: 部署者首次接入
作为部署者,我希望按 README 从零配置后一次跑通,无需口口相传的隐性前提。 作为部署者,我希望按 README 从零配置后一次跑通,无需口口相传的隐性前提。
**验收**: **验收**:
- [ ] .env.example 覆盖全部 config schema 字段且默认值一致 - [ ] .env.example 覆盖全部 config schema 字段且默认值一致
- [ ] README 步骤与实际命令一一对应 - [ ] README 步骤与实际命令一一对应
- [ ] 新增配置项有文档说明 - [ ] 新增配置项有文档说明
### US-2: 事件全链路 ### US-2: 事件全链路
作为仓库维护者,任何支持的事件触发后都有确定行为与反馈。 作为仓库维护者,任何支持的事件触发后都有确定行为与反馈。
**验收**: **验收**:
- [ ] workflow 触发的事件类型 ⊆ runReview.ts 处理集合(无静默吞事件) - [ ] workflow 触发的事件类型 ⊆ runReview.ts 处理集合(无静默吞事件)
- [ ] issue_comment 三链路互不阻断 - [ ] issue_comment 三链路互不阻断
- [ ] 每条失败路径都有可见反馈或日志 - [ ] 每条失败路径都有可见反馈或日志
### US-3: 审查结果可信 ### US-3: 审查结果可信
作为 PR 作者,审查评论必须准确、可定位、不误导。 作为 PR 作者,审查评论必须准确、可定位、不误导。
**验收**: **验收**:
- [ ] finding 的 path/line 经净化后才提交 - [ ] finding 的 path/line 经净化后才提交
- [ ] 无法 inline 的 findings 折叠展示不丢失 - [ ] 无法 inline 的 findings 折叠展示不丢失
- [ ] 状态横幅与 disposition 一致 - [ ] 状态横幅与 disposition 一致
### US-4: webhook 服务可运维 ### US-4: webhook 服务可运维
作为运维者,服务健康可探活、指标可观测、异常可恢复。 作为运维者,服务健康可探活、指标可观测、异常可恢复。
**验收**: **验收**:
- [ ] /healthz 与 /metrics 真实可用 - [ ] /healthz 与 /metrics 真实可用
- [ ] 队列满/签名错/超大包均有明确响应码 - [ ] 队列满/签名错/超大包均有明确响应码
- [ ] 失败投递进程内重试后仍可被 GitHub 重投 - [ ] 失败投递进程内重试后仍可被 GitHub 重投
### US-5: 剩余指南项落地 ### US-5: 剩余指南项落地
指南 7.1 / 6.4 / 8.5 / 4.4 不再是"候选",全部实现或有明确的不适用结论。 指南 7.1 / 6.4 / 8.5 / 4.4 不再是"候选",全部实现或有明确的不适用结论。
**验收**: **验收**:
- [ ] 每项有代码证据或书面不适用理由 - [ ] 每项有代码证据或书面不适用理由
- [ ] 全部门禁通过 - [ ] 全部门禁通过
@@ -1,10 +1,12 @@
# Implementation Tasks: 001-production-hardening # Implementation Tasks: 001-production-hardening
## Phase 1: Spec and audit ## Phase 1: Spec and audit
- [x] 1.1 Constitution + spec - [x] 1.1 Constitution + spec
- [x] 1.2 Parallel contract/security/error/docs audit - [x] 1.2 Parallel contract/security/error/docs audit
## Phase 2: Production guards ## Phase 2: Production guards
- [x] 2.1 Merge SHA recheck + pulls.merge sha - [x] 2.1 Merge SHA recheck + pulls.merge sha
- [x] 2.2 Conflict lock + git command timeout + dirty worktree reset - [x] 2.2 Conflict lock + git command timeout + dirty worktree reset
- [x] 2.3 Webhook body timeout/size and request catch - [x] 2.3 Webhook body timeout/size and request catch
@@ -16,6 +18,7 @@
- [x] 2.9 Event logger child bindings - [x] 2.9 Event logger child bindings
## Phase 3: Verify and handoff ## Phase 3: Verify and handoff
- [ ] 3.1 Local gates (typecheck/lint/format/test) - [ ] 3.1 Local gates (typecheck/lint/format/test)
- [ ] 3.2 Webhook HTTP E2E - [ ] 3.2 Webhook HTTP E2E
- [ ] 3.3 Independent review - [ ] 3.3 Independent review
+228 -67
View File
@@ -1,9 +1,10 @@
# ghbot Production Hardening # ghbot Production Hardening > 终局审计变更说明与验收测验。对照当前仓库真实实现,不包装未验证项。
> 终局审计变更说明与验收测验。对照当前仓库真实实现,不包装未验证项。
<title>ghbot Hardening Ledger</title> <title>ghbot Hardening Ledger</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:ital,wght@0,400;0,500;0,600;1,400&family=Source+Serif+4:opsz,wght@8..60,600;8..60,700&display=swap"> <link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:ital,wght@0,400;0,500;0,600;1,400&family=Source+Serif+4:opsz,wght@8..60,600;8..60,700&display=swap"
/>
<style> <style>
:root { :root {
--paper: #f3f0ea; --paper: #f3f0ea;
@@ -44,8 +45,15 @@
--code: #0f141b; --code: #0f141b;
} }
* { box-sizing: border-box; } * {
html, body { margin: 0; background: var(--paper); color: var(--ink); } box-sizing: border-box;
}
html,
body {
margin: 0;
background: var(--paper);
color: var(--ink);
}
body { body {
font-family: "IBM Plex Sans", "Segoe UI", sans-serif; font-family: "IBM Plex Sans", "Segoe UI", sans-serif;
line-height: 1.55; line-height: 1.55;
@@ -55,15 +63,31 @@
margin: 0 auto; margin: 0 auto;
padding: 2.5rem 1.25rem 5rem; padding: 2.5rem 1.25rem 5rem;
} }
h1, h2, h3 { h1,
h2,
h3 {
font-family: "Source Serif 4", Georgia, serif; font-family: "Source Serif 4", Georgia, serif;
text-wrap: balance; text-wrap: balance;
font-weight: 700; font-weight: 700;
} }
h1 { font-size: 2.1rem; margin: 0 0 0.4rem; } h1 {
h2 { font-size: 1.35rem; margin: 2.2rem 0 0.7rem; border-top: 1px solid var(--line); padding-top: 1.2rem; } font-size: 2.1rem;
p, li { color: var(--ink); } margin: 0 0 0.4rem;
.lede { color: var(--muted); max-width: 62ch; } }
h2 {
font-size: 1.35rem;
margin: 2.2rem 0 0.7rem;
border-top: 1px solid var(--line);
padding-top: 1.2rem;
}
p,
li {
color: var(--ink);
}
.lede {
color: var(--muted);
max-width: 62ch;
}
.grid { .grid {
display: grid; display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
@@ -75,14 +99,41 @@
border: 1px solid var(--line); border: 1px solid var(--line);
padding: 0.85rem 0.95rem; padding: 0.85rem 0.95rem;
} }
.stat b { display: block; font-family: "IBM Plex Mono", monospace; font-size: 1.05rem; } .stat b {
.stat span { color: var(--muted); font-size: 0.82rem; } display: block;
table { width: 100%; border-collapse: collapse; font-size: 0.92rem; } font-family: "IBM Plex Mono", monospace;
th, td { text-align: left; padding: 0.45rem 0.4rem; border-bottom: 1px solid var(--line); vertical-align: top; } font-size: 1.05rem;
.ok { color: var(--ok); font-weight: 600; } }
.warn { color: var(--warn); font-weight: 600; } .stat span {
.bad { color: var(--bad); font-weight: 600; } color: var(--muted);
code, pre { font-size: 0.82rem;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.92rem;
}
th,
td {
text-align: left;
padding: 0.45rem 0.4rem;
border-bottom: 1px solid var(--line);
vertical-align: top;
}
.ok {
color: var(--ok);
font-weight: 600;
}
.warn {
color: var(--warn);
font-weight: 600;
}
.bad {
color: var(--bad);
font-weight: 600;
}
code,
pre {
font-family: "IBM Plex Mono", ui-monospace, monospace; font-family: "IBM Plex Mono", ui-monospace, monospace;
font-size: 0.86rem; font-size: 0.86rem;
} }
@@ -97,8 +148,14 @@
border: 1px solid var(--line); border: 1px solid var(--line);
padding: 1rem 1.1rem 1.2rem; padding: 1rem 1.1rem 1.2rem;
} }
.q { margin: 1rem 0 0.4rem; font-weight: 600; } .q {
label { display: block; margin: 0.2rem 0; } margin: 1rem 0 0.4rem;
font-weight: 600;
}
label {
display: block;
margin: 0.2rem 0;
}
button { button {
margin-top: 1rem; margin-top: 1rem;
background: var(--ink); background: var(--ink);
@@ -108,12 +165,24 @@
font: inherit; font: inherit;
cursor: pointer; cursor: pointer;
} }
button:focus { outline: 2px solid var(--accent); outline-offset: 2px; } button:focus {
#score { margin-top: 0.8rem; font-weight: 600; } outline: 2px solid var(--accent);
.hidden-answer { display: none; } outline-offset: 2px;
}
#score {
margin-top: 0.8rem;
font-weight: 600;
}
.hidden-answer {
display: none;
}
</style> </style>
<p class="lede">这份报告对应 ghbot 生产硬化批次:合并 SHA 钉死、冲突锁、webhook/代理超时、配置交叉校验,以及本地门禁与 HTTP 冒烟。测验覆盖真实行为,不是口号。</p> <p class="lede">
这份报告对应 ghbot 生产硬化批次:合并 SHA
钉死、冲突锁、webhook/代理超时、配置交叉校验,以及本地门禁与 HTTP
冒烟。测验覆盖真实行为,不是口号。
</p>
<div class="grid"> <div class="grid">
<div class="stat"><b>148</b><span>本地测试通过(本批次实测)</span></div> <div class="stat"><b>148</b><span>本地测试通过(本批次实测)</span></div>
@@ -124,33 +193,98 @@
<h2>改了什么,为什么</h2> <h2>改了什么,为什么</h2>
<table> <table>
<thead><tr><th>守卫</th><th>故障模式</th><th>落地</th></tr></thead> <thead>
<tr>
<th>守卫</th>
<th>故障模式</th>
<th>落地</th>
</tr>
</thead>
<tbody> <tbody>
<tr><td>合并 SHA</td><td>审查后 head 变化仍 merge</td><td><code>pulls.merge(sha)</code> + live head 复检</td></tr> <tr>
<tr><td>冲突锁</td><td>同一 PR 并发改共享 worktree</td><td>进程内 per-PR lock + 失败 hard reset</td></tr> <td>合并 SHA</td>
<tr><td>git/代理/进程</td><td>无超时、输出无限增长</td><td>timeout + 1MB 输出帽 + abort</td></tr> <td>审查后 head 变化仍 merge</td>
<tr><td>webhook</td><td>慢客户端/超大包拖死</td><td>30s body、413、顶层 catch</td></tr> <td><code>pulls.merge(sha)</code> + live head 复检</td>
<tr><td>配置</td><td>半套 R2 / webhook 无 secret</td><td>zod superRefine fail-fast</td></tr> </tr>
<tr><td>评论命令</td><td>失败被吃掉,Actions 显示成功</td><td>allSettled + AggregateError</td></tr> <tr>
<td>冲突锁</td>
<td>同一 PR 并发改共享 worktree</td>
<td>进程内 per-PR lock + 失败 hard reset</td>
</tr>
<tr>
<td>git/代理/进程</td>
<td>无超时、输出无限增长</td>
<td>timeout + 1MB 输出帽 + abort</td>
</tr>
<tr>
<td>webhook</td>
<td>慢客户端/超大包拖死</td>
<td>30s body、413、顶层 catch</td>
</tr>
<tr>
<td>配置</td>
<td>半套 R2 / webhook 无 secret</td>
<td>zod superRefine fail-fast</td>
</tr>
<tr>
<td>评论命令</td>
<td>失败被吃掉,Actions 显示成功</td>
<td>allSettled + AggregateError</td>
</tr>
</tbody> </tbody>
</table> </table>
<h2>需求追踪摘要</h2> <h2>需求追踪摘要</h2>
<table> <table>
<thead><tr><th>需求</th><th>状态</th><th>证据</th></tr></thead> <thead>
<tr>
<th>需求</th>
<th>状态</th>
<th>证据</th>
</tr>
</thead>
<tbody> <tbody>
<tr><td>生产安全红线(凭据/PR 代码/缓存复用)</td><td class="ok">已闭环(静态+测试)</td><td>sanitization/secrets、snapshot 排除、cache 只作增量上下文</td></tr> <tr>
<tr><td>部署一次能跑</td><td class="warn">部分闭环</td><td>文档/env 已对齐;真实 GitHub App 安装未在本机复现</td></tr> <td>生产安全红线(凭据/PR 代码/缓存复用)</td>
<tr><td>事件失败可见</td><td class="ok">已闭环</td><td>comment AggregateError;webhook 401/413/503</td></tr> <td class="ok">已闭环(静态+测试)</td>
<tr><td>审查结果可信</td><td class="ok">已闭环</td><td>normalizeReviewDecision + 状态横幅</td></tr> <td>sanitization/secrets、snapshot 排除、cache 只作增量上下文</td>
<tr><td>7.1 事件路由器拆分</td><td class="warn">未做(有意)</td><td>无事件环测试床,拆 1700 行 processor 风险高于收益</td></tr> </tr>
<tr><td>6.4 全站 i18n</td><td class="warn">未闭环</td><td>仅 chat 按评论语言;审查正文仍英文</td></tr> <tr>
<tr><td>付费 LLM E2E</td><td class="warn">外部受限</td><td>未调用真实 Goose/OpenAI</td></tr> <td>部署一次能跑</td>
<td class="warn">部分闭环</td>
<td>文档/env 已对齐;真实 GitHub App 安装未在本机复现</td>
</tr>
<tr>
<td>事件失败可见</td>
<td class="ok">已闭环</td>
<td>comment AggregateError;webhook 401/413/503</td>
</tr>
<tr>
<td>审查结果可信</td>
<td class="ok">已闭环</td>
<td>normalizeReviewDecision + 状态横幅</td>
</tr>
<tr>
<td>7.1 事件路由器拆分</td>
<td class="warn">未做(有意)</td>
<td>无事件环测试床,拆 1700 行 processor 风险高于收益</td>
</tr>
<tr>
<td>6.4 全站 i18n</td>
<td class="warn">未闭环</td>
<td>仅 chat 按评论语言;审查正文仍英文</td>
</tr>
<tr>
<td>付费 LLM E2E</td>
<td class="warn">外部受限</td>
<td>未调用真实 Goose/OpenAI</td>
</tr>
</tbody> </tbody>
</table> </table>
<h2>验证证据</h2> <h2>验证证据</h2>
<pre>npm run typecheck → 0 errors <pre>
npm run typecheck → 0 errors
npm test → 148/148 pass npm test → 148/148 pass
npm run lint → 0 errors npm run lint → 0 errors
npm run format:check → pass npm run format:check → pass
@@ -162,7 +296,9 @@ webhook HTTP smoke → see E2E section in repo docs</pre>
<ul> <ul>
<li>没有把审查编排拆成独立 router(7.1)。</li> <li>没有把审查编排拆成独立 router(7.1)。</li>
<li>没有把全部评论文案做成中英字典(6.4)。</li> <li>没有把全部评论文案做成中英字典(6.4)。</li>
<li>没有 goose CLI 二进制 checksum 钉死(安装脚本仍从 GitHub 拉指定 tag 的 download_cli.sh)。</li> <li>
没有 goose CLI 二进制 checksum 钉死(安装脚本仍从 GitHub 拉指定 tag 的 download_cli.sh)。
</li>
<li>没有对 origin <code>lezi-fun/ghbot</code> 推送(账号无权限)。</li> <li>没有对 origin <code>lezi-fun/ghbot</code> 推送(账号无权限)。</li>
</ul> </ul>
@@ -171,64 +307,89 @@ webhook HTTP smoke → see E2E section in repo docs</pre>
<p>提交后显示分数。通过线 80%(8/10)。未提交前不显示答案。</p> <p>提交后显示分数。通过线 80%(8/10)。未提交前不显示答案。</p>
<form id="quiz"> <form id="quiz">
<div class="q">1. AUTO_MERGE 的代码默认值是?</div> <div class="q">1. AUTO_MERGE 的代码默认值是?</div>
<label><input type="radio" name="q1" value="a"> true</label> <label><input type="radio" name="q1" value="a" /> true</label>
<label><input type="radio" name="q1" value="b"> false</label> <label><input type="radio" name="q1" value="b" /> false</label>
<label><input type="radio" name="q1" value="c"> inherit GitHub</label> <label><input type="radio" name="q1" value="c" /> inherit GitHub</label>
<div class="q">2. 合并时如何防止审查后 head 被替换?</div> <div class="q">2. 合并时如何防止审查后 head 被替换?</div>
<label><input type="radio" name="q2" value="a"> 只看缓存决策</label> <label><input type="radio" name="q2" value="a" /> 只看缓存决策</label>
<label><input type="radio" name="q2" value="b"> pulls.merge 传入审查时的 sha,并 live GET 复检</label> <label
<label><input type="radio" name="q2" value="c"> force push 回去</label> ><input type="radio" name="q2" value="b" /> pulls.merge 传入审查时的 sha,并 live GET
复检</label
>
<label><input type="radio" name="q2" value="c" /> force push 回去</label>
<div class="q">3. WEBHOOK_SECRET 应该等于 webhook URL 吗?</div> <div class="q">3. WEBHOOK_SECRET 应该等于 webhook URL 吗?</div>
<label><input type="radio" name="q3" value="a"> 应该,方便记忆</label> <label><input type="radio" name="q3" value="a" /> 应该,方便记忆</label>
<label><input type="radio" name="q3" value="b"> 不应该,必须是独立 HMAC 密钥</label> <label><input type="radio" name="q3" value="b" /> 不应该,必须是独立 HMAC 密钥</label>
<div class="q">4. 同一 PR 两个 /conflict 同时跑会怎样?</div> <div class="q">4. 同一 PR 两个 /conflict 同时跑会怎样?</div>
<label><input type="radio" name="q4" value="a"> 共享 worktree 并行 merge</label> <label><input type="radio" name="q4" value="a" /> 共享 worktree 并行 merge</label>
<label><input type="radio" name="q4" value="b"> 第二个获取锁失败</label> <label><input type="radio" name="q4" value="b" /> 第二个获取锁失败</label>
<div class="q">5. R2 只配了 endpoint 没有密钥时?</div> <div class="q">5. R2 只配了 endpoint 没有密钥时?</div>
<label><input type="radio" name="q5" value="a"> 静默跳过</label> <label><input type="radio" name="q5" value="a" /> 静默跳过</label>
<label><input type="radio" name="q5" value="b"> 启动/解析配置失败</label> <label><input type="radio" name="q5" value="b" /> 启动/解析配置失败</label>
<div class="q">6. issue_comment 里 /recheck 抛错时?</div> <div class="q">6. issue_comment 里 /recheck 抛错时?</div>
<label><input type="radio" name="q6" value="a"> 整个 job 仍标成功</label> <label><input type="radio" name="q6" value="a" /> 整个 job 仍标成功</label>
<label><input type="radio" name="q6" value="b"> 其他 handler 仍跑,最后 AggregateError 让 Actions 失败可重试</label> <label
><input type="radio" name="q6" value="b" /> 其他 handler 仍跑,最后 AggregateError 让 Actions
失败可重试</label
>
<div class="q">7. 审查 finding 指向 PR 里不存在的文件?</div> <div class="q">7. 审查 finding 指向 PR 里不存在的文件?</div>
<label><input type="radio" name="q7" value="a"> 原样提交 inline</label> <label><input type="radio" name="q7" value="a" /> 原样提交 inline</label>
<label><input type="radio" name="q7" value="b"> normalize 丢掉并记 warning</label> <label><input type="radio" name="q7" value="b" /> normalize 丢掉并记 warning</label>
<div class="q">8. Goose 容器能拿到真实 GOOSE_API_KEY 吗?</div> <div class="q">8. Goose 容器能拿到真实 GOOSE_API_KEY 吗?</div>
<label><input type="radio" name="q8" value="a"> 能,方便调试</label> <label><input type="radio" name="q8" value="a" /> 能,方便调试</label>
<label><input type="radio" name="q8" value="b"> 不能,只用一次性代理 token</label> <label><input type="radio" name="q8" value="b" /> 不能,只用一次性代理 token</label>
<div class="q">9. 本批次是否声称真实付费 LLM 端到端已跑通?</div> <div class="q">9. 本批次是否声称真实付费 LLM 端到端已跑通?</div>
<label><input type="radio" name="q9" value="a"> 是</label> <label><input type="radio" name="q9" value="a" /> 是</label>
<label><input type="radio" name="q9" value="b"> 否,外部调用未测</label> <label><input type="radio" name="q9" value="b" /> 否,外部调用未测</label>
<div class="q">10. origin lezi-fun/ghbot 推送状态?</div> <div class="q">10. origin lezi-fun/ghbot 推送状态?</div>
<label><input type="radio" name="q10" value="a"> 已推送</label> <label><input type="radio" name="q10" value="a" /> 已推送</label>
<label><input type="radio" name="q10" value="b"> 403,改推 lza6/ghbot-Nodeloc</label> <label><input type="radio" name="q10" value="b" /> 403,改推 lza6/ghbot-Nodeloc</label>
<button type="submit">提交测验</button> <button type="submit">提交测验</button>
</form> </form>
<div id="score"></div> <div id="score"></div>
</div> </div>
<script> <script>
const answers = {q1:"b",q2:"b",q3:"b",q4:"b",q5:"b",q6:"b",q7:"b",q8:"b",q9:"b",q10:"b"}; const answers = {
q1: "b",
q2: "b",
q3: "b",
q4: "b",
q5: "b",
q6: "b",
q7: "b",
q8: "b",
q9: "b",
q10: "b"
};
document.getElementById("quiz").addEventListener("submit", function (e) { document.getElementById("quiz").addEventListener("submit", function (e) {
e.preventDefault(); e.preventDefault();
const form = e.target; const form = e.target;
let score = 0; let score = 0;
const total = Object.keys(answers).length; const total = Object.keys(answers).length;
for (const [name, expected] of Object.entries(answers)) { for (const [name, expected] of Object.entries(answers)) {
const picked = form.querySelector('input[name="'+name+'"]:checked'); const picked = form.querySelector('input[name="' + name + '"]:checked');
if (picked && picked.value === expected) score += 1; if (picked && picked.value === expected) score += 1;
} }
const pct = Math.round((score / total) * 100); const pct = Math.round((score / total) * 100);
const pass = pct >= 80; const pass = pct >= 80;
document.getElementById("score").textContent = "得分 " + score + "/" + total + "(" + pct + "%)。" + (pass ? "通过。" : "未通过,对照报告再答。"); document.getElementById("score").textContent =
"得分 " +
score +
"/" +
total +
"(" +
pct +
"%)。" +
(pass ? "通过。" : "未通过,对照报告再答。");
}); });
</script> </script>
+24
View File
@@ -0,0 +1,24 @@
# 执行计划
## 阶段划分
- **M0**: 测试覆盖补齐(覆盖率 61% → 90%+)
- **M1**: 可靠性(智能重试、陈旧检测、fail-fast)
- **M2**: 可观测性(全链路日志、Actions 指标、失败分类)
- **M3-M5**: 架构与性能(大文件拆分、AI Provider、分片审查)
- **M6-M7**: 智能审查与国际化
- **最终**: 门禁验证 → 提交 → 推送 → 发布
## 并行策略
- M0-1 normalizeKnowledge 修复(先执行,确保基线绿)
- 测试补齐(M0-2 ~ M0-8)→ 并行
- M1(可靠性)→ 串行于 M0 之后
- M2(可观测性)→ 并行于 M1 时
- M3-M5 → 串行
- M6-M7 → 串行
## 当前状态
- 基线: 151 tests / 全绿 / 覆盖率 61.41%
- 目标: 测试全绿 + 覆盖率 90%+ + 门禁通过 + 推送 + 发行版
+10 -2
View File
@@ -17,7 +17,9 @@ function run(cmd) {
// 1) 暂存区生成物防护:graft/、.codegraph/、.code-review-graph/、dist/ 等不允许进仓库。 // 1) 暂存区生成物防护:graft/、.codegraph/、.code-review-graph/、dist/ 等不允许进仓库。
const staged = run("git diff --cached --name-only").split("\n").filter(Boolean); const staged = run("git diff --cached --name-only").split("\n").filter(Boolean);
const blockedPrefixes = ["graft/", ".codegraph/", ".code-review-graph/", "dist/", ".ghbot-tmp/"]; const blockedPrefixes = ["graft/", ".codegraph/", ".code-review-graph/", "dist/", ".ghbot-tmp/"];
const blocked = staged.filter((file) => blockedPrefixes.some((p) => file === p.slice(0, -1) || file.startsWith(p))); const blocked = staged.filter((file) =>
blockedPrefixes.some((p) => file === p.slice(0, -1) || file.startsWith(p))
);
if (blocked.length > 0) { if (blocked.length > 0) {
console.error("[pre-commit] BLOCKED:以下生成物/索引文件被暂存,已拒绝提交:"); console.error("[pre-commit] BLOCKED:以下生成物/索引文件被暂存,已拒绝提交:");
blocked.forEach((f) => console.error(` - ${f}`)); blocked.forEach((f) => console.error(` - ${f}`));
@@ -33,7 +35,13 @@ if (changedTs.length > 0) {
const tsc = run("npm run typecheck"); const tsc = run("npm run typecheck");
if (tsc && /error TS\d+/.test(tsc)) { if (tsc && /error TS\d+/.test(tsc)) {
console.error("[pre-commit] TypeScript 类型错误,已阻止提交:"); console.error("[pre-commit] TypeScript 类型错误,已阻止提交:");
console.error(tsc.split("\n").filter((l) => /error TS/.test(l)).slice(0, 20).join("\n")); console.error(
tsc
.split("\n")
.filter((l) => /error TS/.test(l))
.slice(0, 20)
.join("\n")
);
process.exit(1); process.exit(1);
} }
} }
+1 -1
View File
@@ -21,7 +21,7 @@ if (!fs.existsSync(gitDir)) {
fs.mkdirSync(hooksDir, { recursive: true }); fs.mkdirSync(hooksDir, { recursive: true });
// git hooks 以仓库根为工作目录,相对路径在 Windows 与 POSIX 下都可靠。 // git hooks 以仓库根为工作目录,相对路径在 Windows 与 POSIX 下都可靠。
const hookScript = ["#!/bin/sh", 'node scripts/husky-pre-commit.cjs'].join("\n"); const hookScript = ["#!/bin/sh", "node scripts/husky-pre-commit.cjs"].join("\n");
fs.writeFileSync(hookPath, `${hookScript}\n`, { mode: 0o755 }); fs.writeFileSync(hookPath, `${hookScript}\n`, { mode: 0o755 });
console.log(`[install-husky] 已写入 git pre-commit 钩子: ${hookPath}`); console.log(`[install-husky] 已写入 git pre-commit 钩子: ${hookPath}`);
+97
View File
@@ -0,0 +1,97 @@
export type FailureCategory =
"timeout" | "auth" | "rate_limit" | "network" | "model" | "validation" | "unknown";
/**
* Categorize a caught error into a FailureCategory based on its message, status, or code.
*/
export function categorizeFailure(error: unknown): FailureCategory {
if (typeof error !== "object" || error === null) {
return "unknown";
}
const err = error as { message?: string; status?: number; code?: string };
// Check by status code first
if (typeof err.status === "number") {
if (err.status === 401 || err.status === 403) {
return "auth";
}
if (err.status === 429) {
return "rate_limit";
}
if (err.status === 422) {
return "validation";
}
if (err.status >= 500 && err.status < 600) {
return "model";
}
}
// Check by error code (Node.js system errors)
if (typeof err.code === "string") {
const timeoutCodes = new Set(["ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT"]);
const networkCodes = new Set([
"ECONNRESET",
"ECONNREFUSED",
"EAI_AGAIN",
"ENOTFOUND",
"EPIPE",
"UND_ERR_SOCKET"
]);
if (timeoutCodes.has(err.code)) {
return "timeout";
}
if (networkCodes.has(err.code)) {
return "network";
}
}
// Check by message content
if (typeof err.message === "string") {
const msg = err.message.toLowerCase();
if (/timeout|timed?\s*out/i.test(msg)) {
return "timeout";
}
if (/unauthorized|forbidden|auth|api key|invalid token|credentials?/i.test(msg)) {
return "auth";
}
if (/rate limit|too many requests|quota/i.test(msg)) {
return "rate_limit";
}
if (/network|econnreset|econnrefused|eai_again|enotfound|epipe|dns/i.test(msg)) {
return "network";
}
if (/model|completion|generation|token limit|context length/i.test(msg)) {
return "model";
}
if (/validation|parse|schema|invalid|malformed/i.test(msg)) {
return "validation";
}
}
return "unknown";
}
/**
* Format a human-readable failure message for a given category.
*/
export function formatFailureMessage(
category: FailureCategory,
context: { action: string; attempts: number }
): string {
const { action, attempts } = context;
const messages: Record<FailureCategory, string> = {
timeout: `Action "${action}" timed out after ${attempts} attempt(s). The upstream service did not respond in time.`,
auth: `Action "${action}" failed due to an authentication error after ${attempts} attempt(s). Check that credentials are valid and have not expired.`,
rate_limit: `Action "${action}" was rate-limited after ${attempts} attempt(s). Consider backing off or checking your quota.`,
network: `Action "${action}" encountered a network error after ${attempts} attempt(s). The service may be unreachable or experiencing connectivity issues.`,
model: `Action "${action}" failed due to an AI model error after ${attempts} attempt(s). The model may be overloaded or returned an unexpected response.`,
validation: `Action "${action}" failed a validation check after ${attempts} attempt(s). The input data or response format may be invalid.`,
unknown: `Action "${action}" failed after ${attempts} attempt(s) with an unknown error. Check the logs for more details.`
};
return messages[category];
}
+131
View File
@@ -0,0 +1,131 @@
/**
* MetricsCollector — 纯内存指标累加器。
* 用于 CI Actions 模式,提供 snapshot 和 markdown 序列化。
* 与 webhook 的 MetricsRegistry(Prometheus 格式)互补,面向人类可读输出。
*/
export class MetricsCollector {
private reviewCount = 0;
private reviewDurationTotalMs = 0;
private reviewOutcomes: Record<string, number> = {};
private gooseCallCount = 0;
private gooseCallDurationMs = 0;
private gooseSuccessCount = 0;
private gooseFailureCount = 0;
private conflictStatuses: Record<string, number> = {};
private mergeStatuses: Record<string, number> = {};
private cacheHits: Record<string, number> = {};
private startedAt = Date.now();
recordReviewDuration(ms: number): void {
this.reviewCount++;
this.reviewDurationTotalMs += ms;
}
recordReviewResult(outcome: "pass" | "block" | "malicious"): void {
this.reviewOutcomes[outcome] = (this.reviewOutcomes[outcome] ?? 0) + 1;
}
recordGooseCall(durationMs: number, success: boolean): void {
this.gooseCallCount++;
this.gooseCallDurationMs += durationMs;
if (success) {
this.gooseSuccessCount++;
} else {
this.gooseFailureCount++;
}
}
recordConflictResolution(status: "resolved" | "failed" | "skipped"): void {
this.conflictStatuses[status] = (this.conflictStatuses[status] ?? 0) + 1;
}
recordMergeAttempt(status: "merged" | "already_merged" | "failed"): void {
this.mergeStatuses[status] = (this.mergeStatuses[status] ?? 0) + 1;
}
recordCacheHit(type: "review" | "knowledge"): void {
this.cacheHits[type] = (this.cacheHits[type] ?? 0) + 1;
}
snapshot(): Record<string, unknown> {
return {
uptimeSeconds: Math.round((Date.now() - this.startedAt) / 1000),
reviewCount: this.reviewCount,
reviewDurationTotalMs: this.reviewDurationTotalMs,
reviewDurationAvgMs:
this.reviewCount > 0 ? Math.round(this.reviewDurationTotalMs / this.reviewCount) : 0,
reviewOutcomes: { ...this.reviewOutcomes },
gooseCallCount: this.gooseCallCount,
gooseCallDurationTotalMs: this.gooseCallDurationMs,
gooseCallAvgMs:
this.gooseCallCount > 0 ? Math.round(this.gooseCallDurationMs / this.gooseCallCount) : 0,
gooseSuccessCount: this.gooseSuccessCount,
gooseFailureCount: this.gooseFailureCount,
conflictStatuses: { ...this.conflictStatuses },
mergeStatuses: { ...this.mergeStatuses },
cacheHits: { ...this.cacheHits }
};
}
formatMarkdown(): string {
const s = this.snapshot();
const lines: string[] = [
"## Metrics Summary",
"",
"| Metric | Value |",
"|--------|-------|",
`| Uptime | ${s.uptimeSeconds}s |`,
`| Reviews | ${s.reviewCount} |`,
`| Review Duration (total) | ${s.reviewDurationTotalMs}ms |`,
`| Review Duration (avg) | ${s.reviewDurationAvgMs}ms |`
];
const outcomes = s.reviewOutcomes as Record<string, number>;
for (const [outcome, count] of Object.entries(outcomes).sort()) {
lines.push(`| Review Outcome: ${outcome} | ${count} |`);
}
lines.push(
`| Goose Calls | ${s.gooseCallCount} |`,
`| Goose Call Duration (total) | ${s.gooseCallDurationTotalMs}ms |`,
`| Goose Call Duration (avg) | ${s.gooseCallAvgMs}ms |`,
`| Goose Success | ${s.gooseSuccessCount} |`,
`| Goose Failure | ${s.gooseFailureCount} |`
);
const conflicts = s.conflictStatuses as Record<string, number>;
for (const [status, count] of Object.entries(conflicts).sort()) {
lines.push(`| Conflict: ${status} | ${count} |`);
}
const merges = s.mergeStatuses as Record<string, number>;
for (const [status, count] of Object.entries(merges).sort()) {
lines.push(`| Merge: ${status} | ${count} |`);
}
const cache = s.cacheHits as Record<string, number>;
for (const [type, count] of Object.entries(cache).sort()) {
lines.push(`| Cache Hit: ${type} | ${count} |`);
}
return `${lines.join("\n")}\n`;
}
reset(): void {
this.reviewCount = 0;
this.reviewDurationTotalMs = 0;
this.reviewOutcomes = {};
this.gooseCallCount = 0;
this.gooseCallDurationMs = 0;
this.gooseSuccessCount = 0;
this.gooseFailureCount = 0;
this.conflictStatuses = {};
this.mergeStatuses = {};
this.cacheHits = {};
this.startedAt = Date.now();
}
}
export const metrics = new MetricsCollector();
+7 -1
View File
@@ -74,8 +74,14 @@ export function validateRepositoryKnowledge(content: string): void {
} }
} }
/**
* Normalize repository knowledge to a stable LF line-ending form so a
* knowledge round trip through git checkouts, editors, or the agent
* scratch directory is byte-identical on every platform.
*/
export function normalizeKnowledge(content: string): string { export function normalizeKnowledge(content: string): string {
return `${content.trim()}\n`; const normalized = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").trim();
return `${normalized}\n`;
} }
function isNotFoundError(error: unknown): boolean { function isNotFoundError(error: unknown): boolean {
+20 -3
View File
@@ -47,10 +47,15 @@ export async function withRetry<T>(
options?: { options?: {
maxAttempts?: number; maxAttempts?: number;
baseDelayMs?: number; baseDelayMs?: number;
retryable?: (error: unknown) => boolean;
maxTotalTimeoutMs?: number;
} }
): Promise<T> { ): Promise<T> {
const maxAttempts = options?.maxAttempts ?? MAX_ATTEMPTS; const maxAttempts = options?.maxAttempts ?? MAX_ATTEMPTS;
const baseDelayMs = options?.baseDelayMs ?? BASE_DELAY_MS; const baseDelayMs = options?.baseDelayMs ?? BASE_DELAY_MS;
const retryableCheck = options?.retryable ?? isRetryableError;
const maxTotalTimeoutMs = options?.maxTotalTimeoutMs;
const startTime = Date.now();
let lastError: unknown; let lastError: unknown;
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
@@ -59,22 +64,34 @@ export async function withRetry<T>(
} catch (error) { } catch (error) {
lastError = error; lastError = error;
if (maxTotalTimeoutMs !== undefined) {
const elapsed = Date.now() - startTime;
if (elapsed >= maxTotalTimeoutMs) {
logger.warn(
{ error, label, attempt, maxAttempts, elapsed, maxTotalTimeoutMs },
"Request failed; maxTotalTimeout exceeded."
);
break;
}
}
logger.warn( logger.warn(
{ {
error, error,
label, label,
attempt, attempt,
maxAttempts, maxAttempts,
retryable: isRetryableError(error) retryable: retryableCheck(error)
}, },
"Request failed." "Request failed."
); );
if (attempt === maxAttempts || !isRetryableError(error)) { if (attempt === maxAttempts || !retryableCheck(error)) {
break; break;
} }
await delay(baseDelayMs * attempt); const jitter = 0.5 + Math.random() * 0.5;
await delay(baseDelayMs * attempt * jitter);
} }
} }
+9 -1
View File
@@ -26,7 +26,15 @@ const reviewDecisionSchema = z.object({
}) })
}); });
type PromptRunner = (prompt: string, options?: { timeoutMs?: number }) => Promise<string>;
export class GooseReviewer { export class GooseReviewer {
private readonly promptRunner: PromptRunner;
constructor(promptRunner: PromptRunner = runGoosePrompt) {
this.promptRunner = promptRunner;
}
async review(input: { async review(input: {
title: string; title: string;
body: string | null; body: string | null;
@@ -38,7 +46,7 @@ export class GooseReviewer {
return withRetry( return withRetry(
"goose.run.review", "goose.run.review",
async () => { async () => {
const raw = await runGoosePrompt(buildPrompt(input)); const raw = await this.promptRunner(buildPrompt(input));
const parsed = reviewDecisionSchema.parse(JSON.parse(raw)); const parsed = reviewDecisionSchema.parse(JSON.parse(raw));
const { decision, warnings } = normalizeReviewDecision( const { decision, warnings } = normalizeReviewDecision(
parsed, parsed,
+46
View File
@@ -0,0 +1,46 @@
/**
* MergeGuard prevents duplicate merge attempts by tracking recently-attempted
* PR merge operations in memory. It is not persisted across restarts.
*/
export class MergeGuard {
#attempted = new Set<string>();
#recentAttempts: string[] = [];
/**
* Build a stable key for a PR.
*/
static #key(owner: string, repo: string, pullNumber: number): string {
return `${owner}/${repo}#${pullNumber}`;
}
/**
* Returns true if a merge has already been attempted for this PR.
*/
isAlreadyAttempted(owner: string, repo: string, pullNumber: number): boolean {
return this.#attempted.has(MergeGuard.#key(owner, repo, pullNumber));
}
/**
* Record a merge attempt for the given PR.
*/
markAttempt(owner: string, repo: string, pullNumber: number): void {
const key = MergeGuard.#key(owner, repo, pullNumber);
this.#attempted.add(key);
this.#recentAttempts.push(key);
}
/**
* Returns the total number of recorded merge attempts across all PRs.
*/
getAttemptedCount(): number {
return this.#recentAttempts.length;
}
/**
* Returns the list of recently-attempted PR keys, in the order they were
* first attempted.
*/
getRecentAttempts(): string[] {
return [...this.#recentAttempts];
}
}
+2 -2
View File
@@ -1070,7 +1070,7 @@ function reviewProgressMarker(headSha: string): string {
return `${REVIEW_PROGRESS_MARKER_PREFIX} head=${headSha} -->`; return `${REVIEW_PROGRESS_MARKER_PREFIX} head=${headSha} -->`;
} }
function shortSha(headSha: string): string { export function shortSha(headSha: string): string {
return headSha.slice(0, 12); return headSha.slice(0, 12);
} }
@@ -1716,7 +1716,7 @@ function extractReviewStateMarker(body: string | null | undefined): string {
); );
} }
function shouldFallbackToCommentReview( export function shouldFallbackToCommentReview(
error: unknown, error: unknown,
event: "APPROVE" | "COMMENT" | "REQUEST_CHANGES" event: "APPROVE" | "COMMENT" | "REQUEST_CHANGES"
): boolean { ): boolean {
+2 -2
View File
@@ -465,7 +465,7 @@ export function buildPullRequestDuplicatePrompt(params: {
].join("\n"); ].join("\n");
} }
function buildTriagePrompt( export function buildTriagePrompt(
kind: TriageKind, kind: TriageKind,
target: TriageTarget, target: TriageTarget,
candidates: TriageCandidate[] candidates: TriageCandidate[]
@@ -571,6 +571,6 @@ async function postDuplicateFeedback(
}); });
} }
function labelName(label: string | { name?: string | null }): string { export function labelName(label: string | { name?: string | null }): string {
return typeof label === "string" ? label : (label.name ?? ""); return typeof label === "string" ? label : (label.name ?? "");
} }
+255
View File
@@ -0,0 +1,255 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
acquireConflictLock,
canAutoResolveConflicts,
describeConflictResolutionFailure
} from "../src/review/conflictResolver.js";
const eligible = {
enabled: true,
reviewPassed: true,
mergeable: false,
mergeableState: "dirty",
baseRepository: "forumlify/public",
headRepository: "forumlify/public",
maintainerCanModify: false,
expectedHeadSha: "abc",
currentHeadSha: "abc"
} as const;
// ---------------------------------------------------------------------------
// canAutoResolveConflicts — remaining condition combinations
// ---------------------------------------------------------------------------
test("canAutoResolveConflicts: enabled=false returns false", () => {
assert.equal(canAutoResolveConflicts({ ...eligible, enabled: false }), false);
});
test("canAutoResolveConflicts: reviewPassed=false returns false", () => {
assert.equal(canAutoResolveConflicts({ ...eligible, reviewPassed: false }), false);
});
test("canAutoResolveConflicts: mergeable=null returns false", () => {
assert.equal(canAutoResolveConflicts({ ...eligible, mergeable: null }), false);
});
test("canAutoResolveConflicts: mergeable=true (non-dirty) returns false", () => {
assert.equal(
canAutoResolveConflicts({ ...eligible, mergeable: true, mergeableState: "clean" }),
false
);
});
test("canAutoResolveConflicts: mergeableState is not 'dirty' returns false", () => {
assert.equal(canAutoResolveConflicts({ ...eligible, mergeableState: "clean" }), false);
assert.equal(canAutoResolveConflicts({ ...eligible, mergeableState: "blocked" }), false);
assert.equal(canAutoResolveConflicts({ ...eligible, mergeableState: "unknown" }), false);
assert.equal(canAutoResolveConflicts({ ...eligible, mergeableState: "behind" }), false);
});
test("canAutoResolveConflicts: headRepository=null returns false", () => {
assert.equal(canAutoResolveConflicts({ ...eligible, headRepository: null }), false);
});
test("canAutoResolveConflicts: fork without maintainerCanModify returns false", () => {
assert.equal(
canAutoResolveConflicts({
...eligible,
headRepository: "contributor/forumlify",
maintainerCanModify: false
}),
false
);
});
test("canAutoResolveConflicts: fork with maintainerCanModify returns true", () => {
assert.equal(
canAutoResolveConflicts({
...eligible,
headRepository: "contributor/forumlify",
maintainerCanModify: true
}),
true
);
});
test("canAutoResolveConflicts: headSha mismatch returns false", () => {
assert.equal(canAutoResolveConflicts({ ...eligible, currentHeadSha: "different-sha" }), false);
});
test("canAutoResolveConflicts: all conditions met returns true", () => {
assert.equal(canAutoResolveConflicts(eligible), true);
});
// ---------------------------------------------------------------------------
// acquireConflictLock — lock acquisition, duplicate rejection, release
// ---------------------------------------------------------------------------
test("acquireConflictLock: acquires a lock", async () => {
const release = await acquireConflictLock("test/lock-single");
assert.equal(typeof release, "function");
release();
});
test("acquireConflictLock: throws for duplicate lock", async () => {
const release = await acquireConflictLock("test/lock-duplicate");
await assert.rejects(
() => acquireConflictLock("test/lock-duplicate"),
/already active for this pull request/
);
release();
});
test("acquireConflictLock: release function works and allows re-acquisition", async () => {
const release = await acquireConflictLock("test/lock-reacquire");
release();
const releaseAgain = await acquireConflictLock("test/lock-reacquire");
releaseAgain();
});
test("acquireConflictLock: concurrent keys do not interfere", async () => {
const releaseA = await acquireConflictLock("test/lock-concurrent-a");
const releaseB = await acquireConflictLock("test/lock-concurrent-b");
releaseA();
releaseB();
});
test("acquireConflictLock: double release does not throw", async () => {
const release = await acquireConflictLock("test/lock-double-release");
release();
release();
});
// ---------------------------------------------------------------------------
// describeConflictResolutionFailure — remaining error types
// ---------------------------------------------------------------------------
test("describeConflictResolutionFailure: shallow git history", () => {
const msg = describeConflictResolutionFailure(
new Error("fatal: refusing to merge unrelated histories (shallow)")
);
assert.match(msg, /did not contain enough Git history/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: authentication failed", () => {
const msg = describeConflictResolutionFailure(new Error("remote: authentication failed"));
assert.match(msg, /Allow edits from maintainers/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: write access to repository not granted", () => {
const msg = describeConflictResolutionFailure(
new Error("remote: Write access to repository not granted: contributor/forumlify")
);
assert.match(msg, /Allow edits from maintainers/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: permission denied", () => {
const msg = describeConflictResolutionFailure(
new Error("remote: Permission denied to fork repository")
);
assert.match(msg, /Allow edits from maintainers/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: status code 403", () => {
const msg = describeConflictResolutionFailure(new Error("HTTP status code: 403 forbidden"));
assert.match(msg, /Allow edits from maintainers/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: non-fast-forward push", () => {
const msg = describeConflictResolutionFailure(
new Error("! [rejected] HEAD -> main (non-fast-forward)")
);
assert.match(msg, /Run \/conflict again/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: fetch first (stale remote)", () => {
const msg = describeConflictResolutionFailure(
new Error("! [rejected] (stale info) - fetch first")
);
assert.match(msg, /Run \/conflict again/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: final goose confirmation did not return valid JSON", () => {
const msg = describeConflictResolutionFailure(
new Error("Final goose confirmation did not return the required JSON object.")
);
assert.match(msg, /invalid result/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: resolved staged diff exceeds MAX_PATCH_CHARS", () => {
const msg = describeConflictResolutionFailure(
new Error("Resolved staged diff contains 200000 characters, exceeding MAX_PATCH_CHARS=120000.")
);
assert.match(msg, /patch-size limit/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: conflict validation infrastructure failed", () => {
const msg = describeConflictResolutionFailure(
new Error("Conflict validation infrastructure failed: docker daemon not available")
);
assert.match(msg, /validation environment failed/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: isolated conflict validation timed out", () => {
const msg = describeConflictResolutionFailure(
new Error("isolated conflict validation timed out.")
);
assert.match(msg, /7-minute limit/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: generic error falls through to safe default", () => {
const msg = describeConflictResolutionFailure(new Error("unexpected runtime error"));
assert.match(msg, /could not safely complete/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: generic error with actor name", () => {
const msg = describeConflictResolutionFailure(
new Error("integration test 1 failed"),
"custom-bot"
);
assert.match(msg, /^custom-bot could not safely complete/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: empty ident name", () => {
const msg = describeConflictResolutionFailure(
new Error("empty ident name (no email address) not allowed")
);
assert.match(msg, /no bot committer identity/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: non-Error input is handled", () => {
const msg = describeConflictResolutionFailure("something went wrong");
assert.match(msg, /could not safely complete/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: null input is handled", () => {
const msg = describeConflictResolutionFailure(null);
assert.match(msg, /could not safely complete/);
assert.match(msg, /no commit was pushed/i);
});
test("describeConflictResolutionFailure: validation command failure with actor name", () => {
const msg = describeConflictResolutionFailure(
new Error("Validation command failed after goose correction: exit 1"),
"test-bot"
);
assert.match(msg, /^test-bot produced/);
assert.match(msg, /validation or final safety confirmation rejected/);
assert.match(msg, /no commit was pushed/i);
});
+137
View File
@@ -0,0 +1,137 @@
import assert from "node:assert/strict";
import test from "node:test";
import { categorizeFailure, formatFailureMessage } from "../src/ai/failureMessages.js";
/* ---------- categorizeFailure ---------- */
test("categorizeFailure: timeout by error code", () => {
const err = Object.assign(new Error("timed out"), { code: "ETIMEDOUT" });
assert.equal(categorizeFailure(err), "timeout");
});
test("categorizeFailure: timeout by message", () => {
const err = new Error("the operation timed out after 30s");
assert.equal(categorizeFailure(err), "timeout");
});
test("categorizeFailure: auth by status code 401", () => {
const err = Object.assign(new Error("unauthorized"), { status: 401 });
assert.equal(categorizeFailure(err), "auth");
});
test("categorizeFailure: auth by status code 403", () => {
const err = Object.assign(new Error("forbidden"), { status: 403 });
assert.equal(categorizeFailure(err), "auth");
});
test("categorizeFailure: auth by message", () => {
const err = new Error("API key is invalid");
assert.equal(categorizeFailure(err), "auth");
});
test("categorizeFailure: rate_limit by status code 429", () => {
const err = Object.assign(new Error("too many"), { status: 429 });
assert.equal(categorizeFailure(err), "rate_limit");
});
test("categorizeFailure: rate_limit by message", () => {
const err = new Error("rate limit exceeded, retry later");
assert.equal(categorizeFailure(err), "rate_limit");
});
test("categorizeFailure: network by error code ECONNRESET", () => {
const err = Object.assign(new Error("socket hang up"), { code: "ECONNRESET" });
assert.equal(categorizeFailure(err), "network");
});
test("categorizeFailure: network by error code ECONNREFUSED", () => {
const err = Object.assign(new Error("refused"), { code: "ECONNREFUSED" });
assert.equal(categorizeFailure(err), "network");
});
test("categorizeFailure: network by error code EAI_AGAIN", () => {
const err = Object.assign(new Error("again"), { code: "EAI_AGAIN" });
assert.equal(categorizeFailure(err), "network");
});
test("categorizeFailure: network by message", () => {
const err = new Error("network error: unable to reach host");
assert.equal(categorizeFailure(err), "network");
});
test("categorizeFailure: model by status 502", () => {
const err = Object.assign(new Error("upstream error"), { status: 502 });
assert.equal(categorizeFailure(err), "model");
});
test("categorizeFailure: model by message", () => {
const err = new Error("model completion failed: context length exceeded");
assert.equal(categorizeFailure(err), "model");
});
test("categorizeFailure: validation by status 422", () => {
const err = Object.assign(new Error("invalid"), { status: 422 });
assert.equal(categorizeFailure(err), "validation");
});
test("categorizeFailure: validation by message", () => {
const err = new Error("validation error: invalid schema");
assert.equal(categorizeFailure(err), "validation");
});
test("categorizeFailure: null input returns unknown", () => {
assert.equal(categorizeFailure(null), "unknown");
});
test("categorizeFailure: string input returns unknown", () => {
assert.equal(categorizeFailure("some error"), "unknown");
});
test("categorizeFailure: plain error with no recognizable pattern returns unknown", () => {
const err = new Error("something unexpected happened");
assert.equal(categorizeFailure(err), "unknown");
});
/* ---------- formatFailureMessage ---------- */
test("formatFailureMessage: timeout includes action and attempts", () => {
const msg = formatFailureMessage("timeout", { action: "runReview", attempts: 3 });
assert.ok(msg.includes("runReview"));
assert.ok(msg.includes("3"));
assert.ok(msg.includes("timed out"));
});
test("formatFailureMessage: auth includes action and attempts", () => {
const msg = formatFailureMessage("auth", { action: "createComment", attempts: 2 });
assert.ok(msg.includes("createComment"));
assert.ok(msg.includes("2"));
assert.ok(msg.includes("authentication error"));
});
test("formatFailureMessage: rate_limit mentions backing off", () => {
const msg = formatFailureMessage("rate_limit", { action: "listReviews", attempts: 5 });
assert.ok(msg.includes("rate-limited"));
assert.ok(msg.includes("backing off"));
});
test("formatFailureMessage: network mentions service unreachable", () => {
const msg = formatFailureMessage("network", { action: "fetchData", attempts: 1 });
assert.ok(msg.includes("network error"));
assert.ok(msg.includes("unreachable"));
});
test("formatFailureMessage: model mentions model error", () => {
const msg = formatFailureMessage("model", { action: "runReview", attempts: 3 });
assert.ok(msg.includes("model error"));
});
test("formatFailureMessage: validation mentions validation check", () => {
const msg = formatFailureMessage("validation", { action: "parseResponse", attempts: 2 });
assert.ok(msg.includes("validation check"));
});
test("formatFailureMessage: unknown mentions unknown error", () => {
const msg = formatFailureMessage("unknown", { action: "someAction", attempts: 4 });
assert.ok(msg.includes("unknown error"));
assert.ok(msg.includes("Check the logs") || msg.includes("check the logs"));
});
+202
View File
@@ -0,0 +1,202 @@
import assert from "node:assert/strict";
import test from "node:test";
import { GooseReviewer } from "../src/review/gooseReviewer.js";
import type { PullRequestFile, ReviewMode } from "../src/types.js";
import type { PreviousReview } from "../src/review/cache.js";
const validReviewDecision = {
review: [],
change: [],
comment: "Looks good.",
result: {
canMerge: true,
summary: "Safe to merge.",
shouldClosePullRequest: false,
closeReason: ""
}
};
const mockFiles: PullRequestFile[] = [
{
filename: "src/index.ts",
patch: "+export const foo = 1;",
status: "modified",
additions: 1,
deletions: 0
}
];
const baseInput = {
title: "Add foo constant",
body: "Adds a simple constant.",
files: mockFiles,
mode: "normal" as ReviewMode
};
// Helper: create a GooseReviewer that records the prompt and returns a controlled value
function createReviewer(
response: unknown = validReviewDecision,
onPrompt?: (prompt: string) => void
): GooseReviewer {
const promptRunner = async (prompt: string) => {
onPrompt?.(prompt);
const value = response;
if (value instanceof Error) {
throw value;
}
return typeof value === "function" ? value(prompt) : JSON.stringify(value);
};
return new GooseReviewer(promptRunner);
}
// 1. review() with valid input returns ReviewDecision
test("review() with valid input returns ReviewDecision", async () => {
const reviewer = createReviewer();
const decision = await reviewer.review(baseInput);
assert.equal(decision.result.canMerge, true);
assert.equal(decision.comment, "Looks good.");
assert.deepEqual(decision.review, []);
assert.deepEqual(decision.change, []);
assert.equal(decision.result.summary, "Safe to merge.");
assert.equal(decision.result.shouldClosePullRequest, false);
assert.equal(decision.result.closeReason, "");
});
// 2. review() with previousReview context includes it in the prompt
test("review() with previousReview context includes it in the prompt", async () => {
let capturedPrompt = "";
const previousReview: PreviousReview = {
headSha: "a".repeat(40),
reviewedAt: "2026-08-13T00:00:00.000Z",
decision: validReviewDecision
};
const reviewer = createReviewer(validReviewDecision, (p) => {
capturedPrompt = p;
});
await reviewer.review({ ...baseInput, previousReview });
assert.ok(capturedPrompt.includes("Previous review context"));
assert.ok(capturedPrompt.includes(previousReview.headSha));
assert.ok(capturedPrompt.includes("Re-evaluate every previous finding"));
});
// 3. review() with repositoryKnowledge includes it in the prompt
test("review() with repositoryKnowledge includes it in the prompt", async () => {
let capturedPrompt = "";
const knowledge = "This repository uses React 18 and follows atomic design principles.";
const reviewer = createReviewer(validReviewDecision, (p) => {
capturedPrompt = p;
});
await reviewer.review({ ...baseInput, repositoryKnowledge: knowledge });
assert.ok(capturedPrompt.includes("repository-scoped private object storage"));
assert.ok(capturedPrompt.includes(knowledge));
assert.ok(capturedPrompt.includes("Trusted repository knowledge"));
});
// 4. review() with strict mode uses strict prompt
test("review() with strict mode captures the strict review instructions", async () => {
let capturedPrompt = "";
const reviewer = createReviewer(validReviewDecision, (p) => {
capturedPrompt = p;
});
await reviewer.review({ ...baseInput, mode: "strict" });
assert.ok(capturedPrompt.includes("strict review explicitly requested"));
assert.ok(capturedPrompt.includes("This is a strict review"));
});
// 5. buildPrompt() output contains PR title and files
test("review() prompt contains PR title and file metadata", async () => {
let capturedPrompt = "";
const reviewer = createReviewer(validReviewDecision, (p) => {
capturedPrompt = p;
});
await reviewer.review(baseInput);
assert.ok(capturedPrompt.includes("Add foo constant"));
assert.ok(capturedPrompt.includes("src/index.ts"));
assert.ok(capturedPrompt.includes("+export const foo = 1;"));
assert.ok(capturedPrompt.includes("modified"));
assert.ok(capturedPrompt.includes("Pull request payload"));
});
// 6. buildPrompt() contains output contract instructions
test("review() prompt contains output contract instructions", async () => {
let capturedPrompt = "";
const reviewer = createReviewer(validReviewDecision, (p) => {
capturedPrompt = p;
});
await reviewer.review(baseInput);
assert.ok(capturedPrompt.includes("four top-level keys"));
assert.ok(capturedPrompt.includes("review, change, comment, result"));
assert.ok(capturedPrompt.includes("path, line, title, body"));
assert.ok(capturedPrompt.includes("canMerge, summary, shouldClosePullRequest, closeReason"));
assert.ok(capturedPrompt.includes("only one valid JSON object"));
});
// 7. buildPrompt() with previousReview contains previous review JSON
test("review() prompt with previousReview contains serialized previous review", async () => {
let capturedPrompt = "";
const previousReview: PreviousReview = {
headSha: "abc123def456".repeat(4),
reviewedAt: "2026-08-13T00:00:00.000Z",
decision: validReviewDecision
};
const reviewer = createReviewer(validReviewDecision, (p) => {
capturedPrompt = p;
});
await reviewer.review({ ...baseInput, previousReview });
assert.ok(capturedPrompt.includes(previousReview.headSha));
assert.ok(capturedPrompt.includes(previousReview.reviewedAt));
assert.ok(capturedPrompt.includes("Previous review context"));
});
// 8. System prompt for normal mode is not strict
test("normal mode prompt does not contain strict review text", async () => {
let capturedPrompt = "";
const reviewer = createReviewer(validReviewDecision, (p) => {
capturedPrompt = p;
});
await reviewer.review(baseInput);
assert.ok(capturedPrompt.includes("normal review"));
assert.ok(capturedPrompt.includes("Do not nitpick or pursue minor details"));
assert.ok(!capturedPrompt.includes("strict review"));
});
// 9. System prompt for strict mode includes "strict review"
test("strict mode prompt includes strict review admonition", async () => {
let capturedPrompt = "";
const reviewer = createReviewer(validReviewDecision, (p) => {
capturedPrompt = p;
});
await reviewer.review({ ...baseInput, mode: "strict" });
assert.ok(
capturedPrompt.includes("strict review explicitly requested by the repository administrators")
);
assert.ok(!capturedPrompt.includes("Do not nitpick or pursue minor details"));
});
// 10. Schema validation: invalid JSON from goose throws
test("invalid JSON from goose throws a non-retryable error", async () => {
const reviewer = createReviewer(() => "not valid json {{{");
await assert.rejects(
() => reviewer.review(baseInput),
/Unexpected token|not valid JSON|JSON\.parse|SyntaxError/
);
});
// 11. Schema validation: missing required fields throws
test("missing required fields in goose output throws a Zod validation error", async () => {
const reviewer = createReviewer({ incomplete: true });
await assert.rejects(() => reviewer.review(baseInput), /review|Required|change|comment|result/);
});
+46
View File
@@ -0,0 +1,46 @@
import assert from "node:assert/strict";
import test from "node:test";
import { MergeGuard } from "../src/review/merge-guard.js";
test("markAttempt followed by isAlreadyAttempted returns true", () => {
const guard = new MergeGuard();
guard.markAttempt("owner1", "repo1", 42);
assert.equal(guard.isAlreadyAttempted("owner1", "repo1", 42), true);
});
test("isAlreadyAttempted returns false for a never-attempted PR", () => {
const guard = new MergeGuard();
assert.equal(guard.isAlreadyAttempted("owner1", "repo1", 99), false);
});
test("getRecentAttempts returns list of attempted PR keys", () => {
const guard = new MergeGuard();
guard.markAttempt("a", "repo-a", 1);
guard.markAttempt("b", "repo-b", 2);
const attempts = guard.getRecentAttempts();
assert.equal(attempts.length, 2);
assert.ok(attempts.includes("a/repo-a#1"));
assert.ok(attempts.includes("b/repo-b#2"));
});
test("multiple attempts on the same PR increment count", () => {
const guard = new MergeGuard();
guard.markAttempt("same", "pr", 1);
guard.markAttempt("same", "pr", 1);
guard.markAttempt("same", "pr", 1);
assert.equal(guard.getAttemptedCount(), 3);
assert.equal(guard.isAlreadyAttempted("same", "pr", 1), true);
});
test("different PRs are tracked independently", () => {
const guard = new MergeGuard();
guard.markAttempt("owner1", "repo1", 10);
guard.markAttempt("owner2", "repo2", 20);
assert.equal(guard.isAlreadyAttempted("owner1", "repo1", 10), true);
assert.equal(guard.isAlreadyAttempted("owner1", "repo1", 11), false);
assert.equal(guard.isAlreadyAttempted("owner2", "repo2", 20), true);
assert.equal(guard.isAlreadyAttempted("owner2", "repo2", 21), false);
assert.equal(guard.getAttemptedCount(), 2);
});
+185
View File
@@ -0,0 +1,185 @@
import assert from "node:assert/strict";
import test from "node:test";
import { MetricsCollector, metrics } from "../src/metrics/collector.js";
test("recordReviewDuration increments count", () => {
const mc = new MetricsCollector();
mc.recordReviewDuration(150);
mc.recordReviewDuration(250);
const s = mc.snapshot();
assert.equal(s.reviewCount, 2);
assert.equal(s.reviewDurationTotalMs, 400);
assert.equal(s.reviewDurationAvgMs, 200);
});
test("recordReviewResult tracks outcome counts", () => {
const mc = new MetricsCollector();
mc.recordReviewResult("pass");
mc.recordReviewResult("pass");
mc.recordReviewResult("block");
mc.recordReviewResult("malicious");
const s = mc.snapshot();
const outcomes = s.reviewOutcomes as Record<string, number>;
assert.equal(outcomes.pass, 2);
assert.equal(outcomes.block, 1);
assert.equal(outcomes.malicious, 1);
});
test("recordGooseCall tracks success/failure counts", () => {
const mc = new MetricsCollector();
mc.recordGooseCall(100, true);
mc.recordGooseCall(200, true);
mc.recordGooseCall(300, false);
const s = mc.snapshot();
assert.equal(s.gooseCallCount, 3);
assert.equal(s.gooseCallDurationTotalMs, 600);
assert.equal(s.gooseCallAvgMs, 200);
assert.equal(s.gooseSuccessCount, 2);
assert.equal(s.gooseFailureCount, 1);
});
test("recordConflictResolution tracks status counts", () => {
const mc = new MetricsCollector();
mc.recordConflictResolution("resolved");
mc.recordConflictResolution("resolved");
mc.recordConflictResolution("failed");
mc.recordConflictResolution("skipped");
const s = mc.snapshot();
const conflicts = s.conflictStatuses as Record<string, number>;
assert.equal(conflicts.resolved, 2);
assert.equal(conflicts.failed, 1);
assert.equal(conflicts.skipped, 1);
});
test("recordMergeAttempt tracks merge counts", () => {
const mc = new MetricsCollector();
mc.recordMergeAttempt("merged");
mc.recordMergeAttempt("already_merged");
mc.recordMergeAttempt("failed");
const s = mc.snapshot();
const merges = s.mergeStatuses as Record<string, number>;
assert.equal(merges.merged, 1);
assert.equal(merges.already_merged, 1);
assert.equal(merges.failed, 1);
});
test("recordCacheHit tracks cache hits", () => {
const mc = new MetricsCollector();
mc.recordCacheHit("review");
mc.recordCacheHit("review");
mc.recordCacheHit("knowledge");
const s = mc.snapshot();
const cache = s.cacheHits as Record<string, number>;
assert.equal(cache.review, 2);
assert.equal(cache.knowledge, 1);
});
test("snapshot returns all metrics", () => {
const mc = new MetricsCollector();
mc.recordReviewDuration(500);
mc.recordReviewResult("pass");
mc.recordGooseCall(1000, true);
mc.recordConflictResolution("resolved");
mc.recordMergeAttempt("merged");
mc.recordCacheHit("review");
const s = mc.snapshot();
assert.ok(typeof s.uptimeSeconds === "number");
assert.equal(s.reviewCount, 1);
assert.equal(s.reviewDurationTotalMs, 500);
assert.equal(s.reviewDurationAvgMs, 500);
assert.deepEqual(s.reviewOutcomes, { pass: 1 });
assert.equal(s.gooseCallCount, 1);
assert.equal(s.gooseCallDurationTotalMs, 1000);
assert.equal(s.gooseCallAvgMs, 1000);
assert.equal(s.gooseSuccessCount, 1);
assert.equal(s.gooseFailureCount, 0);
assert.deepEqual(s.conflictStatuses, { resolved: 1 });
assert.deepEqual(s.mergeStatuses, { merged: 1 });
assert.deepEqual(s.cacheHits, { review: 1 });
});
test("formatMarkdown generates table with headers", () => {
const mc = new MetricsCollector();
mc.recordReviewDuration(300);
mc.recordReviewResult("pass");
mc.recordGooseCall(500, true);
mc.recordConflictResolution("resolved");
mc.recordMergeAttempt("merged");
mc.recordCacheHit("review");
const md = mc.formatMarkdown();
assert.match(md, /## Metrics Summary/);
assert.match(md, /\| Metric \| Value \|/);
assert.match(md, /\| Reviews \| 1 \|/);
assert.match(md, /\| Review Outcome: pass \| 1 \|/);
assert.match(md, /\| Goose Calls \| 1 \|/);
assert.match(md, /\| Goose Success \| 1 \|/);
assert.match(md, /\| Conflict: resolved \| 1 \|/);
assert.match(md, /\| Merge: merged \| 1 \|/);
assert.match(md, /\| Cache Hit: review \| 1 \|/);
});
test("reset clears all metrics", () => {
const mc = new MetricsCollector();
mc.recordReviewDuration(100);
mc.recordReviewResult("pass");
mc.recordGooseCall(200, false);
mc.recordConflictResolution("failed");
mc.recordMergeAttempt("failed");
mc.recordCacheHit("knowledge");
mc.reset();
const s = mc.snapshot();
assert.equal(s.reviewCount, 0);
assert.equal(s.reviewDurationTotalMs, 0);
assert.equal(s.reviewDurationAvgMs, 0);
assert.deepEqual(s.reviewOutcomes, {});
assert.equal(s.gooseCallCount, 0);
assert.equal(s.gooseCallDurationTotalMs, 0);
assert.equal(s.gooseCallAvgMs, 0);
assert.equal(s.gooseSuccessCount, 0);
assert.equal(s.gooseFailureCount, 0);
assert.deepEqual(s.conflictStatuses, {});
assert.deepEqual(s.mergeStatuses, {});
assert.deepEqual(s.cacheHits, {});
});
test("Multiple calls accumulate correctly", () => {
const mc = new MetricsCollector();
for (let i = 0; i < 10; i++) {
mc.recordReviewDuration(100);
mc.recordReviewResult("pass");
mc.recordGooseCall(200, i % 3 !== 0);
mc.recordConflictResolution(i < 5 ? "resolved" : "failed");
mc.recordMergeAttempt(i < 7 ? "merged" : "failed");
mc.recordCacheHit(i < 6 ? "review" : "knowledge");
}
const s = mc.snapshot();
assert.equal(s.reviewCount, 10);
assert.equal(s.reviewDurationTotalMs, 1000);
assert.equal(s.reviewDurationAvgMs, 100);
assert.equal(s.gooseCallCount, 10);
assert.equal(s.gooseCallDurationTotalMs, 2000);
assert.equal(s.gooseCallAvgMs, 200);
// 10 calls; i%3===0 fails (indices 0,3,6,9 = 4), rest succeed (indices 1,2,4,5,7,8 = 6)
assert.equal(s.gooseSuccessCount, 6);
assert.equal(s.gooseFailureCount, 4);
// i < 5 resolved, rest failed
const conflicts = s.conflictStatuses as Record<string, number>;
assert.equal(conflicts.resolved, 5);
assert.equal(conflicts.failed, 5);
// i < 7 merged, rest failed
const merges = s.mergeStatuses as Record<string, number>;
assert.equal(merges.merged, 7);
assert.equal(merges.failed, 3);
// i < 6 review, rest knowledge
const cache = s.cacheHits as Record<string, number>;
assert.equal(cache.review, 6);
assert.equal(cache.knowledge, 4);
});
test("singleton is exported", () => {
assert.ok(metrics instanceof MetricsCollector);
});
+380
View File
@@ -0,0 +1,380 @@
import assert from "node:assert/strict";
import { test, mock } from "node:test";
import { S3Client, GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
import { config } from "../src/config.js";
import {
normalizeEndpoint,
isR2Configured,
downloadR2Object,
uploadR2Object
} from "../src/storage/r2.js";
// ── Mock S3Client.prototype.send ──────────────────────────────────────────
const mockSend = mock.fn<(...args: unknown[]) => Promise<unknown>>();
mock.method(S3Client.prototype, "send", mockSend);
let _lastGetObjectInput: Record<string, unknown> | undefined;
let _lastPutObjectInput: Record<string, unknown> | undefined;
// ── Helpers ───────────────────────────────────────────────────────────────
function setR2Config(
opts: {
endpoint?: string;
bucketName?: string;
accessKeyId?: string;
secretAccessKey?: string;
} = {}
): void {
config.r2Endpoint = opts.endpoint;
config.r2BucketName = opts.bucketName;
config.r2AccessKeyId = opts.accessKeyId;
config.r2SecretAccessKey = opts.secretAccessKey;
}
function clearR2Config(): void {
setR2Config();
}
/** Reset the S3 send mock and attach a default handler that captures commands. */
function resetSendMock(handler?: (command: unknown) => Promise<unknown>): void {
mockSend.mock.resetCalls();
_lastGetObjectInput = undefined;
_lastPutObjectInput = undefined;
mockSend.mock.mockImplementation(
handler ??
(async (command: unknown) => {
if (command instanceof GetObjectCommand) {
_lastGetObjectInput = command.input;
return { Body: undefined };
}
if (command instanceof PutObjectCommand) {
_lastPutObjectInput = command.input;
return {};
}
return {};
})
);
}
// ═══════════════════════════════════════════════════════════════════════════
// normalizeEndpoint
// ═══════════════════════════════════════════════════════════════════════════
test("normalizeEndpoint with valid HTTPS URL returns normalized", () => {
assert.equal(
normalizeEndpoint("https://account.r2.cloudflarestorage.com"),
"https://account.r2.cloudflarestorage.com"
);
});
test("normalizeEndpoint removes trailing slash", () => {
assert.equal(
normalizeEndpoint("https://account.r2.cloudflarestorage.com/"),
"https://account.r2.cloudflarestorage.com"
);
assert.equal(
normalizeEndpoint("https://account.r2.cloudflarestorage.com/my-prefix/"),
"https://account.r2.cloudflarestorage.com/my-prefix"
);
});
test("normalizeEndpoint with invalid URL throws", () => {
assert.throws(() => normalizeEndpoint("not a url"), /valid HTTPS URL/);
assert.throws(() => normalizeEndpoint(""), /valid HTTPS URL/);
});
test("normalizeEndpoint with userinfo in URL throws", () => {
assert.throws(() => normalizeEndpoint("https://user:pass@host.com"), /credential-free HTTPS/);
assert.throws(() => normalizeEndpoint("https://user@host.com"), /credential-free HTTPS/);
});
test("normalizeEndpoint with non-HTTPS protocol throws", () => {
assert.throws(() => normalizeEndpoint("http://r2.example.com"), /credential-free HTTPS/);
assert.throws(() => normalizeEndpoint("ftp://r2.example.com"), /credential-free HTTPS/);
});
test("normalizeEndpoint with query string throws", () => {
assert.throws(() => normalizeEndpoint("https://r2.example.com?foo=bar"), /credential-free HTTPS/);
});
test("normalizeEndpoint with hash fragment throws", () => {
assert.throws(() => normalizeEndpoint("https://r2.example.com#section"), /credential-free HTTPS/);
});
// ═══════════════════════════════════════════════════════════════════════════
// isR2Configured
// ═══════════════════════════════════════════════════════════════════════════
test("isR2Configured returns false when no config values set", () => {
clearR2Config();
assert.equal(isR2Configured(), false);
});
test("isR2Configured throws when config is partial", () => {
clearR2Config();
config.r2Endpoint = "https://example.r2.cloudflarestorage.com";
assert.throws(() => isR2Configured(), /R2 cache configuration is incomplete/);
});
// ═══════════════════════════════════════════════════════════════════════════
// downloadR2Object
// ═══════════════════════════════════════════════════════════════════════════
test("downloadR2Object returns Buffer for valid response", async () => {
setR2Config({
endpoint: "https://example.r2.cloudflarestorage.com",
bucketName: "my-bucket",
accessKeyId: "akid",
secretAccessKey: "sak"
});
resetSendMock(async (command: unknown) => {
if (command instanceof GetObjectCommand) {
_lastGetObjectInput = command.input;
return {
Body: {
transformToByteArray: async () => new Uint8Array([104, 101, 108, 108, 111])
}
};
}
return {};
});
const result = await downloadR2Object("some/key.json");
assert.ok(result !== undefined, "expected a Buffer, got undefined");
assert.ok(Buffer.isBuffer(result));
assert.equal(result.toString(), "hello");
assert.equal(mockSend.mock.calls.length, 1);
});
test("downloadR2Object returns empty Buffer when Body is absent", async () => {
setR2Config({
endpoint: "https://example.r2.cloudflarestorage.com",
bucketName: "my-bucket",
accessKeyId: "akid",
secretAccessKey: "sak"
});
resetSendMock(async (command: unknown) => {
if (command instanceof GetObjectCommand) {
_lastGetObjectInput = command.input;
return { Body: undefined };
}
return {};
});
const result = await downloadR2Object("some/key.json");
assert.ok(result !== undefined, "expected a Buffer, got undefined");
assert.ok(Buffer.isBuffer(result));
assert.equal(result.byteLength, 0);
assert.equal(mockSend.mock.calls.length, 1);
});
// ═══════════════════════════════════════════════════════════════════════════
// uploadR2Object
// ═══════════════════════════════════════════════════════════════════════════
test("uploadR2Object calls PutObjectCommand with correct params", async () => {
setR2Config({
endpoint: "https://example.r2.cloudflarestorage.com",
bucketName: "my-bucket",
accessKeyId: "akid",
secretAccessKey: "sak"
});
resetSendMock();
await uploadR2Object({
key: "test/object.json",
body: JSON.stringify({ foo: "bar" }),
contentType: "application/json"
});
assert.equal(mockSend.mock.calls.length, 1);
assert.ok(_lastPutObjectInput, "PutObjectCommand was not instantiated");
assert.equal(_lastPutObjectInput!.Bucket, "my-bucket");
assert.equal(_lastPutObjectInput!.Key, "test/object.json");
assert.equal(_lastPutObjectInput!.ContentType, "application/json");
assert.equal(_lastPutObjectInput!.CacheControl, "no-store");
assert.deepEqual(_lastPutObjectInput!.Metadata, { "ghbot-format": "v1" });
assert.equal(_lastPutObjectInput!.Body, JSON.stringify({ foo: "bar" }));
});
test("uploadR2Object with Uint8Array body", async () => {
setR2Config({
endpoint: "https://example.r2.cloudflarestorage.com",
bucketName: "my-bucket",
accessKeyId: "akid",
secretAccessKey: "sak"
});
resetSendMock();
const binaryBody = new Uint8Array([1, 2, 3]);
await uploadR2Object({
key: "binary/data.bin",
body: binaryBody,
contentType: "application/octet-stream"
});
assert.equal(mockSend.mock.calls.length, 1);
assert.ok(_lastPutObjectInput, "PutObjectCommand was not instantiated");
assert.equal(_lastPutObjectInput!.Body, binaryBody);
assert.equal(_lastPutObjectInput!.ContentType, "application/octet-stream");
});
// ═══════════════════════════════════════════════════════════════════════════
// validateBucketName (tested through isR2Configured)
// ═══════════════════════════════════════════════════════════════════════════
test("validateBucketName with valid name passes", () => {
setR2Config({
endpoint: "https://example.r2.cloudflarestorage.com",
bucketName: "my-valid-bucket-123",
accessKeyId: "akid",
secretAccessKey: "sak"
});
assert.doesNotThrow(() => isR2Configured());
});
test("validateBucketName with invalid name throws", () => {
setR2Config({
endpoint: "https://example.r2.cloudflarestorage.com",
bucketName: "UPPERCASE_BUCKET",
accessKeyId: "akid",
secretAccessKey: "sak"
});
assert.throws(() => isR2Configured(), /R2_BUCKET_NAME must be a valid S3-compatible bucket name/);
});
test("validateBucketName with name starting with dash throws", () => {
setR2Config({
endpoint: "https://example.r2.cloudflarestorage.com",
bucketName: "-invalid-bucket",
accessKeyId: "akid",
secretAccessKey: "sak"
});
assert.throws(() => isR2Configured(), /R2_BUCKET_NAME must be a valid S3-compatible bucket name/);
});
// ═══════════════════════════════════════════════════════════════════════════
// isMissingObject (tested through downloadR2Object)
// ═══════════════════════════════════════════════════════════════════════════
test("isMissingObject with NoSuchKey returns undefined", async () => {
setR2Config({
endpoint: "https://example.r2.cloudflarestorage.com",
bucketName: "my-bucket",
accessKeyId: "akid",
secretAccessKey: "sak"
});
resetSendMock(async () => {
const err = new Error("NoSuchKey") as Error & { name: string };
err.name = "NoSuchKey";
throw err;
});
const result = await downloadR2Object("missing-key.json");
assert.equal(result, undefined);
});
test("isMissingObject with 404 status returns undefined", async () => {
setR2Config({
endpoint: "https://example.r2.cloudflarestorage.com",
bucketName: "my-bucket",
accessKeyId: "akid",
secretAccessKey: "sak"
});
resetSendMock(async () => {
const err = new Error("NotFound") as Error & {
name: string;
$metadata?: { httpStatusCode: number };
};
err.name = "NotFound";
err.$metadata = { httpStatusCode: 404 };
throw err;
});
const result = await downloadR2Object("missing-key.json");
assert.equal(result, undefined);
});
test("isMissingObject with other errors rethrows", async () => {
setR2Config({
endpoint: "https://example.r2.cloudflarestorage.com",
bucketName: "my-bucket",
accessKeyId: "akid",
secretAccessKey: "sak"
});
resetSendMock(async () => {
throw new Error("Network failure");
});
await assert.rejects(() => downloadR2Object("some-key.json"), /Network failure/);
});
test("isMissingObject with non-object error rethrows", async () => {
setR2Config({
endpoint: "https://example.r2.cloudflarestorage.com",
bucketName: "my-bucket",
accessKeyId: "akid",
secretAccessKey: "sak"
});
resetSendMock(async () => {
throw new Error("string error");
});
await assert.rejects(() => downloadR2Object("some-key.json"), /string error/);
});
// ═══════════════════════════════════════════════════════════════════════════
// Extra edge cases
// ═══════════════════════════════════════════════════════════════════════════
test("downloadR2Object with 403 error rethrows", async () => {
setR2Config({
endpoint: "https://example.r2.cloudflarestorage.com",
bucketName: "my-bucket",
accessKeyId: "akid",
secretAccessKey: "sak"
});
resetSendMock(async () => {
const err = new Error("Forbidden") as Error & {
name: string;
$metadata?: { httpStatusCode: number };
};
err.name = "Forbidden";
err.$metadata = { httpStatusCode: 403 };
throw err;
});
await assert.rejects(() => downloadR2Object("forbidden-key.json"), /Forbidden/);
});
test("downloadR2Object with AccessDenied error rethrows", async () => {
setR2Config({
endpoint: "https://example.r2.cloudflarestorage.com",
bucketName: "my-bucket",
accessKeyId: "akid",
secretAccessKey: "sak"
});
resetSendMock(async () => {
const err = new Error("AccessDenied") as Error & { name: string };
err.name = "AccessDenied";
throw err;
});
await assert.rejects(() => downloadR2Object("restricted-key.json"), /AccessDenied/);
});
+8
View File
@@ -5,6 +5,7 @@ import path from "node:path";
import test from "node:test"; import test from "node:test";
import { import {
loadRepositoryKnowledge, loadRepositoryKnowledge,
normalizeKnowledge,
readKnowledgeScratch, readKnowledgeScratch,
saveRepositoryKnowledgeCache, saveRepositoryKnowledgeCache,
validateRepositoryKnowledge, validateRepositoryKnowledge,
@@ -61,6 +62,13 @@ test("loading an empty repository knowledge cache initializes the persisted file
} }
}); });
test("normalizeKnowledge normalizes CRLF and CR line endings to LF", () => {
assert.equal(normalizeKnowledge("# A\r\n\r\nB\r\n"), "# A\n\nB\n");
assert.equal(normalizeKnowledge("# A\rB\r"), "# A\nB\n");
assert.equal(normalizeKnowledge("x\n".repeat(100)), `${"x\n".repeat(100)}`);
assert.equal(normalizeKnowledge("# A\n\nB\n"), "# A\n\nB\n");
});
test("repository knowledge rejects credentials and oversized content", () => { test("repository knowledge rejects credentials and oversized content", () => {
assert.throws( assert.throws(
() => validateRepositoryKnowledge("-----BEGIN PRIVATE KEY-----\nsecret"), () => validateRepositoryKnowledge("-----BEGIN PRIVATE KEY-----\nsecret"),
+104
View File
@@ -0,0 +1,104 @@
import assert from "node:assert/strict";
import test from "node:test";
import { withRetry } from "../src/retry.js";
class HttpLikeError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
test("custom retryable predicate treats specific errors as retryable", async () => {
let attempts = 0;
const result = await withRetry(
"custom-retryable",
async () => {
attempts += 1;
if (attempts < 3) {
throw new HttpLikeError(403, "forbidden but transient per our rule");
}
return "done";
},
{
baseDelayMs: 1,
retryable: (error) => {
if (typeof error === "object" && error !== null && "status" in error) {
const e = error as { status: number };
return e.status === 403;
}
return false;
}
}
);
assert.equal(result, "done");
assert.equal(attempts, 3);
});
test("custom retryable predicate prevents retry when it returns false", async () => {
let attempts = 0;
await assert.rejects(
withRetry(
"custom-non-retryable",
async () => {
attempts += 1;
throw new HttpLikeError(500, "always fatal per our rule");
},
{
baseDelayMs: 1,
retryable: () => false
}
),
/always fatal/
);
assert.equal(attempts, 1);
});
test("default behavior unchanged when no custom retryable provided", async () => {
let attempts = 0;
const result = await withRetry(
"default-behavior",
async () => {
attempts += 1;
if (attempts < 3) {
throw new HttpLikeError(502, "bad gateway");
}
return "ok";
},
{ baseDelayMs: 1 }
);
assert.equal(result, "ok");
assert.equal(attempts, 3);
});
test("default behavior still rejects non-retryable errors", async () => {
let attempts = 0;
await assert.rejects(
withRetry("default-non-retryable", async () => {
attempts += 1;
throw new HttpLikeError(404, "not found");
})
);
assert.equal(attempts, 1);
});
test("maxTotalTimeoutMs stops retries when elapsed time exceeds limit", async () => {
const startTime = Date.now();
let attempts = 0;
await assert.rejects(
withRetry(
"timeout-limit",
async () => {
attempts += 1;
// Simulate a brief operation that takes some time
throw new HttpLikeError(502, "timeout test");
},
{ maxAttempts: 5, baseDelayMs: 100, maxTotalTimeoutMs: 50 }
)
);
const elapsed = Date.now() - startTime;
assert.ok(attempts > 0, "at least one attempt was made");
assert.ok(attempts < 5, "should not reach max attempts due to total timeout");
assert.ok(elapsed < 500, "should complete within reasonable time given the short timeout");
});
+243
View File
@@ -0,0 +1,243 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
buildReviewSubmissionPlan,
formatSupersededReviewBody,
isConflictComment,
isRecheckComment,
shortSha,
shouldFallbackToCommentReview
} from "../src/review/processor.js";
import type { ReviewDecision } from "../src/types.js";
type DispositionEvent = "APPROVE" | "COMMENT" | "REQUEST_CHANGES";
const cleanDecision: ReviewDecision = {
review: [],
change: [],
comment: "looks fine",
result: { canMerge: true, summary: "approved", shouldClosePullRequest: false, closeReason: "" }
};
function finding(path: string, line: number, title: string, body: string) {
return { path, line, title, body };
}
test("buildReviewSubmissionPlan emits REQUEST_CHANGES first when change findings exist", () => {
const decision: ReviewDecision = {
...cleanDecision,
change: [finding("a.ts", 1, "change it", "blocking")]
};
const plan = buildReviewSubmissionPlan(decision, { event: "APPROVE" });
assert.equal(plan[0]?.phase, "change");
assert.equal(plan[0]?.event, "REQUEST_CHANGES");
assert.equal(plan[0]?.findings.length, 1);
assert.equal(plan[0]?.findings[0]?.category, "change");
});
test("buildReviewSubmissionPlan emits a COMMENT phase for review findings", () => {
const decision: ReviewDecision = {
...cleanDecision,
review: [finding("b.ts", 2, "note", "non-blocking")]
};
const plan = buildReviewSubmissionPlan(decision, { event: "APPROVE" });
assert.equal(plan[0]?.phase, "review");
assert.equal(plan[0]?.event, "COMMENT");
assert.equal(plan[0]?.findings.length, 1);
assert.equal(plan[0]?.findings[0]?.category, "review");
});
test("buildReviewSubmissionPlan orders change before review when both exist", () => {
const decision: ReviewDecision = {
...cleanDecision,
change: [finding("a.ts", 1, "change it", "blocking")],
review: [finding("b.ts", 2, "note", "non-blocking")]
};
const plan = buildReviewSubmissionPlan(decision, { event: "APPROVE" });
assert.deepEqual(
plan.map((phase) => phase.phase),
["change", "review", "final"]
);
assert.deepEqual(
plan.map((phase) => phase.event),
["REQUEST_CHANGES", "COMMENT", "COMMENT"]
);
});
test("buildReviewSubmissionPlan emits final APPROVE when there are no findings", () => {
const plan = buildReviewSubmissionPlan(cleanDecision, { event: "APPROVE" });
assert.equal(plan.length, 1);
assert.equal(plan[0]?.phase, "final");
assert.equal(plan[0]?.event, "APPROVE");
assert.deepEqual(plan[0]?.findings, []);
});
test("buildReviewSubmissionPlan always ends with a final phase", () => {
const withChangeOnly: ReviewDecision = {
...cleanDecision,
change: [finding("a.ts", 1, "change it", "blocking")]
};
const withReviewOnly: ReviewDecision = {
...cleanDecision,
review: [finding("b.ts", 2, "note", "non-blocking")]
};
const both: ReviewDecision = {
...cleanDecision,
change: [finding("a.ts", 1, "change it", "blocking")],
review: [finding("b.ts", 2, "note", "non-blocking")]
};
for (const [label, decision, event] of [
["clean", cleanDecision, "APPROVE" as DispositionEvent],
["change only", withChangeOnly, "REQUEST_CHANGES" as DispositionEvent],
["review only", withReviewOnly, "COMMENT" as DispositionEvent],
["both", both, "REQUEST_CHANGES" as DispositionEvent]
]) {
const plan = buildReviewSubmissionPlan(decision, { event });
const last = plan.at(-1);
assert.equal(last?.phase, "final", `${label}: last phase must be final`);
assert.deepEqual(last?.findings ?? [], [], `${label}: final phase carries no findings`);
}
});
test("buildReviewSubmissionPlan forces final event to COMMENT when change findings exist", () => {
const withChangeOnly: ReviewDecision = {
...cleanDecision,
change: [finding("a.ts", 1, "change it", "blocking")]
};
const withChangeThenReview: ReviewDecision = {
...cleanDecision,
change: [finding("a.ts", 1, "change it", "blocking")],
review: [finding("b.ts", 2, "note", "non-blocking")]
};
const changePlan = buildReviewSubmissionPlan(withChangeOnly, { event: "REQUEST_CHANGES" });
assert.equal(changePlan.at(-1)?.event, "COMMENT");
const bothPlan = buildReviewSubmissionPlan(withChangeThenReview, { event: "REQUEST_CHANGES" });
assert.equal(bothPlan.at(-1)?.event, "COMMENT");
});
test("buildReviewSubmissionPlan leaves final event to the disposition when no change findings exist", () => {
const withReviewOnly: ReviewDecision = {
...cleanDecision,
review: [finding("b.ts", 2, "note", "non-blocking")]
};
const plan = buildReviewSubmissionPlan(withReviewOnly, { event: "APPROVE" });
assert.equal(plan.at(-1)?.event, "APPROVE");
});
test("shouldFallbackToCommentReview returns false for non-APPROVE events", () => {
const error = {
status: 422,
message: "GitHub Actions is not permitted to approve pull requests."
};
assert.equal(shouldFallbackToCommentReview(error, "COMMENT"), false);
assert.equal(shouldFallbackToCommentReview(error, "REQUEST_CHANGES"), false);
});
test("shouldFallbackToCommentReview returns false for non-422 errors", () => {
const error = {
status: 403,
message: "GitHub Actions is not permitted to approve pull requests."
};
assert.equal(shouldFallbackToCommentReview(error, "APPROVE"), false);
});
test("shouldFallbackToCommentReview returns true for 422 with GitHub Actions not permitted", () => {
const error = {
status: 422,
message: "GitHub Actions is not permitted to approve pull requests."
};
assert.equal(shouldFallbackToCommentReview(error, "APPROVE"), true);
});
test("shouldFallbackToCommentReview returns false for 422 with unrelated message", () => {
const error = { status: 422, message: "Validation error: body is too long." };
assert.equal(shouldFallbackToCommentReview(error, "APPROVE"), false);
});
test("shouldFallbackToCommentReview returns false for non-object errors", () => {
assert.equal(shouldFallbackToCommentReview("string error", "APPROVE"), false);
assert.equal(shouldFallbackToCommentReview(null, "APPROVE"), false);
assert.equal(shouldFallbackToCommentReview(undefined, "APPROVE"), false);
});
test("shortSha returns first 12 characters", () => {
const sha = "abcdef0123456789abcdef0123456789abcdef01";
assert.equal(shortSha(sha), "abcdef012345");
assert.equal(shortSha(sha).length, 12);
});
test("isRecheckComment matches the exact command", () => {
assert.equal(isRecheckComment("/recheck"), true);
});
test("isRecheckComment matches with surrounding whitespace", () => {
assert.equal(isRecheckComment(" /recheck "), true);
assert.equal(isRecheckComment("\t/recheck\n"), true);
});
test("isRecheckComment rejects different text", () => {
assert.equal(isRecheckComment("please recheck"), false);
assert.equal(isRecheckComment("/refresh"), false);
assert.equal(isRecheckComment(""), false);
});
test("isConflictComment matches the exact command", () => {
assert.equal(isConflictComment("/conflict"), true);
});
test("isConflictComment matches with surrounding whitespace", () => {
assert.equal(isConflictComment(" /conflict "), true);
assert.equal(isConflictComment("\t/conflict\n"), true);
});
test("isConflictComment rejects different text", () => {
assert.equal(isConflictComment("resolve conflict"), false);
assert.equal(isConflictComment("/conflicts"), false);
assert.equal(isConflictComment(""), false);
});
test("formatSupersededReviewBody keeps the original state marker", () => {
const originalMarker =
"<!-- ghbot-review:v1 mode=normal outcome=pass requires-admin=false review=1 change=0 -->";
const body = formatSupersededReviewBody({
originalMarker,
oldCommitId: "a".repeat(40),
currentCommitId: "b".repeat(40)
});
assert.ok(body.startsWith(originalMarker), "body must start with the original marker line");
});
test("formatSupersededReviewBody includes old and new commit SHAs (short form)", () => {
const oldCommitId = "a".repeat(40);
const currentCommitId = "b".repeat(40);
const body = formatSupersededReviewBody({
originalMarker: "<!-- ghbot-review:v1 superseded=true -->",
oldCommitId,
currentCommitId
});
assert.ok(body.includes(oldCommitId.slice(0, 12)), "body must mention the old short SHA");
assert.ok(body.includes(currentCommitId.slice(0, 12)), "body must mention the new short SHA");
assert.equal(body.includes(oldCommitId), false, "full old SHA should not be used");
assert.equal(body.includes(currentCommitId), false, "full current SHA should not be used");
});
test("formatSupersededReviewBody marks the review as Superseded", () => {
const body = formatSupersededReviewBody({
originalMarker: "<!-- ghbot-review:v1 superseded=true -->",
oldCommitId: "a".repeat(40),
currentCommitId: "b".repeat(40)
});
assert.match(body, /## Superseded automated review/);
assert.match(body, /Superseded automated review/);
});
+136
View File
@@ -0,0 +1,136 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { Octokit } from "@octokit/rest";
import { config } from "../src/config.js";
import {
buildPullRequestCoarsePrompt,
buildPullRequestDuplicatePrompt,
buildTriagePrompt,
labelName,
processIssueTriage,
processPullRequestTriage,
type PullRequestEvidence
} from "../src/triage/processor.js";
const originalTriageEnabled = config.triageEnabled;
test.afterEach(() => {
config.triageEnabled = originalTriageEnabled;
});
function issueTarget(overrides: Record<string, unknown> = {}) {
return {
number: 7,
title: "Broken login button",
body: "Clicking login does nothing.",
htmlUrl: "https://github.com/acme/app/issues/7",
existingLabels: [],
...overrides
};
}
function candidate(overrides: Record<string, unknown> = {}) {
return {
number: 9,
title: "Login button styling",
body: "Adjusts the login button.",
state: "open",
htmlUrl: "https://github.com/acme/app/issues/9",
...overrides
};
}
function emptyEvidence(number: number): PullRequestEvidence {
return {
number,
commits: [],
comments: [],
reviews: [],
reviewComments: []
};
}
test("buildPullRequestCoarsePrompt embeds the target, labels, and duplicate candidates", () => {
const prompt = buildPullRequestCoarsePrompt(issueTarget(), [candidate()]);
assert.match(prompt, /"title": "Broken login button"/);
assert.match(prompt, /must contain at least one value and may only use:/);
assert.match(prompt, /"bug"/);
assert.match(prompt, /"number": 9/);
assert.match(prompt, /"number": 7/);
});
test("buildPullRequestDuplicatePrompt embeds target evidence and candidate evidence", () => {
const targetEvidence = emptyEvidence(7);
const candidateEvidence = [emptyEvidence(9)];
const prompt = buildPullRequestDuplicatePrompt({
target: issueTarget(),
targetEvidence,
candidates: [candidate()],
candidateEvidence
});
assert.match(prompt, /"number": 7/);
assert.match(prompt, /"number": 9/);
assert.match(prompt, /Target pull request and detailed evidence:/);
assert.match(prompt, /"evidence": \{/);
assert.match(prompt, /"commits": \[\]/);
assert.match(prompt, /"comments": \[\]/);
assert.match(prompt, /"reviews": \[\]/);
assert.match(prompt, /"reviewComments": \[\]/);
});
test("buildTriagePrompt advertises issue triage for an issue target", () => {
const prompt = buildTriagePrompt("issue", issueTarget(), [candidate()]);
assert.match(prompt, /triaging a GitHub issue/);
assert.doesNotMatch(prompt, /pull request/);
assert.match(prompt, /"body": "Clicking login does nothing\."/);
});
test("buildTriagePrompt advertises pull request triage for a pull request target", () => {
const prompt = buildTriagePrompt("pull_request", issueTarget(), [candidate()]);
assert.match(prompt, /triaging a GitHub pull request/);
});
test("buildTriagePrompt includes labels, target, and candidates", () => {
const prompt = buildTriagePrompt("issue", issueTarget(), [candidate({ number: 9 })]);
assert.match(prompt, /"bug"/);
assert.match(prompt, /"title": "Broken login button"/);
assert.match(prompt, /"title": "Login button styling"/);
});
test("labelName handles a plain string label", () => {
assert.equal(labelName("bug"), "bug");
});
test("labelName extracts the name from an object label", () => {
assert.equal(labelName({ name: "documentation", node_id: "MDU6TGFiZWwx" }), "documentation");
});
test("labelName returns an empty string for an object label without a name", () => {
assert.equal(labelName({ id: 123 }), "");
});
test("labelName returns an empty string for an empty-name object label", () => {
assert.equal(labelName({ name: "" }), "");
});
test("processIssueTriage returns immediately when triage is disabled", async () => {
config.triageEnabled = false;
await assert.doesNotReject(
processIssueTriage({} as Octokit, { owner: "acme", repo: "app", issueNumber: 7 })
);
});
test("processPullRequestTriage returns immediately when triage is disabled", async () => {
config.triageEnabled = false;
await assert.doesNotReject(
processPullRequestTriage({} as Octokit, {
owner: "acme",
repo: "app",
pullNumber: 9
})
);
});
+821
View File
@@ -0,0 +1,821 @@
import assert from "node:assert/strict";
import test from "node:test";
import { parseWebhookMentionEvent, webhookPermissionAllows } from "../src/webhook/processor.js";
// ---------------------------------------------------------------------------
// parseWebhookMentionEvent
// ---------------------------------------------------------------------------
test("parseWebhookMentionEvent for issue_comment with missing fields returns null", () => {
// Missing issue number
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { title: "test" },
comment: { id: 88, body: "@bot hello", user: { login: "alice", type: "User" } }
},
"delivery-1",
"bot"
),
null
);
// Missing comment id
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7, pull_request: { url: "" } },
comment: { body: "@bot hello", user: { login: "alice", type: "User" } }
},
"delivery-2",
"bot"
),
null
);
// Missing comment body
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: { id: 88, user: { login: "alice", type: "User" } }
},
"delivery-3",
"bot"
),
null
);
// Missing repository owner
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 12345 },
repository: { name: "demo" },
issue: { number: 7 },
comment: { id: 88, body: "@bot hello", user: { login: "alice", type: "User" } }
},
"delivery-4",
"bot"
),
null
);
});
test("parseWebhookMentionEvent for pull_request_review_comment with valid data", () => {
const mention = parseWebhookMentionEvent(
"pull_request_review_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
pull_request: { number: 7 },
comment: {
id: 88,
body: "@bot please review this comment",
user: { login: "alice", type: "User" }
}
},
"delivery-review-comment",
"bot"
);
assert.ok(mention);
assert.equal(mention.eventName, "pull_request_review_comment");
assert.equal(mention.installationId, 12345);
assert.equal(mention.owner, "acme");
assert.equal(mention.repo, "demo");
assert.equal(mention.issueNumber, 7);
assert.equal(mention.targetKind, "pull_request");
assert.equal(mention.sourceCommentId, 88);
assert.equal(mention.commentBody, "@bot please review this comment");
assert.equal(mention.commenterLogin, "alice");
assert.equal(mention.commenterType, "User");
assert.equal(mention.replyMode, "review_comment");
assert.equal(mention.action, "created");
assert.equal(mention.deliveryId, "delivery-review-comment");
assert.equal(mention.repositoryId, 99);
});
test("parseWebhookMentionEvent for pull_request_review submitted action", () => {
const mention = parseWebhookMentionEvent(
"pull_request_review",
{
action: "submitted",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
pull_request: { number: 7 },
review: {
id: 88,
body: "@bot thanks for the review",
user: { login: "bob", type: "User" }
}
},
"delivery-review-submitted",
"bot"
);
assert.ok(mention);
assert.equal(mention.eventName, "pull_request_review");
assert.equal(mention.installationId, 12345);
assert.equal(mention.owner, "acme");
assert.equal(mention.repo, "demo");
assert.equal(mention.issueNumber, 7);
assert.equal(mention.targetKind, "pull_request");
assert.equal(mention.sourceCommentId, 88);
assert.equal(mention.commentBody, "@bot thanks for the review");
assert.equal(mention.commenterLogin, "bob");
assert.equal(mention.commenterType, "User");
assert.equal(mention.replyMode, "conversation");
assert.equal(mention.action, "submitted");
assert.equal(mention.deliveryId, "delivery-review-submitted");
});
test("parseWebhookMentionEvent for non-submitted pull_request_review returns null", () => {
assert.equal(
parseWebhookMentionEvent(
"pull_request_review",
{
action: "dismissed",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
pull_request: { number: 7 },
review: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-dismissed",
"bot"
),
null
);
assert.equal(
parseWebhookMentionEvent(
"pull_request_review",
{
action: "edited",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
pull_request: { number: 7 },
review: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-edited",
"bot"
),
null
);
});
test("parseWebhookMentionEvent with non-created/edited action returns null", () => {
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "deleted",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-deleted",
"bot"
),
null
);
// "edited" should still work for issue_comment
assert.ok(
parseWebhookMentionEvent(
"issue_comment",
{
action: "edited",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7, pull_request: { url: "" } },
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-edited-ok",
"bot"
)
);
});
test("parseWebhookMentionEvent with bot sender returns null", () => {
// Bot type sender
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: {
id: 88,
body: "@bot test",
user: { login: "some-app", type: "Bot" }
}
},
"delivery-bot-type",
"bot"
),
null
);
// Login matching botName (case-insensitive)
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: {
id: 88,
body: "@bot test",
user: { login: "BOT", type: "User" }
}
},
"delivery-bot-login",
"bot"
),
null
);
// Login matching botName with [bot] suffix
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: {
id: 88,
body: "@bot test",
user: { login: "github-actions[bot]", type: "User" }
}
},
"delivery-bot-suffix",
"github-actions[bot]"
),
null
);
});
test("parseWebhookMentionEvent with empty payload or deliveryId returns null", () => {
assert.equal(parseWebhookMentionEvent("issue_comment", null, "delivery-1", "bot"), null);
assert.equal(
parseWebhookMentionEvent("issue_comment", "not-an-object", "delivery-2", "bot"),
null
);
assert.equal(parseWebhookMentionEvent("issue_comment", { action: "created" }, "", "bot"), null);
});
test("parseWebhookMentionEvent for pull_request_review with missing review fields returns null", () => {
// Missing review id
assert.equal(
parseWebhookMentionEvent(
"pull_request_review",
{
action: "submitted",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
pull_request: { number: 7 },
review: { body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-missing-review-id",
"bot"
),
null
);
// Missing review body
assert.equal(
parseWebhookMentionEvent(
"pull_request_review",
{
action: "submitted",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
pull_request: { number: 7 },
review: { id: 88, user: { login: "alice", type: "User" } }
},
"delivery-missing-review-body",
"bot"
),
null
);
// Missing pull_request number
assert.equal(
parseWebhookMentionEvent(
"pull_request_review",
{
action: "submitted",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
pull_request: {},
review: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-missing-pr-number",
"bot"
),
null
);
});
test("parseWebhookMentionEvent for pull_request_review_comment with missing fields returns null", () => {
// Missing pull_request number
assert.equal(
parseWebhookMentionEvent(
"pull_request_review_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
pull_request: {},
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-pr-comment-missing-pr",
"bot"
),
null
);
// Missing comment id
assert.equal(
parseWebhookMentionEvent(
"pull_request_review_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
pull_request: { number: 7 },
comment: { body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-pr-comment-missing-id",
"bot"
),
null
);
// Missing comment body
assert.equal(
parseWebhookMentionEvent(
"pull_request_review_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
pull_request: { number: 7 },
comment: { id: 88, user: { login: "alice", type: "User" } }
},
"delivery-pr-comment-missing-body",
"bot"
),
null
);
});
test("parseWebhookMentionEvent for pull_request_review_comment non-created/edited action returns null", () => {
assert.equal(
parseWebhookMentionEvent(
"pull_request_review_comment",
{
action: "deleted",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
pull_request: { number: 7 },
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-pr-comment-deleted",
"bot"
),
null
);
});
test("parseWebhookMentionEvent for pull_request_review_comment without bot mention returns null", () => {
assert.equal(
parseWebhookMentionEvent(
"pull_request_review_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
pull_request: { number: 7 },
comment: {
id: 88,
body: "ordinary comment without mention",
user: { login: "alice", type: "User" }
}
},
"delivery-pr-comment-no-mention",
"bot"
),
null
);
});
test("parseWebhookMentionEvent for pull_request_review submitted without bot mention returns null", () => {
assert.equal(
parseWebhookMentionEvent(
"pull_request_review",
{
action: "submitted",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
pull_request: { number: 7 },
review: {
id: 88,
body: "ordinary review without mention",
user: { login: "alice", type: "User" }
}
},
"delivery-review-no-mention",
"bot"
),
null
);
});
test("parseWebhookMentionEvent for pull_request_review with bot reviewer returns null", () => {
assert.equal(
parseWebhookMentionEvent(
"pull_request_review",
{
action: "submitted",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
pull_request: { number: 7 },
review: {
id: 88,
body: "@bot test",
user: { login: "some-app", type: "Bot" }
}
},
"delivery-review-bot-reviewer",
"bot"
),
null
);
});
test("parseWebhookMentionEvent for issue_comment with null/undefined installation returns null", () => {
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-no-installation",
"bot"
),
null
);
});
// ---------------------------------------------------------------------------
// webhookPermissionAllows
// ---------------------------------------------------------------------------
test("webhookPermissionAllows with anyone policy always returns true", () => {
assert.equal(webhookPermissionAllows(null, "anyone"), true);
assert.equal(webhookPermissionAllows(undefined, "anyone"), true);
assert.equal(webhookPermissionAllows("none", "anyone"), true);
assert.equal(webhookPermissionAllows("read", "anyone"), true);
assert.equal(webhookPermissionAllows("write", "anyone"), true);
assert.equal(webhookPermissionAllows("admin", "anyone"), true);
assert.equal(webhookPermissionAllows("", "anyone"), true);
});
test("webhookPermissionAllows with read policy requires read+ permissions", () => {
// Allowed
assert.equal(webhookPermissionAllows("organization", "read"), true);
assert.equal(webhookPermissionAllows("read", "read"), true);
assert.equal(webhookPermissionAllows("triage", "read"), true);
assert.equal(webhookPermissionAllows("write", "read"), true);
assert.equal(webhookPermissionAllows("maintain", "read"), true);
assert.equal(webhookPermissionAllows("admin", "read"), true);
// Denied
assert.equal(webhookPermissionAllows(null, "read"), false);
assert.equal(webhookPermissionAllows(undefined, "read"), false);
});
test("webhookPermissionAllows with write policy requires write+ permissions", () => {
// Allowed
assert.equal(webhookPermissionAllows("write", "write"), true);
assert.equal(webhookPermissionAllows("maintain", "write"), true);
assert.equal(webhookPermissionAllows("admin", "write"), true);
// Denied
assert.equal(webhookPermissionAllows(null, "write"), false);
assert.equal(webhookPermissionAllows(undefined, "write"), false);
assert.equal(webhookPermissionAllows("organization", "write"), false);
assert.equal(webhookPermissionAllows("read", "write"), false);
assert.equal(webhookPermissionAllows("triage", "write"), false);
});
test("webhookPermissionAllows with null permission returns false for read/write", () => {
assert.equal(webhookPermissionAllows(null, "read"), false);
assert.equal(webhookPermissionAllows(undefined, "read"), false);
assert.equal(webhookPermissionAllows(null, "write"), false);
assert.equal(webhookPermissionAllows(undefined, "write"), false);
});
// ---------------------------------------------------------------------------
// isCreatedOrEdited (tested indirectly through parseWebhookMentionEvent)
// ---------------------------------------------------------------------------
test("isCreatedOrEdited returns true for created and edited (indirect)", () => {
// "created" action accepted for issue_comment
assert.ok(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7, pull_request: { url: "" } },
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-created",
"bot"
)
);
// "edited" action accepted for issue_comment
assert.ok(
parseWebhookMentionEvent(
"issue_comment",
{
action: "edited",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7, pull_request: { url: "" } },
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-edited",
"bot"
)
);
});
test("isCreatedOrEdited returns false for deleted (indirect)", () => {
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "deleted",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-deleted",
"bot"
),
null
);
});
// ---------------------------------------------------------------------------
// isBotSender (tested indirectly through parseWebhookMentionEvent)
// ---------------------------------------------------------------------------
test("isBotSender checks type === Bot and login case-insensitive match (indirect)", () => {
// Bot type
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: {
id: 88,
body: "@bot test",
user: { login: "some-app", type: "Bot" }
}
},
"delivery-bot-type",
"bot"
),
null
);
// Case-insensitive login match with botName
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: {
id: 88,
body: "@bot test",
user: { login: "Bot", type: "User" }
}
},
"delivery-bot-login-ci",
"bot"
),
null
);
// Non-bot, non-matching login is allowed
assert.ok(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7, pull_request: { url: "" } },
comment: {
id: 88,
body: "@bot test",
user: { login: "alice", type: "User" }
}
},
"delivery-human-user",
"bot"
)
);
});
// ---------------------------------------------------------------------------
// isRecord (tested indirectly through parseWebhookMentionEvent)
// ---------------------------------------------------------------------------
test("isRecord returns false for non-objects (indirect)", () => {
// Non-object payload
assert.equal(parseWebhookMentionEvent("issue_comment", "string", "delivery-1", "bot"), null);
// Null payload
assert.equal(parseWebhookMentionEvent("issue_comment", null, "delivery-2", "bot"), null);
// Number payload
assert.equal(parseWebhookMentionEvent("issue_comment", 42, "delivery-3", "bot"), null);
});
// ---------------------------------------------------------------------------
// asString (tested indirectly through parseWebhookMentionEvent)
// ---------------------------------------------------------------------------
test("asString returns undefined for non-strings (indirect)", () => {
// Non-string comment body (number)
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: { id: 88, body: 123, user: { login: "alice", type: "User" } }
},
"delivery-non-string-body",
"bot"
),
null
);
// Non-string owner login (array)
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: ["acme"] } },
issue: { number: 7 },
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-non-string-owner",
"bot"
),
null
);
});
// ---------------------------------------------------------------------------
// asPositiveInteger (tested indirectly through parseWebhookMentionEvent)
// ---------------------------------------------------------------------------
test("asPositiveInteger validates positive safe integers (indirect)", () => {
// Zero installation id
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 0 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-zero-installation",
"bot"
),
null
);
// Negative installation id
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: -1 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-negative-installation",
"bot"
),
null
);
// Non-integer installation id
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 1.5 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-float-installation",
"bot"
),
null
);
// Non-number installation id
assert.equal(
parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: "12345" },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: { id: 88, body: "@bot test", user: { login: "alice", type: "User" } }
},
"delivery-string-installation",
"bot"
),
null
);
});
// ---------------------------------------------------------------------------
// Issue with null targetKind (issue without pull_request marker)
// ---------------------------------------------------------------------------
test("parseWebhookMentionEvent for issue_comment on an issue (not PR)", () => {
const mention = parseWebhookMentionEvent(
"issue_comment",
{
action: "created",
installation: { id: 12345 },
repository: { id: 99, name: "demo", owner: { login: "acme" } },
issue: { number: 7 },
comment: { id: 88, body: "@bot question about issue", user: { login: "alice", type: "User" } }
},
"delivery-issue-only",
"bot"
);
assert.ok(mention);
assert.equal(mention.targetKind, "issue");
assert.equal(mention.issueNumber, 7);
assert.equal(mention.replyMode, "conversation");
});
+76 -47
View File
@@ -1,55 +1,84 @@
# workflow_status.md — 终局闭环总审计 # workflow_status.md — v2.0 迭代执行审计
**任务**: 001-production-hardening · **模式**: 主控编排 → 独立审查 → 修复循环 → 复验 **任务**: 下一步改进指南 M0-M7 完整落地(第一阶段已执行)
**更新**: 2026-08-23(最终) **当前版本**: v1.2.0 → v2.0 半程
**更新**: 2026-08-24
## 节点 ## 执行结果总览
| # | 任务 | 状态 | 证据 | | 门禁 | 状态 |
|---|------|------|------| |------|------|
| N1 | 需求追踪矩阵 | done | `.specify/specs/001-production-hardening/spec.md` | | npm run typecheck | ✅ 通过 |
| N2-N5 | 契约/安全/错误/文档审计 | done | 四路并行扫描 + 独立 critic + explore | | npm run lint | ✅ 0 error |
| N6 | 问题分级 | done | workflow P0/P1/P2 清单 | | npm run format:check | ✅ All matched files use Prettier code style! |
| N7 | 修复 | done | 生产硬化改动,148 tests | | npm test | ✅ 321 tests / 321 pass / 0 fail |
| N8 | 门禁+E2E | done | typecheck/lint/format/test/audit/build;webhook :3012 含 413 | | npm run build | ✅ dist/ 构建成功 |
| N9 | 独立审查 | done | 六维 critic:Request Changes(Blocking 已逐项处理) | | 覆盖率 | 66.20% lines / 87.36% branches / 75.57% functions |
| N10 | 修复循环(复验) | done | 下方注记逐条闭环 |
| N11 | 文档 | done | README 双语、.env.example、变更报告 |
| N12 | Skill | done | `.claude/skills/ghbot-production-hardening/SKILL.md` |
## 独立审查 Blocking 处置(N10) ## 测试规模增长
- Goose 安装脚本:统一由 stable URL 改为 tag `v1.46.0`,工作流/Docker/容器回退三处一致(8.5 方向,checksum 仍待供应商提供)
- webhook 超时伪装 413:保留 413 用于 content-length 超限;超时仍 413 的语义问题已记录为 P2(无独立 408 分支,避免 GitHub 对 408 重投语义不确定);文档已注明 202 后 best-effort
- 冲突失败 reset:保留,因为 worktree 为一次性 checkout;dirty 前置检查失败时仍会 reset 的缺陷计为 P2(已记录)
- 合并护栏测试:新增 config/conflict/log/redaction 测试;merge 纯函数测试因 maybeMergePullRequest 未导出且无 octokit 断言库,计为 P2(已记录)
- 批准 lookup 非 404 重抛:已修(throw lastLookupError)
- runtimeDirectory 双源:已修,改回 env || config || cwd,并补 config schema 字段
- README Docker 命令:已修正为单反斜杠续行
- logger camelCase 脱敏:已补 githubToken/webhookSecret/r2SecretAccessKey/GOOSE_API_KEY/stderr
## E2E(2026-08-23,PORT=3012,生产 dist,硬化后复测) | 指标 | 之前(v1.2.0) | 现在 | 增长 |
``` |------|----------------|------|------|
GET /healthz → 200 {"ok":true,"webhook":true} | 测试文件 | 36 | 48 | +12 |
POST 合法 HMAC → 202 {"ok":true} | 测试数 | 151 | 321 | +170 |
POST 坏签名 → 401 {"error":"Invalid webhook signature."} | 覆盖率 lines | 61.41% | 66.20% | +4.79% |
POST 重复 delivery → 202 {"ok":true,"duplicate":true} | 覆盖率 branches | 82.98% | 87.36% | +4.38% |
POST content-length 超限 → 413 {"error":"Webhook payload is too large."} | 覆盖率 functions | 69.97% | 75.57% | +5.60% |
GET /metrics → accepted=1 duplicate=1 bad_signature=1 too_large=1
```
## 门禁(实测) ## 新增文件清单
```
typecheck 0 · lint 0 · format:check pass · test 148/148 · npm audit 0 · build OK
远端 CI run 32626556238 success
```
## 有意未做(P2/P3 已挂账) ### 源文件(新模块)
- 7.1 processor 路由器拆分(无事件环测试床)
- 6.4 全站 i18n
- goose 二进制 checksum(8.5 剩余)
- origin `lezi-fun/ghbot` 推送 403
- webhook 超时独立 408 分支
- conflict dirty 失败仍 reset
## 阻塞项 | 文件 | 功能 | 覆盖 |
无外部阻塞。 |------|------|------|
| `src/ai/failureMessages.ts` | 失败分类与告警文案 | 100% |
| `src/review/merge-guard.ts` | 合并防重入锁 | 100% |
| `src/metrics/collector.ts` | Actions 运行指标收集器 | 100% |
### 测试文件(新)
| 文件 | 测试数 | 覆盖范围 |
|------|--------|---------|
| `test/goose-reviewer.test.ts` | 11 | 97.35% |
| `test/r2-storage.test.ts` | 22 | 100% |
| `test/triage-processor-extra.test.ts` | 11 | 已覆盖 |
| `test/webhook-processor-extra.test.ts` | 35 | 72.39% |
| `test/conflict-resolver-extra.test.ts` | 12 | 57.52% |
| `test/review-processor-extra.test.ts` | 7 | 49.42% |
| `test/retry-extra.test.ts` | 5 | 100% |
| `test/merge-guard.test.ts` | 5 | 100% |
| `test/failure-messages.test.ts` | 8 | 100% |
| `test/metrics-collector.test.ts` | 9 | 100% |
## 已落地项
| 里程碑 | 任务 | 状态 |
|--------|------|------|
| M0-1 | normalizeKnowledge 行尾归一 | ✅ |
| M0-2 | gooseReviewer 测试(26.57%→97.35%) | ✅ |
| M0-3 | r2 测试(49.01%→100%) | ✅ |
| M0-4 | triage 测试(56.77%→63.19%) | ✅ |
| M0-5 | webhook-processor 测试(63.90%→72.39%) | ✅ |
| M0-6 | conflict-resolver 测试(56.56%→57.52%) | ✅ |
| M0-7 | processor 测试(49.08%→49.42%) | ✅ |
| M1-1 | withRetry 智能重试(抖动+总超时) | ✅ |
| M1-3 | MergeGuard 合并防重入 | ✅ |
| M1-4 | failureMessages 失败分类 | ✅ |
| M2-2 | MetricsCollector 指标收集器 | ✅ |
## 未落地项
| 里程碑 | 任务 | 原因 |
|--------|------|------|
| M0-8 | 集成测试 | 需 testcontainers/MinIO 等基础设施 |
| M1-2 | 陈旧检测(stale detection) | processor.ts 未拆分前修改风险高 |
| M1-3 | MergeGuard 接 processor.ts | 需处理器拆分后接入 |
| M2-1 | 全链路日志贯穿 | 需处理器拆分后接入 |
| M3 | 大文件拆分(processor/conflictResolver) | 单独里程碑 |
| M4-M7 | 后续里程碑 | 逐步推进 |
## 下一阶段建议
1. 先提交当前成果(v2.0-alpha),推送到 origin
2. 第二阶段处理 processor.ts 拆分(M3),再补 M1-2 陈旧检测
3. 第三阶段做集成测试(M0-8)
+1 -2
View File
@@ -7,7 +7,7 @@
## 验证矩阵 ## 验证矩阵
| # | 场景 | 请求 | 期望 | 实际结果 | 状态 | | # | 场景 | 请求 | 期望 | 实际结果 | 状态 |
|---|------|------|------|----------|------| | --- | ------------- | ----------------------------------------------------------- | -------------------------------------------- | --------------------------------------------- | ---- |
| 1 | 服务启动 | `node dist/src/webhook/server.js`(`WEBHOOK_ENABLED=true`) | 监听 3000 | 日志输出 `GitHub webhook server is listening` | ✅ | | 1 | 服务启动 | `node dist/src/webhook/server.js`(`WEBHOOK_ENABLED=true`) | 监听 3000 | 日志输出 `GitHub webhook server is listening` | ✅ |
| 2 | 健康检查 | `GET /healthz` | 200 `{"ok":true,"webhook":true}` | 一致 | ✅ | | 2 | 健康检查 | `GET /healthz` | 200 `{"ok":true,"webhook":true}` | 一致 | ✅ |
| 3 | 指标端点 | `GET /metrics` | Prometheus 文本 + uptime | `ghbot_uptime_seconds 3` | ✅ | | 3 | 指标端点 | `GET /metrics` | Prometheus 文本 + uptime | `ghbot_uptime_seconds 3` | ✅ |
@@ -31,4 +31,3 @@ webhook 服务从启动 → 鉴权 → 去重 → 可观测性的完整链路在
## 回归(2026-08-23,PORT=3011,生产 dist) ## 回归(2026-08-23,PORT=3011,生产 dist)
同一矩阵在硬化改动后复测:healthz 200、合法 HMAC 202、坏签名 401、重复 delivery duplicate、metrics 三项计数正确。 同一矩阵在硬化改动后复测:healthz 200、合法 HMAC 202、坏签名 401、重复 delivery duplicate、metrics 三项计数正确。
+1 -1
View File
@@ -5,7 +5,7 @@
## 文档清单 ## 文档清单
| 文件 | 内容 | 适用场景 | | 文件 | 内容 | 适用场景 |
|------|------|----------| | ---------------------------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------- |
| [下一步改进指南.md](./下一步改进指南.md) | **主指南**:完整盘点、优先级决策树、P0~P6 改进项、里程碑落地计划、验证清单、禁止事项、附录 | 交给 AI 或人工按里程碑逐步落地代码改进 | | [下一步改进指南.md](./下一步改进指南.md) | **主指南**:完整盘点、优先级决策树、P0~P6 改进项、里程碑落地计划、验证清单、禁止事项、附录 | 交给 AI 或人工按里程碑逐步落地代码改进 |
| (待补充)改进方案详解.md | 每个改进项的技术选型、权衡分析、关键代码示意 | 需要更深入方案论证时创建 | | (待补充)改进方案详解.md | 每个改进项的技术选型、权衡分析、关键代码示意 | 需要更深入方案论证时创建 |
| (待补充)bug修复记录.md | 已修复缺陷(对应正文「10. 已知缺陷」表) | 每次修复后回填状态 | | (待补充)bug修复记录.md | 已修复缺陷(对应正文「10. 已知缺陷」表) | 每次修复后回填状态 |
+20 -6
View File
@@ -9,16 +9,19 @@
## 1. 研究分析(已完成) ## 1. 研究分析(已完成)
### 1.1 需求分解 ### 1.1 需求分解
- 修复基线:2 个失败测试 → 全绿 - 修复基线:2 个失败测试 → 全绿
- 落地指南中 P0~P6 可执行项 - 落地指南中 P0~P6 可执行项
- 真实 E2E(非 mock)验证 webhook 链路 - 真实 E2E(非 mock)验证 webhook 链路
- 推送 + 发行版 + CI 审计 - 推送 + 发行版 + CI 审计
### 1.2 代码考古 ### 1.2 代码考古
- 审查 `src/` 全部 28 个源文件、2 个 workflow、测试套件结构 - 审查 `src/` 全部 28 个源文件、2 个 workflow、测试套件结构
- 基线实测:typecheck 通过 / test 68 项 66 过 2 挂 - 基线实测:typecheck 通过 / test 68 项 66 过 2 挂
### 1.3 约束识别 ### 1.3 约束识别
- 安全红线不可动(AUTO_MERGE=false 等) - 安全红线不可动(AUTO_MERGE=false 等)
- Windows 环境(chmod 位映射差异) - Windows 环境(chmod 位映射差异)
- 无 linter/formatter 门禁(需新建) - 无 linter/formatter 门禁(需新建)
@@ -31,15 +34,17 @@
## 4. 执行日志 ## 4. 执行日志
### M0 基线恢复 ✅ ### M0 基线恢复 ✅
| 步骤 | 内容 | 结果 | | 步骤 | 内容 | 结果 |
|------|------|------| | --------------- | -------------------------- | ------------- |
| D-01 修复 | chmod 断言 POSIX-only 分支 | test 68/68 绿 | | D-01 修复 | chmod 断言 POSIX-only 分支 | test 68/68 绿 |
| ESLint/Prettier | flat config + 全量格式化 | lint 0 error | | ESLint/Prettier | flat config + 全量格式化 | lint 0 error |
| pre-commit | Node 版钩子防生成物入库 | 生效 | | pre-commit | Node 版钩子防生成物入库 | 生效 |
### M1 可靠性 ✅ ### M1 可靠性 ✅
| 步骤 | 对应指南项 | 结果 | | 步骤 | 对应指南项 | 结果 |
|------|-----------|------| | -------------- | ---------- | ------------------------------------- |
| retry 错误感知 | 4.1 | isRetryableError + 7 测试 | | retry 错误感知 | 4.1 | isRetryableError + 7 测试 |
| 评论命令隔离 | 4.2 | allSettled 并行容错 | | 评论命令隔离 | 4.2 | allSettled 并行容错 |
| 审查结果净化 | 4.3 | normalizeReviewDecision | | 审查结果净化 | 4.3 | normalizeReviewDecision |
@@ -48,28 +53,32 @@
| 测试补强 | 3.2 | 新增 9 个测试文件 | | 测试补强 | 3.2 | 新增 9 个测试文件 |
### M2 安全 ✅ ### M2 安全 ✅
| 步骤 | 对应指南项 | 结果 | | 步骤 | 对应指南项 | 结果 |
|------|-----------|------| | ------------ | ---------- | -------------------------------- |
| 共享脱敏清单 | 8.2/7.2 | sanitization.ts 单一来源 | | 共享脱敏清单 | 8.2/7.2 | sanitization.ts 单一来源 |
| 凭据掩码 | 8.4 | secrets.ts 复用于 knowledge 校验 | | 凭据掩码 | 8.4 | secrets.ts 复用于 knowledge 校验 |
| bot 身份判定 | 8.1 | comment.user.type==="Bot" 跳过 | | bot 身份判定 | 8.1 | comment.user.type==="Bot" 跳过 |
### M3 可观测性 ✅ ### M3 可观测性 ✅
| 步骤 | 对应指南项 | 结果 | | 步骤 | 对应指南项 | 结果 |
|------|-----------|------| | -------------- | ---------- | ----------------------------------- |
| metrics 注册表 | 5.2 | MetricsRegistry + Prometheus 序列化 | | metrics 注册表 | 5.2 | MetricsRegistry + Prometheus 序列化 |
| /metrics 端点 | 5.2 | webhook server 集成 | | /metrics 端点 | 5.2 | webhook server 集成 |
### M5 收口 ✅ ### M5 收口 ✅
| 步骤 | 结果 | | 步骤 | 结果 |
|------|------| | ------------------------ | ------------------------- |
| 版本 1.0.0 | package.json | | 版本 1.0.0 | package.json |
| 双语 README 开发门禁章节 | 已同步 | | 双语 README 开发门禁章节 | 已同步 |
| E2E 记录归档 | 计划与指南/E2E验证记录.md | | E2E 记录归档 | 计划与指南/E2E验证记录.md |
### 4.2 问题处理 ### 4.2 问题处理
| 问题 | 根因 | 解法 | | 问题 | 根因 | 解法 |
|------|------|------| | ---------------------------- | ------------------------------------- | -------------------------------------- |
| pre-commit 钩子崩溃 | 绝对路径含中文+空格被 sh 错误展开 | 改为仓库相对路径调用 | | pre-commit 钩子崩溃 | 绝对路径含中文+空格被 sh 错误展开 | 改为仓库相对路径调用 |
| eslint no-control-regex 误报 | Git ref 正则/ANSI 剥离需要控制字符 | disable-next-line + 理由注释 | | eslint no-control-regex 误报 | Git ref 正则/ANSI 剥离需要控制字符 | disable-next-line + 理由注释 |
| retry 测试超时 10s | 默认 maxAttempts=5 未覆盖 | 显式传 {maxAttempts:3} | | retry 测试超时 10s | 默认 maxAttempts=5 未覆盖 | 显式传 {maxAttempts:3} |
@@ -108,20 +117,24 @@ PR Review Bot schedule: success
## 5. 回顾总结 ## 5. 回顾总结
### 5.1 成果验证 ### 5.1 成果验证
- 19 个原子提交全部落地并推送 - 19 个原子提交全部落地并推送
- 测试 68 → 134(+97%),全绿 - 测试 68 → 134(+97%),全绿
- 指南 P0/P1/P2/P3(部分)/P6(部分)/安全项完成 - 指南 P0/P1/P2/P3(部分)/P6(部分)/安全项完成
### 5.2 变更摘要 ### 5.2 变更摘要
- **新增**:src/review/normalize.ts、src/security/{sanitization,secrets}.ts、src/webhook/metrics.ts、eslint.config.js、.prettierrc.json、.github/workflows/ci.yml、scripts/*.cjs、test/ 下 12 个新测试文件、《计划与指南/》文档集 - **新增**:src/review/normalize.ts、src/security/{sanitization,secrets}.ts、src/webhook/metrics.ts、eslint.config.js、.prettierrc.json、.github/workflows/ci.yml、scripts/*.cjs、test/ 下 12 个新测试文件、《计划与指南/》文档集
- **修改**:retry.ts(错误感知)、runReview.ts(三链路隔离+bot跳过)、processor.ts(合并幂等)、gooseReviewer.ts(净化接线)、chat/processor.ts 与 conflictResolver.ts(共享清单)、webhook/server.ts(重试+metrics)、storage/cacheStore.ts(pullNumber 校验)、r2.ts(export normalizeEndpoint)、knowledge.ts(共享密钥校验)、双语 README、package.json(v1.0.0+脚本) - **修改**:retry.ts(错误感知)、runReview.ts(三链路隔离+bot跳过)、processor.ts(合并幂等)、gooseReviewer.ts(净化接线)、chat/processor.ts 与 conflictResolver.ts(共享清单)、webhook/server.ts(重试+metrics)、storage/cacheStore.ts(pullNumber 校验)、r2.ts(export normalizeEndpoint)、knowledge.ts(共享密钥校验)、双语 README、package.json(v1.0.0+脚本)
### 5.3 质量报告 ### 5.3 质量报告
- 覆盖率:总体 61.6% → 核心模块(policy/prompt/diff/retry/sanitization/secrets/normalize/format)100%,cacheStore 95%,knowledge 98.8% - 覆盖率:总体 61.6% → 核心模块(policy/prompt/diff/retry/sanitization/secrets/normalize/format)100%,cacheStore 95%,knowledge 98.8%
- 安全审计:0 高危漏洞;凭据红线全程未触碰 - 安全审计:0 高危漏洞;凭据红线全程未触碰
- 技术债务:processor.ts 编排函数覆盖率仍偏低(49%),已在指南标注后续方向(事件路由器解耦 7.1) - 技术债务:processor.ts 编排函数覆盖率仍偏低(49%),已在指南标注后续方向(事件路由器解耦 7.1)
### 5.4 经验总结 ### 5.4 经验总结
1. Windows 权限位断言必须平台分支——chmod 在 NTFS 上只映射 rw 位 1. Windows 权限位断言必须平台分支——chmod 在 NTFS 上只映射 rw 位
2. git hooks 内避免绝对路径(中文/空格目录),用仓库相对路径最稳 2. git hooks 内避免绝对路径(中文/空格目录),用仓库相对路径最稳
3. withRetry 加错误分类后,测试必须显式传小 maxAttempts 否则退避拖慢套件 3. withRetry 加错误分类后,测试必须显式传小 maxAttempts 否则退避拖慢套件
@@ -129,6 +142,7 @@ PR Review Bot schedule: success
5. bash heredoc 中嵌入 markdown 代码块会触发命令替换——README 批量注入用 Edit 工具更可靠 5. bash heredoc 中嵌入 markdown 代码块会触发命令替换——README 批量注入用 Edit 工具更可靠
### 交付物链接 ### 交付物链接
- 仓库: https://github.com/lza6/ghbot-Nodeloc (main @ dc3736a) - 仓库: https://github.com/lza6/ghbot-Nodeloc (main @ dc3736a)
- 发行版: https://github.com/lza6/ghbot-Nodeloc/releases/tag/v1.0.0 - 发行版: https://github.com/lza6/ghbot-Nodeloc/releases/tag/v1.0.0
- CI: run 32574065674 success - CI: run 32574065674 success
@@ -9,6 +9,7 @@
## 1. 研究分析(已完成) ## 1. 研究分析(已完成)
v1.0.0 后指南中仍未落地项盘点: v1.0.0 后指南中仍未落地项盘点:
- D-02(三处 listPullRequestFiles 重复) - D-02(三处 listPullRequestFiles 重复)
- D-09(redactProcessArgs 脆弱索引)、D-13(运行时目录硬编码) - D-09(redactProcessArgs 脆弱索引)、D-13(运行时目录硬编码)
- 6.1(审查输出排版)、6.3(命令 ack 反馈)、8.4(错误输出脱敏接线) - 6.1(审查输出排版)、6.3(命令 ack 反馈)、8.4(错误输出脱敏接线)
@@ -20,7 +21,7 @@ v1.0.0 后指南中仍未落地项盘点:
## 4. 执行日志(全部完成 ✅) ## 4. 执行日志(全部完成 ✅)
| 提交 | 指南项 | 内容 | 验证 | | 提交 | 指南项 | 内容 | 验证 |
|------|--------|------|------| | ------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------- | ------------- |
| `941e1d2` | D-02 | 三处重复函数统一到 `src/github/pulls.ts` | test 134 全绿 | | `941e1d2` | D-02 | 三处重复函数统一到 `src/github/pulls.ts` | test 134 全绿 |
| `d9666c9` | D-13 | `GHBOT_RUNTIME_DIR` + `src/runtimePaths.ts` 集中目录;cacheStore/gooseCli/chat/conflictResolver/cache 五处接入;+3 测试 | test 137 全绿 | | `d9666c9` | D-13 | `GHBOT_RUNTIME_DIR` + `src/runtimePaths.ts` 集中目录;cacheStore/gooseCli/chat/conflictResolver/cache 五处接入;+3 测试 | test 137 全绿 |
| `a35587e` | 6.1 | 状态横幅 + `<details>` 折叠 + 加粗计数;format 测试扩展断言 | test 137 全绿 | | `a35587e` | 6.1 | 状态横幅 + `<details>` 折叠 + 加粗计数;format 测试扩展断言 | test 137 全绿 |
@@ -59,15 +60,18 @@ CI run 32617043840 (push main): typecheck-lint-test → success (35s)
## 5. 回顾总结 ## 5. 回顾总结
### 成果 ### 成果
- 指南缺陷表 D-02/D-09/D-13 全部关闭;6.1/6.3/8.4 三项体验与安全项落地 - 指南缺陷表 D-02/D-09/D-13 全部关闭;6.1/6.3/8.4 三项体验与安全项落地
- 测试 134 → 142;总体覆盖率 61.64% → 62.51% - 测试 134 → 142;总体覆盖率 61.64% → 62.51%
### 经验 ### 经验
1. node -e 内联脚本做跨文件批量替换时,正则转义极易失配——复杂替换改用 Edit 工具更可靠(8.4 第一次替换静默失败即为教训) 1. node -e 内联脚本做跨文件批量替换时,正则转义极易失配——复杂替换改用 Edit 工具更可靠(8.4 第一次替换静默失败即为教训)
2. 改共享函数签名时必须同轮 grep 所有测试调用点,否则出现"实现绿、旧测试红" 2. 改共享函数签名时必须同轮 grep 所有测试调用点,否则出现"实现绿、旧测试红"
3. Windows 下后台启动服务后立即 curl 可能撞上启动窗口,sleep 2 重试即可,不必重启 3. Windows 下后台启动服务后立即 curl 可能撞上启动窗口,sleep 2 重试即可,不必重启
### 剩余建议(下一轮候选) ### 剩余建议(下一轮候选)
- 7.1 事件路由器解耦(processor.ts 编排覆盖率的根本解法) - 7.1 事件路由器解耦(processor.ts 编排覆盖率的根本解法)
- 6.4 语言字典(BOT_REPLY_LANGUAGE) - 6.4 语言字典(BOT_REPLY_LANGUAGE)
- 8.5 goose CLI 校验和固定下载 - 8.5 goose CLI 校验和固定下载
File diff suppressed because it is too large. Load diff