# Technology Stack

> Complete guide to every technology used in Izri and why we chose it

## 📊 Stack at a Glance

| Category | Technology | Version | Purpose |
|----------|-----------|---------|---------|
| **Frontend Framework** | React Router | v7 | Modern React framework with SSR |
| **UI Library** | React | v19 | User interface components |
| **Styling** | Tailwind CSS | v3 | Utility-first CSS framework |
| **Component Library** | shadcn/ui | Latest | Accessible UI components |
| **Build Tool** | Vite | v6 | Fast build and dev server |
| **Backend Framework** | Hono | v4 | Lightweight web framework |
| **API Layer** | tRPC | v11 | Type-safe RPC framework |
| **ORM** | Drizzle ORM | Latest | TypeScript-first ORM |
| **Database** | PostgreSQL | 15 | Relational database |
| **Cache** | Redis | 7 | In-memory data store |
| **AI Backend** | FastAPI | Latest | Python async framework |
| **Runtime** | Node.js | 18+ | JavaScript runtime |
| **Package Manager** | pnpm | 10+ | Fast, disk-efficient PM |
| **Monorepo Tool** | Turbo | v2 | Build system orchestrator |
| **Language** | TypeScript | 5.3+ | Static type checking |

## 🎨 Frontend Technologies

### React Router v7

**What it is**: Modern full-stack React framework with file-based routing

**Why we chose it**:

- ✅ Server-side rendering ready
- ✅ File-based routing with excellent DX
- ✅ Built-in data loading patterns
- ✅ Better bundle optimization than competitors
- ✅ Active development and community
- ✅ Smooth migration path from React Router v6

**Alternatives considered**:

- Next.js: Too opinionated, vendor lock-in concerns
- Remix: React Router v7 is the evolution of Remix
- Create React App: No SSR, deprecated

**Key Features**:

```typescript
// Type-safe route definitions
import { type Route } from "./+types/projects"

export async function loader({ params }: Route.LoaderArgs) {
  return { project: await getProject(params.id) }
}

export default function Project({ loaderData }: Route.ComponentProps) {
  return <div>{loaderData.project.name}</div>
}
```

### React 19

**What it is**: Latest version of the React library

**Why we use it**:

- ✅ Improved concurrent features
- ✅ Better server components support
- ✅ Enhanced performance
- ✅ New compiler optimizations

### Tailwind CSS

**What it is**: Utility-first CSS framework

**Why we chose it**:

- ✅ Rapid UI development
- ✅ Consistent design system
- ✅ Small production bundle (purged)
- ✅ No CSS naming conflicts
- ✅ Excellent IntelliSense support

**Configuration**:

```javascript
// tailwind.config.js
export default {
  content: ['./app/**/*.{js,jsx,ts,tsx}'],
  theme: {
    extend: {
      colors: {
        // Custom brand colors
      }
    }
  }
}
```

### shadcn/ui

**What it is**: Copy-paste component library built on Radix UI

**Why we chose it**:

- ✅ Accessible by default (Radix UI)
- ✅ Fully customizable (you own the code)
- ✅ Consistent with Tailwind
- ✅ No runtime dependency bloat
- ✅ TypeScript support

**Components used**:

- Button, Input, Select, Dialog
- Table, Card, Badge, Avatar
- DropdownMenu, Tooltip, Toast
- Form components with validation

### Vite

**What it is**: Next-generation frontend build tool

**Why we use it**:

- ✅ Lightning-fast HMR (<100ms)
- ✅ ESM-based dev server
- ✅ Optimized production builds
- ✅ Built-in TypeScript support
- ✅ Rich plugin ecosystem

## ⚙️ Backend Technologies

### Hono

**What it is**: Ultra-fast web framework for edge and Node.js

**Why we chose it**:

- ✅ Fastest Node.js framework (benchmarks)
- ✅ Express-like API (familiar)
- ✅ Excellent TypeScript support
- ✅ Built-in middleware ecosystem
- ✅ Edge runtime compatible
- ✅ Tiny bundle size (~10KB)

**Alternatives considered**:

- Express: Slower, older architecture
- Fastify: Good but more complex
- Koa: Less active community

**Example**:

```typescript
import { Hono } from 'hono'
import { logger } from 'hono/logger'
import { cors } from 'hono/cors'

const app = new Hono()
app.use('*', logger())
app.use('*', cors())

app.get('/health', (c) => c.json({ status: 'ok' }))
```

### tRPC

**What it is**: End-to-end type-safe RPC framework

**Why we chose it**:

