High-performance development with Bun runtime for Google Antigravity projects including APIs, testing, and package management.
# 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 hashingThis bun prompt is ideal for developers working on:
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.
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.
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.
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.