---
created: 2025-10-10T11:28:08Z
last_updated: 2025-10-20T15:02:39Z
version: 1.1
author: Claude Code PM System
---

# Project Style Guide

## Lint Standards (Updated October 2025)

**Zero Tolerance Policy**: All production code must pass ESLint with `--max-warnings=0`. See `CONTRIBUTING.md` and `docs/LINT_RULES_RATIONALE.md` for complete details.

### Enforced Quality Rules

**Type Safety** (ERROR level):
- `@typescript-eslint/no-explicit-any` - Avoid `any` types, use proper typing
- `@typescript-eslint/await-thenable` - Only await promises
- Prefer specific types over `any`: `unknown`, `Record<string, unknown>`, or proper interfaces

**Async Safety** (ERROR level):
- `@typescript-eslint/no-floating-promises` - All promises must be awaited or explicitly voided
- `@typescript-eslint/no-misused-promises` - Promises only in async contexts
- Use IIFE void pattern for fire-and-forget: `void (async () => { ... })()`

**Code Cleanliness** (ERROR level):
- `@typescript-eslint/no-unused-vars` - No unused variables or imports
- Prefix intentionally unused params with underscore: `_unused`
- Remove dead code immediately

**String Safety** (ERROR level):
- `no-template-curly-in-string` - Catch template literal errors

### Common Patterns

**Fire-and-Forget Async** (event handlers, callbacks):
```typescript
// ✅ Good: IIFE void pattern
button.addEventListener('click', () => {
  void (async () => {
    await processClick();
  })();
});

// ❌ Bad: Floating promise
button.addEventListener('click', async () => {
  await processClick(); // ESLint error
});
```

**Intentional Unused Variables**:
```typescript
// ✅ Good: Underscore prefix
const _unusedForNow = computeValue();
function handler(_event: Event) { ... }

// ❌ Bad: Unprefixed unused
const unusedValue = computeValue(); // ESLint error
```

**Type Safety**:
```typescript
// ✅ Good: Proper typing
const data: Record<string, unknown> = JSON.parse(str);
const user = data as UserProfile;

// ❌ Bad: any type
const data: any = JSON.parse(str); // ESLint error
```

## TypeScript/JavaScript Conventions

### File Naming

**TypeScript/JavaScript Files**:
- Use kebab-case for file names: `user-service.ts`, `data-mapper.ts`
- Component files: `UserProfile.tsx` (PascalCase for React components)
- Test files: `user-service.spec.ts` or `user-service.test.ts`
- Type definition files: `user-types.ts` or `types.ts`
- Configuration files: `jest.config.js`, `tsconfig.json`

**Examples**:
```
✅ Good:
- apps/slide-system/src/lib/slidev-generator.ts
- libs/shared/utils/src/lib/api-client.ts
- apps/demos/src/components/DemoCard.tsx

❌ Avoid:
- slideVGenerator.ts (camelCase)
- Slidev_Generator.ts (snake_case with caps)
- democard.tsx (lowercase component)
```

### Variable Naming

**General Rules**:
- Use camelCase for variables and functions
- Use PascalCase for classes, interfaces, types, and React components
- Use UPPER_SNAKE_CASE for constants
- Prefix private properties with underscore: `_privateField`
- Prefix boolean variables with `is`, `has`, `should`: `isLoading`, `hasError`

**Examples**:
```typescript
// Variables and functions
const userId = 'user-123';
const generatePresentation = async () => { ... };

// Classes and types
class UserService { ... }
interface UserProfile { ... }
type SessionState = 'active' | 'inactive';

// React components
const UserProfileCard = () => { ... };

// Constants
const MAX_RETRY_ATTEMPTS = 3;
const API_BASE_URL = process.env.API_URL;

// Booleans
const isAuthenticated = true;
const hasPermission = checkPermission();
const shouldRender = isVisible && hasData;

// Private fields
class ApiClient {
  private _apiKey: string;
  private _rateLimiter: RateLimiter;
}
```

### Function Style

**Prefer arrow functions** for consistency:
```typescript
// ✅ Good
const calculateTotal = (items: Item[]): number => {
  return items.reduce((sum, item) => sum + item.price, 0);
};

// ✅ Also good for async
const fetchUser = async (id: string): Promise<User> => {
  const response = await api.get(`/users/${id}`);
  return response.data;
};

// ❌ Avoid (unless needed for 'this' binding)
function calculateTotal(items: Item[]): number {
  return items.reduce((sum, item) => sum + item.price, 0);
}
```

**Small, focused functions**:
```typescript
// ✅ Good - single responsibility
const validateEmail = (email: string): boolean => {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
};

const sendEmail = async (to: string, subject: string, body: string) => {
  if (!validateEmail(to)) {
    throw new Error('Invalid email address');
  }
  await emailService.send({ to, subject, body });
};

// ❌ Avoid - too many responsibilities
const validateAndSendEmail = async (email: string, subject: string, body: string) => {
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    throw new Error('Invalid email');
  }
  const user = await getUserByEmail(email);
  if (!user.emailVerified) {
    await sendVerificationEmail(user);
  }
  await emailService.send({ to: email, subject, body });
  await logEmailSent(email, subject);
};
```

