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

# JavaScript

## Overview

The Siren JS SDK enhances Siren's capabilities by providing advanced notification management functionalities within JavaScript applications. It offers seamless integration, robust error handling, and compatibility with Siren's ecosystem.

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install @sirenapp/js-sdk
  ```

  ```bash Yarn theme={null}
  yarn add @sirenapp/js-sdk
  ```

  ```bash CDN theme={null}
  <script src="https://siren-js.sirenapp.io/siren-js-umd-sdk.js"></script>
  ```
</CodeGroup>

## Usage

### Initialization

```javascript theme={null}
import Siren from "@sirenapp/js-sdk";

const sirenInstance = new Siren({
  token: "your-user-token",
  recipientId: "your-recipient-id",
  onError: (error) => {
    console.error("Siren Error:", error);
  },
  actionCallbacks: {
    onEventReceive: (response, eventType) => {
      console.log("Event received:", eventType, response);
    }
  }
});
```

### Constructor Options

| Property          | Description                            | Type     | Required |
| ----------------- | -------------------------------------- | -------- | -------- |
| `token`           | Siren user token                       | string   | Yes      |
| `recipientId`     | Siren recipient ID                     | string   | Yes      |
| `onError`         | Error callback function                | Function | Yes      |
| `actionCallbacks` | Callbacks for notifications and counts | Object   | No       |

## Methods

### fetchUnviewedNotificationsCount()

Retrieves the count of unviewed notifications.

```javascript theme={null}
const { unviewedCount } = await sirenInstance.fetchUnviewedNotificationsCount();
console.log("Unviewed notifications:", unviewedCount);
```

### fetchAllNotifications(options)

Retrieves a paginated list of notifications.

```javascript theme={null}
const notifications = await sirenInstance.fetchAllNotifications({
  page: 0,
  size: 15,
  start: '2024-01-01T00:00:00.000Z',
  end: '2024-12-31T23:59:59.999Z',
  isRead: false,
  category: 'updates'
});
```

#### Options

| Parameter  | Description                                        | Type    | Default |
| ---------- | -------------------------------------------------- | ------- | ------- |
| `page`     | Current page number                                | number  | 0       |
| `size`     | Items per page                                     | number  | 10      |
| `start`    | Filter notifications after this date (ISO string)  | string  | null    |
| `end`      | Filter notifications before this date (ISO string) | string  | null    |
| `isRead`   | Filter by read status                              | boolean | null    |
| `category` | Filter by category                                 | string  | null    |

#### Response

```typescript theme={null}
interface Notification {
  id: string;
  createdAt?: string;
  message: {
    channel: string;
    header: string;
    subHeader: string;
    body: string;
    actionUrl: string;
    avatar: {
      imageUrl: string;
      actionUrl: string | null;
    };
    additionalData: string;
  };
  requestId: string;
  isRead: boolean;
}
```

### startRealTimeFetch(options)

Starts real-time notification updates.

```javascript theme={null}
// For notifications
sirenInstance.startRealTimeFetch({
  eventType: 'NOTIFICATIONS',
  params: {
    page: 0,
    size: 15,
    start: '2024-01-01T00:00:00.000Z',
    end: '2024-12-31T23:59:59.999Z',
    isRead: false,
    category: 'updates'
  }
});

// For unviewed count
sirenInstance.startRealTimeFetch({
  eventType: 'UNVIEWED_COUNT'
});
```

### stopRealTimeFetch(eventType)

Stops real-time updates.

```javascript theme={null}
// Stop notifications updates
sirenInstance.stopRealTimeFetch('NOTIFICATIONS');

// Stop unviewed count updates
sirenInstance.stopRealTimeFetch('UNVIEWED_COUNT');
```

### markAsReadById(notificationId)

Marks a notification as read.

```javascript theme={null}
await sirenInstance.markAsReadById("notification-id-123");
```

### markAsReadByDate(params)

Marks notifications as read until a specific date.

```javascript theme={null}
await sirenInstance.markAsReadByDate({
  startDate: "2024-01-01T00:00:00.000Z",
  category: "updates" // Optional
});
```

### deleteById(notificationId)

Deletes a notification.

```javascript theme={null}
await sirenInstance.deleteById("notification-id-123");
```

### deleteByDate(params)

Deletes notifications until a specific date.

```javascript theme={null}
await sirenInstance.deleteByDate({
  startDate: "2024-01-01T00:00:00.000Z",
  isRead: true, // Optional
  category: "updates" // Optional
});
```

### markAllAsViewed(date)

Marks all notifications as viewed until the specified date.

```javascript theme={null}
await sirenInstance.markAllAsViewed("2024-01-01T00:00:00.000Z");
```

## Example

```javascript theme={null}
import Siren from "@sirenapp/js-sdk";

// Initialize
const siren = new Siren({
  token: "your-user-token",
  recipientId: "your-recipient-id",
  onError: (error) => {
    console.error("Siren Error:", error);
  },
  actionCallbacks: {
    onEventReceive: (response, eventType) => {
      if (eventType === 'NOTIFICATIONS') {
        console.log("New notifications:", response);
      } else if (eventType === 'UNVIEWED_COUNT') {
        console.log("Unviewed count:", response.unviewedCount);
      }
    }
  }
});

// Fetch initial data
async function initialize() {
  try {
    // Get unread count
    const { unviewedCount } = await siren.fetchUnviewedNotificationsCount();
    console.log("Initial unread count:", unviewedCount);

    // Get notifications
    const notifications = await siren.fetchAllNotifications({
      page: 0,
      size: 10,
      isRead: false
    });
    console.log("Initial notifications:", notifications);

    // Start real-time updates
    siren.startRealTimeFetch({ eventType: 'NOTIFICATIONS' });
    siren.startRealTimeFetch({ eventType: 'UNVIEWED_COUNT' });

  } catch (error) {
    console.error("Initialization failed:", error);
  }
}

// Mark all as read
async function markAllAsRead() {
  try {
    await siren.markAsReadByDate({
      startDate: new Date().toISOString()
    });
    console.log("All notifications marked as read");
  } catch (error) {
    console.error("Failed to mark as read:", error);
  }
}

// Clean up
function cleanup() {
  siren.stopRealTimeFetch('NOTIFICATIONS');
  siren.stopRealTimeFetch('UNVIEWED_COUNT');
}

// Initialize the app
initialize();

// Clean up on unmount
window.addEventListener('beforeunload', cleanup);
```
