# Reference

### Usage

You can access all methods through a `ref` to the `<DidomiSDK />` component.

```tsx
import { DidomiSDK, DidomiSDKAPI } from '@didomi/vega-sdk';
import React, { useRef } from 'react';

const App = () => {
  const didomiRef = useRef<DidomiSDKAPI>(null);

  return (
    <DidomiSDK
      noticeId="YOUR_NOTICE_ID"
      didomiPublicApiKey="YOUR_PUBLIC_API_KEY"
      ref={didomiRef}
      onReady={() => console.log('SDK ready')}
    >
      <YourApp />
    </DidomiSDK>
  );
};
```

***

### addEventListener

Attach a listener to SDK events (consent changes, UI visibility, errors, etc.).

**Signature**

```ts
didomi.addEventListener(event: DidomiEvent, handler: (payload?: unknown) => void): void
```

**Parameters**

* `event` — Event name (see **Events** list below).
* `handler` — Callback invoked with an optional payload.

**Returns**

* `void`

**Example**

```ts
didomiRef.current?.addEventListener('consent.changed', (status) => {
  console.log('Consent changed', status);
});
```

***

### removeEventListener

Detach a previously registered event listener.

**Signature**

```ts
didomi.removeEventListener(event: DidomiEvent, handler: (payload?: unknown) => void): void
```

**Parameters**

* `event` — Event name.
* `handler` — The same function reference passed to `addEventListener`.

**Returns**

* `void`

**Example**

```ts
const onChanged = (s: unknown) => {/* ... */};
didomiRef.current?.addEventListener('consent.changed', onChanged);
// later
didomiRef.current?.removeEventListener('consent.changed', onChanged);
```

***

### getJavaScriptForWebView

Generate an inline JS snippet to inject into a Vega WebView that mirrors the current consent state.

**Signature**

```ts
didomi.getJavaScriptForWebView(): Promise<string>
```

**Parameters**

* *None*

**Returns**

* `Promise<string>` — JavaScript to inject.

**Example**

```ts
const js = await didomiRef.current?.getJavaScriptForWebView();
vegaWebView.injectJavaScript(js!);
```

***

### getQueryStringForWebView

Build a query string carrying the current consent information for WebView navigation.

**Signature**

```ts
didomi.getQueryStringForWebView(): Promise<string>
```

**Parameters**

* *None*

**Returns**

* `Promise<string>` — Query string (without the leading `?`).

**Example**

