Skip to main content

@uniformdev/context

This package provides the core functionality for Uniform's classification, personalization, and testing capabilities.

Classes

Context

Represents the Uniform tracker.
- Constructor
Context(options)
Creates a new object using the specified options.
Parameters:
  • optionsContextOptions
    + show child attributes
- Events
log
Emitted when a log message is emitted from the Context.
personalizationResult
Emitted when personalization variants have been selected.
+ show event data members
For more information, see example in our developer guide.
quirksUpdated

Emitted when quirk data changes.

  • The event is not fired if an update does not result in at least one change to a quirk value.

Each key on the event object is a string that identifies the name of the quirk. The value for each key is a string.

For more information, see example in our developer guide.
scoresUpdated

Emitted when the scores are updated.

  • The event is not fired if an update does not result in any score changes.
  • The result is merged between session and permanent data.

Each key on the event object is a string that identifies the name of the visitor dimension. The value for each key is a number.

For more information, see example in our developer guide.
testResult
Emitted when an A/B test runs.
+ show event data members
For more information, see example in our developer guide.
- Members
eventsobject (read-only)
Object used to add and remove listeners for the events emitted by the Context.
+ show child attributes
forget(fromAllDevices)
Forgets the visitor's data and resets the Context to its initial state.
Parameters:
  • fromAllDevicesboolean- If false, logout from this device ID. If true, forget all data about the visitor and their identity.
Returns: Promise<void>
getServerToClientTransitionState()
Computes server to client transition state. Removes state from server-to-client if it came in initial state (cookies) to avoid double tracking on the client.
Returns: ServerToClientTransitionState
+ show child attributes
log(message)
Writes a message to the Context log sink. Used by Uniform internal SDK; not intended for public use.
Parameters:
  • messageLogMessage
Returns:
manifestManifestInstance (read-only)
personalize(options)
Parameters:
  • optionsPersonalizeOptions
    + show child attributes
Returns:
quirksQuirks (read-only)
Quirks set on visitor.
scoresScoreVector (read-only)
Gets the current visitor's dimension score vector.
storageVisitorDataStore (read-only)
test(options)
Executes an A/B test with a given set of variants, showing the visitor's assigned variant (or selecting one to assign, if none is set yet).
Parameters:
  • optionsTestOptions- Options that control how the A/B testing process runs.
    + show child attributes
Returns: void
update(newData)
Updates the Context with new data of any sort, such as new URLs, cookies, quirks, and enrichments.
Parameters:
  • newDataContextState- New data used to updated the Context.
    + show child attributes
Returns: void

CookieTransitionDataStore

Handles client-to-server score handoff using an encoded cookie with the visitor score vector.
Inherits from
- Constructor
CookieTransitionDataStore(options)
Creates a new object using the specified options.
Parameters:
  • optionsCookieTransitionDataStoreOptions
    + show child attributes
- Events
dataUpdatedAsync
Fired when the data is updated asynchronously (i.e. a promise resolves with new data from a backend).
+ show event data members
- Members
dataVisitorData (read-only)
The visitor data.
delete(fromAllDevices)
Deletes a visitor's stored data, forgetting them.
Parameters:
  • fromAllDevicesboolean (optional)- If false, logout from this device ID. If true, forget all data about the visitor and their identity.
Returns: Promise<void>
eventsobject (read-only)
Object used to add and remove listeners for the events emitted by the TransitionDataStore.
+ show child attributes
getClientTransitionState()
When we load on the client side after a server side rendering has occurred (server to client transition), we can have a page script (ID: __UNIFORM_DATA__) that contains the computed visitor data from the SSR/edge render. This data is injected into the first render to allow score syncing and the server to request commands be applied to the client side data store.
Returns:
  • ServerToClientTransitionState- Client transition state was resolved.
    + show child attributes
  • null- No client transition state was resolved.
initialDataVisitorData (read-only)
During server-side rendering we pre-fetch the data before rendering for the visitor, and pass it in here in order to avoid any asynchonry during SSR. This property is set through the constructor.
updateData(commands, computedValue)
Deletes a visitor's stored data, forgetting them.
Parameters:
Returns: Promise<void>

ManifestInstance