### Type Safety

**Always use explicit types**:
```typescript
// ✅ Good
const fetchSession = async (id: string): Promise<Session> => {
  const response = await api.get<SessionResponse>(`/sessions/${id}`);
  return mapSessionResponse(response.data);
};

interface Session {
  id: string;
  userId: string;
  createdAt: Date;
  expiresAt: Date;
}

// ❌ Avoid
const fetchSession = async (id) => {
  const response = await api.get(`/sessions/${id}`);
  return response.data;
};
```

**Prefer interfaces for objects, types for unions/primitives**:
```typescript
// ✅ Good
interface User {
  id: string;
  name: string;
  email: string;
}

type UserRole = 'admin' | 'user' | 'guest';
type UserId = string;

// ❌ Less preferred
type User = {
  id: string;
  name: string;
  email: string;
};
```

### Async/Await

**Always use async/await** over promises:
```typescript
// ✅ Good
const processData = async () => {
  try {
    const data = await fetchData();
    const processed = await processData(data);
    await saveData(processed);
    return processed;
  } catch (error) {
    logger.error('Failed to process data', { error });
    throw error;
  }
};

// ❌ Avoid
const processData = () => {
  return fetchData()
    .then(data => processData(data))
    .then(processed => saveData(processed))
    .catch(error => {
      logger.error('Failed to process data', { error });
      throw error;
    });
};
```

## React Conventions

### Component Structure

**Functional components with hooks**:
```typescript
// ✅ Good structure
import { useState, useEffect } from 'react';
import { logger } from '@buzztrail/shared/utils';

interface UserProfileProps {
  userId: string;
  onUpdate?: (user: User) => void;
}

export const UserProfile = ({ userId, onUpdate }: UserProfileProps) => {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    const fetchUser = async () => {
      try {
        const userData = await api.getUser(userId);
        setUser(userData);
      } catch (err) {
        logger.error('Failed to fetch user', { userId, error: err });
        setError(err as Error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchUser();
  }, [userId]);

  if (isLoading) return <LoadingSpinner />;
  if (error) return <ErrorMessage error={error} />;
  if (!user) return null;

  return (
    <div className="user-profile">
      <h2>{user.name}</h2>
      <p>{user.email}</p>
    </div>
  );
};
```

### Custom Hooks

**Prefix with 'use'**:
```typescript
// ✅ Good
const useUser = (userId: string) => {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // fetch user
  }, [userId]);

  return { user, isLoading };
};

// Usage
const { user, isLoading } = useUser(userId);
```

### Props Destructuring

**Destructure in function signature**:
```typescript
// ✅ Good
const Button = ({ label, onClick, disabled = false }: ButtonProps) => {
  return <button onClick={onClick} disabled={disabled}>{label}</button>;
};

// ❌ Avoid
const Button = (props: ButtonProps) => {
  return <button onClick={props.onClick} disabled={props.disabled}>
    {props.label}
  </button>;
};
```

## Code Organization

### Import Order

```typescript
// 1. External libraries (React, third-party)
import { useState, useEffect } from 'react';
import axios from 'axios';

// 2. Internal libraries (@buzztrail/*)
import { logger } from '@buzztrail/shared/utils';
import { Button } from '@buzztrail/shared/components';

// 3. Relative imports
import { UserService } from './user-service';
import { validateEmail } from '../utils/validation';
import type { User } from '../types';

// 4. CSS/styling (if applicable)
import './styles.css';
```

### File Structure Pattern

```typescript
// types.ts - Type definitions
export interface User {
  id: string;
  name: string;
  email: string;
}

// constants.ts - Constants
export const MAX_USERS = 100;
export const DEFAULT_TIMEOUT = 30000;

// utils.ts - Utility functions
export const formatUserName = (user: User): string => {
  return `${user.name} (${user.email})`;
};

// service.ts - Business logic
export class UserService {
  async getUser(id: string): Promise<User> {
    // implementation
  }
}

// component.tsx - React component
export const UserList = () => {
  // implementation
};

// index.ts - Public exports
export * from './types';
export * from './service';
export { UserList } from './component';
```

## Error Handling

### Consistent Error Handling

```typescript
// ✅ Good - structured error handling
const processRequest = async (data: RequestData) => {
  try {
    validateInput(data);
    const result = await performOperation(data);
    return { success: true, data: result };
  } catch (error) {
    logger.error('Request processing failed', {
      error,
      data,
      timestamp: new Date().toISOString()
    });

    if (error instanceof ValidationError) {
      throw new ApplicationError('Invalid input data', error);
    }

    throw new ApplicationError('Request processing failed', error);
  }
};

// ❌ Avoid - swallowing errors
const processRequest = async (data: RequestData) => {
  try {
    return await performOperation(data);
  } catch (error) {
    console.log('Error:', error);
    return null;
  }
};
```

## Logging

### Structured Logging

```typescript
// ✅ Good
logger.info('User session created', {
  userId: user.id,
  sessionId: session.id,
  timestamp: new Date().toISOString(),
  ipAddress: request.ip
});

logger.error('Database connection failed', {
  error: error.message,
  stack: error.stack,
  connectionString: sanitizeConnectionString(config.db.url)
});

// ❌ Avoid
console.log('User session created');
console.log('Error:', error);
```

