npm package: @kokolabs-io/sdk
Description: Complete SDK for Koko user pods and remote runtime environments
Author: KokoLabs.io
Latest version: 1.0.0

# @kokolabs-io/sdk

Complete SDK for Koko user pods and remote runtime environments.

## Features

- **SQL API**: Execute SQL queries with parameter binding
- **File System API**: Read/write files in pod storage
- **Authentication**: User authentication and authorization
- **Environment Variables**: Access to pod environment
- **KV Store**: Key-value storage (coming soon)
- **Queue**: Task queue management (coming soon)
- **Logging**: Structured logging (coming soon)
- **Dual Mode**: Works in both native and remote environments

## Installation

```bash
pnpm add @kokolabs-io/sdk
```

## Usage

### Basic Setup

```typescript
import { koko } from '@kokolabs-io/sdk';

// Check pod connection
console.log(koko.ping()); // "pong"
console.log(koko.podId()); // Your pod ID
```

### SQL API

```typescript
import { sql } from '@kokolabs-io/sdk';

// Execute a query
const result = await sql.query('SELECT * FROM users WHERE age > ?', [18]);
console.log(result.columns); // ['id', 'name', 'age']
console.log(result.rows);    // [[1, 'Alice', 25], [2, 'Bob', 30]]

// Execute a statement (INSERT, UPDATE, DELETE)
await sql.execute('INSERT INTO users (name, age) VALUES (?, ?)', ['Charlie', 35]);

// Query each row with callback
await sql.queryEach(
  'SELECT * FROM large_table',
  [],
  undefined,
  (row) => {
    console.log(row);
    return true; // Continue iteration
  }
);

// Attach another database
await sql.attach('/data/other.db', 'other_db');
await sql.query('SELECT * FROM other_db.table_name');
await sql.detach('other_db');
```

### File System API

```typescript
import { fs } from '@kokolabs-io/sdk';

// Read text file
const content = await fs.readText('/data/config.json');

// Write text file
await fs.writeText('/data/output.txt', 'Hello, world!');

// Write with conditional update (optimistic locking)
await fs.writeText('/data/config.json', newConfig, {
  ifMatch: previousETag,
  force: false
});

// Read binary data
const bytes = await fs.readBytes('/data/image.png');
const buffer = await fs.readBuffer('/data/file.bin');

// File operations
const exists = await fs.exists('/data/file.txt');
const stat = await fs.stat('/data/file.txt');
const files = await fs.readdir('/data/');

// Directory operations
await fs.mkdir('/data/new-folder', true);
await fs.rm('/data/old-folder', true);

// Get file tree
const tree = await fs.tree('/data/', {
  typed: true,
  filesOnly: false
});
```

### Authentication API

```typescript
import { auth } from '@kokolabs-io/sdk';

// Get current user
const user = auth.getUser();
if (user) {
  console.log(user.id);
  console.log(user.roles);
  console.log(user.scopes);
}

// Require authentication
try {
  const user = auth.require();
  console.log('Authenticated:', user.id);
} catch (error) {
  console.error('Unauthorized');
}

// Check whitelist
if (auth.isWhitelisted()) {
  console.log('User is whitelisted');
}

// Server-side authentication
import { auth } from '@kokolabs-io/sdk';

async function handler(req: Request) {
  // Require authentication for this request
  const user = await auth.requireAuth(req, {
    mode: 'auth',
    whitelist: true
  });

  return new Response(`Hello, ${user.id}`);
}

// Token management
auth.setToken('your-access-token');
const token = auth.getToken();

// Provider info
console.log(auth.provider()); // 'koko', 'custom', etc.
console.log(auth.isProviderPod()); // true/false
```

### Environment Variables

```typescript
import { env } from '@kokolabs-io/sdk';

const apiKey = env.API_KEY;
const dbUrl = env.DATABASE_URL;
const port = env.PORT || '3000';
```

### Custom Client

```typescript
import { createClient } from '@kokolabs-io/sdk';

const client = createClient({
  apiUrl: 'https://api.example.com',
  apiKey: 'your-api-key',
  podId: 'your-pod-id',
  token: 'your-access-token'
});

// Use the custom client
await client.sql.query('SELECT * FROM users');
const content = await client.fs.readText('/data/config.json');
```

## API Reference

### SQL API

```typescript
interface SqlApi {
  query(statement: string, params?: unknown[], options?: SqlOptions): Promise<SqlQueryResult>;
  execute(statement: string, params?: unknown[], options?: SqlOptions): Promise<SqlExecResult>;
  queryRaw(statement: string, params?: unknown[], options?: SqlOptions): Promise<SqlQueryResult>;
  queryEach(
    statement: string,
    params: unknown[] | undefined,
    options: SqlOptions | undefined,
    onRow: (row: unknown[]) => boolean | void
  ): Promise<SqlEachResult>;
  attach(targetPath: string, alias: string, options?: SqlOptions): Promise<SqlExecResult>;
  detach(alias: string, options?: SqlOptions): Promise<SqlExecResult>;
}
```

### File System API

```typescript
interface FsApi {
  read(path: string): string | Promise<string>;
  write(path: string, data: string, options?: { ifMatch?: string; force?: boolean }): unknown | Promise<unknown>;
  readText(path: string): Promise<string>;
  writeText(path: string, data: string, options?: { ifMatch?: string; force?: boolean }): Promise<boolean>;
  readBytes?(path: string): Promise<Uint8Array>;
  readBuffer?(path: string): Promise<ArrayBuffer>;
  writeBytes?(path: string, data: Uint8Array | ArrayBuffer): Promise<unknown>;
  tree?(path?: string, options?: { typed?: boolean; filesOnly?: boolean }): Promise<unknown>;
  mkdir?(path: string, recursive?: boolean): Promise<unknown>;
  rm?(path: string, recursive?: boolean): Promise<unknown>;
  exists?(path: string): Promise<boolean>;
  stat?(path: string): Promise<unknown>;
  readdir?(path: string): Promise<string[]>;
}
```

### Authentication API

```typescript
interface AuthApi {
  getUser(): KokoUser | null;
  provider(): string;
  isProviderPod(): boolean;
  whitelist(): string[];
  isWhitelisted(userId?: string): boolean;
  require(options?: { mode?: AuthMode; whitelist?: boolean }): KokoUser;
  requireAuth(req: Request, options?: { mode?: AuthMode; whitelist?: boolean; token?: string; accessToken?: string }): Promise<KokoUser>;
  getToken(): string;
  setToken(token: string): void;
  loadPodAuthConfig?(): Promise<PodAuthConfig>;
  loginPassword?(input: PasswordLoginInput): Promise<LoginResult>;
}
```

## Build

Build from root:

```bash
pnpm -C .. build
```

Build this package only:

```bash
pnpm --filter @kokolabs-io/sdk build
```

## License

MIT - Copyright (c) 2026 KokoLabs.io