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

# Types & Interfaces

> TypeScript type definitions for both Grain SDKs

## Grain Tag Types

```typescript theme={null}
import type { GrainTagConfig, GrainTagInstance, ConsentState } from '@grainql/tag';
```

### GrainTagConfig

Configuration options passed to `init()`.

```typescript theme={null}
interface GrainTagConfig {
  // Required
  tenantId: string;

  // API
  apiUrl?: string;

  // Debug
  debug?: boolean;

  // Version
  version?: string;

  // Consent
  consentMode?: 'auto' | 'opt-in' | 'opt-out';

  // Tracking features
  enablePageViews?: boolean;
  enableHeatmaps?: boolean;
  enableSnapshots?: boolean;
  enableRescue?: boolean;

  // Advanced
  batchSize?: number;
  flushInterval?: number;
  retryAttempts?: number;
}
```

| Field             | Type                              | Default        | Description                    |
| ----------------- | --------------------------------- | -------------- | ------------------------------ |
| `tenantId`        | `string`                          | *required*     | Your tenant identifier         |
| `apiUrl`          | `string`                          | Production URL | Override the API endpoint      |
| `debug`           | `boolean`                         | `false`        | Enable debug logging           |
| `version`         | `string`                          | —              | SDK version override           |
| `consentMode`     | `'auto' \| 'opt-in' \| 'opt-out'` | `'auto'`       | Consent handling strategy      |
| `enablePageViews` | `boolean`                         | `true`         | Auto-track page views          |
| `enableHeatmaps`  | `boolean`                         | `true`         | Track clicks and scroll depth  |
| `enableSnapshots` | `boolean`                         | `true`         | Capture DOM snapshots          |
| `enableRescue`    | `boolean`                         | `true`         | Enable rescue tracking         |
| `batchSize`       | `number`                          | `50`           | Max events per batch           |
| `flushInterval`   | `number`                          | `5000`         | Flush interval in milliseconds |
| `retryAttempts`   | `number`                          | `3`            | Number of retry attempts       |

***

### GrainTagInstance

The instance returned by `init()` and `getInstance()`.

```typescript theme={null}
interface GrainTagInstance {
  track(eventName: string, properties?: Record<string, unknown>): void;
  identify(userId: string): void;
  consent: {
    grant(categories?: string[]): void;
    revoke(categories?: string[]): void;
    status(): ConsentState | null;
  };
  flush(): Promise<void>;
  destroy(): void;
  isReady(): boolean;
}
```

***

### ConsentState

Returned by `grain.consent.status()`.

```typescript theme={null}
interface ConsentState {
  granted: boolean;
  categories: string[];
  timestamp: number;
  version: string;
}
```

| Field        | Type       | Description                                                   |
| ------------ | ---------- | ------------------------------------------------------------- |
| `granted`    | `boolean`  | Whether consent is currently granted                          |
| `categories` | `string[]` | Active consent categories (e.g. `['necessary', 'analytics']`) |
| `timestamp`  | `number`   | Unix timestamp of the consent decision                        |
| `version`    | `string`   | Consent version identifier                                    |

***

### ConsentMode

```typescript theme={null}
type ConsentMode = 'auto' | 'opt-in' | 'opt-out';
```

* **`auto`** — Starts in cookieless mode, upgrades when consent is granted
* **`opt-in`** — Requires explicit consent before any tracking beyond necessary
* **`opt-out`** — Full tracking by default, respects revocation

***

### ConsentCategory

```typescript theme={null}
type ConsentCategory = 'necessary' | 'analytics' | 'functional' | 'marketing';
```

***

## Analytics Web Types

```typescript theme={null}
import type { GrainConfig, GrainEvent, AuthProvider } from '@grainql/analytics-web';
```

### GrainConfig

Configuration options for `createGrainAnalytics()`.

```typescript theme={null}
interface GrainConfig {
  // Required
  tenantId: string;

  // Authentication
  authStrategy?: 'NONE' | 'SERVER_SIDE' | 'JWT';
  secretKey?: string;
  authProvider?: AuthProvider;

  // User
  userId?: string;

  // API
  apiUrl?: string;

  // Batching
  batchSize?: number;
  flushInterval?: number;

  // Retry
  retryAttempts?: number;
  retryDelay?: number;

  // Remote Config
  defaultConfigurations?: Record<string, string>;
  configCacheKey?: string;
  configRefreshInterval?: number;
  enableConfigCache?: boolean;

  // Debug
  debug?: boolean;
}
```

***

### GrainEvent

Event structure for tracking.

```typescript theme={null}
interface GrainEvent {
  eventName: string;
  userId?: string;
  properties?: Record<string, unknown>;
  timestamp?: Date;
}
```

***

### AuthProvider

JWT authentication provider interface.

```typescript theme={null}
interface AuthProvider {
  getToken(): Promise<string> | string;
}
```

**Example:**

```typescript theme={null}
const authProvider: AuthProvider = {
  async getToken() {
    return await auth0.getAccessToken();
  }
};
```

