# Build Context & Advanced Features

Advanced build management with watch mode, development server, and incremental rebuilding capabilities. Build contexts provide efficient workflows for development and production environments with persistent build state.

## Capabilities

### Context Creation

Creates a build context that maintains build state and enables advanced features like watching and serving.

```typescript { .api }
/**
 * Create a build context for advanced build operations
 * @param options - Build configuration options
 * @returns Promise resolving to build context instance
 */
function context(options: BuildOptions): Promise<BuildContext>;
```

**Usage Example:**

```typescript
import * as esbuild from "esbuild";

const ctx = await esbuild.context({
  entryPoints: ["src/app.js"],
  bundle: true,
  outdir: "dist",
  format: "esm",
  splitting: true,
});

// Context can now be used for rebuild, watch, or serve
```

### Build Context Interface

The context object provides methods for advanced build operations.

```typescript { .api }
interface BuildContext {
  /**
   * Perform an incremental rebuild using cached state
   * @returns Promise resolving to build results
   */
  rebuild(): Promise<BuildResult>;
  
  /**
   * Enable watch mode for automatic rebuilds on file changes
   * @param options - Watch configuration options
   * @returns Promise that resolves when watching stops
   */
  watch(options?: WatchOptions): Promise<void>;
  
  /**
   * Start a development server
   * @param options - Server configuration options  
   * @returns Promise resolving to server details
   */
  serve(options?: ServeOptions): Promise<ServeResult>;
  
  /**
   * Cancel any ongoing operations (builds, watching, serving)
   * @returns Promise that resolves when operations are cancelled
   */
  cancel(): Promise<void>;
  
  /**
   * Dispose of the context and clean up resources
   * @returns Promise that resolves when cleanup is complete
   */
  dispose(): Promise<void>;
}
```

### Incremental Rebuilding

Perform efficient rebuilds using cached build state.

```typescript { .api }
/**
 * Perform an incremental rebuild using cached state
 * @returns Promise resolving to build results
 */
rebuild(): Promise<BuildResult>;
```

**Usage Example:**

```typescript
const ctx = await esbuild.context({
  entryPoints: ["src/app.js"],
  bundle: true,
  outfile: "dist/app.js",
});

// Initial build
let result = await ctx.rebuild();
console.log("Initial build:", result.errors.length, "errors");

// Subsequent rebuilds are faster (incremental)
result = await ctx.rebuild();
console.log("Incremental rebuild:", result.errors.length, "errors");

await ctx.dispose();
```

### Watch Mode

Enable automatic rebuilds when source files change.

```typescript { .api }
/**
 * Enable watch mode for automatic rebuilds on file changes
 * @param options - Watch configuration options
 * @returns Promise that resolves when watching stops
 */
watch(options?: WatchOptions): Promise<void>;

interface WatchOptions {
  /**
   * Delay in milliseconds before triggering a rebuild after file changes
   * @default 10
   */
  delay?: number;
}
```

**Usage Example:**

```typescript
const ctx = await esbuild.context({
  entryPoints: ["src/app.js"],
  bundle: true,
  outdir: "dist",
  logLevel: "info",
});

// Start watching - this promise won't resolve until watching stops
console.log("Starting watch mode...");
await ctx.watch({
  delay: 100, // Wait 100ms after changes before rebuilding
});

// This won't be reached unless watching is cancelled
console.log("Watch mode stopped");
```

### Development Server

Start a development server with live reloading and file serving.

```typescript { .api }
/**
 * Start a development server
 * @param options - Server configuration options
 * @returns Promise resolving to server details
 */
serve(options?: ServeOptions): Promise<ServeResult>;

interface ServeOptions {
  /**
   * Port number for the server
   * @default 0 (random available port)
   */
  port?: number;
  
  /**
   * Hostname to bind to
   * @default "localhost"
   */
  host?: string;
  
  /**
   * Directory to serve static files from
   */
  servedir?: string;
  
  /**
   * Path to HTTPS key file for secure server
   */
  keyfile?: string;
  
  /**
   * Path to HTTPS certificate file for secure server  
   */
  certfile?: string;
  
  /**
   * Fallback file for single-page applications
   */
  fallback?: string;
  
  /**
   * Enable CORS headers
   * @default false
   */
  cors?: boolean;
  
  /**
   * Callback for handling server requests
   */
  onRequest?: (args: ServeOnRequestArgs) => void;
}

interface ServeResult {
  /**
   * Actual port the server is listening on
   */
  port: number;
  
  /**
   * Available hostnames/addresses for the server
   */
  host: string;
}

interface ServeOnRequestArgs {
  remoteAddress: string;
  method: string;
  path: string;
  status: number;
  timeInMS: number;
}
```

**Usage Examples:**

```typescript
const ctx = await esbuild.context({
  entryPoints: ["src/app.js"],
  bundle: true,
  outdir: "dist",
  format: "esm",
});

// Basic development server
const server = await ctx.serve({
  port: 3000,
  servedir: "public",
});

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

// Advanced server with HTTPS and request logging
const httpsServer = await ctx.serve({
  port: 8443,
  host: "0.0.0.0",
  servedir: "public",
  keyfile: "server.key",
  certfile: "server.crt",
  fallback: "index.html", // SPA fallback
  cors: true,
  onRequest: (args) => {
    console.log(`${args.method} ${args.path} - ${args.status} (${args.timeInMS}ms)`);
  },
});
```

### Context Management

Methods for managing context lifecycle and cancelling operations.

```typescript { .api }
/**
 * Cancel any ongoing operations (builds, watching, serving)
 * @returns Promise that resolves when operations are cancelled
 */
cancel(): Promise<void>;

/**
 * Dispose of the context and clean up resources
 * @returns Promise that resolves when cleanup is complete
 */
dispose(): Promise<void>;
```

**Usage Example:**

```typescript
const ctx = await esbuild.context({
  entryPoints: ["src/app.js"],
  bundle: true,
  outdir: "dist",
});

// Start watching
const watchPromise = ctx.watch();

// In another part of your code, you can cancel operations
setTimeout(async () => {
  console.log("Cancelling operations...");
  await ctx.cancel();
  
  console.log("Disposing context...");
  await ctx.dispose();
}, 10000);

// Wait for watch to complete (after cancellation)
await watchPromise;
console.log("All operations complete");
```

## Combined Usage Patterns

### Development Workflow

```typescript
// Development setup with watch and serve
const ctx = await esbuild.context({
  entryPoints: ["src/app.js"],
  bundle: true,
  outdir: "dist",
  format: "esm",
  sourcemap: true,
  logLevel: "info",
});

// Start both watching and serving simultaneously
const [_, server] = await Promise.all([
  ctx.watch(),
  ctx.serve({
    port: 3000,
    servedir: "public",
    fallback: "index.html",
  }),
]);

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

### Production Build Pipeline

```typescript
// Production build with analysis
const ctx = await esbuild.context({
  entryPoints: ["src/app.js"],
  bundle: true,
  outdir: "dist",
  format: "esm",
  minify: true,
  splitting: true,
  metafile: true,
});

try {
  const result = await ctx.rebuild();
  
  if (result.errors.length > 0) {
    console.error("Build errors:", result.errors);
    process.exit(1);
  }
  
  if (result.metafile) {
    const analysis = await esbuild.analyzeMetafile(result.metafile);
    console.log("Bundle analysis:", analysis);
  }
  
  console.log("Production build complete");
} finally {
  await ctx.dispose();
}
```