# Directo adUnit Integration Guide

<img alt="version" src="https://img.shields.io/badge/version-2.0.0-blue?style=flat" />
<a href="https://getdirecto.com" target="_blank">
  <img alt="getdirecto.com" src="https://img.shields.io/badge/getdirecto-join-brightgreen?style=flat" />
</a>

## Overview

This guide provides comprehensive instructions for integrating the **Directo adUnit Library** into your browser extension projects. It covers installation, background/content setup, required permissions, message filtering, API usage, and troubleshooting. 

## Installation Methods

### Method 1: NPM Installation

1. Install the package from npm:

```shell
npm install @directo/adunit
```

2. Import the library in your code:

```javascript
// In background scripts
import { initializeAdUnit, isAdUnitMessage } from '@directo/adunit/background';

// In content scripts
import { initializeAdUnit } from '@directo/adunit/content';
```

3. Use your bundler of choice (Vite, webpack, Rollup, esbuild) to build your extension.

**TypeScript Compatibility Note:** This package is bundled with the ES2023 library and targets ES6. Ensure your project's TypeScript configuration (`tsconfig.json`) is compatible with these settings for optimal type support and compatibility.

@todo
### Method 2: Direct Script Inclusion

1. Obtain the Directo library JS builds from the `directo-global` folder:

* directo-global/background.js – for background/service worker

* directo-global/content.js – for content scripts

2. Place these files in your extension (e.g., vendor/).

3. Reference them in manifest.json and your entry points:

```json
{
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": [
        "vendor/directo-global/content.js",
        "content.js"
      ]
    }
  ]
}
```

## Implementation Guide

### Separate Background and Content Entrypoints

`@directo/adunit` ships **two distinct entrypoints**: `@directo/adunit/background` for the service worker and `@directo/adunit/content` for content scripts. They are not interchangeable:

- The background entrypoint uses background-only Chrome APIs (e.g. `chrome.runtime.onInstalled` for config migration purposes on extension updates) that are unavailable in content scripts.
- The content entrypoint runs in the page context and uses DOM/page APIs that are unavailable in the service worker.

⚠️ **Do not pull the background entrypoint into a content-script bundle, or vice versa** — even transitively through a shared module. Make sure your bundler configuration produces fully separated bundles for each entrypoint, and avoid sharing modules between them that re-export from `@directo/adunit/background` or `@directo/adunit/content`.

#### How to spot a misbundling

`@directo/adunit` detects when its background or content module is evaluated in the wrong execution context and reports it in the browser's devtools. Specifically, you will see one of the following `console.error` messages, followed by a `console.trace` showing the import chain that pulled the offending module in:

- `[Directo] @directo/extension-core/background was loaded outside a service-worker / background-page context…` — background-only code ended up in a content script (or another extension page like the popup/options).
- `[Directo] @directo/extension-core/content was loaded inside a service-worker / background-page context…` — content-only code ended up in the background bundle.

Both messages also tell you that they are likely caused by transitive imports and point back to this section of the README. To diagnose the offending import chain:

1. **Open devtools on the failing context**: for content scripts use the page's devtools; for the service worker / background page use `chrome://extensions` → "Inspect views: service worker" (or the equivalent in Firefox's `about:debugging`).
2. **Find the `[Directo] …` `console.error`** and expand the `console.trace` immediately below it. The stack frames are the modules that were mid-evaluation when the misuse was detected, walking back to your bundle's entrypoint.
3. **Enable source maps in your bundler's build configuration** (`devtool: 'source-map'` in webpack, `sourcemap: true` in Rollup/Vite/esbuild). Without source maps the trace frames point at minified bundle internals; with them they point at the actual `import` lines in your source.
4. **Fix the import chain**: usually this means moving a shared helper into a module that doesn't transitively re-export from `@directo/adunit/background` or `@directo/adunit/content`, or splitting it into background-safe and content-safe halves.

When this misuse is detected the SDK suppresses the Chrome API calls that would otherwise crash the host script, so seeing the warning does not necessarily mean the script will fail outright — but some functionality will be silently disabled. Treat the warning as a build bug and fix it.

### Background Script

After installing via NPM or including the JS file:

