Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Bun Runtime Development Patterns

Bun Runtime Development Patterns

High-performance development with Bun runtime for Google Antigravity projects including APIs, testing, and package management.

bunruntimeperformancetestingjavascript
by Antigravity Team
⭐0Stars
👁️3Views
.antigravity
# Bun Runtime Development Patterns for Google Antigravity

Build high-performance applications with Bun runtime in your Google Antigravity IDE projects. This comprehensive guide covers server APIs, testing, package management, and performance optimization optimized for Gemini 3 agentic development.

## HTTP Server Setup

Create fast HTTP servers with Bun.serve:

```typescript
// server.ts
import { Database } from 'bun:sqlite';

const db = new Database('app.db');

// Initialize database
db.run(`
  CREATE TABLE IF NOT EXISTS prompts (
    id TEXT PRIMARY KEY,
    slug TEXT UNIQUE NOT NULL,
    title TEXT NOT NULL,
    description TEXT NOT NULL,
    content TEXT NOT NULL,
    tags TEXT NOT NULL,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP
  )
`);

const server = Bun.serve({
  port: process.env.PORT || 3000,
  
  async fetch(request) {
    const url = new URL(request.url);
    const path = url.pathname;
    const method = request.method;

    // CORS headers
    const corsHeaders = {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    };

    if (method === 'OPTIONS') {
      return new Response(null, { headers: corsHeaders });
    }

    try {
      // Route handling
      if (path === '/api/prompts' && method === 'GET') {
        return handleGetPrompts(url, corsHeaders);
      }

      if (path.startsWith('/api/prompts/') && method === 'GET') {
        const slug = path.split('/').pop()!;
        return handleGetPrompt(slug, corsHeaders);
      }

      if (path === '/api/prompts' && method === 'POST') {
        return handleCreatePrompt(request, corsHeaders);
      }

      // Static files
      if (path.startsWith('/public/')) {
        const file = Bun.file(`./public${path.slice(7)}`);
        if (await file.exists()) {
          return new Response(file);
        }
      }

      return new Response('Not Found', { status: 404, headers: corsHeaders });
    } catch (error) {
      console.error('Server error:', error);
      return Response.json(
        { error: 'Internal server error' },
        { status: 500, headers: corsHeaders }
      );
    }
  },

  error(error) {
    console.error('Bun server error:', error);
    return new Response('Internal Server Error', { status: 500 });
  },
});

console.log(`Server running at http://localhost:${server.port}`);

// Route handlers
function handleGetPrompts(url: URL, headers: Record<string, string>) {
  const limit = Number(url.searchParams.get('limit')) || 20;
  const offset = Number(url.searchParams.get('offset')) || 0;
  const search = url.searchParams.get('search');

  let query = 'SELECT * FROM prompts';
  const params: unknown[] = [];

  if (search) {
    query += ' WHERE title LIKE ? OR description LIKE ?';
    params.push(`%${search}%`, `%${search}%`);
  }

  query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  params.push(limit, offset);

  const prompts = db.query(query).all(...params);

  return Response.json({ prompts }, { headers });
}

function handleGetPrompt(slug: string, headers: Record<string, string>) {
  const prompt = db.query('SELECT * FROM prompts WHERE slug = ?').get(slug);

  if (!prompt) {
    return Response.json({ error: 'Prompt not found' }, { status: 404, headers });
  }

  return Response.json(prompt, { headers });
}

async function handleCreatePrompt(request: Request, headers: Record<string, string>) {
  const body = await request.json();
  const id = crypto.randomUUID();
  const slug = body.title.toLowerCase().replace(/[^a-z0-9]+/g, '-');

  db.run(
    `INSERT INTO prompts (id, slug, title, description, content, tags) 
     VALUES (?, ?, ?, ?, ?, ?)`,
    [id, slug, body.title, body.description, body.content, JSON.stringify(body.tags)]
  );

  const prompt = db.query('SELECT * FROM prompts WHERE id = ?').get(id);

  return Response.json(prompt, { status: 201, headers });
}
```

## File Operations

Efficient file handling with Bun:

```typescript
// lib/files.ts

// Read file as text
async function readTextFile(path: string): Promise<string> {
  const file = Bun.file(path);
  return file.text();
}

// Read file as JSON
async function readJsonFile<T>(path: string): Promise<T> {
  const file = Bun.file(path);
  return file.json();
}

// Write file
async function writeFile(path: string, content: string | Uint8Array): Promise<void> {
  await Bun.write(path, content);
}

// Stream large files
async function streamFile(path: string): Promise<ReadableStream> {
  const file = Bun.file(path);
  return file.stream();
}