- ✅ **No code generation needed**
- ✅ Full type safety from DB to UI
- ✅ Excellent DX with autocomplete
- ✅ Automatic request/response validation
- ✅ Built-in error handling
- ✅ WebSocket support

**Alternatives considered**:

- REST: No type safety, boilerplate
- GraphQL: Code generation, complexity
- gRPC: Protocol buffers, overkill

**Architecture**:

```typescript
// Backend: Define procedures
export const projectRouter = router({
  list: publicProcedure.query(async ({ ctx }) => {
    return ctx.db.select().from(projects)
  }),
  
  create: protectedProcedure
    .input(createProjectSchema)
    .mutation(async ({ ctx, input }) => {
      return ctx.db.insert(projects).values(input)
    })
})

// Frontend: Type-safe calls
const projects = await trpc.projects.list.query()
await trpc.projects.create.mutate({ name: 'New Project' })
```

### Drizzle ORM

**What it is**: TypeScript ORM that feels like writing SQL

**Why we chose it**:

- ✅ SQL-like syntax (familiar)
- ✅ Zero runtime overhead
- ✅ Full TypeScript inference
- ✅ No magic, no proxies
- ✅ Excellent migration system
- ✅ Drizzle Studio for visualization

**Alternatives considered**:

- Prisma: Runtime overhead, code generation
- TypeORM: Complex, heavy
- Kysely: Great but less ecosystem

**Example**:

```typescript
// Define schema
import { ulid } from 'ulid';

export const projects = pgTable('projects', {
  id: varchar('id', { length: 191 }).primaryKey(), // ULID stored as varchar
  name: text('name').notNull(),
  organizationId: varchar('organization_id', { length: 191 }).references(() => organizations.id),
  createdAt: timestamp('created_at').defaultNow()
})

// Query with type safety
const result = await db
  .select()
  .from(projects)
  .where(eq(projects.organizationId, orgId))
  .leftJoin(testRuns, eq(testRuns.projectId, projects.id))

// When inserting, generate ULID
const projectId = ulid();
await db.insert(projects).values({
  id: projectId,
  name: 'My Project',
  // ...
})
```

## 💾 Data Storage

### PostgreSQL 15

**What it is**: Advanced open-source relational database

**Why we chose it**:

- ✅ ACID transactions
- ✅ JSONB support (flexible schemas)
- ✅ Excellent indexing options
- ✅ Rich extension ecosystem
- ✅ Proven at scale
- ✅ Strong community support

**Features we use**:

- JSONB columns for flexible data
- Full-text search
- Partial indexes
- Foreign key constraints
- Transactions

**Configuration**:

```bash
# docker-compose.yml
postgres:
  image: postgres:15-alpine
  environment:
    POSTGRES_DB: izri
    POSTGRES_USER: postgres
    POSTGRES_PASSWORD: postgres
  ports:
    - "5433:5432"
  volumes:
    - postgres_data:/var/lib/postgresql/data
```

### Redis 7

**What it is**: In-memory data structure store

**Why we use it**:

- ✅ Ultra-fast caching (<1ms reads)
- ✅ Session storage
- ✅ Rate limiting support
- ✅ Pub/sub messaging
- ✅ Simple to operate

**Use cases**:

- Session management (Lucia)
- API response caching
- Rate limiting (planned)
- Background job queues (planned)

## 🤖 AI & Analysis

### Python 3.12

**Why Python for AI**:

- ✅ Best ecosystem for ML/AI
- ✅ LangChain and AI frameworks
- ✅ Tree-sitter for code parsing
- ✅ Excellent async support

### FastAPI

**What it is**: Modern Python web framework

**Why we chose it**:

- ✅ Async/await support
- ✅ Automatic API documentation
- ✅ Type hints with Pydantic
- ✅ Fast performance
- ✅ Easy to test

**Example**:

```python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class AnalysisRequest(BaseModel):
    repo_url: str
    branch: str = "main"

@app.post("/analyze")
async def analyze_repo(request: AnalysisRequest):
    # Perform analysis
    return {"status": "success"}
```

## 🛠️ Development Tools

### pnpm

**What it is**: Fast, disk space efficient package manager

**Why we chose it**:

- ✅ 3x faster than npm
- ✅ Efficient disk usage (symlinks)
- ✅ Strict dependency resolution
- ✅ Built-in monorepo support
- ✅ Workspace protocol

**Workspace structure**:

```yaml
# pnpm-workspace.yaml
packages:
  - 'apps/*'
  - 'packages/*'
```

