npm package: @nommos/core
Description: A core typed library, have constants, functions, types, enums and classes which serve as bases for the framework based nommos user activity tracking module.
Latest version: 0.0.30

# @nommos/core

A core typed library, have constants, functions, types, enums and classes which serve as bases for the framework based nommos user activity tracking module.

## 🧩 Compatibility

| Technology | Version |
|-----------|---------|
| **Node.js** | ≥ 14.x |
| **TypeScript** | ≥ 4.7 |
| **Browser Support** | Modern browsers + evergreen versions |

## 🛠 Technologies & Build System

This library is built with:

- TypeScript
- RxJS
- ES2022 output
- Jest
- UUID
- STOMP-JS

## 🏷 Tags

tracking, analytics, typescript, events, observables, nommos, webSockets

##  Enums Definitions

### `ANALYTICS_ACTION`

```ts
enum ANALYTICS_ACTION {
  SIGNIN = 'SIGNIN',
  REGISTRATION = 'REGISTRATION',
  BET = 'BET',
  MENU = 'MENU',
  TOURNAMENT = 'TOURNAMENT',
  SPORT = 'SPORT',
  DEPOSIT = 'DEPOSIT',
  VISIT = 'VISIT',
  COUPON = 'COUPON',
}
```
#### Description
Represents the various actions that are carried by a user.

#### Members
| Member | Value | Description |
|--------|-------|-------------|
| `SIGNIN` | `"SIGNIN"` | login or sign in action |
| `REGISTRATION` | `"REGISTRATION"` | registration or sign up action |
| `BET` | `"BET"` | Bet selection and placement action |
| `MENU` | `"MENU"` | Menu selection action |
| `TOURNAMENT` | `"TOURNAMENT"` | Tournament selection action |
| `SPORT` | `"SPORT"` | Sport selection action |
| `DEPOSIT` | `"DEPOSIT"` | Deposit or refill account action |
| `VISIT` | `"VISIT"` | Site or platform is visited action |
| `COUPON` | `"COUPON"` | Making or using a coupon code action |

---

### `ANALYTICS_ACTION_STATE`

```ts
enum ANALYTICS_ACTION_STATE {
  SELECT = 'SELECT',
  UNSELECT = 'UN_SELECT',
  SUBMIT = 'SUBMIT',
  SUCCESS = 'SUCCESS',
  FAILURE = 'FAILURE',
  INIT = 'INIT',
}
```
#### Description
Represents the various states associated to an action carried by a user.

### Members
| Member | Value | Description |
|--------|-------|-------------|
| `SELECT` | `"SELECT"` | An action was selected |
| `UNSELECT` | `"UN_SELECT"` | An action was unselected |
| `SUBMIT` | `"SUBMIT"` | An action was submitted |
| `SUCCESS` | `"SUCCESS"` | An action was successful |
| `FAILURE` | `"FAILURE"` | An action failed |
| `INIT` | `"INIT"` | An action was initialized |
---


### `SITE_SOURCE`

```ts
enum SITE_SOURCE {
  FACEBOOK = 'FACEBOOK',
  INSTAGRAM = 'INSTAGRAM',
  TWITTER = 'TWITTER',
  TELEGRAM = 'TELEGRAM',
  DIRECT = 'DIRECT',
  SMS = 'SMS',
}
```
#### Description
Represents the platform (Social Media, SMS or direct access) the user used to have access to the site where his actions are monitored.

#### Members
| Member | Value | Description |
|--------|-------|-------------|
| `FACEBOOK` | `"FACEBOOK"` | Accessed from Facebook |
| `INSTAGRAM` | `"INSTAGRAM"` | Accessed from Instagram |
| `TWITTER` | `"TWITTER"` | Accessed from Twitter |
| `TELEGRAM` | `"TELEGRAM"` | Accessed from Telegram |
| `DIRECT` | `"DIRECT"` | Accessed directly |
| `SMS` | `"SMS"` | Accessed from an SMS |


##  Types and Interfaces Definitions

### `Interface: ConnectionConfig`
```ts
interface ConnectionConfig {
  token: string;
  mode: string;
}
```
#### Description
An Interface representing the required information for initializing the tracking module. All connection details are fetched from the API using the provided token.

