npm package: @refleet/refleet-sdk-js
Description: Refleet TypeScript SDK
Author: Qiulin Li
Latest version: 0.1.0

# Refleet TypeScript SDK

[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![bundle][bundle-src]][bundle-href]
[![JSDocs][jsdocs-src]][jsdocs-href]
[![License][license-src]][license-href]

TypeScript/JavaScript SDK for Refleet BaaS platform. Supports both HTTP and gRPC protocols.

## Features

- 🚀 **Dual Protocol Support** - Switch between HTTP and gRPC with a single configuration change
- 📦 **Full TypeScript Support** - Complete type safety from Protocol Buffer definitions
- 🔐 **Built-in Auth Management** - Automatic token refresh and authentication handling
- 🎯 **Intuitive API** - Clean, modern API design with full IntelliSense support
- 🛡️ **Error Handling** - Structured error types with retry logic
- 📝 **Well Documented** - Comprehensive examples and documentation

## Installation

```bash
# npm
npm install refleet-sdk-ts

# yarn
yarn add refleet-sdk-ts

# pnpm
pnpm add refleet-sdk-ts
```

## Quick Start

```typescript
import { RefleetClient } from 'refleet-sdk-ts'

// Initialize client
const client = new RefleetClient({
  protocol: 'http',
  baseURL: 'https://api.refleet.cloud'
})

// Login
const response = await client.auth.login('user@example.com', 'password')

// Set auth token
client.setAuthToken(response.token)

// Use services
const teams = await client.teams.listTeams({
  pageSize: 10,
  pageToken: '',
  filter: '',
  orderBy: ''
})

console.log(teams.teams)
```

## Configuration

### Basic Configuration

```typescript
const client = new RefleetClient({
  protocol: 'http',  // 'rest' or 'grpc'
  baseURL: 'https://api.refleet.cloud'
})
```

### Advanced Configuration

```typescript
const client = new RefleetClient({
  protocol: 'http',
  baseURL: 'https://api.refleet.cloud',

  // Auth token (optional, can set later)
  authToken: 'your-jwt-token',

  // Request timeout in milliseconds
  timeout: 30000,

  // Custom headers
  headers: {
    'X-Custom-Header': 'value'
  },

  // Auto-refresh token on 401
  refreshAuthToken: async () => {
    const response = await fetch('/refresh-token')
    const data = await response.json()
    return data.token
  },

  // Enable debug logging
  debug: false
})
```

## Protocol Support

### HTTP Protocol (Recommended for Web)

Uses standard HTTP/JSON for communication. Better compatibility and easier debugging.

```typescript
const client = new RefleetClient({
  protocol: 'http',
  baseURL: 'https://api.refleet.cloud'
})
```

### gRPC Protocol (Coming Soon)

Uses binary protobuf for better performance. Ideal for high-throughput applications.

```typescript
// Note: gRPC transport is not yet implemented
const client = new RefleetClient({
  protocol: 'grpc',
  baseURL: 'https://api.refleet.cloud'
})
```

## Services

### AuthService

Authentication and user management operations.

```typescript
// Login
const response = await client.auth.login('user@example.com', 'password')
console.log(response.token)

// Sign up
const signUpResponse = await client.auth.signUp({
  username: 'newuser',
  email: 'user@example.com',
  password: 'SecurePassword123!',
  phone: '+1234567890',
  data: {
    referralCode: 'ABC123'
  }
})

// Refresh token
const newToken = await client.auth.refreshToken('refresh-token')
```

### TeamsService

Team management operations.

```typescript
// Create team
const team = await client.teams.createTeam({
  team: {
    name: 'acme-corp',
    displayName: 'Acme Corporation',
    icon: '🏢',
    plan: 'pro'
  }
})

// Get team
const teamDetails = await client.teams.getTeam({
  teamId: 'team-123'
})

// List teams
const teamsList = await client.teams.listTeams({
  pageSize: 20,
  pageToken: '',
  filter: 'plan == "pro"',
  orderBy: 'name asc'
})

// Find by name
const foundTeam = await client.teams.findByName('acme-corp')
```

## Pagination

For list operations that return many items, use pagination:

```typescript
let allTeams = []
let pageToken = ''

do {
  const response = await client.teams.listTeams({
    pageSize: 50,
    pageToken,
    filter: '',
    orderBy: 'name asc'
  })

  allTeams.push(...response.teams)
  pageToken = response.nextPageToken
} while (pageToken)

console.log(`Total teams: ${allTeams.length}`)
```

## Error Handling

The SDK provides specific error types for different scenarios:

```typescript
import {
  AuthenticationError,
  ValidationError,
  NotFoundError,
  PermissionError,
  RateLimitError,
  isRetryableError
} from 'refleet-sdk-ts'

try {
  await client.auth.login('user@example.com', 'password')
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Authentication failed:', error.message)
  } else if (error instanceof ValidationError) {
    console.error('Invalid input:', error.message)
  } else if (error instanceof NotFoundError) {
    console.error('Resource not found:', error.message)
  } else if (error instanceof PermissionError) {
    console.error('Permission denied:', error.message)
  } else if (error instanceof RateLimitError) {
    console.error('Rate limit exceeded:', error.message)
  }

  // Check if error is retryable
  if (isRetryableError(error)) {
    console.log('You can retry this request')
  }
}
```

## Token Management

### Manual Token Management

```typescript
// Login and get token
const response = await client.auth.login('user@example.com', 'password')

// Set token for subsequent requests
client.setAuthToken(response.token)

// Clear token (logout)
client.clearAuthToken()

// Get current token
const token = client.getAuthToken()
```

### Auto Token Refresh

Configure automatic token refresh:

```typescript
const client = new RefleetClient({
  protocol: 'http',
  baseURL: 'https://api.refleet.cloud',
  authToken: 'your-access-token',
  refreshAuthToken: async () => {
    // Logic to refresh token
    const response = await fetch('https://api.refleet.cloud/v1/refresh', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        refresh_token: 'your-refresh-token'
      })
    })
    const data = await response.json()
    return data.token
  }
})

// Token will automatically refresh on 401 errors
await client.teams.listTeams({ ... })
```

## Advanced Examples

### Custom Headers

```typescript
const client = new RefleetClient({
  protocol: 'http',
  baseURL: 'https://api.refleet.cloud',
  headers: {
    'X-Custom-Header': 'value',
    'X-Request-ID': '12345'
  }
})
```

### Debug Mode

```typescript
const client = new RefleetClient({
  protocol: 'http',
  baseURL: 'https://api.refleet.cloud',
  debug: true  // Enable request/response logging
})
```

### Cleanup

```typescript
try {
  // ... use client
  await client.auth.login('user@example.com', 'password')
} finally {
  // Always close client when done
  await client.close()
}
```

## Type Safety

Full TypeScript support with auto-completion:

```typescript
import type {
  TokenRequest,
  TokenResponse,
  Team,
  CreateTeamRequest
} from 'refleet-sdk-ts'

// Types are automatically inferred
const request: TokenRequest = {
  grantType: 'password',
  email: 'user@example.com',
  password: 'password',
  username: '',
  phone: '',
  refreshToken: ''
}
```

## Browser Support

- Chrome/Edge: ✅ Latest
- Firefox: ✅ Latest
- Safari: ✅ Latest
- Mobile browsers: ✅ Latest

## Development

```bash
# Install dependencies
pnpm install

# Build
pnpm build

# Run tests
pnpm test

# Type check
pnpm typecheck

# Lint
pnpm lint

# Watch mode
pnpm dev

# Run test page (browser-based testing)
pnpm test-page
```

### Browser Test Page

The SDK includes a browser-based test page for interactive testing:

```bash
# Start the test page dev server
pnpm test-page
```

This will open a web interface where you can:
- Connect to a Refleet API instance
- Test authentication flows
- Run API tests (list teams, create teams, etc.)
- View real-time logs

See [test-page/README.md](./test-page/README.md) for more details.

## Roadmap

- [ ] gRPC transport implementation
- [ ] Streaming support
- [ ] React hooks
- [ ] Vue composables
- [ ] More services (Users, Projects, Collections, etc.)
- [ ] Retry logic with exponential backoff
- [ ] Request caching
- [ ] Observability/monitoring hooks

## Contributing

Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) for details.

## License

[MIT](./LICENSE.md) License © [Qiulin Li](https://github.com/refleet)

## Sponsors

<p align="center">
  <a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
    <img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
  </a>
</p>

<!-- Badges -->

[npm-version-src]: https://img.shields.io/npm/v/refleet-sdk-ts?style=flat&colorA=080f12&colorB=1fa669
[npm-version-href]: https://npmjs.com/package/refleet-sdk-ts
[npm-downloads-src]: https://img.shields.io/npm/dm/refleet-sdk-ts?style=flat&colorA=080f12&colorB=1fa669
[npm-downloads-href]: https://npmjs.com/package/refleet-sdk-ts
[bundle-src]: https://img.shields.io/bundlephobia/minzip/refleet-sdk-ts?style=flat&colorA=080f12&colorB=1fa669&label=minzip
[bundle-href]: https://bundlephobia.com/result?p=refleet-sdk-ts
[license-src]: https://img.shields.io/github/license/deeplooplabs/refleet.svg?style=flat&colorA=080f12&colorB=1fa669
[license-href]: https://github.com/deeplooplabs/refleet/blob/main/sdks/ts/LICENSE.md
[jsdocs-src]: https://img.shields.io/badge/jsdocs-reference-080f12?style=flat&colorA=080f12&colorB=1fa669
[jsdocs-href]: https://www.jsdocs.io/package/refleet-sdk-ts