> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/pingdotgg/t3code/llms.txt
> Use this file to discover all available pages before exploring further.

# Building

> Build T3 Code for production deployment and distribution

## Overview

T3 Code uses **Turbo** for orchestrated builds across the monorepo. The build process produces optimized bundles for web, server, and desktop distributions.

## Quick Build Commands

<CodeGroup>
  ```bash Full Build theme={null}
  # Build all packages
  bun run build
  ```

  ```bash Server Only theme={null}
  # Build server package (t3 CLI)
  bun run build:contracts
  cd apps/server && bun run build
  ```

  ```bash Desktop Build theme={null}
  # Build desktop app (includes server + web)
  bun run build:desktop
  ```

  ```bash Marketing Site theme={null}
  # Build marketing website
  bun run build:marketing
  ```
</CodeGroup>

## Build Process

### Build Order

Turbo builds packages in dependency order:

<Steps>
  <Step title="Packages (Parallel)">
    * `packages/contracts` (Effect/Schema → ESM/CJS)
    * `packages/shared` (Runtime utilities)
  </Step>

  <Step title="Apps (Sequential)">
    * `apps/web` (React + Vite → static assets)
    * `apps/server` (Node.js → bundled ESM)
  </Step>

  <Step title="Desktop (Final)">
    * `apps/desktop` (Electron → platform binaries)
  </Step>
</Steps>

### Build Outputs

| Package     | Output Directory | Format                    |
| ----------- | ---------------- | ------------------------- |
| `contracts` | `dist/`          | ESM + CJS + types         |
| `web`       | `dist/`          | Static HTML/JS/CSS        |
| `server`    | `dist/`          | Bundled ESM (`index.mjs`) |
| `desktop`   | `dist-electron/` | Electron bundles          |

## Building Components

### Contracts Package

Builds Effect/Schema definitions to distributable format:

```bash theme={null}
cd packages/contracts
bun run build
```

**Build Tool:** `tsdown` (TypeScript bundler)

**Output:**

* `dist/index.mjs` - ESM bundle
* `dist/index.cjs` - CommonJS bundle
* `dist/index.d.ts` - TypeScript declarations

**Configuration:**

```json package.json theme={null}
{
  "scripts": {
    "build": "tsdown src/index.ts --format esm,cjs --dts --clean"
  }
}
```

### Web App

Builds React application to static assets:

```bash theme={null}
cd apps/web
bun run build
```

**Build Tool:** Vite 8

**Output:** `dist/` directory with:

* `index.html` - HTML entry point
* `assets/*.js` - Code-split JavaScript bundles
* `assets/*.css` - Extracted stylesheets
* `assets/*` - Images, fonts, other assets

**Optimizations:**

* React Compiler (automatic memoization)
* Code splitting (route-based)
* Tree shaking (unused code elimination)
* Minification (Terser)
* CSS optimization (Lightning CSS)

**Configuration:**

```typescript vite.config.ts theme={null}
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [
    react({
      babel: {
        plugins: [['babel-plugin-react-compiler', {}]],
      },
    }),
  ],
  build: {
    outDir: 'dist',
    sourcemap: true,
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          router: ['@tanstack/react-router'],
        },
      },
    },
  },
});
```

### Server Package

Builds Node.js backend to bundled ESM:

```bash theme={null}
cd apps/server
bun run build
```

**Build Tool:** Custom bundler (`scripts/cli.ts build`)

**Output:** `dist/index.mjs` (single bundle including web assets)

**Process:**

1. Builds web app (if not already built)
2. Bundles server code with tsdown
3. Embeds web assets in server bundle
4. Generates CLI entry point

**Configuration:**

```typescript scripts/cli.ts theme={null}
// Custom build script
// - Bundles TypeScript to ESM
// - Includes web dist as static assets
// - Generates shebang for CLI execution
```

<Note>
  The server build includes the web app for production serving.
</Note>

### Desktop App

Builds Electron application:

```bash theme={null}
cd apps/desktop
bun run build
```

**Build Tool:** `tsdown` + Electron

**Output:** `dist-electron/` directory with:

* `main.js` - Electron main process
* `preload.js` - Preload scripts

**For distribution, see [Desktop Distribution](#desktop-distribution) below.**

## Production Build

### Full Production Build

Build everything for production:

```bash theme={null}
# Clean previous builds (optional)
bun run clean

# Install dependencies
bun install

# Run full build
bun run build

# Verify with typecheck
bun run typecheck

# Run tests
bun run test
```

### Start Production Server

Run the built server:

```bash theme={null}
bun run start
```

This runs `node dist/index.mjs` which:

* Starts WebSocket server
* Serves built web app as static files
* Opens browser to the app

**Production Configuration:**

```bash theme={null}
# Custom port
T3CODE_PORT=8080 bun run start

# Custom state directory
bun run start -- --state-dir ~/.t3/prod

# Don't open browser
T3CODE_NO_BROWSER=1 bun run start
```

## Desktop Distribution

### Build Desktop Artifacts

Create platform-specific installers:

<Tabs>
  <Tab title="macOS">
    ```bash theme={null}
    # ARM64 .dmg (default)
    bun run dist:desktop:dmg

    # Intel .dmg
    bun run dist:desktop:dmg:x64

    # Specific architecture
    bun run dist:desktop:dmg:arm64
    ```

    **Output:** `release/T3 Code (Alpha)-0.0.3-arm64.dmg`
  </Tab>

  <Tab title="Linux">
    ```bash theme={null}
    # AppImage (x64)
    bun run dist:desktop:linux
    ```

    **Output:** `release/T3 Code (Alpha)-0.0.3.AppImage`
  </Tab>

  <Tab title="Windows">
    ```bash theme={null}
    # NSIS installer (x64)
    bun run dist:desktop:win
    ```

    **Output:** `release/T3 Code (Alpha) Setup 0.0.3.exe`
  </Tab>
</Tabs>

### Custom Platform/Architecture

Build for specific targets:

```bash theme={null}
bun run dist:desktop:artifact -- \
  --platform mac \
  --target dmg \
  --arch arm64
```

**Available Options:**

| Flag         | Values                    | Description      |
| ------------ | ------------------------- | ---------------- |
| `--platform` | `mac`, `linux`, `win`     | Target platform  |
| `--target`   | `dmg`, `AppImage`, `nsis` | Installer format |
| `--arch`     | `arm64`, `x64`            | CPU architecture |

### DMG Packaging Options

<Accordion title="Keep staging files">
  For debugging package contents:

  ```bash theme={null}
  bun run dist:desktop:dmg -- --keep-stage
  ```

  Staging files remain in `.stage/` directory.
</Accordion>

<Accordion title="Code signing">
  Enable code signing (requires certificates in CI/secrets):

  ```bash theme={null}
  bun run dist:desktop:dmg -- --signed
  ```

  **macOS:** Uses Apple Developer ID

  **Windows:** Uses Azure Trusted Signing with these environment variables:

  * `AZURE_TRUSTED_SIGNING_ENDPOINT`
  * `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`
  * `AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`
  * `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`
  * `AZURE_TENANT_ID`
  * `AZURE_CLIENT_ID`
  * `AZURE_CLIENT_SECRET`
</Accordion>

### Desktop Package Contents

The desktop package includes:

* **Electron shell** (`dist-electron/`)
* **Web UI** (bundled from `apps/web/dist`)
* **Backend server** (`apps/server/dist` as `t3` CLI)
* **App icon** (from `assets/macos-icon-1024.png`)

**How it works:**

```typescript apps/desktop/src/main/backend.ts theme={null}
// Spawns bundled t3 CLI on loopback with auth token
const backend = spawn(t3BinaryPath, [
  '--auth-token', token,
  '--no-browser',
]);

// UI connects via WebSocket
const wsUrl = `ws://127.0.0.1:${port}?token=${token}`;
```

## Build Optimization

### Turbo Caching

Turbo caches build outputs for faster rebuilds:

```bash theme={null}
# Check cache status
turbo run build --dry-run

# Force rebuild (skip cache)
turbo run build --force

# Clear cache
rm -rf .turbo
```

**Cache Configuration:**

```json turbo.json theme={null}
{
  "tasks": {
    "build": {
      "outputs": ["dist/**", "dist-electron/**"],
      "dependsOn": ["^build"]
    }
  }
}
```

### Parallel Builds

Turbo runs independent builds in parallel:

```bash theme={null}
# Build with concurrency limit
turbo run build --concurrency=2

# Build specific packages
turbo run build --filter=@t3tools/web --filter=@t3tools/server
```

### Incremental Builds

Development builds support incremental compilation:

```bash theme={null}
# Watch mode (incremental)
cd packages/contracts
bun run dev  # tsdown --watch
```

## CI/CD Integration

### GitHub Actions Example

```yaml .github/workflows/build.yml theme={null}
name: Build

on:
  push:
    branches: [main]
  pull_request:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - uses: oven-sh/setup-bun@v1
        with:
          bun-version: 1.3.9
      
      - name: Install dependencies
        run: bun install
      
      - name: Build
        run: bun run build
      
      - name: Typecheck
        run: bun run typecheck
      
      - name: Test
        run: bun run test
      
      - name: Upload server artifact
        uses: actions/upload-artifact@v3
        with:
          name: t3-server
          path: apps/server/dist/
```

### Desktop Release Workflow

```yaml .github/workflows/release.yml theme={null}
name: Release

on:
  push:
    tags:
      - 'v*'

jobs:
  build-desktop:
    strategy:
      matrix:
        os: [macos-latest, ubuntu-latest, windows-latest]
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v4
      - uses: oven-sh/setup-bun@v1
      
      - name: Build desktop
        run: |
          bun install
          bun run build:desktop
      
      - name: Create installer (macOS)
        if: matrix.os == 'macos-latest'
        run: bun run dist:desktop:dmg -- --signed
        env:
          APPLE_ID: ${{ secrets.APPLE_ID }}
          APPLE_ID_PASSWORD: ${{ secrets.APPLE_ID_PASSWORD }}
      
      - name: Upload to release
        uses: actions/upload-release-asset@v1
        with:
          upload_url: ${{ github.event.release.upload_url }}
          asset_path: ./release/*
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="Build fails with missing dependencies">
    Ensure all dependencies are installed:

    ```bash theme={null}
    bun run clean
    bun install
    bun run build
    ```
  </Accordion>

  <Accordion title="Turbo cache issues">
    Clear the Turbo cache:

    ```bash theme={null}
    rm -rf .turbo apps/*/.turbo packages/*/.turbo
    bun run build --force
    ```
  </Accordion>

  <Accordion title="Desktop build fails">
    Check that you've built the dependencies first:

    ```bash theme={null}
    bun run build:contracts
    bun run build:desktop
    ```
  </Accordion>

  <Accordion title="Web assets not updating">
    Force rebuild the web app:

    ```bash theme={null}
    cd apps/web
    rm -rf dist
    bun run build
    ```
  </Accordion>
</AccordionGroup>

## Pre-Commit Checks

<Warning>
  Both `bun lint` and `bun typecheck` must pass before tasks are considered complete.
</Warning>

Run all checks before committing:

```bash theme={null}
# Lint
bun run lint

# Type check
bun run typecheck

# Test
bun run test

# Build
bun run build
```

### Automated Checks

Add to `.husky/pre-commit`:

```bash theme={null}
#!/bin/sh
bun run lint
bun run typecheck
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Testing" icon="flask" href="/development/testing">
    Learn about testing strategies
  </Card>

  <Card title="Setup" icon="rocket" href="/development/setup">
    Review development setup
  </Card>
</CardGroup>
