# Compass Web SDK: JavaScript API Reference

Source: https://dev.arcxp.com/content-recommendations/sdk/api-reference/

Reference for the Compass Web SDK's public JavaScript API: every ArcCompass method, init() configuration options, markup attributes and meta tags, DOM lifecycle events, the onError payload, diagnostics, and browser support.

This page is the reference for the public JavaScript API of the Arc XP Compass Web SDK, version 1.2.0\. To add the SDK to a site, see [Compass Web SDK: Integration Guide](https://dev.arcxp.com/content-recommendations/sdk/integration-guide/).

## Entry points

The SDK exposes the same methods in two ways:

| Distribution                            | Entry point            | Notes                                                                                                                                                                                              |
| --------------------------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Script bundle (compass-sdk.iife.min.js) | window.ArcCompass      | A single client. The [loader snippet](https://dev.arcxp.com/content-recommendations/sdk/integration-guide/#2-add-the-snippet) queues calls made before the bundle loads and replays them in order. |
| npm package (@arcxp/compass-sdk)        | new ArcCompassClient() | An ES module for build pipelines. Construct one client, then call init() on it.                                                                                                                    |

```ts
import { ArcCompassClient } from "@arcxp/compass-sdk";

const compass = new ArcCompassClient();
compass.init({ origin: "https://{org}-config-prod.api.arc-cdn.net", apiKey: "<arc-delivery-token>" });
```

The npm package also exports these values:

| Export                | Value                                                                                                |
| --------------------- | ---------------------------------------------------------------------------------------------------- |
| EVENT\_TYPES          | Every event type track() accepts, as an array.                                                       |
| ATTRIBUTION\_ATTRS    | The data-arc-compass-\* attribute names listed in [Attribution attributes](#attribution-attributes). |
| ATTRIBUTION\_SELECTOR | \[data-arc-compass-attribution-id\], the selector the SDK scans for.                                 |
| CATCH\_UP\_SOURCE     | "fy-catchup", the attribution source on Catch Up card events.                                        |

It exports these TypeScript types: `InitOptions`, `BatchOptions`, `QueueOptions`, `ArcCompassErrorInfo`, `ExperienceFailureCode`, `ConsentStatus`, `EventType`, `TrackProps`, `AttributionContext`, `ItemAttribution`, `ObservedItem`, `ObserveOptions`, `ObserveHandle`, `CatchUpCardAttribution`, and `CatchUpSegmentAttribution`.

## Methods

| Method                                                                   | Returns        | Summary                                                     |
| ------------------------------------------------------------------------ | -------------- | ----------------------------------------------------------- |
| [init(options)](#initoptions)                                            | void           | Configure and start the SDK. Call once.                     |
| [setConsent(granted)](#setconsentgranted)                                | void           | Record the reader’s consent decision.                       |
| [setUserId(userId)](#setuseriduserid)                                    | void           | Set or clear the known user ID.                             |
| [getUserId()](#getuserid)                                                | string \| null | The identifier the SDK puts on events.                      |
| [track(eventType, props?)](#trackeventtype-props)                        | void           | Queue a behavioral event.                                   |
| [observeRecommendations(options)](#observerecommendationsoptions)        | ObserveHandle  | Attribution-track a rendered recommendation set.            |
| [trackExposure(element, attribution)](#trackexposureelement-attribution) | void           | Attribution-track one host-rendered recommendation element. |
| [refreshExperiences(selector?)](#refreshexperiencesselector)             | void           | Re-fetch and re-render SDK-rendered Experiences.            |
| [flush()](#flush)                                                        | Promise<void>  | Send queued events now.                                     |
| [diagnose()](#diagnose)                                                  | void           | Print a setup summary to the console.                       |

None of these methods throws except `init()`. On an `ArcCompassClient`, calls to `setUserId()`, `track()`, `observeRecommendations()`, and `trackExposure()` made before `init()` are ignored; under `debug`, the last three log a warning. On the script bundle, calls made before the SDK initializes, from `init()` or from [markup](#configure-from-markup), are held and applied in order right after it initializes.

### `init(options)`

Configures the client and starts it: it registers the `<arc-compass-*>`Experience elements, starts automatic `page_view` capture unless `autoPageView` is `false`, and starts the [attribution attribute](#attribution-attributes)scan unless `attributionRoot` is `false`. For `options`, see [Configuration options](#configuration-options).

`init()` throws an `Error` when:

- `apiKey` is missing or empty.
- Neither `origin` nor `domain` is set.
- `origin` is not a bare `http` or `https` origin, for example because it carries a path.
- It has already been called on this client.

On the script bundle, an `init()` call made after the SDK initialized from markup has no effect and logs a `console.error` instead of throwing. See [When the SDK initializes](#when-the-sdk-initializes).

### `setConsent(granted)`

Records the reader’s consent decision. It is the single gate on collection and on SDK-rendered Experiences.

| granted | Effect                                                                                                                                   |
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| true    | Sends the events queued while consent was unknown, sends later events as they are tracked, and lets Experiences render.                  |
| false   | Discards the queued events, deletes the persistent identifiers the SDK wrote, and drops later track() calls. Experiences render nothing. |

Until you call it, events wait in memory and Experiences render nothing. See [Consent & Identity](https://dev.arcxp.com/content-recommendations/sdk/consent-identity/).

### `setUserId(userId)`

Sets the known user ID, such as your own ID for a logged-in reader. Pass `null` to clear it, so that events fall back to the SDK’s anonymous ID. Compass stores the value as sent, so pass an opaque identifier, never PII such as an email address. To re-render SDK-rendered Experiences for the new reader, call [refreshExperiences()](#refreshexperiencesselector) afterward.

### `getUserId()`

Returns the identifier the SDK puts on events, so you can pass the identical value as `user_id` when you request recommendations yourself:

- The ID set with `setUserId()`, when there is one.
- Otherwise, the SDK’s anonymous ID, after consent is granted.
- Otherwise, `null`, before consent or before `init()`.

It returns a value, so it can’t be queued. The loader snippet’s stub returns `null`until the bundle has loaded and initialized.

### `track(eventType, props?)`

Queues one behavioral event. The SDK resolves identity and the item and site IDs when it sends the batch, so a consent decision made after `track()` still applies. `track()` never throws.

- Before `init()`, the event is dropped.
- While consent is unknown, the event waits in the queue.
- After `setConsent(false)`, the event is dropped.

`eventType` is one of: `page_view`, `click`, `video_start`, `video_complete`, `video_progress`, `search`, `share`, `article_save`, `deepest_scroll`, `engaged_read`, `recommendation_exposure`, `recommendation_click`, `catch_up_shown`, `catch_up_click`, or `catch_up_dismiss`. The SDK emits the `recommendation_*` and `catch_up_*` types itself; don’t track them by hand. For what each type means, see [Supported Event Types](https://dev.arcxp.com/content-recommendations/content-recommendations-api-developer-guide/#supported-event-types).

`props` is optional:

| Property           | Type               | Default                                                 | Description                                                                                                    |                                                                                                     |
| ------------------ | ------------------ | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| itemId             | string             | The arc-compass:item-id meta tag                        | The item this event is about.                                                                                  |                                                                                                     |
| siteId             | string \| null     | init({ siteId }), then the arc-compass:site-id meta tag | The site for this event. null sends no site\_id.                                                               |                                                                                                     |
| eventValue         | number             | —                                                       | Magnitude from 0.0 to 1.0, such as the fraction of a video watched.                                            |                                                                                                     |
| sessionId          | string             | The SDK-managed session                                 | Overrides the session ID for this event.                                                                       |                                                                                                     |
| timestamp          | Date \| string     | number                                                  | Capture time                                                                                                   | A Date, a parseable timestamp string, or epoch milliseconds. A value that doesn’t parse is ignored. |
| attributionContext | AttributionContext | —                                                       | Attribution identifiers from the recommendation response. Ignored on event types that don’t carry attribution. |                                                                                                     |

The SDK applies the Collector’s `event_value` rules before sending. It drops a `deepest_scroll` that has no `eventValue` and reports the drop to `onError` with `reason: "rejected"`. It sends an `article_save` without its `eventValue`. See

[Events & Reliability](https://dev.arcxp.com/content-recommendations/sdk/events-reliability/) 

for item ID and site ID resolution and batching.

### `observeRecommendations(options)`

Attribution-tracks a recommendation set that your code rendered. The SDK sends a `recommendation_exposure` when an element has been at least 50% visible in the viewport for 1 second, and a `recommendation_click` when the reader clicks the element or anything inside it.

`options` is an `ObserveOptions` object:

| Property  | Type             | Description                                                                                                     |
| --------- | ---------------- | --------------------------------------------------------------------------------------------------------------- |
| container | Element          | The element that wraps the set. The SDK attaches one click listener here.                                       |
| items     | ObservedItem\[\] | Each rendered element as { element, attribution }, where attribution is an [ItemAttribution](#itemattribution). |

It returns an `ObserveHandle`. Call its `disconnect()` method when the set is replaced or removed, so a stale set stops sending events. `disconnect()` is safe to call more than once. Through the loader snippet, the call is queued and the returned handle takes effect after the bundle loads.

### `trackExposure(element, attribution)`

Attribution-tracks one recommendation element that your code rendered, with the same exposure and click behavior as `observeRecommendations()`. It is the imperative alternative to the [attribution attributes](#attribution-attributes). `attribution` is an [ItemAttribution](#itemattribution).

The element must be inside `attributionRoot` for its clicks to register. Registering the same element twice has no effect. A call made before the SDK has found `attributionRoot` is held until it does. When `attributionRoot` is `false`or invalid, the call is dropped with a warning.

### `ItemAttribution`

The attribution for one rendered recommendation element. Copy each value from the recommendation response.

| Property      | Type           | Required | Description                                                                                                 |
| ------------- | -------------- | -------- | ----------------------------------------------------------------------------------------------------------- |
| itemId        | string         | Yes      | The recommended item’s item\_id, not the page’s own item.                                                   |
| attributionId | string         | Yes      | The item’s attribution\_id.                                                                                 |
| exposureId    | string         | Yes      | The response’s attribution.exposure\_id. Identical for every item in the set.                               |
| surfaceId     | string         | No       | The surface the set is rendered on.                                                                         |
| position      | number         | No       | The item’s zero-based position.                                                                             |
| issuedAt      | Date \| string | No       | The response’s attribution.issued\_at.                                                                      |
| source        | string         | No       | Attribution origin. Leave it unset; it defaults to fy, and only fy attribution counts toward Confirmed CTR. |

For the full attribution flow, see [Recommendation Attribution](https://dev.arcxp.com/content-recommendations/sdk/attribution/).

### `refreshExperiences(selector?)`

Re-fetches and re-renders SDK-rendered Experiences, for example after `setUserId()` on a login. With a CSS `selector`, it refreshes the Experiences that match the selector or are inside an element that matches it; without one, it refreshes every Experience on the page. An invalid selector refreshes nothing and logs a warning under `debug`. A refreshed Experience still waits for consent.

### `flush()`

Sends the queued events now and resolves when the request finishes. It does nothing until consent is granted. You rarely need it: the SDK sends on a timer, on batch size, and when the reader leaves the page.

### `diagnose()`

Prints a setup summary with `console.warn`: the SDK version, the event and Experiences endpoints, whether an API key is set, the `debug` and consent state, whether a `site_id` resolved, the `arc-compass:*` meta tags present, and each Experience tag with its last lifecycle event. It works before `init()` and without `debug`, and it never prints the API key, a meta tag’s value, or anything that identifies the reader. Type `ArcCompass.diagnose()` in the browser console; the loader snippet doesn’t queue it.

### Reserved methods

`ArcCompassClient` also has `observeCatchUp()`, `trackCatchUpShown()`, `trackCatchUpClick()`, and `trackCatchUpDismiss()`. The SDK’s Catch Up card uses them to send its own analytics events. They aren’t on `window.ArcCompass`; don’t call them.

## Configure from markup

Instead of calling `init()`, you can put the SDK configuration in HTML. The bundle reads it when it loads and initializes itself, so you don’t write any JavaScript to set up the SDK.

> **Note:**
> 
> Configuration from markup is available since SDK 1.2.0\. Load a 1.2.0 or later exact-version URL, as in the example. An earlier version ignores the attributes and meta tags and does not initialize.

Add the configuration as `data-arc-compass-*` attributes on the `<script>` tag that loads the bundle:

```html
<head>
  <meta name="arc-compass:item-id" content="ARTICLE-ABC123" />
  <meta name="arc-compass:site-id" content="the-daily" />
  <script
    src="https://arc-rec.app-recommend.aws.arc.pub/arc-rec/v1.2.0/compass-sdk.iife.min.js"
    integrity="sha384-VvYEr4g99L9WMmYHPcTMN3vZyiIlN4jT+c/GtVx5CBfQimkjKeTbE/Njl6hWfdGZ"
    crossorigin="anonymous"
    data-arc-compass-origin="https://{org}-config-prod.api.arc-cdn.net"
    data-arc-compass-api-key="<arc-delivery-token>"
  ></script>
  <script>
    // Pass true after your CMP reports consent.
    ArcCompass.setConsent(true);
  </script>
</head>
<body>
  <!-- … -->
  <arc-compass-recommendations-list surface-id="article-footer"></arc-compass-recommendations-list>
</body>
```

Load the bundle with a plain `<script>` tag, without `async` or `defer`, so `ArcCompass` exists when the code that follows it runs. To load the bundle asynchronously, use the [loader snippet](https://dev.arcxp.com/content-recommendations/sdk/integration-guide/#2-add-the-snippet) and put the configuration in meta tags instead (see [Meta tags](#meta-tags)).

Consent is not part of the markup configuration. You still call `ArcCompass.setConsent()` from your consent code, as described in [Resolve consent](https://dev.arcxp.com/content-recommendations/sdk/integration-guide/#4-resolve-consent). Until you do, the SDK sends no events and SDK-rendered Experiences render nothing.

### Attributes

Each attribute sets the `init()` option of the same name. See the [configuration options](#configuration-options) for what each option does.

| Attribute                           | init() option     | Value                                                    |
| ----------------------------------- | ----------------- | -------------------------------------------------------- |
| data-arc-compass-origin             | origin            | Required, unless data-arc-compass-domain is set.         |
| data-arc-compass-api-key            | apiKey            | Required.                                                |
| data-arc-compass-site-id            | siteId            | Optional. The Site every event and Experience uses.      |
| data-arc-compass-domain             | domain            | Optional override.                                       |
| data-arc-compass-experiences-domain | experiencesDomain | Optional override.                                       |
| data-arc-compass-cookie-domain      | cookieDomain      | Optional.                                                |
| data-arc-compass-attribution-root   | attributionRoot   | Optional. A CSS selector, or false to turn off the scan. |
| data-arc-compass-auto-page-view     | autoPageView      | Optional. On unless set to false or 0.                   |
| data-arc-compass-debug              | debug             | Optional. On when present, unless set to false or 0.     |

The batching, queue, and `onError` options have no attribute. To set them, call `init()` instead.

### Meta tags

If you can’t add attributes to the `<script>` tag, for example because a tag manager or the loader snippet inserts it, use meta tags with the same names:

```html
<meta name="arc-compass:origin" content="https://{org}-config-prod.api.arc-cdn.net" />
<meta name="arc-compass:api-key" content="<arc-delivery-token>" />
```

If an attribute and a meta tag set the same option, the attribute is used.

The Site is the exception. `<meta name="arc-compass:site-id">` keeps the meaning described in [Add the content and site meta tags](https://dev.arcxp.com/content-recommendations/sdk/integration-guide/#5-add-the-content-and-site-meta-tags): the SDK reads it each time it needs a Site, so it can change from route to route. It does not count as configuration. To fix the Site for every page, use the `data-arc-compass-site-id` attribute.

### When the SDK initializes

The SDK initializes from markup when the page finishes parsing (`DOMContentLoaded`), and only if the page sets an origin, a domain, or an API key. A page that declares none of them, for example one with only a `data-arc-compass-debug` attribute, does not initialize from markup.

- An `init()` call made before then takes precedence, whether you call it directly or the loader snippet queues it. The SDK ignores the markup configuration entirely; it does not merge the two.
- Calls such as `setConsent()`, `setUserId()`, and `track()` made before the SDK initializes are held and applied in order right after it initializes, from either source.
- The SDK initializes only one time, so an `init()` call made after it has initialized from markup has no effect: none of its options apply, including `onError`. The SDK logs a `console.error` instead of throwing. If you need an option that markup can’t express, call `init()` before `DOMContentLoaded`, or remove the markup configuration.
- If the markup configuration is invalid, for example because the API key is missing, the SDK logs a `console.error` and does not initialize. A later `init()` call still works.

## Configuration options

`ArcCompass.init(options)` accepts the following options. Only `apiKey` and one of `origin` or `domain` are required.

| Option                | Type                             | Default                             | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| --------------------- | -------------------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| origin                | string                           | — _(required unless domain is set)_ | Your org’s Arc XP edge origin with no path, for example https://{org}-config-prod.api.arc-cdn.net. The SDK derives the event collector endpoint (/collect-web/v1/events/batch) and the Experiences endpoints (/experiences/…) from it. init() throws if it carries a path, query, or fragment, or is not an http(s) URL. Since SDK 1.2.0.                                                                                                                                                                                          |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| apiKey                | string                           | — _(required)_                      | Delivery token provisioned by Arc XP. Sent as X-API-Key on every request — event posts and the SDK-rendered Experiences’ recommendation reads alike.                                                                                                                                                                                                                                                                                                                                                                               |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| domain                | string                           | origin \+ /collect-web/v1           | Override for the events collector base path, for example https://{org}-config-prod.api.arc-cdn.net/collect-web/v1. The SDK appends /events/batch. Set it only when your event collector is not at the path origin implies. On SDK versions earlier than 1.2.0, this option is required in place of origin.                                                                                                                                                                                                                         |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| experiencesDomain     | string                           | origin                              | Override for the origin the SDK-rendered Experiences read from, the Arc XP edge root the /experiences/… recommendation and Catch Up routes hang off. Defaults to origin, or, when only domain is set, to domain with a trailing /collect-web/v<n> removed. Set it only when the Experiences service is on a different host from your event collector.                                                                                                                                                                              |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| siteId                | string                           | the arc-compass:site-id meta tag    | The Site every event and Experience read uses. Takes priority over <meta name="arc-compass:site-id">, which the SDK then never reads; a siteId passed to track() still overrides it for that event. Leave it unset on a host whose Site varies by route, and set the meta tag on each route instead. See [Add the content and site meta tags](https://dev.arcxp.com/content-recommendations/sdk/integration-guide/#5-add-the-content-and-site-meta-tags). Since SDK 1.2.0.                                                         |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| cookieDomain          | string                           | detected registrable domain         | Cookie Domain attribute for the anonymous-ID and session cookies. Defaults to the broadest scope the browser accepts for the current host, found by probing rather than by counting labels, so ccTLDs and platform hosts share identity across subdomains without configuration. Set it explicitly to override. See [Cookie domain](#cookie-domain).                                                                                                                                                                               |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| batch.maxEvents       | number                           | 20                                  | Flush when the buffer reaches this many events.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| batch.flushIntervalMs | number                           | 2000                                | Flush this many milliseconds after the last flush.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| queue.maxBuffered     | number                           | 500                                 | Hard cap on in-memory queued events. Oldest are dropped on overflow with a console.warn.                                                                                                                                                                                                                                                                                                                                                                                                                                           |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| autoPageView          | boolean                          | true                                | Fire page\_view automatically each time the <meta name="arc-compass:item-id"> tag resolves to a new item (covering the initial load and every SPA route change), reading the optional site\_id from <meta name="arc-compass:site-id"> at the same moment. Set false to call track('page\_view', { itemId }) yourself.                                                                                                                                                                                                              |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| attributionRoot       | Element \| string                | false                               | document.body                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | Root under which the SDK scans for host-rendered recommendations carrying the data-arc-compass-\* binding — also the click-delegation container, so tagged elements (and elements passed to trackExposure) must live inside it. Accepts an element or a CSS selector (resolved after the DOM is ready). Narrow it to the container that holds recommendations to avoid a page-wide MutationObserver; pass false to disable the scan entirely. A structurally-broken root (invalid selector, or a non-Element value) disables the binding with a console.warn; a valid selector whose container has not mounted yet is deferred and attaches on the next trackExposure. See [Recommendation Attribution](https://dev.arcxp.com/content-recommendations/sdk/attribution/). |
| debug                 | boolean                          | false                               | Log lifecycle and transport diagnostics, including the event and Experiences endpoints the SDK resolved from your configuration, the cookie scope it detected, and why an SDK-rendered Experience showed nothing. You can also turn it on without editing init(); see [Diagnostics](#diagnostics) and [Nothing renders?](https://dev.arcxp.com/content-recommendations/sdk/troubleshooting/).                                                                                                                                      |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| onError               | (e: ArcCompassErrorInfo) => void | —                                   | Called when the SDK abandons a batch (a terminal 4xx/429, or a 5xx/network failure that exhausts retries), when it drops an event before sending because the Collector would reject it, when an SDK-rendered Experience fails to load, and when the browser accepts no cookie scope so identity drops to per-origin. Use it to forward otherwise-silent loss to your observability. Never runs inside a track() call, so it cannot interrupt the page; anything it throws is swallowed. See [Error visibility](#error-visibility). |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |

### Diagnostics

The `debug` option logs lifecycle, transport, and Experience-render diagnostics to the console. When you can’t edit the `init()` call, for example because it sits in a tag manager or a template you don’t own, you can turn `debug` on from the page (since SDK 1.2.0):

- Add `?arcCompassDebug` to the page URL.
- Add a `data-arc-compass-debug` attribute to the `<script>` tag that loads the SDK.

Either one turns `debug` on even when `init()` passes `debug: false`. A value of `0` or `false` leaves it off.

Separately from `debug`, the SDK logs one `console.warn` when an `<arc-compass-*>` Experience tag on the page can’t render (since SDK 1.2.0). The SDK checks a few seconds after the page loads, and the warning names the cause:

- `init()` never ran, threw, or couldn’t load the Experience.
- `setConsent()` hasn’t been called, so the Experience is still waiting for consent.

The warning is always on, and logs at most one time per page. It stays silent when the SDK is initialized and consent is set, including `setConsent(false)`, because a Reader who declines consent is not an integration error.

Also without `debug`, an Experience that fails to load for a setup cause (the key, the origin or domain, a missing `site_id`, or a timeout) logs one `console.warn`per cause per page. For a summary of the whole setup, call [ArcCompass.diagnose()](#diagnose) from the browser console.

### Error visibility

The SDK is fire-and-forget: `track()` never throws, and a batch that the Collector rejects (or that never gets through) is dropped rather than surfaced to the page. To make those drops observable, wire `onError` to your tooling. It never runs inside a `track()` call: batch failures and dropped events arrive from a batch timer or the page-unload handler, `experience` arrives from the failed Experience’s render, and `degraded` arrives wherever identity first resolves after consent.

```ts
ArcCompass.init({
  origin: "https://{org}-config-prod.api.arc-cdn.net",
  apiKey: "<browser token>",
  onError: (e) => {
    // e: { message, reason, code?, experience?, status?, droppedEvents, eventTypes, cause? }
    Sentry.captureException(e.cause ?? new Error(e.message), { extra: e });
    // or: datadogRum.addError(e.cause ?? new Error(e.message), e);
  },
});
```

`onError` receives an `ArcCompassErrorInfo` object:

| Property      | Type                      | Description                                                                                                                                 |              |                                                                                                                           |
| ------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------- |
| message       | string                    | Human-readable summary, safe to log.                                                                                                        |              |                                                                                                                           |
| reason        | "rejected" \| "exhausted" | "degraded"                                                                                                                                  | "experience" | What went wrong. See the following table. More values may be added in a minor version, so give a switch a default branch. |
| code          | ExperienceFailureCode     | Why an Experience didn’t load. Set only when reason is "experience". See [Failure codes](#failure-codes).                                   |              |                                                                                                                           |
| experience    | string                    | The failed Experience’s tag name, such as arc-compass-recommendations-list. Set with code.                                                  |              |                                                                                                                           |
| status        | number                    | The Collector’s HTTP status, when there was a response. Absent for network and CORS failures and for events the SDK dropped before sending. |              |                                                                                                                           |
| droppedEvents | number                    | Events discarded. 0 when reason is "degraded" or "experience".                                                                              |              |                                                                                                                           |
| eventTypes    | string\[\]                | Distinct event types among the discarded events. Empty when reason is "degraded" or "experience".                                           |              |                                                                                                                           |
| cause         | unknown                   | The underlying thrown value, such as a network error, when there was one.                                                                   |              |                                                                                                                           |

| reason       | Meaning                                                                                                                                                                                  | Events lost |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
| "rejected"   | The Collector returned a terminal 4xx or 429, or the SDK dropped events before sending because the Collector would reject them (no status). Fix the payload or key; retrying won’t help. | Yes         |
| "exhausted"  | Repeated 5xx or network failures used up the retry budget.                                                                                                                               | Yes         |
| "degraded"   | The browser accepted no cookie scope, so identity is per-origin. Fires at most once per page. See [Cookie domain](#cookie-domain).                                                       | No          |
| "experience" | An SDK-rendered Experience didn’t load. Fires once per code and tag per page.                                                                                                            | No          |

Per-event issues (an unresolved `item_id`, a coerced `event_value`) are logged only under `debug`, not through `onError`.

### Cookie domain

When `cookieDomain` is omitted, the SDK writes its identity cookies at the broadest scope the browser accepts for the current host, which is that host’s registrable domain. It finds the scope by offering each candidate to the browser and keeping the first one that sticks, rather than by counting labels, so multi-segment public suffixes (`.co.uk`, `.com.au`) and platform hosts (CloudFront, Vercel, Netlify, GitHub Pages) resolve correctly without configuration. Probe cookies are deleted as soon as they are read back, and none is written before consent.

Set `cookieDomain` explicitly to override the detected scope. If the browser accepts no scope at all, identity still works but is per-origin rather than shared across subdomains, and `onError` fires once with `reason: "degraded"`(see [Error visibility](#error-visibility)).

## DOM lifecycle events

Every SDK-rendered Experience element dispatches lifecycle events on itself. The events bubble, so you can listen on a container and use `event.target` to tell which element fired.

| Event                    | detail   | When                                                                                                                                   |
| ------------------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| arc-compass:rendered     | null     | The Experience rendered content.                                                                                                       |
| arc-compass:empty        | null     | There is no content for this reader. This is a successful answer, not a failure.                                                       |
| arc-compass:error        | { code } | The Experience failed at any step. code is one of the [failure codes](#failure-codes).                                                 |
| arc-compass:catchup-done | null     | Fired only by arc-compass-catchup-card, when the reader reaches the end of the card. It can fire after arc-compass:rendered, or never. |

Each mount fires exactly one of `rendered`, `empty`, or `error`. Nothing fires while the Experience is waiting for consent. `arc-compass:error` is also reported to `onError` with `reason: "experience"`. For using these events to reserve and release layout space, see [Reserve Space and Handle Empty States](https://dev.arcxp.com/content-recommendations/sdk/reserving-space/).

### Failure codes

`ExperienceFailureCode` names a setup cause you can fix:

| Code              | Cause                                                                                                                                                                                                                                                                                                                                                                             |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| unauthorized      | The Experiences API rejected apiKey (401).                                                                                                                                                                                                                                                                                                                                        |
| forbidden         | The Experiences API returned 403. Either the key can’t read Experiences from this page, so check its access and allowed origins, or your organization isn’t active yet, with the body {"detail":"Tenant is not active"}. See [Cold-start response states](https://dev.arcxp.com/content-recommendations/content-recommendations-api-developer-guide/#cold-start-response-states). |
| network           | No readable response: the API refused this page’s origin (CORS), the host is unreachable, or origin or experiencesDomain is wrong.                                                                                                                                                                                                                                                |
| not\_found        | The Experiences base returned 404. Check origin or experiencesDomain.                                                                                                                                                                                                                                                                                                             |
| missing\_site\_id | No site resolved. Pass siteId to init() or add <meta name="arc-compass:site-id">.                                                                                                                                                                                                                                                                                                 |
| timeout           | No response within 5 seconds.                                                                                                                                                                                                                                                                                                                                                     |
| other             | Anything else, such as a 5xx, a response that didn’t validate, or a render error. Turn on debug for the detail.                                                                                                                                                                                                                                                                   |

## Attribution attributes

To attribution-track recommendations your code renders without calling `trackExposure()`, add these attributes to each rendered recommendation element inside `attributionRoot`. The SDK finds elements by `data-arc-compass-attribution-id`, including elements added later.

| Attribute                       | Required | Value                                                                         |
| ------------------------------- | -------- | ----------------------------------------------------------------------------- |
| data-arc-compass-item-id        | Yes      | The recommended item’s item\_id. An element without it is skipped.            |
| data-arc-compass-attribution-id | Yes      | The item’s attribution\_id.                                                   |
| data-arc-compass-exposure-id    | Yes      | The response’s attribution.exposure\_id. Identical for every item in the set. |
| data-arc-compass-surface-id     | No       | The surface the set is rendered on.                                           |
| data-arc-compass-position       | No       | The item’s zero-based position.                                               |
| data-arc-compass-issued-at      | No       | The response’s attribution.issued\_at.                                        |

See [Recommendation Attribution](https://dev.arcxp.com/content-recommendations/sdk/attribution/). For the attributes of the `<arc-compass-*>` Experience elements themselves, see

[Recommendations Components](https://dev.arcxp.com/content-recommendations/sdk/recommendations-components/#attributes) 

and [Catch Up Card](https://dev.arcxp.com/content-recommendations/sdk/catch-up-card/).

## Endpoints the SDK calls

The SDK posts events to `POST {domain}/events/batch`, which is `/collect-web/v1/events/batch` by default, in batches of up to 100\. SDK-rendered Experiences read `GET /experiences/recommend/v1/recommendations` and `GET /experiences/storyline/v1/catch-up` from `experiencesDomain`. These requests are internal to the SDK, and their contract can change with it; you don’t call the `collect-web` or Catch Up endpoints yourself. The events use the same envelope as the [Collector API](https://dev.arcxp.com/content-recommendations/content-recommendations-api-developer-guide/#events-endpoint).

## Browser support

The SDK supports **Chrome and Edge 111+, Firefox 113+, Safari and iOS Safari 16.2+, and Samsung Internet 22+**. That floor is set by the rendered Experiences; event collection on its own runs on older browsers too, with the caveats in the table. The floor ships as the `browserslist` field in the package’s `package.json`.

| Feature                               | Used for                                                                 | Chrome / Edge | Firefox | Safari   | Without it                                                                              |
| ------------------------------------- | ------------------------------------------------------------------------ | ------------- | ------- | -------- | --------------------------------------------------------------------------------------- |
| fetch with keepalive: true            | Sending events, including the flush when the reader leaves the page      | 66            | 133     | 13       | Events still send, but the final flush on page exit can be lost                         |
| visibilitychange, pagehide            | Detecting when the reader leaves, to flush queued events                 | 33            | 18      | 7        | Events still in the queue when the reader leaves may not be sent                        |
| localStorage, sessionStorage, cookies | Anonymous and session IDs                                                | All           | All     | All      | If storage is blocked, IDs do not persist across page views                             |
| crypto.randomUUID                     | Generating IDs                                                           | 92            | 95      | 15.4     | Falls back to crypto.getRandomValues; no effect                                         |
| Custom elements, shadow DOM           | Every Experience is an <arc-compass-\*> element with a shadow root       | 67            | 63      | 10.1     | Experiences do not render                                                               |
| IntersectionObserver                  | Exposure attribution; Catch Up Card view telemetry                       | 58            | 55      | 12.1     | Exposure events are not sent; click attribution still works                             |
| ::part()                              | Restyling Experience internals from your CSS                             | 73            | 72      | 13.1     | Your ::part() rules do not apply                                                        |
| color-mix(), including in oklab       | The Catch Up Card’s neutral colours: muted text, hairlines, subtle fills | **111**       | **113** | **16.2** | The card renders without its fills and hairlines, and muted text shows at full strength |

The recommendations Components do not use `color-mix()`, so they render in older browsers as well, but only the browsers listed at the start of this section are supported. In Firefox before 133, the event flush on page exit is best-effort. For more on theming features, see [Compass Web SDK: Theming Reference](https://dev.arcxp.com/content-recommendations/sdk/theming/).

The SDK is browser-only. The IIFE bundle is safe to include in a server-rendered page — it no-ops on import when `window` is undefined.
