> ## Documentation Index
> Fetch the complete documentation index at: https://docs.frankieone.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Event System

> Complete reference for the OneSDK event system

## Overview

The OneSDK uses an event-driven architecture that allows you to listen for and respond to various events throughout the verification lifecycle. Every module and the SDK itself emit events that you can subscribe to.

## Event Methods

All modules and the SDK context provide these event methods:

### `on(eventName, callback)`

Registers an event listener for the specified event.

**Signature:**

```typescript theme={null}
on<EventName>(
  eventName: EventName | EventName[],
  callback: (...args: EventArguments) => void
): void
```

**Parameters:**

* `eventName`: String or array of strings representing event name(s)
* `callback`: Function to call when the event is emitted

**Example:**

```javascript theme={null}
// Single event
oneSDKInstance.on('error', (error) => {
  console.error('SDK error:', error);
});

// Multiple events
oneSDKInstance.on(['loading', 'info'], (data) => {
  console.log('Event received:', data);
});
```

***

### `off(eventName, callback)`

Removes a previously registered event listener.

**Signature:**

```typescript theme={null}
off<EventName>(
  eventName: EventName | EventName[],
  callback: (...args: EventArguments) => void
): void
```

**Parameters:**

* `eventName`: String or array of strings representing event name(s)
* `callback`: The exact function reference that was registered with `on()`

**Example:**

```javascript theme={null}
const errorHandler = (error) => {
  console.error('Error:', error);
};

// Register
oneSDKInstance.on('error', errorHandler);

// Later, remove
oneSDKInstance.off('error', errorHandler);
```

<Warning>
  Do not call `off()` without parameters on global event handlers. This removes ALL listeners and may break internal SDK functionality.
</Warning>

***

### `emit(eventName, ...args)`

Emits an event with optional arguments. Available only on the SDK context (not on module instances).

**Signature:**

```typescript theme={null}
emit<EventName>(
  eventName: EventName,
  ...args: EventArguments
): void
```

**Example:**

```javascript theme={null}
// Emit custom telemetry event
oneSDKInstance.emit('telemetry', {
  eventName: 'CUSTOM_EVENT',
  data: { action: 'button_clicked' }
});
```

***

## Global Events

These events are emitted by the SDK context and are available on all SDK instances.

### Common Events

Available on all modules and the SDK context:

| Event     | Arguments                                                         | Description                        |
| --------- | ----------------------------------------------------------------- | ---------------------------------- |
| `error`   | `(error: OneSDKError)`                                            | Emitted when an error occurs       |
| `warning` | `(warning: { message: string, payload?: unknown })`               | Emitted for non-critical warnings  |
| `info`    | `(info: { message?: string, payload?: unknown, name?: unknown })` | Emitted for informational messages |
| `loading` | `(isLoading: boolean, context: { message: string })`              | Emitted when loading state changes |
| `*`       | `(event: { eventName: string, arguments: unknown[] })`            | Wildcard - captures all events     |

### SDK-Specific Events

| Event                    | Arguments                                 | Description                                                                   |
| ------------------------ | ----------------------------------------- | ----------------------------------------------------------------------------- |
| `resolved_root_config`   | `(config: GlobalState)`                   | Emitted when root configuration is resolved                                   |
| `resolved_module_config` | `(state: InjectedState, config: unknown)` | Emitted when a module configuration is resolved                               |
| `telemetry`              | `(event: TelemetryEvent)`                 | Emitted for internal diagnostic data (used by FrankieOne for troubleshooting) |
| `network_offline`        | `()`                                      | Emitted when network connection is lost                                       |
| `network_online`         | `()`                                      | Emitted when network connection is restored                                   |

## Event Examples

### Handling Errors

```javascript theme={null}
oneSDKInstance.on('error', (error) => {
  console.error('SDK Error:', {
    message: error.message,
    code: error.code,
    details: error.details
  });

  // Show user-friendly message
  showErrorToUser('Verification error. Please try again.');
});
```

### Monitoring Loading States

```javascript theme={null}
oneSDKInstance.on('loading', (isLoading, context) => {
  if (isLoading) {
    showSpinner(context.message);
  } else {
    hideSpinner();
  }
});
```

### Telemetry Events

<Note>
  Telemetry events are used internally by FrankieOne for troubleshooting and diagnostic purposes. You generally don't need to listen to these events in your application.
</Note>

```javascript theme={null}
// For debugging purposes only
oneSDKInstance.on('telemetry', (event) => {
  if (typeof event === 'string') {
    console.log('Telemetry event:', event);
  } else {
    console.log('Telemetry event:', event.eventName, event.data);
  }
});
```

### Network Status Monitoring

```javascript theme={null}
let isOnline = true;

oneSDKInstance.on('network_offline', () => {
  isOnline = false;
  showBanner('You are offline. Verification will resume when connection is restored.');
});

oneSDKInstance.on('network_online', () => {
  if (!isOnline) {
    isOnline = true;
    showBanner('Connection restored. Resuming verification...');
  }
});
```

### Configuration Events