// Process directory
async function* walkDirectory(dir: string): AsyncGenerator<string> {
  const glob = new Bun.Glob('**/*');
  
  for await (const file of glob.scan({ cwd: dir, onlyFiles: true })) {
    yield `${dir}/${file}`;
  }
}

// Hash file for caching
async function hashFile(path: string): Promise<string> {
  const file = Bun.file(path);
  const buffer = await file.arrayBuffer();
  const hash = Bun.hash(buffer);
  return hash.toString(16);
}

// Copy with progress
async function copyWithProgress(
  src: string,
  dest: string,
  onProgress?: (progress: number) => void
): Promise<void> {
  const srcFile = Bun.file(src);
  const size = srcFile.size;
  let copied = 0;

  const reader = srcFile.stream().getReader();
  const chunks: Uint8Array[] = [];

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    
    chunks.push(value);
    copied += value.length;
    onProgress?.(copied / size);
  }

  const combined = new Uint8Array(copied);
  let offset = 0;
  for (const chunk of chunks) {
    combined.set(chunk, offset);
    offset += chunk.length;
  }

  await Bun.write(dest, combined);
}
```

## Testing with Bun

Write and run tests with built-in test runner:

```typescript
// tests/prompts.test.ts
import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
import { Database } from 'bun:sqlite';

describe('Prompts API', () => {
  let db: Database;
  let server: ReturnType<typeof Bun.serve>;

  beforeAll(() => {
    db = new Database(':memory:');
    db.run(`
      CREATE TABLE prompts (
        id TEXT PRIMARY KEY,
        slug TEXT UNIQUE NOT NULL,
        title TEXT NOT NULL,
        description TEXT NOT NULL,
        content TEXT NOT NULL,
        tags TEXT NOT NULL,
        created_at TEXT DEFAULT CURRENT_TIMESTAMP
      )
    `);

    // Insert test data
    db.run(`
      INSERT INTO prompts (id, slug, title, description, content, tags)
      VALUES (?, ?, ?, ?, ?, ?)
    `, ['1', 'test-prompt', 'Test Prompt', 'A test prompt', 'Content here', '["test"]']);
  });

  afterAll(() => {
    db.close();
  });

  it('should return a list of prompts', async () => {
    const response = await fetch('http://localhost:3000/api/prompts');
    const data = await response.json();

    expect(response.status).toBe(200);
    expect(data.prompts).toBeArray();
  });

  it('should return a single prompt by slug', async () => {
    const response = await fetch('http://localhost:3000/api/prompts/test-prompt');
    const data = await response.json();

    expect(response.status).toBe(200);
    expect(data.title).toBe('Test Prompt');
  });

  it('should create a new prompt', async () => {
    const response = await fetch('http://localhost:3000/api/prompts', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        title: 'New Prompt',
        description: 'A new test prompt',
        content: 'New content',
        tags: ['new', 'test'],
      }),
    });

    expect(response.status).toBe(201);
    const data = await response.json();
    expect(data.slug).toBe('new-prompt');
  });

  it('should return 404 for non-existent prompt', async () => {
    const response = await fetch('http://localhost:3000/api/prompts/non-existent');
    expect(response.status).toBe(404);
  });
});

// Run with: bun test
```

## Package Scripts

Configure package.json for Bun:

```json
{
  "name": "antigravity-api",
  "version": "1.0.0",
  "scripts": {
    "dev": "bun --watch server.ts",
    "start": "bun server.ts",
    "test": "bun test",
    "test:watch": "bun test --watch",
    "build": "bun build ./server.ts --outdir ./dist --target bun",
    "typecheck": "bun x tsc --noEmit",
    "lint": "bun x eslint .",
    "db:migrate": "bun run scripts/migrate.ts",
    "db:seed": "bun run scripts/seed.ts"
  },
  "dependencies": {
    "hono": "^4.0.0"
  },
  "devDependencies": {
    "@types/bun": "latest",
    "typescript": "^5.0.0"
  }
}
```

## Best Practices

1. **Use Bun.serve** for HTTP servers with maximum performance
2. **Leverage SQLite** with bun:sqlite for embedded databases
3. **Use Bun.file** for efficient file operations
4. **Write tests** with built-in bun:test
5. **Use --watch** for development hot reload
6. **Bundle for production** with bun build
7. **Use native APIs** like crypto and hashing

When to Use This Prompt

This bun prompt is ideal for developers working on:

  • bun applications requiring modern best practices and optimal performance
  • Projects that need production-ready bun code with proper error handling
  • Teams looking to standardize their bun development workflow
  • Developers wanting to learn industry-standard bun patterns and techniques

By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their bun implementations.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the bun code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this bun prompt commercially?

Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.

Which AI assistants work best with this prompt?

This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.

How do I customize this prompt for my specific needs?

You can modify the prompt by adding specific requirements, constraints, or preferences. For bun projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...