```ts
const qs = await didomiRef.current?.getQueryStringForWebView();
vegaWebView.loadUrl(`https://example.app/privacy?${qs}`);
```

***

### showNotice

Display the consent notice. If already visible, it becomes focused.

**Signature**

```ts
didomi.notice.show(): void
```

**Parameters**

* *None*

**Returns**

* `void`

**Example**

```ts
didomiRef.current?.notice.show();
```

***

### hideNotice

Hide the consent notice if visible.

**Signature**

```ts
didomi.notice.hide(): void
```

**Parameters**

* *None*

**Returns**

* `void`

**Example**

```ts
didomiRef.current?.notice.hide();
```

***

### isNoticeVisible

Check if the consent notice is currently visible.

**Signature**

```ts
didomi.notice.isVisible(): Promise<boolean>
```

**Parameters**

* *None*

**Returns**

* `Promise<boolean>`

**Example**

```ts
const visible = await didomiRef.current?.notice.isVisible();
```

***

### showPreferences

Open the preferences dialog.

**Signature**

```ts
didomi.preferences.show(type?: 'information' | 'purposes' | 'vendor'): void
```

**Parameters**

* `type` *(optional)* — Initial tab to open (`'information'`, `'purposes'`, or `'vendor'`). Defaults to `'purposes'`.

**Returns**

* `void`

**Example**

```ts
didomiRef.current?.preferences.show('vendor');
```

***

### hidePreferences

Close the preferences dialog if open.

**Signature**

```ts
didomi.preferences.hide(): void
```

**Parameters**

* *None*

**Returns**

* `void`

**Example**

```ts
didomiRef.current?.preferences.hide();
```

***

### isPreferencesVisible

Check if the preferences dialog is visible.

**Signature**

```ts
didomi.preferences.isVisible(): Promise<boolean>
```

**Parameters**

* *None*

**Returns**

* `Promise<boolean>`

**Example**

```ts
const isOpen = await didomiRef.current?.preferences.isVisible();
```

***

### isReady

Return whether the SDK has finished initialization.

**Signature**

```ts
didomi.isReady(): boolean
```

**Parameters**

* *None*

**Returns**

* `boolean`

**Example**

```ts
if (didomiRef.current?.isReady()) { /* ... */ }
```

***

### onReady

Register a callback to run once the SDK is ready.

**Signature**

```ts
didomi.onReady(callback: () => void): void
```

**Parameters**

* `callback` — Invoked when the SDK is ready (called immediately if already ready).

**Returns**

* `void`

**Example**

```ts
didomiRef.current?.onReady(() => console.log('Vega SDK ready'));
```

***

### onError

Register a callback for SDK-level errors (configuration, network, rendering).

**Signature**

```ts
didomi.onError(callback: (error: unknown) => void): void
```

**Parameters**

* `callback` — Receives an error object or message.

**Returns**

* `void`

**Example**

```ts
didomiRef.current?.onError((e) => console.error('Didomi error', e));
```

***

### isError

Returns whether the SDK is in an error state.

**Signature**

```ts
didomi.isError(): boolean
```

**Parameters**

* *None*

**Returns**

* `boolean`

**Example**

```ts
if (didomiRef.current?.isError()) { /* show fallback */ }
```

***

### setLogLevel

Set the SDK log verbosity.

**Signature**

```ts
didomi.setLogLevel(level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR'): void
```

**Parameters**

* `level` — Desired log level.

**Returns**

* `void`

**Example**

```ts
didomiRef.current?.setLogLevel('INFO');
```

***

### getText

Resolve a UI text key using the current language.

**Signature**

```ts
didomi.getText(key: string): Promise<string | undefined>
```

**Parameters**

* `key` — Text key.

**Returns**

* `Promise<string | undefined>`

**Example**

```ts
const title = await didomiRef.current?.getText('notice.title');
```

***

### getTranslatedText

Resolve a UI text key for a specific language.

**Signature**

```ts
didomi.getTranslatedText(key: string, lang: string): Promise<string | undefined>
```

**Parameters**

* `key` — Text key.
* `lang` — IETF language tag (e.g., `en`, `fr-FR`).

**Returns**

* `Promise<string | undefined>`

**Example**

```ts
const titleFr = await didomiRef.current?.getTranslatedText('notice.title', 'fr');
```

***

### updateSelectedLanguage

Change the SDK UI language at runtime.

**Signature**

```ts
didomi.updateSelectedLanguage(lang: string): Promise<void>
```

**Parameters**

* `lang` — IETF language tag.

**Returns**

* `Promise<void>`

**Example**

```ts
await didomiRef.current?.updateSelectedLanguage('es');
```

***

### getVendor

Retrieve a vendor definition by ID.

**Signature**

```ts
didomi.getVendor(vendorId: string): Promise<Vendor | undefined>
```

**Parameters**

* `vendorId` — Vendor identifier.

**Returns**

* `Promise<Vendor | undefined>`

**Example**

```ts
const vendor = await didomiRef.current?.getVendor('google');
```

***

### getPurpose

Retrieve a purpose definition by ID.

**Signature**

```ts
didomi.getPurpose(purposeId: string): Promise<Purpose | undefined>
```

**Parameters**

* `purposeId` — Purpose identifier.

**Returns**

* `Promise<Purpose | undefined>`

**Example**

```ts
const purpose = await didomiRef.current?.getPurpose('cookies');
```

***

### getTotalVendorCount / getIabVendorCount / getNonIabVendorCount

Counts for vendors in the current configuration.

**Signatures**

```ts
didomi.getTotalVendorCount(): Promise<number>
didomi.getIabVendorCount(): Promise<number>
didomi.getNonIabVendorCount(): Promise<number>
```

**Parameters**

* *None*

**Returns**

* `Promise<number>`

**Example**

```ts
const [all, iab, nonIab] = await Promise.all([
  didomiRef.current!.getTotalVendorCount(),
  didomiRef.current!.getIabVendorCount(),
  didomiRef.current!.getNonIabVendorCount(),
]);
```

***

### getRequiredPurposes / getRequiredVendors

Return lists of purposes/vendors that are required by configuration.

**Signatures**

```ts
didomi.getRequiredPurposes(): Promise<string[]>
didomi.getRequiredVendors(): Promise<string[]>
```

**Parameters**

* *None*

**Returns**

* `Promise<string[]>`

**Example**

```ts
const requiredPurposes = await didomiRef.current?.getRequiredPurposes();
```

***

### applicableRegulation

Get the regulation currently applied to the user (e.g., `gdpr`, `cpra`, `none`).

**Signature**

```ts
didomi.applicableRegulation(): Promise<string>
```

**Parameters**

* *None*

**Returns**

* `Promise<string>`

**Example**

```ts
const reg = await didomiRef.current?.applicableRegulation();
```

***

### getCurrentUserStatus

Return the current user consent status.

**Signature**

```ts
didomi.getCurrentUserStatus(): Promise<UserStatus>
```

**Parameters**

* *None*

**Returns**

* `Promise<UserStatus>`

**Example**

```ts
const status = await didomiRef.current?.getCurrentUserStatus();
```

***

### isUserStatusPartial

Whether the stored status is partial (some choices missing).

**Signature**

```ts
didomi.isUserStatusPartial(): Promise<boolean>
```

**Parameters**

* *None*

**Returns**

* `Promise<boolean>`

**Example**

```ts
const partial = await didomiRef.current?.isUserStatusPartial();
```

***

### setCurrentUserStatus

Set the user consent status at purpose/vendor level.

**Signature**

```ts
didomi.setCurrentUserStatus(status: {
  purposes?: Record<string, 'granted' | 'denied'>,
  vendors?: Record<string, 'granted' | 'denied'>
}): Promise<void>
```

**Parameters**

* `status` — Object with per-purpose and/or per-vendor decisions.

**Returns**

* `Promise<void>`

**Example**

```ts
await didomiRef.current?.setCurrentUserStatus({
  purposes: { storage: 'granted', measurement: 'denied' },
  vendors: { google: 'granted' }
});
```

***

### setUserAgreeToAll

Grant consent for all purposes and vendors.

**Signature**

```ts
didomi.setUserAgreeToAll(): Promise<void>
```

**Parameters**

* *None*

**Returns**

* `Promise<void>`

**Example**

```ts
await didomiRef.current?.setUserAgreeToAll();
```

***

### setUserDisagreeToAll

Deny consent for all purposes and vendors.

**Signature**

```ts
didomi.setUserDisagreeToAll(): Promise<void>
```

**Parameters**

* *None*

**Returns**

* `Promise<void>`

**Example**

```ts
await didomiRef.current?.setUserDisagreeToAll();
```

***

### openCurrentUserStatusTransaction

Create a **transaction** to stage updates to the current user status (purposes & vendors) and apply them **atomically** on commit.

Updates made via the transaction are **queued** and only written to the user status when you call `commit()`.

**Signature**

```ts
didomi.openCurrentUserStatusTransaction(): CurrentUserStatusTransaction
```

**Parameters**

* *None*

**Returns**

* `CurrentUserStatusTransaction` — A chainable object for batching purpose/vendor updates.

**Behavior & Notes**

* Purposes/vendors **not specified** in the transaction remain **unchanged**.
* **Essential purposes** are always enabled and cannot be changed by the transaction.
* If the applied regulation is **none**, vendors and purposes remain enabled; `commit()` will return `false`.
* IDs not present in the **Notice Config** are **ignored** (no-op).
* Invalid IDs are ignored; errors may be logged to the console (see *Error handling* below).

**Example**

```ts
const tx = didomiRef.current!.openCurrentUserStatusTransaction();

// enable / disable purposes
tx.enablePurpose('cookies');
tx.enablePurposes(['cookies', 'analytics']);
tx.disablePurpose('analytics');
tx.disablePurposes(['cookies', 'analytics']);

// enable / disable vendors
tx.enableVendor('vendor-1');
tx.enableVendors(['vendor-1', 'vendor-2']);
tx.disableVendor('vendor-1');
tx.disableVendors(['vendor-1', 'vendor-2']);

// chain calls
tx.enablePurpose('cookies').disablePurpose('analytics');

// apply all staged changes
const updated = await tx.commit(); // true if changes applied, false otherwise
```

**Error handling**

* Invalid purposes or vendors are ignored; the SDK may log messages to the browser console.\
  Example:

  ```ts
  const tx = didomiRef.current!.openCurrentUserStatusTransaction();
  tx.enablePurposes(['cookies', 'invalid_ID']);
  const ok = await tx.commit();
  // Console:
  // 'Didomi SDK - disablePurpose ignored due to invalid purpose: invalid_ID'
  // ok === true
  ```

***

#### CurrentUserStatusTransaction (Methods)

| Method            | Parameters      | Returns                        | Description                                                                                 |
| ----------------- | --------------- | ------------------------------ | ------------------------------------------------------------------------------------------- |
| `enablePurpose`   | `id: string`    | `CurrentUserStatusTransaction` | Enable a single purpose by ID.                                                              |
| `enablePurposes`  | `ids: string[]` | `CurrentUserStatusTransaction` | Enable multiple purposes by ID.                                                             |
| `disablePurpose`  | `id: string`    | `CurrentUserStatusTransaction` | Disable a single purpose by ID.                                                             |
| `disablePurposes` | `ids: string[]` | `CurrentUserStatusTransaction` | Disable multiple purposes by ID.                                                            |
| `enableVendor`    | `id: string`    | `CurrentUserStatusTransaction` | Enable a single vendor by Didomi ID.                                                        |
| `enableVendors`   | `ids: string[]` | `CurrentUserStatusTransaction` | Enable multiple vendors by Didomi ID.                                                       |
| `disableVendor`   | `id: string`    | `CurrentUserStatusTransaction` | Disable a single vendor by Didomi ID.                                                       |
| `disableVendors`  | `ids: string[]` | `CurrentUserStatusTransaction` | Disable multiple vendors by Didomi ID.                                                      |
| `commit`          | —               | `Promise<boolean>`             | Apply all staged changes. Returns `true` if the user status was updated, `false` otherwise. |

***

### Types

Add these to the **Types** section for completeness:

```ts
export interface CurrentUserStatusTransaction {
  enablePurpose: (id: string) => CurrentUserStatusTransaction;
  enablePurposes: (ids: string[]) => CurrentUserStatusTransaction;
  disablePurpose: (id: string) => CurrentUserStatusTransaction;
  disablePurposes: (ids: string[]) => CurrentUserStatusTransaction;
  enableVendor: (id: string) => CurrentUserStatusTransaction;
  enableVendors: (ids: string[]) => CurrentUserStatusTransaction;
  disableVendor: (id: string) => CurrentUserStatusTransaction;
  disableVendors: (ids: string[]) => CurrentUserStatusTransaction;
  commit: () => Promise<boolean>;
}
```

And add the method to your API surface:

```ts
export interface DidomiSDKAPI {
  // ...
  openCurrentUserStatusTransaction: () => CurrentUserStatusTransaction;
  // ...
}
```

***

### reset

Clear locally stored consent data and re-evaluate.

**Signature**

```ts
didomi.reset(): Promise<void>
```

**Parameters**

* *None*

**Returns**

* `Promise<void>`

**Example**

```ts
await didomiRef.current?.reset();
```

***

### shouldUserStatusBeCollected

Whether the app should prompt for consent (e.g., user is in-scope, no valid status yet).

**Signature**

```ts
didomi.shouldUserStatusBeCollected(): Promise<boolean>
```

**Parameters**

* *None*

**Returns**

* `Promise<boolean>`

**Example**

<pre class="language-ts"><code class="lang-ts"><strong>if (await didomiRef.current?.shouldUserStatusBeCollected()) {
</strong>  didomiRef.current?.notice.show();
}
</code></pre>

***

#### syncUser

Update the **local user status** from the Didomi servers in a **single-page application**.

If your site is **not** an SPA, do **not** call this method directly — syncing is automatically performed when `window.didomiConfig.user` is set on page load.

Synchronization will only run if:

* Sync is enabled in the configuration,
* An `organizationUserId` is provided,
* The user is not a bot, and
* The sync frequency has not been exceeded.

**Signature**

```ts
didomi.syncUser(): Promise<SyncReadyEvent>
```

**Parameters**

* *None*

**Returns**

* `Promise<SyncReadyEvent>` — An object describing the result of the sync.

***

#### SyncReadyEvent

| Property           | Type                     | Description                                                                                                                                                                         |
| ------------------ | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `statusApplied`    | `boolean`                | `true` if the local user status was updated from the server, `false` otherwise.                                                                                                     |
| `syncAcknowledged` | `() => Promise<boolean>` | Call this to confirm to Didomi that the synchronized status has been communicated to the user. Returns `true` if the acknowledgment event was sent successfully, `false` otherwise. |
| `syncError`        | `string \| undefined`    | Error message if the sync failed.                                                                                                                                                   |

***

#### Examples

**Simple sync**

```ts
await didomiRef.current!.syncUser();
```

**Reassurance notice flow**

```ts
const syncResult = await didomiRef.current!.syncUser();

if (syncResult.statusApplied) {
  // The user status actually changed from syncing

  // Show your reassurance notice to the user

  // Report that the reassurance notice has been shown
  const acknowledged = await syncResult.syncAcknowledged();
  console.log('Sync acknowledged:', acknowledged);
}
```

***

**Notes**

* Use `syncUser()` only when you need to **refresh consent state** in an SPA.
* Always check `statusApplied` — if it’s `false`, the local state is already up to date.
* If you show any UI reassurance (e.g., “Your preferences are updated”), remember to call `syncAcknowledged()`.

***

#### setUser

Update the user configuration details in a **single-page application**.\
In multi-page apps, do **not** call this method directly. Instead, set the user configuration details via `window.didomiConfig.user` on page load.

The function updates all the provided properties and sets any omitted properties to `undefined`.

**Signature**

```ts
didomi.setUser(userConfiguration: UserConfiguration): Promise<void>
```

**Parameters**

| Name                              | Type     | Description                                                  |
| --------------------------------- | -------- | ------------------------------------------------------------ |
| `organizationUserId`              | `string` | Organization User ID to associate with the user.             |
| `organizationUserIdAuthAlgorithm` | `string` | Algorithm used for computing the digest.                     |
| `organizationUserIdAuthSid`       | `string` | ID of the secret used for computing the digest.              |
| `organizationUserIdAuthSalt`      | `string` | Salt used for computing the digest.                          |
| `organizationUserIdAuthDigest`    | `string` | Digest of the organization user ID and secret.               |
| `organizationUserIdExp`           | `number` | Unix timestamp (expiration).                                 |
| `organizationUserIdIv`            | `string` | Initialization vector if encryption was used for the digest. |

**Returns**

* `Promise<void>`

**Example**

```ts
await didomiRef.current?.setUser({
  organizationUserId: 'organizationUserID',
  organizationUserIdAuthAlgorithm: 'HS256',
  organizationUserIdAuthSid: 'sid_123',
  organizationUserIdAuthSalt: 'random_salt',
  organizationUserIdAuthDigest: 'abcdef123456',
  organizationUserIdExp: 1699999999,
  organizationUserIdIv: 'iv_string'
});
```

**Notes**

* Call `setUser` **only once per session** unless you explicitly need to update the user identity.
* If you pass only a subset of fields, any omitted ones will be reset to `undefined`.
* Always ensure the digest values (if used) are generated securely on your backend.

***

### clearUser

Disassociate any user identifier from the current session.

**Signature**

```ts
didomi.clearUser(): Promise<void>
```

**Parameters**

* *None*

**Returns**

* `Promise<void>`

**Example**

```ts
await didomiRef.current?.clearUser();
```

***

### Notice Config

These helpers expose details about the loaded notice/config.

> Depending on your Vega integration, some fields may be undefined until `onReady`.

***

#### Types

Below are the key TypeScript interfaces surfaced by the SDK.

```ts
type DidomiEvent =
  | 'sdk.ready'
  | 'sdk.error'
  | 'notice.shown'
  | 'notice.hidden'
  | 'preferences.shown'
  | 'preferences.hidden'
  | 'preferences.saved'
  | 'consent.changed';

interface Vendor {
  id: string;
  name?: string;
  policyUrl?: string;
  purposeIds?: string[];
  [key: string]: unknown;
}

interface Purpose {
  id: string;
  name?: string;
  description?: string;
  [key: string]: unknown;
}

interface UserStatus {
  purposes: Record<string, 'granted' | 'denied'>;
  vendors: Record<string, 'granted' | 'denied'>;
  regulation?: 'gdpr' | 'cpra' | 'none' | string;
  updatedAt?: string;
}
```