## Comments and Documentation

### JSDoc for Public APIs

```typescript
/**
 * Generates a Slidev presentation from a template.
 *
 * @param templateId - The ID of the template to use
 * @param data - Data to inject into the template
 * @param options - Optional generation configuration
 * @returns The generated deck information
 * @throws {ValidationError} If template or data is invalid
 * @throws {GenerationError} If generation fails
 *
 * @example
 * ```typescript
 * const deck = await generatePresentation('starter', {
 *   company: 'Acme Corp',
 *   slides: [{ title: 'Welcome' }]
 * });
 * ```
 */
export const generatePresentation = async (
  templateId: string,
  data: TemplateData,
  options?: GenerationOptions
): Promise<Deck> => {
  // implementation
};
```

### Inline Comments

```typescript
// ✅ Good - explain WHY, not WHAT
// Retry with exponential backoff due to rate limiting
const result = await retryWithBackoff(apiCall, 3);

// Clear TODO comments with context
// TODO(username): Add caching layer once Redis is configured (#123)

// ❌ Avoid - obvious comments
// Increment counter by 1
counter++;

// Call API
const data = await api.fetch();
```

## Testing Conventions

### Test File Structure

```typescript
// user-service.spec.ts
describe('UserService', () => {
  let service: UserService;

  beforeEach(() => {
    service = new UserService();
  });

  describe('getUser', () => {
    it('should return user when found', async () => {
      const userId = 'user-123';
      const user = await service.getUser(userId);

      expect(user).toBeDefined();
      expect(user.id).toBe(userId);
    });

    it('should throw error when user not found', async () => {
      await expect(service.getUser('invalid')).rejects.toThrow();
    });
  });
});
```

### Test Naming

```typescript
// ✅ Good - descriptive test names
it('should generate presentation in less than 60 seconds', async () => {
  // test
});

it('should retry failed requests up to 3 times', async () => {
  // test
});

// ❌ Avoid - vague names
it('works', () => {
  // test
});

it('test1', () => {
  // test
});
```

## Git Commit Conventions

### Commit Message Format

```
<type>: <subject>

<body>

<footer>
```

**Types**:
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation changes
- `style`: Code style changes (formatting, etc.)
- `refactor`: Code refactoring
- `test`: Adding or updating tests
- `chore`: Maintenance tasks

**Examples**:
```
✅ Good:
feat: Add real-time presentation control API

Implement POST /api/slidev/control endpoint that broadcasts
commands to all viewers via Supabase realtime channels.

Closes #42

fix: Prevent race condition in session creation

Add mutex lock around session creation to prevent duplicate
sessions when multiple requests arrive simultaneously.

---

❌ Avoid:
Updated files
Fixed bug
Changes
```

## Code Review Standards

### Required Checks
- ✅ All tests passing
- ✅ No TypeScript errors
- ✅ No linting errors
- ✅ Performance acceptable
- ✅ Security considerations addressed
- ✅ Documentation updated

### Review Focus
- Code clarity and readability
- Error handling completeness
- Test coverage adequacy
- Performance implications
- Security vulnerabilities
- Breaking changes documented

## Performance Guidelines

### Avoid Premature Optimization
```typescript
// ✅ Good - clear and maintainable
const total = items.reduce((sum, item) => sum + item.price, 0);

// ❌ Avoid - premature optimization
let total = 0;
const len = items.length;
for (let i = 0; i < len; i++) {
  total += items[i].price;
}
```

### Optimize Hot Paths
```typescript
// ✅ Good - memoized expensive computation
const ExpensiveComponent = React.memo(({ data }: Props) => {
  const processedData = useMemo(() => {
    return expensiveComputation(data);
  }, [data]);

  return <div>{processedData}</div>;
});
```

## Security Best Practices

### Input Validation
```typescript
// ✅ Good
const createUser = async (input: unknown) => {
  const validated = UserSchema.parse(input);
  return await db.users.create(validated);
};

// ❌ Avoid
const createUser = async (input: any) => {
  return await db.users.create(input);
};
```

### Never Log Sensitive Data
```typescript
// ✅ Good
logger.info('User authenticated', {
  userId: user.id,
  email: maskEmail(user.email)
});

// ❌ Avoid
logger.info('User authenticated', {
  userId: user.id,
  email: user.email,
  password: user.password // NEVER!
});
```

## Accessibility

### Semantic HTML
```typescript
// ✅ Good
<button onClick={handleClick}>
  Click me
</button>

// ❌ Avoid
<div onClick={handleClick}>
  Click me
</div>
```

### ARIA Labels
```typescript
// ✅ Good
<button aria-label="Close dialog" onClick={onClose}>
  ×
</button>
```

## Final Notes

- **Consistency over preference**: Follow existing patterns
- **Readability first**: Code is read more than written
- **Test thoroughly**: Write tests for critical paths
- **Document decisions**: Explain non-obvious choices
- **Keep it simple**: Simpler is usually better