***

## Options Types

### SendEventOptions

Options for the Analytics Web `track()` method.

```typescript theme={null}
interface SendEventOptions {
  flush?: boolean;  // Force immediate send
}
```

***

### SetPropertyOptions

Options for the Analytics Web `setProperty()` method.

```typescript theme={null}
interface SetPropertyOptions {
  userId?: string;  // User ID override
}
```

***

### RemoteConfigOptions

Options for Analytics Web configuration methods.

```typescript theme={null}
interface RemoteConfigOptions {
  immediateKeys?: string[];
  properties?: Record<string, string>;
  userId?: string;
  forceRefresh?: boolean;
}
```

***

## Response Types

### RemoteConfigResponse

API response for configuration fetch.

```typescript theme={null}
interface RemoteConfigResponse {
  userId: string;
  snapshotId: string;
  configurations: Record<string, string>;
  isFinal: boolean;
  qualifiedSegments: string[];
  qualifiedRuleSets: string[];
  timestamp: string;
  isFromCache: boolean;
}
```

***

## Template Event Types

### LoginEventProperties

```typescript theme={null}
interface LoginEventProperties extends Record<string, unknown> {
  method?: string;
  success?: boolean;
  errorMessage?: string;
  loginAttempt?: number;
  rememberMe?: boolean;
  twoFactorEnabled?: boolean;
}
```

***

### SignupEventProperties

```typescript theme={null}
interface SignupEventProperties extends Record<string, unknown> {
  method?: string;
  source?: string;
  plan?: string;
  success?: boolean;
  referralCode?: string;
}
```

***

### CheckoutEventProperties

```typescript theme={null}
interface CheckoutEventProperties extends Record<string, unknown> {
  orderId?: string;
  total?: number;
  currency?: string;
  items?: Array<{
    id: string;
    name: string;
    price: number;
    quantity: number;
  }>;
  paymentMethod?: string;
  success?: boolean;
  errorMessage?: string;
  couponCode?: string;
  discount?: number;
}
```

***

### PurchaseEventProperties

```typescript theme={null}
interface PurchaseEventProperties extends Record<string, unknown> {
  orderId?: string;
  total?: number;
  currency?: string;
  paymentMethod?: string;
  shipping?: number;
  tax?: number;
}
```

***

### AddToCartEventProperties

```typescript theme={null}
interface AddToCartEventProperties extends Record<string, unknown> {
  itemId?: string;
  itemName?: string;
  price?: number;
  quantity?: number;
  currency?: string;
}
```

***

### RemoveFromCartEventProperties

```typescript theme={null}
interface RemoveFromCartEventProperties extends Record<string, unknown> {
  itemId?: string;
  itemName?: string;
  price?: number;
  quantity?: number;
}
```

***

### PageViewEventProperties

```typescript theme={null}
interface PageViewEventProperties extends Record<string, unknown> {
  page?: string;
  title?: string;
  url?: string;
  referrer?: string;
}
```

***

### SearchEventProperties

```typescript theme={null}
interface SearchEventProperties extends Record<string, unknown> {
  query?: string;
  results?: number;
  filters?: Record<string, unknown>;
  sortBy?: string;
}
```

***

## React Hook Types

```typescript theme={null}
import type { UseConfigResult, UseAllConfigsResult } from '@grainql/analytics-web/react';
```

### UseConfigResult

```typescript theme={null}
interface UseConfigResult {
  value: string | undefined;
  isRefreshing: boolean;
  error: Error | null;
  refresh: () => Promise<void>;
}
```

***

### UseAllConfigsResult

```typescript theme={null}
interface UseAllConfigsResult {
  configs: Record<string, string>;
  isRefreshing: boolean;
  error: Error | null;
  refresh: () => Promise<void>;
}
```

***

## Listener Types

### ConfigChangeListener

```typescript theme={null}
type ConfigChangeListener = (
  configurations: Record<string, string>
) => void;
```

**Example:**

```typescript theme={null}
const listener: ConfigChangeListener = (configs) => {
  console.log('Updated:', configs);
};
```

***

## Importing Types

### Grain Tag

```typescript theme={null}
import type {
  GrainTagConfig,
  GrainTagInstance,
  ConsentState,
  ConsentMode,
  GrainEvent
} from '@grainql/tag';
```

### Analytics Web

```typescript theme={null}
import type {
  GrainConfig,
  GrainEvent,
  AuthProvider,
  SendEventOptions,
  RemoteConfigOptions,
  LoginEventProperties,
  CheckoutEventProperties
} from '@grainql/analytics-web';
```

### React Hook Types

```typescript theme={null}
import type {
  UseConfigResult,
  UseAllConfigsResult
} from '@grainql/analytics-web/react';
```

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Core Methods" icon="code" href="/api-reference/core-methods">
    Event tracking and user management
  </Card>

  <Card title="API Overview" icon="book" href="/api-reference/overview">
    Complete API reference
  </Card>
</CardGroup>