```javascript
// For JS inclusion only (Method 2):
// self.importScripts('vendor/directo-global/background.js');
// globalThis.DirectoAdUnit.initializeAdUnit('YOUR_PARTNER_API_KEY');

// Using an IIFE for error handling isolation in the service worker context
(() => {
  try {
    // Initialize the Directo adUnit with your partner API key
    initializeAdUnit('YOUR_PARTNER_API_KEY');
    console.log('Directo background initialized successfully');
  } catch (err) {
    console.error('Failed to initialize Directo:', err);
    // Optional: fallback logic
  }
})();
```

The background process bootstraps the Directo runtime, sets up listeners, and coordinates content activity. 


### Content Script

```javascript
async function initializeContent() {
  if (document.body) {
    try {
      console.log('Attempting to initialize Directo AdUnit');
      await initializeAdUnit();
      console.log('Directo AdUnit initialized successfully');
    } catch (error) {
      console.error('Error initializing Directo AdUnit:', error);
    }
  } else {
    console.warn('Document body not available yet');
    setTimeout(initializeContent, 50);
  }
}

if (document.readyState === 'loading') {
  console.log('Document still loading, waiting for DOMContentLoaded');
  document.addEventListener('DOMContentLoaded', initializeContent);
} else {
  console.log('Document already loaded, running initialization immediately');
  initializeContent();
}
```

Initialize the AdUnit early, once the DOM is ready, to ensure timely UI/display behavior. 

## Required Permissions

**Exception requested:** the required extension permissions for this Directo integration are **storage**, **unlimitedStorage** and **scripting**.

```json
{
  "permissions": [
    "storage",
    "unlimitedStorage",
    "scripting"
  ],
  "host_permissions": [ "<all_urls>" ]
}
```

**Permission explanation**

* `storage`: persists configuration and user preferences used by the AdUnit/runtime.  
* `unlimitedStorage` (optional but recommended): if your combined extension \+ Directo data may exceed 10 MB; expect several MB used by cached rules/assets.  
* `scripting`: needed to power core on-page features, like showing deal widgets on supported travel sites in real time.

Ensure your injection strategy (e.g., content scripts declared in manifest.json) aligns with this permissions model. 

## Critical Integration Requirements

### Auto-Rejecting Directo Messages

⚠️ **IMPORTANT:** Your extension **must** short-circuit Directo internal messages in your message listener to avoid conflicts with your own app messages. 

```javascript
// If using the package:
import { isAdUnitMessage } from '@directo/adunit/background';

// Example message listener (service worker / background)
chrome.runtime.onMessage.addListener((data, sender, sendResponse) => {
  // Always gate Directo messages first:
  if (isAdUnitMessage(data)) {
    return; // Ignore: handled internally by Directo
  }

  // Your extension's message handling below...
});
```

Why this is required

Without this guard:

1. Your extension might process Directo’s internal messages.

2. Directo functionality could break or behave unpredictably.

3. You may see console errors or crashes stemming from message handling. 

## API Reference

### Background Script API

```javascript
initializeAdUnit('YOUR_PARTNER_API_KEY');
```

### Content Script API

```javascript
// Sets up the Directo AdUnit and observers
initializeAdUnit();
```

Implement robust try/catch (or .catch) around initialization to surface failures and enact fallbacks. Both functions return promises that should be fire-and-forget, however we encourage handling initialization errors.

## Error Handling

```javascript
initializeAdUnit('YOUR_PARTNER_KEY')
  .then(() => {
    console.log('Directo background initialized successfully');
  })
  .catch((error) => {
    console.error('Failed to initialize Directo:', error);
    // Add any cleanup or degraded-mode logic here
  });
```

## Testing Your Integration

1. Confirm the background script initializes without errors (Service Worker logs).

2. Navigate to pages where the AdUnit should activate and verify expected UI/behavior.

## Troubleshooting

### Common issues

* **Initialization Failures**: Usually invalid/absent API key or network errors.

* **Missing AdUnit UI**: Ensure content scripts are injected as expected (manifest matches) and that DOM is ready before calling initializeAdUnit().

* **Console Errors**: Inspect logs from both background and content scripts.

* **Minimum Version**: Confirm compatibility with the minimum Directo library version intended for this integration. 

## Support

For technical support or integration questions, contact julian@getdirecto.com.

## License

Proprietary - Directo Tech, Inc.