```javascript theme={null}
oneSDKInstance.on('resolved_root_config', (config) => {
  console.log('SDK configured with:', {
    mode: config.mode,
    recipe: config.recipe,
    session: config.session
  });
});
```

### Wildcard Event Listener

Capture all events for debugging:

```javascript theme={null}
oneSDKInstance.on('*', (event) => {
  console.log('Event emitted:', event.eventName, event.arguments);
});
```

## Module Events

Each module has its own set of events. Subscribe to module events through the module instance:

### Individual Module Events

```javascript theme={null}
const individual = oneSDKInstance.individual();

individual.on('data_loaded', () => {
  console.log('Individual data loaded');
});

individual.on('results', (results) => {
  console.log('Verification results:', results);
});

individual.on('detection_complete', (data) => {
  console.log('Detection complete:', data);
});
```

### Component Events

Dynamic components also emit events:

```javascript theme={null}
const documentComponent = oneSDKInstance.component('document', {
  countries: ['AUS', 'NZL']
});

documentComponent.on('results', (results) => {
  console.log('Document capture results:', results);
});

documentComponent.on('ready', () => {
  console.log('Document component ready');
  documentComponent.mount('#document-container');
});
```

## Event Patterns

### Async Event Handling

```javascript theme={null}
individual.on('results', async (results) => {
  try {
    // Send results to backend
    await sendToBackend(results);

    // Continue to next step
    startNextVerificationStep();
  } catch (error) {
    console.error('Failed to process results:', error);
  }
});
```

### Event Cleanup

Always clean up event listeners when components unmount:

```javascript theme={null}
// React example
useEffect(() => {
  const handleError = (error) => {
    console.error(error);
  };

  oneSDKInstance.on('error', handleError);

  // Cleanup on unmount
  return () => {
    oneSDKInstance.off('error', handleError);
  };
}, []);
```

### Event Chaining

Chain events to create verification flows:

```javascript theme={null}
const individual = oneSDKInstance.individual();

// Step 1: Wait for data to load
individual.on('data_loaded', () => {
  console.log('Step 1: Data loaded');

  // Step 2: Submit data
  individual.submit();
});

// Step 3: Handle results
individual.on('results', (results) => {
  console.log('Step 2: Results received');

  if (results.status.type === 'passed') {
    navigateToSuccess();
  } else {
    showErrorScreen(results);
  }
});
```

## Error Event Details

The `error` event provides a structured error object:

```typescript theme={null}
class OneSDKError<Payload = unknown> extends Error {
  readonly message: string;
  readonly name: string;
  readonly payload: Payload;
}
```

**Properties:**

* `message` - Human-readable error description
* `name` - Error type identifier (optional)
* `payload` - Additional error context (type varies by error)

### Error Handling Example

```javascript theme={null}
oneSDKInstance.on('error', (error) => {
  console.error('SDK Error:', {
    message: error.message,
    name: error.name,
    payload: error.payload
  });

  // Handle errors based on name and message patterns
  if (error.name === 'NetworkError') {
    showRetryButton();
  } else if (error.message.includes('token')) {
    redirectToLogin();
  } else {
    showGenericError(error.message);
  }
});
```

## Telemetry Event Structure

Telemetry events can be either a simple string or an object:

```typescript theme={null}
type TelemetryEvent =
  | string
  | {
      eventName: string;
      data?: Record<string, unknown>;
      error?: Error;
    };
```

### Telemetry Event Details

<Warning>
  Telemetry events are used internally by FrankieOne for diagnostic and troubleshooting purposes. These events are not intended for use in your application logic or analytics.
</Warning>

```javascript theme={null}
// For debugging purposes only - not recommended for production use
oneSDKInstance.on('telemetry', (event) => {
  console.log('Internal diagnostic event:', event);
});
```

## Best Practices

1. **Always handle errors**: Subscribe to the `error` event on all modules and the SDK context.

2. **Clean up listeners**: Remove event listeners when components unmount to prevent memory leaks.

3. **Use specific events**: Subscribe to specific events rather than relying on the wildcard (`*`) event.

4. **Avoid inline functions with `off`**: Store function references if you need to remove them later.

5. **Don't block event handlers**: Keep event handler logic lightweight. Use async handlers for heavy operations.

6. **Monitor network events**: Handle offline scenarios gracefully by listening to network events.

7. **Log telemetry in production**: Use telemetry events to monitor SDK behavior in production.

## Debugging Events

### Log All Events

```javascript theme={null}
if (process.env.NODE_ENV === 'development') {
  oneSDKInstance.on('*', (event) => {
    console.debug('[OneSDK Event]', event.eventName, event.arguments);
  });
}
```

### Event Timeline

```javascript theme={null}
const eventLog = [];

oneSDKInstance.on('*', (event) => {
  eventLog.push({
    timestamp: Date.now(),
    name: event.eventName,
    args: event.arguments
  });
});

// Later, inspect the timeline
console.table(eventLog);
```

## Related

* [SDK Initialization](/sdk-reference/sdk-initialization)
* [Error Handling](/sdk-reference/error-handling)
* [Individual Module](/sdk-reference/individual-module)
* [Component System](/sdk-reference/components)
