Skip to main content

@xaiku/core

The core SDK factory that creates an Xaiku instance with storage, event system, GUID management, and client attributes. This is the foundational package that all environment-specific SDKs build upon.

tip

Most users should use @xaiku/browser, @xaiku/react, or @xaiku/nextjs instead. Use @xaiku/core directly only when building a custom integration or a new environment-specific SDK.

Installation

npm install @xaiku/core

Usage

import makeSDK from '@xaiku/core';

const sdk = makeSDK({
pkey: 'pk_your_public_key',
appName: 'my-app',
version: '1.0.0',
});

Factory Function

makeSDK(options?: SDKOptions): SDKInstance

Creates and returns an SDK instance. The factory initializes the event system, storage, GUID, API URL resolution, and an optional client for managing attributes.

Options

OptionTypeDefaultDescription
pkeystringRequired. Your public key (must start with pk_).
appNamestring'xaiku'Application name for identification.
versionstring'N/A'Application version string.
storeobject{ name: 'memory', custom: null }Storage configuration. See Storage.
experimentIdsstring | string[][]Experiment IDs to fetch on initialization.
skipClientbooleanfalseSkip client creation when true.
onReportfunction | nullnullCallback invoked with the event buffer before flushing.
frameworkstringFramework identifier (set by higher-level SDKs).
frameworkVersionstringFramework version (set by higher-level SDKs).
userIdstring''User identifier passed through to client attributes.
orgIdstring''Organization identifier passed through to client attributes.
guidstringExplicit GUID. When omitted, one is generated or retrieved from storage.
devbooleanWhen true, uses the local development API URL.
proxyApiUrlstringCustom API URL. Overridden by dev.
searchParamsstring[]URL search parameter names to capture with metrics.

Instance Properties

PropertyTypeDescription
optionsobjectMerged options object.
appNamestringApplication name.
versionstringApplication version.
pkeystringPublic key.
experimentIdsstring[]Normalized array of experiment IDs.
storageobjectResolved storage adapter (see Storage).
guidstringUnique visitor identifier (UUID v4 format).
apiUrlstringResolved API base URL.
tokenstringToken extracted from the public key.
clientobject | undefinedClient instance (omitted when skipClient is true).

Event System

Every SDK instance exposes an event emitter for inter-module communication.

on(eventName, handler)

Subscribe to an event. Returns an unsubscribe function that itself has a chainable .on() method, allowing multiple subscriptions to be torn down together.

const off = sdk.on('experiments:fetched', (experiments) => {
console.log(experiments);
});

const offAll = sdk.on('experiments:fetched', handlerA)
.on('variants:select', handlerB);

offAll();

once(eventName, handler)

Subscribe to an event and automatically unsubscribe after the first invocation.

sdk.once('experiments:fetched', (experiments) => {
console.log('Fetched once:', experiments);
});

off(eventName, handler)

Remove a specific handler from an event.

sdk.off('experiments:fetched', handler);

trigger(eventName, ...args)

Emit an event, calling all registered handlers with the provided arguments.

sdk.trigger('custom:event', { key: 'value' });

offAll()

Remove all event listeners.

Client API

The client manages session attributes that are attached to every reported metric. It is created automatically unless skipClient is true.

client.getAttribute(key)

Returns the value of a single attribute.

sdk.client.getAttribute('sessionId');

client.getAttributes()

Returns all current attributes as an object.

const attrs = sdk.client.getAttributes();

client.setAttribute(key, value)

Set an attribute. value can be a direct value or an updater function receiving the current value.

sdk.client.setAttribute('userId', 'user_123');

sdk.client.setAttribute('counter', (prev) => prev + 1);

client.setAttributes(values)

Set multiple attributes at once.

sdk.client.setAttributes({
userId: 'user_123',
orgId: 'org_456',
});

Default Client Attributes

AttributeSource
frameworkoptions.framework
frameworkVersionoptions.frameworkVersion
sessionIdoptions.guid or sdk.guid
userIdoptions.userId
orgIdoptions.orgId

Function Proxy

The instance includes proxy utilities from makeFnProxy, exposed as:

MethodDescription
canProxyFn(fn)Check if a function can be proxied.
proxy(obj, fnNames, callback, context)Proxy one or more methods on an object.
proxyFn(name, fn, callback, context, obj)Proxy a single function.
xaikuFnSymbolSymbol used to mark proxied functions.
proxyStatesObject with start, end, error state strings.

Storage

Storage is resolved in the following order:

  1. If store.custom is provided and valid, it is used directly.
  2. The named store from store.name is created ('cookie', 'localStorage', 'sessionStorage', or 'memory').
  3. If the resolved store is not supported in the current environment, falls back to memory.

A valid store must implement get(key), set(key, value), and delete(key).

destroy()

Tears down the SDK instance and cleans up the client.

sdk.destroy();