#### Fields
| Field | type | Description |
|--------|-------|-------------|
| `token` | `string` | The access token for fetching configuration |
| `mode` | `string` | Run tracking module in 'dev' or 'prod' mode |
---

### `Interface: UrlTrackingKey`
```ts
interface UrlTrackingKey {
  source: string;
  affiliateKey?: string;
  parrainageKey?: string;
}
```
#### Description
An Interface representing the query parameters that should be tracked on the site url to get the `SITE_SOURCE` and optionly the `affiliateCode` (for affiliate Tracking) and the `parrainageCode` (for parrainage Tracking)

#### Fields
| Field | type | Description |
|--------|-------|-------------|
| `source` | `string` | The query parameter key for `SITE_SOURCE`|
| `affiliateKey` | `string` | The optional query parameter key for `affiliateCode`|
| `parrainageKey` | `string` | The optional query parameter key for `parrainageCode` |
---

### `Interface: AnalyticsEvent`
```ts
interface AnalyticsEvent {
  timeStamp: number;
  channel: number;
  source: SITE_SOURCE;
  action: ANALYTICS_ACTION;
  state: ANALYTICS_ACTION_STATE;
  affiliateCode?: string;
  uid: string;
  bid: string;
  ip?: string;
  data?: Record<string, unknown>;
  meta?: Record<string, unknown>;
}
```
#### Description
An Interface representing the event being actually tracked, holding information which are exploited in analytics.

#### Fields
| Field | type | Description |
|--------|-------|-------------|
| `timeStamp` | `number` | The date and time at which the action was carried|
| `channel` | `number` | Information if the action was carried out on a mobile device or a desktop|
| `source` | `SITE_SOURCE` | The platform from which the user came from |
| `action` | `ANALYTICS_ACTION` | The action carried out by the user |
| `state` | `ANALYTICS_ACTION_STATE` | The state associated to the action carried out by the user |
| `affiliateCode` | `string` | The affilate code tracked from the site url |
| `uid` | `string` | The ID of the user who carried out the action |
| `bid` | `string` | An string to uniquely identify a user from the navigator used |
| `ip` | `string` | Optional IP address of the machine from which the user is accessing the site |
| `data` | `Record<string, unknown>` | Optional extra information concerning the action carried out by the user|
| `meta` | `Record<string, unknown>` | Optional meta data of where the action was carried by the user|
---

### `Type: ActionSelectState`
```ts
type AnalyticsEvent = Record<ANALYTICS_ACTION, boolean>;
```
#### Description
A type to represent the select state (`SELECT` or `UNSELECT`) of actions (`ANALYTICS_ACTION`) tracked.


##  Functions

### `Function: getQueryParams`

```ts
getQueryParams(url)
```
#### Description
Extracts the query parameters from a url.

#### Parameters
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `url` | `string` | `true`| The url from which to extra query parameters |

#### Returns
- `Record<string, string>` - The records of the query parameters (key, value)

### Examples
```ts
import { getQueryParams } from "@nommos/core";

getQueryParams("http://example.com?name=james&department=science&count=61");
// Returns: { name: "james", department: "science", count: "61"}

getQueryParams("http://example.com");
// Returns: {}

getQueryParams("");
// Returns: {}
```

### `Function: normString`

```ts
normString(s)
```
#### Description
Format a string by removing trailing spaces and lower cases it.

#### Parameters
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `s` | `string` | `true`| The string to format|

#### Returns
- `string` - formatted string

### Examples
```ts
import { normString } from "@nommos/core";

normString(" hello world ");
// Returns: "hello world"

getQueryParams("Big Bang Theory ");
// Returns: "big bang theory"

getQueryParams("GOOD-MORNING");
// Returns: "good-morning"
```

### `Function: userAgentInfo`

```ts
userAgentInfo(ua)
```
#### Description
Get browser, operating system and channel (mobile or desktop) of a user agent.

#### Parameters
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `ua` | `string` | `true`| The user agent of the device|

#### Returns
- `{browser: string, os: string, channel: 3 | 7}` - Object having browser, operating system and channel information|

