@uniformdev/context 16.0.1-alpha.128 → 16.0.1-alpha.143

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,772 +0,0 @@
1
- import { c as components, e as external } from './v2-manifest.swagger-ff2af13e.js';
2
- import * as mitt from 'mitt';
3
-
4
- declare type StorageCommand<TID extends string = string, TData = unknown> = {
5
- type: TID;
6
- data: TData;
7
- };
8
- /** Commands that can be issued to alter the storage of Uniform Context data */
9
- declare type StorageCommands = ModifyScoreCommand | ModifySessionScoreCommand | SetConsentCommand | SetQuirkCommand | SetTestCommand | IdentifyCommand | SetControlGroupCommand;
10
- /**
11
- * Changes the visitor's permanent score for a given dimension
12
- */
13
- declare type ModifyScoreCommand = StorageCommand<'modscore', {
14
- dimension: string;
15
- delta: number;
16
- }>;
17
- /**
18
- * Changes the visitor's session (time-based) score for a given dimension
19
- */
20
- declare type ModifySessionScoreCommand = StorageCommand<'modscoreS', {
21
- dimension: string;
22
- delta: number;
23
- }>;
24
- /**
25
- * Changes the visitor's storage consent setting.
26
- * Setting consent to false will trigger deletion of any stored data for the visitor.
27
- * Scores are still collected in-memory when consent is false; just not persisted.
28
- */
29
- declare type SetConsentCommand = StorageCommand<'consent', boolean>;
30
- /** Sets a permanent quirk key and value for the visitor */
31
- declare type SetQuirkCommand = StorageCommand<'setquirk', {
32
- key: string;
33
- value: string;
34
- }>;
35
- /** Sets a specific variant as being this visitor's variant on an A/B test */
36
- declare type SetTestCommand = StorageCommand<'settest', {
37
- test: string;
38
- variant: string;
39
- }>;
40
- /**
41
- * Identifies the visitor as being a specific unique identifier.
42
- * NOTE: this only has an effect when using an external cross-device transition storage system.
43
- * NOTE: you cannot read the identified visitor ID back from the storage system once it is set.
44
- */
45
- declare type IdentifyCommand = StorageCommand<'identify', {
46
- identity: string;
47
- }>;
48
- /**
49
- * Sets whether the current visitor is in the personalization control group
50
- * (Will not be exposed to personalization or gather classification data; WILL see A/B tests)
51
- * In most cases this should not be sent as the membership is computed automatically for visitors;
52
- * this command is intended mostly for diagnostics and testing purposes.
53
- */
54
- declare type SetControlGroupCommand = StorageCommand<'setcontrol', boolean>;
55
-
56
- declare type Quirks = {
57
- [key: string]: string;
58
- };
59
- declare type Tests = {
60
- [key: string]: string;
61
- };
62
- declare type ScoreVector = {
63
- [key: string]: number;
64
- };
65
- declare type EnrichmentData = {
66
- /** Enrichment category name */
67
- cat: string;
68
- /** Enrichment key value */
69
- key: string;
70
- /** Strength value (amount of score added when viewing content) */
71
- str: number;
72
- };
73
- declare type EventData = {
74
- event: string;
75
- payload?: any;
76
- };
77
- declare type VisitorData = {
78
- /** Quirk key-value data */
79
- quirks: Quirks;
80
- /** A/B test variant selections */
81
- tests: Tests;
82
- /** Personalization score data for the current session (merge with all time for totals) */
83
- sessionScores: ScoreVector;
84
- /** Personalization score data for all time (merge with session for totals) */
85
- scores: ScoreVector;
86
- /**
87
- * Whether consent has been given to store the visitor data
88
- * If false or not set: visitor data is stored in memory and is lost if the browser refreshes
89
- * If true: visitor data is stored in localStorage and any other transition storage if registered
90
- */
91
- consent?: boolean;
92
- /**
93
- * Whether the visitor has been assigned to the personalization control group -
94
- * visitors who are not shown personalization. If this is true, all scores will be zeroed,
95
- * and score updates will be ignored. This has no effect on quirks or tests.
96
- *
97
- * If this value is not set, a random roll will be performed to determine membership,
98
- * based on the control group size.
99
- */
100
- controlGroup?: boolean;
101
- };
102
- declare const emptyVisitorData: () => VisitorData;
103
- /**
104
- * Expresses a 'patch' to the Uniform Context state
105
- */
106
- declare type ContextState = {
107
- cookies: Record<string, string>;
108
- url?: URL;
109
- quirks: Quirks;
110
- enrichments: EnrichmentData[];
111
- events: EventData[];
112
- };
113
- declare type ContextStateUpdate = {
114
- state: Partial<ContextState>;
115
- previousState: Partial<ContextState>;
116
- visitor: VisitorData;
117
- scores: ScoreVector;
118
- };
119
-
120
- declare type TransitionDataStoreOptions = {
121
- initialData?: Partial<VisitorData>;
122
- };
123
- declare type ServerToClientTransitionState = Pick<Partial<VisitorData>, 'quirks' | 'tests'> & {
124
- /**
125
- * Server Score Vector - the resultant scores _on the server side_ after the server/edge render completes
126
- * Note that the client side does not trust these scores; they are only used until it's done with initial
127
- * recomputation.
128
- */
129
- ssv?: ScoreVector;
130
- };
131
- declare const SERVER_STATE_ID = "__UNIFORM_DATA__";
132
- declare type TransitionDataStoreEvents = {
133
- /**
134
- * Fired when the data is updated asynchronously
135
- * (i.e. a promise resolves with new data from a backend)
136
- *
137
- * NOT fired for synchronous updates (e.g. calling updateData()), unless this also results in an async update of the data afterwards.
138
- * NOT fired if an asynchronous update does not result in any change compared to the last known data.
139
- */
140
- dataUpdatedAsync: Partial<VisitorData>;
141
- };
142
- declare abstract class TransitionDataStore {
143
- #private;
144
- constructor({ initialData }: TransitionDataStoreOptions);
145
- get data(): Partial<VisitorData> | undefined;
146
- /**
147
- * Subscribe to events from the transition storage
148
- */
149
- readonly events: {
150
- on: {
151
- <Key extends "dataUpdatedAsync">(type: Key, handler: mitt.Handler<TransitionDataStoreEvents[Key]>): void;
152
- (type: "*", handler: mitt.WildcardHandler<TransitionDataStoreEvents>): void;
153
- };
154
- off: {
155
- <Key_1 extends "dataUpdatedAsync">(type: Key_1, handler?: mitt.Handler<TransitionDataStoreEvents[Key_1]> | undefined): void;
156
- (type: "*", handler: mitt.WildcardHandler<TransitionDataStoreEvents>): void;
157
- };
158
- };
159
- /**
160
- * Updates data in the transition storage.
161
- * @param commands Commands to execute against existing stored value (event based stores)
162
- * @param computedValue Pre-computed new value against existing value (object based stores)
163
- * @returns Resolved promise when the data has been updated
164
- */
165
- updateData(commands: StorageCommands[], computedValue: VisitorData): Promise<void>;
166
- /**
167
- * Deletes a visitor's stored data, forgetting them.
168
- * @param fromAllDevices - false: logout from this device ID. true: forget all data about the visitor and their identity.
169
- */
170
- delete(fromAllDevices?: boolean): Promise<void>;
171
- /**
172
- * Deletes a visitor's stored data, forgetting them.
173
- * Important: do not emit any async score update events from this function.
174
- * @param fromAllDevices - false: logout from this device ID. true: forget all data about the visitor and their identity.
175
- */
176
- abstract handleDelete(fromAllDevices?: boolean): Promise<void>;
177
- /**
178
- * Updates visitor data in the transition store.
179
- *
180
- * NOTE: The updated data is optimistically stored in TransitionDataStore automatically,
181
- * so unless the updated data is _changed_ by the backend data store, there is no need
182
- * to emit async score changed events when the visitor data is done updating.
183
- */
184
- abstract handleUpdateData(commands: StorageCommands[], computedValue: VisitorData): Promise<void>;
185
- protected signalAsyncDataUpdate(newScores: Partial<VisitorData>): void;
186
- /**
187
- * When we load on the client side after a server side rendering has occurred (server to client transition),
188
- * we can have a page script (ID: __UNIFORM_DATA__) that contains the computed visitor data from the SSR/edge render.
189
- * This data is injected into the first render to allow score syncing and the server to request commands be applied
190
- * to the client side data store.
191
- */
192
- getClientTransitionState(): ServerToClientTransitionState | undefined;
193
- }
194
-
195
- declare type SharedTypes = external['uniform-context-types.swagger.yml']['components']['schemas'];
196
- declare type ManifestV2 = components['schemas']['ManifestV2'];
197
- declare type PersonalizationManifest = components['schemas']['PersonalizationManifest'];
198
- declare type Signal = SharedTypes['Signal'];
199
- declare type SignalCriteriaGroup = SharedTypes['SignalCriteriaGroup'];
200
- declare type SignalCriteria = SharedTypes['SignalCriteria'];
201
- declare type EnrichmentCategory = SharedTypes['EnrichmentCategory'];
202
- declare type StringMatch = SharedTypes['StringMatch'];
203
- declare type NumberMatch = SharedTypes['NumberMatch'];
204
- declare type TestDefinition = SharedTypes['Test'];
205
- declare type AggregateDimension = SharedTypes['AggregateDimension'];
206
- declare type AggregateDimensionInput = SharedTypes['AggregateDimensionInput'];
207
-
208
- /**
209
- * The result of evaluating a signal criteria.
210
- */
211
- declare type CriteriaEvaluatorResult = {
212
- /** Whether the criteria evaluated to true or not */
213
- result: boolean;
214
- /**
215
- * Whether the value of the criteria changed from the previous state
216
- * If ALL criteria on a signal have NOT changed, the signal is skipped
217
- * and its score is left alone.
218
- */
219
- changed: boolean;
220
- };
221
- declare type CriteriaEvaluatorParameters = {
222
- /** The update being made to the Context state */
223
- update: ContextStateUpdate;
224
- /** Current criteria to evaluate the update against */
225
- criteria: SignalCriteria;
226
- /**
227
- * The storage commands that will be executed by this update.
228
- * If the evaluation requires custom commands, push them into this parameter.
229
- * NOTE: needing to use this is very rare and should be avoided if possible.
230
- */
231
- commands: StorageCommands[];
232
- /** The parent signal containing the criteria we are evaluating */
233
- signal: SignalData;
234
- /** Function to emit log notices to the Context log */
235
- onLogMessage?: (message: LogMessage) => void;
236
- };
237
- declare type SignalData = Signal & {
238
- id: string;
239
- };
240
- /**
241
- * A type that evaluates a signal criteria type and
242
- * decides if it matches the current Context state or not.
243
- */
244
- declare type CriteriaEvaluator = ((parameters: CriteriaEvaluatorParameters) => CriteriaEvaluatorResult) & {
245
- /** If true the criteria will always execute even if a short-circuit would normally skip it */
246
- alwaysExecute?: boolean;
247
- };
248
-
249
- declare class GroupCriteriaEvaluator {
250
- #private;
251
- constructor(criteriaEvaluators: Record<string, CriteriaEvaluator>);
252
- evaluate(update: ContextStateUpdate, crit: SignalCriteriaGroup, commands: StorageCommands[], signal: SignalData, onLogMessage?: (message: LogMessage) => void): CriteriaEvaluatorResult;
253
- }
254
-
255
- /** Defines all error codes and their parameter(s) */
256
- declare type LogMessages = {
257
- /** Context constructed */
258
- 1: MessageFunc;
259
- /** Context received data update */
260
- 2: MessageFunc<Partial<Omit<ContextState, 'url'> & {
261
- url: string;
262
- }>>;
263
- /** Context emitted new score vector */
264
- 3: MessageFunc<ScoreVector>;
265
- /** Context emitted updated quirks */
266
- 4: MessageFunc<Quirks>;
267
- /** Tried to set enrichment category that did not exist */
268
- 5: MessageFunc<EnrichmentData>;
269
- /** Storage received update commands */
270
- 101: MessageFunc<StorageCommands[]>;
271
- /** Storage data was updated */
272
- 102: MessageFunc<VisitorData>;
273
- /** Storage data was deleted bool: fromAllDevices */
274
- 103: MessageFunc<boolean>;
275
- /** Visitor was assigned or removed from control group */
276
- 104: MessageFunc<boolean>;
277
- /** Storage score was truncated to its cap */
278
- 110: MessageFunc<{
279
- dim: string;
280
- score: number;
281
- cap: number;
282
- }>;
283
- /** Storage visitor data expired and was cleared */
284
- 120: MessageFunc;
285
- /** Server to client transition score data was loaded */
286
- 130: MessageFunc<ScoreVector>;
287
- /** Server to client transition data was discarded */
288
- 131: MessageFunc;
289
- /** Decay function executed */
290
- 140: MessageFunc<string>;
291
- /** Signals evaluation beginning */
292
- 200: MessageFunc;
293
- /** Evaluation of a specific signal beginning */
294
- 201: MessageFunc<SignalData>;
295
- /** Evaluation of a group beginning */
296
- 202: MessageFunc<SignalCriteriaGroup>;
297
- 203: MessageFunc<{
298
- criteria: SignalCriteria;
299
- result: CriteriaEvaluatorResult;
300
- explanation: string;
301
- }>;
302
- /** Result of evaluating a criteria group */
303
- 204: MessageFunc<CriteriaEvaluatorResult>;
304
- /** Personalization placement executing */
305
- 300: MessageFunc<{
306
- name: string;
307
- take?: number;
308
- }>;
309
- /** Personalization placement testing variation */
310
- 301: MessageFunc<{
311
- id: string;
312
- op?: string;
313
- }>;
314
- /** Processed a personalization criteria */
315
- 302: MessageFunc<{
316
- matched: boolean;
317
- description: string;
318
- }>;
319
- /** Final result for a personalized variation */
320
- 303: MessageFunc<boolean>;
321
- /** A/B test placement executing */
322
- 400: MessageFunc<string>;
323
- /** A/B Test definition did not exist */
324
- 401: MessageFunc<string>;
325
- /** Previously shown test variant no longer in variant data */
326
- 402: MessageFunc<{
327
- missingVariant: string;
328
- variants: string[];
329
- }>;
330
- /** Selected a new A/B test variation */
331
- 403: MessageFunc<string>;
332
- /** Displaying A/B test variation */
333
- 404: MessageFunc<string>;
334
- /** gtag was not present on the page to emit events to */
335
- 700: MessageFunc;
336
- /** Enabled gtag event signal redirection */
337
- 701: MessageFunc;
338
- };
339
-
340
- declare type Severity = 'debug' | 'info' | 'warn' | 'error';
341
- declare type MessageCategory = 'context' | 'storage' | 'testing' | 'personalization' | 'gtag' | 'signals';
342
- declare type OutputSeverity = Severity | 'none';
343
- declare type MessageFunc<TArg = void> = (arg: TArg) => [
344
- /** Category of the message */
345
- MessageCategory,
346
- /** Log message text */
347
- string,
348
- /** Log message */
349
- ...unknown[]
350
- ];
351
- declare type LogMessage = LogMessageSingle | LogMessageGroup;
352
- declare type LogMessageSingle<TID extends keyof LogMessages = keyof LogMessages> = [
353
- severity: Severity,
354
- id: TID,
355
- ...args: Parameters<LogMessages[TID]>
356
- ];
357
- declare type LogMessageGroup<TID extends keyof LogMessages = keyof LogMessages> = [severity: Severity, id: TID, group: 'GROUP', ...args: Parameters<LogMessages[TID]>] | [severity: Severity, id: TID, group: 'ENDGROUP'];
358
- declare type LogDrain = (message: LogMessage) => void;
359
-
360
- declare type DecayOptions = {
361
- now: number;
362
- lastUpd: number | undefined;
363
- scores: ScoreVector;
364
- sessionScores: ScoreVector;
365
- onLogMessage?: (message: LogMessage) => void;
366
- };
367
- /**
368
- * Computes decay of visitor scores over time.
369
- * NOTE: it is expected that this function mutates the incoming score vectors,
370
- * if it needs to apply score decay. The data store ensures immutability already.
371
- *
372
- * @returns true if any decay was applied, false otherwise
373
- */
374
- declare type DecayFunction = (options: DecayOptions) => boolean;
375
-
376
- declare type VisitorDataStoreOptions = {
377
- /** Transition storage used to transfer server or edge side execution state to the client. Unused for client side only. */
378
- transitionStore?: TransitionDataStore;
379
- /** Duration of a 'visit' measured by this number of milliseconds without performing any updates */
380
- visitLifespan?: number;
381
- /** Personalization manifest data. If set, the data store will automatically apply score caps in the manifest data. */
382
- manifest?: ManifestInstance;
383
- /** Allows decaying of scores over time based on time between visits. Default: no decay */
384
- decay?: DecayFunction;
385
- /**
386
- * Sets the default value of storage consent for new unknown visitors.
387
- * If storage consent is not given, only in-memory data will be stored which is lost when the browser leaves the page.
388
- * @default false - consent is not given for new visitors until they explicitly give it with an update command
389
- */
390
- defaultConsent?: boolean;
391
- /**
392
- * Function called when server-to-client transfer state is loaded and contains server-side computed scores.
393
- * These scores are used as a temporary shim for the current scores on the client side, until score computation
394
- * is completed the first time (which occurs when the current url is fed into the Context).
395
- *
396
- * Because the feed of the URL may be marginally delayed (for example in React it's in an effect so it's a second render),
397
- * one render might be done with _no_ scores unless we dropped the server scores in temporarily, resulting in a flash of unpersonalized content.
398
- */
399
- onServerTransitionReceived?: (state: ServerToClientTransitionState) => void;
400
- /** Called when a log message is emitted from the data store */
401
- onLogMessage?: (message: LogMessage) => void;
402
- };
403
- declare type VisitorDataStoreEvents = {
404
- /**
405
- * Fired when the stored data is updated.
406
- * This is fired for any update, whether from integrated or transition storage.
407
- * The event is NOT fired if an update does not result in any score changes.
408
- */
409
- scoresUpdated: Pick<VisitorData, 'scores' | 'sessionScores'>;
410
- /**
411
- * Fired when stored quirks are updated.
412
- * This is fired for any update, whether from integrated or transition storage.
413
- * The event is NOT fired if an update does not result in any quirk changes.
414
- */
415
- quirksUpdated: Pick<VisitorData, 'quirks'>;
416
- /**
417
- * Fired when test variant selection is updated.
418
- */
419
- testsUpdated: Pick<VisitorData, 'tests'>;
420
- /**
421
- * Fired when storage consent is changed
422
- */
423
- consentUpdated: Pick<VisitorData, 'consent'>;
424
- /**
425
- * Fired when visitor control group membership is changed
426
- */
427
- controlGroupUpdated: Pick<VisitorData, 'controlGroup'>;
428
- };
429
- declare class VisitorDataStore {
430
- #private;
431
- constructor(options: VisitorDataStoreOptions);
432
- /** Gets the current visitor data. This property is always up to date. */
433
- get data(): VisitorData;
434
- get decayEnabled(): boolean;
435
- /**
436
- * Subscribe to events from storage
437
- */
438
- readonly events: {
439
- on: {
440
- <Key extends keyof VisitorDataStoreEvents>(type: Key, handler: mitt.Handler<VisitorDataStoreEvents[Key]>): void;
441
- (type: "*", handler: mitt.WildcardHandler<VisitorDataStoreEvents>): void;
442
- };
443
- off: {
444
- <Key_1 extends keyof VisitorDataStoreEvents>(type: Key_1, handler?: mitt.Handler<VisitorDataStoreEvents[Key_1]> | undefined): void;
445
- (type: "*", handler: mitt.WildcardHandler<VisitorDataStoreEvents>): void;
446
- };
447
- };
448
- /** Push data update command(s) into the visitor data */
449
- updateData(commands: StorageCommands[]): Promise<void>;
450
- /**
451
- * Deletes visitor data (forgetting them)
452
- * In most cases you should use forget() on the Context instead of this function, which also clears the Context state.
453
- * @param fromAllDevices for an identified user, whether to delete all their data (for the entire account) - true, or data for this device (sign out) - false
454
- */
455
- delete(fromAllDevices: boolean): Promise<void>;
456
- }
457
-
458
- declare class ManifestInstance {
459
- #private;
460
- readonly data: ManifestV2;
461
- constructor({ manifest, evaluator, onLogMessage, }: {
462
- manifest: ManifestV2;
463
- evaluator?: GroupCriteriaEvaluator;
464
- onLogMessage?: (message: LogMessage) => void;
465
- });
466
- rollForControlGroup(): boolean;
467
- getTest(name: string): TestDefinition | undefined;
468
- computeSignals(update: ContextStateUpdate): StorageCommands[];
469
- /**
470
- * Computes aggregated scores based on other dimensions
471
- */
472
- computeAggregateDimensions(primitiveScores: ScoreVector): ScoreVector;
473
- getDimensionByKey(scoreKey: string): EnrichmentCategory | Signal | undefined;
474
- }
475
-
476
- /** Content that is tagged for adding enrichment score when triggered by behavior (i.e. being shown that content) */
477
- declare type BehaviorTag = {
478
- beh?: EnrichmentData[];
479
- };
480
- /** Defines the shape of a personalized content variant */
481
- declare type PersonalizedVariant = {
482
- /** A unique identifier for this variation */
483
- id: string;
484
- /** Match criteria for this variation */
485
- pz?: VariantMatchCriteria;
486
- };
487
- /** The result of computing personalized content from variations */
488
- declare type PersonalizedResult<TVariant> = {
489
- /** Whether or not this result contains a personalized result */
490
- personalized: boolean;
491
- /** Matching variations */
492
- variations: Array<TVariant>;
493
- };
494
- /** Defines the shape of a A/B test variant */
495
- declare type TestVariant = {
496
- /** The identifier for this variant. This value persisted to storage when a variant is selected. */
497
- id: string;
498
- /**
499
- * A number between 0 and 100 representing what percentage of visitors will be selected for this variant.
500
- * If not provided, this variant will be selected in equal proportion to other variants without an explicit distribution.
501
- */
502
- testDistribution?: number;
503
- };
504
- /** The result of computing an A/B test result */
505
- declare type TestResult<TVariant> = {
506
- /** The selected variation */
507
- result: TVariant | undefined;
508
- /**
509
- * Whether the test variant was newly assigned to the visitor.
510
- * True: variant was assigned to the visitor for the first time.
511
- * False: variant was already assigned to the visitor and is being reused.
512
- */
513
- variantAssigned: boolean;
514
- };
515
-
516
- declare type PersonalizeOptions<TVariant> = {
517
- /** Name of placement (sent to analytics) */
518
- name: string;
519
- /** Possible variants to place */
520
- variations: Iterable<TVariant>;
521
- /** Maximum number of variants to place (default: 1) */
522
- take?: number;
523
- onLogMessage?: (message: LogMessage) => void;
524
- };
525
- declare function personalizeVariations<TVariant extends PersonalizedVariant>({ name, context, variations, take, onLogMessage, }: PersonalizeOptions<TVariant> & {
526
- context: Context;
527
- }): PersonalizedResult<TVariant>;
528
-
529
- declare type VariantMatchCriteria = {
530
- /**
531
- * Operation for match criteria
532
- *
533
- * @defaultValue `&`
534
- */
535
- op?: '&' | '|';
536
- crit: DimensionMatch[];
537
- };
538
- declare type DimensionMatch = {
539
- /**
540
- * Left hand side of the match expression (name of dimension in score vector)
541
- * NOTE: if the dimension is not present in the score vector, it will be treated as if it has a value of 0
542
- */
543
- l: string;
544
- /**
545
- * Operator of the match expression
546
- * Whole-vector (RHS only) operators - these do not require a `r` or `rDim` set:
547
- * +: `l` is the strongest dimension in the score vector
548
- * -: `l` is the weakest dimension in the score vector. This does not match if the dimension has no score at all.
549
- *
550
- * Comparison operators:
551
- * >: `l` is greater than the right hand side expression
552
- * >= : `l` is greater than or equal to the right hand side expression
553
- * <: `l` is less than the right hand side expression
554
- * <= : `l` is less than or equal to the right hand side expression
555
- * =: `l` is equal to the right hand side expression
556
- * !=: `l` is not equal to the right hand side expression
557
- */
558
- op: '+' | '-' | '>' | '>=' | '<' | '<=' | '=' | '!=';
559
- /**
560
- * Right hand side of the match expression (not required for op = + or - which have no right side)
561
- * This value is treated as a constant value, if it is present. If it's a string, it is parsed to an integer.
562
- * To reference another score dimension as the RHS, use the `rDim` property instead.
563
- * `r` and `rDim` are mutually exclusive; if both are specified, then `rDim` wins.
564
- */
565
- r?: number | string;
566
- /**
567
- * Right hand side of the match expression (not required for op = + or - which have no right side)
568
- * This value is treated as a reference to another score dimension, if it is present in the score vector.
569
- * If the referenced dimension is NOT present in the score vector, the match will always be false.
570
- * To reference a constant value instead as the RHS, use the `r` property instead.
571
- * `r` and `rDim` are mutually exclusive; if both are specified, then `rDim` wins.
572
- */
573
- rDim?: string;
574
- };
575
-
576
- declare type TestOptions<TVariant extends TestVariant> = {
577
- /** The name of the test that is being run, must be included in the manifest. */
578
- name: string;
579
- /** Variations that are being tested. */
580
- variations: TVariant[];
581
- };
582
- declare const testVariations: <TVariant extends TestVariant>({ name, context, variations, onLogMessage, }: TestOptions<TVariant> & {
583
- context: Context;
584
- onLogMessage?: ((message: LogMessage) => void) | undefined;
585
- }) => TestResult<TVariant>;
586
-
587
- /**
588
- * Defines a plugin for Uniform Context.
589
- * The plugin should attach event handlers in its creation function.
590
- * @returns A function that detaches any event handlers when called
591
- */
592
- declare type ContextPlugin = {
593
- logDrain?: LogDrain;
594
- init?: (context: Context) => () => void;
595
- };
596
- declare type ContextOptions = {
597
- /** The Context Manifest to load (from the Context API) */
598
- manifest: ManifestV2;
599
- /**
600
- * Context plugins to load at initialize time.
601
- * Plugins that hook to the log event should be added here so that they can catch init-time log message events.
602
- *
603
- * Note that the Context passed to the plugin is not yet fully initialized, and is intended for event handler attachment
604
- * only - don't call scores, update, etc on it. If you need to call these methods immediately, attach your plugin after initialisation.
605
- */
606
- plugins?: Array<ContextPlugin>;
607
- } & Omit<VisitorDataStoreOptions, 'manifest' | 'onServerTransitionScoresReceived'>;
608
- /** Emitted when a personalization runs */
609
- declare type PersonalizationEvent = {
610
- /** Name of the personalized placement */
611
- name: string;
612
- /** Selected variant ID(s) */
613
- variantIds: string[];
614
- /** Whether the user was part of the control group (and did not receive any personalization) */
615
- control: boolean | undefined;
616
- /**
617
- * Whether the personalized placement has changed since the last time the placement was evaluated.
618
- * True: the placement was evaluated for the first time, or the variant(s) selected changed from last time (e.g. due to a score change that activated a new variant).
619
- * False: the variant(s) selected were the same as a previous evaluation of this placement.
620
- */
621
- changed: boolean;
622
- };
623
- /** Emitted event when an A/B test runs */
624
- declare type TestEvent = {
625
- /** Name (public ID) of the A/B test */
626
- name: string;
627
- /** ID of the variant that was selected */
628
- variantId: string | undefined;
629
- /**
630
- * Whether the test variant was newly assigned to the visitor.
631
- * True: variant was assigned to the visitor for the first time.
632
- * False: variant was already assigned to the visitor and is being reused.
633
- */
634
- variantAssigned: boolean;
635
- };
636
- declare type ContextEvents = {
637
- /**
638
- * Fired when the scores are updated.
639
- * The event is NOT fired if an update does not result in any score changes.
640
- * The result is merged between session and permanent data.
641
- */
642
- scoresUpdated: Readonly<ScoreVector>;
643
- /**
644
- * Fired when quirk data changes. Not fired if no changes to quirks are made
645
- * (e.g. setting it to the same value it already has)
646
- */
647
- quirksUpdated: Quirks;
648
- /**
649
- * Fired when a log message is emitted from Context
650
- * Note that event handlers attached to this event will not catch events
651
- * logged during initialisation of the Context unless they are attached as plugins to the constructor.
652
- */
653
- log: LogMessage | LogMessageGroup;
654
- /** Test variant has been selected */
655
- testResult: TestEvent;
656
- /** Personalization variants have been selected */
657
- personalizationResult: PersonalizationEvent;
658
- };
659
- declare class Context implements Context {
660
- #private;
661
- readonly manifest: ManifestInstance;
662
- constructor(options: ContextOptions);
663
- get scores(): Readonly<ScoreVector>;
664
- /**
665
- * Subscribe to events
666
- */
667
- readonly events: {
668
- on: {
669
- <Key extends keyof ContextEvents>(type: Key, handler: mitt.Handler<ContextEvents[Key]>): void;
670
- (type: "*", handler: mitt.WildcardHandler<ContextEvents>): void;
671
- };
672
- off: {
673
- <Key_1 extends keyof ContextEvents>(type: Key_1, handler?: mitt.Handler<ContextEvents[Key_1]> | undefined): void;
674
- (type: "*", handler: mitt.WildcardHandler<ContextEvents>): void;
675
- };
676
- };
677
- readonly storage: VisitorDataStore;
678
- /**
679
- * Updates the Context with new data of any sort, such as
680
- * new URLs, cookies, quirks, and enrichments.
681
- *
682
- * Only properties that are set in the data parameter will be updated.
683
- * Properties that do not result in a changed state,
684
- * i.e. pushing the same URL or cookies as before,
685
- * will NOT result in a recomputation of signal state.
686
- */
687
- update(newData: Partial<ContextState>): Promise<void>;
688
- /** use test() instead */
689
- getTestVariantId(testName: string): string | null | undefined;
690
- /** use test() instead */
691
- setTestVariantId(testName: string, variantId: string): void;
692
- /**
693
- * Writes a message to the Context log sink.
694
- * Used by Uniform internal SDK; not intended for public use.
695
- */
696
- log(...message: LogMessage): void;
697
- /** 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) */
698
- test<TVariant extends TestVariant>(options: TestOptions<TVariant>): TestResult<TVariant>;
699
- /** Executes a personalized placement with a given set of variants */
700
- personalize<TVariant extends PersonalizedVariant>(options: PersonalizeOptions<TVariant>): PersonalizedResult<TVariant>;
701
- /**
702
- * Forgets the visitor's data and resets the Context to its initial state.
703
- * @param fromAllDevices for an identified user, whether to delete all their data (for the entire account) - true, or data for this device (sign out) - false
704
- */
705
- forget(fromAllDevices: boolean): Promise<void>;
706
- }
707
-
708
- /**
709
- * The version of the DevTools UI to load when in Chromium extension context.
710
- * 1: Uniform Optimize.
711
- * 2: Uniform Context.
712
- */
713
- declare type DevToolsUiVersion = 1 | 2;
714
- /**
715
- * The data state provided to the devtools for rendering.
716
- */
717
- declare type DevToolsState = {
718
- /** Current computed visitor scores (includes aggregates) */
719
- scores: Readonly<ScoreVector>;
720
- /** Current visitor data (includes quirks, raw scores, tests, consent, etc) */
721
- data: Readonly<VisitorData>;
722
- /** Personalization events that have fired since devtools started */
723
- personalizations: Array<PersonalizationEvent>;
724
- /** Test events that have fired since devtools started */
725
- tests: Array<TestEvent>;
726
- /** The Context manifest */
727
- manifest: ManifestV2;
728
- };
729
- /** Mutations the DevTools can take on the data it receives */
730
- declare type DevToolsActions = {
731
- /** Standard updates; maps to Context.update() */
732
- update: (newData: Partial<ContextState>) => Promise<void>;
733
- /** Raw updates to the storage subsystem. Maps to Context.storage.updateData() */
734
- rawUpdate: (commands: StorageCommands[]) => Promise<void>;
735
- /** Forget the current visitor and clear data on this device */
736
- forget: () => Promise<void>;
737
- };
738
- declare type DevToolsEvent<Type extends string = string, TEventData = unknown> = {
739
- /** The integration ID that is required */
740
- type: Type;
741
- } & TEventData;
742
- declare type DevToolsEvents = DevToolsLogEvent | DevToolsDataEvent | DevToolsHelloEvent | DevToolsUpdateEvent | DevToolsRawCommandsEvent | DevToolsForgetEvent;
743
- /** A log message emitted as an event to the browser extension */
744
- declare type DevToolsLogEvent = DevToolsEvent<'uniform:context:log', {
745
- message: LogMessage;
746
- }>;
747
- /** Emitted when data is updated in Context to the devtools */
748
- declare type DevToolsDataEvent = DevToolsEvent<'uniform:context:data', {
749
- data: DevToolsState;
750
- }>;
751
- /** A hello message emitted as an event from the browser extension to test if the page contains Context */
752
- declare type DevToolsHelloEvent = DevToolsEvent<'uniform:context:hello', {
753
- uiVersion: DevToolsUiVersion;
754
- }>;
755
- /** Devtools requests a normal update cycle (regular data update, re-eval signals, etc) */
756
- declare type DevToolsUpdateEvent = DevToolsEvent<'uniform-in:context:update', {
757
- newData: Partial<ContextState>;
758
- }>;
759
- /** Devtools requests a raw update cycle (explicitly set scores of dimensions in durations, etc) */
760
- declare type DevToolsRawCommandsEvent = DevToolsEvent<'uniform-in:context:commands', {
761
- commands: StorageCommands[];
762
- }>;
763
- /** A request to forget me from the DevTools */
764
- declare type DevToolsForgetEvent = DevToolsEvent<'uniform-in:context:forget', unknown>;
765
- declare global {
766
- interface Window {
767
- /** Window var set by enableContextDevTools() to enable embedded devtools to receive Context instance and attach events to it. */
768
- __UNIFORM_DEVTOOLS_CONTEXT_INSTANCE__?: Context;
769
- }
770
- }
771
-
772
- export { ContextEvents as $, AggregateDimension as A, SetTestCommand as B, ContextPlugin as C, DecayFunction as D, EnrichmentCategory as E, SetControlGroupCommand as F, GroupCriteriaEvaluator as G, DecayOptions as H, IdentifyCommand as I, VisitorDataStoreOptions as J, VisitorDataStoreEvents as K, LogDrain as L, ManifestInstance as M, NumberMatch as N, OutputSeverity as O, PersonalizationManifest as P, Quirks as Q, VisitorDataStore as R, StorageCommands as S, TransitionDataStore as T, ServerToClientTransitionState as U, VisitorData as V, SERVER_STATE_ID as W, TransitionDataStoreEvents as X, ContextOptions as Y, PersonalizationEvent as Z, TestEvent as _, TransitionDataStoreOptions as a, Context as a0, LogMessages as a1, Severity as a2, MessageCategory as a3, MessageFunc as a4, LogMessageSingle as a5, LogMessageGroup as a6, testVariations as a7, TestOptions as a8, PersonalizeOptions as a9, personalizeVariations as aa, DimensionMatch as ab, BehaviorTag as ac, PersonalizedVariant as ad, PersonalizedResult as ae, TestVariant as af, TestResult as ag, DevToolsUiVersion as ah, DevToolsState as ai, DevToolsActions as aj, DevToolsEvent as ak, DevToolsEvents as al, DevToolsLogEvent as am, DevToolsDataEvent as an, DevToolsHelloEvent as ao, DevToolsUpdateEvent as ap, DevToolsRawCommandsEvent as aq, DevToolsForgetEvent as ar, CriteriaEvaluator as b, StringMatch as c, ScoreVector as d, VariantMatchCriteria as e, LogMessage as f, ManifestV2 as g, Signal as h, SignalCriteriaGroup as i, SignalCriteria as j, TestDefinition as k, AggregateDimensionInput as l, CriteriaEvaluatorResult as m, CriteriaEvaluatorParameters as n, SignalData as o, Tests as p, EnrichmentData as q, EventData as r, emptyVisitorData as s, ContextState as t, ContextStateUpdate as u, StorageCommand as v, ModifyScoreCommand as w, ModifySessionScoreCommand as x, SetConsentCommand as y, SetQuirkCommand as z };