Skip to main content
This is Part 3 of 3. If you haven’t completed the previous parts:
  • Time to complete: 15-20 minutes
  • What you’ll learn: TypeScript validation, build process, error fixing loop
  • Platform: Designed for AI PCs with Ryzen AI (NPU/iGPU acceleration)

The Validation & Build Pipeline

After generating code, GAIA Code doesn’t just stop—it validates, builds, and fixes errors automatically until the application works.
This iterative process ensures every generated application is functional.

Phase 1: TypeScript Validation

The first validation step checks for type errors.

What TypeScript Validation Checks

Type Safety

Variables used with correct types

Import Errors

All imports resolve correctly

API Compatibility

Function calls match signatures

Null Safety

Nullable values handled properly

Example: Type Error Detection

Generated code with error:
// Error: Property 'map' does not exist on type 'Movie | undefined'
export default function MoviesPage() {
  const [movies, setMovies] = useState<Movie[]>();
  
  return (
    <div>
      {movies.map((movie) => (  // ❌ Error: movies might be undefined
        <div key={movie.id}>{movie.title}</div>
      ))}
    </div>
  );
}
TypeScript compiler output:
src/app/movies/page.tsx:15:14 - error TS2532: Object is possibly 'undefined'.

15       {movies.map((movie) => (
              ~~~~~~

Auto-Fix Process

  1. Error detected: TypeScript compiler identifies the issue
  2. LLM analyzes: Understands the error context
  3. Fix generated: Provides corrected code
  4. Applied: Code is updated
Fixed code:
export default function MoviesPage() {
  const [movies, setMovies] = useState<Movie[]>([]);  // ✅ Default to empty array
  
  return (
    <div>
      {movies.map((movie) => (  // ✅ Now safe - movies is always an array
        <div key={movie.id}>{movie.title}</div>
      ))}
    </div>
  );
}

Phase 2: Next.js Build Process

After TypeScript validation passes, the agent runs the Next.js build.

Build Steps

npm run build
This command:
  1. Compiles TypeScript → JavaScript
  2. Bundles code → Optimized chunks
  3. Generates static pages → Pre-rendered HTML
  4. Optimizes images → Next.js image optimization
  5. Creates server bundles → API routes

Build Output Example

▲ Next.js 15.0.0

  Creating an optimized production build ...
✓ Compiled successfully
✓ Linting and checking validity of types
✓ Collecting page data
✓ Generating static pages (5/5)
✓ Finalizing page optimization

Route (app)                              Size     First Load JS
┌ ○ /                                    142 B          87.2 kB
├ ○ /api/movies                          0 B                0 B
├ ○ /movies                              2.1 kB         89.3 kB
├ ○ /movies/new                          1.8 kB         89.0 kB
└ ○ /movies/[id]                         1.9 kB         89.1 kB

○ (Static) prerendered as static content

Common Build Errors

Error:
Module not found: Can't resolve '@/lib/prisma'
Cause: Missing or incorrect path aliasAuto-fix:
  • Check tsconfig.json paths
  • Verify file exists
  • Update import statement
Error:
@prisma/client did not initialize yet
Cause: Prisma client not generatedAuto-fix:
  • Run npx prisma generate
  • Ensure schema is valid
  • Check database connection
Error:
Cannot find name 'NextResponse'
Cause: Missing Next.js importsAuto-fix:
  • Add missing import
  • Verify Next.js version
  • Check API route syntax

Phase 3: Error Iteration Loop

When errors are found, the agent enters an iteration loop.

Iteration Process

1

Error Collection

Gather all TypeScript and build errors with line numbers and context
2

Error Analysis

LLM analyzes each error:
  • What caused it?
  • What’s the fix?
  • Will this fix break anything else?
3

Fix Generation

Generate minimal fixes:
  • Change only what’s needed
  • Maintain code style
  • Keep functionality intact
4

Apply Fixes

Update files with corrections
5

Re-validate

Run TypeScript validation and build again
6

Repeat or Complete

  • More errors? → Back to step 1
  • No errors? → Success!

Example: Complete Iteration

Iteration 1:
Error: Type 'string' is not assignable to type 'Date'
Location: src/app/api/movies/route.ts:24

Fix: Convert string to Date object before storing
Applied fix:
const movie = await prisma.movie.create({
  data: {
    ...validatedData,
    dateWatched: new Date(validatedData.dateWatched),  // ✅ Convert to Date
  },
});
Iteration 2:
Error: Property 'dateWatched' does not exist on type 'InferSelectModel<typeof movies>'
Location: src/app/movies/page.tsx:32

Fix: Update Prisma schema or TypeScript interface
Applied fix:
interface Movie {
  id: number;
  title: string;
  genre: string;
  dateWatched: string;  // ✅ Match database type
  score: number;
}
Iteration 3:
✓ Compiled successfully
✓ No type errors found
✓ Build completed

Success: Application is ready!

Validation Features

1. Intelligent Error Detection

The agent recognizes different error types:
Error TypeDetection MethodFix Strategy
Type ErrorsTypeScript compilerType conversion, interface updates
Import ErrorsModule resolutionAdd imports, fix paths
Build ErrorsNext.js buildConfiguration fixes, dependency updates
Runtime ErrorsCode analysisLogic fixes, null checks

2. Context-Aware Fixes

Fixes consider the broader context:
// Not just: Add null check
if (movie) {
  console.log(movie.title);
}

// But: Initialize properly at source
const [movie, setMovie] = useState<Movie | null>(null);

// And: Handle loading state
if (!movie) return <div>Loading...</div>;
console.log(movie.title);

3. Minimal Changes

The agent makes the smallest possible fix:
// ❌ Don't rewrite entire component
// ✅ Change only the problematic line

// Before:
const [movies, setMovies] = useState<Movie[]>();

// After:
const [movies, setMovies] = useState<Movie[]>([]);  // ← Only this changed

Build Optimization

The agent ensures optimal build configuration.

Generated Configuration Files

{
  "compilerOptions": {
    "target": "ES2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}

Testing the Final Application

Once validation passes and build succeeds, test the application:

Run the app

cd movie-tracking-app
npm run dev

Verification Checklist

Database

✓ Schema applied
✓ Tables created
✓ Migrations work

API Routes

✓ GET returns data
✓ POST creates records
✓ PUT updates records
✓ DELETE removes records

UI Components

✓ List view displays data
✓ Create form works
✓ Detail view shows record
✓ Delete confirms action

Validation

✓ Required fields enforced
✓ Type validation works
✓ Error messages display
✓ Edge cases handled

Summary

GAIA Code’s validation and build process ensures:
  1. Type Safety - TypeScript catches type errors
  2. Build Success - Next.js builds without issues
  3. Automatic Fixes - Errors are fixed iteratively
  4. Working App - Final output is functional
This three-phase process (validation → build → iteration) is what makes GAIA Code reliable for generating production-ready applications.

Complete Example

From prompt to working app:
# 1. Generate
gaia code "Build me a workout tracking app in nextjs where I can track workout, duration, date, and goal"

# 2. Run
cd workout-tracking-app
npm run dev

# 3. Use
# Opens at http://localhost:3000
# ✓ Create workouts
# ✓ View workout list
# ✓ Edit workouts
# ✓ Delete workouts