info

Coming soon.

TransitionDataStore

This object is used to transfer server-side or edge-side execution state to the client.
- Constructor
TransitionDataStore(options)
Creates a new object using the specified options.
Parameters:
  • optionsTransitionDataStoreOptions
    + show child attributes
- Events
dataUpdatedAsync
Fired when the data is updated asynchronously (i.e. a promise resolves with new data from a backend).
+ show event data members
- Members
dataVisitorData (read-only)
The visitor data.
delete(fromAllDevices)
Deletes a visitor's stored data, forgetting them.
Parameters:
  • fromAllDevicesboolean (optional)- If false, logout from this device ID. If true, forget all data about the visitor and their identity.
Returns: Promise<void>
eventsobject (read-only)
Object used to add and remove listeners for the events emitted by the TransitionDataStore.
+ show child attributes
getClientTransitionState()
When we load on the client side after a server side rendering has occurred (server to client transition), we can have a page script (ID: __UNIFORM_DATA__) that contains the computed visitor data from the SSR/edge render. This data is injected into the first render to allow score syncing and the server to request commands be applied to the client side data store.
Returns:
  • ServerToClientTransitionState- Client transition state was resolved.
    + show child attributes
  • null- No client transition state was resolved.
initialDataVisitorData (read-only)
During server-side rendering we pre-fetch the data before rendering for the visitor, and pass it in here in order to avoid any asynchonry during SSR. This property is set through the constructor.
updateData(commands, computedValue)
Deletes a visitor's stored data, forgetting them.
Parameters:
Returns: Promise<void>

VisitorDataStore

Provides access to storage for visitor data.
- Events
consentUpdated
Emitted when storage consent is changed.
+ show event data members
controlGroupUpdated
Emitted when visitor control group membership is changed.
+ show event data members
quirksUpdated

Emitted when quirk data changes.

  • The event is not fired if an update does not result in at least one change to a quirk value.
+ show event data members
scoresUpdated

Emitted when the scores are updated.

  • The event is not fired if an update does not result in any score changes.
  • This is fired for any update, whether from integrated or transition storage.
+ show event data members
testsUpdated
Fired when test variant selection is updated.
+ show event data members
- Members
dataVisitorData (read-only)
decayEnabledboolean (read-only)
delete(fromAllDevices)
Deletes visitor data (forgetting them). In most cases you should use forget() on Context, which also clears the Context state.
Parameters:
  • fromAllDevicesboolean- If false, logout from this device ID. If true, forget all data about the visitor and their identity.
Returns: Promise<void>
eventsobject (read-only)
Object used to add and remove listeners for the events emitted by the VisitorDataStore.
+ show child attributes
optionsVisitorDataStoreOptions (read-only)
updateData(commands)
Push data update command(s) into the visitor data.
Parameters:
  • commandsStorageCommands[]- If false, logout from this device ID. If true, forget all data about the visitor and their identity.
Returns: Promise<void>

Functions

createLinearDecay

Creates a linear decay function that can be assigned to the Context. Linear decay involves reducing a score by the same amount each day the decay runs.

The following describes how decay works over time and with continuing engagement. Consider the following settings:

  • Scores will decay by 10% each day (decay rate).
  • The most a score will decay in a day is 95% (decay cap).
  • Decay will start after 1 day (grace period).
DayNew activityDecayTotal scoreNotes
11000100No decay due to grace period.
201090Decay is 10% of the previous day's score (100).
30981Decay is 10% of the previous day's score (90).
4208.192.9Decay is 10% of the previous day's score (81). Decay does not apply to the new activity score.
509.2983.61Decay is 10% of the previous day's score (92.9).
- Arguments
optionsLinearDecayOptions (optional)
Options that control how linear decay works.
+ show child attributes
- Return
DecayFunctionThe decay function.
Example
import { 
Context,
createLinearDecay,
} from '@uniformdev/context';

const manifest = { project: {} };
const options = { decayRate: 0.1 };

const context = new Context({
manifest,
consent: true,
decay: createLinearDecay(options),
});
info

For more information, see the linear decay activation guide.

enableConsoleLogDrain