### Turbo

**What it is**: High-performance build system for monorepos

**Why we chose it**:

- ✅ Intelligent caching
- ✅ Parallel execution
- ✅ Remote caching support
- ✅ Task pipelines
- ✅ Simple configuration

**Configuration**:

```json
{
  "pipeline": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": ["dist/**", "lib/**"]
    },
    "dev": {
      "cache": false,
      "persistent": true
    }
  }
}
```

### TypeScript 5.3+

**Why TypeScript**:

- ✅ Static type checking
- ✅ Better IDE support
- ✅ Catch errors at compile time
- ✅ Self-documenting code
- ✅ Refactoring confidence

**Configuration highlights**:

```json
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "moduleResolution": "bundler",
    "verbatimModuleSyntax": true
  }
}
```

## 🧪 Testing & Quality

### Biome

**What it is**: Fast formatter and linter (Rust-based)

**Why we use it**:

- ✅ 10x faster than ESLint+Prettier
- ✅ Single tool for format + lint
- ✅ Drop-in replacement
- ✅ Minimal configuration

### ESLint (Legacy)

**Current state**: Transitioning to Biome

**Still used for**:

- React-specific linting
- Import order enforcement

## 🐳 Infrastructure & DevOps

### Docker & Docker Compose

**Why we use it**:

- ✅ Consistent development environment
- ✅ Easy service orchestration
- ✅ Production parity
- ✅ Simplified onboarding

**Services**:

```yaml
services:
  postgres:
    image: postgres:15-alpine
  redis:
    image: redis:7-alpine
  api:
    build: ./docker/api
  web:
    build: ./docker/web
```

## 📊 Comparison with Alternatives

### Why Not Next.js?

| Feature | React Router v7 | Next.js |
|---------|----------------|---------|
| SSR | ✅ Yes | ✅ Yes |
| File Routing | ✅ Flexible | ✅ Pages/App dir |
| Vendor Lock-in | ✅ None | ❌ Vercel-optimized |
| Edge Functions | ✅ Yes | ✅ Yes |
| Learning Curve | ✅ Lower | ⚠️ Higher |
| Bundle Size | ✅ Smaller | ⚠️ Larger |

### Why tRPC Over GraphQL?

| Feature | tRPC | GraphQL |
|---------|------|---------|
| Type Safety | ✅ Native TS | ⚠️ Code generation |
| Setup Complexity | ✅ Minimal | ❌ High |
| Learning Curve | ✅ Easy | ❌ Steep |
| Over-fetching | ⚠️ Can happen | ✅ Prevented |
| Tooling | ✅ Great | ✅ Excellent |
| Ecosystem | ✅ Growing | ✅ Mature |

### Why Drizzle Over Prisma?

| Feature | Drizzle | Prisma |
|---------|---------|--------|
| Runtime Overhead | ✅ Zero | ❌ 4MB+ |
| SQL-like API | ✅ Yes | ❌ DSL |
| Type Inference | ✅ Native | ⚠️ Generated |
| Migrations | ✅ SQL files | ✅ Own format |
| Studio | ✅ Yes | ✅ Yes |
| Edge Compatible | ✅ Yes | ❌ No |

## 🎓 Learning Resources

### Official Documentation

- [React Router](https://reactrouter.com)
- [tRPC](https://trpc.io)
- [Drizzle ORM](https://orm.drizzle.team)
- [Hono](https://hono.dev)
- [Tailwind CSS](https://tailwindcss.com)
- [shadcn/ui](https://ui.shadcn.com)

### Internal Guides

- [System Overview](./overview.md)
- [Monorepo Structure](./monorepo-structure.md)
- [Data Flow](./data-flow.md)

## 🔄 Keeping Up to Date

### Monitoring Updates

```bash
# Check for outdated packages
pnpm outdated

# Update all to latest within version ranges
pnpm update

# Update specific package
pnpm update react-router
```

### Upgrade Strategy

1. **Patch versions**: Auto-update (security fixes)
2. **Minor versions**: Review changelog, test, update
3. **Major versions**: Plan migration, test extensively, update docs

## 🔗 Next Steps

- **[Monorepo Structure](./monorepo-structure.md)**: Understand code organization
- **[Design Decisions](./design-decisions.md)**: Learn why these choices were made
- **[Frontend Docs](../frontend/README.md)**: Deep dive into React Router app
- **[Backend Docs](../backend/README.md)**: Deep dive into Hono + tRPC API

---

*Questions about a specific technology? Check the official docs linked above or ask the team.*
