npm package: @repobit/dex-target
Description: Client for Adobe Target
Author: Constantin Ioan Mihai
Latest version: 2.13.6

# `@repobit/dex-target`

# Target Integration SDK Documentation

This document provides a comprehensive overview of the Target Integration SDK, outlining its purpose, key features, installation guidelines, and detailed information on its core components such as the main class, available methods, public properties and usability.

---

## Overview

The Target Integration SDK is designed to simplify the integration process with Adobe Target and the Adobe Data Layer. It provides a centralized solution for managing visitor identity operations, sending events, appending visitor IDs to URLs, retrieving mbox offers, and fetching Customer Data Platform (CDP) data. The SDK encapsulates these operations within a single abstract class, ensuring that targeting functionalities are cleanly organized and maintainable in your application.

---

## Key Features

- **Adobe SDK base:**
  This package is built on top of the `Adobe WebSDK` implementation and it makes use of the `alloy` methods in order to deliver mbox offers, define the identity of the user using the Adobe Cloud and append identity information onto external links.

- **Integration through proxy:**  
  The SDK initializes a global proxy to Adobe WebSDK's `alloy` called `alloyProxy`, ensuring that all Adobe Target-related operations are performed through a consistent interface and that early calls are queued up before they can be resolved by the WebSDK once Adobe Launch actually loads.

- **Visitor Identity Management:**  
  It handles asynchronous retrieval and caching of visitor identity information, ensuring that personalized experiences are based on accurate and up-to-date visitor data.

- **Dynamic URL Parameter Extraction:**  
  Automatically extracts URL query parameters from the current page, enabling seamless integration with targeting operations without manual parameter management.

- **CDP Data Processing:**  
  The SDK retrieves, processes, and integrates Customer Data Platform (CDP) data, which is then dispatched to the Adobe Data Layer for further analysis and personalization.

- **Offer Retrieval and Caching:**  
  Supports multiple configurations for retrieving mbox offers. It caches responses to avoid redundant network requests and optimizes the offer delivery process.

- **Abort Mechanism for Robust Operations:**  
  Utilizes an AbortController to cancel pending operations if needed, preventing issues when operations take longer than expected or if a page is unloaded.

---

## Installation

Install via npm or yarn:

```bash
npm install @repobit/dex-target
```

---

## Class: Target

The `Target` class is a class that serves as the main entry point for Adobe Target integration. It is responsible for initializing Adobe Target operations, managing internal state, and providing methods to interact with Adobe Target functionalities.

---

## Usage

### Import the SDK
Simply import the `Target` class into your project and instantiate it. The module automatically sets up the global `window.alloyProxy` and begins fetching necessary data as soon as it is loaded.

```typescript
import Target from '@repobit/dex-target';
import { PageLoadStartedEvent } from '@repobit/dex-data-layer';
import { Page } from '@repobit/dex-utils';

const pageLoadStartedEvent = new PageLoadStartedEvent(
  new Page('en-us', 'test', 'dev'),
  {
    geoRegion: 'us',
    name     : 'en-us:test'
  }
);

// option 1, if you need CDP data calls
const target = new Target({pageLoadStartedEvent});

// option 2, if you don't need CDP data calls
const target = new Target();
```

### Getting the config mbox
The `Config mbox` contains information regarding promotions, buy link and product information changes, as well as the useGeoIpPricing boolean value which specifies that the user locale should be used instead of the website locale. The type definition of the mbox is described below:

```typescript
export type ConfigMbox = Partial<{
  promotion: string,
  provider: 'init' | 'vlaicu',
  products: {
    [key: string]: {
      [key: `${number}-${number}`]: Partial<{
        extraParameters: {
          key  : string,
          value: string
        }[],
        price          : number,
        discountedPrice: number,
        buyLink        : string
      }>
    }
  },
  useGeoIpPricing: boolean
}>;
```

Usage:

```typescript
target.configMbox.then(configMboxData => {
  console.log('Config data: ', configMboxData);
});
```

### Getting Visitor Info
The visitorInfo property returns a promise that resolves to the visitor’s identity details (such as ECID).

```typescript
target.visitorInfo.then(info => {
  console.log('Visitor Info: ', info);
});
```

### Append Visitor IDs to a URL
Use the appendVisitorIDsTo method to append the Adobe Marketing Cloud (adobe_mc) identifier to any URL. This is useful for tracking and personalization.

```typescript
target.appendVisitorIDsTo('https://example.com')
  .then((updatedUrl) => {
    console.log('Updated URL:', updatedUrl);
  });
```

### Retrieve Offers
The getOffers method can be used to fetch Adobe Target offers. It supports both single and multiple mbox names, and accepts optional mbox and profile parameters. It is important to note that all getOffers calls made are cached, but the calls themselves will differ based on the parameters and profile parameters passed, not just by the mboxNames. So if you make a call for an mbox, then another one for same mbox, but you use differenet parameters or profile parameters, these will be cached separately since their scope will be different.

#### Single mbox example:

```typescript
target.getOffers({
  mboxNames: 'config-mbox',
  parameters: { customParam: 'value' },
  profileParameters: { profile.custom: 'value' }
}).then(offer => {
  console.log('Config Mbox Offer:', offer);
});
```

#### Multiple mbox example:

```typescript
target.getOffers({
  mboxNames: ['mbox1', 'mbox2'],
  parameters: { customParam: 'value' },
  profileParameters: { profile.custom: 'value' }
}).then(offers => {
  console.log('Offers:', offers);
});
```

Here the response type of offers will be something like this, instead of the actual data directly:

```typescript
{
  mbox1: {<data_object>},
  mbox2: {<data_object>}
}
```

### Retrieve HTML Content as a DocumentFragment
Use getContentFragment to fetch an HTML offer for a single mbox and return it as a DocumentFragment. The fragment includes any inline scripts, rehydrated as real script elements. Scripts will execute only after you insert the fragment into the live DOM (for example, into document.body).

```typescript
const fragment = await target.getContentFragment({ mboxName: 'html-mbox' });
if (fragment) {
  document.body.replaceChildren(fragment);
}
```

Notes:
- This method is intended for mboxes that return HTML content.
- Script execution depends on the host environment. In browsers, inline scripts execute when inserted into the live DOM.
- If the mbox itself does not get data, the returned fragment will be null.


### Aborting Requests
If needed, abort all ongoing Target-related calls using the abort method. This is particularly useful when Target fails to load or if you need to cancel pending operations. This work well with the @repobit/dex-launch to cancel all alloy requests if the `Adobe Launch` does not load.

```typescript
try {
    Launch.load()
} catch (e) {
    target.abort()
}
```

### Sending CDP data
Use the sendCdpData method to send data regarding the pageLoadStarted event to the CDP endpoint. The function returns Promise<void> and a PageLoadStartedEvent needs to be passed as a parameter.

```typescript
await target.sendCdpData(pageLoadStartedEvent);
```