Creates a plugin that writes log messages to the console.
- Arguments
The logger will only write messages at or greater than this level of severity.
optionsConsoleDebugLogDrainOptions (optional)
Additional settings that control the logger.
+ show child attributes
- Return
ContextPluginThe plugin.
Example
import { 
Context,
enableDebugConsoleLogDrain,
} from '@uniformdev/context';

const manifest = { project: {} };
const level = "debug";
const options = { enableOnServer: false };

const context = new Context({
manifest,
consent: true,
plugins: [
createConsoleLogDrain(level, options),
],
});
info

For more information, see the console log plugin guide.

enableContextDevTools

Creates a plugin that causes the Context to expose visitor classification data that the Context DevTools can display.
- Arguments
None
- Return
ContextPluginThe plugin.
Example
import { Context, enableContextDevTools } from '@uniformdev/context';

const manifest = { project: {} };

const context = new Context({
manifest,
consent: true,
plugins: [
enableContextDevTools(),
],
});
info

For more information, see the Context DevTools plugin guide.

getEnrichmentVectorKey

Generates the name of an enrichment key based on the enrichment category and enrichment value. This key is needed if you are writing enrichment values programmatically.
- Arguments
categorystring
The enrichment category id.
valuestring
The enrichment value id.
- Return
stringThe name of the enrichment key.

Types

ContextOptions

Represents options that can be specified when creating the Context.
- Members
decayDecayFunction (optional)
Allows decaying of scores over time based on time between visits. If not specified, scores do not decay over time.
defaultConsentboolean (optional)
By default, the Context stores visitor activity in-memory, only. This activity data is lost when the browser leaves the page. When set to true, visitor activity is stored in the visitor's browser.
For more information, see our compliance and consent guide.
manifestManifestV2
Settings the Context uses to perform processes such as classification and testing.
onLogMessagefunction (optional)
Called when a log message is emitted from the data store.
Parameters:
Returns: void
onServerTransitionReceivedfunction (optional)

Called when server-to-client transfer state is loaded and contains server-side computed scores. These scores are used as a temporary shim for the current scores on the client side until score computation is completed the first time (which occurs when the current url is fed into the tracker).

Because the feed of the URL may be marginally delayed (for example in React it is in an effect so it is a second render), one render might be done with no scores unless we dropped the server scores in temporarily, resulting in a flash of unpersonalized content.

Parameters:
  • stateServerToClientTransitionState
Returns: void
transitionDataStoreTransitionDataStore (optional)
Used to transfer server or edge-side execution (e.g. personalization) state to the client. This member is not applicable when client-side execution is used.
visitLifespannumber (optional)
Duration of a visit. The Context determines a new visit has started when this number of milliseconds has elapsed without performing any updates.

ContextPlugin

Represents a plugin for the Context.
- Members
logDrainLogDrain (optional)
The component responsible for handling logging events emitted by the Context.
initfunction (optional)
Initializes the plugin, usually by assigning event handlers to the Context.
Parameters:
  • contextContext- The tracker to which the plugin is being initialized for.
Returns: Promise<void>
info

For information on how to create your own plugin, see the custom plugins guide.

DecayFunction

The function that implements the score decay process.
- Parameters
optionsDecayOptions
Options that are passed to the decay function when the decay process is started.
+ show child attributes
- Return
booleanIf any decay was applied, true is returned. If no decay was applied, false is returned.
info

For information on how to create your own decay function, see the custom decay functions guide.

LogDrain

Represents a component that can handle logging messages (i.e. a logger).
- Arguments
The message or messages to write to the log.

LogMessageSingle

info

Coming soon.

LogMessageGroup

info

Coming soon.

ManifestV2

Represents the settings the Context uses to perform processes such as classification and testing.
- Members
projectobject
Project described by the manifest.
+ show child attributes
Example
{
  "project": {
    "pz": {
      "enr": {
        "1": {
          "cap": 100
        }
      }
    },
    "test": {
      "firstTest": {}
    }
  }
}

OutputSeverity

When a logger is created, an output severity level is assigned. The logger only outputs messages written at least as severe as this the severity level on the logger.
- Options
none
No messages will be logged. This effectively disables logging.
debug
All messages will be logged.
info
Messages with the severity of info, warn or error will be logged.
warn
Messages with the severity of warn or error will be logged.
error
Messages with the severity of error will be logged.

