npm package: @orchard9ai/warden-sdk
Description: TypeScript SDK for Warden Authentication and Authorization Platform
Author: Orchard9
Latest version: 0.2.1

# Warden TypeScript SDK

Official TypeScript SDK for the Warden Authentication and Authorization Platform.

**ESM-Only Package**: This package is published as an ES module for optimal compatibility with modern web applications, Vite, Next.js, and other modern bundlers.

## Installation

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

### Requirements

- **Node.js 18+** - Modern Node.js with ESM support
- **ESM Project** - Your project should support ES modules

For Node.js projects, add `"type": "module"` to your `package.json`:

```json
{
  "type": "module"
}
```

### Optional: React Query Support

If you're using React Query, you can take advantage of our generated hooks:

```bash
npm install @tanstack/react-query
```

## Quick Start

```typescript
import { initializeWardenClient, getAuthService } from '@orchard9ai/warden-sdk';

// Initialize the client
const client = initializeWardenClient({
  baseURL: 'http://localhost:21383', // Your Warden server URL
});

// Use the auth service
const authApi = getAuthService();

// Login
const loginResponse = await authApi.authServiceLogin({
  email: 'user@example.com',
  password: 'password123',
});

// Set the access token for future requests
client.setAccessToken(loginResponse.accessToken);

// Now you can make authenticated requests
const profile = await authApi.authServiceGetCurrentAccount();
console.log('Current user:', profile);
```

## Authentication Methods

### JWT Token Authentication

```typescript
import { initializeWardenClient, getAuthServiceApi } from '@orchard9/warden-sdk';

const client = initializeWardenClient({
  baseURL: 'http://localhost:21383',
});

const authApi = getAuthServiceApi();

// Login with email/password
const { data: tokens } = await authApi.authServiceLogin({
  email: 'user@example.com',
  password: 'password123',
});

// Use the access token
client.setAccessToken(tokens.accessToken);

// Refresh token when needed
const { data: newTokens } = await authApi.authServiceRefreshToken({
  refreshToken: tokens.refreshToken,
});
```

### API Key Authentication

```typescript
import { initializeWardenClient, getAuthServiceApi } from '@orchard9/warden-sdk';

const client = initializeWardenClient({
  baseURL: 'http://localhost:21383',
  apiKey: 'your-api-key-here',
});

// All requests will now use the API key
const authApi = getAuthServiceApi();
const { data: profile } = await authApi.authServiceGetCurrentAccount();
```

### Magic Link Authentication

```typescript
const authApi = getAuthServiceApi();

// Send magic code
await authApi.authServiceSendMagicCode({
  email: 'user@example.com',
});

// Verify magic code
const { data: tokens } = await authApi.authServiceVerifyMagicCode({
  email: 'user@example.com',
  code: '123456',
});

client.setAccessToken(tokens.accessToken);
```

## Organization Management

```typescript
import { getOrganizationServiceApi } from '@orchard9/warden-sdk';

const orgApi = getOrganizationServiceApi();

// List user's organizations
const { data: orgs } = await orgApi.organizationServiceListOrganizations();

// Create organization
const { data: newOrg } = await orgApi.organizationServiceCreateOrganization({
  name: 'Acme Corp',
  slug: 'acme-corp',
  description: 'The Acme Corporation',
});

// Switch organization context
const { data: switchResponse } = await authApi.authServiceSwitchOrganization({
  organizationId: newOrg.id,
});

// Update client with new tokens that have org context
client.setAccessToken(switchResponse.accessToken);
```

## User Management

```typescript
import { getUserServiceApi } from '@orchard9/warden-sdk';

const userApi = getUserServiceApi();

// Get current user profile
const { data: profile } = await userApi.userServiceGetProfile();

// Update profile
await userApi.userServiceUpdateProfile({
  displayName: 'John Doe',
  bio: 'Software Developer',
});

// List API keys
const { data: apiKeys } = await userApi.userServiceListApiKeys();

// Create API key
const { data: newKey } = await userApi.userServiceCreateApiKey({
  name: 'CI/CD Pipeline',
  description: 'Used by GitHub Actions',
  scopes: ['read:profile', 'write:data'],
});
```

## React Query Integration

If you're using React Query, you can use our generated hooks:

```tsx
import { useAuthServiceLogin, useUserServiceGetProfile } from '@orchard9/warden-sdk/react-query';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <LoginForm />
    </QueryClientProvider>
  );
}

function LoginForm() {
  const loginMutation = useAuthServiceLogin();
  const { data: profile, isLoading } = useUserServiceGetProfile();

  const handleLogin = async (email: string, password: string) => {
    const result = await loginMutation.mutateAsync({ email, password });
    // Handle successful login
  };

  if (isLoading) return <div>Loading...</div>;
  
  return (
    <div>
      {profile ? (
        <p>Welcome, {profile.displayName}!</p>
      ) : (
        <button onClick={() => handleLogin('user@example.com', 'password')}>
          Login
        </button>
      )}
    </div>
  );
}
```

## Error Handling

The SDK provides typed error responses:

```typescript
import { WardenError } from '@orchard9/warden-sdk';

try {
  await authApi.authServiceLogin({
    email: 'user@example.com',
    password: 'wrong-password',
  });
} catch (error) {
  if (error.response?.data) {
    const wardenError = error.response.data as WardenError;
    console.error(`Error ${wardenError.code}: ${wardenError.message}`);
    
    if (wardenError.details) {
      console.error('Details:', wardenError.details);
    }
  }
}
```

## Advanced Configuration

### Custom Axios Instance

You can provide your own Axios configuration:

```typescript
import axios from 'axios';
import { initializeWardenClient } from '@orchard9/warden-sdk';

const customAxios = axios.create({
  timeout: 30000,
  headers: {
    'X-Custom-Header': 'value',
  },
});

const client = initializeWardenClient({
  baseURL: 'http://localhost:21383',
  axios: customAxios,
});
```

### Token Refresh Callback

Handle token refresh automatically:

```typescript
const client = initializeWardenClient({
  baseURL: 'http://localhost:21383',
  onTokenRefresh: async (newToken: string) => {
    // Save the new token to your storage
    localStorage.setItem('accessToken', newToken);
  },
});
```

## TypeScript Support

The SDK is fully typed. All request and response types are generated from the OpenAPI specification:

```typescript
import type { 
  LoginRequest,
  LoginResponse,
  Account,
  Organization,
  ApiKey,
} from '@orchard9/warden-sdk';
```

## Development

### Regenerate SDK from OpenAPI

```bash
npm run generate
```

### Build

```bash
npm run build
```

### Test

```bash
npm test
```

## License

MIT License - see LICENSE file for details.