### Examples
```ts
import { userAgentInfo } from "@nommos/core";

userAgentInfo("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36");
// Returns: {browser: "Chrome 119", os: "macOs 10.15.7", channel: 7 }

userAgentInfo("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0");
// Returns: {browser: "Chrome 119", os: "Windows 10.0", channel: 7 }

userAgentInfo("Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36");
// Returns: {browser: "Chrome 114", os: "Android 10", channel: 3 }
```
##  Classes

### `Class: DataAttribution`

#### Description
Represents a wrapper to extract informations associated to events being tracked and make them accessible for user activity tracking.

#### Properties
| Property | Type | Description | Default|
|----------|------|-------------|--------|
| `loadedUserIp$` | `Observable<boolean>` | Observable to know if the user IP address was captured | none |
| `hasParrainOrAffiliate$` | `Observable<boolean>` | Observable to know if Affiliate or Parrainage code was captured | none|
| `stripUrlTrackedParams$` | `Observable<boolean>` | Observable to know whether to strip tracked query parameters from the url | none|
| `stripUrlTrackedParams$` | `Observable<boolean>` | Observable to know whether to strip tracked query parameters from the url | none|

#### Constructor
```ts
constructor(private readonly urlTrackingKey: UrlTrackingKey)
```
##### Parameters
| Name | Type | Required |Description|
|------|------|----------|-----------|
| `urlTrackingKey` | `UrlTrackingKey` | `true` | Query parameters to capture from url for tracking |

#### Getters
##### `Getter: browserId`
###### Description
Unique identifier for the browser used to visit the site
###### Returns  `string`

##### `Getter: userIp`
###### Description
IP address of the machine used to visit the site
###### Returns `string`

##### `Getter: source`
###### Description
Source of the user visiting the site
###### Returns `SITE_SOURCE`

##### `Getter: affiliate`
###### Description
Affiliate code from the url used by the user
###### Returns `string | null`

##### `Getter: parrainage`
###### Description
Parrainage code from the url used by the user
###### Returns `string | null`

##### `Getter: trackAffiliate`
###### Description
Tells us if an affiliate code was not yet tracked and should be tracked or it should not.
###### Returns `boolean`

#### Methods
#### `Method: init`
##### Description
Initialize the capturing of query parameters to track from the site url

##### Parameters

| Name | Type | Required |Description|
|------|------|----------|-----------|
| `currentUrl` | `string` | `true` | Url from which to capture query parameters for tracking |
| `options` | `{ stripFromUrl?: boolean }` | `false` | Object to strip query parameters from url after capturing them. By default they are stripped off |

##### Returns `void`

#### `Method: setLoadedIP`
##### Description
Pushes a true to the `loadedUserIP$` observable
##### Parameters `none`
##### Returns `void`

#### `Method: fetchIp`
##### Description
Fetches the IP address of the machine used to accessed the site and sets the current user IP address.
##### Parameters `none`
##### Returns `Observable<void>`

#### `Method: clearSourceSession`
##### Description
Clears the source key value from session storage
##### Parameters `none`
##### Returns `void`

#### `Method: clearAffiliateSession`
##### Description
Clears the affiliate code key value from session storage
##### Parameters `none`
##### Returns `void`

#### `Method: clearAffiliateHistory`
##### Description
Clears the affiliate code key value history from session storage
##### Parameters `none`
##### Returns `void`


### `Class: WebSocketClient`

#### Description
Represents a wrapper for connecting/disconnecting from rabbit, keeping track of pending events tracked not yet published, publishing events tracked and managed rabbit reconnections and publishing of pending events tracked.

#### Properties
| Property | Type | Description | Default|
|----------|------|-------------|--------|
| `pendingEvents` | `AnalyticsEvent[]` | List of pending tracked events not yet published | `[]` |
| `stompAnalyticsConnected$` | `Observable<boolean>` | Observable for connection status to web socket for events publishing  | none |

#### Constructor
```ts
constructor()
```
##### Parameters - `none`

#### Methods
#### `Method: connectAnalyticsStomp`
##### Description
Establishes a STOMP WebSocket connection and wires lifecycle handlers.
- On successful connection:
  - Emits `true` for reactive subscribers
  - Flushes all queued analytics events
