npm package: @maravilla-labs/platform
Description: Universal platform client for Maravilla runtime
Latest version: 0.1.27

# @maravilla/platform

Universal platform client for Maravilla Runtime that provides seamless access to KV, Database, and other platform services in both development and production environments.

## 🎯 Enhanced Developer Experience

This package includes **comprehensive JSDoc documentation** for enhanced IDE support:
- **IntelliSense** with detailed parameter descriptions
- **Hover tooltips** with examples and usage guidance  
- **Type hints** with real-world examples
- **Auto-completion** with contextual help

> 💡 **IDE Integration**: Works with VS Code, WebStorm, and any TypeScript-compatible editor

## Installation

```bash
npm install @maravilla/platform
# or
pnpm add @maravilla/platform
# or
yarn add @maravilla/platform
```

## Usage

### Basic Setup

```typescript
import { getPlatform } from '@maravilla/platform';

// Auto-detects environment (dev/prod)
const platform = getPlatform();

// Access platform services
const { KV, DB } = platform.env;
```

### Development Mode

In development, the client automatically connects to the Maravilla dev server running on port 3001. Make sure to start the dev server first:

```bash
# Start the dev server
maravilla dev --port 3001

# In another terminal, start your app
npm run dev
```

### Production Mode

In production, the platform client is injected by the Maravilla runtime automatically. No configuration needed.

## API Reference

### KV Store

Key-Value store for caching and simple data storage.

```typescript
// Get a value
const value = await platform.env.KV.get('my-key');

// Set a value with optional TTL (in seconds)
await platform.env.KV.put('my-key', 'my-value', {
  expirationTtl: 3600, // Expires in 1 hour
});

// Delete a value
await platform.env.KV.delete('my-key');

// List keys with optional prefix
const keys = await platform.env.KV.list({
  prefix: 'user:',
  limit: 100,
  cursor: 'optional-cursor-for-pagination',
});
```

### Database (MongoDB-style API)

Document database with MongoDB-compatible query and update operators.

#### Query Operations

```typescript
// Find multiple documents
const users = await platform.env.DB.find('users', {
  active: true,
  age: { $gte: 18 },
});

// Find single document
const user = await platform.env.DB.findOne('users', {
  _id: 'user-123',
});

// With options (limit, skip, sort)
const posts = await platform.env.DB.find('posts', 
  { published: true },
  { 
    limit: 10,
    skip: 20,
    sort: { createdAt: -1 },
  }
);
```

#### Insert Operations

```typescript
// Insert single document
const result = await platform.env.DB.insertOne('users', {
  name: 'John Doe',
  email: 'john@example.com',
  createdAt: new Date(),
});
console.log(result.insertedId); // Generated ID

// Insert multiple documents
const results = await platform.env.DB.insertMany('users', [
  { name: 'Alice', email: 'alice@example.com' },
  { name: 'Bob', email: 'bob@example.com' },
]);
console.log(results.insertedIds); // Array of IDs
```

#### Update Operations

```typescript
// Update single document
await platform.env.DB.updateOne('users',
  { _id: 'user-123' },
  { 
    $set: { name: 'Updated Name' },
    $inc: { loginCount: 1 },
    $push: { tags: 'new-tag' },
  }
);

// Update multiple documents
await platform.env.DB.updateMany('users',
  { status: 'pending' },
  { $set: { status: 'active' } }
);
```

##### Supported Update Operators

- `$set` - Set field values
- `$unset` - Remove fields
- `$inc` - Increment numeric values
- `$push` - Add to array
- `$pull` - Remove from array
- `$addToSet` - Add unique value to array

#### Delete Operations

```typescript
// Delete single document
await platform.env.DB.deleteOne('users', {
  _id: 'user-123',
});

// Delete multiple documents
const result = await platform.env.DB.deleteMany('users', {
  inactive: true,
  lastLogin: { $lt: thirtyDaysAgo },
});
console.log(result.deletedCount);
```

### Storage (Coming Soon)

Object storage for files and large data.

```typescript
// Future API
await platform.env.STORAGE.put('file-key', buffer);
const file = await platform.env.STORAGE.get('file-key');
await platform.env.STORAGE.delete('file-key');
```

## Environment Detection

The client automatically detects the environment:

1. **Development**: When `MARAVILLA_DEV_SERVER` env var is set (automatically set by vite-plugin)
2. **Production**: When running inside Maravilla runtime (global `__MARAVILLA_PLATFORM__` is available)
3. **Fallback**: Returns a mock platform for testing

## TypeScript Support

Full TypeScript support with comprehensive JSDoc documentation:

```typescript
import type { Platform, KVNamespace, Database } from '@maravilla/platform';

function myFunction(platform: Platform) {
  const kv: KVNamespace = platform.env.KV;
  const db: Database = platform.env.DB;
  
  // Hover over any method to see detailed documentation
  // Get parameter hints as you type
}
```

### IDE Features
- **Parameter IntelliSense**: See parameter descriptions while typing
- **Method Documentation**: Hover for detailed explanations and examples
- **Type Safety**: Full TypeScript integration with runtime type checking
- **Error Context**: Understand what errors might be thrown and when

> 📖 **See [JSDOC_GUIDE.md](./JSDOC_GUIDE.md) for detailed IDE integration information**

## Framework Integration

### SvelteKit

```typescript
// src/routes/+page.server.ts
import { getPlatform } from '@maravilla/platform';

export async function load() {
  const platform = getPlatform();
  const data = await platform.env.KV.get('my-data');
  
  return {
    data: data ? JSON.parse(data) : null,
  };
}
```

### Nuxt (Coming Soon)

```typescript
// server/api/data.ts
export default defineEventHandler(async (event) => {
  const platform = getPlatform();
  const data = await platform.env.DB.find('items', {});
  return data;
});
```

### Next.js (Coming Soon)

```typescript
// app/api/route.ts
import { getPlatform } from '@maravilla/platform';

export async function GET() {
  const platform = getPlatform();
  const value = await platform.env.KV.get('key');
  return Response.json({ value });
}
```

## Error Handling

All methods throw errors that should be handled:

```typescript
try {
  const data = await platform.env.KV.get('key');
} catch (error) {
  console.error('Failed to get KV value:', error);
  // Handle error appropriately
}
```

## Development Tips

1. **Start Dev Server First**: Always start `maravilla dev` before your app dev server
2. **Use Namespaces**: Prefix your KV keys to avoid collisions (e.g., `user:123`, `cache:api:...`)
3. **Handle Missing Data**: Always check for null/undefined when getting values
4. **Use TTL**: Set expiration for cache entries to avoid stale data
5. **Batch Operations**: Use `insertMany`/`updateMany` for better performance

## License

Proprietary. © 2025 SOLUTAS GmbH, Switzerland. All rights reserved.
Use is governed by the root LICENSE file or a separate written agreement
with SOLUTAS GmbH.