# Module Injector

Lightweight library for injecting AB Tasty modules into an iframe, wiring
postMessage events, and syncing module storage/config with the modules API.

## What it does

- Loads a listener into an iframe and injects module runtime helpers.
- Fetches module config and source, then evaluates it in the iframe.
- Provides simple event, tracking, and storage plumbing between parent and iframe.

## Install

```bash
npm install
```

Node 22+ is required.

## Build

```bash
npm run build
```

## Usage

```js
import injector, { updateAccessToken, setModuleApiBase } from './dist/index';

setModuleApiBase('https://modules-api.poc.abtastylab.com');

injector.inject({
  iframeElement: document.getElementById('module-frame'),
  ab: {
    accessToken: '<token>',
    accountId: '<account-id>',
    moduleId: '<module-id>',
    testId: '<test-id>',
    env: 'production'
  },
  injectedCallback: () => console.log('injected')
});

// Optionally update token later
updateAccessToken(document.getElementById('module-frame'), '<new-token>');
```

## Options

`inject` accepts:

- `iframeElement` (required): target iframe element.
- `ab` (required): object containing access/module identifiers and config.
- `script` (optional): raw source code to inject instead of fetching from API.
- `allowedOrigins` (optional): allowlist for incoming postMessage events.
  Defaults to `'*'` for backward compatibility.
- `targetOrigin` (optional): target origin for outgoing postMessage calls.
  Defaults to `'*'`.
- Callback hooks: `injectedCallback`, `readyCallback`, `waitCallback`,
  `heightUpdatedCallback`, `eventCallback`, `trackCallback`.

You can also set the modules API base URL globally:

```js
import { setModuleApiBase } from './dist/index';

setModuleApiBase('https://modules-api.poc.abtastylab.com');
```

## Security notes

- The iframe listener uses `eval` to run module code. Only use trusted sources.
- If you enable `allowedOrigins`, remember that `srcdoc`/`data:` iframes report
  origin as `"null"`.

## Development

The entrypoint is `src/index.js`.
Build output is written to `dist/`.

## Examples

The example test harness lives in `examples/test.js` and is not bundled into `dist/`.