- On broker error:
  - Logs structured error output

##### Parameters

| Name | Type | Required |Description|
|------|------|----------|-----------|
| `cfg` | `ConnectionConfig` | `true` | Configuration including URL, credentials, mode etc for connecting to the websocket |

##### Returns `void`

#### `Method: publishAnalyticsMessage`
##### Description
Publishes a tracked event to a RabbitMQ queue.
If the connection is not ready, the event is automatically queued and delivered once the socket reconnects.

##### Parameters

| Name | Type | Required |Description|
|------|------|----------|-----------|
| `payload` | `AnalyticsEvent` | `true` | The analytics event to send |

##### Returns `void`

#### `Method: disconnect`
##### Description
Gracefully shuts down the STOMP client and updates connection status.
Safe to call even if the client was never created or already disconnected.

##### Parameters `none`

##### Returns `void`

### `Class: EventTracker`

#### Description
Represents a wrapper to initialize tracking and publishing of events with required informations and meta data. Once an instance is made, data about the user and found on the site current url are captured, and connection to the rabbit webs socket is established. 

#### Properties
| Property | Type | Description | Default|
|----------|------|-------------|--------|
| `analyticsEvent$` | `Observable<AnalyticsEvent>` | Observable holding recently pushed tracked event  | none |

#### Constructor
```ts
constructor( private readonly cfg: ConnectionConfig, private readonly urlTrackingKey: UrlTrackingKey)
```
##### Parameters
| Name | Type | Required |Description|
|------|------|----------|-----------|
| `cfg` | `ConnectionConfig` | `true` | Configuration config to initialize the web socket connection  |
| `urlTrackingKey` | `UrlTrackingKey` | `true` | Query parameters to initialize an instance of `DataAttribution` for information collection |

#### Methods
#### `Method: trackingIsEnabled`
##### Description
Tells whether tracking is enabled/disabled from config

##### Parameters - `none`

##### Returns `boolean`

#### `Method: getActionSelectState`
##### Description
Get the selection state of an action

##### Parameters
| Name | Type | Required |Description|
|------|------|----------|-----------|
| `action` | `ANALYTICS_ACTION` | `true` | Action you want to know the selection state  |

##### Returns `boolean`

#### `Method: setActionSelectState`
##### Description
Set the selection state of an action

##### Parameters
| Name | Type | Required |Description|
|------|------|----------|-----------|
| `action` | `ANALYTICS_ACTION` | `true` | Action you want to set the selection state  |
| `selected` | `boolean` | `true` | selection state  |

##### Returns `void`

#### `Method: trackEvent`
##### Description
Constructs the user interaction event and emits it into a pipeline for storage. The event has the action, action state, extra information associated to the action and the user, and information gotten from the `DataAttribution` instance and the user agent of the device used. the mode of operation to set the action state. This method:
   - Resolves the correct `SELECT` or `UNSELECT` state
   - Enriches the event with attribution information
   - Extracts browser/channel/OS from the user agent
   - Publishes the event to s pipeline for storage


##### Parameters
| Name | Type | Required |Description|
|------|------|----------|-----------|
| `action` | `ANALYTICS_ACTION` | `true` | Action to be tracked|
| `state` | `ANALYTICS_ACTION_STATE` | `true` | State associated to the action being tracked|
| `data` | `Record<string, unknown> \| null` | `false` | Extra information associated to the action being tracked|
| `toggle` | `boolean` | `false` | Boolean value to know whether toggle selection state of the Action|
| `selected` | `boolean \| null` | `false` | Boolean value to set the selection state of the action tracked, it is prioritized over `toggle`|
| `userId` | `string` | `false` | ID of the user whom carried out the `action`|
| `currentUrl` | `string` | `false` | The url of the page where the action was carried out by the user|

##### Returns `void`

#### `Method: unsubscribe`
##### Description
Unsubscribe to subscriptions made during connection to the web socket, fetching the machine IP address and publishing events tracked. This should be called on destroying an instance of this class.

##### Parameters `none`

##### Returns `void`