@uniformdev/context 18.11.1-alpha.4 → 18.11.1-alpha.5

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