npm package: @schafevormfenster/rest-commons
Description: Centralized authority for REST standards and schemas - XSD schemas, parsing functions, and coding instructions
Latest version: 0.1.10

# @schafevormfenster/rest-commons

> Centralized authority for REST API standards and schemas

[![npm version](https://img.shields.io/npm/v/@schafevormfenster/rest-commons.svg)](https://www.npmjs.com/package/@schafevormfenster/rest-commons)
[![License](https://img.shields.io/npm/l/@schafevormfenster/rest-commons.svg)](LICENSE)

## What is this package?

**@schafevormfenster/rest-commons** is the central repository for REST API standards, schemas, and utilities used across all @schafevormfenster services. It provides a standardized foundation for building consistent, type-safe REST APIs with built-in validation, security, and best practices.

Think of it as the **"XSD for REST APIs"** - a single source of truth for API contracts, data structures, and validation rules.

## Why does this package exist?

### The Problem

Without centralized standards, REST APIs often suffer from:

- **Inconsistent response formats** across different endpoints
- **Duplicated validation logic** in multiple services
- **Type mismatches** between client and server
- **Security vulnerabilities** from inadequate input validation
- **Poor API documentation** due to lack of standard structures
- **Maintenance burden** when response formats need to change

### The Solution

This package provides:

1. **Standardized Response Schemas**: Consistent wrappers for all API responses (success, error, collections, health checks)
2. **Reusable Primitive Schemas**: Common data types (UUID, slug, location, timestamps) that work across all services
3. **Type-Safe Validation**: Runtime validation with Zod that automatically generates TypeScript types
4. **Security Utilities**: Input sanitization, suspicious pattern detection, and validation helpers
5. **Time Handling**: Robust ISO 8601 support, relative time parsing, and timezone handling
6. **Response Utilities**: Correlation IDs, standardized headers, and environment detection

## What problems does it solve?

### 1. Response Consistency

**Before**: Every service defines its own response format
```typescript
// Service A
{ data: {...}, success: true }

// Service B
{ result: {...}, status: "ok" }

// Service C
{ body: {...}, code: 200 }
```

**After**: All services use standard response schemas
```typescript
// All services
{
  status: 200,
  timestamp: "2024-01-15T10:30:00.000Z",
  data: {...}
}
```

### 2. Type Safety

**Before**: Manual type definitions that can drift from runtime validation
```typescript
// Types might not match actual validation
type User = { id: string; name: string };
// Validation is separate and can diverge
const validateUser = (data: any) => { ... };
```

**After**: Single source of truth with Zod
```typescript
// Schema and type are always in sync
export const UserSchema = z.object({
  id: z.string().uuid(),
  name: z.string().min(1),
});
export type User = z.infer<typeof UserSchema>;
```

### 3. Code Reusability

**Before**: Every service implements its own validation
```typescript
// Service A
function validateUUID(id: string) { ... }

// Service B (duplicate implementation)
function validateUUID(id: string) { ... }
```

**After**: Import and reuse from commons
```typescript
import { UuidSchema } from "@schafevormfenster/rest-commons";

const validated = UuidSchema.parse(id);
```

### 4. Security & Validation

**Before**: Inconsistent or missing security checks
```typescript
// Some services check for suspicious patterns, others don't
```

**After**: Built-in security utilities
```typescript
import { detectSuspiciousPatterns } from "@schafevormfenster/rest-commons";

if (detectSuspiciousPatterns(userInput)) {
  throw new ValidationError("Invalid input detected");
}
```

### 5. API Documentation

**Before**: Manual documentation that quickly becomes outdated
```markdown
## Response Format
Returns a JSON object with...
```

**After**: Self-documenting schemas
```typescript
// Schema serves as executable documentation
export const MyResponseSchema = ResultSchema.extend({
  data: MyDataSchema,
});
// Automatically generates OpenAPI spec, TypeScript types, and validation
```

## When should you use this package?

Use **@schafevormfenster/rest-commons** when you:

- ✅ Build REST APIs in the @schafevormfenster ecosystem
- ✅ Need standardized response formats
- ✅ Want type-safe validation with Zod
- ✅ Require input sanitization and security checks
- ✅ Need to handle ISO 8601 timestamps or relative time
- ✅ Want consistent error handling across services
- ✅ Need correlation IDs for request tracing

Don't use this package if you:

- ❌ Build GraphQL APIs (use appropriate GraphQL schema tools)
- ❌ Work outside the @schafevormfenster ecosystem (fork and adapt instead)
- ❌ Need real-time WebSocket protocols (this is for REST only)

## What's included?

### Core Response Schemas

- **ResultSchema**: Single resource responses
- **ResultsSchema**: Collection responses
- **ErrorSchema**: Standardized error responses
- **HealthSchema**: Service health checks
- **OkaySchema**: Simple success acknowledgments

### Primitive Schemas

- **UuidSchema**: UUID validation
- **SlugSchema**: URL-safe slugs
- **LocationSchema**: Geographic locations
- **ISO8601Schema**: Timestamp validation
- **RelativeTimeSchema**: Relative time expressions
- And more...

### Utilities

- **Time Handling**: ISO 8601 parsing, relative time, week boundaries
- **Validation**: Suspicious pattern detection, parameter validation
- **Normalization**: List normalization, location normalization
- **Response Helpers**: Correlation IDs, header builders, environment detection

## Installation

```bash
pnpm add @schafevormfenster/rest-commons
```

### TypeScript Sources (Optional)

For faster development with Vite, use TypeScript sources directly:

```typescript
// vite.config.ts - Requires tsconfig "target": "ES2022"+
export default defineConfig({
  resolve: { conditions: ['source', 'import', 'default'] }
});
```

Benefits: Faster HMR, direct debugging, better tree-shaking.

## Quick Start

```typescript
import {
  ResultSchema,
  ErrorSchema,
  UuidSchema,
  detectSuspiciousPatterns,
  getCorrelationId,
} from "@schafevormfenster/rest-commons";

// Define your data schema
const UserSchema = z.object({
  id: UuidSchema,
  name: z.string(),
  email: z.string().email(),
});

// Create response schema
const UserResponseSchema = ResultSchema.extend({
  data: UserSchema,
});

// Use in your API route
export async function GET(request: Request) {
  const correlationId = getCorrelationId(request);
  
  // Your business logic here
  const user = await fetchUser();
  
  // Validate and return
  const response = UserResponseSchema.parse({
    status: 200,
    timestamp: new Date().toISOString(),
    data: user,
  });
  
  return Response.json(response);
}
```

## Documentation

For detailed implementation guides and best practices, see:

- **[CONTRIBUTING.md](./CONTRIBUTING.md)** - How to use this package and develop REST endpoints
- **[REST Service Design Guide](../eslint-plugin/docs/rest-service-design-guide.md)** - Architectural patterns
- **[E2E Testing Guide](../eslint-plugin/docs/instructions/rest-api-e2e-testing-guide.md)** - Testing patterns
- **[Tech Stack](../eslint-plugin/docs/instructions/tech-stack.md)** - Technology choices

## Key Principles

This package embodies these principles:

1. **Contract-First Development**: Define schemas before implementation
2. **Type Safety**: Runtime validation generates compile-time types
3. **Consistency**: Standardized formats across all services
4. **Security**: Built-in input validation and sanitization
5. **Observability**: Correlation IDs and structured responses
6. **Developer Experience**: Self-documenting, autocomplete-friendly APIs

## Tech Stack

This package is built with:

- **Zod**: Schema validation and type inference
- **TypeScript**: Type-safe development
- **Vitest**: Unit testing
- **ESLint**: Code quality enforcement

## Contributing

This package is part of the @schafevormfenster monorepo. For contribution guidelines, see:

- [CONTRIBUTING.md](./CONTRIBUTING.md) - Development guide for this package
- Root monorepo CONTRIBUTING.md - General contribution guidelines

## Related Packages

- **@schafevormfenster/eslint-plugin**: Custom ESLint rules for REST APIs
- **@schafevormfenster/eslint-config**: ESLint configurations for the monorepo
- **@schafevormfenster/logging**: Structured logging utilities
- **@schafevormfenster/security**: Security helpers and utilities

## License

See the root LICENSE file for license information.

---

**Built with ❤️ by the Schafe vorm Fenster team**