> ## Documentation Index
> Fetch the complete documentation index at: https://docs.snackbase.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Client Reference

> Complete reference for the SnackBaseClient class

This is a complete reference for the `SnackBaseClient` class, the main entry point for the SnackBase JavaScript SDK.

## Constructor

Create a new SnackBaseClient instance:

```ts theme={null}
import { SnackBaseClient } from "@snackbase/sdk";

const client = new SnackBaseClient(config: SnackBaseConfig);
```

### Configuration

```ts theme={null}
interface SnackBaseConfig {
  // Required
  baseUrl: string;

  // Optional - Authentication
  apiKey?: string;
  defaultAccount?: string;

  // Optional - Request settings
  timeout?: number;
  maxRetries?: number;
  retryDelay?: number;

  // Optional - Token management
  enableAutoRefresh?: boolean;
  refreshBeforeExpiry?: number;
  storageBackend?: StorageBackend;

  // Optional - Realtime
  maxRealTimeRetries?: number;
  realTimeReconnectionDelay?: number;

  // Optional - Logging
  enableLogging?: boolean;
  logLevel?: LogLevel;

  // Optional - Error callbacks
  onAuthError?: (error: any) => void;
  onNetworkError?: (error: any) => void;
  onRateLimitError?: (error: any) => void;
}

type StorageBackend = "localStorage" | "sessionStorage" | "memory" | "asyncStorage";
type LogLevel = "debug" | "info" | "warn" | "error";
```

## Properties

### Auth State

```ts theme={null}
// Current authenticated user
client.user: User | null

// Current account
client.account: Account | null

// Authentication status
client.isAuthenticated: boolean
```

### Services

```ts theme={null}
// Authentication service
client.auth: AuthService

// Account management
client.accounts: AccountService

// User management
client.users: UserService

// Collection management
client.collections: CollectionService

// Record operations
client.records: RecordService

// Group management
client.groups: GroupsService

// Invitation management
client.invitations: InvitationService

// API key management
client.apiKeys: ApiKeyService

// Audit log access
client.auditLogs: AuditLogService

// Role management
client.roles: RoleService

// Collection rule management
client.collectionRules: CollectionRuleService

// Macro operations
client.macros: MacroService

// Dashboard statistics
client.dashboard: DashboardService

// System administration
client.admin: AdminService

// Email template management
client.emailTemplates: EmailTemplateService

// File management
client.files: FileService

// Real-time features
client.realtime: RealTimeService

// Migration status
client.migrations: MigrationService
```

## Methods

### Configuration

#### `getConfig()`

Get the current client configuration.

```ts theme={null}
const config = client.getConfig(): Required<SnackBaseConfig>
```

**Returns:** The merged configuration object with defaults applied.

***

### Authentication

#### `login(credentials)`

Authenticate with email and password.

```ts theme={null}
await client.login(credentials: LoginCredentials): Promise<AuthResponse>
```

**Alias for:** `client.auth.loginWithPassword()`

***

#### `logout()`

Log out the current user.

```ts theme={null}
await client.logout(): Promise<void>
```

**Alias for:** `client.auth.logout()`

***

#### `register(data)`

Register a new user and account.

```ts theme={null}
await client.register(data: RegisterData): Promise<AuthResponse>
```

**Alias for:** `client.auth.register()`

***

#### `refreshToken()`

Refresh the access token.

```ts theme={null}
await client.refreshToken(): Promise<TokenResponse>
```

**Alias for:** `client.auth.refreshToken()`

***

#### `getCurrentUser()`

Get the current authenticated user profile.

```ts theme={null}
await client.getCurrentUser(): Promise<User>
```

**Alias for:** `client.auth.getCurrentUser()`

***

#### `forgotPassword(data)`

Initiate password reset flow.

```ts theme={null}
await client.forgotPassword(data: PasswordResetRequest): Promise<void>
```

**Alias for:** `client.auth.forgotPassword()`

***

#### `resetPassword(data)`

Reset password using a token.

```ts theme={null}
await client.resetPassword(data: PasswordResetConfirm): Promise<void>
```

**Alias for:** `client.auth.resetPassword()`

***

#### `verifyEmail(token)`

Verify email using a token.

```ts theme={null}
await client.verifyEmail(token: string): Promise<void>
```

**Alias for:** `client.auth.verifyEmail()`

***

#### `resendVerificationEmail()`

Resend the verification email to the current user.

```ts theme={null}
await client.resendVerificationEmail(): Promise<void>
```

**Alias for:** `client.auth.resendVerificationEmail()`

***

#### `getSAMLUrl(provider, account, relayState?)`

Generate SAML SSO authorization URL.

```ts theme={null}
await client.getSAMLUrl(
  provider: SAMLProvider,
  account: string,
  relayState?: string
): Promise<string>
```

**Alias for:** `client.auth.getSAMLUrl()`

***

#### `handleSAMLCallback(params)`

Handle SAML callback.

```ts theme={null}
await client.handleSAMLCallback(params: SAMLCallbackParams): Promise<AuthResponse>
```

**Alias for:** `client.auth.handleSAMLCallback()`

***

#### `getSAMLMetadata(provider, account)`

Get SAML metadata.

```ts theme={null}
await client.getSAMLMetadata(
  provider: SAMLProvider,
  account: string
): Promise<string>
```

**Alias for:** `client.auth.getSAMLMetadata()`

***

### Events

#### `on(event, listener)`

Subscribe to authentication events.

```ts theme={null}
client.on<K extends keyof AuthEvents>(
  event: K,
  listener: AuthEvents[K]
): () => void
```

**Returns:** Unsubscribe function

**Events:**

* `auth:login` - User logged in
* `auth:logout` - User logged out
* `auth:refresh` - Token refreshed
* `auth:error` - Authentication error

**Example:**

```ts theme={null}
const unsubscribe = client.on("auth:login", (state) => {
  console.log("User logged in:", state.user);
});

// Unsubscribe later
unsubscribe();
```

***

## Complete Example

```ts theme={null}
import { SnackBaseClient } from "@snackbase/sdk";

const client = new SnackBaseClient({
  baseUrl: "https://api.example.com",
  defaultAccount: "my-account",
  timeout: 30000,
  maxRetries: 3,
  enableLogging: true,
  logLevel: "debug",
});

// Listen to auth events
client.on("auth:login", (state) => {
  console.log("Logged in as:", state.user.email);
});

client.on("auth:logout", () => {
  console.log("Logged out");
  window.location.href = "/login";
});

// Use services
const posts = await client.records.list("posts");
const collections = await client.collections.list();

// Access auth state
console.log("Authenticated:", client.isAuthenticated);
console.log("User:", client.user);
console.log("Account:", client.account);
```

## Next Steps

* **[Type Reference](/sdk/js/reference/types)** - Type definitions
* **[Services](/sdk/js/services/records)** - Service references
* **[Configuration](/sdk/js/configuration)** - Configuration options