Quirks

Quirks are used to store arbirary data that is associated with a visitor. The quirks object is a set of key-value pairs where the key and value are both strings.

Example
{
"location": "San Francisco",
"status": "Member",
"value": "10000"
}
info

For more information about quirks, see the classification capability.

ScoreVector

This type is used to store the scores calculated during the classification process. The object is a set of key-value pairs where the key is a string (i.e. the name of the visitor dimension) and value is a number.

Example
{
"developer": 10,
"investment": 5,
"challenger": 3
}
info

For more information about visitor dimensions, see the classification capability.

Severity

Each message that is sent to the logger has a severity level. Whether the logger writes the message to the log depends on the output severity assigned to the logger.

- Options
none
No messages will be logged. This effectively disables logging.
debug
All messages will be logged.
info
Messages with the severity of info, warn or error will be logged.
warn
Messages with the severity of warn or error will be logged.
error
Messages with the severity of error will be logged.

StorageCommands

Commands that can be issued to alter the storage of Uniform Context data.
- Members
typestring
The command type.
modscore - Changes the visitor's permanent score for a given dimension.
modscoreS - Changes the visitor's session (time-based) score for a given dimension.
consent - Changes the visitor's storage consent setting. Setting consent to false will trigger deletion of any stored data for the visitor. Scores are still collected in-memory when consent is false; just not persisted.
setquirk - Sets a permanent quirk key and value for the visitor.
settest - Sets a specific variant as being this visitor's variant on an A/B test. This only has an effect when using an external cross-device transition storage system. You cannot read the identified visitor ID back from the storage system once it is set.
identify - Identifies the visitor as being a specific unique identifier.
setcontrol - Sets whether the current visitor is in the personalization control group (i.e. will not be exposed to personalization or gather classification data; WILL see A/B tests). In most cases this should not be sent as the membership is computed automatically for visitors. This command is intended mostly for diagnostics and testing purposes.
data
Data used in the storage command. The data type depends on the property type.
Property valueData type
modscore
object
Changes the visitor's permanent score for a given dimension.
+ show child attributes
modscoreS
object
Changes the visitor's session (time-based) score for a given dimension.
+ show child attributes
consent
boolean
Changes the visitor's storage consent setting. Setting consent to false will trigger deletion of any stored data for the visitor. Scores are still collected in-memory when consent is false; just not persisted.
setquirk
object
Sets a permanent quirk key and value for the visitor.
+ show child attributes
settest
object
Sets a specific variant as being this visitor's variant on an A/B test.
+ show child attributes
identify
string
Identifies the visitor as being a specific unique identifier. This only has an effect when using an external cross-device transition storage system. You cannot read the identified visitor ID back from the storage system once it is set.
setcontrol
boolean
Sets whether the current visitor is in the personalization control group (will not be exposed to personalization or gather classification data; WILL see A/B tests). In most cases this should not be sent as the membership is computed automatically for visitors. This command is intended mostly for diagnostics and testing purposes.

Tests

This type represents the A/B test variants that were displayed to the visitor. The object is a set of key-value pairs where the key (i.e. the name of the test) and value (i.e. the name of the variant) are both strings.

Example
{
"promo": "full-color",
}
info

For more information about testing, see the A/B testing capability.

VisitorData

Visitor behavior data collected by the Uniform tracker.
- Members
consentboolean (optional)
Whether consent has been given to store the visitor data. If false or not set, visitor data is stored in memory and is lost if the browser refreshes. If true, visitor data is stored in local storage and any other transition storage (if registered).
controlGroupboolean (optional)
Whether the visitor has been assigned to the personalization control group - visitors who are not shown personalization. If this is true, all scores will be zeroed, and score updates will be ignored. This has no effect on quirks or tests.
quirksQuirks (optional)
Quirks set on visitor.
scoresScoreVector (optional)
Personalization score data for all time (merge with session for totals).
sessionScoresScoreVector (optional)
Personalization score data for the current session (merge with all time for totals).
testsTests (optional)
A/B test variant selections.