npm package: @gem64-sdk/sdk
Description: TypeScript SDK for Gem64 API
Author: Gem64 Team
Latest version: 1.0.0

# Gem64 SDK

A modern TypeScript SDK for interacting with the Gem64 API. Designed to provide type-safe access to authentication, entities.

## Features

- 🔐 **Complete Authentication System** - Login, registration, token management
- 📊 **Dynamic Entity Operations** - Type-safe CRUD operations for any entity
- 🔌 **Extensible Integrations** - Built-in integrations for AI, email, file uploads
- 📱 **Browser & Node.js Support** - Works in all JavaScript environments
- 🏗️ **TypeScript First** - Full type safety with excellent IDE support
- 🚀 **Tree-Shakeable** - Import only what you need
- 🔄 **Auto Token Refresh** - Seamless authentication management
- ⚡ **High Performance** - Optimized for speed and efficiency

## Installation

```bash
npm install @gem64-sdk/sdk
# or
yarn add @gem64-sdk/sdk
# or
pnpm add @gem64-sdk/sdk
```

## Quick Start

```typescript
import { createClient } from '@gem64-sdk/sdk'

// Create a client instance
const gem64 = createClient({
  appId: 'your-app-id',
  serverUrl: 'http://localhost:8080', // Your Gem64 API server
  env: 'dev' // or 'prod', 'staging'
})

// Authentication
const auth = await gem64.auth.loginWithCredentials('user@example.com', 'password')
console.log('Logged in as:', auth.user.name)

// Entity operations
const boards = await gem64.entities.Board.list()
const newBoard = await gem64.entities.Board.create({
  title: 'My New Board',
  description: 'A collaborative workspace'
})

// Integration usage
const aiResponse = await gem64.integrations.Core.InvokeLLM({
  prompt: 'Generate creative ideas for my project'
})
```

## Configuration

### Basic Configuration

```typescript
const client = createClient({
  appId: 'your-app-id',           // Required: Your application ID
  serverUrl: 'http://localhost:8080', // Optional: API server URL
  env: 'prod',                    // Optional: Environment (dev, staging, prod)
  autoInitAuth: true,             // Optional: Auto-detect tokens (default: true)
  timeout: 30000,                 // Optional: Request timeout in ms
  debug: false                    // Optional: Enable debug logging
})
```

### Environment Variables

You can also use environment variables:

```bash
GEM64_SERVER_URL=http://localhost:8080
GEM64_APP_ID=your-app-id
GEM64_ENV=dev
```

## Authentication

### Login and Registration

```typescript
// Login with email and password
const auth = await gem64.auth.loginWithCredentials('user@example.com', 'password')

// Register new user
const newUser = await gem64.auth.register('new@example.com', 'password', 'Full Name')

// Get current user
const user = await gem64.auth.me()

// Update user profile
const updatedUser = await gem64.auth.updateMe({
  name: 'Updated Name',
  profile: { bio: 'Software developer' }
})

// Change password
await gem64.auth.changePassword('oldPassword', 'newPassword')

// Logout
await gem64.auth.logout()
```

### Token Management

```typescript
// Check authentication status
const isAuth = await gem64.auth.isAuthenticated()

// Manual token management
gem64.setAccessToken('your-access-token')
gem64.setRefreshToken('your-refresh-token')

// Clear all tokens
gem64.clearTokens()
```

### Redirect-based Authentication

```typescript
// Redirect to hosted login page
gem64.auth.login('/dashboard') // Redirects back to /dashboard after login
```

## Entity Operations

The SDK provides dynamic entity access with full CRUD operations:

### Basic Operations

```typescript
// Get entity operations
const Board = gem64.entities.Board
const BoardItem = gem64.entities.BoardItem

// List entities
const boards = await Board.list()
const recentBoards = await Board.list('-createdAt', 10) // Sort by created date, limit 10

// Filter entities
const myBoards = await Board.filter({ 
  owner: userId,
  isPublic: false 
})

// Get specific entity
const board = await Board.get('board-id')

// Create new entity
const newBoard = await Board.create({
  title: 'Project Planning',
  description: 'Strategic planning board',
  isPublic: false
})

// Update entity
const updatedBoard = await Board.update('board-id', {
  title: 'Updated Title'
})

// Delete entity
await Board.delete('board-id')
```

### Advanced Operations

```typescript
// Bulk operations
const results = await Board.bulkCreate({
  data: [
    { title: 'Board 1', description: 'First board' },
    { title: 'Board 2', description: 'Second board' }
  ]
})

// Delete multiple entities
const deleteResult = await Board.deleteMany({ 
  owner: userId,
  lastActivity: { $lt: '2024-01-01' }
})

// Update multiple entities
const updateResult = await Board.bulkUpdate(
  { owner: userId },
  { isArchived: true }
)
```

### Pagination and Sorting

```typescript
// Paginated list
const boards = await Board.list('-createdAt', 20, 0) // Sort desc, limit 20, skip 0

// Filtered with pagination
const filtered = await Board.filter(
  { isPublic: true },
  'title',  // Sort by title
  10,       // Limit
  20,       // Skip
  ['title', 'description'] // Only return these fields
)
```

## Integrations

### Core Integrations

The SDK includes built-in integrations for common services:

```typescript
// AI/LLM Integration
const aiResponse = await gem64.integrations.Core.InvokeLLM({
  prompt: 'Generate 5 creative project names',
  model: 'gpt-4',
  temperature: 0.7,
  maxTokens: 150
})

// Email Integration
const emailResult = await gem64.integrations.Core.SendEmail({
  to: 'user@example.com',
  subject: 'Welcome to our platform',
  body: 'Thank you for joining!',
  isHtml: true
})

// File Upload
const fileInput = document.querySelector('input[type="file"]')
const file = fileInput.files[0]
const uploadResult = await gem64.integrations.Core.UploadFile({
  file,
  metadata: { type: 'profile-picture' }
})

// Image Generation
const imageResult = await gem64.integrations.Core.GenerateImage({
  prompt: 'A futuristic city skyline at sunset',
  size: '1024x1024',
  quality: 'hd'
})

// Data Extraction
const extractedData = await gem64.integrations.Core.ExtractDataFromUploadedFile({
  fileId: 'uploaded-file-id',
  type: 'structured',
  options: { format: 'json' }
})
```

### Custom Integrations

```typescript
// Use custom integration packages
const customResult = await gem64.integrations.MyPackage.MyEndpoint({
  customParam: 'value',
  options: { setting: true }
})

// Or execute directly
const result = await gem64.integrations.execute('MyPackage', 'MyEndpoint', {
  data: 'request data'
})
```

## Error Handling

The SDK provides comprehensive error handling:

```typescript
import { Gem64Error, HttpError, AuthError, ValidationError } from '@gem64-sdk/sdk'

try {
  const board = await gem64.entities.Board.get('invalid-id')
} catch (error) {
  if (error instanceof AuthError) {
    console.log('Authentication required:', error.getUserMessage())
    gem64.auth.login() // Redirect to login
  } else if (error instanceof ValidationError) {
    console.log('Validation errors:', error.getFieldErrors('title'))
  } else if (error instanceof HttpError) {
    console.log('HTTP error:', error.status, error.getUserMessage())
    if (error.isRecoverable()) {
      // Retry after delay
      setTimeout(() => retry(), error.getRetryDelay())
    }
  } else if (error instanceof Gem64Error) {
    console.log('SDK error:', error.getSummary())
  }
}
```

## React Integration

### Authentication Hook

```typescript
import { createClient } from '@gem64-sdk/sdk'
import { createContext, useContext, useEffect, useState } from 'react'

const Gem64Context = createContext(null)

export function Gem64Provider({ children }) {
  const [client] = useState(() => createClient({ appId: 'your-app-id' }))
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    async function initAuth() {
      try {
        if (await client.auth.isAuthenticated()) {
          const userData = await client.auth.me()
          setUser(userData)
        }
      } catch (error) {
        console.error('Auth init failed:', error)
      } finally {
        setLoading(false)
      }
    }
    
    initAuth()
  }, [client])

  return (
    <Gem64Context.Provider value={{ client, user, loading }}>
      {children}
    </Gem64Context.Provider>
  )
}

export function useGem64() {
  const context = useContext(Gem64Context)
  if (!context) throw new Error('useGem64 must be used within Gem64Provider')
  return context
}
```

### Data Fetching Hook

```typescript
import { useEffect, useState } from 'react'
import { useGem64 } from './Gem64Provider'

export function useEntity(entityName, id) {
  const { client } = useGem64()
  const [entity, setEntity] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  useEffect(() => {
    async function fetchEntity() {
      try {
        setLoading(true)
        const data = await client.entities[entityName].get(id)
        setEntity(data)
      } catch (err) {
        setError(err)
      } finally {
        setLoading(false)
      }
    }

    if (id) fetchEntity()
  }, [client, entityName, id])

  return { entity, loading, error }
}
```

## TypeScript Support

The SDK is written in TypeScript and provides excellent type safety:

```typescript
import type { Board, BoardItem, User } from '@gem64-sdk/sdk'

// Type-safe entity operations
const board: Board = await gem64.entities.Board.get('board-id')
const items: BoardItem[] = await gem64.entities.BoardItem.filter({
  boardId: board.id
})

// Custom entity types
interface CustomEntity extends Entity {
  customField: string
  metadata: { tags: string[] }
}

const customEntity = gem64.entities.getEntity<CustomEntity>('CustomEntity')
const result: CustomEntity = await customEntity.get('id')
```

## Advanced Usage

### Custom HTTP Client

```typescript
const client = createClient({ appId: 'your-app-id' })

// Access HTTP client for custom requests
const httpClient = client.getHttpClient()
const response = await httpClient.request({
  method: 'GET',
  url: '/custom-endpoint',
  requiresAuth: true
})
```

### Configuration Management

```typescript
// Update configuration at runtime
client.updateConfig({
  timeout: 60000,
  debug: true
})

// Get current configuration
const config = client.getConfig()
console.log('Current server:', config.serverUrl)
```

### Health Checks

```typescript
// Check API health
const health = await client.healthCheck()
console.log('API Status:', health.status)
```

## Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

## License

MIT License - see [LICENSE](LICENSE) file for details.

## Support

- 📖 [Documentation](https://docs.gem64.com)
- 🐛 [Issue Tracker](https://github.com/gem64/sdk/issues)
- 💬 [Discord Community](https://discord.gg/gem64)
- 📧 Email: support@gem64.com